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/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/CommandFlags.h"
23 #include "llvm/CodeGen/ParallelCG.h"
24 #include "llvm/IR/AutoUpgrade.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/Linker/Linker.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/Object/IRObjectFile.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Transforms/IPO.h"
42 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
43 #include "llvm/Transforms/Utils/GlobalStatus.h"
44 #include "llvm/Transforms/Utils/ModuleUtils.h"
45 #include "llvm/Transforms/Utils/ValueMapper.h"
47 #include <plugin-api.h>
48 #include <system_error>
52 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
53 // Precise and Debian Wheezy (binutils 2.23 is required)
62 std::vector<ld_plugin_symbol> syms;
66 static ld_plugin_status discard_message(int level, const char *format, ...) {
67 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
68 // callback in the transfer vector. This should never be called.
72 static ld_plugin_get_input_file get_input_file = nullptr;
73 static ld_plugin_release_input_file release_input_file = nullptr;
74 static ld_plugin_add_symbols add_symbols = nullptr;
75 static ld_plugin_get_symbols get_symbols = nullptr;
76 static ld_plugin_add_input_file add_input_file = nullptr;
77 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
78 static ld_plugin_get_view get_view = nullptr;
79 static ld_plugin_message message = discard_message;
80 static Reloc::Model RelocationModel = Reloc::Default;
81 static std::string output_name = "";
82 static std::list<claimed_file> Modules;
83 static std::vector<std::string> Cleanup;
84 static llvm::TargetOptions TargetOpts;
93 static bool generate_api_file = false;
94 static OutputType TheOutputType = OT_NORMAL;
95 static unsigned OptLevel = 2;
96 static unsigned Parallelism = 1;
97 static std::string obj_path;
98 static std::string extra_library_path;
99 static std::string triple;
100 static std::string mcpu;
101 // Additional options to pass into the code generator.
102 // Note: This array will contain all plugin options which are not claimed
103 // as plugin exclusive to pass to the code generator.
104 // For example, "generate-api-file" and "as"options are for the plugin
105 // use only and will not be passed.
106 static std::vector<const char *> extra;
108 static void process_plugin_option(const char *opt_)
112 llvm::StringRef opt = opt_;
114 if (opt == "generate-api-file") {
115 generate_api_file = true;
116 } else if (opt.startswith("mcpu=")) {
117 mcpu = opt.substr(strlen("mcpu="));
118 } else if (opt.startswith("extra-library-path=")) {
119 extra_library_path = opt.substr(strlen("extra_library_path="));
120 } else if (opt.startswith("mtriple=")) {
121 triple = opt.substr(strlen("mtriple="));
122 } else if (opt.startswith("obj-path=")) {
123 obj_path = opt.substr(strlen("obj-path="));
124 } else if (opt == "emit-llvm") {
125 TheOutputType = OT_BC_ONLY;
126 } else if (opt == "save-temps") {
127 TheOutputType = OT_SAVE_TEMPS;
128 } else if (opt == "disable-output") {
129 TheOutputType = OT_DISABLE;
130 } else if (opt.size() == 2 && opt[0] == 'O') {
131 if (opt[1] < '0' || opt[1] > '3')
132 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
133 OptLevel = opt[1] - '0';
134 } else if (opt.startswith("jobs=")) {
135 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
136 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
138 // Save this option to pass to the code generator.
139 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
142 extra.push_back("LLVMgold");
144 extra.push_back(opt_);
149 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
151 static ld_plugin_status all_symbols_read_hook(void);
152 static ld_plugin_status cleanup_hook(void);
154 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
155 ld_plugin_status onload(ld_plugin_tv *tv) {
156 InitializeAllTargetInfos();
157 InitializeAllTargets();
158 InitializeAllTargetMCs();
159 InitializeAllAsmParsers();
160 InitializeAllAsmPrinters();
162 // We're given a pointer to the first transfer vector. We read through them
163 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
164 // contain pointers to functions that we need to call to register our own
165 // hooks. The others are addresses of functions we can use to call into gold
168 bool registeredClaimFile = false;
169 bool RegisteredAllSymbolsRead = false;
171 for (; tv->tv_tag != LDPT_NULL; ++tv) {
172 switch (tv->tv_tag) {
173 case LDPT_OUTPUT_NAME:
174 output_name = tv->tv_u.tv_string;
176 case LDPT_LINKER_OUTPUT:
177 switch (tv->tv_u.tv_val) {
179 case LDPO_DYN: // .so
180 case LDPO_PIE: // position independent executable
181 RelocationModel = Reloc::PIC_;
183 case LDPO_EXEC: // .exe
184 RelocationModel = Reloc::Static;
187 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
192 options::process_plugin_option(tv->tv_u.tv_string);
194 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
195 ld_plugin_register_claim_file callback;
196 callback = tv->tv_u.tv_register_claim_file;
198 if (callback(claim_file_hook) != LDPS_OK)
201 registeredClaimFile = true;
203 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
204 ld_plugin_register_all_symbols_read callback;
205 callback = tv->tv_u.tv_register_all_symbols_read;
207 if (callback(all_symbols_read_hook) != LDPS_OK)
210 RegisteredAllSymbolsRead = true;
212 case LDPT_REGISTER_CLEANUP_HOOK: {
213 ld_plugin_register_cleanup callback;
214 callback = tv->tv_u.tv_register_cleanup;
216 if (callback(cleanup_hook) != LDPS_OK)
219 case LDPT_GET_INPUT_FILE:
220 get_input_file = tv->tv_u.tv_get_input_file;
222 case LDPT_RELEASE_INPUT_FILE:
223 release_input_file = tv->tv_u.tv_release_input_file;
225 case LDPT_ADD_SYMBOLS:
226 add_symbols = tv->tv_u.tv_add_symbols;
228 case LDPT_GET_SYMBOLS_V2:
229 get_symbols = tv->tv_u.tv_get_symbols;
231 case LDPT_ADD_INPUT_FILE:
232 add_input_file = tv->tv_u.tv_add_input_file;
234 case LDPT_SET_EXTRA_LIBRARY_PATH:
235 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
238 get_view = tv->tv_u.tv_get_view;
241 message = tv->tv_u.tv_message;
248 if (!registeredClaimFile) {
249 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
253 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
257 if (!RegisteredAllSymbolsRead)
260 if (!get_input_file) {
261 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
264 if (!release_input_file) {
265 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
272 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
273 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
274 return GA->getBaseObject();
275 return cast<GlobalObject>(&GV);
278 static bool shouldSkip(uint32_t Symflags) {
279 if (!(Symflags & object::BasicSymbolRef::SF_Global))
281 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
286 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
287 if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
288 std::error_code EC = BDI->getError();
289 if (EC == BitcodeError::InvalidBitcodeSignature)
293 std::string ErrStorage;
295 raw_string_ostream OS(ErrStorage);
296 DiagnosticPrinterRawOStream DP(OS);
299 ld_plugin_level Level;
300 switch (DI.getSeverity()) {
302 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
304 llvm_unreachable("Fatal doesn't return.");
306 Level = LDPL_WARNING;
313 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
316 /// Called by gold to see whether this file is one that our plugin can handle.
317 /// We'll try to open it and register all the symbols with add_symbol if
319 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
322 MemoryBufferRef BufferRef;
323 std::unique_ptr<MemoryBuffer> Buffer;
326 if (get_view(file->handle, &view) != LDPS_OK) {
327 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
331 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
334 // Gold has found what might be IR part-way inside of a file, such as
337 offset = file->offset;
339 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
340 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
342 if (std::error_code EC = BufferOrErr.getError()) {
343 message(LDPL_ERROR, EC.message().c_str());
346 Buffer = std::move(BufferOrErr.get());
347 BufferRef = Buffer->getMemBufferRef();
350 Context.setDiagnosticHandler(diagnosticHandler);
351 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
352 object::IRObjectFile::create(BufferRef, Context);
353 std::error_code EC = ObjOrErr.getError();
354 if (EC == object::object_error::invalid_file_type ||
355 EC == object::object_error::bitcode_section_not_found)
361 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
362 EC.message().c_str());
365 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
367 Modules.resize(Modules.size() + 1);
368 claimed_file &cf = Modules.back();
370 cf.handle = file->handle;
372 for (auto &Sym : Obj->symbols()) {
373 uint32_t Symflags = Sym.getFlags();
374 if (shouldSkip(Symflags))
377 cf.syms.push_back(ld_plugin_symbol());
378 ld_plugin_symbol &sym = cf.syms.back();
379 sym.version = nullptr;
381 SmallString<64> Name;
383 raw_svector_ostream OS(Name);
386 sym.name = strdup(Name.c_str());
388 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
390 sym.visibility = LDPV_DEFAULT;
392 switch (GV->getVisibility()) {
393 case GlobalValue::DefaultVisibility:
394 sym.visibility = LDPV_DEFAULT;
396 case GlobalValue::HiddenVisibility:
397 sym.visibility = LDPV_HIDDEN;
399 case GlobalValue::ProtectedVisibility:
400 sym.visibility = LDPV_PROTECTED;
405 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
406 sym.def = LDPK_UNDEF;
407 if (GV && GV->hasExternalWeakLinkage())
408 sym.def = LDPK_WEAKUNDEF;
412 assert(!GV->hasExternalWeakLinkage() &&
413 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
414 if (GV->hasCommonLinkage())
415 sym.def = LDPK_COMMON;
416 else if (GV->isWeakForLinker())
417 sym.def = LDPK_WEAKDEF;
422 sym.comdat_key = nullptr;
424 const GlobalObject *Base = getBaseObject(*GV);
426 message(LDPL_FATAL, "Unable to determine comdat of alias!");
427 const Comdat *C = Base->getComdat();
429 sym.comdat_key = strdup(C->getName().str().c_str());
430 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
431 sym.comdat_key = strdup(sym.name);
434 sym.resolution = LDPR_UNKNOWN;
437 if (!cf.syms.empty()) {
438 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
439 message(LDPL_ERROR, "Unable to add symbols!");
447 static void keepGlobalValue(GlobalValue &GV,
448 std::vector<GlobalAlias *> &KeptAliases) {
449 assert(!GV.hasLocalLinkage());
451 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
452 KeptAliases.push_back(GA);
454 switch (GV.getLinkage()) {
457 case GlobalValue::LinkOnceAnyLinkage:
458 GV.setLinkage(GlobalValue::WeakAnyLinkage);
460 case GlobalValue::LinkOnceODRLinkage:
461 GV.setLinkage(GlobalValue::WeakODRLinkage);
465 assert(!GV.isDiscardableIfUnused());
468 static void internalize(GlobalValue &GV) {
469 if (GV.isDeclarationForLinker())
470 return; // We get here if there is a matching asm definition.
471 if (!GV.hasLocalLinkage())
472 GV.setLinkage(GlobalValue::InternalLinkage);
475 static void drop(GlobalValue &GV) {
476 if (auto *F = dyn_cast<Function>(&GV)) {
478 F->setComdat(nullptr); // Should deleteBody do this?
482 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
483 Var->setInitializer(nullptr);
485 GlobalValue::ExternalLinkage); // Should setInitializer do this?
486 Var->setComdat(nullptr); // and this?
490 auto &Alias = cast<GlobalAlias>(GV);
491 Module &M = *Alias.getParent();
492 PointerType &Ty = *cast<PointerType>(Alias.getType());
493 GlobalValue::LinkageTypes L = Alias.getLinkage();
495 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
496 /*Initializer*/ nullptr);
497 Var->takeName(&Alias);
498 Alias.replaceAllUsesWith(Var);
499 Alias.eraseFromParent();
502 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
508 case LDPR_PREVAILING_DEF:
509 return "PREVAILING_DEF";
510 case LDPR_PREVAILING_DEF_IRONLY:
511 return "PREVAILING_DEF_IRONLY";
512 case LDPR_PREEMPTED_REG:
513 return "PREEMPTED_REG";
514 case LDPR_PREEMPTED_IR:
515 return "PREEMPTED_IR";
516 case LDPR_RESOLVED_IR:
517 return "RESOLVED_IR";
518 case LDPR_RESOLVED_EXEC:
519 return "RESOLVED_EXEC";
520 case LDPR_RESOLVED_DYN:
521 return "RESOLVED_DYN";
522 case LDPR_PREVAILING_DEF_IRONLY_EXP:
523 return "PREVAILING_DEF_IRONLY_EXP";
525 llvm_unreachable("Unknown resolution");
529 class LocalValueMaterializer : public ValueMaterializer {
530 DenseSet<GlobalValue *> &Dropped;
531 DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
534 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
535 Value *materializeValueFor(Value *V) override;
539 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
540 auto *GO = dyn_cast<GlobalObject>(V);
544 auto I = LocalVersions.find(GO);
545 if (I != LocalVersions.end())
548 if (!Dropped.count(GO))
551 Module &M = *GO->getParent();
552 GlobalValue::LinkageTypes L = GO->getLinkage();
553 GlobalObject *Declaration;
554 if (auto *F = dyn_cast<Function>(GO)) {
555 Declaration = Function::Create(F->getFunctionType(), L, "", &M);
557 auto *Var = cast<GlobalVariable>(GO);
558 Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
559 Var->isConstant(), L,
560 /*Initializer*/ nullptr);
562 Declaration->takeName(GO);
563 Declaration->copyAttributesFrom(GO);
565 GO->setLinkage(GlobalValue::InternalLinkage);
566 GO->setName(Declaration->getName());
568 GO->replaceAllUsesWith(Declaration);
570 LocalVersions[Declaration] = GO;
575 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
576 LocalValueMaterializer *Materializer) {
577 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
580 static void freeSymName(ld_plugin_symbol &Sym) {
582 free(Sym.comdat_key);
584 Sym.comdat_key = nullptr;
587 static std::unique_ptr<Module>
588 getModuleForFile(LLVMContext &Context, claimed_file &F,
589 ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
590 StringSet<> &Internalize, StringSet<> &Maybe) {
592 if (get_symbols(F.handle, F.syms.size(), F.syms.data()) != LDPS_OK)
593 message(LDPL_FATAL, "Failed to get symbol information");
596 if (get_view(F.handle, &View) != LDPS_OK)
597 message(LDPL_FATAL, "Failed to get a view of file");
599 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
601 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
602 object::IRObjectFile::create(BufferRef, Context);
604 if (std::error_code EC = ObjOrErr.getError())
605 message(LDPL_FATAL, "Could not read bitcode from file : %s",
606 EC.message().c_str());
608 object::IRObjectFile &Obj = **ObjOrErr;
610 Module &M = Obj.getModule();
612 M.materializeMetadata();
615 SmallPtrSet<GlobalValue *, 8> Used;
616 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
618 DenseSet<GlobalValue *> Drop;
619 std::vector<GlobalAlias *> KeptAliases;
622 for (auto &ObjSym : Obj.symbols()) {
623 if (shouldSkip(ObjSym.getFlags()))
625 ld_plugin_symbol &Sym = F.syms[SymNum];
628 ld_plugin_symbol_resolution Resolution =
629 (ld_plugin_symbol_resolution)Sym.resolution;
631 if (options::generate_api_file)
632 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
634 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
637 continue; // Asm symbol.
640 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
641 // Common linkage is special. There is no single symbol that wins the
642 // resolution. Instead we have to collect the maximum alignment and size.
643 // The IR linker does that for us if we just pass it every common GV.
644 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
645 // internalize once the IR linker has done its job.
650 switch (Resolution) {
652 llvm_unreachable("Unexpected resolution");
654 case LDPR_RESOLVED_IR:
655 case LDPR_RESOLVED_EXEC:
656 case LDPR_RESOLVED_DYN:
657 assert(GV->isDeclarationForLinker());
661 if (!GV->isDeclarationForLinker()) {
662 assert(GV->hasComdat());
667 case LDPR_PREVAILING_DEF_IRONLY: {
668 keepGlobalValue(*GV, KeptAliases);
669 if (!Used.count(GV)) {
670 // Since we use the regular lib/Linker, we cannot just internalize GV
671 // now or it will not be copied to the merged module. Instead we force
672 // it to be copied and then internalize it.
673 Internalize.insert(GV->getName());
678 case LDPR_PREVAILING_DEF:
679 keepGlobalValue(*GV, KeptAliases);
682 case LDPR_PREEMPTED_IR:
683 // Gold might have selected a linkonce_odr and preempted a weak_odr.
684 // In that case we have to make sure we don't end up internalizing it.
685 if (!GV->isDiscardableIfUnused())
686 Maybe.erase(GV->getName());
689 case LDPR_PREEMPTED_REG:
693 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
694 // We can only check for address uses after we merge the modules. The
695 // reason is that this GV might have a copy in another module
696 // and in that module the address might be significant, but that
697 // copy will be LDPR_PREEMPTED_IR.
698 if (GV->hasLinkOnceODRLinkage())
699 Maybe.insert(GV->getName());
700 keepGlobalValue(*GV, KeptAliases);
708 ValueToValueMapTy VM;
709 LocalValueMaterializer Materializer(Drop);
710 for (GlobalAlias *GA : KeptAliases) {
711 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
712 // expression is being dropped. If that is the case, that GV must be copied.
713 Constant *Aliasee = GA->getAliasee();
714 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
715 GA->setAliasee(Replacement);
718 for (auto *GV : Drop)
721 return Obj.takeModule();
724 static void runLTOPasses(Module &M, TargetMachine &TM) {
725 M.setDataLayout(TM.createDataLayout());
727 legacy::PassManager passes;
728 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
730 PassManagerBuilder PMB;
731 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
732 PMB.Inliner = createFunctionInliningPass();
733 PMB.VerifyInput = true;
734 PMB.VerifyOutput = true;
735 PMB.LoopVectorize = true;
736 PMB.SLPVectorize = true;
737 PMB.OptLevel = options::OptLevel;
738 PMB.populateLTOPassManager(passes);
742 static void saveBCFile(StringRef Path, Module &M) {
744 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
746 message(LDPL_FATAL, "Failed to write the output file.");
747 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
750 static void codegen(std::unique_ptr<Module> M) {
751 const std::string &TripleStr = M->getTargetTriple();
752 Triple TheTriple(TripleStr);
755 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
757 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
759 if (unsigned NumOpts = options::extra.size())
760 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
762 SubtargetFeatures Features;
763 Features.getDefaultSubtargetFeatures(TheTriple);
764 for (const std::string &A : MAttrs)
765 Features.AddFeature(A);
767 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
768 CodeGenOpt::Level CGOptLevel;
769 switch (options::OptLevel) {
771 CGOptLevel = CodeGenOpt::None;
774 CGOptLevel = CodeGenOpt::Less;
777 CGOptLevel = CodeGenOpt::Default;
780 CGOptLevel = CodeGenOpt::Aggressive;
783 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
784 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
785 CodeModel::Default, CGOptLevel));
787 runLTOPasses(*M, *TM);
789 if (options::TheOutputType == options::OT_SAVE_TEMPS)
790 saveBCFile(output_name + ".opt.bc", *M);
792 SmallString<128> Filename;
793 if (!options::obj_path.empty())
794 Filename = options::obj_path;
795 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
796 Filename = output_name + ".o";
798 std::vector<SmallString<128>> Filenames(options::Parallelism);
799 bool TempOutFile = Filename.empty();
801 // Open a file descriptor for each backend thread. This is done in a block
802 // so that the output file descriptors are closed before gold opens them.
803 std::list<llvm::raw_fd_ostream> OSs;
804 std::vector<llvm::raw_pwrite_stream *> OSPtrs(options::Parallelism);
805 for (unsigned I = 0; I != options::Parallelism; ++I) {
809 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filenames[I]);
811 message(LDPL_FATAL, "Could not create temporary file: %s",
812 EC.message().c_str());
814 Filenames[I] = Filename;
815 if (options::Parallelism != 1)
816 Filenames[I] += utostr(I);
818 sys::fs::openFileForWrite(Filenames[I], FD, sys::fs::F_None);
820 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
822 OSs.emplace_back(FD, true);
823 OSPtrs[I] = &OSs.back();
826 // Run backend threads.
827 splitCodeGen(std::move(M), OSPtrs, options::mcpu, Features.getString(),
828 Options, RelocationModel, CodeModel::Default, CGOptLevel);
831 for (auto &Filename : Filenames) {
832 if (add_input_file(Filename.c_str()) != LDPS_OK)
834 "Unable to add .o file to the link. File left behind in: %s",
837 Cleanup.push_back(Filename.c_str());
841 /// gold informs us that all symbols have been read. At this point, we use
842 /// get_symbols to see if any of our definitions have been overridden by a
843 /// native object file. Then, perform optimization and codegen.
844 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
849 Context.setDiagnosticHandler(diagnosticHandler, nullptr, true);
851 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
852 Linker L(Combined.get());
854 std::string DefaultTriple = sys::getDefaultTargetTriple();
856 StringSet<> Internalize;
858 for (claimed_file &F : Modules) {
859 ld_plugin_input_file File;
860 if (get_input_file(F.handle, &File) != LDPS_OK)
861 message(LDPL_FATAL, "Failed to get file information");
862 std::unique_ptr<Module> M =
863 getModuleForFile(Context, F, File, ApiFile, Internalize, Maybe);
864 if (!options::triple.empty())
865 M->setTargetTriple(options::triple.c_str());
866 else if (M->getTargetTriple().empty()) {
867 M->setTargetTriple(DefaultTriple);
870 if (L.linkInModule(M.get()))
871 message(LDPL_FATAL, "Failed to link module");
872 if (release_input_file(F.handle) != LDPS_OK)
873 message(LDPL_FATAL, "Failed to release file information");
876 for (const auto &Name : Internalize) {
877 GlobalValue *GV = Combined->getNamedValue(Name.first());
882 for (const auto &Name : Maybe) {
883 GlobalValue *GV = Combined->getNamedValue(Name.first());
886 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
887 if (canBeOmittedFromSymbolTable(GV))
891 if (options::TheOutputType == options::OT_DISABLE)
894 if (options::TheOutputType != options::OT_NORMAL) {
896 if (options::TheOutputType == options::OT_BC_ONLY)
899 path = output_name + ".bc";
900 saveBCFile(path, *L.getModule());
901 if (options::TheOutputType == options::OT_BC_ONLY)
905 codegen(std::move(Combined));
907 if (!options::extra_library_path.empty() &&
908 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
909 message(LDPL_FATAL, "Unable to set the extra library path.");
914 static ld_plugin_status all_symbols_read_hook(void) {
915 ld_plugin_status Ret;
916 if (!options::generate_api_file) {
917 Ret = allSymbolsReadHook(nullptr);
920 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
922 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
923 EC.message().c_str());
924 Ret = allSymbolsReadHook(&ApiFile);
929 if (options::TheOutputType == options::OT_BC_ONLY ||
930 options::TheOutputType == options::OT_DISABLE) {
931 if (options::TheOutputType == options::OT_DISABLE)
932 // Remove the output file here since ld.bfd creates the output file
934 sys::fs::remove(output_name);
941 static ld_plugin_status cleanup_hook(void) {
942 for (std::string &Name : Cleanup) {
943 std::error_code EC = sys::fs::remove(Name);
945 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
946 EC.message().c_str());