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/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/Target/TargetLibraryInfo.h"
36 #include "llvm/Transforms/IPO.h"
37 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38 #include "llvm/Transforms/Utils/GlobalStatus.h"
39 #include "llvm/Transforms/Utils/ModuleUtils.h"
40 #include "llvm/Transforms/Utils/ValueMapper.h"
42 #include <plugin-api.h>
43 #include <system_error>
47 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
48 // Precise and Debian Wheezy (binutils 2.23 is required)
57 std::vector<ld_plugin_symbol> syms;
61 static ld_plugin_status discard_message(int level, const char *format, ...) {
62 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
63 // callback in the transfer vector. This should never be called.
67 static ld_plugin_get_input_file get_input_file = nullptr;
68 static ld_plugin_release_input_file release_input_file = nullptr;
69 static ld_plugin_add_symbols add_symbols = nullptr;
70 static ld_plugin_get_symbols get_symbols = nullptr;
71 static ld_plugin_add_input_file add_input_file = nullptr;
72 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
73 static ld_plugin_get_view get_view = nullptr;
74 static ld_plugin_message message = discard_message;
75 static Reloc::Model RelocationModel = Reloc::Default;
76 static std::string output_name = "";
77 static std::list<claimed_file> Modules;
78 static std::vector<std::string> Cleanup;
79 static llvm::TargetOptions TargetOpts;
88 static bool generate_api_file = false;
89 static OutputType TheOutputType = OT_NORMAL;
90 static std::string obj_path;
91 static std::string extra_library_path;
92 static std::string triple;
93 static std::string mcpu;
94 // Additional options to pass into the code generator.
95 // Note: This array will contain all plugin options which are not claimed
96 // as plugin exclusive to pass to the code generator.
97 // For example, "generate-api-file" and "as"options are for the plugin
98 // use only and will not be passed.
99 static std::vector<const char *> extra;
101 static void process_plugin_option(const char* opt_)
105 llvm::StringRef opt = opt_;
107 if (opt == "generate-api-file") {
108 generate_api_file = true;
109 } else if (opt.startswith("mcpu=")) {
110 mcpu = opt.substr(strlen("mcpu="));
111 } else if (opt.startswith("extra-library-path=")) {
112 extra_library_path = opt.substr(strlen("extra_library_path="));
113 } else if (opt.startswith("mtriple=")) {
114 triple = opt.substr(strlen("mtriple="));
115 } else if (opt.startswith("obj-path=")) {
116 obj_path = opt.substr(strlen("obj-path="));
117 } else if (opt == "emit-llvm") {
118 TheOutputType = OT_BC_ONLY;
119 } else if (opt == "save-temps") {
120 TheOutputType = OT_SAVE_TEMPS;
121 } else if (opt == "disable-output") {
122 TheOutputType = OT_DISABLE;
124 // Save this option to pass to the code generator.
125 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
128 extra.push_back("LLVMgold");
130 extra.push_back(opt_);
135 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
137 static ld_plugin_status all_symbols_read_hook(void);
138 static ld_plugin_status cleanup_hook(void);
140 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
141 ld_plugin_status onload(ld_plugin_tv *tv) {
142 InitializeAllTargetInfos();
143 InitializeAllTargets();
144 InitializeAllTargetMCs();
145 InitializeAllAsmParsers();
146 InitializeAllAsmPrinters();
148 // We're given a pointer to the first transfer vector. We read through them
149 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
150 // contain pointers to functions that we need to call to register our own
151 // hooks. The others are addresses of functions we can use to call into gold
154 bool registeredClaimFile = false;
155 bool RegisteredAllSymbolsRead = false;
157 for (; tv->tv_tag != LDPT_NULL; ++tv) {
158 switch (tv->tv_tag) {
159 case LDPT_OUTPUT_NAME:
160 output_name = tv->tv_u.tv_string;
162 case LDPT_LINKER_OUTPUT:
163 switch (tv->tv_u.tv_val) {
165 case LDPO_DYN: // .so
166 case LDPO_PIE: // position independent executable
167 RelocationModel = Reloc::PIC_;
169 case LDPO_EXEC: // .exe
170 RelocationModel = Reloc::Static;
173 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
178 options::process_plugin_option(tv->tv_u.tv_string);
180 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
181 ld_plugin_register_claim_file callback;
182 callback = tv->tv_u.tv_register_claim_file;
184 if (callback(claim_file_hook) != LDPS_OK)
187 registeredClaimFile = true;
189 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
190 ld_plugin_register_all_symbols_read callback;
191 callback = tv->tv_u.tv_register_all_symbols_read;
193 if (callback(all_symbols_read_hook) != LDPS_OK)
196 RegisteredAllSymbolsRead = true;
198 case LDPT_REGISTER_CLEANUP_HOOK: {
199 ld_plugin_register_cleanup callback;
200 callback = tv->tv_u.tv_register_cleanup;
202 if (callback(cleanup_hook) != LDPS_OK)
205 case LDPT_GET_INPUT_FILE:
206 get_input_file = tv->tv_u.tv_get_input_file;
208 case LDPT_RELEASE_INPUT_FILE:
209 release_input_file = tv->tv_u.tv_release_input_file;
211 case LDPT_ADD_SYMBOLS:
212 add_symbols = tv->tv_u.tv_add_symbols;
214 case LDPT_GET_SYMBOLS_V2:
215 get_symbols = tv->tv_u.tv_get_symbols;
217 case LDPT_ADD_INPUT_FILE:
218 add_input_file = tv->tv_u.tv_add_input_file;
220 case LDPT_SET_EXTRA_LIBRARY_PATH:
221 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
224 get_view = tv->tv_u.tv_get_view;
227 message = tv->tv_u.tv_message;
234 if (!registeredClaimFile) {
235 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
239 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
243 if (!RegisteredAllSymbolsRead)
246 if (!get_input_file) {
247 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
250 if (!release_input_file) {
251 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
258 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
259 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
260 return GA->getBaseObject();
261 return cast<GlobalObject>(&GV);
264 static bool shouldSkip(uint32_t Symflags) {
265 if (!(Symflags & object::BasicSymbolRef::SF_Global))
267 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
272 /// Called by gold to see whether this file is one that our plugin can handle.
273 /// We'll try to open it and register all the symbols with add_symbol if
275 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
278 MemoryBufferRef BufferRef;
279 std::unique_ptr<MemoryBuffer> Buffer;
282 if (get_view(file->handle, &view) != LDPS_OK) {
283 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
286 BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
289 // Gold has found what might be IR part-way inside of a file, such as
292 offset = file->offset;
294 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
295 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
297 if (std::error_code EC = BufferOrErr.getError()) {
298 message(LDPL_ERROR, EC.message().c_str());
301 Buffer = std::move(BufferOrErr.get());
302 BufferRef = Buffer->getMemBufferRef();
305 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
306 object::IRObjectFile::createIRObjectFile(BufferRef, Context);
307 std::error_code EC = ObjOrErr.getError();
308 if (EC == BitcodeError::InvalidBitcodeSignature ||
309 EC == object::object_error::invalid_file_type ||
310 EC == object::object_error::bitcode_section_not_found)
316 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
317 EC.message().c_str());
320 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
322 Modules.resize(Modules.size() + 1);
323 claimed_file &cf = Modules.back();
325 cf.handle = file->handle;
327 for (auto &Sym : Obj->symbols()) {
328 uint32_t Symflags = Sym.getFlags();
329 if (shouldSkip(Symflags))
332 cf.syms.push_back(ld_plugin_symbol());
333 ld_plugin_symbol &sym = cf.syms.back();
334 sym.version = nullptr;
336 SmallString<64> Name;
338 raw_svector_ostream OS(Name);
341 sym.name = strdup(Name.c_str());
343 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
345 sym.visibility = LDPV_DEFAULT;
347 switch (GV->getVisibility()) {
348 case GlobalValue::DefaultVisibility:
349 sym.visibility = LDPV_DEFAULT;
351 case GlobalValue::HiddenVisibility:
352 sym.visibility = LDPV_HIDDEN;
354 case GlobalValue::ProtectedVisibility:
355 sym.visibility = LDPV_PROTECTED;
360 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
361 sym.def = LDPK_UNDEF;
362 if (GV && GV->hasExternalWeakLinkage())
363 sym.def = LDPK_WEAKUNDEF;
367 assert(!GV->hasExternalWeakLinkage() &&
368 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
369 if (GV->hasCommonLinkage())
370 sym.def = LDPK_COMMON;
371 else if (GV->isWeakForLinker())
372 sym.def = LDPK_WEAKDEF;
377 sym.comdat_key = nullptr;
379 const GlobalObject *Base = getBaseObject(*GV);
381 message(LDPL_FATAL, "Unable to determine comdat of alias!");
382 const Comdat *C = Base->getComdat();
384 sym.comdat_key = strdup(C->getName().str().c_str());
385 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
386 sym.comdat_key = strdup(sym.name);
389 sym.resolution = LDPR_UNKNOWN;
392 if (!cf.syms.empty()) {
393 if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
394 message(LDPL_ERROR, "Unable to add symbols!");
402 static void keepGlobalValue(GlobalValue &GV,
403 std::vector<GlobalAlias *> &KeptAliases) {
404 assert(!GV.hasLocalLinkage());
406 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
407 KeptAliases.push_back(GA);
409 switch (GV.getLinkage()) {
412 case GlobalValue::LinkOnceAnyLinkage:
413 GV.setLinkage(GlobalValue::WeakAnyLinkage);
415 case GlobalValue::LinkOnceODRLinkage:
416 GV.setLinkage(GlobalValue::WeakODRLinkage);
420 assert(!GV.isDiscardableIfUnused());
423 static void internalize(GlobalValue &GV) {
424 if (GV.isDeclarationForLinker())
425 return; // We get here if there is a matching asm definition.
426 if (!GV.hasLocalLinkage())
427 GV.setLinkage(GlobalValue::InternalLinkage);
430 static void drop(GlobalValue &GV) {
431 if (auto *F = dyn_cast<Function>(&GV)) {
433 F->setComdat(nullptr); // Should deleteBody do this?
437 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
438 Var->setInitializer(nullptr);
440 GlobalValue::ExternalLinkage); // Should setInitializer do this?
441 Var->setComdat(nullptr); // and this?
445 auto &Alias = cast<GlobalAlias>(GV);
446 Module &M = *Alias.getParent();
447 PointerType &Ty = *cast<PointerType>(Alias.getType());
448 GlobalValue::LinkageTypes L = Alias.getLinkage();
450 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
451 /*Initializer*/ nullptr);
452 Var->takeName(&Alias);
453 Alias.replaceAllUsesWith(Var);
454 Alias.eraseFromParent();
457 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
463 case LDPR_PREVAILING_DEF:
464 return "PREVAILING_DEF";
465 case LDPR_PREVAILING_DEF_IRONLY:
466 return "PREVAILING_DEF_IRONLY";
467 case LDPR_PREEMPTED_REG:
468 return "PREEMPTED_REG";
469 case LDPR_PREEMPTED_IR:
470 return "PREEMPTED_IR";
471 case LDPR_RESOLVED_IR:
472 return "RESOLVED_IR";
473 case LDPR_RESOLVED_EXEC:
474 return "RESOLVED_EXEC";
475 case LDPR_RESOLVED_DYN:
476 return "RESOLVED_DYN";
477 case LDPR_PREVAILING_DEF_IRONLY_EXP:
478 return "PREVAILING_DEF_IRONLY_EXP";
480 llvm_unreachable("Unknown resolution");
483 static GlobalObject *makeInternalReplacement(GlobalObject *GO) {
484 Module *M = GO->getParent();
486 if (auto *F = dyn_cast<Function>(GO)) {
487 if (F->materialize())
488 message(LDPL_FATAL, "LLVM gold plugin has failed to read a function");
490 auto *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
493 ValueToValueMapTy VM;
494 Function::arg_iterator NewI = NewF->arg_begin();
495 for (auto &Arg : F->args()) {
496 NewI->setName(Arg.getName());
501 NewF->getBasicBlockList().splice(NewF->end(), F->getBasicBlockList());
502 for (auto &BB : *NewF) {
503 for (auto &Inst : BB)
504 RemapInstruction(&Inst, VM, RF_IgnoreMissingEntries);
510 auto *Var = cast<GlobalVariable>(GO);
511 Ret = new GlobalVariable(
512 *M, Var->getType()->getElementType(), Var->isConstant(),
513 Var->getLinkage(), Var->getInitializer(), Var->getName(),
514 nullptr, Var->getThreadLocalMode(), Var->getType()->getAddressSpace(),
515 Var->isExternallyInitialized());
516 Var->setInitializer(nullptr);
518 Ret->copyAttributesFrom(GO);
519 Ret->setLinkage(GlobalValue::InternalLinkage);
520 Ret->setComdat(GO->getComdat());
526 class LocalValueMaterializer : public ValueMaterializer {
527 DenseSet<GlobalValue *> &Dropped;
530 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
531 Value *materializeValueFor(Value *V) override;
535 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
536 auto *GV = dyn_cast<GlobalValue>(V);
539 if (!Dropped.count(GV))
541 assert(!isa<GlobalAlias>(GV) && "Found alias point to weak alias.");
542 return makeInternalReplacement(cast<GlobalObject>(GV));
545 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
546 LocalValueMaterializer *Materializer) {
547 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
550 static std::unique_ptr<Module>
551 getModuleForFile(LLVMContext &Context, claimed_file &F, raw_fd_ostream *ApiFile,
552 StringSet<> &Internalize, StringSet<> &Maybe) {
553 ld_plugin_input_file File;
554 if (get_input_file(F.handle, &File) != LDPS_OK)
555 message(LDPL_FATAL, "Failed to get file information");
557 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
558 message(LDPL_FATAL, "Failed to get symbol information");
561 if (get_view(F.handle, &View) != LDPS_OK)
562 message(LDPL_FATAL, "Failed to get a view of file");
564 MemoryBufferRef BufferRef(StringRef((const char *)View, File.filesize), "");
565 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
566 object::IRObjectFile::createIRObjectFile(BufferRef, Context);
568 if (std::error_code EC = ObjOrErr.getError())
569 message(LDPL_FATAL, "Could not read bitcode from file : %s",
570 EC.message().c_str());
572 if (release_input_file(F.handle) != LDPS_OK)
573 message(LDPL_FATAL, "Failed to release file information");
575 object::IRObjectFile &Obj = **ObjOrErr;
577 Module &M = Obj.getModule();
579 SmallPtrSet<GlobalValue *, 8> Used;
580 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
582 DenseSet<GlobalValue *> Drop;
583 std::vector<GlobalAlias *> KeptAliases;
586 for (auto &ObjSym : Obj.symbols()) {
587 if (shouldSkip(ObjSym.getFlags()))
589 ld_plugin_symbol &Sym = F.syms[SymNum];
592 ld_plugin_symbol_resolution Resolution =
593 (ld_plugin_symbol_resolution)Sym.resolution;
595 if (options::generate_api_file)
596 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
598 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
600 continue; // Asm symbol.
602 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
603 // Common linkage is special. There is no single symbol that wins the
604 // resolution. Instead we have to collect the maximum alignment and size.
605 // The IR linker does that for us if we just pass it every common GV.
606 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
607 // internalize once the IR linker has done its job.
611 switch (Resolution) {
613 llvm_unreachable("Unexpected resolution");
615 case LDPR_RESOLVED_IR:
616 case LDPR_RESOLVED_EXEC:
617 case LDPR_RESOLVED_DYN:
619 assert(GV->isDeclarationForLinker());
622 case LDPR_PREVAILING_DEF_IRONLY: {
623 keepGlobalValue(*GV, KeptAliases);
624 if (!Used.count(GV)) {
625 // Since we use the regular lib/Linker, we cannot just internalize GV
626 // now or it will not be copied to the merged module. Instead we force
627 // it to be copied and then internalize it.
628 Internalize.insert(GV->getName());
633 case LDPR_PREVAILING_DEF:
634 keepGlobalValue(*GV, KeptAliases);
637 case LDPR_PREEMPTED_IR:
638 // Gold might have selected a linkonce_odr and preempted a weak_odr.
639 // In that case we have to make sure we don't end up internalizing it.
640 if (!GV->isDiscardableIfUnused())
641 Maybe.erase(GV->getName());
644 case LDPR_PREEMPTED_REG:
648 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
649 // We can only check for address uses after we merge the modules. The
650 // reason is that this GV might have a copy in another module
651 // and in that module the address might be significant, but that
652 // copy will be LDPR_PREEMPTED_IR.
653 if (GV->hasLinkOnceODRLinkage())
654 Maybe.insert(GV->getName());
655 keepGlobalValue(*GV, KeptAliases);
661 free(Sym.comdat_key);
663 Sym.comdat_key = nullptr;
666 ValueToValueMapTy VM;
667 LocalValueMaterializer Materializer(Drop);
668 for (GlobalAlias *GA : KeptAliases) {
669 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
670 // expression is being dropped. If that is the case, that GV must be copied.
671 Constant *Aliasee = GA->getAliasee();
672 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
673 if (Aliasee != Replacement)
674 GA->setAliasee(Replacement);
677 for (auto *GV : Drop)
680 return Obj.takeModule();
683 static void runLTOPasses(Module &M, TargetMachine &TM) {
685 PassManagerBuilder PMB;
686 PMB.LibraryInfo = new TargetLibraryInfo(Triple(TM.getTargetTriple()));
687 PMB.Inliner = createFunctionInliningPass();
688 PMB.VerifyInput = true;
689 PMB.VerifyOutput = true;
690 PMB.LoopVectorize = true;
691 PMB.SLPVectorize = true;
692 PMB.populateLTOPassManager(passes, &TM);
696 static void saveBCFile(StringRef Path, Module &M) {
698 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
700 message(LDPL_FATAL, "Failed to write the output file.");
701 WriteBitcodeToFile(&M, OS);
704 static void codegen(Module &M) {
705 const std::string &TripleStr = M.getTargetTriple();
706 Triple TheTriple(TripleStr);
709 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
711 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
713 if (unsigned NumOpts = options::extra.size())
714 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
716 SubtargetFeatures Features;
717 Features.getDefaultSubtargetFeatures(TheTriple);
718 for (const std::string &A : MAttrs)
719 Features.AddFeature(A);
721 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
722 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
723 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
724 CodeModel::Default, CodeGenOpt::Aggressive));
726 runLTOPasses(M, *TM);
728 if (options::TheOutputType == options::OT_SAVE_TEMPS)
729 saveBCFile(output_name + ".opt.bc", M);
731 PassManager CodeGenPasses;
732 CodeGenPasses.add(new DataLayoutPass());
734 SmallString<128> Filename;
736 if (options::obj_path.empty()) {
738 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
740 message(LDPL_FATAL, "Could not create temporary file: %s",
741 EC.message().c_str());
743 Filename = options::obj_path;
745 sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
747 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
751 raw_fd_ostream OS(FD, true);
752 formatted_raw_ostream FOS(OS);
754 if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
755 TargetMachine::CGFT_ObjectFile))
756 message(LDPL_FATAL, "Failed to setup codegen");
757 CodeGenPasses.run(M);
760 if (add_input_file(Filename.c_str()) != LDPS_OK)
762 "Unable to add .o file to the link. File left behind in: %s",
765 if (options::obj_path.empty())
766 Cleanup.push_back(Filename.c_str());
769 /// gold informs us that all symbols have been read. At this point, we use
770 /// get_symbols to see if any of our definitions have been overridden by a
771 /// native object file. Then, perform optimization and codegen.
772 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
777 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
778 Linker L(Combined.get());
780 std::string DefaultTriple = sys::getDefaultTargetTriple();
782 StringSet<> Internalize;
784 for (claimed_file &F : Modules) {
785 std::unique_ptr<Module> M =
786 getModuleForFile(Context, F, ApiFile, Internalize, Maybe);
787 if (!options::triple.empty())
788 M->setTargetTriple(options::triple.c_str());
789 else if (M->getTargetTriple().empty()) {
790 M->setTargetTriple(DefaultTriple);
793 if (L.linkInModule(M.get()))
794 message(LDPL_FATAL, "Failed to link module");
797 for (const auto &Name : Internalize) {
798 GlobalValue *GV = Combined->getNamedValue(Name.first());
803 for (const auto &Name : Maybe) {
804 GlobalValue *GV = Combined->getNamedValue(Name.first());
807 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
808 if (canBeOmittedFromSymbolTable(GV))
812 if (options::TheOutputType == options::OT_DISABLE)
815 if (options::TheOutputType != options::OT_NORMAL) {
817 if (options::TheOutputType == options::OT_BC_ONLY)
820 path = output_name + ".bc";
821 saveBCFile(path, *L.getModule());
822 if (options::TheOutputType == options::OT_BC_ONLY)
826 codegen(*L.getModule());
828 if (!options::extra_library_path.empty() &&
829 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
830 message(LDPL_FATAL, "Unable to set the extra library path.");
835 static ld_plugin_status all_symbols_read_hook(void) {
836 ld_plugin_status Ret;
837 if (!options::generate_api_file) {
838 Ret = allSymbolsReadHook(nullptr);
841 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
843 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
844 EC.message().c_str());
845 Ret = allSymbolsReadHook(&ApiFile);
850 if (options::TheOutputType == options::OT_BC_ONLY ||
851 options::TheOutputType == options::OT_DISABLE)
857 static ld_plugin_status cleanup_hook(void) {
858 for (std::string &Name : Cleanup) {
859 std::error_code EC = sys::fs::remove(Name);
861 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
862 EC.message().c_str());