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/IR/Constants.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/DiagnosticPrinter.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/LegacyPassManager.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/Linker/Linker.h"
31 #include "llvm/MC/SubtargetFeature.h"
32 #include "llvm/Object/IRObjectFile.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Transforms/IPO.h"
40 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
41 #include "llvm/Transforms/Utils/GlobalStatus.h"
42 #include "llvm/Transforms/Utils/ModuleUtils.h"
43 #include "llvm/Transforms/Utils/ValueMapper.h"
45 #include <plugin-api.h>
46 #include <system_error>
50 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
51 // Precise and Debian Wheezy (binutils 2.23 is required)
60 std::vector<ld_plugin_symbol> syms;
64 static ld_plugin_status discard_message(int level, const char *format, ...) {
65 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
66 // callback in the transfer vector. This should never be called.
70 static ld_plugin_get_input_file get_input_file = nullptr;
71 static ld_plugin_release_input_file release_input_file = nullptr;
72 static ld_plugin_add_symbols add_symbols = nullptr;
73 static ld_plugin_get_symbols get_symbols = nullptr;
74 static ld_plugin_add_input_file add_input_file = nullptr;
75 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
76 static ld_plugin_get_view get_view = nullptr;
77 static ld_plugin_message message = discard_message;
78 static Reloc::Model RelocationModel = Reloc::Default;
79 static std::string output_name = "";
80 static std::list<claimed_file> Modules;
81 static std::vector<std::string> Cleanup;
82 static llvm::TargetOptions TargetOpts;
91 static bool generate_api_file = false;
92 static OutputType TheOutputType = OT_NORMAL;
93 static unsigned OptLevel = 2;
94 static std::string obj_path;
95 static std::string extra_library_path;
96 static std::string triple;
97 static std::string mcpu;
98 // Additional options to pass into the code generator.
99 // Note: This array will contain all plugin options which are not claimed
100 // as plugin exclusive to pass to the code generator.
101 // For example, "generate-api-file" and "as"options are for the plugin
102 // use only and will not be passed.
103 static std::vector<const char *> extra;
105 static void process_plugin_option(const char* opt_)
109 llvm::StringRef opt = opt_;
111 if (opt == "generate-api-file") {
112 generate_api_file = true;
113 } else if (opt.startswith("mcpu=")) {
114 mcpu = opt.substr(strlen("mcpu="));
115 } else if (opt.startswith("extra-library-path=")) {
116 extra_library_path = opt.substr(strlen("extra_library_path="));
117 } else if (opt.startswith("mtriple=")) {
118 triple = opt.substr(strlen("mtriple="));
119 } else if (opt.startswith("obj-path=")) {
120 obj_path = opt.substr(strlen("obj-path="));
121 } else if (opt == "emit-llvm") {
122 TheOutputType = OT_BC_ONLY;
123 } else if (opt == "save-temps") {
124 TheOutputType = OT_SAVE_TEMPS;
125 } else if (opt == "disable-output") {
126 TheOutputType = OT_DISABLE;
127 } else if (opt.size() == 2 && opt[0] == 'O') {
128 if (opt[1] < '0' || opt[1] > '3')
129 report_fatal_error("Optimization level must be between 0 and 3");
130 OptLevel = opt[1] - '0';
132 // Save this option to pass to the code generator.
133 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
136 extra.push_back("LLVMgold");
138 extra.push_back(opt_);
143 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
145 static ld_plugin_status all_symbols_read_hook(void);
146 static ld_plugin_status cleanup_hook(void);
148 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
149 ld_plugin_status onload(ld_plugin_tv *tv) {
150 InitializeAllTargetInfos();
151 InitializeAllTargets();
152 InitializeAllTargetMCs();
153 InitializeAllAsmParsers();
154 InitializeAllAsmPrinters();
156 // We're given a pointer to the first transfer vector. We read through them
157 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
158 // contain pointers to functions that we need to call to register our own
159 // hooks. The others are addresses of functions we can use to call into gold
162 bool registeredClaimFile = false;
163 bool RegisteredAllSymbolsRead = false;
165 for (; tv->tv_tag != LDPT_NULL; ++tv) {
166 switch (tv->tv_tag) {
167 case LDPT_OUTPUT_NAME:
168 output_name = tv->tv_u.tv_string;
170 case LDPT_LINKER_OUTPUT:
171 switch (tv->tv_u.tv_val) {
173 case LDPO_DYN: // .so
174 case LDPO_PIE: // position independent executable
175 RelocationModel = Reloc::PIC_;
177 case LDPO_EXEC: // .exe
178 RelocationModel = Reloc::Static;
181 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
186 options::process_plugin_option(tv->tv_u.tv_string);
188 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
189 ld_plugin_register_claim_file callback;
190 callback = tv->tv_u.tv_register_claim_file;
192 if (callback(claim_file_hook) != LDPS_OK)
195 registeredClaimFile = true;
197 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
198 ld_plugin_register_all_symbols_read callback;
199 callback = tv->tv_u.tv_register_all_symbols_read;
201 if (callback(all_symbols_read_hook) != LDPS_OK)
204 RegisteredAllSymbolsRead = true;
206 case LDPT_REGISTER_CLEANUP_HOOK: {
207 ld_plugin_register_cleanup callback;
208 callback = tv->tv_u.tv_register_cleanup;
210 if (callback(cleanup_hook) != LDPS_OK)
213 case LDPT_GET_INPUT_FILE:
214 get_input_file = tv->tv_u.tv_get_input_file;
216 case LDPT_RELEASE_INPUT_FILE:
217 release_input_file = tv->tv_u.tv_release_input_file;
219 case LDPT_ADD_SYMBOLS:
220 add_symbols = tv->tv_u.tv_add_symbols;
222 case LDPT_GET_SYMBOLS_V2:
223 get_symbols = tv->tv_u.tv_get_symbols;
225 case LDPT_ADD_INPUT_FILE:
226 add_input_file = tv->tv_u.tv_add_input_file;
228 case LDPT_SET_EXTRA_LIBRARY_PATH:
229 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
232 get_view = tv->tv_u.tv_get_view;
235 message = tv->tv_u.tv_message;
242 if (!registeredClaimFile) {
243 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
247 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
251 if (!RegisteredAllSymbolsRead)
254 if (!get_input_file) {
255 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
258 if (!release_input_file) {
259 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
266 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
267 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
268 return GA->getBaseObject();
269 return cast<GlobalObject>(&GV);
272 static bool shouldSkip(uint32_t Symflags) {
273 if (!(Symflags & object::BasicSymbolRef::SF_Global))
275 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
280 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
281 if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
282 std::error_code EC = BDI->getError();
283 if (EC == BitcodeError::InvalidBitcodeSignature)
287 std::string ErrStorage;
289 raw_string_ostream OS(ErrStorage);
290 DiagnosticPrinterRawOStream DP(OS);
293 ld_plugin_level Level;
294 switch (DI.getSeverity()) {
296 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
298 llvm_unreachable("Fatal doesn't return.");
300 Level = LDPL_WARNING;
307 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
310 /// Called by gold to see whether this file is one that our plugin can handle.
311 /// We'll try to open it and register all the symbols with add_symbol if
313 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
316 MemoryBufferRef BufferRef;
317 std::unique_ptr<MemoryBuffer> Buffer;
320 if (get_view(file->handle, &view) != LDPS_OK) {
321 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
324 BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
327 // Gold has found what might be IR part-way inside of a file, such as
330 offset = file->offset;
332 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
333 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
335 if (std::error_code EC = BufferOrErr.getError()) {
336 message(LDPL_ERROR, EC.message().c_str());
339 Buffer = std::move(BufferOrErr.get());
340 BufferRef = Buffer->getMemBufferRef();
343 Context.setDiagnosticHandler(diagnosticHandler);
344 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
345 object::IRObjectFile::create(BufferRef, Context);
346 std::error_code EC = ObjOrErr.getError();
347 if (EC == object::object_error::invalid_file_type ||
348 EC == object::object_error::bitcode_section_not_found)
354 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
355 EC.message().c_str());
358 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
360 Modules.resize(Modules.size() + 1);
361 claimed_file &cf = Modules.back();
363 cf.handle = file->handle;
365 for (auto &Sym : Obj->symbols()) {
366 uint32_t Symflags = Sym.getFlags();
367 if (shouldSkip(Symflags))
370 cf.syms.push_back(ld_plugin_symbol());
371 ld_plugin_symbol &sym = cf.syms.back();
372 sym.version = nullptr;
374 SmallString<64> Name;
376 raw_svector_ostream OS(Name);
379 sym.name = strdup(Name.c_str());
381 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
383 sym.visibility = LDPV_DEFAULT;
385 switch (GV->getVisibility()) {
386 case GlobalValue::DefaultVisibility:
387 sym.visibility = LDPV_DEFAULT;
389 case GlobalValue::HiddenVisibility:
390 sym.visibility = LDPV_HIDDEN;
392 case GlobalValue::ProtectedVisibility:
393 sym.visibility = LDPV_PROTECTED;
398 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
399 sym.def = LDPK_UNDEF;
400 if (GV && GV->hasExternalWeakLinkage())
401 sym.def = LDPK_WEAKUNDEF;
405 assert(!GV->hasExternalWeakLinkage() &&
406 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
407 if (GV->hasCommonLinkage())
408 sym.def = LDPK_COMMON;
409 else if (GV->isWeakForLinker())
410 sym.def = LDPK_WEAKDEF;
415 sym.comdat_key = nullptr;
417 const GlobalObject *Base = getBaseObject(*GV);
419 message(LDPL_FATAL, "Unable to determine comdat of alias!");
420 const Comdat *C = Base->getComdat();
422 sym.comdat_key = strdup(C->getName().str().c_str());
423 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
424 sym.comdat_key = strdup(sym.name);
427 sym.resolution = LDPR_UNKNOWN;
430 if (!cf.syms.empty()) {
431 if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
432 message(LDPL_ERROR, "Unable to add symbols!");
440 static void keepGlobalValue(GlobalValue &GV,
441 std::vector<GlobalAlias *> &KeptAliases) {
442 assert(!GV.hasLocalLinkage());
444 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
445 KeptAliases.push_back(GA);
447 switch (GV.getLinkage()) {
450 case GlobalValue::LinkOnceAnyLinkage:
451 GV.setLinkage(GlobalValue::WeakAnyLinkage);
453 case GlobalValue::LinkOnceODRLinkage:
454 GV.setLinkage(GlobalValue::WeakODRLinkage);
458 assert(!GV.isDiscardableIfUnused());
461 static void internalize(GlobalValue &GV) {
462 if (GV.isDeclarationForLinker())
463 return; // We get here if there is a matching asm definition.
464 if (!GV.hasLocalLinkage())
465 GV.setLinkage(GlobalValue::InternalLinkage);
468 static void drop(GlobalValue &GV) {
469 if (auto *F = dyn_cast<Function>(&GV)) {
471 F->setComdat(nullptr); // Should deleteBody do this?
475 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
476 Var->setInitializer(nullptr);
478 GlobalValue::ExternalLinkage); // Should setInitializer do this?
479 Var->setComdat(nullptr); // and this?
483 auto &Alias = cast<GlobalAlias>(GV);
484 Module &M = *Alias.getParent();
485 PointerType &Ty = *cast<PointerType>(Alias.getType());
486 GlobalValue::LinkageTypes L = Alias.getLinkage();
488 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
489 /*Initializer*/ nullptr);
490 Var->takeName(&Alias);
491 Alias.replaceAllUsesWith(Var);
492 Alias.eraseFromParent();
495 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
501 case LDPR_PREVAILING_DEF:
502 return "PREVAILING_DEF";
503 case LDPR_PREVAILING_DEF_IRONLY:
504 return "PREVAILING_DEF_IRONLY";
505 case LDPR_PREEMPTED_REG:
506 return "PREEMPTED_REG";
507 case LDPR_PREEMPTED_IR:
508 return "PREEMPTED_IR";
509 case LDPR_RESOLVED_IR:
510 return "RESOLVED_IR";
511 case LDPR_RESOLVED_EXEC:
512 return "RESOLVED_EXEC";
513 case LDPR_RESOLVED_DYN:
514 return "RESOLVED_DYN";
515 case LDPR_PREVAILING_DEF_IRONLY_EXP:
516 return "PREVAILING_DEF_IRONLY_EXP";
518 llvm_unreachable("Unknown resolution");
522 class LocalValueMaterializer : public ValueMaterializer {
523 DenseSet<GlobalValue *> &Dropped;
524 DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
527 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
528 Value *materializeValueFor(Value *V) override;
532 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
533 auto *GO = dyn_cast<GlobalObject>(V);
537 auto I = LocalVersions.find(GO);
538 if (I != LocalVersions.end())
541 if (!Dropped.count(GO))
544 Module &M = *GO->getParent();
545 GlobalValue::LinkageTypes L = GO->getLinkage();
546 GlobalObject *Declaration;
547 if (auto *F = dyn_cast<Function>(GO)) {
548 Declaration = Function::Create(F->getFunctionType(), L, "", &M);
550 auto *Var = cast<GlobalVariable>(GO);
551 Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
552 Var->isConstant(), L,
553 /*Initializer*/ nullptr);
555 Declaration->takeName(GO);
556 Declaration->copyAttributesFrom(GO);
558 GO->setLinkage(GlobalValue::InternalLinkage);
559 GO->setName(Declaration->getName());
561 GO->replaceAllUsesWith(Declaration);
563 LocalVersions[Declaration] = GO;
568 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
569 LocalValueMaterializer *Materializer) {
570 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
573 static void freeSymName(ld_plugin_symbol &Sym) {
575 free(Sym.comdat_key);
577 Sym.comdat_key = nullptr;
580 static std::unique_ptr<Module>
581 getModuleForFile(LLVMContext &Context, claimed_file &F,
582 ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
583 StringSet<> &Internalize, StringSet<> &Maybe) {
585 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
586 message(LDPL_FATAL, "Failed to get symbol information");
589 if (get_view(F.handle, &View) != LDPS_OK)
590 message(LDPL_FATAL, "Failed to get a view of file");
592 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
594 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
595 object::IRObjectFile::create(BufferRef, Context);
597 if (std::error_code EC = ObjOrErr.getError())
598 message(LDPL_FATAL, "Could not read bitcode from file : %s",
599 EC.message().c_str());
601 object::IRObjectFile &Obj = **ObjOrErr;
603 Module &M = Obj.getModule();
605 // Fixme (pr23045). We would like to upgrade the metadata with something like
606 // Result->materializeMetadata();
607 // UpgradeDebugInfo(*Result);
608 // but that fails to drop old debug info from function bodies.
609 M.materializeAllPermanently();
611 SmallPtrSet<GlobalValue *, 8> Used;
612 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
614 DenseSet<GlobalValue *> Drop;
615 std::vector<GlobalAlias *> KeptAliases;
618 for (auto &ObjSym : Obj.symbols()) {
619 if (shouldSkip(ObjSym.getFlags()))
621 ld_plugin_symbol &Sym = F.syms[SymNum];
624 ld_plugin_symbol_resolution Resolution =
625 (ld_plugin_symbol_resolution)Sym.resolution;
627 if (options::generate_api_file)
628 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
630 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
633 continue; // Asm symbol.
636 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
637 // Common linkage is special. There is no single symbol that wins the
638 // resolution. Instead we have to collect the maximum alignment and size.
639 // The IR linker does that for us if we just pass it every common GV.
640 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
641 // internalize once the IR linker has done its job.
646 switch (Resolution) {
648 llvm_unreachable("Unexpected resolution");
650 case LDPR_RESOLVED_IR:
651 case LDPR_RESOLVED_EXEC:
652 case LDPR_RESOLVED_DYN:
653 assert(GV->isDeclarationForLinker());
657 if (!GV->isDeclarationForLinker()) {
658 assert(GV->hasComdat());
663 case LDPR_PREVAILING_DEF_IRONLY: {
664 keepGlobalValue(*GV, KeptAliases);
665 if (!Used.count(GV)) {
666 // Since we use the regular lib/Linker, we cannot just internalize GV
667 // now or it will not be copied to the merged module. Instead we force
668 // it to be copied and then internalize it.
669 Internalize.insert(GV->getName());
674 case LDPR_PREVAILING_DEF:
675 keepGlobalValue(*GV, KeptAliases);
678 case LDPR_PREEMPTED_IR:
679 // Gold might have selected a linkonce_odr and preempted a weak_odr.
680 // In that case we have to make sure we don't end up internalizing it.
681 if (!GV->isDiscardableIfUnused())
682 Maybe.erase(GV->getName());
685 case LDPR_PREEMPTED_REG:
689 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
690 // We can only check for address uses after we merge the modules. The
691 // reason is that this GV might have a copy in another module
692 // and in that module the address might be significant, but that
693 // copy will be LDPR_PREEMPTED_IR.
694 if (GV->hasLinkOnceODRLinkage())
695 Maybe.insert(GV->getName());
696 keepGlobalValue(*GV, KeptAliases);
704 ValueToValueMapTy VM;
705 LocalValueMaterializer Materializer(Drop);
706 for (GlobalAlias *GA : KeptAliases) {
707 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
708 // expression is being dropped. If that is the case, that GV must be copied.
709 Constant *Aliasee = GA->getAliasee();
710 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
711 GA->setAliasee(Replacement);
714 for (auto *GV : Drop)
717 return Obj.takeModule();
720 static void runLTOPasses(Module &M, TargetMachine &TM) {
721 if (const DataLayout *DL = TM.getDataLayout())
722 M.setDataLayout(*DL);
724 legacy::PassManager passes;
725 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
727 PassManagerBuilder PMB;
728 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
729 PMB.Inliner = createFunctionInliningPass();
730 PMB.VerifyInput = true;
731 PMB.VerifyOutput = true;
732 PMB.LoopVectorize = true;
733 PMB.SLPVectorize = true;
734 PMB.OptLevel = options::OptLevel;
735 PMB.populateLTOPassManager(passes);
739 static void saveBCFile(StringRef Path, Module &M) {
741 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
743 message(LDPL_FATAL, "Failed to write the output file.");
744 WriteBitcodeToFile(&M, OS);
747 static void codegen(Module &M) {
748 const std::string &TripleStr = M.getTargetTriple();
749 Triple TheTriple(TripleStr);
752 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
754 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
756 if (unsigned NumOpts = options::extra.size())
757 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
759 SubtargetFeatures Features;
760 Features.getDefaultSubtargetFeatures(TheTriple);
761 for (const std::string &A : MAttrs)
762 Features.AddFeature(A);
764 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
765 CodeGenOpt::Level CGOptLevel;
766 switch (options::OptLevel) {
768 CGOptLevel = CodeGenOpt::None;
771 CGOptLevel = CodeGenOpt::Less;
774 CGOptLevel = CodeGenOpt::Default;
777 CGOptLevel = CodeGenOpt::Aggressive;
780 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
781 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
782 CodeModel::Default, CGOptLevel));
784 runLTOPasses(M, *TM);
786 if (options::TheOutputType == options::OT_SAVE_TEMPS)
787 saveBCFile(output_name + ".opt.bc", M);
789 legacy::PassManager CodeGenPasses;
791 SmallString<128> Filename;
793 if (options::obj_path.empty()) {
795 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
797 message(LDPL_FATAL, "Could not create temporary file: %s",
798 EC.message().c_str());
800 Filename = options::obj_path;
802 sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
804 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
808 raw_fd_ostream OS(FD, true);
809 formatted_raw_ostream FOS(OS);
811 if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
812 TargetMachine::CGFT_ObjectFile))
813 message(LDPL_FATAL, "Failed to setup codegen");
814 CodeGenPasses.run(M);
817 if (add_input_file(Filename.c_str()) != LDPS_OK)
819 "Unable to add .o file to the link. File left behind in: %s",
822 if (options::obj_path.empty())
823 Cleanup.push_back(Filename.c_str());
826 /// gold informs us that all symbols have been read. At this point, we use
827 /// get_symbols to see if any of our definitions have been overridden by a
828 /// native object file. Then, perform optimization and codegen.
829 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
834 Context.setDiagnosticHandler(diagnosticHandler, nullptr, true);
836 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
837 Linker L(Combined.get());
839 std::string DefaultTriple = sys::getDefaultTargetTriple();
841 StringSet<> Internalize;
843 for (claimed_file &F : Modules) {
844 ld_plugin_input_file File;
845 if (get_input_file(F.handle, &File) != LDPS_OK)
846 message(LDPL_FATAL, "Failed to get file information");
847 std::unique_ptr<Module> M =
848 getModuleForFile(Context, F, File, ApiFile, Internalize, Maybe);
849 if (!options::triple.empty())
850 M->setTargetTriple(options::triple.c_str());
851 else if (M->getTargetTriple().empty()) {
852 M->setTargetTriple(DefaultTriple);
855 if (L.linkInModule(M.get()))
856 message(LDPL_FATAL, "Failed to link module");
857 if (release_input_file(F.handle) != LDPS_OK)
858 message(LDPL_FATAL, "Failed to release file information");
861 for (const auto &Name : Internalize) {
862 GlobalValue *GV = Combined->getNamedValue(Name.first());
867 for (const auto &Name : Maybe) {
868 GlobalValue *GV = Combined->getNamedValue(Name.first());
871 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
872 if (canBeOmittedFromSymbolTable(GV))
876 if (options::TheOutputType == options::OT_DISABLE)
879 if (options::TheOutputType != options::OT_NORMAL) {
881 if (options::TheOutputType == options::OT_BC_ONLY)
884 path = output_name + ".bc";
885 saveBCFile(path, *L.getModule());
886 if (options::TheOutputType == options::OT_BC_ONLY)
890 codegen(*L.getModule());
892 if (!options::extra_library_path.empty() &&
893 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
894 message(LDPL_FATAL, "Unable to set the extra library path.");
899 static ld_plugin_status all_symbols_read_hook(void) {
900 ld_plugin_status Ret;
901 if (!options::generate_api_file) {
902 Ret = allSymbolsReadHook(nullptr);
905 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
907 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
908 EC.message().c_str());
909 Ret = allSymbolsReadHook(&ApiFile);
914 if (options::TheOutputType == options::OT_BC_ONLY ||
915 options::TheOutputType == options::OT_DISABLE) {
916 if (options::TheOutputType == options::OT_DISABLE)
917 // Remove the output file here since ld.bfd creates the output file
919 sys::fs::remove(output_name);
926 static ld_plugin_status cleanup_hook(void) {
927 for (std::string &Name : Cleanup) {
928 std::error_code EC = sys::fs::remove(Name);
930 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
931 EC.message().c_str());