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. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/LTO/legacy/LTOModule.h" 15 #include "llvm/ADT/Triple.h" 16 #include "llvm/Bitcode/BitcodeReader.h" 17 #include "llvm/CodeGen/TargetSubtargetInfo.h" 18 #include "llvm/IR/Constants.h" 19 #include "llvm/IR/LLVMContext.h" 20 #include "llvm/IR/Mangler.h" 21 #include "llvm/IR/Metadata.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/MC/MCExpr.h" 24 #include "llvm/MC/MCInst.h" 25 #include "llvm/MC/MCParser/MCAsmParser.h" 26 #include "llvm/MC/MCSection.h" 27 #include "llvm/MC/MCSubtargetInfo.h" 28 #include "llvm/MC/MCSymbol.h" 29 #include "llvm/MC/SubtargetFeature.h" 30 #include "llvm/Object/IRObjectFile.h" 31 #include "llvm/Object/MachO.h" 32 #include "llvm/Object/ObjectFile.h" 33 #include "llvm/Support/FileSystem.h" 34 #include "llvm/Support/Host.h" 35 #include "llvm/Support/MemoryBuffer.h" 36 #include "llvm/Support/Path.h" 37 #include "llvm/Support/SourceMgr.h" 38 #include "llvm/Support/TargetRegistry.h" 39 #include "llvm/Support/TargetSelect.h" 40 #include "llvm/Target/TargetLoweringObjectFile.h" 41 #include "llvm/Transforms/Utils/GlobalStatus.h" 42 #include <system_error> 43 using namespace llvm; 44 using namespace llvm::object; 45 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()); 51 } 52 53 LTOModule::~LTOModule() {} 54 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()); 61 } 62 63 bool LTOModule::isBitcodeFile(StringRef Path) { 64 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 65 MemoryBuffer::getFile(Path); 66 if (!BufferOrErr) 67 return false; 68 69 Expected<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer( 70 BufferOrErr.get()->getMemBufferRef()); 71 return !errorToBool(BCData.takeError()); 72 } 73 74 bool LTOModule::isThinLTO() { 75 Expected<BitcodeLTOInfo> Result = getBitcodeLTOInfo(MBRef); 76 if (!Result) { 77 logAllUnhandledErrors(Result.takeError(), errs()); 78 return false; 79 } 80 return Result->IsThinLTO; 81 } 82 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).startswith(TriplePrefix); 95 } 96 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; 108 } 109 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; 118 } 119 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get()); 120 return makeLTOModule(Buffer->getMemBufferRef(), options, Context, 121 /* ShouldBeLazy*/ false); 122 } 123 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); 128 } 129 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; 140 } 141 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get()); 142 return makeLTOModule(Buffer->getMemBufferRef(), options, Context, 143 /* ShouldBeLazy */ false); 144 } 145 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); 153 } 154 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; 168 } 169 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; 180 } 181 182 if (!ShouldBeLazy) { 183 // Parse the full file. 184 return expectedToErrorOrAndEmitErrors(Context, 185 parseBitcodeFile(*MBOrErr, Context)); 186 } 187 188 // Parse lazily. 189 return expectedToErrorOrAndEmitErrors( 190 Context, 191 getLazyBitcodeModule(*MBOrErr, Context, true /*ShouldLazyLoadMetadata*/)); 192 } 193 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; 202 203 std::string TripleStr = M->getTargetTriple(); 204 if (TripleStr.empty()) 205 TripleStr = sys::getDefaultTargetTriple(); 206 llvm::Triple Triple(TripleStr); 207 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); 213 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.getArch() == llvm::Triple::aarch64 || 226 Triple.getArch() == llvm::Triple::aarch64_32) 227 CPU = "cyclone"; 228 } 229 230 TargetMachine *target = 231 march->createTargetMachine(TripleStr, CPU, FeatureStr, options, None); 232 233 std::unique_ptr<LTOModule> Ret(new LTOModule(std::move(M), Buffer, target)); 234 Ret->parseSymbols(); 235 Ret->parseMetadata(); 236 237 return std::move(Ret); 238 } 239 240 /// Create a MemoryBuffer from a memory range with an optional name. 241 std::unique_ptr<MemoryBuffer> 242 LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) { 243 const char *startPtr = (const char*)mem; 244 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false); 245 } 246 247 /// objcClassNameFromExpression - Get string that the data pointer points to. 248 bool 249 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) { 250 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) { 251 Constant *op = ce->getOperand(0); 252 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) { 253 Constant *cn = gvn->getInitializer(); 254 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) { 255 if (ca->isCString()) { 256 name = (".objc_class_name_" + ca->getAsCString()).str(); 257 return true; 258 } 259 } 260 } 261 } 262 return false; 263 } 264 265 /// addObjCClass - Parse i386/ppc ObjC class data structure. 266 void LTOModule::addObjCClass(const GlobalVariable *clgv) { 267 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer()); 268 if (!c) return; 269 270 // second slot in __OBJC,__class is pointer to superclass name 271 std::string superclassName; 272 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) { 273 auto IterBool = 274 _undefines.insert(std::make_pair(superclassName, NameAndAttributes())); 275 if (IterBool.second) { 276 NameAndAttributes &info = IterBool.first->second; 277 info.name = IterBool.first->first(); 278 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 279 info.isFunction = false; 280 info.symbol = clgv; 281 } 282 } 283 284 // third slot in __OBJC,__class is pointer to class name 285 std::string className; 286 if (objcClassNameFromExpression(c->getOperand(2), className)) { 287 auto Iter = _defines.insert(className).first; 288 289 NameAndAttributes info; 290 info.name = Iter->first(); 291 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA | 292 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT; 293 info.isFunction = false; 294 info.symbol = clgv; 295 _symbols.push_back(info); 296 } 297 } 298 299 /// addObjCCategory - Parse i386/ppc ObjC category data structure. 300 void LTOModule::addObjCCategory(const GlobalVariable *clgv) { 301 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer()); 302 if (!c) return; 303 304 // second slot in __OBJC,__category is pointer to target class name 305 std::string targetclassName; 306 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName)) 307 return; 308 309 auto IterBool = 310 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes())); 311 312 if (!IterBool.second) 313 return; 314 315 NameAndAttributes &info = IterBool.first->second; 316 info.name = IterBool.first->first(); 317 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 318 info.isFunction = false; 319 info.symbol = clgv; 320 } 321 322 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure. 323 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) { 324 std::string targetclassName; 325 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) 326 return; 327 328 auto IterBool = 329 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes())); 330 331 if (!IterBool.second) 332 return; 333 334 NameAndAttributes &info = IterBool.first->second; 335 info.name = IterBool.first->first(); 336 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 337 info.isFunction = false; 338 info.symbol = clgv; 339 } 340 341 void LTOModule::addDefinedDataSymbol(ModuleSymbolTable::Symbol Sym) { 342 SmallString<64> Buffer; 343 { 344 raw_svector_ostream OS(Buffer); 345 SymTab.printSymbolName(OS, Sym); 346 Buffer.c_str(); 347 } 348 349 const GlobalValue *V = Sym.get<GlobalValue *>(); 350 addDefinedDataSymbol(Buffer, V); 351 } 352 353 void LTOModule::addDefinedDataSymbol(StringRef Name, const GlobalValue *v) { 354 // Add to list of defined symbols. 355 addDefinedSymbol(Name, v, false); 356 357 if (!v->hasSection() /* || !isTargetDarwin */) 358 return; 359 360 // Special case i386/ppc ObjC data structures in magic sections: 361 // The issue is that the old ObjC object format did some strange 362 // contortions to avoid real linker symbols. For instance, the 363 // ObjC class data structure is allocated statically in the executable 364 // that defines that class. That data structures contains a pointer to 365 // its superclass. But instead of just initializing that part of the 366 // struct to the address of its superclass, and letting the static and 367 // dynamic linkers do the rest, the runtime works by having that field 368 // instead point to a C-string that is the name of the superclass. 369 // At runtime the objc initialization updates that pointer and sets 370 // it to point to the actual super class. As far as the linker 371 // knows it is just a pointer to a string. But then someone wanted the 372 // linker to issue errors at build time if the superclass was not found. 373 // So they figured out a way in mach-o object format to use an absolute 374 // symbols (.objc_class_name_Foo = 0) and a floating reference 375 // (.reference .objc_class_name_Bar) to cause the linker into erroring when 376 // a class was missing. 377 // The following synthesizes the implicit .objc_* symbols for the linker 378 // from the ObjC data structures generated by the front end. 379 380 // special case if this data blob is an ObjC class definition 381 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(v)) { 382 StringRef Section = GV->getSection(); 383 if (Section.startswith("__OBJC,__class,")) { 384 addObjCClass(GV); 385 } 386 387 // special case if this data blob is an ObjC category definition 388 else if (Section.startswith("__OBJC,__category,")) { 389 addObjCCategory(GV); 390 } 391 392 // special case if this data blob is the list of referenced classes 393 else if (Section.startswith("__OBJC,__cls_refs,")) { 394 addObjCClassRef(GV); 395 } 396 } 397 } 398 399 void LTOModule::addDefinedFunctionSymbol(ModuleSymbolTable::Symbol Sym) { 400 SmallString<64> Buffer; 401 { 402 raw_svector_ostream OS(Buffer); 403 SymTab.printSymbolName(OS, Sym); 404 Buffer.c_str(); 405 } 406 407 const Function *F = cast<Function>(Sym.get<GlobalValue *>()); 408 addDefinedFunctionSymbol(Buffer, F); 409 } 410 411 void LTOModule::addDefinedFunctionSymbol(StringRef Name, const Function *F) { 412 // add to list of defined symbols 413 addDefinedSymbol(Name, F, true); 414 } 415 416 void LTOModule::addDefinedSymbol(StringRef Name, const GlobalValue *def, 417 bool isFunction) { 418 const GlobalObject *go = dyn_cast<GlobalObject>(def); 419 uint32_t attr = go ? Log2(go->getAlign().valueOrOne()) : 0; 420 421 // set permissions part 422 if (isFunction) { 423 attr |= LTO_SYMBOL_PERMISSIONS_CODE; 424 } else { 425 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def); 426 if (gv && gv->isConstant()) 427 attr |= LTO_SYMBOL_PERMISSIONS_RODATA; 428 else 429 attr |= LTO_SYMBOL_PERMISSIONS_DATA; 430 } 431 432 // set definition part 433 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage()) 434 attr |= LTO_SYMBOL_DEFINITION_WEAK; 435 else if (def->hasCommonLinkage()) 436 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE; 437 else 438 attr |= LTO_SYMBOL_DEFINITION_REGULAR; 439 440 // set scope part 441 if (def->hasLocalLinkage()) 442 // Ignore visibility if linkage is local. 443 attr |= LTO_SYMBOL_SCOPE_INTERNAL; 444 else if (def->hasHiddenVisibility()) 445 attr |= LTO_SYMBOL_SCOPE_HIDDEN; 446 else if (def->hasProtectedVisibility()) 447 attr |= LTO_SYMBOL_SCOPE_PROTECTED; 448 else if (def->canBeOmittedFromSymbolTable()) 449 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN; 450 else 451 attr |= LTO_SYMBOL_SCOPE_DEFAULT; 452 453 if (def->hasComdat()) 454 attr |= LTO_SYMBOL_COMDAT; 455 456 if (isa<GlobalAlias>(def)) 457 attr |= LTO_SYMBOL_ALIAS; 458 459 auto Iter = _defines.insert(Name).first; 460 461 // fill information structure 462 NameAndAttributes info; 463 StringRef NameRef = Iter->first(); 464 info.name = NameRef; 465 assert(NameRef.data()[NameRef.size()] == '\0'); 466 info.attributes = attr; 467 info.isFunction = isFunction; 468 info.symbol = def; 469 470 // add to table of symbols 471 _symbols.push_back(info); 472 } 473 474 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the 475 /// defined list. 476 void LTOModule::addAsmGlobalSymbol(StringRef name, 477 lto_symbol_attributes scope) { 478 auto IterBool = _defines.insert(name); 479 480 // only add new define if not already defined 481 if (!IterBool.second) 482 return; 483 484 NameAndAttributes &info = _undefines[IterBool.first->first()]; 485 486 if (info.symbol == nullptr) { 487 // FIXME: This is trying to take care of module ASM like this: 488 // 489 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0" 490 // 491 // but is gross and its mother dresses it funny. Have the ASM parser give us 492 // more details for this type of situation so that we're not guessing so 493 // much. 494 495 // fill information structure 496 info.name = IterBool.first->first(); 497 info.attributes = 498 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope; 499 info.isFunction = false; 500 info.symbol = nullptr; 501 502 // add to table of symbols 503 _symbols.push_back(info); 504 return; 505 } 506 507 if (info.isFunction) 508 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol)); 509 else 510 addDefinedDataSymbol(info.name, info.symbol); 511 512 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK; 513 _symbols.back().attributes |= scope; 514 } 515 516 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the 517 /// undefined list. 518 void LTOModule::addAsmGlobalSymbolUndef(StringRef name) { 519 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes())); 520 521 _asm_undefines.push_back(IterBool.first->first()); 522 523 // we already have the symbol 524 if (!IterBool.second) 525 return; 526 527 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED; 528 attr |= LTO_SYMBOL_SCOPE_DEFAULT; 529 NameAndAttributes &info = IterBool.first->second; 530 info.name = IterBool.first->first(); 531 info.attributes = attr; 532 info.isFunction = false; 533 info.symbol = nullptr; 534 } 535 536 /// Add a symbol which isn't defined just yet to a list to be resolved later. 537 void LTOModule::addPotentialUndefinedSymbol(ModuleSymbolTable::Symbol Sym, 538 bool isFunc) { 539 SmallString<64> name; 540 { 541 raw_svector_ostream OS(name); 542 SymTab.printSymbolName(OS, Sym); 543 name.c_str(); 544 } 545 546 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes())); 547 548 // we already have the symbol 549 if (!IterBool.second) 550 return; 551 552 NameAndAttributes &info = IterBool.first->second; 553 554 info.name = IterBool.first->first(); 555 556 const GlobalValue *decl = Sym.dyn_cast<GlobalValue *>(); 557 558 if (decl->hasExternalWeakLinkage()) 559 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF; 560 else 561 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 562 563 info.isFunction = isFunc; 564 info.symbol = decl; 565 } 566 567 void LTOModule::parseSymbols() { 568 for (auto Sym : SymTab.symbols()) { 569 auto *GV = Sym.dyn_cast<GlobalValue *>(); 570 uint32_t Flags = SymTab.getSymbolFlags(Sym); 571 if (Flags & object::BasicSymbolRef::SF_FormatSpecific) 572 continue; 573 574 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined; 575 576 if (!GV) { 577 SmallString<64> Buffer; 578 { 579 raw_svector_ostream OS(Buffer); 580 SymTab.printSymbolName(OS, Sym); 581 Buffer.c_str(); 582 } 583 StringRef Name(Buffer); 584 585 if (IsUndefined) 586 addAsmGlobalSymbolUndef(Name); 587 else if (Flags & object::BasicSymbolRef::SF_Global) 588 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT); 589 else 590 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL); 591 continue; 592 } 593 594 auto *F = dyn_cast<Function>(GV); 595 if (IsUndefined) { 596 addPotentialUndefinedSymbol(Sym, F != nullptr); 597 continue; 598 } 599 600 if (F) { 601 addDefinedFunctionSymbol(Sym); 602 continue; 603 } 604 605 if (isa<GlobalVariable>(GV)) { 606 addDefinedDataSymbol(Sym); 607 continue; 608 } 609 610 assert(isa<GlobalAlias>(GV)); 611 addDefinedDataSymbol(Sym); 612 } 613 614 // make symbols for all undefines 615 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(), 616 e = _undefines.end(); u != e; ++u) { 617 // If this symbol also has a definition, then don't make an undefine because 618 // it is a tentative definition. 619 if (_defines.count(u->getKey())) continue; 620 NameAndAttributes info = u->getValue(); 621 _symbols.push_back(info); 622 } 623 } 624 625 /// parseMetadata - Parse metadata from the module 626 void LTOModule::parseMetadata() { 627 raw_string_ostream OS(LinkerOpts); 628 629 // Linker Options 630 if (NamedMDNode *LinkerOptions = 631 getModule().getNamedMetadata("llvm.linker.options")) { 632 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 633 MDNode *MDOptions = LinkerOptions->getOperand(i); 634 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 635 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 636 OS << " " << MDOption->getString(); 637 } 638 } 639 } 640 641 // Globals - we only need to do this for COFF. 642 const Triple TT(_target->getTargetTriple()); 643 if (!TT.isOSBinFormatCOFF()) 644 return; 645 Mangler M; 646 for (const NameAndAttributes &Sym : _symbols) { 647 if (!Sym.symbol) 648 continue; 649 emitLinkerFlagsForGlobalCOFF(OS, Sym.symbol, TT, M); 650 } 651 } 652 653 lto::InputFile *LTOModule::createInputFile(const void *buffer, 654 size_t buffer_size, const char *path, 655 std::string &outErr) { 656 StringRef Data((const char *)buffer, buffer_size); 657 MemoryBufferRef BufferRef(Data, path); 658 659 Expected<std::unique_ptr<lto::InputFile>> ObjOrErr = 660 lto::InputFile::create(BufferRef); 661 662 if (ObjOrErr) 663 return ObjOrErr->release(); 664 665 outErr = std::string(path) + 666 ": Could not read LTO input file: " + toString(ObjOrErr.takeError()); 667 return nullptr; 668 } 669 670 size_t LTOModule::getDependentLibraryCount(lto::InputFile *input) { 671 return input->getDependentLibraries().size(); 672 } 673 674 const char *LTOModule::getDependentLibrary(lto::InputFile *input, size_t index, 675 size_t *size) { 676 StringRef S = input->getDependentLibraries()[index]; 677 *size = S.size(); 678 return S.data(); 679 } 680 681 Expected<uint32_t> LTOModule::getMachOCPUType() const { 682 return MachO::getCPUType(Triple(Mod->getTargetTriple())); 683 } 684 685 Expected<uint32_t> LTOModule::getMachOCPUSubType() const { 686 return MachO::getCPUSubType(Triple(Mod->getTargetTriple())); 687 } 688