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