[clang][bytecode] Fix reporting failed local constexpr initializers (#123588)
[llvm-project.git] / llvm / lib / LTO / LTOModule.cpp
blob00eb8adb4e10357b473f589dcdc181d5ed2ef0df
1 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/LTO/legacy/LTOModule.h"
15 #include "llvm/Bitcode/BitcodeReader.h"
16 #include "llvm/CodeGen/TargetSubtargetInfo.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/Mangler.h"
20 #include "llvm/IR/Metadata.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCSection.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/TargetRegistry.h"
29 #include "llvm/Object/IRObjectFile.h"
30 #include "llvm/Object/MachO.h"
31 #include "llvm/Object/ObjectFile.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/TargetSelect.h"
37 #include "llvm/Target/TargetLoweringObjectFile.h"
38 #include "llvm/TargetParser/Host.h"
39 #include "llvm/TargetParser/SubtargetFeature.h"
40 #include "llvm/TargetParser/Triple.h"
41 #include "llvm/Transforms/Utils/GlobalStatus.h"
42 #include <system_error>
43 using namespace llvm;
44 using namespace llvm::object;
46 LTOModule::LTOModule(std::unique_ptr<Module> M, MemoryBufferRef MBRef,
47 llvm::TargetMachine *TM)
48 : Mod(std::move(M)), MBRef(MBRef), _target(TM) {
49 assert(_target && "target machine is null");
50 SymTab.addModule(Mod.get());
53 LTOModule::~LTOModule() = default;
55 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
56 /// bitcode.
57 bool LTOModule::isBitcodeFile(const void *Mem, size_t Length) {
58 Expected<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
59 MemoryBufferRef(StringRef((const char *)Mem, Length), "<mem>"));
60 return !errorToBool(BCData.takeError());
63 bool LTOModule::isBitcodeFile(StringRef Path) {
64 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
65 MemoryBuffer::getFile(Path);
66 if (!BufferOrErr)
67 return false;
69 Expected<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
70 BufferOrErr.get()->getMemBufferRef());
71 return !errorToBool(BCData.takeError());
74 bool LTOModule::isThinLTO() {
75 Expected<BitcodeLTOInfo> Result = getBitcodeLTOInfo(MBRef);
76 if (!Result) {
77 logAllUnhandledErrors(Result.takeError(), errs());
78 return false;
80 return Result->IsThinLTO;
83 bool LTOModule::isBitcodeForTarget(MemoryBuffer *Buffer,
84 StringRef TriplePrefix) {
85 Expected<MemoryBufferRef> BCOrErr =
86 IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
87 if (errorToBool(BCOrErr.takeError()))
88 return false;
89 LLVMContext Context;
90 ErrorOr<std::string> TripleOrErr =
91 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(*BCOrErr));
92 if (!TripleOrErr)
93 return false;
94 return StringRef(*TripleOrErr).starts_with(TriplePrefix);
97 std::string LTOModule::getProducerString(MemoryBuffer *Buffer) {
98 Expected<MemoryBufferRef> BCOrErr =
99 IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
100 if (errorToBool(BCOrErr.takeError()))
101 return "";
102 LLVMContext Context;
103 ErrorOr<std::string> ProducerOrErr = expectedToErrorOrAndEmitErrors(
104 Context, getBitcodeProducerString(*BCOrErr));
105 if (!ProducerOrErr)
106 return "";
107 return *ProducerOrErr;
110 ErrorOr<std::unique_ptr<LTOModule>>
111 LTOModule::createFromFile(LLVMContext &Context, StringRef path,
112 const TargetOptions &options) {
113 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
114 MemoryBuffer::getFile(path);
115 if (std::error_code EC = BufferOrErr.getError()) {
116 Context.emitError(EC.message());
117 return EC;
119 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
120 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
121 /* ShouldBeLazy*/ false);
124 ErrorOr<std::unique_ptr<LTOModule>>
125 LTOModule::createFromOpenFile(LLVMContext &Context, int fd, StringRef path,
126 size_t size, const TargetOptions &options) {
127 return createFromOpenFileSlice(Context, fd, path, size, 0, options);
130 ErrorOr<std::unique_ptr<LTOModule>>
131 LTOModule::createFromOpenFileSlice(LLVMContext &Context, int fd, StringRef path,
132 size_t map_size, off_t offset,
133 const TargetOptions &options) {
134 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
135 MemoryBuffer::getOpenFileSlice(sys::fs::convertFDToNativeFile(fd), path,
136 map_size, offset);
137 if (std::error_code EC = BufferOrErr.getError()) {
138 Context.emitError(EC.message());
139 return EC;
141 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
142 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
143 /* ShouldBeLazy */ false);
146 ErrorOr<std::unique_ptr<LTOModule>>
147 LTOModule::createFromBuffer(LLVMContext &Context, const void *mem,
148 size_t length, const TargetOptions &options,
149 StringRef path) {
150 StringRef Data((const char *)mem, length);
151 MemoryBufferRef Buffer(Data, path);
152 return makeLTOModule(Buffer, options, Context, /* ShouldBeLazy */ false);
155 ErrorOr<std::unique_ptr<LTOModule>>
156 LTOModule::createInLocalContext(std::unique_ptr<LLVMContext> Context,
157 const void *mem, size_t length,
158 const TargetOptions &options, StringRef path) {
159 StringRef Data((const char *)mem, length);
160 MemoryBufferRef Buffer(Data, path);
161 // If we own a context, we know this is being used only for symbol extraction,
162 // not linking. Be lazy in that case.
163 ErrorOr<std::unique_ptr<LTOModule>> Ret =
164 makeLTOModule(Buffer, options, *Context, /* ShouldBeLazy */ true);
165 if (Ret)
166 (*Ret)->OwnedContext = std::move(Context);
167 return Ret;
170 static ErrorOr<std::unique_ptr<Module>>
171 parseBitcodeFileImpl(MemoryBufferRef Buffer, LLVMContext &Context,
172 bool ShouldBeLazy) {
173 // Find the buffer.
174 Expected<MemoryBufferRef> MBOrErr =
175 IRObjectFile::findBitcodeInMemBuffer(Buffer);
176 if (Error E = MBOrErr.takeError()) {
177 std::error_code EC = errorToErrorCode(std::move(E));
178 Context.emitError(EC.message());
179 return EC;
182 if (!ShouldBeLazy) {
183 // Parse the full file.
184 return expectedToErrorOrAndEmitErrors(Context,
185 parseBitcodeFile(*MBOrErr, Context));
188 // Parse lazily.
189 return expectedToErrorOrAndEmitErrors(
190 Context,
191 getLazyBitcodeModule(*MBOrErr, Context, true /*ShouldLazyLoadMetadata*/));
194 ErrorOr<std::unique_ptr<LTOModule>>
195 LTOModule::makeLTOModule(MemoryBufferRef Buffer, const TargetOptions &options,
196 LLVMContext &Context, bool ShouldBeLazy) {
197 ErrorOr<std::unique_ptr<Module>> MOrErr =
198 parseBitcodeFileImpl(Buffer, Context, ShouldBeLazy);
199 if (std::error_code EC = MOrErr.getError())
200 return EC;
201 std::unique_ptr<Module> &M = *MOrErr;
203 std::string TripleStr = M->getTargetTriple();
204 if (TripleStr.empty())
205 TripleStr = sys::getDefaultTargetTriple();
206 llvm::Triple Triple(TripleStr);
208 // find machine architecture for this module
209 std::string errMsg;
210 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
211 if (!march)
212 return make_error_code(object::object_error::arch_not_found);
214 // construct LTOModule, hand over ownership of module and target
215 SubtargetFeatures Features;
216 Features.getDefaultSubtargetFeatures(Triple);
217 std::string FeatureStr = Features.getString();
218 // Set a default CPU for Darwin triples.
219 std::string CPU;
220 if (Triple.isOSDarwin()) {
221 if (Triple.getArch() == llvm::Triple::x86_64)
222 CPU = "core2";
223 else if (Triple.getArch() == llvm::Triple::x86)
224 CPU = "yonah";
225 else if (Triple.isArm64e())
226 CPU = "apple-a12";
227 else if (Triple.getArch() == llvm::Triple::aarch64 ||
228 Triple.getArch() == llvm::Triple::aarch64_32)
229 CPU = "cyclone";
232 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
233 options, std::nullopt);
235 std::unique_ptr<LTOModule> Ret(new LTOModule(std::move(M), Buffer, target));
236 Ret->parseSymbols();
237 Ret->parseMetadata();
239 return std::move(Ret);
242 /// Create a MemoryBuffer from a memory range with an optional name.
243 std::unique_ptr<MemoryBuffer>
244 LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {
245 const char *startPtr = (const char*)mem;
246 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
249 /// objcClassNameFromExpression - Get string that the data pointer points to.
250 bool
251 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
252 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
253 Constant *op = ce->getOperand(0);
254 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
255 Constant *cn = gvn->getInitializer();
256 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
257 if (ca->isCString()) {
258 name = (".objc_class_name_" + ca->getAsCString()).str();
259 return true;
264 return false;
267 /// addObjCClass - Parse i386/ppc ObjC class data structure.
268 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
269 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
270 if (!c) return;
272 // second slot in __OBJC,__class is pointer to superclass name
273 std::string superclassName;
274 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
275 auto IterBool =
276 _undefines.insert(std::make_pair(superclassName, NameAndAttributes()));
277 if (IterBool.second) {
278 NameAndAttributes &info = IterBool.first->second;
279 info.name = IterBool.first->first();
280 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
281 info.isFunction = false;
282 info.symbol = clgv;
286 // third slot in __OBJC,__class is pointer to class name
287 std::string className;
288 if (objcClassNameFromExpression(c->getOperand(2), className)) {
289 auto Iter = _defines.insert(className).first;
291 NameAndAttributes info;
292 info.name = Iter->first();
293 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
294 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
295 info.isFunction = false;
296 info.symbol = clgv;
297 _symbols.push_back(info);
301 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
302 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
303 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
304 if (!c) return;
306 // second slot in __OBJC,__category is pointer to target class name
307 std::string targetclassName;
308 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
309 return;
311 auto IterBool =
312 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
314 if (!IterBool.second)
315 return;
317 NameAndAttributes &info = IterBool.first->second;
318 info.name = IterBool.first->first();
319 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
320 info.isFunction = false;
321 info.symbol = clgv;
324 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
325 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
326 std::string targetclassName;
327 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
328 return;
330 auto IterBool =
331 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
333 if (!IterBool.second)
334 return;
336 NameAndAttributes &info = IterBool.first->second;
337 info.name = IterBool.first->first();
338 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
339 info.isFunction = false;
340 info.symbol = clgv;
343 void LTOModule::addDefinedDataSymbol(ModuleSymbolTable::Symbol Sym) {
344 SmallString<64> Buffer;
346 raw_svector_ostream OS(Buffer);
347 SymTab.printSymbolName(OS, Sym);
348 Buffer.c_str();
351 const GlobalValue *V = cast<GlobalValue *>(Sym);
352 addDefinedDataSymbol(Buffer, V);
355 void LTOModule::addDefinedDataSymbol(StringRef Name, const GlobalValue *v) {
356 // Add to list of defined symbols.
357 addDefinedSymbol(Name, v, false);
359 if (!v->hasSection() /* || !isTargetDarwin */)
360 return;
362 // Special case i386/ppc ObjC data structures in magic sections:
363 // The issue is that the old ObjC object format did some strange
364 // contortions to avoid real linker symbols. For instance, the
365 // ObjC class data structure is allocated statically in the executable
366 // that defines that class. That data structures contains a pointer to
367 // its superclass. But instead of just initializing that part of the
368 // struct to the address of its superclass, and letting the static and
369 // dynamic linkers do the rest, the runtime works by having that field
370 // instead point to a C-string that is the name of the superclass.
371 // At runtime the objc initialization updates that pointer and sets
372 // it to point to the actual super class. As far as the linker
373 // knows it is just a pointer to a string. But then someone wanted the
374 // linker to issue errors at build time if the superclass was not found.
375 // So they figured out a way in mach-o object format to use an absolute
376 // symbols (.objc_class_name_Foo = 0) and a floating reference
377 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
378 // a class was missing.
379 // The following synthesizes the implicit .objc_* symbols for the linker
380 // from the ObjC data structures generated by the front end.
382 // special case if this data blob is an ObjC class definition
383 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(v)) {
384 StringRef Section = GV->getSection();
385 if (Section.starts_with("__OBJC,__class,")) {
386 addObjCClass(GV);
389 // special case if this data blob is an ObjC category definition
390 else if (Section.starts_with("__OBJC,__category,")) {
391 addObjCCategory(GV);
394 // special case if this data blob is the list of referenced classes
395 else if (Section.starts_with("__OBJC,__cls_refs,")) {
396 addObjCClassRef(GV);
401 void LTOModule::addDefinedFunctionSymbol(ModuleSymbolTable::Symbol Sym) {
402 SmallString<64> Buffer;
404 raw_svector_ostream OS(Buffer);
405 SymTab.printSymbolName(OS, Sym);
406 Buffer.c_str();
409 auto *GV = cast<GlobalValue *>(Sym);
410 assert((isa<Function>(GV) ||
411 (isa<GlobalAlias>(GV) &&
412 isa<Function>(cast<GlobalAlias>(GV)->getAliasee()))) &&
413 "Not function or function alias");
415 addDefinedFunctionSymbol(Buffer, GV);
418 void LTOModule::addDefinedFunctionSymbol(StringRef Name, const GlobalValue *F) {
419 // add to list of defined symbols
420 addDefinedSymbol(Name, F, true);
423 void LTOModule::addDefinedSymbol(StringRef Name, const GlobalValue *def,
424 bool isFunction) {
425 const GlobalObject *go = dyn_cast<GlobalObject>(def);
426 uint32_t attr = go ? Log2(go->getAlign().valueOrOne()) : 0;
428 // set permissions part
429 if (isFunction) {
430 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
431 } else {
432 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
433 if (gv && gv->isConstant())
434 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
435 else
436 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
439 // set definition part
440 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
441 attr |= LTO_SYMBOL_DEFINITION_WEAK;
442 else if (def->hasCommonLinkage())
443 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
444 else
445 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
447 // set scope part
448 if (def->hasLocalLinkage())
449 // Ignore visibility if linkage is local.
450 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
451 else if (def->hasHiddenVisibility())
452 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
453 else if (def->hasProtectedVisibility())
454 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
455 else if (def->canBeOmittedFromSymbolTable())
456 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
457 else
458 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
460 if (def->hasComdat())
461 attr |= LTO_SYMBOL_COMDAT;
463 if (isa<GlobalAlias>(def))
464 attr |= LTO_SYMBOL_ALIAS;
466 auto Iter = _defines.insert(Name).first;
468 // fill information structure
469 NameAndAttributes info;
470 StringRef NameRef = Iter->first();
471 info.name = NameRef;
472 assert(NameRef.data()[NameRef.size()] == '\0');
473 info.attributes = attr;
474 info.isFunction = isFunction;
475 info.symbol = def;
477 // add to table of symbols
478 _symbols.push_back(info);
481 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
482 /// defined list.
483 void LTOModule::addAsmGlobalSymbol(StringRef name,
484 lto_symbol_attributes scope) {
485 auto IterBool = _defines.insert(name);
487 // only add new define if not already defined
488 if (!IterBool.second)
489 return;
491 NameAndAttributes &info = _undefines[IterBool.first->first()];
493 if (info.symbol == nullptr) {
494 // FIXME: This is trying to take care of module ASM like this:
496 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
498 // but is gross and its mother dresses it funny. Have the ASM parser give us
499 // more details for this type of situation so that we're not guessing so
500 // much.
502 // fill information structure
503 info.name = IterBool.first->first();
504 info.attributes =
505 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
506 info.isFunction = false;
507 info.symbol = nullptr;
509 // add to table of symbols
510 _symbols.push_back(info);
511 return;
514 if (info.isFunction)
515 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
516 else
517 addDefinedDataSymbol(info.name, info.symbol);
519 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
520 _symbols.back().attributes |= scope;
523 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
524 /// undefined list.
525 void LTOModule::addAsmGlobalSymbolUndef(StringRef name) {
526 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
528 _asm_undefines.push_back(IterBool.first->first());
530 // we already have the symbol
531 if (!IterBool.second)
532 return;
534 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
535 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
536 NameAndAttributes &info = IterBool.first->second;
537 info.name = IterBool.first->first();
538 info.attributes = attr;
539 info.isFunction = false;
540 info.symbol = nullptr;
543 /// Add a symbol which isn't defined just yet to a list to be resolved later.
544 void LTOModule::addPotentialUndefinedSymbol(ModuleSymbolTable::Symbol Sym,
545 bool isFunc) {
546 SmallString<64> name;
548 raw_svector_ostream OS(name);
549 SymTab.printSymbolName(OS, Sym);
550 name.c_str();
553 auto IterBool =
554 _undefines.insert(std::make_pair(name.str(), NameAndAttributes()));
556 // we already have the symbol
557 if (!IterBool.second)
558 return;
560 NameAndAttributes &info = IterBool.first->second;
562 info.name = IterBool.first->first();
564 const GlobalValue *decl = dyn_cast_if_present<GlobalValue *>(Sym);
566 if (decl->hasExternalWeakLinkage())
567 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
568 else
569 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
571 info.isFunction = isFunc;
572 info.symbol = decl;
575 void LTOModule::parseSymbols() {
576 for (auto Sym : SymTab.symbols()) {
577 auto *GV = dyn_cast_if_present<GlobalValue *>(Sym);
578 uint32_t Flags = SymTab.getSymbolFlags(Sym);
579 if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
580 continue;
582 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
584 if (!GV) {
585 SmallString<64> Buffer;
587 raw_svector_ostream OS(Buffer);
588 SymTab.printSymbolName(OS, Sym);
589 Buffer.c_str();
591 StringRef Name = Buffer;
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;
602 auto *F = dyn_cast<Function>(GV);
603 if (IsUndefined) {
604 addPotentialUndefinedSymbol(Sym, F != nullptr);
605 continue;
608 if (F) {
609 addDefinedFunctionSymbol(Sym);
610 continue;
613 if (isa<GlobalVariable>(GV)) {
614 addDefinedDataSymbol(Sym);
615 continue;
618 assert(isa<GlobalAlias>(GV));
620 if (isa<Function>(cast<GlobalAlias>(GV)->getAliasee()))
621 addDefinedFunctionSymbol(Sym);
622 else
623 addDefinedDataSymbol(Sym);
626 // make symbols for all undefines
627 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
628 e = _undefines.end(); u != e; ++u) {
629 // If this symbol also has a definition, then don't make an undefine because
630 // it is a tentative definition.
631 if (_defines.count(u->getKey())) continue;
632 NameAndAttributes info = u->getValue();
633 _symbols.push_back(info);
637 /// parseMetadata - Parse metadata from the module
638 void LTOModule::parseMetadata() {
639 raw_string_ostream OS(LinkerOpts);
641 // Linker Options
642 if (NamedMDNode *LinkerOptions =
643 getModule().getNamedMetadata("llvm.linker.options")) {
644 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
645 MDNode *MDOptions = LinkerOptions->getOperand(i);
646 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
647 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
648 OS << " " << MDOption->getString();
653 // Globals - we only need to do this for COFF.
654 const Triple TT(_target->getTargetTriple());
655 if (!TT.isOSBinFormatCOFF())
656 return;
657 Mangler M;
658 for (const NameAndAttributes &Sym : _symbols) {
659 if (!Sym.symbol)
660 continue;
661 emitLinkerFlagsForGlobalCOFF(OS, Sym.symbol, TT, M);
665 lto::InputFile *LTOModule::createInputFile(const void *buffer,
666 size_t buffer_size, const char *path,
667 std::string &outErr) {
668 StringRef Data((const char *)buffer, buffer_size);
669 MemoryBufferRef BufferRef(Data, path);
671 Expected<std::unique_ptr<lto::InputFile>> ObjOrErr =
672 lto::InputFile::create(BufferRef);
674 if (ObjOrErr)
675 return ObjOrErr->release();
677 outErr = std::string(path) +
678 ": Could not read LTO input file: " + toString(ObjOrErr.takeError());
679 return nullptr;
682 size_t LTOModule::getDependentLibraryCount(lto::InputFile *input) {
683 return input->getDependentLibraries().size();
686 const char *LTOModule::getDependentLibrary(lto::InputFile *input, size_t index,
687 size_t *size) {
688 StringRef S = input->getDependentLibraries()[index];
689 *size = S.size();
690 return S.data();
693 Expected<uint32_t> LTOModule::getMachOCPUType() const {
694 return MachO::getCPUType(Triple(Mod->getTargetTriple()));
697 Expected<uint32_t> LTOModule::getMachOCPUSubType() const {
698 return MachO::getCPUSubType(Triple(Mod->getTargetTriple()));
701 bool LTOModule::hasCtorDtor() const {
702 for (auto Sym : SymTab.symbols()) {
703 if (auto *GV = dyn_cast_if_present<GlobalValue *>(Sym)) {
704 StringRef Name = GV->getName();
705 if (Name.consume_front("llvm.global_")) {
706 if (Name == "ctors" || Name == "dtors")
707 return true;
711 return false;