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