brintos

brintos / llvm-project-archived public Read only

0
0
Text · 44.0 KiB · 06045a6 Raw
1228 lines · cpp
1//===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization  ------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This is a gold plugin for LLVM. It provides an LLVM implementation of the10// interface described in http://gcc.gnu.org/wiki/whopr/driver .11//12//===----------------------------------------------------------------------===//13 14#include "llvm/ADT/ScopeExit.h"15#include "llvm/ADT/Statistic.h"16#include "llvm/Bitcode/BitcodeReader.h"17#include "llvm/Bitcode/BitcodeWriter.h"18#include "llvm/CodeGen/CommandFlags.h"19#include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H20#include "llvm/Config/llvm-config.h"21#include "llvm/IR/Constants.h"22#include "llvm/IR/DiagnosticPrinter.h"23#include "llvm/LTO/LTO.h"24#include "llvm/Object/Error.h"25#include "llvm/Remarks/HotnessThresholdParser.h"26#include "llvm/Support/CachePruning.h"27#include "llvm/Support/Caching.h"28#include "llvm/Support/CommandLine.h"29#include "llvm/Support/FileSystem.h"30#include "llvm/Support/ManagedStatic.h"31#include "llvm/Support/MemoryBuffer.h"32#include "llvm/Support/Path.h"33#include "llvm/Support/TargetSelect.h"34#include "llvm/Support/Threading.h"35#include "llvm/Support/TimeProfiler.h"36#include "llvm/Support/raw_ostream.h"37#include "llvm/TargetParser/Host.h"38#include <list>39#include <plugin-api.h>40#include <string>41#include <system_error>42#include <utility>43#include <vector>44 45// FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and46// Precise and Debian Wheezy (binutils 2.23 is required)47#define LDPO_PIE 348 49#define LDPT_GET_SYMBOLS_V3 2850 51// FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum52// required version.53#define LDPT_GET_WRAP_SYMBOLS 3254 55using namespace llvm;56using namespace lto;57 58static codegen::RegisterCodeGenFlags CodeGenFlags;59 60// FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum61// required version.62typedef enum ld_plugin_status (*ld_plugin_get_wrap_symbols)(63    uint64_t *num_symbols, const char ***wrap_symbol_list);64 65static ld_plugin_status discard_message(int level, const char *format, ...) {66  // Die loudly. Recent versions of Gold pass ld_plugin_message as the first67  // callback in the transfer vector. This should never be called.68  abort();69}70 71static ld_plugin_release_input_file release_input_file = nullptr;72static ld_plugin_get_input_file get_input_file = nullptr;73static ld_plugin_message message = discard_message;74static ld_plugin_get_wrap_symbols get_wrap_symbols = nullptr;75 76namespace {77struct claimed_file {78  void *handle;79  void *leader_handle;80  std::vector<ld_plugin_symbol> syms;81  off_t filesize;82  std::string name;83};84 85/// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.86struct PluginInputFile {87  void *Handle;88  std::unique_ptr<ld_plugin_input_file> File;89 90  PluginInputFile(void *Handle) : Handle(Handle) {91    File = std::make_unique<ld_plugin_input_file>();92    if (get_input_file(Handle, File.get()) != LDPS_OK)93      message(LDPL_FATAL, "Failed to get file information");94  }95  ~PluginInputFile() {96    // File would have been reset to nullptr if we moved this object97    // to a new owner.98    if (File)99      if (release_input_file(Handle) != LDPS_OK)100        message(LDPL_FATAL, "Failed to release file information");101  }102 103  ld_plugin_input_file &file() { return *File; }104 105  PluginInputFile(PluginInputFile &&RHS) = default;106  PluginInputFile &operator=(PluginInputFile &&RHS) = default;107};108 109struct ResolutionInfo {110  bool CanOmitFromDynSym = true;111  bool DefaultVisibility = true;112  bool CanInline = true;113  bool IsUsedInRegularObj = false;114};115 116}117 118static ld_plugin_add_symbols add_symbols = nullptr;119static ld_plugin_get_symbols get_symbols = nullptr;120static ld_plugin_add_input_file add_input_file = nullptr;121static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;122static ld_plugin_get_view get_view = nullptr;123static bool IsExecutable = false;124static bool SplitSections = true;125static std::optional<Reloc::Model> RelocationModel;126static std::string output_name = "";127static std::list<claimed_file> Modules;128static DenseMap<int, void *> FDToLeaderHandle;129static StringMap<ResolutionInfo> ResInfo;130static std::vector<std::string> Cleanup;131 132namespace options {133  enum OutputType {134    OT_NORMAL,135    OT_DISABLE,136    OT_BC_ONLY,137    OT_ASM_ONLY,138    OT_SAVE_TEMPS139  };140  static OutputType TheOutputType = OT_NORMAL;141  static unsigned OptLevel = 2;142  // Currently only affects ThinLTO, where the default is the max cores in the143  // system. See llvm::get_threadpool_strategy() for acceptable values.144  static std::string Parallelism;145  // Default regular LTO codegen parallelism (number of partitions).146  static unsigned ParallelCodeGenParallelismLevel = 1;147#ifdef NDEBUG148  static bool DisableVerify = true;149#else150  static bool DisableVerify = false;151#endif152  static std::string obj_path;153  static std::string extra_library_path;154  static std::string triple;155  static std::string mcpu;156  // Tells plugin to use unified lto157  static bool unifiedlto = false;158  // When the thinlto plugin option is specified, only read the function159  // the information from intermediate files and write a combined160  // global index for the ThinLTO backends.161  static bool thinlto = false;162  // If false, all ThinLTO backend compilations through code gen are performed163  // using multiple threads in the gold-plugin, before handing control back to164  // gold. If true, write individual backend index files which reflect165  // the import decisions, and exit afterwards. The assumption is166  // that the build system will launch the backend processes.167  static bool thinlto_index_only = false;168  // If non-empty, holds the name of a file in which to write the list of169  // oject files gold selected for inclusion in the link after symbol170  // resolution (i.e. they had selected symbols). This will only be non-empty171  // in the thinlto_index_only case. It is used to identify files, which may172  // have originally been within archive libraries specified via173  // --start-lib/--end-lib pairs, that should be included in the final174  // native link process (since intervening function importing and inlining175  // may change the symbol resolution detected in the final link and which176  // files to include out of --start-lib/--end-lib libraries as a result).177  static std::string thinlto_linked_objects_file;178  // If true, when generating individual index files for distributed backends,179  // also generate a "${bitcodefile}.imports" file at the same location for each180  // bitcode file, listing the files it imports from in plain text. This is to181  // support distributed build file staging.182  static bool thinlto_emit_imports_files = false;183  // Option to control where files for a distributed backend (the individual184  // index files and optional imports files) are created.185  // If specified, expects a string of the form "oldprefix:newprefix", and186  // instead of generating these files in the same directory path as the187  // corresponding bitcode file, will use a path formed by replacing the188  // bitcode file's path prefix matching oldprefix with newprefix.189  static std::string thinlto_prefix_replace;190  // Option to control the name of modules encoded in the individual index191  // files for a distributed backend. This enables the use of minimized192  // bitcode files for the thin link, assuming the name of the full bitcode193  // file used in the backend differs just in some part of the file suffix.194  // If specified, expects a string of the form "oldsuffix:newsuffix".195  static std::string thinlto_object_suffix_replace;196  // Optional path to a directory for caching ThinLTO objects.197  static std::string cache_dir;198  // Optional pruning policy for ThinLTO caches.199  static std::string cache_policy;200  // Additional options to pass into the code generator.201  // Note: This array will contain all plugin options which are not claimed202  // as plugin exclusive to pass to the code generator.203  static std::vector<const char *> extra;204  // Sample profile file path205  static std::string sample_profile;206  // Debug new pass manager207  static bool debug_pass_manager = false;208  // Directory to store the .dwo files.209  static std::string dwo_dir;210  /// Statistics output filename.211  static std::string stats_file;212  // Asserts that LTO link has whole program visibility213  static bool whole_program_visibility = false;214 215  // Optimization remarks filename, accepted passes and hotness options216  static std::string RemarksFilename;217  static std::string RemarksPasses;218  static bool RemarksWithHotness = false;219  static std::optional<uint64_t> RemarksHotnessThreshold = 0;220  static std::string RemarksFormat;221 222  // Context sensitive PGO options.223  static std::string cs_profile_path;224  static bool cs_pgo_gen = false;225 226  // When true, MergeFunctions pass is used in LTO link pipeline.227  static bool merge_functions = false;228 229  // Time trace options.230  static std::string time_trace_file;231  static unsigned time_trace_granularity = 500;232 233  static void process_plugin_option(const char *opt_)234  {235    if (opt_ == nullptr)236      return;237    llvm::StringRef opt = opt_;238 239    if (opt.consume_front("mcpu=")) {240      mcpu = std::string(opt);241    } else if (opt.consume_front("extra-library-path=")) {242      extra_library_path = std::string(opt);243    } else if (opt.consume_front("mtriple=")) {244      triple = std::string(opt);245    } else if (opt.consume_front("obj-path=")) {246      obj_path = std::string(opt);247    } else if (opt == "emit-llvm") {248      TheOutputType = OT_BC_ONLY;249    } else if (opt == "save-temps") {250      TheOutputType = OT_SAVE_TEMPS;251    } else if (opt == "disable-output") {252      TheOutputType = OT_DISABLE;253    } else if (opt == "emit-asm") {254      TheOutputType = OT_ASM_ONLY;255    } else if (opt == "unifiedlto") {256      unifiedlto = true;257    } else if (opt == "thinlto") {258      thinlto = true;259    } else if (opt == "thinlto-index-only") {260      thinlto_index_only = true;261    } else if (opt.consume_front("thinlto-index-only=")) {262      thinlto_index_only = true;263      thinlto_linked_objects_file = std::string(opt);264    } else if (opt == "thinlto-emit-imports-files") {265      thinlto_emit_imports_files = true;266    } else if (opt.consume_front("thinlto-prefix-replace=")) {267      thinlto_prefix_replace = std::string(opt);268      if (thinlto_prefix_replace.find(';') == std::string::npos)269        message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");270    } else if (opt.consume_front("thinlto-object-suffix-replace=")) {271      thinlto_object_suffix_replace = std::string(opt);272      if (thinlto_object_suffix_replace.find(';') == std::string::npos)273        message(LDPL_FATAL,274                "thinlto-object-suffix-replace expects 'old;new' format");275    } else if (opt.consume_front("cache-dir=")) {276      cache_dir = std::string(opt);277    } else if (opt.consume_front("cache-policy=")) {278      cache_policy = std::string(opt);279    } else if (opt.size() == 2 && opt[0] == 'O') {280      if (opt[1] < '0' || opt[1] > '3')281        message(LDPL_FATAL, "Optimization level must be between 0 and 3");282      OptLevel = opt[1] - '0';283    } else if (opt.consume_front("jobs=")) {284      Parallelism = std::string(opt);285      if (!get_threadpool_strategy(opt))286        message(LDPL_FATAL, "Invalid parallelism level: %s",287                Parallelism.c_str());288    } else if (opt.consume_front("lto-partitions=")) {289      if (opt.getAsInteger(10, ParallelCodeGenParallelismLevel))290        message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);291    } else if (opt == "disable-verify") {292      DisableVerify = true;293    } else if (opt.consume_front("sample-profile=")) {294      sample_profile = std::string(opt);295    } else if (opt == "cs-profile-generate") {296      cs_pgo_gen = true;297    } else if (opt == "merge-functions") {298      merge_functions = true;299    } else if (opt.consume_front("cs-profile-path=")) {300      cs_profile_path = std::string(opt);301    } else if (opt == "new-pass-manager") {302      // We always use the new pass manager.303    } else if (opt == "debug-pass-manager") {304      debug_pass_manager = true;305    } else if (opt == "whole-program-visibility") {306      whole_program_visibility = true;307    } else if (opt.consume_front("dwo_dir=")) {308      dwo_dir = std::string(opt);309    } else if (opt.consume_front("opt-remarks-filename=")) {310      RemarksFilename = std::string(opt);311    } else if (opt.consume_front("opt-remarks-passes=")) {312      RemarksPasses = std::string(opt);313    } else if (opt == "opt-remarks-with-hotness") {314      RemarksWithHotness = true;315    } else if (opt.consume_front("opt-remarks-hotness-threshold=")) {316      auto ResultOrErr = remarks::parseHotnessThresholdOption(opt);317      if (!ResultOrErr)318        message(LDPL_FATAL, "Invalid remarks hotness threshold: %s",319                opt.data());320      else321        RemarksHotnessThreshold = *ResultOrErr;322    } else if (opt.consume_front("opt-remarks-format=")) {323      RemarksFormat = std::string(opt);324    } else if (opt.consume_front("stats-file=")) {325      stats_file = std::string(opt);326    } else if (opt.consume_front("time-trace=")) {327      time_trace_file = std::string(opt);328    } else if (opt.consume_front("time-trace-granularity=")) {329      unsigned Granularity;330      if (opt.getAsInteger(10, Granularity))331        message(LDPL_FATAL, "Invalid time trace granularity: %s", opt.data());332      else333        time_trace_granularity = Granularity;334    } else {335      // Save this option to pass to the code generator.336      // ParseCommandLineOptions() expects argv[0] to be program name. Lazily337      // add that.338      if (extra.empty())339        extra.push_back("LLVMgold");340 341      extra.push_back(opt_);342    }343  }344}345 346static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,347                                        int *claimed);348static ld_plugin_status all_symbols_read_hook(void);349static ld_plugin_status cleanup_hook(void);350 351extern "C" ld_plugin_status onload(ld_plugin_tv *tv);352ld_plugin_status onload(ld_plugin_tv *tv) {353  InitializeAllTargetInfos();354  InitializeAllTargets();355  InitializeAllTargetMCs();356  InitializeAllAsmParsers();357  InitializeAllAsmPrinters();358 359  // We're given a pointer to the first transfer vector. We read through them360  // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values361  // contain pointers to functions that we need to call to register our own362  // hooks. The others are addresses of functions we can use to call into gold363  // for services.364 365  bool registeredClaimFile = false;366  bool RegisteredAllSymbolsRead = false;367 368  for (; tv->tv_tag != LDPT_NULL; ++tv) {369    // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for370    // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h371    // header.372    switch (static_cast<int>(tv->tv_tag)) {373    case LDPT_OUTPUT_NAME:374      output_name = tv->tv_u.tv_string;375      break;376    case LDPT_LINKER_OUTPUT:377      switch (tv->tv_u.tv_val) {378      case LDPO_REL: // .o379        IsExecutable = false;380        SplitSections = false;381        break;382      case LDPO_DYN: // .so383        IsExecutable = false;384        RelocationModel = Reloc::PIC_;385        break;386      case LDPO_PIE: // position independent executable387        IsExecutable = true;388        RelocationModel = Reloc::PIC_;389        break;390      case LDPO_EXEC: // .exe391        IsExecutable = true;392        RelocationModel = Reloc::Static;393        break;394      default:395        message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);396        return LDPS_ERR;397      }398      break;399    case LDPT_OPTION:400      options::process_plugin_option(tv->tv_u.tv_string);401      break;402    case LDPT_REGISTER_CLAIM_FILE_HOOK: {403      ld_plugin_register_claim_file callback;404      callback = tv->tv_u.tv_register_claim_file;405 406      if (callback(claim_file_hook) != LDPS_OK)407        return LDPS_ERR;408 409      registeredClaimFile = true;410    } break;411    case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {412      ld_plugin_register_all_symbols_read callback;413      callback = tv->tv_u.tv_register_all_symbols_read;414 415      if (callback(all_symbols_read_hook) != LDPS_OK)416        return LDPS_ERR;417 418      RegisteredAllSymbolsRead = true;419    } break;420    case LDPT_REGISTER_CLEANUP_HOOK: {421      ld_plugin_register_cleanup callback;422      callback = tv->tv_u.tv_register_cleanup;423 424      if (callback(cleanup_hook) != LDPS_OK)425        return LDPS_ERR;426    } break;427    case LDPT_GET_INPUT_FILE:428      get_input_file = tv->tv_u.tv_get_input_file;429      break;430    case LDPT_RELEASE_INPUT_FILE:431      release_input_file = tv->tv_u.tv_release_input_file;432      break;433    case LDPT_ADD_SYMBOLS:434      add_symbols = tv->tv_u.tv_add_symbols;435      break;436    case LDPT_GET_SYMBOLS_V2:437      // Do not override get_symbols_v3 with get_symbols_v2.438      if (!get_symbols)439        get_symbols = tv->tv_u.tv_get_symbols;440      break;441    case LDPT_GET_SYMBOLS_V3:442      get_symbols = tv->tv_u.tv_get_symbols;443      break;444    case LDPT_ADD_INPUT_FILE:445      add_input_file = tv->tv_u.tv_add_input_file;446      break;447    case LDPT_SET_EXTRA_LIBRARY_PATH:448      set_extra_library_path = tv->tv_u.tv_set_extra_library_path;449      break;450    case LDPT_GET_VIEW:451      get_view = tv->tv_u.tv_get_view;452      break;453    case LDPT_MESSAGE:454      message = tv->tv_u.tv_message;455      break;456    case LDPT_GET_WRAP_SYMBOLS:457      // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum458      // required version, this should be changed to:459      // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;460#pragma GCC diagnostic push461#pragma GCC diagnostic ignored "-Wcast-function-type"462      get_wrap_symbols = (ld_plugin_get_wrap_symbols)tv->tv_u.tv_message;463#pragma GCC diagnostic pop464      break;465    default:466      break;467    }468  }469 470  if (!registeredClaimFile) {471    message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");472    return LDPS_ERR;473  }474  if (!add_symbols) {475    message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");476    return LDPS_ERR;477  }478 479  if (!RegisteredAllSymbolsRead)480    return LDPS_OK;481 482  if (!get_input_file) {483    message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");484    return LDPS_ERR;485  }486  if (!release_input_file) {487    message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");488    return LDPS_ERR;489  }490 491  return LDPS_OK;492}493 494static void diagnosticHandler(const DiagnosticInfo &DI) {495  std::string ErrStorage;496  {497    raw_string_ostream OS(ErrStorage);498    DiagnosticPrinterRawOStream DP(OS);499    DI.print(DP);500  }501  ld_plugin_level Level;502  switch (DI.getSeverity()) {503  case DS_Error:504    Level = LDPL_FATAL;505    break;506  case DS_Warning:507    Level = LDPL_WARNING;508    break;509  case DS_Note:510  case DS_Remark:511    Level = LDPL_INFO;512    break;513  }514  message(Level, "LLVM gold plugin: %s",  ErrStorage.c_str());515}516 517static void check(Error E, std::string Msg = "LLVM gold plugin") {518  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {519    message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());520    return Error::success();521  });522}523 524template <typename T> static T check(Expected<T> E) {525  if (E)526    return std::move(*E);527  check(E.takeError());528  return T();529}530 531/// Called by gold to see whether this file is one that our plugin can handle.532/// We'll try to open it and register all the symbols with add_symbol if533/// possible.534static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,535                                        int *claimed) {536  MemoryBufferRef BufferRef;537  std::unique_ptr<MemoryBuffer> Buffer;538  if (get_view) {539    const void *view;540    if (get_view(file->handle, &view) != LDPS_OK) {541      message(LDPL_ERROR, "Failed to get a view of %s", file->name);542      return LDPS_ERR;543    }544    BufferRef =545        MemoryBufferRef(StringRef((const char *)view, file->filesize), "");546  } else {547    int64_t offset = 0;548    // Gold has found what might be IR part-way inside of a file, such as549    // an .a archive.550    if (file->offset) {551      offset = file->offset;552    }553    ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =554        MemoryBuffer::getOpenFileSlice(sys::fs::convertFDToNativeFile(file->fd),555                                       file->name, file->filesize, offset);556    if (std::error_code EC = BufferOrErr.getError()) {557      message(LDPL_ERROR, EC.message().c_str());558      return LDPS_ERR;559    }560    Buffer = std::move(BufferOrErr.get());561    BufferRef = Buffer->getMemBufferRef();562  }563 564  *claimed = 1;565 566  Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);567  if (!ObjOrErr) {568    handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {569      std::error_code EC = EI.convertToErrorCode();570      if (EC == object::object_error::invalid_file_type ||571          EC == object::object_error::bitcode_section_not_found)572        *claimed = 0;573      else574        message(LDPL_FATAL,575                "LLVM gold plugin has failed to create LTO module: %s",576                EI.message().c_str());577    });578 579    return *claimed ? LDPS_ERR : LDPS_OK;580  }581 582  std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);583 584  Modules.emplace_back();585  claimed_file &cf = Modules.back();586 587  cf.handle = file->handle;588  // Keep track of the first handle for each file descriptor, since there are589  // multiple in the case of an archive. This is used later in the case of590  // ThinLTO parallel backends to ensure that each file is only opened and591  // released once.592  auto LeaderHandle =593      FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;594  cf.leader_handle = LeaderHandle->second;595  // Save the filesize since for parallel ThinLTO backends we can only596  // invoke get_input_file once per archive (only for the leader handle).597  cf.filesize = file->filesize;598  // In the case of an archive library, all but the first member must have a599  // non-zero offset, which we can append to the file name to obtain a600  // unique name.601  cf.name = file->name;602  if (file->offset)603    cf.name += ".llvm." + std::to_string(file->offset) + "." +604               sys::path::filename(Obj->getSourceFileName()).str();605 606  for (auto &Sym : Obj->symbols()) {607    cf.syms.push_back(ld_plugin_symbol());608    ld_plugin_symbol &sym = cf.syms.back();609    sym.version = nullptr;610    StringRef Name = Sym.getName();611    sym.name = strdup(Name.str().c_str());612 613    ResolutionInfo &Res = ResInfo[Name];614 615    Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();616 617    sym.visibility = LDPV_DEFAULT;618    GlobalValue::VisibilityTypes Vis = Sym.getVisibility();619    if (Vis != GlobalValue::DefaultVisibility)620      Res.DefaultVisibility = false;621    switch (Vis) {622    case GlobalValue::DefaultVisibility:623      break;624    case GlobalValue::HiddenVisibility:625      sym.visibility = LDPV_HIDDEN;626      break;627    case GlobalValue::ProtectedVisibility:628      sym.visibility = LDPV_PROTECTED;629      break;630    }631 632    if (Sym.isUndefined()) {633      sym.def = LDPK_UNDEF;634      if (Sym.isWeak())635        sym.def = LDPK_WEAKUNDEF;636    } else if (Sym.isCommon())637      sym.def = LDPK_COMMON;638    else if (Sym.isWeak())639      sym.def = LDPK_WEAKDEF;640    else641      sym.def = LDPK_DEF;642 643    sym.size = 0;644    sym.comdat_key = nullptr;645    int CI = Sym.getComdatIndex();646    if (CI != -1) {647      // Not setting comdat_key for nodeduplicate ensuress we don't deduplicate.648      std::pair<StringRef, Comdat::SelectionKind> C = Obj->getComdatTable()[CI];649      if (C.second != Comdat::NoDeduplicate)650        sym.comdat_key = strdup(C.first.str().c_str());651    }652 653    sym.resolution = LDPR_UNKNOWN;654  }655 656  if (!cf.syms.empty()) {657    if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {658      message(LDPL_ERROR, "Unable to add symbols!");659      return LDPS_ERR;660    }661  }662 663  // Handle any --wrap options passed to gold, which are than passed664  // along to the plugin.665  if (get_wrap_symbols) {666    const char **wrap_symbols;667    uint64_t count = 0;668    if (get_wrap_symbols(&count, &wrap_symbols) != LDPS_OK) {669      message(LDPL_ERROR, "Unable to get wrap symbols!");670      return LDPS_ERR;671    }672    for (uint64_t i = 0; i < count; i++) {673      StringRef Name = wrap_symbols[i];674      ResolutionInfo &Res = ResInfo[Name];675      ResolutionInfo &WrapRes = ResInfo["__wrap_" + Name.str()];676      ResolutionInfo &RealRes = ResInfo["__real_" + Name.str()];677      // Tell LTO not to inline symbols that will be overwritten.678      Res.CanInline = false;679      RealRes.CanInline = false;680      // Tell LTO not to eliminate symbols that will be used after renaming.681      Res.IsUsedInRegularObj = true;682      WrapRes.IsUsedInRegularObj = true;683    }684  }685 686  return LDPS_OK;687}688 689static void freeSymName(ld_plugin_symbol &Sym) {690  free(Sym.name);691  free(Sym.comdat_key);692  Sym.name = nullptr;693  Sym.comdat_key = nullptr;694}695 696/// Helper to get a file's symbols and a view into it via gold callbacks.697static const void *getSymbolsAndView(claimed_file &F) {698  ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());699  if (status == LDPS_NO_SYMS)700    return nullptr;701 702  if (status != LDPS_OK)703    message(LDPL_FATAL, "Failed to get symbol information");704 705  const void *View;706  if (get_view(F.handle, &View) != LDPS_OK)707    message(LDPL_FATAL, "Failed to get a view of file");708 709  return View;710}711 712/// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and713/// \p NewSuffix strings, if it was specified.714static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,715                                      std::string &NewSuffix) {716  assert(options::thinlto_object_suffix_replace.empty() ||717         options::thinlto_object_suffix_replace.find(';') != StringRef::npos);718  StringRef SuffixReplace = options::thinlto_object_suffix_replace;719  auto Split = SuffixReplace.split(';');720  OldSuffix = std::string(Split.first);721  NewSuffix = std::string(Split.second);722}723 724/// Given the original \p Path to an output file, replace any filename725/// suffix matching \p OldSuffix with \p NewSuffix.726static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,727                                            StringRef NewSuffix) {728  if (Path.consume_back(OldSuffix))729    return (Path + NewSuffix).str();730  return std::string(Path);731}732 733// Returns true if S is valid as a C language identifier.734static bool isValidCIdentifier(StringRef S) {735  return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&736         llvm::all_of(llvm::drop_begin(S),737                      [](char C) { return C == '_' || isAlnum(C); });738}739 740static bool isUndefined(ld_plugin_symbol &Sym) {741  return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;742}743 744static void addModule(LTO &Lto, claimed_file &F, const void *View,745                      StringRef Filename) {746  MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),747                            Filename);748  Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);749 750  if (!ObjOrErr)751    message(LDPL_FATAL, "Could not read bitcode from file : %s",752            toString(ObjOrErr.takeError()).c_str());753 754  unsigned SymNum = 0;755  std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());756  auto InputFileSyms = Input->symbols();757  assert(InputFileSyms.size() == F.syms.size());758  std::vector<SymbolResolution> Resols(F.syms.size());759  for (ld_plugin_symbol &Sym : F.syms) {760    const InputFile::Symbol &InpSym = InputFileSyms[SymNum];761    SymbolResolution &R = Resols[SymNum++];762 763    ld_plugin_symbol_resolution Resolution =764        (ld_plugin_symbol_resolution)Sym.resolution;765 766    ResolutionInfo &Res = ResInfo[Sym.name];767 768    switch (Resolution) {769    case LDPR_UNKNOWN:770      llvm_unreachable("Unexpected resolution");771 772    case LDPR_RESOLVED_IR:773    case LDPR_RESOLVED_EXEC:774    case LDPR_PREEMPTED_IR:775    case LDPR_PREEMPTED_REG:776    case LDPR_UNDEF:777      break;778 779    case LDPR_RESOLVED_DYN:780      R.ExportDynamic = true;781      break;782 783    case LDPR_PREVAILING_DEF_IRONLY:784      R.Prevailing = !isUndefined(Sym);785      break;786 787    case LDPR_PREVAILING_DEF:788      R.Prevailing = !isUndefined(Sym);789      R.VisibleToRegularObj = true;790      break;791 792    case LDPR_PREVAILING_DEF_IRONLY_EXP:793      R.Prevailing = !isUndefined(Sym);794      // Identify symbols exported dynamically, and that therefore could be795      // referenced by a shared library not visible to the linker.796      R.ExportDynamic = true;797      if (!Res.CanOmitFromDynSym)798        R.VisibleToRegularObj = true;799      break;800    }801 802    // If the symbol has a C identifier section name, we need to mark803    // it as visible to a regular object so that LTO will keep it around804    // to ensure the linker generates special __start_<secname> and805    // __stop_<secname> symbols which may be used elsewhere.806    if (isValidCIdentifier(InpSym.getSectionName()))807      R.VisibleToRegularObj = true;808 809    if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&810        (IsExecutable || !Res.DefaultVisibility))811      R.FinalDefinitionInLinkageUnit = true;812 813    if (!Res.CanInline)814      R.LinkerRedefined = true;815 816    if (Res.IsUsedInRegularObj)817      R.VisibleToRegularObj = true;818 819    freeSymName(Sym);820  }821 822  check(Lto.add(std::move(Input), Resols),823        std::string("Failed to link module ") + F.name);824}825 826static void recordFile(const std::string &Filename, bool TempOutFile) {827  if (add_input_file(Filename.c_str()) != LDPS_OK)828    message(LDPL_FATAL,829            "Unable to add .o file to the link. File left behind in: %s",830            Filename.c_str());831  if (TempOutFile)832    Cleanup.push_back(Filename);833}834 835/// Return the desired output filename given a base input name, a flag836/// indicating whether a temp file should be generated, and an optional task id.837/// The new filename generated is returned in \p NewFilename.838static int getOutputFileName(StringRef InFilename, bool TempOutFile,839                             SmallString<128> &NewFilename, int TaskID) {840  int FD = -1;841  if (TempOutFile) {842    std::error_code EC =843        sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);844    if (EC)845      message(LDPL_FATAL, "Could not create temporary file: %s",846              EC.message().c_str());847  } else {848    NewFilename = InFilename;849    if (TaskID > 0)850      NewFilename += utostr(TaskID);851    std::error_code EC =852        sys::fs::openFileForWrite(NewFilename, FD, sys::fs::CD_CreateAlways);853    if (EC)854      message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),855              EC.message().c_str());856  }857  return FD;858}859 860/// Parse the thinlto_prefix_replace option into the \p OldPrefix and861/// \p NewPrefix strings, if it was specified.862static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,863                                      std::string &NewPrefix) {864  StringRef PrefixReplace = options::thinlto_prefix_replace;865  assert(PrefixReplace.empty() || PrefixReplace.find(';') != StringRef::npos);866  auto Split = PrefixReplace.split(';');867  OldPrefix = std::string(Split.first);868  NewPrefix = std::string(Split.second);869}870 871/// Creates instance of LTO.872/// OnIndexWrite is callback to let caller know when LTO writes index files.873/// LinkedObjectsFile is an output stream to write the list of object files for874/// the final ThinLTO linking. Can be nullptr.875static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite,876                                      raw_fd_ostream *LinkedObjectsFile) {877  Config Conf;878  ThinBackend Backend;879 880  Conf.CPU = options::mcpu;881  Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());882 883  // Disable the new X86 relax relocations since gold might not support them.884  // FIXME: Check the gold version or add a new option to enable them.885  Conf.Options.MCOptions.X86RelaxRelocations = false;886 887  // Toggle function/data sections.888  if (!codegen::getExplicitFunctionSections())889    Conf.Options.FunctionSections = SplitSections;890  if (!codegen::getExplicitDataSections())891    Conf.Options.DataSections = SplitSections;892 893  Conf.MAttrs = codegen::getMAttrs();894  Conf.RelocModel = RelocationModel;895  Conf.CodeModel = codegen::getExplicitCodeModel();896  std::optional<CodeGenOptLevel> CGOptLevelOrNone =897      CodeGenOpt::getLevel(options::OptLevel);898  assert(CGOptLevelOrNone && "Invalid optimization level");899  Conf.CGOptLevel = *CGOptLevelOrNone;900  Conf.DisableVerify = options::DisableVerify;901  Conf.OptLevel = options::OptLevel;902  Conf.PTO.LoopVectorization = options::OptLevel > 1;903  Conf.PTO.SLPVectorization = options::OptLevel > 1;904  Conf.PTO.MergeFunctions = options::merge_functions;905  Conf.PTO.UnifiedLTO = options::unifiedlto;906  Conf.AlwaysEmitRegularLTOObj = !options::obj_path.empty();907 908  if (options::thinlto_index_only) {909    std::string OldPrefix, NewPrefix;910    getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);911    Backend = createWriteIndexesThinBackend(912        llvm::hardware_concurrency(options::Parallelism), OldPrefix, NewPrefix,913        // TODO: Add support for optional native object path in914        // thinlto_prefix_replace option to match lld.915        /*NativeObjectPrefix=*/"", options::thinlto_emit_imports_files,916        LinkedObjectsFile, OnIndexWrite);917  } else {918    Backend = createInProcessThinBackend(919        llvm::heavyweight_hardware_concurrency(options::Parallelism));920  }921 922  Conf.OverrideTriple = options::triple;923  Conf.DefaultTriple = sys::getDefaultTargetTriple();924 925  Conf.DiagHandler = diagnosticHandler;926 927  switch (options::TheOutputType) {928  case options::OT_NORMAL:929    break;930 931  case options::OT_DISABLE:932    Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };933    break;934 935  case options::OT_BC_ONLY:936    Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {937      std::error_code EC;938      SmallString<128> TaskFilename;939      getOutputFileName(output_name, /* TempOutFile */ false, TaskFilename,940                        Task);941      raw_fd_ostream OS(TaskFilename, EC, sys::fs::OpenFlags::OF_None);942      if (EC)943        message(LDPL_FATAL, "Failed to write the output file.");944      WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);945      return false;946    };947    break;948 949  case options::OT_SAVE_TEMPS:950    check(Conf.addSaveTemps(output_name + ".",951                            /* UseInputModulePath */ true));952    break;953  case options::OT_ASM_ONLY:954    Conf.CGFileType = CodeGenFileType::AssemblyFile;955    Conf.Options.MCOptions.AsmVerbose = true;956    break;957  }958 959  if (!options::sample_profile.empty())960    Conf.SampleProfile = options::sample_profile;961 962  if (!options::cs_profile_path.empty())963    Conf.CSIRProfile = options::cs_profile_path;964  Conf.RunCSIRInstr = options::cs_pgo_gen;965 966  Conf.DwoDir = options::dwo_dir;967 968  // Set up optimization remarks handling.969  Conf.RemarksFilename = options::RemarksFilename;970  Conf.RemarksPasses = options::RemarksPasses;971  Conf.RemarksWithHotness = options::RemarksWithHotness;972  Conf.RemarksHotnessThreshold = options::RemarksHotnessThreshold;973  Conf.RemarksFormat = options::RemarksFormat;974 975  // Debug new pass manager if requested976  Conf.DebugPassManager = options::debug_pass_manager;977 978  Conf.HasWholeProgramVisibility = options::whole_program_visibility;979 980  Conf.StatsFile = options::stats_file;981 982  Conf.TimeTraceEnabled = !options::time_trace_file.empty();983  Conf.TimeTraceGranularity = options::time_trace_granularity;984 985  LTO::LTOKind ltoKind = LTO::LTOK_Default;986  if (options::unifiedlto)987    ltoKind =988        options::thinlto ? LTO::LTOK_UnifiedThin : LTO::LTOK_UnifiedRegular;989  return std::make_unique<LTO>(std::move(Conf), Backend,990                               options::ParallelCodeGenParallelismLevel,991                               ltoKind);992}993 994// Write empty files that may be expected by a distributed build995// system when invoked with thinlto_index_only. This is invoked when996// the linker has decided not to include the given module in the997// final link. Frequently the distributed build system will want to998// confirm that all expected outputs are created based on all of the999// modules provided to the linker.1000// If SkipModule is true then .thinlto.bc should contain just1001// SkipModuleByDistributedBackend flag which requests distributed backend1002// to skip the compilation of the corresponding module and produce an empty1003// object file.1004static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,1005                                              const std::string &OldPrefix,1006                                              const std::string &NewPrefix,1007                                              bool SkipModule) {1008  std::string NewModulePath =1009      getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);1010  std::error_code EC;1011  {1012    raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,1013                      sys::fs::OpenFlags::OF_None);1014    if (EC)1015      message(LDPL_FATAL, "Failed to write '%s': %s",1016              (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());1017 1018    if (SkipModule) {1019      ModuleSummaryIndex Index(/*HaveGVs*/ false);1020      Index.setSkipModuleByDistributedBackend();1021      writeIndexToFile(Index, OS, nullptr);1022    }1023  }1024  if (options::thinlto_emit_imports_files) {1025    raw_fd_ostream OS(NewModulePath + ".imports", EC,1026                      sys::fs::OpenFlags::OF_None);1027    if (EC)1028      message(LDPL_FATAL, "Failed to write '%s': %s",1029              (NewModulePath + ".imports").c_str(), EC.message().c_str());1030  }1031}1032 1033// Creates and returns output stream with a list of object files for final1034// linking of distributed ThinLTO.1035static std::unique_ptr<raw_fd_ostream> CreateLinkedObjectsFile() {1036  if (options::thinlto_linked_objects_file.empty())1037    return nullptr;1038  assert(options::thinlto_index_only);1039  std::error_code EC;1040  auto LinkedObjectsFile = std::make_unique<raw_fd_ostream>(1041      options::thinlto_linked_objects_file, EC, sys::fs::OpenFlags::OF_None);1042  if (EC)1043    message(LDPL_FATAL, "Failed to create '%s': %s",1044            options::thinlto_linked_objects_file.c_str(), EC.message().c_str());1045  return LinkedObjectsFile;1046}1047 1048/// Runs LTO and return a list of pairs <FileName, IsTemporary>.1049static std::vector<std::pair<SmallString<128>, bool>> runLTO() {1050  // Map to own RAII objects that manage the file opening and releasing1051  // interfaces with gold. This is needed only for ThinLTO mode, since1052  // unlike regular LTO, where addModule will result in the opened file1053  // being merged into a new combined module, we need to keep these files open1054  // through Lto->run().1055  DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;1056 1057  // Owns string objects and tells if index file was already created.1058  StringMap<bool> ObjectToIndexFileState;1059 1060  std::unique_ptr<raw_fd_ostream> LinkedObjects = CreateLinkedObjectsFile();1061  std::unique_ptr<LTO> Lto = createLTO(1062      [&ObjectToIndexFileState](const std::string &Identifier) {1063        ObjectToIndexFileState[Identifier] = true;1064      },1065      LinkedObjects.get());1066 1067  std::string OldPrefix, NewPrefix;1068  if (options::thinlto_index_only)1069    getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);1070 1071  std::string OldSuffix, NewSuffix;1072  getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);1073 1074  for (claimed_file &F : Modules) {1075    if (options::thinlto) {1076      auto [It, Inserted] = HandleToInputFile.try_emplace(F.leader_handle);1077      if (Inserted)1078        It->second = std::make_unique<PluginInputFile>(F.handle);1079    }1080    // In case we are thin linking with a minimized bitcode file, ensure1081    // the module paths encoded in the index reflect where the backends1082    // will locate the full bitcode files for compiling/importing.1083    std::string Identifier =1084        getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);1085    auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});1086    assert(ObjFilename.second);1087    if (const void *View = getSymbolsAndView(F))1088      addModule(*Lto, F, View, ObjFilename.first->first());1089    else if (options::thinlto_index_only) {1090      ObjFilename.first->second = true;1091      writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,1092                                        /* SkipModule */ true);1093    }1094  }1095 1096  SmallString<128> Filename;1097  // Note that getOutputFileName will append a unique ID for each task1098  if (!options::obj_path.empty())1099    Filename = options::obj_path;1100  else if (options::TheOutputType == options::OT_SAVE_TEMPS)1101    Filename = output_name + ".lto.o";1102  else if (options::TheOutputType == options::OT_ASM_ONLY)1103    Filename = output_name;1104  bool SaveTemps = !Filename.empty();1105 1106  size_t MaxTasks = Lto->getMaxTasks();1107  std::vector<std::pair<SmallString<128>, bool>> Files(MaxTasks);1108 1109  auto AddStream =1110      [&](size_t Task,1111          const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {1112    Files[Task].second = !SaveTemps;1113    int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,1114                               Files[Task].first, Task);1115    return std::make_unique<CachedFileStream>(1116        std::make_unique<llvm::raw_fd_ostream>(FD, true));1117  };1118 1119  auto AddBuffer = [&](size_t Task, const Twine &ModuleName,1120                       std::unique_ptr<MemoryBuffer> MB) {1121    auto Stream = AddStream(Task, ModuleName);1122    *Stream->OS << MB->getBuffer();1123    check(Stream->commit(), "Failed to commit cache");1124  };1125 1126  FileCache Cache;1127  if (!options::cache_dir.empty())1128    Cache = check(localCache("ThinLTO", "Thin", options::cache_dir, AddBuffer));1129 1130  check(Lto->run(AddStream, Cache));1131 1132  // Write empty output files that may be expected by the distributed build1133  // system.1134  if (options::thinlto_index_only)1135    for (auto &Identifier : ObjectToIndexFileState)1136      if (!Identifier.getValue())1137        writeEmptyDistributedBuildOutputs(std::string(Identifier.getKey()),1138                                          OldPrefix, NewPrefix,1139                                          /* SkipModule */ false);1140 1141  return Files;1142}1143 1144/// gold informs us that all symbols have been read. At this point, we use1145/// get_symbols to see if any of our definitions have been overridden by a1146/// native object file. Then, perform optimization and codegen.1147static ld_plugin_status allSymbolsReadHook() {1148  if (Modules.empty())1149    return LDPS_OK;1150 1151  if (unsigned NumOpts = options::extra.size())1152    cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);1153 1154  // Initialize time trace profiler1155  if (!options::time_trace_file.empty())1156    llvm::timeTraceProfilerInitialize(options::time_trace_granularity,1157                                      options::extra.size() ? options::extra[0]1158                                                            : "LLVMgold");1159  auto FinalizeTimeTrace = llvm::make_scope_exit([&]() {1160    if (!llvm::timeTraceProfilerEnabled())1161      return;1162    assert(!options::time_trace_file.empty());1163    check(llvm::timeTraceProfilerWrite(options::time_trace_file, output_name));1164    llvm::timeTraceProfilerCleanup();1165  });1166 1167  std::vector<std::pair<SmallString<128>, bool>> Files = runLTO();1168 1169  if (options::TheOutputType == options::OT_DISABLE ||1170      options::TheOutputType == options::OT_BC_ONLY ||1171      options::TheOutputType == options::OT_ASM_ONLY)1172    return LDPS_OK;1173 1174  if (options::thinlto_index_only) {1175    llvm_shutdown();1176    cleanup_hook();1177    exit(0);1178  }1179 1180  for (const auto &F : Files)1181    if (!F.first.empty())1182      recordFile(std::string(F.first.str()), F.second);1183 1184  if (!options::extra_library_path.empty() &&1185      set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)1186    message(LDPL_FATAL, "Unable to set the extra library path.");1187 1188  return LDPS_OK;1189}1190 1191static ld_plugin_status all_symbols_read_hook(void) {1192  ld_plugin_status Ret = allSymbolsReadHook();1193  llvm_shutdown();1194 1195  if (options::TheOutputType == options::OT_BC_ONLY ||1196      options::TheOutputType == options::OT_ASM_ONLY ||1197      options::TheOutputType == options::OT_DISABLE) {1198    if (options::TheOutputType == options::OT_DISABLE) {1199      // Remove the output file here since ld.bfd creates the output file1200      // early.1201      std::error_code EC = sys::fs::remove(output_name);1202      if (EC)1203        message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),1204                EC.message().c_str());1205    }1206    exit(0);1207  }1208 1209  return Ret;1210}1211 1212static ld_plugin_status cleanup_hook(void) {1213  for (std::string &Name : Cleanup) {1214    std::error_code EC = sys::fs::remove(Name);1215    if (EC)1216      message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),1217              EC.message().c_str());1218  }1219 1220  // Prune cache1221  if (!options::cache_dir.empty()) {1222    CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));1223    pruneCache(options::cache_dir, policy);1224  }1225 1226  return LDPS_OK;1227}1228