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/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/CodeGen/CommandFlags.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/DiagnosticPrinter.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/Linker/Linker.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Object/IRObjectFile.h"
31 #include "llvm/PassManager.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Transforms/IPO.h"
39 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
40 #include "llvm/Transforms/Utils/GlobalStatus.h"
41 #include "llvm/Transforms/Utils/ModuleUtils.h"
42 #include "llvm/Transforms/Utils/ValueMapper.h"
44 #include <plugin-api.h>
45 #include <system_error>
49 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
50 // Precise and Debian Wheezy (binutils 2.23 is required)
59 std::vector<ld_plugin_symbol> syms;
63 static ld_plugin_status discard_message(int level, const char *format, ...) {
64 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
65 // callback in the transfer vector. This should never be called.
69 static ld_plugin_get_input_file get_input_file = nullptr;
70 static ld_plugin_release_input_file release_input_file = nullptr;
71 static ld_plugin_add_symbols add_symbols = nullptr;
72 static ld_plugin_get_symbols get_symbols = nullptr;
73 static ld_plugin_add_input_file add_input_file = nullptr;
74 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
75 static ld_plugin_get_view get_view = nullptr;
76 static ld_plugin_message message = discard_message;
77 static Reloc::Model RelocationModel = Reloc::Default;
78 static std::string output_name = "";
79 static std::list<claimed_file> Modules;
80 static std::vector<std::string> Cleanup;
81 static llvm::TargetOptions TargetOpts;
90 static bool generate_api_file = false;
91 static OutputType TheOutputType = OT_NORMAL;
92 static std::string obj_path;
93 static std::string extra_library_path;
94 static std::string triple;
95 static std::string mcpu;
96 // Additional options to pass into the code generator.
97 // Note: This array will contain all plugin options which are not claimed
98 // as plugin exclusive to pass to the code generator.
99 // For example, "generate-api-file" and "as"options are for the plugin
100 // use only and will not be passed.
101 static std::vector<const char *> extra;
103 static void process_plugin_option(const char* opt_)
107 llvm::StringRef opt = opt_;
109 if (opt == "generate-api-file") {
110 generate_api_file = true;
111 } else if (opt.startswith("mcpu=")) {
112 mcpu = opt.substr(strlen("mcpu="));
113 } else if (opt.startswith("extra-library-path=")) {
114 extra_library_path = opt.substr(strlen("extra_library_path="));
115 } else if (opt.startswith("mtriple=")) {
116 triple = opt.substr(strlen("mtriple="));
117 } else if (opt.startswith("obj-path=")) {
118 obj_path = opt.substr(strlen("obj-path="));
119 } else if (opt == "emit-llvm") {
120 TheOutputType = OT_BC_ONLY;
121 } else if (opt == "save-temps") {
122 TheOutputType = OT_SAVE_TEMPS;
123 } else if (opt == "disable-output") {
124 TheOutputType = OT_DISABLE;
126 // Save this option to pass to the code generator.
127 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
130 extra.push_back("LLVMgold");
132 extra.push_back(opt_);
137 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
139 static ld_plugin_status all_symbols_read_hook(void);
140 static ld_plugin_status cleanup_hook(void);
142 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
143 ld_plugin_status onload(ld_plugin_tv *tv) {
144 InitializeAllTargetInfos();
145 InitializeAllTargets();
146 InitializeAllTargetMCs();
147 InitializeAllAsmParsers();
148 InitializeAllAsmPrinters();
150 // We're given a pointer to the first transfer vector. We read through them
151 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
152 // contain pointers to functions that we need to call to register our own
153 // hooks. The others are addresses of functions we can use to call into gold
156 bool registeredClaimFile = false;
157 bool RegisteredAllSymbolsRead = false;
159 for (; tv->tv_tag != LDPT_NULL; ++tv) {
160 switch (tv->tv_tag) {
161 case LDPT_OUTPUT_NAME:
162 output_name = tv->tv_u.tv_string;
164 case LDPT_LINKER_OUTPUT:
165 switch (tv->tv_u.tv_val) {
167 case LDPO_DYN: // .so
168 case LDPO_PIE: // position independent executable
169 RelocationModel = Reloc::PIC_;
171 case LDPO_EXEC: // .exe
172 RelocationModel = Reloc::Static;
175 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
180 options::process_plugin_option(tv->tv_u.tv_string);
182 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
183 ld_plugin_register_claim_file callback;
184 callback = tv->tv_u.tv_register_claim_file;
186 if (callback(claim_file_hook) != LDPS_OK)
189 registeredClaimFile = true;
191 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
192 ld_plugin_register_all_symbols_read callback;
193 callback = tv->tv_u.tv_register_all_symbols_read;
195 if (callback(all_symbols_read_hook) != LDPS_OK)
198 RegisteredAllSymbolsRead = true;
200 case LDPT_REGISTER_CLEANUP_HOOK: {
201 ld_plugin_register_cleanup callback;
202 callback = tv->tv_u.tv_register_cleanup;
204 if (callback(cleanup_hook) != LDPS_OK)
207 case LDPT_GET_INPUT_FILE:
208 get_input_file = tv->tv_u.tv_get_input_file;
210 case LDPT_RELEASE_INPUT_FILE:
211 release_input_file = tv->tv_u.tv_release_input_file;
213 case LDPT_ADD_SYMBOLS:
214 add_symbols = tv->tv_u.tv_add_symbols;
216 case LDPT_GET_SYMBOLS_V2:
217 get_symbols = tv->tv_u.tv_get_symbols;
219 case LDPT_ADD_INPUT_FILE:
220 add_input_file = tv->tv_u.tv_add_input_file;
222 case LDPT_SET_EXTRA_LIBRARY_PATH:
223 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
226 get_view = tv->tv_u.tv_get_view;
229 message = tv->tv_u.tv_message;
236 if (!registeredClaimFile) {
237 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
241 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
245 if (!RegisteredAllSymbolsRead)
248 if (!get_input_file) {
249 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
252 if (!release_input_file) {
253 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
260 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
261 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
262 return GA->getBaseObject();
263 return cast<GlobalObject>(&GV);
266 static bool shouldSkip(uint32_t Symflags) {
267 if (!(Symflags & object::BasicSymbolRef::SF_Global))
269 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
274 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
275 assert(DI.getSeverity() == DS_Error && "Only expecting errors");
276 const auto &BDI = cast<BitcodeDiagnosticInfo>(DI);
277 std::error_code EC = BDI.getError();
278 if (EC == BitcodeError::InvalidBitcodeSignature)
281 std::string ErrStorage;
283 raw_string_ostream OS(ErrStorage);
284 DiagnosticPrinterRawOStream DP(OS);
287 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
291 /// Called by gold to see whether this file is one that our plugin can handle.
292 /// We'll try to open it and register all the symbols with add_symbol if
294 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
297 MemoryBufferRef BufferRef;
298 std::unique_ptr<MemoryBuffer> Buffer;
301 if (get_view(file->handle, &view) != LDPS_OK) {
302 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
305 BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
308 // Gold has found what might be IR part-way inside of a file, such as
311 offset = file->offset;
313 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
314 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
316 if (std::error_code EC = BufferOrErr.getError()) {
317 message(LDPL_ERROR, EC.message().c_str());
320 Buffer = std::move(BufferOrErr.get());
321 BufferRef = Buffer->getMemBufferRef();
324 Context.setDiagnosticHandler(diagnosticHandler);
325 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
326 object::IRObjectFile::create(BufferRef, Context);
327 std::error_code EC = ObjOrErr.getError();
328 if (EC == object::object_error::invalid_file_type ||
329 EC == object::object_error::bitcode_section_not_found)
335 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
336 EC.message().c_str());
339 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
341 Modules.resize(Modules.size() + 1);
342 claimed_file &cf = Modules.back();
344 cf.handle = file->handle;
346 for (auto &Sym : Obj->symbols()) {
347 uint32_t Symflags = Sym.getFlags();
348 if (shouldSkip(Symflags))
351 cf.syms.push_back(ld_plugin_symbol());
352 ld_plugin_symbol &sym = cf.syms.back();
353 sym.version = nullptr;
355 SmallString<64> Name;
357 raw_svector_ostream OS(Name);
360 sym.name = strdup(Name.c_str());
362 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
364 sym.visibility = LDPV_DEFAULT;
366 switch (GV->getVisibility()) {
367 case GlobalValue::DefaultVisibility:
368 sym.visibility = LDPV_DEFAULT;
370 case GlobalValue::HiddenVisibility:
371 sym.visibility = LDPV_HIDDEN;
373 case GlobalValue::ProtectedVisibility:
374 sym.visibility = LDPV_PROTECTED;
379 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
380 sym.def = LDPK_UNDEF;
381 if (GV && GV->hasExternalWeakLinkage())
382 sym.def = LDPK_WEAKUNDEF;
386 assert(!GV->hasExternalWeakLinkage() &&
387 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
388 if (GV->hasCommonLinkage())
389 sym.def = LDPK_COMMON;
390 else if (GV->isWeakForLinker())
391 sym.def = LDPK_WEAKDEF;
396 sym.comdat_key = nullptr;
398 const GlobalObject *Base = getBaseObject(*GV);
400 message(LDPL_FATAL, "Unable to determine comdat of alias!");
401 const Comdat *C = Base->getComdat();
403 sym.comdat_key = strdup(C->getName().str().c_str());
404 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
405 sym.comdat_key = strdup(sym.name);
408 sym.resolution = LDPR_UNKNOWN;
411 if (!cf.syms.empty()) {
412 if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
413 message(LDPL_ERROR, "Unable to add symbols!");
421 static void keepGlobalValue(GlobalValue &GV,
422 std::vector<GlobalAlias *> &KeptAliases) {
423 assert(!GV.hasLocalLinkage());
425 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
426 KeptAliases.push_back(GA);
428 switch (GV.getLinkage()) {
431 case GlobalValue::LinkOnceAnyLinkage:
432 GV.setLinkage(GlobalValue::WeakAnyLinkage);
434 case GlobalValue::LinkOnceODRLinkage:
435 GV.setLinkage(GlobalValue::WeakODRLinkage);
439 assert(!GV.isDiscardableIfUnused());
442 static void internalize(GlobalValue &GV) {
443 if (GV.isDeclarationForLinker())
444 return; // We get here if there is a matching asm definition.
445 if (!GV.hasLocalLinkage())
446 GV.setLinkage(GlobalValue::InternalLinkage);
449 static void drop(GlobalValue &GV) {
450 if (auto *F = dyn_cast<Function>(&GV)) {
452 F->setComdat(nullptr); // Should deleteBody do this?
456 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
457 Var->setInitializer(nullptr);
459 GlobalValue::ExternalLinkage); // Should setInitializer do this?
460 Var->setComdat(nullptr); // and this?
464 auto &Alias = cast<GlobalAlias>(GV);
465 Module &M = *Alias.getParent();
466 PointerType &Ty = *cast<PointerType>(Alias.getType());
467 GlobalValue::LinkageTypes L = Alias.getLinkage();
469 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
470 /*Initializer*/ nullptr);
471 Var->takeName(&Alias);
472 Alias.replaceAllUsesWith(Var);
473 Alias.eraseFromParent();
476 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
482 case LDPR_PREVAILING_DEF:
483 return "PREVAILING_DEF";
484 case LDPR_PREVAILING_DEF_IRONLY:
485 return "PREVAILING_DEF_IRONLY";
486 case LDPR_PREEMPTED_REG:
487 return "PREEMPTED_REG";
488 case LDPR_PREEMPTED_IR:
489 return "PREEMPTED_IR";
490 case LDPR_RESOLVED_IR:
491 return "RESOLVED_IR";
492 case LDPR_RESOLVED_EXEC:
493 return "RESOLVED_EXEC";
494 case LDPR_RESOLVED_DYN:
495 return "RESOLVED_DYN";
496 case LDPR_PREVAILING_DEF_IRONLY_EXP:
497 return "PREVAILING_DEF_IRONLY_EXP";
499 llvm_unreachable("Unknown resolution");
503 class LocalValueMaterializer : public ValueMaterializer {
504 DenseSet<GlobalValue *> &Dropped;
505 DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
508 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
509 Value *materializeValueFor(Value *V) override;
513 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
514 auto *GO = dyn_cast<GlobalObject>(V);
518 auto I = LocalVersions.find(GO);
519 if (I != LocalVersions.end())
522 if (!Dropped.count(GO))
525 Module &M = *GO->getParent();
526 GlobalValue::LinkageTypes L = GO->getLinkage();
527 GlobalObject *Declaration;
528 if (auto *F = dyn_cast<Function>(GO)) {
529 Declaration = Function::Create(F->getFunctionType(), L, "", &M);
531 auto *Var = cast<GlobalVariable>(GO);
532 Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
533 Var->isConstant(), L,
534 /*Initializer*/ nullptr);
536 Declaration->takeName(GO);
537 Declaration->copyAttributesFrom(GO);
539 GO->setLinkage(GlobalValue::InternalLinkage);
540 GO->setName(Declaration->getName());
542 GO->replaceAllUsesWith(Declaration);
544 LocalVersions[Declaration] = GO;
549 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
550 LocalValueMaterializer *Materializer) {
551 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
554 static void freeSymName(ld_plugin_symbol &Sym) {
556 free(Sym.comdat_key);
558 Sym.comdat_key = nullptr;
561 static std::unique_ptr<Module>
562 getModuleForFile(LLVMContext &Context, claimed_file &F, raw_fd_ostream *ApiFile,
563 StringSet<> &Internalize, StringSet<> &Maybe) {
564 ld_plugin_input_file File;
565 if (get_input_file(F.handle, &File) != LDPS_OK)
566 message(LDPL_FATAL, "Failed to get file information");
568 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
569 message(LDPL_FATAL, "Failed to get symbol information");
572 if (get_view(F.handle, &View) != LDPS_OK)
573 message(LDPL_FATAL, "Failed to get a view of file");
575 MemoryBufferRef BufferRef(StringRef((const char *)View, File.filesize), "");
576 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
577 object::IRObjectFile::create(BufferRef, Context);
579 if (std::error_code EC = ObjOrErr.getError())
580 message(LDPL_FATAL, "Could not read bitcode from file : %s",
581 EC.message().c_str());
583 if (release_input_file(F.handle) != LDPS_OK)
584 message(LDPL_FATAL, "Failed to release file information");
586 object::IRObjectFile &Obj = **ObjOrErr;
588 Module &M = Obj.getModule();
590 SmallPtrSet<GlobalValue *, 8> Used;
591 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
593 DenseSet<GlobalValue *> Drop;
594 std::vector<GlobalAlias *> KeptAliases;
597 for (auto &ObjSym : Obj.symbols()) {
598 if (shouldSkip(ObjSym.getFlags()))
600 ld_plugin_symbol &Sym = F.syms[SymNum];
603 ld_plugin_symbol_resolution Resolution =
604 (ld_plugin_symbol_resolution)Sym.resolution;
606 if (options::generate_api_file)
607 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
609 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
612 continue; // Asm symbol.
615 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
616 // Common linkage is special. There is no single symbol that wins the
617 // resolution. Instead we have to collect the maximum alignment and size.
618 // The IR linker does that for us if we just pass it every common GV.
619 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
620 // internalize once the IR linker has done its job.
625 switch (Resolution) {
627 llvm_unreachable("Unexpected resolution");
629 case LDPR_RESOLVED_IR:
630 case LDPR_RESOLVED_EXEC:
631 case LDPR_RESOLVED_DYN:
632 assert(GV->isDeclarationForLinker());
636 if (!GV->isDeclarationForLinker()) {
637 assert(GV->hasComdat());
642 case LDPR_PREVAILING_DEF_IRONLY: {
643 keepGlobalValue(*GV, KeptAliases);
644 if (!Used.count(GV)) {
645 // Since we use the regular lib/Linker, we cannot just internalize GV
646 // now or it will not be copied to the merged module. Instead we force
647 // it to be copied and then internalize it.
648 Internalize.insert(GV->getName());
653 case LDPR_PREVAILING_DEF:
654 keepGlobalValue(*GV, KeptAliases);
657 case LDPR_PREEMPTED_IR:
658 // Gold might have selected a linkonce_odr and preempted a weak_odr.
659 // In that case we have to make sure we don't end up internalizing it.
660 if (!GV->isDiscardableIfUnused())
661 Maybe.erase(GV->getName());
664 case LDPR_PREEMPTED_REG:
668 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
669 // We can only check for address uses after we merge the modules. The
670 // reason is that this GV might have a copy in another module
671 // and in that module the address might be significant, but that
672 // copy will be LDPR_PREEMPTED_IR.
673 if (GV->hasLinkOnceODRLinkage())
674 Maybe.insert(GV->getName());
675 keepGlobalValue(*GV, KeptAliases);
683 ValueToValueMapTy VM;
684 LocalValueMaterializer Materializer(Drop);
685 for (GlobalAlias *GA : KeptAliases) {
686 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
687 // expression is being dropped. If that is the case, that GV must be copied.
688 Constant *Aliasee = GA->getAliasee();
689 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
690 GA->setAliasee(Replacement);
693 for (auto *GV : Drop)
696 return Obj.takeModule();
699 static void runLTOPasses(Module &M, TargetMachine &TM) {
701 PassManagerBuilder PMB;
702 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
703 PMB.Inliner = createFunctionInliningPass();
704 PMB.VerifyInput = true;
705 PMB.VerifyOutput = true;
706 PMB.LoopVectorize = true;
707 PMB.SLPVectorize = true;
708 PMB.populateLTOPassManager(passes, &TM);
712 static void saveBCFile(StringRef Path, Module &M) {
714 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
716 message(LDPL_FATAL, "Failed to write the output file.");
717 WriteBitcodeToFile(&M, OS);
720 static void codegen(Module &M) {
721 const std::string &TripleStr = M.getTargetTriple();
722 Triple TheTriple(TripleStr);
725 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
727 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
729 if (unsigned NumOpts = options::extra.size())
730 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
732 SubtargetFeatures Features;
733 Features.getDefaultSubtargetFeatures(TheTriple);
734 for (const std::string &A : MAttrs)
735 Features.AddFeature(A);
737 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
738 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
739 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
740 CodeModel::Default, CodeGenOpt::Aggressive));
742 runLTOPasses(M, *TM);
744 if (options::TheOutputType == options::OT_SAVE_TEMPS)
745 saveBCFile(output_name + ".opt.bc", M);
747 PassManager CodeGenPasses;
748 CodeGenPasses.add(new DataLayoutPass());
750 SmallString<128> Filename;
752 if (options::obj_path.empty()) {
754 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
756 message(LDPL_FATAL, "Could not create temporary file: %s",
757 EC.message().c_str());
759 Filename = options::obj_path;
761 sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
763 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
767 raw_fd_ostream OS(FD, true);
768 formatted_raw_ostream FOS(OS);
770 if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
771 TargetMachine::CGFT_ObjectFile))
772 message(LDPL_FATAL, "Failed to setup codegen");
773 CodeGenPasses.run(M);
776 if (add_input_file(Filename.c_str()) != LDPS_OK)
778 "Unable to add .o file to the link. File left behind in: %s",
781 if (options::obj_path.empty())
782 Cleanup.push_back(Filename.c_str());
785 /// gold informs us that all symbols have been read. At this point, we use
786 /// get_symbols to see if any of our definitions have been overridden by a
787 /// native object file. Then, perform optimization and codegen.
788 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
793 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
794 Linker L(Combined.get());
796 std::string DefaultTriple = sys::getDefaultTargetTriple();
798 StringSet<> Internalize;
800 for (claimed_file &F : Modules) {
801 std::unique_ptr<Module> M =
802 getModuleForFile(Context, F, ApiFile, Internalize, Maybe);
803 if (!options::triple.empty())
804 M->setTargetTriple(options::triple.c_str());
805 else if (M->getTargetTriple().empty()) {
806 M->setTargetTriple(DefaultTriple);
809 if (L.linkInModule(M.get()))
810 message(LDPL_FATAL, "Failed to link module");
813 for (const auto &Name : Internalize) {
814 GlobalValue *GV = Combined->getNamedValue(Name.first());
819 for (const auto &Name : Maybe) {
820 GlobalValue *GV = Combined->getNamedValue(Name.first());
823 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
824 if (canBeOmittedFromSymbolTable(GV))
828 if (options::TheOutputType == options::OT_DISABLE)
831 if (options::TheOutputType != options::OT_NORMAL) {
833 if (options::TheOutputType == options::OT_BC_ONLY)
836 path = output_name + ".bc";
837 saveBCFile(path, *L.getModule());
838 if (options::TheOutputType == options::OT_BC_ONLY)
842 codegen(*L.getModule());
844 if (!options::extra_library_path.empty() &&
845 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
846 message(LDPL_FATAL, "Unable to set the extra library path.");
851 static ld_plugin_status all_symbols_read_hook(void) {
852 ld_plugin_status Ret;
853 if (!options::generate_api_file) {
854 Ret = allSymbolsReadHook(nullptr);
857 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
859 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
860 EC.message().c_str());
861 Ret = allSymbolsReadHook(&ApiFile);
866 if (options::TheOutputType == options::OT_BC_ONLY ||
867 options::TheOutputType == options::OT_DISABLE)
873 static ld_plugin_status cleanup_hook(void) {
874 for (std::string &Name : Cleanup) {
875 std::error_code EC = sys::fs::remove(Name);
877 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
878 EC.message().c_str());