707 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements the Link Time Optimization library. This library is10// intended to be used by linker to optimize code at link time.11//12//===----------------------------------------------------------------------===//13 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/MCSection.h"25#include "llvm/MC/MCSymbol.h"26#include "llvm/MC/TargetRegistry.h"27#include "llvm/Object/IRObjectFile.h"28#include "llvm/Object/MachO.h"29#include "llvm/Object/ObjectFile.h"30#include "llvm/Support/FileSystem.h"31#include "llvm/Support/MemoryBuffer.h"32#include "llvm/Support/SourceMgr.h"33#include "llvm/Target/TargetLoweringObjectFile.h"34#include "llvm/TargetParser/Host.h"35#include "llvm/TargetParser/SubtargetFeature.h"36#include "llvm/TargetParser/Triple.h"37#include "llvm/Transforms/Utils/GlobalStatus.h"38#include <system_error>39using namespace llvm;40using namespace llvm::object;41 42LTOModule::LTOModule(std::unique_ptr<Module> M, MemoryBufferRef MBRef,43 llvm::TargetMachine *TM)44 : Mod(std::move(M)), MBRef(MBRef), _target(TM) {45 assert(_target && "target machine is null");46 SymTab.addModule(Mod.get());47}48 49LTOModule::~LTOModule() = default;50 51/// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM52/// bitcode.53bool LTOModule::isBitcodeFile(const void *Mem, size_t Length) {54 Expected<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(55 MemoryBufferRef(StringRef((const char *)Mem, Length), "<mem>"));56 return !errorToBool(BCData.takeError());57}58 59bool LTOModule::isBitcodeFile(StringRef Path) {60 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =61 MemoryBuffer::getFile(Path);62 if (!BufferOrErr)63 return false;64 65 Expected<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(66 BufferOrErr.get()->getMemBufferRef());67 return !errorToBool(BCData.takeError());68}69 70bool LTOModule::isThinLTO() {71 Expected<BitcodeLTOInfo> Result = getBitcodeLTOInfo(MBRef);72 if (!Result) {73 logAllUnhandledErrors(Result.takeError(), errs());74 return false;75 }76 return Result->IsThinLTO;77}78 79bool LTOModule::isBitcodeForTarget(MemoryBuffer *Buffer,80 StringRef TriplePrefix) {81 Expected<MemoryBufferRef> BCOrErr =82 IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());83 if (errorToBool(BCOrErr.takeError()))84 return false;85 LLVMContext Context;86 ErrorOr<std::string> TripleOrErr =87 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(*BCOrErr));88 if (!TripleOrErr)89 return false;90 return StringRef(*TripleOrErr).starts_with(TriplePrefix);91}92 93std::string LTOModule::getProducerString(MemoryBuffer *Buffer) {94 Expected<MemoryBufferRef> BCOrErr =95 IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());96 if (errorToBool(BCOrErr.takeError()))97 return "";98 LLVMContext Context;99 ErrorOr<std::string> ProducerOrErr = expectedToErrorOrAndEmitErrors(100 Context, getBitcodeProducerString(*BCOrErr));101 if (!ProducerOrErr)102 return "";103 return *ProducerOrErr;104}105 106ErrorOr<std::unique_ptr<LTOModule>>107LTOModule::createFromFile(LLVMContext &Context, StringRef path,108 const TargetOptions &options) {109 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =110 MemoryBuffer::getFile(path);111 if (std::error_code EC = BufferOrErr.getError()) {112 Context.emitError(EC.message());113 return EC;114 }115 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());116 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,117 /* ShouldBeLazy*/ false);118}119 120ErrorOr<std::unique_ptr<LTOModule>>121LTOModule::createFromOpenFile(LLVMContext &Context, int fd, StringRef path,122 size_t size, const TargetOptions &options) {123 return createFromOpenFileSlice(Context, fd, path, size, 0, options);124}125 126ErrorOr<std::unique_ptr<LTOModule>>127LTOModule::createFromOpenFileSlice(LLVMContext &Context, int fd, StringRef path,128 size_t map_size, off_t offset,129 const TargetOptions &options) {130 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =131 MemoryBuffer::getOpenFileSlice(sys::fs::convertFDToNativeFile(fd), path,132 map_size, offset);133 if (std::error_code EC = BufferOrErr.getError()) {134 Context.emitError(EC.message());135 return EC;136 }137 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());138 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,139 /* ShouldBeLazy */ false);140}141 142ErrorOr<std::unique_ptr<LTOModule>>143LTOModule::createFromBuffer(LLVMContext &Context, const void *mem,144 size_t length, const TargetOptions &options,145 StringRef path) {146 StringRef Data((const char *)mem, length);147 MemoryBufferRef Buffer(Data, path);148 return makeLTOModule(Buffer, options, Context, /* ShouldBeLazy */ false);149}150 151ErrorOr<std::unique_ptr<LTOModule>>152LTOModule::createInLocalContext(std::unique_ptr<LLVMContext> Context,153 const void *mem, size_t length,154 const TargetOptions &options, StringRef path) {155 StringRef Data((const char *)mem, length);156 MemoryBufferRef Buffer(Data, path);157 // If we own a context, we know this is being used only for symbol extraction,158 // not linking. Be lazy in that case.159 ErrorOr<std::unique_ptr<LTOModule>> Ret =160 makeLTOModule(Buffer, options, *Context, /* ShouldBeLazy */ true);161 if (Ret)162 (*Ret)->OwnedContext = std::move(Context);163 return Ret;164}165 166static ErrorOr<std::unique_ptr<Module>>167parseBitcodeFileImpl(MemoryBufferRef Buffer, LLVMContext &Context,168 bool ShouldBeLazy) {169 // Find the buffer.170 Expected<MemoryBufferRef> MBOrErr =171 IRObjectFile::findBitcodeInMemBuffer(Buffer);172 if (Error E = MBOrErr.takeError()) {173 std::error_code EC = errorToErrorCode(std::move(E));174 Context.emitError(EC.message());175 return EC;176 }177 178 if (!ShouldBeLazy) {179 // Parse the full file.180 return expectedToErrorOrAndEmitErrors(Context,181 parseBitcodeFile(*MBOrErr, Context));182 }183 184 // Parse lazily.185 return expectedToErrorOrAndEmitErrors(186 Context,187 getLazyBitcodeModule(*MBOrErr, Context, true /*ShouldLazyLoadMetadata*/));188}189 190ErrorOr<std::unique_ptr<LTOModule>>191LTOModule::makeLTOModule(MemoryBufferRef Buffer, const TargetOptions &options,192 LLVMContext &Context, bool ShouldBeLazy) {193 ErrorOr<std::unique_ptr<Module>> MOrErr =194 parseBitcodeFileImpl(Buffer, Context, ShouldBeLazy);195 if (std::error_code EC = MOrErr.getError())196 return EC;197 std::unique_ptr<Module> &M = *MOrErr;198 199 llvm::Triple Triple = M->getTargetTriple();200 if (Triple.empty())201 Triple = llvm::Triple(sys::getDefaultTargetTriple());202 203 // find machine architecture for this module204 std::string errMsg;205 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);206 if (!march) {207 Context.emitError(errMsg);208 return make_error_code(object::object_error::arch_not_found);209 }210 211 // construct LTOModule, hand over ownership of module and target212 SubtargetFeatures Features;213 Features.getDefaultSubtargetFeatures(Triple);214 std::string FeatureStr = Features.getString();215 // Set a default CPU for Darwin triples.216 std::string CPU;217 if (Triple.isOSDarwin()) {218 if (Triple.getArch() == llvm::Triple::x86_64)219 CPU = "core2";220 else if (Triple.getArch() == llvm::Triple::x86)221 CPU = "yonah";222 else if (Triple.isArm64e())223 CPU = "apple-a12";224 else if (Triple.getArch() == llvm::Triple::aarch64 ||225 Triple.getArch() == llvm::Triple::aarch64_32)226 CPU = "cyclone";227 }228 229 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr,230 options, std::nullopt);231 232 std::unique_ptr<LTOModule> Ret(new LTOModule(std::move(M), Buffer, target));233 Ret->parseSymbols();234 Ret->parseMetadata();235 236 return std::move(Ret);237}238 239/// Create a MemoryBuffer from a memory range with an optional name.240std::unique_ptr<MemoryBuffer>241LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {242 const char *startPtr = (const char*)mem;243 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);244}245 246/// objcClassNameFromExpression - Get string that the data pointer points to.247bool248LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {249 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {250 Constant *op = ce->getOperand(0);251 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {252 Constant *cn = gvn->getInitializer();253 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {254 if (ca->isCString()) {255 name = (".objc_class_name_" + ca->getAsCString()).str();256 return true;257 }258 }259 }260 }261 return false;262}263 264/// addObjCClass - Parse i386/ppc ObjC class data structure.265void LTOModule::addObjCClass(const GlobalVariable *clgv) {266 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());267 if (!c) return;268 269 // second slot in __OBJC,__class is pointer to superclass name270 std::string superclassName;271 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {272 auto IterBool = _undefines.try_emplace(superclassName);273 if (IterBool.second) {274 NameAndAttributes &info = IterBool.first->second;275 info.name = IterBool.first->first();276 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;277 info.isFunction = false;278 info.symbol = clgv;279 }280 }281 282 // third slot in __OBJC,__class is pointer to class name283 std::string className;284 if (objcClassNameFromExpression(c->getOperand(2), className)) {285 auto Iter = _defines.insert(className).first;286 287 NameAndAttributes info;288 info.name = Iter->first();289 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |290 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;291 info.isFunction = false;292 info.symbol = clgv;293 _symbols.push_back(info);294 }295}296 297/// addObjCCategory - Parse i386/ppc ObjC category data structure.298void LTOModule::addObjCCategory(const GlobalVariable *clgv) {299 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());300 if (!c) return;301 302 // second slot in __OBJC,__category is pointer to target class name303 std::string targetclassName;304 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))305 return;306 307 auto IterBool = _undefines.try_emplace(targetclassName);308 309 if (!IterBool.second)310 return;311 312 NameAndAttributes &info = IterBool.first->second;313 info.name = IterBool.first->first();314 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;315 info.isFunction = false;316 info.symbol = clgv;317}318 319/// addObjCClassRef - Parse i386/ppc ObjC class list data structure.320void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {321 std::string targetclassName;322 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))323 return;324 325 auto IterBool = _undefines.try_emplace(targetclassName);326 327 if (!IterBool.second)328 return;329 330 NameAndAttributes &info = IterBool.first->second;331 info.name = IterBool.first->first();332 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;333 info.isFunction = false;334 info.symbol = clgv;335}336 337void LTOModule::addDefinedDataSymbol(ModuleSymbolTable::Symbol Sym) {338 SmallString<64> Buffer;339 {340 raw_svector_ostream OS(Buffer);341 SymTab.printSymbolName(OS, Sym);342 Buffer.c_str();343 }344 345 const GlobalValue *V = cast<GlobalValue *>(Sym);346 addDefinedDataSymbol(Buffer, V);347}348 349void LTOModule::addDefinedDataSymbol(StringRef Name, const GlobalValue *v) {350 // Add to list of defined symbols.351 addDefinedSymbol(Name, v, false);352 353 if (!v->hasSection() /* || !isTargetDarwin */)354 return;355 356 // Special case i386/ppc ObjC data structures in magic sections:357 // The issue is that the old ObjC object format did some strange358 // contortions to avoid real linker symbols. For instance, the359 // ObjC class data structure is allocated statically in the executable360 // that defines that class. That data structures contains a pointer to361 // its superclass. But instead of just initializing that part of the362 // struct to the address of its superclass, and letting the static and363 // dynamic linkers do the rest, the runtime works by having that field364 // instead point to a C-string that is the name of the superclass.365 // At runtime the objc initialization updates that pointer and sets366 // it to point to the actual super class. As far as the linker367 // knows it is just a pointer to a string. But then someone wanted the368 // linker to issue errors at build time if the superclass was not found.369 // So they figured out a way in mach-o object format to use an absolute370 // symbols (.objc_class_name_Foo = 0) and a floating reference371 // (.reference .objc_class_name_Bar) to cause the linker into erroring when372 // a class was missing.373 // The following synthesizes the implicit .objc_* symbols for the linker374 // from the ObjC data structures generated by the front end.375 376 // special case if this data blob is an ObjC class definition377 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(v)) {378 StringRef Section = GV->getSection();379 if (Section.starts_with("__OBJC,__class,")) {380 addObjCClass(GV);381 }382 383 // special case if this data blob is an ObjC category definition384 else if (Section.starts_with("__OBJC,__category,")) {385 addObjCCategory(GV);386 }387 388 // special case if this data blob is the list of referenced classes389 else if (Section.starts_with("__OBJC,__cls_refs,")) {390 addObjCClassRef(GV);391 }392 }393}394 395void LTOModule::addDefinedFunctionSymbol(ModuleSymbolTable::Symbol Sym) {396 SmallString<64> Buffer;397 {398 raw_svector_ostream OS(Buffer);399 SymTab.printSymbolName(OS, Sym);400 Buffer.c_str();401 }402 403 auto *GV = cast<GlobalValue *>(Sym);404 assert((isa<Function>(GV) ||405 (isa<GlobalAlias>(GV) &&406 isa<Function>(cast<GlobalAlias>(GV)->getAliasee()))) &&407 "Not function or function alias");408 409 addDefinedFunctionSymbol(Buffer, GV);410}411 412void LTOModule::addDefinedFunctionSymbol(StringRef Name, const GlobalValue *F) {413 // add to list of defined symbols414 addDefinedSymbol(Name, F, true);415}416 417void LTOModule::addDefinedSymbol(StringRef Name, const GlobalValue *def,418 bool isFunction) {419 uint32_t attr = 0;420 if (auto *gv = dyn_cast<GlobalVariable>(def))421 attr = Log2(gv->getAlign().valueOrOne());422 else if (auto *f = dyn_cast<Function>(def))423 attr = Log2(f->getAlign().valueOrOne());424 425 // set permissions part426 if (isFunction) {427 attr |= LTO_SYMBOL_PERMISSIONS_CODE;428 } else {429 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);430 if (gv && gv->isConstant())431 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;432 else433 attr |= LTO_SYMBOL_PERMISSIONS_DATA;434 }435 436 // set definition part437 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())438 attr |= LTO_SYMBOL_DEFINITION_WEAK;439 else if (def->hasCommonLinkage())440 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;441 else442 attr |= LTO_SYMBOL_DEFINITION_REGULAR;443 444 // set scope part445 if (def->hasLocalLinkage())446 // Ignore visibility if linkage is local.447 attr |= LTO_SYMBOL_SCOPE_INTERNAL;448 else if (def->hasHiddenVisibility())449 attr |= LTO_SYMBOL_SCOPE_HIDDEN;450 else if (def->hasProtectedVisibility())451 attr |= LTO_SYMBOL_SCOPE_PROTECTED;452 else if (def->canBeOmittedFromSymbolTable())453 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;454 else455 attr |= LTO_SYMBOL_SCOPE_DEFAULT;456 457 if (def->hasComdat())458 attr |= LTO_SYMBOL_COMDAT;459 460 if (isa<GlobalAlias>(def))461 attr |= LTO_SYMBOL_ALIAS;462 463 auto Iter = _defines.insert(Name).first;464 465 // fill information structure466 NameAndAttributes info;467 StringRef NameRef = Iter->first();468 info.name = NameRef;469 assert(NameRef.data()[NameRef.size()] == '\0');470 info.attributes = attr;471 info.isFunction = isFunction;472 info.symbol = def;473 474 // add to table of symbols475 _symbols.push_back(info);476}477 478/// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the479/// defined list.480void LTOModule::addAsmGlobalSymbol(StringRef name,481 lto_symbol_attributes scope) {482 auto IterBool = _defines.insert(name);483 484 // only add new define if not already defined485 if (!IterBool.second)486 return;487 488 NameAndAttributes &info = _undefines[IterBool.first->first()];489 490 if (info.symbol == nullptr) {491 // FIXME: This is trying to take care of module ASM like this:492 //493 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"494 //495 // but is gross and its mother dresses it funny. Have the ASM parser give us496 // more details for this type of situation so that we're not guessing so497 // much.498 499 // fill information structure500 info.name = IterBool.first->first();501 info.attributes =502 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;503 info.isFunction = false;504 info.symbol = nullptr;505 506 // add to table of symbols507 _symbols.push_back(info);508 return;509 }510 511 if (info.isFunction)512 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));513 else514 addDefinedDataSymbol(info.name, info.symbol);515 516 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;517 _symbols.back().attributes |= scope;518}519 520/// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the521/// undefined list.522void LTOModule::addAsmGlobalSymbolUndef(StringRef name) {523 auto IterBool = _undefines.try_emplace(name);524 525 _asm_undefines.push_back(IterBool.first->first());526 527 // we already have the symbol528 if (!IterBool.second)529 return;530 531 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;532 attr |= LTO_SYMBOL_SCOPE_DEFAULT;533 NameAndAttributes &info = IterBool.first->second;534 info.name = IterBool.first->first();535 info.attributes = attr;536 info.isFunction = false;537 info.symbol = nullptr;538}539 540/// Add a symbol which isn't defined just yet to a list to be resolved later.541void LTOModule::addPotentialUndefinedSymbol(ModuleSymbolTable::Symbol Sym,542 bool isFunc) {543 SmallString<64> name;544 {545 raw_svector_ostream OS(name);546 SymTab.printSymbolName(OS, Sym);547 name.c_str();548 }549 550 auto IterBool = _undefines.try_emplace(name.str());551 552 // we already have the symbol553 if (!IterBool.second)554 return;555 556 NameAndAttributes &info = IterBool.first->second;557 558 info.name = IterBool.first->first();559 560 const GlobalValue *decl = dyn_cast_if_present<GlobalValue *>(Sym);561 562 if (decl->hasExternalWeakLinkage())563 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;564 else565 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;566 567 info.isFunction = isFunc;568 info.symbol = decl;569}570 571void LTOModule::parseSymbols() {572 for (auto Sym : SymTab.symbols()) {573 auto *GV = dyn_cast_if_present<GlobalValue *>(Sym);574 uint32_t Flags = SymTab.getSymbolFlags(Sym);575 if (Flags & object::BasicSymbolRef::SF_FormatSpecific)576 continue;577 578 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;579 580 if (!GV) {581 SmallString<64> Buffer;582 {583 raw_svector_ostream OS(Buffer);584 SymTab.printSymbolName(OS, Sym);585 Buffer.c_str();586 }587 StringRef Name = Buffer;588 589 if (IsUndefined)590 addAsmGlobalSymbolUndef(Name);591 else if (Flags & object::BasicSymbolRef::SF_Global)592 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);593 else594 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);595 continue;596 }597 598 auto *F = dyn_cast<Function>(GV);599 if (IsUndefined) {600 addPotentialUndefinedSymbol(Sym, F != nullptr);601 continue;602 }603 604 if (F) {605 addDefinedFunctionSymbol(Sym);606 continue;607 }608 609 if (isa<GlobalVariable>(GV)) {610 addDefinedDataSymbol(Sym);611 continue;612 }613 614 assert(isa<GlobalAlias>(GV));615 616 if (isa<Function>(cast<GlobalAlias>(GV)->getAliasee()))617 addDefinedFunctionSymbol(Sym);618 else619 addDefinedDataSymbol(Sym);620 }621 622 // make symbols for all undefines623 for (const auto &[Key, Value] : _undefines) {624 // If this symbol also has a definition, then don't make an undefine because625 // it is a tentative definition.626 if (!_defines.contains(Key))627 _symbols.push_back(Value);628 }629}630 631/// parseMetadata - Parse metadata from the module632void LTOModule::parseMetadata() {633 raw_string_ostream OS(LinkerOpts);634 635 // Linker Options636 if (NamedMDNode *LinkerOptions =637 getModule().getNamedMetadata("llvm.linker.options")) {638 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {639 MDNode *MDOptions = LinkerOptions->getOperand(i);640 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {641 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));642 OS << " " << MDOption->getString();643 }644 }645 }646 647 // Globals - we only need to do this for COFF.648 const Triple TT(_target->getTargetTriple());649 if (!TT.isOSBinFormatCOFF())650 return;651 Mangler M;652 for (const NameAndAttributes &Sym : _symbols) {653 if (!Sym.symbol)654 continue;655 emitLinkerFlagsForGlobalCOFF(OS, Sym.symbol, TT, M);656 }657}658 659lto::InputFile *LTOModule::createInputFile(const void *buffer,660 size_t buffer_size, const char *path,661 std::string &outErr) {662 StringRef Data((const char *)buffer, buffer_size);663 MemoryBufferRef BufferRef(Data, path);664 665 Expected<std::unique_ptr<lto::InputFile>> ObjOrErr =666 lto::InputFile::create(BufferRef);667 668 if (ObjOrErr)669 return ObjOrErr->release();670 671 outErr = std::string(path) +672 ": Could not read LTO input file: " + toString(ObjOrErr.takeError());673 return nullptr;674}675 676size_t LTOModule::getDependentLibraryCount(lto::InputFile *input) {677 return input->getDependentLibraries().size();678}679 680const char *LTOModule::getDependentLibrary(lto::InputFile *input, size_t index,681 size_t *size) {682 StringRef S = input->getDependentLibraries()[index];683 *size = S.size();684 return S.data();685}686 687Expected<uint32_t> LTOModule::getMachOCPUType() const {688 return MachO::getCPUType(Mod->getTargetTriple());689}690 691Expected<uint32_t> LTOModule::getMachOCPUSubType() const {692 return MachO::getCPUSubType(Mod->getTargetTriple());693}694 695bool LTOModule::hasCtorDtor() const {696 for (auto Sym : SymTab.symbols()) {697 if (auto *GV = dyn_cast_if_present<GlobalValue *>(Sym)) {698 StringRef Name = GV->getName();699 if (Name.consume_front("llvm.global_")) {700 if (Name == "ctors" || Name == "dtors")701 return true;702 }703 }704 }705 return false;706}707