Commit r331416 breaks the big-endian PPC bot. On the big endian build, we
[llvm-core.git] / tools / gold / gold-plugin.cpp
blobe5058249d3d26bfd180a62842cb404a2bdd76be3
1 //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/ADT/Statistic.h"
16 #include "llvm/Bitcode/BitcodeReader.h"
17 #include "llvm/Bitcode/BitcodeWriter.h"
18 #include "llvm/CodeGen/CommandFlags.inc"
19 #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/LTO/Caching.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/Object/Error.h"
25 #include "llvm/Support/CachePruning.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/TargetSelect.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <list>
34 #include <map>
35 #include <plugin-api.h>
36 #include <string>
37 #include <system_error>
38 #include <utility>
39 #include <vector>
41 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
42 // Precise and Debian Wheezy (binutils 2.23 is required)
43 #define LDPO_PIE 3
45 #define LDPT_GET_SYMBOLS_V3 28
47 // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
48 // required version.
49 #define LDPT_GET_WRAP_SYMBOLS 32
51 using namespace llvm;
52 using namespace lto;
54 // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
55 // required version.
56 typedef enum ld_plugin_status (*ld_plugin_get_wrap_symbols)(
57 uint64_t *num_symbols, const char ***wrap_symbol_list);
59 static ld_plugin_status discard_message(int level, const char *format, ...) {
60 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
61 // callback in the transfer vector. This should never be called.
62 abort();
65 static ld_plugin_release_input_file release_input_file = nullptr;
66 static ld_plugin_get_input_file get_input_file = nullptr;
67 static ld_plugin_message message = discard_message;
68 static ld_plugin_get_wrap_symbols get_wrap_symbols = nullptr;
70 namespace {
71 struct claimed_file {
72 void *handle;
73 void *leader_handle;
74 std::vector<ld_plugin_symbol> syms;
75 off_t filesize;
76 std::string name;
79 /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
80 struct PluginInputFile {
81 void *Handle;
82 std::unique_ptr<ld_plugin_input_file> File;
84 PluginInputFile(void *Handle) : Handle(Handle) {
85 File = llvm::make_unique<ld_plugin_input_file>();
86 if (get_input_file(Handle, File.get()) != LDPS_OK)
87 message(LDPL_FATAL, "Failed to get file information");
89 ~PluginInputFile() {
90 // File would have been reset to nullptr if we moved this object
91 // to a new owner.
92 if (File)
93 if (release_input_file(Handle) != LDPS_OK)
94 message(LDPL_FATAL, "Failed to release file information");
97 ld_plugin_input_file &file() { return *File; }
99 PluginInputFile(PluginInputFile &&RHS) = default;
100 PluginInputFile &operator=(PluginInputFile &&RHS) = default;
103 struct ResolutionInfo {
104 bool CanOmitFromDynSym = true;
105 bool DefaultVisibility = true;
106 bool CanInline = true;
107 bool IsUsedInRegularObj = false;
112 static ld_plugin_add_symbols add_symbols = nullptr;
113 static ld_plugin_get_symbols get_symbols = nullptr;
114 static ld_plugin_add_input_file add_input_file = nullptr;
115 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
116 static ld_plugin_get_view get_view = nullptr;
117 static bool IsExecutable = false;
118 static Optional<Reloc::Model> RelocationModel = None;
119 static std::string output_name = "";
120 static std::list<claimed_file> Modules;
121 static DenseMap<int, void *> FDToLeaderHandle;
122 static StringMap<ResolutionInfo> ResInfo;
123 static std::vector<std::string> Cleanup;
125 namespace options {
126 enum OutputType {
127 OT_NORMAL,
128 OT_DISABLE,
129 OT_BC_ONLY,
130 OT_SAVE_TEMPS
132 static OutputType TheOutputType = OT_NORMAL;
133 static unsigned OptLevel = 2;
134 // Default parallelism of 0 used to indicate that user did not specify.
135 // Actual parallelism default value depends on implementation.
136 // Currently only affects ThinLTO, where the default is
137 // llvm::heavyweight_hardware_concurrency.
138 static unsigned Parallelism = 0;
139 // Default regular LTO codegen parallelism (number of partitions).
140 static unsigned ParallelCodeGenParallelismLevel = 1;
141 #ifdef NDEBUG
142 static bool DisableVerify = true;
143 #else
144 static bool DisableVerify = false;
145 #endif
146 static std::string obj_path;
147 static std::string extra_library_path;
148 static std::string triple;
149 static std::string mcpu;
150 // When the thinlto plugin option is specified, only read the function
151 // the information from intermediate files and write a combined
152 // global index for the ThinLTO backends.
153 static bool thinlto = false;
154 // If false, all ThinLTO backend compilations through code gen are performed
155 // using multiple threads in the gold-plugin, before handing control back to
156 // gold. If true, write individual backend index files which reflect
157 // the import decisions, and exit afterwards. The assumption is
158 // that the build system will launch the backend processes.
159 static bool thinlto_index_only = false;
160 // If non-empty, holds the name of a file in which to write the list of
161 // oject files gold selected for inclusion in the link after symbol
162 // resolution (i.e. they had selected symbols). This will only be non-empty
163 // in the thinlto_index_only case. It is used to identify files, which may
164 // have originally been within archive libraries specified via
165 // --start-lib/--end-lib pairs, that should be included in the final
166 // native link process (since intervening function importing and inlining
167 // may change the symbol resolution detected in the final link and which
168 // files to include out of --start-lib/--end-lib libraries as a result).
169 static std::string thinlto_linked_objects_file;
170 // If true, when generating individual index files for distributed backends,
171 // also generate a "${bitcodefile}.imports" file at the same location for each
172 // bitcode file, listing the files it imports from in plain text. This is to
173 // support distributed build file staging.
174 static bool thinlto_emit_imports_files = false;
175 // Option to control where files for a distributed backend (the individual
176 // index files and optional imports files) are created.
177 // If specified, expects a string of the form "oldprefix:newprefix", and
178 // instead of generating these files in the same directory path as the
179 // corresponding bitcode file, will use a path formed by replacing the
180 // bitcode file's path prefix matching oldprefix with newprefix.
181 static std::string thinlto_prefix_replace;
182 // Option to control the name of modules encoded in the individual index
183 // files for a distributed backend. This enables the use of minimized
184 // bitcode files for the thin link, assuming the name of the full bitcode
185 // file used in the backend differs just in some part of the file suffix.
186 // If specified, expects a string of the form "oldsuffix:newsuffix".
187 static std::string thinlto_object_suffix_replace;
188 // Optional path to a directory for caching ThinLTO objects.
189 static std::string cache_dir;
190 // Optional pruning policy for ThinLTO caches.
191 static std::string cache_policy;
192 // Additional options to pass into the code generator.
193 // Note: This array will contain all plugin options which are not claimed
194 // as plugin exclusive to pass to the code generator.
195 static std::vector<const char *> extra;
196 // Sample profile file path
197 static std::string sample_profile;
198 // New pass manager
199 static bool new_pass_manager = false;
200 // Debug new pass manager
201 static bool debug_pass_manager = false;
202 // Objcopy for debug fission.
203 static std::string objcopy;
204 // Directory to store the .dwo files.
205 static std::string dwo_dir;
206 /// Statistics output filename.
207 static std::string stats_file;
209 // Optimization remarks filename and hotness options
210 static std::string OptRemarksFilename;
211 static bool OptRemarksWithHotness = false;
213 static void process_plugin_option(const char *opt_)
215 if (opt_ == nullptr)
216 return;
217 llvm::StringRef opt = opt_;
219 if (opt.startswith("mcpu=")) {
220 mcpu = opt.substr(strlen("mcpu="));
221 } else if (opt.startswith("extra-library-path=")) {
222 extra_library_path = opt.substr(strlen("extra_library_path="));
223 } else if (opt.startswith("mtriple=")) {
224 triple = opt.substr(strlen("mtriple="));
225 } else if (opt.startswith("obj-path=")) {
226 obj_path = opt.substr(strlen("obj-path="));
227 } else if (opt == "emit-llvm") {
228 TheOutputType = OT_BC_ONLY;
229 } else if (opt == "save-temps") {
230 TheOutputType = OT_SAVE_TEMPS;
231 } else if (opt == "disable-output") {
232 TheOutputType = OT_DISABLE;
233 } else if (opt == "thinlto") {
234 thinlto = true;
235 } else if (opt == "thinlto-index-only") {
236 thinlto_index_only = true;
237 } else if (opt.startswith("thinlto-index-only=")) {
238 thinlto_index_only = true;
239 thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
240 } else if (opt == "thinlto-emit-imports-files") {
241 thinlto_emit_imports_files = true;
242 } else if (opt.startswith("thinlto-prefix-replace=")) {
243 thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
244 if (thinlto_prefix_replace.find(';') == std::string::npos)
245 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
246 } else if (opt.startswith("thinlto-object-suffix-replace=")) {
247 thinlto_object_suffix_replace =
248 opt.substr(strlen("thinlto-object-suffix-replace="));
249 if (thinlto_object_suffix_replace.find(';') == std::string::npos)
250 message(LDPL_FATAL,
251 "thinlto-object-suffix-replace expects 'old;new' format");
252 } else if (opt.startswith("cache-dir=")) {
253 cache_dir = opt.substr(strlen("cache-dir="));
254 } else if (opt.startswith("cache-policy=")) {
255 cache_policy = opt.substr(strlen("cache-policy="));
256 } else if (opt.size() == 2 && opt[0] == 'O') {
257 if (opt[1] < '0' || opt[1] > '3')
258 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
259 OptLevel = opt[1] - '0';
260 } else if (opt.startswith("jobs=")) {
261 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
262 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
263 } else if (opt.startswith("lto-partitions=")) {
264 if (opt.substr(strlen("lto-partitions="))
265 .getAsInteger(10, ParallelCodeGenParallelismLevel))
266 message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
267 } else if (opt == "disable-verify") {
268 DisableVerify = true;
269 } else if (opt.startswith("sample-profile=")) {
270 sample_profile= opt.substr(strlen("sample-profile="));
271 } else if (opt == "new-pass-manager") {
272 new_pass_manager = true;
273 } else if (opt == "debug-pass-manager") {
274 debug_pass_manager = true;
275 } else if (opt.startswith("objcopy=")) {
276 objcopy = opt.substr(strlen("objcopy="));
277 } else if (opt.startswith("dwo_dir=")) {
278 dwo_dir = opt.substr(strlen("dwo_dir="));
279 } else if (opt.startswith("opt-remarks-filename=")) {
280 OptRemarksFilename = opt.substr(strlen("opt-remarks-filename="));
281 } else if (opt == "opt-remarks-with-hotness") {
282 OptRemarksWithHotness = true;
283 } else if (opt.startswith("stats-file=")) {
284 stats_file = opt.substr(strlen("stats-file="));
285 } else {
286 // Save this option to pass to the code generator.
287 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
288 // add that.
289 if (extra.empty())
290 extra.push_back("LLVMgold");
292 extra.push_back(opt_);
297 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
298 int *claimed);
299 static ld_plugin_status all_symbols_read_hook(void);
300 static ld_plugin_status cleanup_hook(void);
302 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
303 ld_plugin_status onload(ld_plugin_tv *tv) {
304 InitializeAllTargetInfos();
305 InitializeAllTargets();
306 InitializeAllTargetMCs();
307 InitializeAllAsmParsers();
308 InitializeAllAsmPrinters();
310 // We're given a pointer to the first transfer vector. We read through them
311 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
312 // contain pointers to functions that we need to call to register our own
313 // hooks. The others are addresses of functions we can use to call into gold
314 // for services.
316 bool registeredClaimFile = false;
317 bool RegisteredAllSymbolsRead = false;
319 for (; tv->tv_tag != LDPT_NULL; ++tv) {
320 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
321 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
322 // header.
323 switch (static_cast<int>(tv->tv_tag)) {
324 case LDPT_OUTPUT_NAME:
325 output_name = tv->tv_u.tv_string;
326 break;
327 case LDPT_LINKER_OUTPUT:
328 switch (tv->tv_u.tv_val) {
329 case LDPO_REL: // .o
330 IsExecutable = false;
331 break;
332 case LDPO_DYN: // .so
333 IsExecutable = false;
334 RelocationModel = Reloc::PIC_;
335 break;
336 case LDPO_PIE: // position independent executable
337 IsExecutable = true;
338 RelocationModel = Reloc::PIC_;
339 break;
340 case LDPO_EXEC: // .exe
341 IsExecutable = true;
342 RelocationModel = Reloc::Static;
343 break;
344 default:
345 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
346 return LDPS_ERR;
348 break;
349 case LDPT_OPTION:
350 options::process_plugin_option(tv->tv_u.tv_string);
351 break;
352 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
353 ld_plugin_register_claim_file callback;
354 callback = tv->tv_u.tv_register_claim_file;
356 if (callback(claim_file_hook) != LDPS_OK)
357 return LDPS_ERR;
359 registeredClaimFile = true;
360 } break;
361 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
362 ld_plugin_register_all_symbols_read callback;
363 callback = tv->tv_u.tv_register_all_symbols_read;
365 if (callback(all_symbols_read_hook) != LDPS_OK)
366 return LDPS_ERR;
368 RegisteredAllSymbolsRead = true;
369 } break;
370 case LDPT_REGISTER_CLEANUP_HOOK: {
371 ld_plugin_register_cleanup callback;
372 callback = tv->tv_u.tv_register_cleanup;
374 if (callback(cleanup_hook) != LDPS_OK)
375 return LDPS_ERR;
376 } break;
377 case LDPT_GET_INPUT_FILE:
378 get_input_file = tv->tv_u.tv_get_input_file;
379 break;
380 case LDPT_RELEASE_INPUT_FILE:
381 release_input_file = tv->tv_u.tv_release_input_file;
382 break;
383 case LDPT_ADD_SYMBOLS:
384 add_symbols = tv->tv_u.tv_add_symbols;
385 break;
386 case LDPT_GET_SYMBOLS_V2:
387 // Do not override get_symbols_v3 with get_symbols_v2.
388 if (!get_symbols)
389 get_symbols = tv->tv_u.tv_get_symbols;
390 break;
391 case LDPT_GET_SYMBOLS_V3:
392 get_symbols = tv->tv_u.tv_get_symbols;
393 break;
394 case LDPT_ADD_INPUT_FILE:
395 add_input_file = tv->tv_u.tv_add_input_file;
396 break;
397 case LDPT_SET_EXTRA_LIBRARY_PATH:
398 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
399 break;
400 case LDPT_GET_VIEW:
401 get_view = tv->tv_u.tv_get_view;
402 break;
403 case LDPT_MESSAGE:
404 message = tv->tv_u.tv_message;
405 break;
406 case LDPT_GET_WRAP_SYMBOLS:
407 // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum
408 // required version, this should be changed to:
409 // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;
410 get_wrap_symbols =
411 (ld_plugin_get_wrap_symbols)tv->tv_u.tv_message;
412 break;
413 default:
414 break;
418 if (!registeredClaimFile) {
419 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
420 return LDPS_ERR;
422 if (!add_symbols) {
423 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
424 return LDPS_ERR;
427 if (!RegisteredAllSymbolsRead)
428 return LDPS_OK;
430 if (!get_input_file) {
431 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
432 return LDPS_ERR;
434 if (!release_input_file) {
435 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
436 return LDPS_ERR;
439 return LDPS_OK;
442 static void diagnosticHandler(const DiagnosticInfo &DI) {
443 std::string ErrStorage;
445 raw_string_ostream OS(ErrStorage);
446 DiagnosticPrinterRawOStream DP(OS);
447 DI.print(DP);
449 ld_plugin_level Level;
450 switch (DI.getSeverity()) {
451 case DS_Error:
452 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
453 ErrStorage.c_str());
454 case DS_Warning:
455 Level = LDPL_WARNING;
456 break;
457 case DS_Note:
458 case DS_Remark:
459 Level = LDPL_INFO;
460 break;
462 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
465 static void check(Error E, std::string Msg = "LLVM gold plugin") {
466 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
467 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
468 return Error::success();
472 template <typename T> static T check(Expected<T> E) {
473 if (E)
474 return std::move(*E);
475 check(E.takeError());
476 return T();
479 /// Called by gold to see whether this file is one that our plugin can handle.
480 /// We'll try to open it and register all the symbols with add_symbol if
481 /// possible.
482 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
483 int *claimed) {
484 MemoryBufferRef BufferRef;
485 std::unique_ptr<MemoryBuffer> Buffer;
486 if (get_view) {
487 const void *view;
488 if (get_view(file->handle, &view) != LDPS_OK) {
489 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
490 return LDPS_ERR;
492 BufferRef =
493 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
494 } else {
495 int64_t offset = 0;
496 // Gold has found what might be IR part-way inside of a file, such as
497 // an .a archive.
498 if (file->offset) {
499 offset = file->offset;
501 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
502 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
503 offset);
504 if (std::error_code EC = BufferOrErr.getError()) {
505 message(LDPL_ERROR, EC.message().c_str());
506 return LDPS_ERR;
508 Buffer = std::move(BufferOrErr.get());
509 BufferRef = Buffer->getMemBufferRef();
512 *claimed = 1;
514 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
515 if (!ObjOrErr) {
516 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
517 std::error_code EC = EI.convertToErrorCode();
518 if (EC == object::object_error::invalid_file_type ||
519 EC == object::object_error::bitcode_section_not_found)
520 *claimed = 0;
521 else
522 message(LDPL_FATAL,
523 "LLVM gold plugin has failed to create LTO module: %s",
524 EI.message().c_str());
527 return *claimed ? LDPS_ERR : LDPS_OK;
530 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
532 Modules.emplace_back();
533 claimed_file &cf = Modules.back();
535 cf.handle = file->handle;
536 // Keep track of the first handle for each file descriptor, since there are
537 // multiple in the case of an archive. This is used later in the case of
538 // ThinLTO parallel backends to ensure that each file is only opened and
539 // released once.
540 auto LeaderHandle =
541 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
542 cf.leader_handle = LeaderHandle->second;
543 // Save the filesize since for parallel ThinLTO backends we can only
544 // invoke get_input_file once per archive (only for the leader handle).
545 cf.filesize = file->filesize;
546 // In the case of an archive library, all but the first member must have a
547 // non-zero offset, which we can append to the file name to obtain a
548 // unique name.
549 cf.name = file->name;
550 if (file->offset)
551 cf.name += ".llvm." + std::to_string(file->offset) + "." +
552 sys::path::filename(Obj->getSourceFileName()).str();
554 for (auto &Sym : Obj->symbols()) {
555 cf.syms.push_back(ld_plugin_symbol());
556 ld_plugin_symbol &sym = cf.syms.back();
557 sym.version = nullptr;
558 StringRef Name = Sym.getName();
559 sym.name = strdup(Name.str().c_str());
561 ResolutionInfo &Res = ResInfo[Name];
563 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
565 sym.visibility = LDPV_DEFAULT;
566 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
567 if (Vis != GlobalValue::DefaultVisibility)
568 Res.DefaultVisibility = false;
569 switch (Vis) {
570 case GlobalValue::DefaultVisibility:
571 break;
572 case GlobalValue::HiddenVisibility:
573 sym.visibility = LDPV_HIDDEN;
574 break;
575 case GlobalValue::ProtectedVisibility:
576 sym.visibility = LDPV_PROTECTED;
577 break;
580 if (Sym.isUndefined()) {
581 sym.def = LDPK_UNDEF;
582 if (Sym.isWeak())
583 sym.def = LDPK_WEAKUNDEF;
584 } else if (Sym.isCommon())
585 sym.def = LDPK_COMMON;
586 else if (Sym.isWeak())
587 sym.def = LDPK_WEAKDEF;
588 else
589 sym.def = LDPK_DEF;
591 sym.size = 0;
592 sym.comdat_key = nullptr;
593 int CI = Sym.getComdatIndex();
594 if (CI != -1) {
595 StringRef C = Obj->getComdatTable()[CI];
596 sym.comdat_key = strdup(C.str().c_str());
599 sym.resolution = LDPR_UNKNOWN;
602 if (!cf.syms.empty()) {
603 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
604 message(LDPL_ERROR, "Unable to add symbols!");
605 return LDPS_ERR;
609 // Handle any --wrap options passed to gold, which are than passed
610 // along to the plugin.
611 if (get_wrap_symbols) {
612 const char **wrap_symbols;
613 uint64_t count = 0;
614 if (get_wrap_symbols(&count, &wrap_symbols) != LDPS_OK) {
615 message(LDPL_ERROR, "Unable to get wrap symbols!");
616 return LDPS_ERR;
618 for (uint64_t i = 0; i < count; i++) {
619 StringRef Name = wrap_symbols[i];
620 ResolutionInfo &Res = ResInfo[Name];
621 ResolutionInfo &WrapRes = ResInfo["__wrap_" + Name.str()];
622 ResolutionInfo &RealRes = ResInfo["__real_" + Name.str()];
623 // Tell LTO not to inline symbols that will be overwritten.
624 Res.CanInline = false;
625 RealRes.CanInline = false;
626 // Tell LTO not to eliminate symbols that will be used after renaming.
627 Res.IsUsedInRegularObj = true;
628 WrapRes.IsUsedInRegularObj = true;
632 return LDPS_OK;
635 static void freeSymName(ld_plugin_symbol &Sym) {
636 free(Sym.name);
637 free(Sym.comdat_key);
638 Sym.name = nullptr;
639 Sym.comdat_key = nullptr;
642 /// Helper to get a file's symbols and a view into it via gold callbacks.
643 static const void *getSymbolsAndView(claimed_file &F) {
644 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
645 if (status == LDPS_NO_SYMS)
646 return nullptr;
648 if (status != LDPS_OK)
649 message(LDPL_FATAL, "Failed to get symbol information");
651 const void *View;
652 if (get_view(F.handle, &View) != LDPS_OK)
653 message(LDPL_FATAL, "Failed to get a view of file");
655 return View;
658 /// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
659 /// \p NewSuffix strings, if it was specified.
660 static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
661 std::string &NewSuffix) {
662 assert(options::thinlto_object_suffix_replace.empty() ||
663 options::thinlto_object_suffix_replace.find(";") != StringRef::npos);
664 StringRef SuffixReplace = options::thinlto_object_suffix_replace;
665 std::tie(OldSuffix, NewSuffix) = SuffixReplace.split(';');
668 /// Given the original \p Path to an output file, replace any filename
669 /// suffix matching \p OldSuffix with \p NewSuffix.
670 static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
671 StringRef NewSuffix) {
672 if (OldSuffix.empty() && NewSuffix.empty())
673 return Path;
674 StringRef NewPath = Path;
675 NewPath.consume_back(OldSuffix);
676 std::string NewNewPath = NewPath;
677 NewNewPath += NewSuffix;
678 return NewNewPath;
681 // Returns true if S is valid as a C language identifier.
682 static bool isValidCIdentifier(StringRef S) {
683 return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
684 std::all_of(S.begin() + 1, S.end(),
685 [](char C) { return C == '_' || isAlnum(C); });
688 static bool isUndefined(ld_plugin_symbol &Sym) {
689 return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;
692 static void addModule(LTO &Lto, claimed_file &F, const void *View,
693 StringRef Filename) {
694 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
695 Filename);
696 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
698 if (!ObjOrErr)
699 message(LDPL_FATAL, "Could not read bitcode from file : %s",
700 toString(ObjOrErr.takeError()).c_str());
702 unsigned SymNum = 0;
703 std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
704 auto InputFileSyms = Input->symbols();
705 assert(InputFileSyms.size() == F.syms.size());
706 std::vector<SymbolResolution> Resols(F.syms.size());
707 for (ld_plugin_symbol &Sym : F.syms) {
708 const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
709 SymbolResolution &R = Resols[SymNum++];
711 ld_plugin_symbol_resolution Resolution =
712 (ld_plugin_symbol_resolution)Sym.resolution;
714 ResolutionInfo &Res = ResInfo[Sym.name];
716 switch (Resolution) {
717 case LDPR_UNKNOWN:
718 llvm_unreachable("Unexpected resolution");
720 case LDPR_RESOLVED_IR:
721 case LDPR_RESOLVED_EXEC:
722 case LDPR_RESOLVED_DYN:
723 case LDPR_PREEMPTED_IR:
724 case LDPR_PREEMPTED_REG:
725 case LDPR_UNDEF:
726 break;
728 case LDPR_PREVAILING_DEF_IRONLY:
729 R.Prevailing = !isUndefined(Sym);
730 break;
732 case LDPR_PREVAILING_DEF:
733 R.Prevailing = !isUndefined(Sym);
734 R.VisibleToRegularObj = true;
735 break;
737 case LDPR_PREVAILING_DEF_IRONLY_EXP:
738 R.Prevailing = !isUndefined(Sym);
739 if (!Res.CanOmitFromDynSym)
740 R.VisibleToRegularObj = true;
741 break;
744 // If the symbol has a C identifier section name, we need to mark
745 // it as visible to a regular object so that LTO will keep it around
746 // to ensure the linker generates special __start_<secname> and
747 // __stop_<secname> symbols which may be used elsewhere.
748 if (isValidCIdentifier(InpSym.getSectionName()))
749 R.VisibleToRegularObj = true;
751 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
752 (IsExecutable || !Res.DefaultVisibility))
753 R.FinalDefinitionInLinkageUnit = true;
755 if (!Res.CanInline)
756 R.LinkerRedefined = true;
758 if (Res.IsUsedInRegularObj)
759 R.VisibleToRegularObj = true;
761 freeSymName(Sym);
764 check(Lto.add(std::move(Input), Resols),
765 std::string("Failed to link module ") + F.name);
768 static void recordFile(const std::string &Filename, bool TempOutFile) {
769 if (add_input_file(Filename.c_str()) != LDPS_OK)
770 message(LDPL_FATAL,
771 "Unable to add .o file to the link. File left behind in: %s",
772 Filename.c_str());
773 if (TempOutFile)
774 Cleanup.push_back(Filename);
777 /// Return the desired output filename given a base input name, a flag
778 /// indicating whether a temp file should be generated, and an optional task id.
779 /// The new filename generated is returned in \p NewFilename.
780 static int getOutputFileName(StringRef InFilename, bool TempOutFile,
781 SmallString<128> &NewFilename, int TaskID) {
782 int FD = -1;
783 if (TempOutFile) {
784 std::error_code EC =
785 sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
786 if (EC)
787 message(LDPL_FATAL, "Could not create temporary file: %s",
788 EC.message().c_str());
789 } else {
790 NewFilename = InFilename;
791 if (TaskID > 0)
792 NewFilename += utostr(TaskID);
793 std::error_code EC =
794 sys::fs::openFileForWrite(NewFilename, FD, sys::fs::F_None);
795 if (EC)
796 message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
797 EC.message().c_str());
799 return FD;
802 static CodeGenOpt::Level getCGOptLevel() {
803 switch (options::OptLevel) {
804 case 0:
805 return CodeGenOpt::None;
806 case 1:
807 return CodeGenOpt::Less;
808 case 2:
809 return CodeGenOpt::Default;
810 case 3:
811 return CodeGenOpt::Aggressive;
813 llvm_unreachable("Invalid optimization level");
816 /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
817 /// \p NewPrefix strings, if it was specified.
818 static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
819 std::string &NewPrefix) {
820 StringRef PrefixReplace = options::thinlto_prefix_replace;
821 assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
822 std::tie(OldPrefix, NewPrefix) = PrefixReplace.split(';');
825 /// Creates instance of LTO.
826 /// OnIndexWrite is callback to let caller know when LTO writes index files.
827 /// LinkedObjectsFile is an output stream to write the list of object files for
828 /// the final ThinLTO linking. Can be nullptr.
829 static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite,
830 raw_fd_ostream *LinkedObjectsFile) {
831 Config Conf;
832 ThinBackend Backend;
834 Conf.CPU = options::mcpu;
835 Conf.Options = InitTargetOptionsFromCodeGenFlags();
837 // Disable the new X86 relax relocations since gold might not support them.
838 // FIXME: Check the gold version or add a new option to enable them.
839 Conf.Options.RelaxELFRelocations = false;
841 // Enable function/data sections by default.
842 Conf.Options.FunctionSections = true;
843 Conf.Options.DataSections = true;
845 Conf.MAttrs = MAttrs;
846 Conf.RelocModel = RelocationModel;
847 Conf.CGOptLevel = getCGOptLevel();
848 Conf.DisableVerify = options::DisableVerify;
849 Conf.OptLevel = options::OptLevel;
850 if (options::Parallelism)
851 Backend = createInProcessThinBackend(options::Parallelism);
852 if (options::thinlto_index_only) {
853 std::string OldPrefix, NewPrefix;
854 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
855 Backend = createWriteIndexesThinBackend(OldPrefix, NewPrefix,
856 options::thinlto_emit_imports_files,
857 LinkedObjectsFile, OnIndexWrite);
860 Conf.OverrideTriple = options::triple;
861 Conf.DefaultTriple = sys::getDefaultTargetTriple();
863 Conf.DiagHandler = diagnosticHandler;
865 switch (options::TheOutputType) {
866 case options::OT_NORMAL:
867 break;
869 case options::OT_DISABLE:
870 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
871 break;
873 case options::OT_BC_ONLY:
874 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
875 std::error_code EC;
876 raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
877 if (EC)
878 message(LDPL_FATAL, "Failed to write the output file.");
879 WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);
880 return false;
882 break;
884 case options::OT_SAVE_TEMPS:
885 check(Conf.addSaveTemps(output_name + ".",
886 /* UseInputModulePath */ true));
887 break;
890 if (!options::sample_profile.empty())
891 Conf.SampleProfile = options::sample_profile;
893 Conf.DwoDir = options::dwo_dir;
895 Conf.Objcopy = options::objcopy;
897 // Set up optimization remarks handling.
898 Conf.RemarksFilename = options::OptRemarksFilename;
899 Conf.RemarksWithHotness = options::OptRemarksWithHotness;
901 // Use new pass manager if set in driver
902 Conf.UseNewPM = options::new_pass_manager;
903 // Debug new pass manager if requested
904 Conf.DebugPassManager = options::debug_pass_manager;
906 Conf.StatsFile = options::stats_file;
907 return llvm::make_unique<LTO>(std::move(Conf), Backend,
908 options::ParallelCodeGenParallelismLevel);
911 // Write empty files that may be expected by a distributed build
912 // system when invoked with thinlto_index_only. This is invoked when
913 // the linker has decided not to include the given module in the
914 // final link. Frequently the distributed build system will want to
915 // confirm that all expected outputs are created based on all of the
916 // modules provided to the linker.
917 // If SkipModule is true then .thinlto.bc should contain just
918 // SkipModuleByDistributedBackend flag which requests distributed backend
919 // to skip the compilation of the corresponding module and produce an empty
920 // object file.
921 static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
922 const std::string &OldPrefix,
923 const std::string &NewPrefix,
924 bool SkipModule) {
925 std::string NewModulePath =
926 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
927 std::error_code EC;
929 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
930 sys::fs::OpenFlags::F_None);
931 if (EC)
932 message(LDPL_FATAL, "Failed to write '%s': %s",
933 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
935 if (SkipModule) {
936 ModuleSummaryIndex Index(false);
937 Index.setSkipModuleByDistributedBackend();
938 WriteIndexToFile(Index, OS, nullptr);
941 if (options::thinlto_emit_imports_files) {
942 raw_fd_ostream OS(NewModulePath + ".imports", EC,
943 sys::fs::OpenFlags::F_None);
944 if (EC)
945 message(LDPL_FATAL, "Failed to write '%s': %s",
946 (NewModulePath + ".imports").c_str(), EC.message().c_str());
950 // Creates and returns output stream with a list of object files for final
951 // linking of distributed ThinLTO.
952 static std::unique_ptr<raw_fd_ostream> CreateLinkedObjectsFile() {
953 if (options::thinlto_linked_objects_file.empty())
954 return nullptr;
955 assert(options::thinlto_index_only);
956 std::error_code EC;
957 auto LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
958 options::thinlto_linked_objects_file, EC, sys::fs::OpenFlags::F_None);
959 if (EC)
960 message(LDPL_FATAL, "Failed to create '%s': %s",
961 options::thinlto_linked_objects_file.c_str(), EC.message().c_str());
962 return LinkedObjectsFile;
965 /// Runs LTO and return a list of pairs <FileName, IsTemporary>.
966 static std::vector<std::pair<SmallString<128>, bool>> runLTO() {
967 // Map to own RAII objects that manage the file opening and releasing
968 // interfaces with gold. This is needed only for ThinLTO mode, since
969 // unlike regular LTO, where addModule will result in the opened file
970 // being merged into a new combined module, we need to keep these files open
971 // through Lto->run().
972 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
974 // Owns string objects and tells if index file was already created.
975 StringMap<bool> ObjectToIndexFileState;
977 std::unique_ptr<raw_fd_ostream> LinkedObjects = CreateLinkedObjectsFile();
978 std::unique_ptr<LTO> Lto = createLTO(
979 [&ObjectToIndexFileState](const std::string &Identifier) {
980 ObjectToIndexFileState[Identifier] = true;
982 LinkedObjects.get());
984 std::string OldPrefix, NewPrefix;
985 if (options::thinlto_index_only)
986 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
988 std::string OldSuffix, NewSuffix;
989 getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
991 for (claimed_file &F : Modules) {
992 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
993 HandleToInputFile.insert(std::make_pair(
994 F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
995 // In case we are thin linking with a minimized bitcode file, ensure
996 // the module paths encoded in the index reflect where the backends
997 // will locate the full bitcode files for compiling/importing.
998 std::string Identifier =
999 getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
1000 auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});
1001 assert(ObjFilename.second);
1002 if (const void *View = getSymbolsAndView(F))
1003 addModule(*Lto, F, View, ObjFilename.first->first());
1004 else if (options::thinlto_index_only) {
1005 ObjFilename.first->second = true;
1006 writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
1007 /* SkipModule */ true);
1011 SmallString<128> Filename;
1012 // Note that getOutputFileName will append a unique ID for each task
1013 if (!options::obj_path.empty())
1014 Filename = options::obj_path;
1015 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
1016 Filename = output_name + ".o";
1017 bool SaveTemps = !Filename.empty();
1019 size_t MaxTasks = Lto->getMaxTasks();
1020 std::vector<std::pair<SmallString<128>, bool>> Files(MaxTasks);
1022 auto AddStream =
1023 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
1024 Files[Task].second = !SaveTemps;
1025 int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,
1026 Files[Task].first, Task);
1027 return llvm::make_unique<lto::NativeObjectStream>(
1028 llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
1031 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
1032 *AddStream(Task)->OS << MB->getBuffer();
1035 NativeObjectCache Cache;
1036 if (!options::cache_dir.empty())
1037 Cache = check(localCache(options::cache_dir, AddBuffer));
1039 check(Lto->run(AddStream, Cache));
1041 // Write empty output files that may be expected by the distributed build
1042 // system.
1043 if (options::thinlto_index_only)
1044 for (auto &Identifier : ObjectToIndexFileState)
1045 if (!Identifier.getValue())
1046 writeEmptyDistributedBuildOutputs(Identifier.getKey(), OldPrefix,
1047 NewPrefix, /* SkipModule */ false);
1049 return Files;
1052 /// gold informs us that all symbols have been read. At this point, we use
1053 /// get_symbols to see if any of our definitions have been overridden by a
1054 /// native object file. Then, perform optimization and codegen.
1055 static ld_plugin_status allSymbolsReadHook() {
1056 if (Modules.empty())
1057 return LDPS_OK;
1059 if (unsigned NumOpts = options::extra.size())
1060 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
1062 std::vector<std::pair<SmallString<128>, bool>> Files = runLTO();
1064 if (options::TheOutputType == options::OT_DISABLE ||
1065 options::TheOutputType == options::OT_BC_ONLY)
1066 return LDPS_OK;
1068 if (options::thinlto_index_only) {
1069 llvm_shutdown();
1070 cleanup_hook();
1071 exit(0);
1074 for (const auto &F : Files)
1075 if (!F.first.empty())
1076 recordFile(F.first.str(), F.second);
1078 if (!options::extra_library_path.empty() &&
1079 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
1080 message(LDPL_FATAL, "Unable to set the extra library path.");
1082 return LDPS_OK;
1085 static ld_plugin_status all_symbols_read_hook(void) {
1086 ld_plugin_status Ret = allSymbolsReadHook();
1087 llvm_shutdown();
1089 if (options::TheOutputType == options::OT_BC_ONLY ||
1090 options::TheOutputType == options::OT_DISABLE) {
1091 if (options::TheOutputType == options::OT_DISABLE) {
1092 // Remove the output file here since ld.bfd creates the output file
1093 // early.
1094 std::error_code EC = sys::fs::remove(output_name);
1095 if (EC)
1096 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
1097 EC.message().c_str());
1099 exit(0);
1102 return Ret;
1105 static ld_plugin_status cleanup_hook(void) {
1106 for (std::string &Name : Cleanup) {
1107 std::error_code EC = sys::fs::remove(Name);
1108 if (EC)
1109 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
1110 EC.message().c_str());
1113 // Prune cache
1114 if (!options::cache_dir.empty()) {
1115 CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
1116 pruneCache(options::cache_dir, policy);
1119 return LDPS_OK;