1 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
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 file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/LTO/legacy/LTOModule.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Mangler.h"
23 #include "llvm/IR/Metadata.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
30 #include "llvm/MC/MCSection.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/Object/IRObjectFile.h"
35 #include "llvm/Object/ObjectFile.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Host.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetLoweringObjectFile.h"
45 #include "llvm/Target/TargetRegisterInfo.h"
46 #include "llvm/Target/TargetSubtargetInfo.h"
47 #include "llvm/Transforms/Utils/GlobalStatus.h"
48 #include <system_error>
49 using namespace llvm;
50 using namespace llvm::object;
51
LTOModule(std::unique_ptr<object::IRObjectFile> Obj,llvm::TargetMachine * TM)52 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj,
53 llvm::TargetMachine *TM)
54 : IRFile(std::move(Obj)), _target(TM) {}
55
~LTOModule()56 LTOModule::~LTOModule() {}
57
58 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
59 /// bitcode.
isBitcodeFile(const void * Mem,size_t Length)60 bool LTOModule::isBitcodeFile(const void *Mem, size_t Length) {
61 ErrorOr<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
62 MemoryBufferRef(StringRef((const char *)Mem, Length), "<mem>"));
63 return bool(BCData);
64 }
65
isBitcodeFile(const char * Path)66 bool LTOModule::isBitcodeFile(const char *Path) {
67 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
68 MemoryBuffer::getFile(Path);
69 if (!BufferOrErr)
70 return false;
71
72 ErrorOr<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
73 BufferOrErr.get()->getMemBufferRef());
74 return bool(BCData);
75 }
76
isThinLTO()77 bool LTOModule::isThinLTO() {
78 // Right now the detection is only based on the summary presence. We may want
79 // to add a dedicated flag at some point.
80 return hasGlobalValueSummary(IRFile->getMemoryBufferRef(),
81 [](const DiagnosticInfo &DI) {
82 DiagnosticPrinterRawOStream DP(errs());
83 DI.print(DP);
84 errs() << '\n';
85 return;
86 });
87 }
88
isBitcodeForTarget(MemoryBuffer * Buffer,StringRef TriplePrefix)89 bool LTOModule::isBitcodeForTarget(MemoryBuffer *Buffer,
90 StringRef TriplePrefix) {
91 ErrorOr<MemoryBufferRef> BCOrErr =
92 IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
93 if (!BCOrErr)
94 return false;
95 LLVMContext Context;
96 std::string Triple = getBitcodeTargetTriple(*BCOrErr, Context);
97 return StringRef(Triple).startswith(TriplePrefix);
98 }
99
getProducerString(MemoryBuffer * Buffer)100 std::string LTOModule::getProducerString(MemoryBuffer *Buffer) {
101 ErrorOr<MemoryBufferRef> BCOrErr =
102 IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
103 if (!BCOrErr)
104 return "";
105 LLVMContext Context;
106 return getBitcodeProducerString(*BCOrErr, Context);
107 }
108
109 ErrorOr<std::unique_ptr<LTOModule>>
createFromFile(LLVMContext & Context,const char * path,const TargetOptions & options)110 LTOModule::createFromFile(LLVMContext &Context, const char *path,
111 const TargetOptions &options) {
112 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
113 MemoryBuffer::getFile(path);
114 if (std::error_code EC = BufferOrErr.getError()) {
115 Context.emitError(EC.message());
116 return EC;
117 }
118 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
119 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
120 /* ShouldBeLazy*/ false);
121 }
122
123 ErrorOr<std::unique_ptr<LTOModule>>
createFromOpenFile(LLVMContext & Context,int fd,const char * path,size_t size,const TargetOptions & options)124 LTOModule::createFromOpenFile(LLVMContext &Context, int fd, const char *path,
125 size_t size, const TargetOptions &options) {
126 return createFromOpenFileSlice(Context, fd, path, size, 0, options);
127 }
128
129 ErrorOr<std::unique_ptr<LTOModule>>
createFromOpenFileSlice(LLVMContext & Context,int fd,const char * path,size_t map_size,off_t offset,const TargetOptions & options)130 LTOModule::createFromOpenFileSlice(LLVMContext &Context, int fd,
131 const char *path, size_t map_size,
132 off_t offset, const TargetOptions &options) {
133 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
134 MemoryBuffer::getOpenFileSlice(fd, path, map_size, offset);
135 if (std::error_code EC = BufferOrErr.getError()) {
136 Context.emitError(EC.message());
137 return EC;
138 }
139 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
140 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
141 /* ShouldBeLazy */ false);
142 }
143
144 ErrorOr<std::unique_ptr<LTOModule>>
createFromBuffer(LLVMContext & Context,const void * mem,size_t length,const TargetOptions & options,StringRef path)145 LTOModule::createFromBuffer(LLVMContext &Context, const void *mem,
146 size_t length, const TargetOptions &options,
147 StringRef path) {
148 StringRef Data((const char *)mem, length);
149 MemoryBufferRef Buffer(Data, path);
150 return makeLTOModule(Buffer, options, Context, /* ShouldBeLazy */ false);
151 }
152
153 ErrorOr<std::unique_ptr<LTOModule>>
createInLocalContext(std::unique_ptr<LLVMContext> Context,const void * mem,size_t length,const TargetOptions & options,StringRef path)154 LTOModule::createInLocalContext(std::unique_ptr<LLVMContext> Context,
155 const void *mem, size_t length,
156 const TargetOptions &options, StringRef path) {
157 StringRef Data((const char *)mem, length);
158 MemoryBufferRef Buffer(Data, path);
159 // If we own a context, we know this is being used only for symbol extraction,
160 // not linking. Be lazy in that case.
161 ErrorOr<std::unique_ptr<LTOModule>> Ret =
162 makeLTOModule(Buffer, options, *Context, /* ShouldBeLazy */ true);
163 if (Ret)
164 (*Ret)->OwnedContext = std::move(Context);
165 return Ret;
166 }
167
168 static ErrorOr<std::unique_ptr<Module>>
parseBitcodeFileImpl(MemoryBufferRef Buffer,LLVMContext & Context,bool ShouldBeLazy)169 parseBitcodeFileImpl(MemoryBufferRef Buffer, LLVMContext &Context,
170 bool ShouldBeLazy) {
171
172 // Find the buffer.
173 ErrorOr<MemoryBufferRef> MBOrErr =
174 IRObjectFile::findBitcodeInMemBuffer(Buffer);
175 if (std::error_code EC = MBOrErr.getError()) {
176 Context.emitError(EC.message());
177 return EC;
178 }
179
180 if (!ShouldBeLazy) {
181 // Parse the full file.
182 ErrorOr<std::unique_ptr<Module>> M = parseBitcodeFile(*MBOrErr, Context);
183 if (std::error_code EC = M.getError())
184 return EC;
185 return std::move(*M);
186 }
187
188 // Parse lazily.
189 std::unique_ptr<MemoryBuffer> LightweightBuf =
190 MemoryBuffer::getMemBuffer(*MBOrErr, false);
191 ErrorOr<std::unique_ptr<Module>> M = getLazyBitcodeModule(
192 std::move(LightweightBuf), Context, true /*ShouldLazyLoadMetadata*/);
193 if (std::error_code EC = M.getError())
194 return EC;
195 return std::move(*M);
196 }
197
198 ErrorOr<std::unique_ptr<LTOModule>>
makeLTOModule(MemoryBufferRef Buffer,const TargetOptions & options,LLVMContext & Context,bool ShouldBeLazy)199 LTOModule::makeLTOModule(MemoryBufferRef Buffer, const TargetOptions &options,
200 LLVMContext &Context, bool ShouldBeLazy) {
201 ErrorOr<std::unique_ptr<Module>> MOrErr =
202 parseBitcodeFileImpl(Buffer, Context, ShouldBeLazy);
203 if (std::error_code EC = MOrErr.getError())
204 return EC;
205 std::unique_ptr<Module> &M = *MOrErr;
206
207 std::string TripleStr = M->getTargetTriple();
208 if (TripleStr.empty())
209 TripleStr = sys::getDefaultTargetTriple();
210 llvm::Triple Triple(TripleStr);
211
212 // find machine architecture for this module
213 std::string errMsg;
214 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
215 if (!march)
216 return std::unique_ptr<LTOModule>(nullptr);
217
218 // construct LTOModule, hand over ownership of module and target
219 SubtargetFeatures Features;
220 Features.getDefaultSubtargetFeatures(Triple);
221 std::string FeatureStr = Features.getString();
222 // Set a default CPU for Darwin triples.
223 std::string CPU;
224 if (Triple.isOSDarwin()) {
225 if (Triple.getArch() == llvm::Triple::x86_64)
226 CPU = "core2";
227 else if (Triple.getArch() == llvm::Triple::x86)
228 CPU = "yonah";
229 else if (Triple.getArch() == llvm::Triple::aarch64)
230 CPU = "cyclone";
231 }
232
233 TargetMachine *target =
234 march->createTargetMachine(TripleStr, CPU, FeatureStr, options, None);
235 M->setDataLayout(target->createDataLayout());
236
237 std::unique_ptr<object::IRObjectFile> IRObj(
238 new object::IRObjectFile(Buffer, std::move(M)));
239
240 std::unique_ptr<LTOModule> Ret(new LTOModule(std::move(IRObj), target));
241 Ret->parseSymbols();
242 Ret->parseMetadata();
243
244 return std::move(Ret);
245 }
246
247 /// Create a MemoryBuffer from a memory range with an optional name.
248 std::unique_ptr<MemoryBuffer>
makeBuffer(const void * mem,size_t length,StringRef name)249 LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {
250 const char *startPtr = (const char*)mem;
251 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
252 }
253
254 /// objcClassNameFromExpression - Get string that the data pointer points to.
255 bool
objcClassNameFromExpression(const Constant * c,std::string & name)256 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
257 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
258 Constant *op = ce->getOperand(0);
259 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
260 Constant *cn = gvn->getInitializer();
261 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
262 if (ca->isCString()) {
263 name = (".objc_class_name_" + ca->getAsCString()).str();
264 return true;
265 }
266 }
267 }
268 }
269 return false;
270 }
271
272 /// addObjCClass - Parse i386/ppc ObjC class data structure.
addObjCClass(const GlobalVariable * clgv)273 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
274 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
275 if (!c) return;
276
277 // second slot in __OBJC,__class is pointer to superclass name
278 std::string superclassName;
279 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
280 auto IterBool =
281 _undefines.insert(std::make_pair(superclassName, NameAndAttributes()));
282 if (IterBool.second) {
283 NameAndAttributes &info = IterBool.first->second;
284 info.name = IterBool.first->first().data();
285 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
286 info.isFunction = false;
287 info.symbol = clgv;
288 }
289 }
290
291 // third slot in __OBJC,__class is pointer to class name
292 std::string className;
293 if (objcClassNameFromExpression(c->getOperand(2), className)) {
294 auto Iter = _defines.insert(className).first;
295
296 NameAndAttributes info;
297 info.name = Iter->first().data();
298 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
299 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
300 info.isFunction = false;
301 info.symbol = clgv;
302 _symbols.push_back(info);
303 }
304 }
305
306 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
addObjCCategory(const GlobalVariable * clgv)307 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
308 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
309 if (!c) return;
310
311 // second slot in __OBJC,__category is pointer to target class name
312 std::string targetclassName;
313 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
314 return;
315
316 auto IterBool =
317 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
318
319 if (!IterBool.second)
320 return;
321
322 NameAndAttributes &info = IterBool.first->second;
323 info.name = IterBool.first->first().data();
324 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
325 info.isFunction = false;
326 info.symbol = clgv;
327 }
328
329 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
addObjCClassRef(const GlobalVariable * clgv)330 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
331 std::string targetclassName;
332 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
333 return;
334
335 auto IterBool =
336 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
337
338 if (!IterBool.second)
339 return;
340
341 NameAndAttributes &info = IterBool.first->second;
342 info.name = IterBool.first->first().data();
343 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
344 info.isFunction = false;
345 info.symbol = clgv;
346 }
347
addDefinedDataSymbol(const object::BasicSymbolRef & Sym)348 void LTOModule::addDefinedDataSymbol(const object::BasicSymbolRef &Sym) {
349 SmallString<64> Buffer;
350 {
351 raw_svector_ostream OS(Buffer);
352 Sym.printName(OS);
353 }
354
355 const GlobalValue *V = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
356 addDefinedDataSymbol(Buffer.c_str(), V);
357 }
358
addDefinedDataSymbol(const char * Name,const GlobalValue * v)359 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) {
360 // Add to list of defined symbols.
361 addDefinedSymbol(Name, v, false);
362
363 if (!v->hasSection() /* || !isTargetDarwin */)
364 return;
365
366 // Special case i386/ppc ObjC data structures in magic sections:
367 // The issue is that the old ObjC object format did some strange
368 // contortions to avoid real linker symbols. For instance, the
369 // ObjC class data structure is allocated statically in the executable
370 // that defines that class. That data structures contains a pointer to
371 // its superclass. But instead of just initializing that part of the
372 // struct to the address of its superclass, and letting the static and
373 // dynamic linkers do the rest, the runtime works by having that field
374 // instead point to a C-string that is the name of the superclass.
375 // At runtime the objc initialization updates that pointer and sets
376 // it to point to the actual super class. As far as the linker
377 // knows it is just a pointer to a string. But then someone wanted the
378 // linker to issue errors at build time if the superclass was not found.
379 // So they figured out a way in mach-o object format to use an absolute
380 // symbols (.objc_class_name_Foo = 0) and a floating reference
381 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
382 // a class was missing.
383 // The following synthesizes the implicit .objc_* symbols for the linker
384 // from the ObjC data structures generated by the front end.
385
386 // special case if this data blob is an ObjC class definition
387 std::string Section = v->getSection();
388 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
389 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
390 addObjCClass(gv);
391 }
392 }
393
394 // special case if this data blob is an ObjC category definition
395 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
396 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
397 addObjCCategory(gv);
398 }
399 }
400
401 // special case if this data blob is the list of referenced classes
402 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
403 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
404 addObjCClassRef(gv);
405 }
406 }
407 }
408
addDefinedFunctionSymbol(const object::BasicSymbolRef & Sym)409 void LTOModule::addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym) {
410 SmallString<64> Buffer;
411 {
412 raw_svector_ostream OS(Buffer);
413 Sym.printName(OS);
414 }
415
416 const Function *F =
417 cast<Function>(IRFile->getSymbolGV(Sym.getRawDataRefImpl()));
418 addDefinedFunctionSymbol(Buffer.c_str(), F);
419 }
420
addDefinedFunctionSymbol(const char * Name,const Function * F)421 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) {
422 // add to list of defined symbols
423 addDefinedSymbol(Name, F, true);
424 }
425
addDefinedSymbol(const char * Name,const GlobalValue * def,bool isFunction)426 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def,
427 bool isFunction) {
428 // set alignment part log2() can have rounding errors
429 uint32_t align = def->getAlignment();
430 uint32_t attr = align ? countTrailingZeros(align) : 0;
431
432 // set permissions part
433 if (isFunction) {
434 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
435 } else {
436 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
437 if (gv && gv->isConstant())
438 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
439 else
440 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
441 }
442
443 // set definition part
444 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
445 attr |= LTO_SYMBOL_DEFINITION_WEAK;
446 else if (def->hasCommonLinkage())
447 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
448 else
449 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
450
451 // set scope part
452 if (def->hasLocalLinkage())
453 // Ignore visibility if linkage is local.
454 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
455 else if (def->hasHiddenVisibility())
456 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
457 else if (def->hasProtectedVisibility())
458 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
459 else if (canBeOmittedFromSymbolTable(def))
460 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
461 else
462 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
463
464 if (def->hasComdat())
465 attr |= LTO_SYMBOL_COMDAT;
466
467 if (isa<GlobalAlias>(def))
468 attr |= LTO_SYMBOL_ALIAS;
469
470 auto Iter = _defines.insert(Name).first;
471
472 // fill information structure
473 NameAndAttributes info;
474 StringRef NameRef = Iter->first();
475 info.name = NameRef.data();
476 assert(info.name[NameRef.size()] == '\0');
477 info.attributes = attr;
478 info.isFunction = isFunction;
479 info.symbol = def;
480
481 // add to table of symbols
482 _symbols.push_back(info);
483 }
484
485 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
486 /// defined list.
addAsmGlobalSymbol(const char * name,lto_symbol_attributes scope)487 void LTOModule::addAsmGlobalSymbol(const char *name,
488 lto_symbol_attributes scope) {
489 auto IterBool = _defines.insert(name);
490
491 // only add new define if not already defined
492 if (!IterBool.second)
493 return;
494
495 NameAndAttributes &info = _undefines[IterBool.first->first().data()];
496
497 if (info.symbol == nullptr) {
498 // FIXME: This is trying to take care of module ASM like this:
499 //
500 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
501 //
502 // but is gross and its mother dresses it funny. Have the ASM parser give us
503 // more details for this type of situation so that we're not guessing so
504 // much.
505
506 // fill information structure
507 info.name = IterBool.first->first().data();
508 info.attributes =
509 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
510 info.isFunction = false;
511 info.symbol = nullptr;
512
513 // add to table of symbols
514 _symbols.push_back(info);
515 return;
516 }
517
518 if (info.isFunction)
519 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
520 else
521 addDefinedDataSymbol(info.name, info.symbol);
522
523 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
524 _symbols.back().attributes |= scope;
525 }
526
527 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
528 /// undefined list.
addAsmGlobalSymbolUndef(const char * name)529 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
530 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
531
532 _asm_undefines.push_back(IterBool.first->first().data());
533
534 // we already have the symbol
535 if (!IterBool.second)
536 return;
537
538 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
539 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
540 NameAndAttributes &info = IterBool.first->second;
541 info.name = IterBool.first->first().data();
542 info.attributes = attr;
543 info.isFunction = false;
544 info.symbol = nullptr;
545 }
546
547 /// Add a symbol which isn't defined just yet to a list to be resolved later.
addPotentialUndefinedSymbol(const object::BasicSymbolRef & Sym,bool isFunc)548 void LTOModule::addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym,
549 bool isFunc) {
550 SmallString<64> name;
551 {
552 raw_svector_ostream OS(name);
553 Sym.printName(OS);
554 }
555
556 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
557
558 // we already have the symbol
559 if (!IterBool.second)
560 return;
561
562 NameAndAttributes &info = IterBool.first->second;
563
564 info.name = IterBool.first->first().data();
565
566 const GlobalValue *decl = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
567
568 if (decl->hasExternalWeakLinkage())
569 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
570 else
571 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
572
573 info.isFunction = isFunc;
574 info.symbol = decl;
575 }
576
parseSymbols()577 void LTOModule::parseSymbols() {
578 for (auto &Sym : IRFile->symbols()) {
579 const GlobalValue *GV = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
580 uint32_t Flags = Sym.getFlags();
581 if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
582 continue;
583
584 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
585
586 if (!GV) {
587 SmallString<64> Buffer;
588 {
589 raw_svector_ostream OS(Buffer);
590 Sym.printName(OS);
591 }
592 const char *Name = Buffer.c_str();
593
594 if (IsUndefined)
595 addAsmGlobalSymbolUndef(Name);
596 else if (Flags & object::BasicSymbolRef::SF_Global)
597 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
598 else
599 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
600 continue;
601 }
602
603 auto *F = dyn_cast<Function>(GV);
604 if (IsUndefined) {
605 addPotentialUndefinedSymbol(Sym, F != nullptr);
606 continue;
607 }
608
609 if (F) {
610 addDefinedFunctionSymbol(Sym);
611 continue;
612 }
613
614 if (isa<GlobalVariable>(GV)) {
615 addDefinedDataSymbol(Sym);
616 continue;
617 }
618
619 assert(isa<GlobalAlias>(GV));
620 addDefinedDataSymbol(Sym);
621 }
622
623 // make symbols for all undefines
624 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
625 e = _undefines.end(); u != e; ++u) {
626 // If this symbol also has a definition, then don't make an undefine because
627 // it is a tentative definition.
628 if (_defines.count(u->getKey())) continue;
629 NameAndAttributes info = u->getValue();
630 _symbols.push_back(info);
631 }
632 }
633
634 /// parseMetadata - Parse metadata from the module
parseMetadata()635 void LTOModule::parseMetadata() {
636 raw_string_ostream OS(LinkerOpts);
637
638 // Linker Options
639 if (Metadata *Val = getModule().getModuleFlag("Linker Options")) {
640 MDNode *LinkerOptions = cast<MDNode>(Val);
641 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
642 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
643 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
644 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
645 OS << " " << MDOption->getString();
646 }
647 }
648 }
649
650 // Globals
651 Mangler Mang;
652 for (const NameAndAttributes &Sym : _symbols) {
653 if (!Sym.symbol)
654 continue;
655 _target->getObjFileLowering()->emitLinkerFlagsForGlobal(OS, Sym.symbol,
656 Mang);
657 }
658
659 // Add other interesting metadata here.
660 }
661