1 //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a gold plugin for LLVM. It provides an LLVM implementation of the
11 // interface described in http://gcc.gnu.org/wiki/whopr/driver .
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/Linker/Linker.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Object/IRObjectFile.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/TargetSelect.h"
34 #include "llvm/Target/TargetLibraryInfo.h"
35 #include "llvm/Transforms/IPO.h"
36 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
37 #include "llvm/Transforms/Utils/GlobalStatus.h"
38 #include "llvm/Transforms/Utils/ModuleUtils.h"
39 #include "llvm/Transforms/Utils/ValueMapper.h"
41 #include <plugin-api.h>
42 #include <system_error>
46 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
47 // Precise and Debian Wheezy (binutils 2.23 is required)
56 std::vector<ld_plugin_symbol> syms;
60 static ld_plugin_status discard_message(int level, const char *format, ...) {
61 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
62 // callback in the transfer vector. This should never be called.
66 static ld_plugin_get_input_file get_input_file = nullptr;
67 static ld_plugin_release_input_file release_input_file = nullptr;
68 static ld_plugin_add_symbols add_symbols = nullptr;
69 static ld_plugin_get_symbols get_symbols = nullptr;
70 static ld_plugin_add_input_file add_input_file = nullptr;
71 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
72 static ld_plugin_get_view get_view = nullptr;
73 static ld_plugin_message message = discard_message;
74 static Reloc::Model RelocationModel = Reloc::Default;
75 static std::string output_name = "";
76 static std::list<claimed_file> Modules;
77 static std::vector<std::string> Cleanup;
78 static llvm::TargetOptions TargetOpts;
81 enum generate_bc { BC_NO, BC_ONLY, BC_SAVE_TEMPS };
82 static bool generate_api_file = false;
83 static generate_bc generate_bc_file = BC_NO;
84 static std::string obj_path;
85 static std::string extra_library_path;
86 static std::string triple;
87 static std::string mcpu;
88 // Additional options to pass into the code generator.
89 // Note: This array will contain all plugin options which are not claimed
90 // as plugin exclusive to pass to the code generator.
91 // For example, "generate-api-file" and "as"options are for the plugin
92 // use only and will not be passed.
93 static std::vector<const char *> extra;
95 static void process_plugin_option(const char* opt_)
99 llvm::StringRef opt = opt_;
101 if (opt == "generate-api-file") {
102 generate_api_file = true;
103 } else if (opt.startswith("mcpu=")) {
104 mcpu = opt.substr(strlen("mcpu="));
105 } else if (opt.startswith("extra-library-path=")) {
106 extra_library_path = opt.substr(strlen("extra_library_path="));
107 } else if (opt.startswith("mtriple=")) {
108 triple = opt.substr(strlen("mtriple="));
109 } else if (opt.startswith("obj-path=")) {
110 obj_path = opt.substr(strlen("obj-path="));
111 } else if (opt == "emit-llvm") {
112 generate_bc_file = BC_ONLY;
113 } else if (opt == "save-temps") {
114 generate_bc_file = BC_SAVE_TEMPS;
116 // Save this option to pass to the code generator.
117 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
120 extra.push_back("LLVMgold");
122 extra.push_back(opt_);
127 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
129 static ld_plugin_status all_symbols_read_hook(void);
130 static ld_plugin_status cleanup_hook(void);
132 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
133 ld_plugin_status onload(ld_plugin_tv *tv) {
134 InitializeAllTargetInfos();
135 InitializeAllTargets();
136 InitializeAllTargetMCs();
137 InitializeAllAsmParsers();
138 InitializeAllAsmPrinters();
140 // We're given a pointer to the first transfer vector. We read through them
141 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
142 // contain pointers to functions that we need to call to register our own
143 // hooks. The others are addresses of functions we can use to call into gold
146 bool registeredClaimFile = false;
147 bool RegisteredAllSymbolsRead = false;
149 for (; tv->tv_tag != LDPT_NULL; ++tv) {
150 switch (tv->tv_tag) {
151 case LDPT_OUTPUT_NAME:
152 output_name = tv->tv_u.tv_string;
154 case LDPT_LINKER_OUTPUT:
155 switch (tv->tv_u.tv_val) {
157 case LDPO_DYN: // .so
158 case LDPO_PIE: // position independent executable
159 RelocationModel = Reloc::PIC_;
161 case LDPO_EXEC: // .exe
162 RelocationModel = Reloc::Static;
165 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
170 options::process_plugin_option(tv->tv_u.tv_string);
172 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
173 ld_plugin_register_claim_file callback;
174 callback = tv->tv_u.tv_register_claim_file;
176 if (callback(claim_file_hook) != LDPS_OK)
179 registeredClaimFile = true;
181 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
182 ld_plugin_register_all_symbols_read callback;
183 callback = tv->tv_u.tv_register_all_symbols_read;
185 if (callback(all_symbols_read_hook) != LDPS_OK)
188 RegisteredAllSymbolsRead = true;
190 case LDPT_REGISTER_CLEANUP_HOOK: {
191 ld_plugin_register_cleanup callback;
192 callback = tv->tv_u.tv_register_cleanup;
194 if (callback(cleanup_hook) != LDPS_OK)
197 case LDPT_GET_INPUT_FILE:
198 get_input_file = tv->tv_u.tv_get_input_file;
200 case LDPT_RELEASE_INPUT_FILE:
201 release_input_file = tv->tv_u.tv_release_input_file;
203 case LDPT_ADD_SYMBOLS:
204 add_symbols = tv->tv_u.tv_add_symbols;
206 case LDPT_GET_SYMBOLS_V2:
207 get_symbols = tv->tv_u.tv_get_symbols;
209 case LDPT_ADD_INPUT_FILE:
210 add_input_file = tv->tv_u.tv_add_input_file;
212 case LDPT_SET_EXTRA_LIBRARY_PATH:
213 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
216 get_view = tv->tv_u.tv_get_view;
219 message = tv->tv_u.tv_message;
226 if (!registeredClaimFile) {
227 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
231 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
235 if (!RegisteredAllSymbolsRead)
238 if (!get_input_file) {
239 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
242 if (!release_input_file) {
243 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
250 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
251 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
252 return GA->getBaseObject();
253 return cast<GlobalObject>(&GV);
256 /// Called by gold to see whether this file is one that our plugin can handle.
257 /// We'll try to open it and register all the symbols with add_symbol if
259 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
262 MemoryBufferRef BufferRef;
263 std::unique_ptr<MemoryBuffer> Buffer;
266 if (get_view(file->handle, &view) != LDPS_OK) {
267 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
270 BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
273 // Gold has found what might be IR part-way inside of a file, such as
276 offset = file->offset;
278 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
279 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
281 if (std::error_code EC = BufferOrErr.getError()) {
282 message(LDPL_ERROR, EC.message().c_str());
285 Buffer = std::move(BufferOrErr.get());
286 BufferRef = Buffer->getMemBufferRef();
289 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
290 object::IRObjectFile::createIRObjectFile(BufferRef, Context);
291 std::error_code EC = ObjOrErr.getError();
292 if (EC == BitcodeError::InvalidBitcodeSignature ||
293 EC == object::object_error::invalid_file_type ||
294 EC == object::object_error::bitcode_section_not_found)
300 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
301 EC.message().c_str());
304 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
306 Modules.resize(Modules.size() + 1);
307 claimed_file &cf = Modules.back();
309 cf.handle = file->handle;
311 for (auto &Sym : Obj->symbols()) {
312 uint32_t Symflags = Sym.getFlags();
313 if (!(Symflags & object::BasicSymbolRef::SF_Global))
316 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
319 cf.syms.push_back(ld_plugin_symbol());
320 ld_plugin_symbol &sym = cf.syms.back();
321 sym.version = nullptr;
323 SmallString<64> Name;
325 raw_svector_ostream OS(Name);
328 sym.name = strdup(Name.c_str());
330 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
332 sym.visibility = LDPV_DEFAULT;
334 switch (GV->getVisibility()) {
335 case GlobalValue::DefaultVisibility:
336 sym.visibility = LDPV_DEFAULT;
338 case GlobalValue::HiddenVisibility:
339 sym.visibility = LDPV_HIDDEN;
341 case GlobalValue::ProtectedVisibility:
342 sym.visibility = LDPV_PROTECTED;
347 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
348 sym.def = LDPK_UNDEF;
349 if (GV && GV->hasExternalWeakLinkage())
350 sym.def = LDPK_WEAKUNDEF;
354 assert(!GV->hasExternalWeakLinkage() &&
355 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
356 if (GV->hasCommonLinkage())
357 sym.def = LDPK_COMMON;
358 else if (GV->isWeakForLinker())
359 sym.def = LDPK_WEAKDEF;
364 sym.comdat_key = nullptr;
366 const GlobalObject *Base = getBaseObject(*GV);
368 message(LDPL_FATAL, "Unable to determine comdat of alias!");
369 const Comdat *C = Base->getComdat();
371 sym.comdat_key = strdup(C->getName().str().c_str());
372 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
373 sym.comdat_key = strdup(sym.name);
376 sym.resolution = LDPR_UNKNOWN;
379 if (!cf.syms.empty()) {
380 if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
381 message(LDPL_ERROR, "Unable to add symbols!");
389 static void keepGlobalValue(GlobalValue &GV,
390 std::vector<GlobalAlias *> &KeptAliases) {
391 assert(!GV.hasLocalLinkage());
393 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
394 KeptAliases.push_back(GA);
396 switch (GV.getLinkage()) {
399 case GlobalValue::LinkOnceAnyLinkage:
400 GV.setLinkage(GlobalValue::WeakAnyLinkage);
402 case GlobalValue::LinkOnceODRLinkage:
403 GV.setLinkage(GlobalValue::WeakODRLinkage);
407 assert(!GV.isDiscardableIfUnused());
410 static void internalize(GlobalValue &GV) {
411 if (GV.isDeclarationForLinker())
412 return; // We get here if there is a matching asm definition.
413 if (!GV.hasLocalLinkage())
414 GV.setLinkage(GlobalValue::InternalLinkage);
417 static void drop(GlobalValue &GV) {
418 if (auto *F = dyn_cast<Function>(&GV)) {
420 F->setComdat(nullptr); // Should deleteBody do this?
424 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
425 Var->setInitializer(nullptr);
427 GlobalValue::ExternalLinkage); // Should setInitializer do this?
428 Var->setComdat(nullptr); // and this?
432 auto &Alias = cast<GlobalAlias>(GV);
433 Module &M = *Alias.getParent();
434 PointerType &Ty = *cast<PointerType>(Alias.getType());
435 GlobalValue::LinkageTypes L = Alias.getLinkage();
437 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
438 /*Initializer*/ nullptr);
439 Var->takeName(&Alias);
440 Alias.replaceAllUsesWith(Var);
441 Alias.eraseFromParent();
444 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
450 case LDPR_PREVAILING_DEF:
451 return "PREVAILING_DEF";
452 case LDPR_PREVAILING_DEF_IRONLY:
453 return "PREVAILING_DEF_IRONLY";
454 case LDPR_PREEMPTED_REG:
455 return "PREEMPTED_REG";
456 case LDPR_PREEMPTED_IR:
457 return "PREEMPTED_IR";
458 case LDPR_RESOLVED_IR:
459 return "RESOLVED_IR";
460 case LDPR_RESOLVED_EXEC:
461 return "RESOLVED_EXEC";
462 case LDPR_RESOLVED_DYN:
463 return "RESOLVED_DYN";
464 case LDPR_PREVAILING_DEF_IRONLY_EXP:
465 return "PREVAILING_DEF_IRONLY_EXP";
467 llvm_unreachable("Unknown resolution");
470 static GlobalObject *makeInternalReplacement(GlobalObject *GO) {
471 Module *M = GO->getParent();
473 if (auto *F = dyn_cast<Function>(GO)) {
474 if (F->materialize())
475 message(LDPL_FATAL, "LLVM gold plugin has failed to read a function");
477 auto *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
480 ValueToValueMapTy VM;
481 Function::arg_iterator NewI = NewF->arg_begin();
482 for (auto &Arg : F->args()) {
483 NewI->setName(Arg.getName());
488 NewF->getBasicBlockList().splice(NewF->end(), F->getBasicBlockList());
489 for (auto &BB : *NewF) {
490 for (auto &Inst : BB)
491 RemapInstruction(&Inst, VM, RF_IgnoreMissingEntries);
497 auto *Var = cast<GlobalVariable>(GO);
498 Ret = new GlobalVariable(
499 *M, Var->getType()->getElementType(), Var->isConstant(),
500 Var->getLinkage(), Var->getInitializer(), Var->getName(),
501 nullptr, Var->getThreadLocalMode(), Var->getType()->getAddressSpace(),
502 Var->isExternallyInitialized());
503 Var->setInitializer(nullptr);
505 Ret->copyAttributesFrom(GO);
506 Ret->setLinkage(GlobalValue::InternalLinkage);
507 Ret->setComdat(GO->getComdat());
513 class LocalValueMaterializer : public ValueMaterializer {
514 DenseSet<GlobalValue *> &Dropped;
517 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
518 Value *materializeValueFor(Value *V) override;
522 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
523 auto *GV = dyn_cast<GlobalValue>(V);
526 if (!Dropped.count(GV))
528 assert(!isa<GlobalAlias>(GV) && "Found alias point to weak alias.");
529 return makeInternalReplacement(cast<GlobalObject>(GV));
532 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
533 LocalValueMaterializer *Materializer) {
534 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
537 static std::unique_ptr<Module>
538 getModuleForFile(LLVMContext &Context, claimed_file &F, raw_fd_ostream *ApiFile,
539 StringSet<> &Internalize, StringSet<> &Maybe) {
540 ld_plugin_input_file File;
541 if (get_input_file(F.handle, &File) != LDPS_OK)
542 message(LDPL_FATAL, "Failed to get file information");
544 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
545 message(LDPL_FATAL, "Failed to get symbol information");
548 if (get_view(F.handle, &View) != LDPS_OK)
549 message(LDPL_FATAL, "Failed to get a view of file");
551 llvm::ErrorOr<MemoryBufferRef> MBOrErr =
552 object::IRObjectFile::findBitcodeInMemBuffer(
553 MemoryBufferRef(StringRef((const char *)View, File.filesize), ""));
554 if (std::error_code EC = MBOrErr.getError())
555 message(LDPL_FATAL, "Could not read bitcode from file : %s",
556 EC.message().c_str());
558 std::unique_ptr<MemoryBuffer> Buffer =
559 MemoryBuffer::getMemBuffer(MBOrErr->getBuffer(), "", false);
561 if (release_input_file(F.handle) != LDPS_OK)
562 message(LDPL_FATAL, "Failed to release file information");
564 ErrorOr<Module *> MOrErr = getLazyBitcodeModule(std::move(Buffer), Context);
566 if (std::error_code EC = MOrErr.getError())
567 message(LDPL_FATAL, "Could not read bitcode from file : %s",
568 EC.message().c_str());
570 std::unique_ptr<Module> M(MOrErr.get());
572 SmallPtrSet<GlobalValue *, 8> Used;
573 collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
575 DenseSet<GlobalValue *> Drop;
576 std::vector<GlobalAlias *> KeptAliases;
577 for (ld_plugin_symbol &Sym : F.syms) {
578 ld_plugin_symbol_resolution Resolution =
579 (ld_plugin_symbol_resolution)Sym.resolution;
581 if (options::generate_api_file)
582 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
584 GlobalValue *GV = M->getNamedValue(Sym.name);
586 continue; // Asm symbol.
588 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
589 // Common linkage is special. There is no single symbol that wins the
590 // resolution. Instead we have to collect the maximum alignment and size.
591 // The IR linker does that for us if we just pass it every common GV.
592 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
593 // internalize once the IR linker has done its job.
597 switch (Resolution) {
599 llvm_unreachable("Unexpected resolution");
601 case LDPR_RESOLVED_IR:
602 case LDPR_RESOLVED_EXEC:
603 case LDPR_RESOLVED_DYN:
605 assert(GV->isDeclarationForLinker());
608 case LDPR_PREVAILING_DEF_IRONLY: {
609 keepGlobalValue(*GV, KeptAliases);
610 if (!Used.count(GV)) {
611 // Since we use the regular lib/Linker, we cannot just internalize GV
612 // now or it will not be copied to the merged module. Instead we force
613 // it to be copied and then internalize it.
614 Internalize.insert(Sym.name);
619 case LDPR_PREVAILING_DEF:
620 keepGlobalValue(*GV, KeptAliases);
623 case LDPR_PREEMPTED_IR:
624 // Gold might have selected a linkonce_odr and preempted a weak_odr.
625 // In that case we have to make sure we don't end up internalizing it.
626 if (!GV->isDiscardableIfUnused())
627 Maybe.erase(Sym.name);
630 case LDPR_PREEMPTED_REG:
634 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
635 // We can only check for address uses after we merge the modules. The
636 // reason is that this GV might have a copy in another module
637 // and in that module the address might be significant, but that
638 // copy will be LDPR_PREEMPTED_IR.
639 if (GV->hasLinkOnceODRLinkage())
640 Maybe.insert(Sym.name);
641 keepGlobalValue(*GV, KeptAliases);
647 free(Sym.comdat_key);
649 Sym.comdat_key = nullptr;
652 ValueToValueMapTy VM;
653 LocalValueMaterializer Materializer(Drop);
654 for (GlobalAlias *GA : KeptAliases) {
655 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
656 // expression is being dropped. If that is the case, that GV must be copied.
657 Constant *Aliasee = GA->getAliasee();
658 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
659 if (Aliasee != Replacement)
660 GA->setAliasee(Replacement);
663 for (auto *GV : Drop)
669 static void runLTOPasses(Module &M, TargetMachine &TM) {
671 PassManagerBuilder PMB;
672 PMB.LibraryInfo = new TargetLibraryInfo(Triple(TM.getTargetTriple()));
673 PMB.Inliner = createFunctionInliningPass();
674 PMB.VerifyInput = true;
675 PMB.VerifyOutput = true;
676 PMB.LoopVectorize = true;
677 PMB.SLPVectorize = true;
678 PMB.populateLTOPassManager(passes, &TM);
682 static void saveBCFile(StringRef Path, Module &M) {
684 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
686 message(LDPL_FATAL, "Failed to write the output file.");
687 WriteBitcodeToFile(&M, OS);
690 static void codegen(Module &M) {
691 const std::string &TripleStr = M.getTargetTriple();
692 Triple TheTriple(TripleStr);
695 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
697 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
699 if (unsigned NumOpts = options::extra.size())
700 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
702 SubtargetFeatures Features;
703 Features.getDefaultSubtargetFeatures(TheTriple);
704 for (const std::string &A : MAttrs)
705 Features.AddFeature(A);
707 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
708 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
709 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
710 CodeModel::Default, CodeGenOpt::Aggressive));
712 runLTOPasses(M, *TM);
714 if (options::generate_bc_file == options::BC_SAVE_TEMPS)
715 saveBCFile(output_name + ".opt.bc", M);
717 PassManager CodeGenPasses;
718 CodeGenPasses.add(new DataLayoutPass());
720 SmallString<128> Filename;
722 if (options::obj_path.empty()) {
724 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
726 message(LDPL_FATAL, "Could not create temorary file: %s",
727 EC.message().c_str());
729 Filename = options::obj_path;
731 sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
733 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
737 raw_fd_ostream OS(FD, true);
738 formatted_raw_ostream FOS(OS);
740 if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
741 TargetMachine::CGFT_ObjectFile))
742 message(LDPL_FATAL, "Failed to setup codegen");
743 CodeGenPasses.run(M);
746 if (add_input_file(Filename.c_str()) != LDPS_OK)
748 "Unable to add .o file to the link. File left behind in: %s",
751 if (options::obj_path.empty())
752 Cleanup.push_back(Filename.c_str());
755 /// gold informs us that all symbols have been read. At this point, we use
756 /// get_symbols to see if any of our definitions have been overridden by a
757 /// native object file. Then, perform optimization and codegen.
758 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
763 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
764 Linker L(Combined.get());
766 std::string DefaultTriple = sys::getDefaultTargetTriple();
768 StringSet<> Internalize;
770 for (claimed_file &F : Modules) {
771 std::unique_ptr<Module> M =
772 getModuleForFile(Context, F, ApiFile, Internalize, Maybe);
773 if (!options::triple.empty())
774 M->setTargetTriple(options::triple.c_str());
775 else if (M->getTargetTriple().empty()) {
776 M->setTargetTriple(DefaultTriple);
779 if (L.linkInModule(M.get()))
780 message(LDPL_FATAL, "Failed to link module");
783 for (const auto &Name : Internalize) {
784 GlobalValue *GV = Combined->getNamedValue(Name.first());
789 for (const auto &Name : Maybe) {
790 GlobalValue *GV = Combined->getNamedValue(Name.first());
793 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
794 if (canBeOmittedFromSymbolTable(GV))
798 if (options::generate_bc_file != options::BC_NO) {
800 if (options::generate_bc_file == options::BC_ONLY)
803 path = output_name + ".bc";
804 saveBCFile(path, *L.getModule());
805 if (options::generate_bc_file == options::BC_ONLY)
809 codegen(*L.getModule());
811 if (!options::extra_library_path.empty() &&
812 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
813 message(LDPL_FATAL, "Unable to set the extra library path.");
818 static ld_plugin_status all_symbols_read_hook(void) {
819 ld_plugin_status Ret;
820 if (!options::generate_api_file) {
821 Ret = allSymbolsReadHook(nullptr);
824 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
826 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
827 EC.message().c_str());
828 Ret = allSymbolsReadHook(&ApiFile);
831 if (options::generate_bc_file == options::BC_ONLY)
837 static ld_plugin_status cleanup_hook(void) {
838 for (std::string &Name : Cleanup) {
839 std::error_code EC = sys::fs::remove(Name);
841 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
842 EC.message().c_str());