1 //===- IRSymtab.cpp - implementation of IR symbol tables ------------------===//
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 #include "llvm/Object/IRSymtab.h"
11 #include "llvm/ADT/ArrayRef.h"
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/ADT/SmallPtrSet.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/IR/Comdat.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/GlobalAlias.h"
22 #include "llvm/IR/GlobalObject.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Bitcode/BitcodeReader.h"
27 #include "llvm/MC/StringTableBuilder.h"
28 #include "llvm/Object/IRObjectFile.h"
29 #include "llvm/Object/ModuleSymbolTable.h"
30 #include "llvm/Object/SymbolicFile.h"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/Error.h"
34 #include "llvm/Support/StringSaver.h"
35 #include "llvm/Support/VCSRevision.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <cassert>
38 #include <string>
39 #include <utility>
40 #include <vector>
41
42 using namespace llvm;
43 using namespace irsymtab;
44
45 static const char *LibcallRoutineNames[] = {
46 #define HANDLE_LIBCALL(code, name) name,
47 #include "llvm/IR/RuntimeLibcalls.def"
48 #undef HANDLE_LIBCALL
49 };
50
51 namespace {
52
getExpectedProducerName()53 const char *getExpectedProducerName() {
54 static char DefaultName[] = LLVM_VERSION_STRING
55 #ifdef LLVM_REVISION
56 " " LLVM_REVISION
57 #endif
58 ;
59 // Allows for testing of the irsymtab writer and upgrade mechanism. This
60 // environment variable should not be set by users.
61 if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
62 return OverrideName;
63 return DefaultName;
64 }
65
66 const char *kExpectedProducerName = getExpectedProducerName();
67
68 /// Stores the temporary state that is required to build an IR symbol table.
69 struct Builder {
70 SmallVector<char, 0> &Symtab;
71 StringTableBuilder &StrtabBuilder;
72 StringSaver Saver;
73
74 // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
75 // The StringTableBuilder does not create a copy of any strings added to it,
76 // so this provides somewhere to store any strings that we create.
Builder__anonc0d02a5b0111::Builder77 Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
78 BumpPtrAllocator &Alloc)
79 : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
80
81 DenseMap<const Comdat *, int> ComdatMap;
82 Mangler Mang;
83 Triple TT;
84
85 std::vector<storage::Comdat> Comdats;
86 std::vector<storage::Module> Mods;
87 std::vector<storage::Symbol> Syms;
88 std::vector<storage::Uncommon> Uncommons;
89
90 std::string COFFLinkerOpts;
91 raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
92
setStr__anonc0d02a5b0111::Builder93 void setStr(storage::Str &S, StringRef Value) {
94 S.Offset = StrtabBuilder.add(Value);
95 S.Size = Value.size();
96 }
97
98 template <typename T>
writeRange__anonc0d02a5b0111::Builder99 void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
100 R.Offset = Symtab.size();
101 R.Size = Objs.size();
102 Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
103 reinterpret_cast<const char *>(Objs.data() + Objs.size()));
104 }
105
106 Expected<int> getComdatIndex(const Comdat *C, const Module *M);
107
108 Error addModule(Module *M);
109 Error addSymbol(const ModuleSymbolTable &Msymtab,
110 const SmallPtrSet<GlobalValue *, 8> &Used,
111 ModuleSymbolTable::Symbol Sym);
112
113 Error build(ArrayRef<Module *> Mods);
114 };
115
addModule(Module * M)116 Error Builder::addModule(Module *M) {
117 if (M->getDataLayoutStr().empty())
118 return make_error<StringError>("input module has no datalayout",
119 inconvertibleErrorCode());
120
121 SmallPtrSet<GlobalValue *, 8> Used;
122 collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
123
124 ModuleSymbolTable Msymtab;
125 Msymtab.addModule(M);
126
127 storage::Module Mod;
128 Mod.Begin = Syms.size();
129 Mod.End = Syms.size() + Msymtab.symbols().size();
130 Mod.UncBegin = Uncommons.size();
131 Mods.push_back(Mod);
132
133 if (TT.isOSBinFormatCOFF()) {
134 if (auto E = M->materializeMetadata())
135 return E;
136 if (NamedMDNode *LinkerOptions =
137 M->getNamedMetadata("llvm.linker.options")) {
138 for (MDNode *MDOptions : LinkerOptions->operands())
139 for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
140 COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
141 }
142 }
143
144 for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
145 if (Error Err = addSymbol(Msymtab, Used, Msym))
146 return Err;
147
148 return Error::success();
149 }
150
getComdatIndex(const Comdat * C,const Module * M)151 Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
152 auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
153 if (P.second) {
154 std::string Name;
155 if (TT.isOSBinFormatCOFF()) {
156 const GlobalValue *GV = M->getNamedValue(C->getName());
157 if (!GV)
158 return make_error<StringError>("Could not find leader",
159 inconvertibleErrorCode());
160 // Internal leaders do not affect symbol resolution, therefore they do not
161 // appear in the symbol table.
162 if (GV->hasLocalLinkage()) {
163 P.first->second = -1;
164 return -1;
165 }
166 llvm::raw_string_ostream OS(Name);
167 Mang.getNameWithPrefix(OS, GV, false);
168 } else {
169 Name = C->getName();
170 }
171
172 storage::Comdat Comdat;
173 setStr(Comdat.Name, Saver.save(Name));
174 Comdats.push_back(Comdat);
175 }
176
177 return P.first->second;
178 }
179
addSymbol(const ModuleSymbolTable & Msymtab,const SmallPtrSet<GlobalValue *,8> & Used,ModuleSymbolTable::Symbol Msym)180 Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
181 const SmallPtrSet<GlobalValue *, 8> &Used,
182 ModuleSymbolTable::Symbol Msym) {
183 Syms.emplace_back();
184 storage::Symbol &Sym = Syms.back();
185 Sym = {};
186
187 storage::Uncommon *Unc = nullptr;
188 auto Uncommon = [&]() -> storage::Uncommon & {
189 if (Unc)
190 return *Unc;
191 Sym.Flags |= 1 << storage::Symbol::FB_has_uncommon;
192 Uncommons.emplace_back();
193 Unc = &Uncommons.back();
194 *Unc = {};
195 setStr(Unc->COFFWeakExternFallbackName, "");
196 setStr(Unc->SectionName, "");
197 return *Unc;
198 };
199
200 SmallString<64> Name;
201 {
202 raw_svector_ostream OS(Name);
203 Msymtab.printSymbolName(OS, Msym);
204 }
205 setStr(Sym.Name, Saver.save(StringRef(Name)));
206
207 auto Flags = Msymtab.getSymbolFlags(Msym);
208 if (Flags & object::BasicSymbolRef::SF_Undefined)
209 Sym.Flags |= 1 << storage::Symbol::FB_undefined;
210 if (Flags & object::BasicSymbolRef::SF_Weak)
211 Sym.Flags |= 1 << storage::Symbol::FB_weak;
212 if (Flags & object::BasicSymbolRef::SF_Common)
213 Sym.Flags |= 1 << storage::Symbol::FB_common;
214 if (Flags & object::BasicSymbolRef::SF_Indirect)
215 Sym.Flags |= 1 << storage::Symbol::FB_indirect;
216 if (Flags & object::BasicSymbolRef::SF_Global)
217 Sym.Flags |= 1 << storage::Symbol::FB_global;
218 if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
219 Sym.Flags |= 1 << storage::Symbol::FB_format_specific;
220 if (Flags & object::BasicSymbolRef::SF_Executable)
221 Sym.Flags |= 1 << storage::Symbol::FB_executable;
222
223 Sym.ComdatIndex = -1;
224 auto *GV = Msym.dyn_cast<GlobalValue *>();
225 if (!GV) {
226 // Undefined module asm symbols act as GC roots and are implicitly used.
227 if (Flags & object::BasicSymbolRef::SF_Undefined)
228 Sym.Flags |= 1 << storage::Symbol::FB_used;
229 setStr(Sym.IRName, "");
230 return Error::success();
231 }
232
233 setStr(Sym.IRName, GV->getName());
234
235 bool IsBuiltinFunc = false;
236
237 for (const char *LibcallName : LibcallRoutineNames)
238 if (GV->getName() == LibcallName)
239 IsBuiltinFunc = true;
240
241 if (Used.count(GV) || IsBuiltinFunc)
242 Sym.Flags |= 1 << storage::Symbol::FB_used;
243 if (GV->isThreadLocal())
244 Sym.Flags |= 1 << storage::Symbol::FB_tls;
245 if (GV->hasGlobalUnnamedAddr())
246 Sym.Flags |= 1 << storage::Symbol::FB_unnamed_addr;
247 if (GV->canBeOmittedFromSymbolTable())
248 Sym.Flags |= 1 << storage::Symbol::FB_may_omit;
249 Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
250
251 if (Flags & object::BasicSymbolRef::SF_Common) {
252 Uncommon().CommonSize = GV->getParent()->getDataLayout().getTypeAllocSize(
253 GV->getType()->getElementType());
254 Uncommon().CommonAlign = GV->getAlignment();
255 }
256
257 const GlobalObject *Base = GV->getBaseObject();
258 if (!Base)
259 return make_error<StringError>("Unable to determine comdat of alias!",
260 inconvertibleErrorCode());
261 if (const Comdat *C = Base->getComdat()) {
262 Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
263 if (!ComdatIndexOrErr)
264 return ComdatIndexOrErr.takeError();
265 Sym.ComdatIndex = *ComdatIndexOrErr;
266 }
267
268 if (TT.isOSBinFormatCOFF()) {
269 emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
270
271 if ((Flags & object::BasicSymbolRef::SF_Weak) &&
272 (Flags & object::BasicSymbolRef::SF_Indirect)) {
273 auto *Fallback = dyn_cast<GlobalValue>(
274 cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
275 if (!Fallback)
276 return make_error<StringError>("Invalid weak external",
277 inconvertibleErrorCode());
278 std::string FallbackName;
279 raw_string_ostream OS(FallbackName);
280 Msymtab.printSymbolName(OS, Fallback);
281 OS.flush();
282 setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
283 }
284 }
285
286 if (!Base->getSection().empty())
287 setStr(Uncommon().SectionName, Saver.save(Base->getSection()));
288
289 return Error::success();
290 }
291
build(ArrayRef<Module * > IRMods)292 Error Builder::build(ArrayRef<Module *> IRMods) {
293 storage::Header Hdr;
294
295 assert(!IRMods.empty());
296 Hdr.Version = storage::Header::kCurrentVersion;
297 setStr(Hdr.Producer, kExpectedProducerName);
298 setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
299 setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
300 TT = Triple(IRMods[0]->getTargetTriple());
301
302 for (auto *M : IRMods)
303 if (Error Err = addModule(M))
304 return Err;
305
306 COFFLinkerOptsOS.flush();
307 setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
308
309 // We are about to fill in the header's range fields, so reserve space for it
310 // and copy it in afterwards.
311 Symtab.resize(sizeof(storage::Header));
312 writeRange(Hdr.Modules, Mods);
313 writeRange(Hdr.Comdats, Comdats);
314 writeRange(Hdr.Symbols, Syms);
315 writeRange(Hdr.Uncommons, Uncommons);
316
317 *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
318 return Error::success();
319 }
320
321 } // end anonymous namespace
322
build(ArrayRef<Module * > Mods,SmallVector<char,0> & Symtab,StringTableBuilder & StrtabBuilder,BumpPtrAllocator & Alloc)323 Error irsymtab::build(ArrayRef<Module *> Mods, SmallVector<char, 0> &Symtab,
324 StringTableBuilder &StrtabBuilder,
325 BumpPtrAllocator &Alloc) {
326 return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
327 }
328
329 // Upgrade a vector of bitcode modules created by an old version of LLVM by
330 // creating an irsymtab for them in the current format.
upgrade(ArrayRef<BitcodeModule> BMs)331 static Expected<FileContents> upgrade(ArrayRef<BitcodeModule> BMs) {
332 FileContents FC;
333
334 LLVMContext Ctx;
335 std::vector<Module *> Mods;
336 std::vector<std::unique_ptr<Module>> OwnedMods;
337 for (auto BM : BMs) {
338 Expected<std::unique_ptr<Module>> MOrErr =
339 BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
340 /*IsImporting*/ false);
341 if (!MOrErr)
342 return MOrErr.takeError();
343
344 Mods.push_back(MOrErr->get());
345 OwnedMods.push_back(std::move(*MOrErr));
346 }
347
348 StringTableBuilder StrtabBuilder(StringTableBuilder::RAW);
349 BumpPtrAllocator Alloc;
350 if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
351 return std::move(E);
352
353 StrtabBuilder.finalizeInOrder();
354 FC.Strtab.resize(StrtabBuilder.getSize());
355 StrtabBuilder.write((uint8_t *)FC.Strtab.data());
356
357 FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
358 {FC.Strtab.data(), FC.Strtab.size()}};
359 return std::move(FC);
360 }
361
readBitcode(const BitcodeFileContents & BFC)362 Expected<FileContents> irsymtab::readBitcode(const BitcodeFileContents &BFC) {
363 if (BFC.Mods.empty())
364 return make_error<StringError>("Bitcode file does not contain any modules",
365 inconvertibleErrorCode());
366
367 if (BFC.StrtabForSymtab.empty() ||
368 BFC.Symtab.size() < sizeof(storage::Header))
369 return upgrade(BFC.Mods);
370
371 // We cannot use the regular reader to read the version and producer, because
372 // it will expect the header to be in the current format. The only thing we
373 // can rely on is that the version and producer will be present as the first
374 // struct elements.
375 auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
376 unsigned Version = Hdr->Version;
377 StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
378 if (Version != storage::Header::kCurrentVersion ||
379 Producer != kExpectedProducerName)
380 return upgrade(BFC.Mods);
381
382 FileContents FC;
383 FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
384 {BFC.StrtabForSymtab.data(), BFC.StrtabForSymtab.size()}};
385
386 // Finally, make sure that the number of modules in the symbol table matches
387 // the number of modules in the bitcode file. If they differ, it may mean that
388 // the bitcode file was created by binary concatenation, so we need to create
389 // a new symbol table from scratch.
390 if (FC.TheReader.getNumModules() != BFC.Mods.size())
391 return upgrade(std::move(BFC.Mods));
392
393 return std::move(FC);
394 }
395