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/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"
35 #include <plugin-api.h>
37 #include <system_error>
41 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
42 // Precise and Debian Wheezy (binutils 2.23 is required)
45 #define LDPT_GET_SYMBOLS_V3 28
47 // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
49 #define LDPT_GET_WRAP_SYMBOLS 32
54 // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
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.
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;
74 std::vector
<ld_plugin_symbol
> syms
;
79 /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
80 struct PluginInputFile
{
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");
90 // File would have been reset to nullptr if we moved this object
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 bool SplitSections
= true;
119 static Optional
<Reloc::Model
> RelocationModel
= None
;
120 static std::string output_name
= "";
121 static std::list
<claimed_file
> Modules
;
122 static DenseMap
<int, void *> FDToLeaderHandle
;
123 static StringMap
<ResolutionInfo
> ResInfo
;
124 static std::vector
<std::string
> Cleanup
;
133 static OutputType TheOutputType
= OT_NORMAL
;
134 static unsigned OptLevel
= 2;
135 // Default parallelism of 0 used to indicate that user did not specify.
136 // Actual parallelism default value depends on implementation.
137 // Currently only affects ThinLTO, where the default is
138 // llvm::heavyweight_hardware_concurrency.
139 static unsigned Parallelism
= 0;
140 // Default regular LTO codegen parallelism (number of partitions).
141 static unsigned ParallelCodeGenParallelismLevel
= 1;
143 static bool DisableVerify
= true;
145 static bool DisableVerify
= false;
147 static std::string obj_path
;
148 static std::string extra_library_path
;
149 static std::string triple
;
150 static std::string mcpu
;
151 // When the thinlto plugin option is specified, only read the function
152 // the information from intermediate files and write a combined
153 // global index for the ThinLTO backends.
154 static bool thinlto
= false;
155 // If false, all ThinLTO backend compilations through code gen are performed
156 // using multiple threads in the gold-plugin, before handing control back to
157 // gold. If true, write individual backend index files which reflect
158 // the import decisions, and exit afterwards. The assumption is
159 // that the build system will launch the backend processes.
160 static bool thinlto_index_only
= false;
161 // If non-empty, holds the name of a file in which to write the list of
162 // oject files gold selected for inclusion in the link after symbol
163 // resolution (i.e. they had selected symbols). This will only be non-empty
164 // in the thinlto_index_only case. It is used to identify files, which may
165 // have originally been within archive libraries specified via
166 // --start-lib/--end-lib pairs, that should be included in the final
167 // native link process (since intervening function importing and inlining
168 // may change the symbol resolution detected in the final link and which
169 // files to include out of --start-lib/--end-lib libraries as a result).
170 static std::string thinlto_linked_objects_file
;
171 // If true, when generating individual index files for distributed backends,
172 // also generate a "${bitcodefile}.imports" file at the same location for each
173 // bitcode file, listing the files it imports from in plain text. This is to
174 // support distributed build file staging.
175 static bool thinlto_emit_imports_files
= false;
176 // Option to control where files for a distributed backend (the individual
177 // index files and optional imports files) are created.
178 // If specified, expects a string of the form "oldprefix:newprefix", and
179 // instead of generating these files in the same directory path as the
180 // corresponding bitcode file, will use a path formed by replacing the
181 // bitcode file's path prefix matching oldprefix with newprefix.
182 static std::string thinlto_prefix_replace
;
183 // Option to control the name of modules encoded in the individual index
184 // files for a distributed backend. This enables the use of minimized
185 // bitcode files for the thin link, assuming the name of the full bitcode
186 // file used in the backend differs just in some part of the file suffix.
187 // If specified, expects a string of the form "oldsuffix:newsuffix".
188 static std::string thinlto_object_suffix_replace
;
189 // Optional path to a directory for caching ThinLTO objects.
190 static std::string cache_dir
;
191 // Optional pruning policy for ThinLTO caches.
192 static std::string cache_policy
;
193 // Additional options to pass into the code generator.
194 // Note: This array will contain all plugin options which are not claimed
195 // as plugin exclusive to pass to the code generator.
196 static std::vector
<const char *> extra
;
197 // Sample profile file path
198 static std::string sample_profile
;
200 static bool new_pass_manager
= false;
201 // Debug new pass manager
202 static bool debug_pass_manager
= false;
203 // Directory to store the .dwo files.
204 static std::string dwo_dir
;
205 /// Statistics output filename.
206 static std::string stats_file
;
208 // Optimization remarks filename and hotness options
209 static std::string OptRemarksFilename
;
210 static bool OptRemarksWithHotness
= false;
212 static void process_plugin_option(const char *opt_
)
216 llvm::StringRef opt
= opt_
;
218 if (opt
.startswith("mcpu=")) {
219 mcpu
= opt
.substr(strlen("mcpu="));
220 } else if (opt
.startswith("extra-library-path=")) {
221 extra_library_path
= opt
.substr(strlen("extra_library_path="));
222 } else if (opt
.startswith("mtriple=")) {
223 triple
= opt
.substr(strlen("mtriple="));
224 } else if (opt
.startswith("obj-path=")) {
225 obj_path
= opt
.substr(strlen("obj-path="));
226 } else if (opt
== "emit-llvm") {
227 TheOutputType
= OT_BC_ONLY
;
228 } else if (opt
== "save-temps") {
229 TheOutputType
= OT_SAVE_TEMPS
;
230 } else if (opt
== "disable-output") {
231 TheOutputType
= OT_DISABLE
;
232 } else if (opt
== "thinlto") {
234 } else if (opt
== "thinlto-index-only") {
235 thinlto_index_only
= true;
236 } else if (opt
.startswith("thinlto-index-only=")) {
237 thinlto_index_only
= true;
238 thinlto_linked_objects_file
= opt
.substr(strlen("thinlto-index-only="));
239 } else if (opt
== "thinlto-emit-imports-files") {
240 thinlto_emit_imports_files
= true;
241 } else if (opt
.startswith("thinlto-prefix-replace=")) {
242 thinlto_prefix_replace
= opt
.substr(strlen("thinlto-prefix-replace="));
243 if (thinlto_prefix_replace
.find(';') == std::string::npos
)
244 message(LDPL_FATAL
, "thinlto-prefix-replace expects 'old;new' format");
245 } else if (opt
.startswith("thinlto-object-suffix-replace=")) {
246 thinlto_object_suffix_replace
=
247 opt
.substr(strlen("thinlto-object-suffix-replace="));
248 if (thinlto_object_suffix_replace
.find(';') == std::string::npos
)
250 "thinlto-object-suffix-replace expects 'old;new' format");
251 } else if (opt
.startswith("cache-dir=")) {
252 cache_dir
= opt
.substr(strlen("cache-dir="));
253 } else if (opt
.startswith("cache-policy=")) {
254 cache_policy
= opt
.substr(strlen("cache-policy="));
255 } else if (opt
.size() == 2 && opt
[0] == 'O') {
256 if (opt
[1] < '0' || opt
[1] > '3')
257 message(LDPL_FATAL
, "Optimization level must be between 0 and 3");
258 OptLevel
= opt
[1] - '0';
259 } else if (opt
.startswith("jobs=")) {
260 if (StringRef(opt_
+ 5).getAsInteger(10, Parallelism
))
261 message(LDPL_FATAL
, "Invalid parallelism level: %s", opt_
+ 5);
262 } else if (opt
.startswith("lto-partitions=")) {
263 if (opt
.substr(strlen("lto-partitions="))
264 .getAsInteger(10, ParallelCodeGenParallelismLevel
))
265 message(LDPL_FATAL
, "Invalid codegen partition level: %s", opt_
+ 5);
266 } else if (opt
== "disable-verify") {
267 DisableVerify
= true;
268 } else if (opt
.startswith("sample-profile=")) {
269 sample_profile
= opt
.substr(strlen("sample-profile="));
270 } else if (opt
== "new-pass-manager") {
271 new_pass_manager
= true;
272 } else if (opt
== "debug-pass-manager") {
273 debug_pass_manager
= true;
274 } else if (opt
.startswith("dwo_dir=")) {
275 dwo_dir
= opt
.substr(strlen("dwo_dir="));
276 } else if (opt
.startswith("opt-remarks-filename=")) {
277 OptRemarksFilename
= opt
.substr(strlen("opt-remarks-filename="));
278 } else if (opt
== "opt-remarks-with-hotness") {
279 OptRemarksWithHotness
= true;
280 } else if (opt
.startswith("stats-file=")) {
281 stats_file
= opt
.substr(strlen("stats-file="));
283 // Save this option to pass to the code generator.
284 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
287 extra
.push_back("LLVMgold");
289 extra
.push_back(opt_
);
294 static ld_plugin_status
claim_file_hook(const ld_plugin_input_file
*file
,
296 static ld_plugin_status
all_symbols_read_hook(void);
297 static ld_plugin_status
cleanup_hook(void);
299 extern "C" ld_plugin_status
onload(ld_plugin_tv
*tv
);
300 ld_plugin_status
onload(ld_plugin_tv
*tv
) {
301 InitializeAllTargetInfos();
302 InitializeAllTargets();
303 InitializeAllTargetMCs();
304 InitializeAllAsmParsers();
305 InitializeAllAsmPrinters();
307 // We're given a pointer to the first transfer vector. We read through them
308 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
309 // contain pointers to functions that we need to call to register our own
310 // hooks. The others are addresses of functions we can use to call into gold
313 bool registeredClaimFile
= false;
314 bool RegisteredAllSymbolsRead
= false;
316 for (; tv
->tv_tag
!= LDPT_NULL
; ++tv
) {
317 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
318 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
320 switch (static_cast<int>(tv
->tv_tag
)) {
321 case LDPT_OUTPUT_NAME
:
322 output_name
= tv
->tv_u
.tv_string
;
324 case LDPT_LINKER_OUTPUT
:
325 switch (tv
->tv_u
.tv_val
) {
327 IsExecutable
= false;
328 SplitSections
= false;
330 case LDPO_DYN
: // .so
331 IsExecutable
= false;
332 RelocationModel
= Reloc::PIC_
;
334 case LDPO_PIE
: // position independent executable
336 RelocationModel
= Reloc::PIC_
;
338 case LDPO_EXEC
: // .exe
340 RelocationModel
= Reloc::Static
;
343 message(LDPL_ERROR
, "Unknown output file type %d", tv
->tv_u
.tv_val
);
348 options::process_plugin_option(tv
->tv_u
.tv_string
);
350 case LDPT_REGISTER_CLAIM_FILE_HOOK
: {
351 ld_plugin_register_claim_file callback
;
352 callback
= tv
->tv_u
.tv_register_claim_file
;
354 if (callback(claim_file_hook
) != LDPS_OK
)
357 registeredClaimFile
= true;
359 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK
: {
360 ld_plugin_register_all_symbols_read callback
;
361 callback
= tv
->tv_u
.tv_register_all_symbols_read
;
363 if (callback(all_symbols_read_hook
) != LDPS_OK
)
366 RegisteredAllSymbolsRead
= true;
368 case LDPT_REGISTER_CLEANUP_HOOK
: {
369 ld_plugin_register_cleanup callback
;
370 callback
= tv
->tv_u
.tv_register_cleanup
;
372 if (callback(cleanup_hook
) != LDPS_OK
)
375 case LDPT_GET_INPUT_FILE
:
376 get_input_file
= tv
->tv_u
.tv_get_input_file
;
378 case LDPT_RELEASE_INPUT_FILE
:
379 release_input_file
= tv
->tv_u
.tv_release_input_file
;
381 case LDPT_ADD_SYMBOLS
:
382 add_symbols
= tv
->tv_u
.tv_add_symbols
;
384 case LDPT_GET_SYMBOLS_V2
:
385 // Do not override get_symbols_v3 with get_symbols_v2.
387 get_symbols
= tv
->tv_u
.tv_get_symbols
;
389 case LDPT_GET_SYMBOLS_V3
:
390 get_symbols
= tv
->tv_u
.tv_get_symbols
;
392 case LDPT_ADD_INPUT_FILE
:
393 add_input_file
= tv
->tv_u
.tv_add_input_file
;
395 case LDPT_SET_EXTRA_LIBRARY_PATH
:
396 set_extra_library_path
= tv
->tv_u
.tv_set_extra_library_path
;
399 get_view
= tv
->tv_u
.tv_get_view
;
402 message
= tv
->tv_u
.tv_message
;
404 case LDPT_GET_WRAP_SYMBOLS
:
405 // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum
406 // required version, this should be changed to:
407 // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;
409 (ld_plugin_get_wrap_symbols
)tv
->tv_u
.tv_message
;
416 if (!registeredClaimFile
) {
417 message(LDPL_ERROR
, "register_claim_file not passed to LLVMgold.");
421 message(LDPL_ERROR
, "add_symbols not passed to LLVMgold.");
425 if (!RegisteredAllSymbolsRead
)
428 if (!get_input_file
) {
429 message(LDPL_ERROR
, "get_input_file not passed to LLVMgold.");
432 if (!release_input_file
) {
433 message(LDPL_ERROR
, "release_input_file not passed to LLVMgold.");
440 static void diagnosticHandler(const DiagnosticInfo
&DI
) {
441 std::string ErrStorage
;
443 raw_string_ostream
OS(ErrStorage
);
444 DiagnosticPrinterRawOStream
DP(OS
);
447 ld_plugin_level Level
;
448 switch (DI
.getSeverity()) {
450 message(LDPL_FATAL
, "LLVM gold plugin has failed to create LTO module: %s",
453 Level
= LDPL_WARNING
;
460 message(Level
, "LLVM gold plugin: %s", ErrStorage
.c_str());
463 static void check(Error E
, std::string Msg
= "LLVM gold plugin") {
464 handleAllErrors(std::move(E
), [&](ErrorInfoBase
&EIB
) -> Error
{
465 message(LDPL_FATAL
, "%s: %s", Msg
.c_str(), EIB
.message().c_str());
466 return Error::success();
470 template <typename T
> static T
check(Expected
<T
> E
) {
472 return std::move(*E
);
473 check(E
.takeError());
477 /// Called by gold to see whether this file is one that our plugin can handle.
478 /// We'll try to open it and register all the symbols with add_symbol if
480 static ld_plugin_status
claim_file_hook(const ld_plugin_input_file
*file
,
482 MemoryBufferRef BufferRef
;
483 std::unique_ptr
<MemoryBuffer
> Buffer
;
486 if (get_view(file
->handle
, &view
) != LDPS_OK
) {
487 message(LDPL_ERROR
, "Failed to get a view of %s", file
->name
);
491 MemoryBufferRef(StringRef((const char *)view
, file
->filesize
), "");
494 // Gold has found what might be IR part-way inside of a file, such as
497 offset
= file
->offset
;
499 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferOrErr
=
500 MemoryBuffer::getOpenFileSlice(file
->fd
, file
->name
, file
->filesize
,
502 if (std::error_code EC
= BufferOrErr
.getError()) {
503 message(LDPL_ERROR
, EC
.message().c_str());
506 Buffer
= std::move(BufferOrErr
.get());
507 BufferRef
= Buffer
->getMemBufferRef();
512 Expected
<std::unique_ptr
<InputFile
>> ObjOrErr
= InputFile::create(BufferRef
);
514 handleAllErrors(ObjOrErr
.takeError(), [&](const ErrorInfoBase
&EI
) {
515 std::error_code EC
= EI
.convertToErrorCode();
516 if (EC
== object::object_error::invalid_file_type
||
517 EC
== object::object_error::bitcode_section_not_found
)
521 "LLVM gold plugin has failed to create LTO module: %s",
522 EI
.message().c_str());
525 return *claimed
? LDPS_ERR
: LDPS_OK
;
528 std::unique_ptr
<InputFile
> Obj
= std::move(*ObjOrErr
);
530 Modules
.emplace_back();
531 claimed_file
&cf
= Modules
.back();
533 cf
.handle
= file
->handle
;
534 // Keep track of the first handle for each file descriptor, since there are
535 // multiple in the case of an archive. This is used later in the case of
536 // ThinLTO parallel backends to ensure that each file is only opened and
539 FDToLeaderHandle
.insert(std::make_pair(file
->fd
, file
->handle
)).first
;
540 cf
.leader_handle
= LeaderHandle
->second
;
541 // Save the filesize since for parallel ThinLTO backends we can only
542 // invoke get_input_file once per archive (only for the leader handle).
543 cf
.filesize
= file
->filesize
;
544 // In the case of an archive library, all but the first member must have a
545 // non-zero offset, which we can append to the file name to obtain a
547 cf
.name
= file
->name
;
549 cf
.name
+= ".llvm." + std::to_string(file
->offset
) + "." +
550 sys::path::filename(Obj
->getSourceFileName()).str();
552 for (auto &Sym
: Obj
->symbols()) {
553 cf
.syms
.push_back(ld_plugin_symbol());
554 ld_plugin_symbol
&sym
= cf
.syms
.back();
555 sym
.version
= nullptr;
556 StringRef Name
= Sym
.getName();
557 sym
.name
= strdup(Name
.str().c_str());
559 ResolutionInfo
&Res
= ResInfo
[Name
];
561 Res
.CanOmitFromDynSym
&= Sym
.canBeOmittedFromSymbolTable();
563 sym
.visibility
= LDPV_DEFAULT
;
564 GlobalValue::VisibilityTypes Vis
= Sym
.getVisibility();
565 if (Vis
!= GlobalValue::DefaultVisibility
)
566 Res
.DefaultVisibility
= false;
568 case GlobalValue::DefaultVisibility
:
570 case GlobalValue::HiddenVisibility
:
571 sym
.visibility
= LDPV_HIDDEN
;
573 case GlobalValue::ProtectedVisibility
:
574 sym
.visibility
= LDPV_PROTECTED
;
578 if (Sym
.isUndefined()) {
579 sym
.def
= LDPK_UNDEF
;
581 sym
.def
= LDPK_WEAKUNDEF
;
582 } else if (Sym
.isCommon())
583 sym
.def
= LDPK_COMMON
;
584 else if (Sym
.isWeak())
585 sym
.def
= LDPK_WEAKDEF
;
590 sym
.comdat_key
= nullptr;
591 int CI
= Sym
.getComdatIndex();
593 StringRef C
= Obj
->getComdatTable()[CI
];
594 sym
.comdat_key
= strdup(C
.str().c_str());
597 sym
.resolution
= LDPR_UNKNOWN
;
600 if (!cf
.syms
.empty()) {
601 if (add_symbols(cf
.handle
, cf
.syms
.size(), cf
.syms
.data()) != LDPS_OK
) {
602 message(LDPL_ERROR
, "Unable to add symbols!");
607 // Handle any --wrap options passed to gold, which are than passed
608 // along to the plugin.
609 if (get_wrap_symbols
) {
610 const char **wrap_symbols
;
612 if (get_wrap_symbols(&count
, &wrap_symbols
) != LDPS_OK
) {
613 message(LDPL_ERROR
, "Unable to get wrap symbols!");
616 for (uint64_t i
= 0; i
< count
; i
++) {
617 StringRef Name
= wrap_symbols
[i
];
618 ResolutionInfo
&Res
= ResInfo
[Name
];
619 ResolutionInfo
&WrapRes
= ResInfo
["__wrap_" + Name
.str()];
620 ResolutionInfo
&RealRes
= ResInfo
["__real_" + Name
.str()];
621 // Tell LTO not to inline symbols that will be overwritten.
622 Res
.CanInline
= false;
623 RealRes
.CanInline
= false;
624 // Tell LTO not to eliminate symbols that will be used after renaming.
625 Res
.IsUsedInRegularObj
= true;
626 WrapRes
.IsUsedInRegularObj
= true;
633 static void freeSymName(ld_plugin_symbol
&Sym
) {
635 free(Sym
.comdat_key
);
637 Sym
.comdat_key
= nullptr;
640 /// Helper to get a file's symbols and a view into it via gold callbacks.
641 static const void *getSymbolsAndView(claimed_file
&F
) {
642 ld_plugin_status status
= get_symbols(F
.handle
, F
.syms
.size(), F
.syms
.data());
643 if (status
== LDPS_NO_SYMS
)
646 if (status
!= LDPS_OK
)
647 message(LDPL_FATAL
, "Failed to get symbol information");
650 if (get_view(F
.handle
, &View
) != LDPS_OK
)
651 message(LDPL_FATAL
, "Failed to get a view of file");
656 /// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
657 /// \p NewSuffix strings, if it was specified.
658 static void getThinLTOOldAndNewSuffix(std::string
&OldSuffix
,
659 std::string
&NewSuffix
) {
660 assert(options::thinlto_object_suffix_replace
.empty() ||
661 options::thinlto_object_suffix_replace
.find(";") != StringRef::npos
);
662 StringRef SuffixReplace
= options::thinlto_object_suffix_replace
;
663 std::tie(OldSuffix
, NewSuffix
) = SuffixReplace
.split(';');
666 /// Given the original \p Path to an output file, replace any filename
667 /// suffix matching \p OldSuffix with \p NewSuffix.
668 static std::string
getThinLTOObjectFileName(StringRef Path
, StringRef OldSuffix
,
669 StringRef NewSuffix
) {
670 if (Path
.consume_back(OldSuffix
))
671 return (Path
+ NewSuffix
).str();
675 // Returns true if S is valid as a C language identifier.
676 static bool isValidCIdentifier(StringRef S
) {
677 return !S
.empty() && (isAlpha(S
[0]) || S
[0] == '_') &&
678 std::all_of(S
.begin() + 1, S
.end(),
679 [](char C
) { return C
== '_' || isAlnum(C
); });
682 static bool isUndefined(ld_plugin_symbol
&Sym
) {
683 return Sym
.def
== LDPK_UNDEF
|| Sym
.def
== LDPK_WEAKUNDEF
;
686 static void addModule(LTO
&Lto
, claimed_file
&F
, const void *View
,
687 StringRef Filename
) {
688 MemoryBufferRef
BufferRef(StringRef((const char *)View
, F
.filesize
),
690 Expected
<std::unique_ptr
<InputFile
>> ObjOrErr
= InputFile::create(BufferRef
);
693 message(LDPL_FATAL
, "Could not read bitcode from file : %s",
694 toString(ObjOrErr
.takeError()).c_str());
697 std::unique_ptr
<InputFile
> Input
= std::move(ObjOrErr
.get());
698 auto InputFileSyms
= Input
->symbols();
699 assert(InputFileSyms
.size() == F
.syms
.size());
700 std::vector
<SymbolResolution
> Resols(F
.syms
.size());
701 for (ld_plugin_symbol
&Sym
: F
.syms
) {
702 const InputFile::Symbol
&InpSym
= InputFileSyms
[SymNum
];
703 SymbolResolution
&R
= Resols
[SymNum
++];
705 ld_plugin_symbol_resolution Resolution
=
706 (ld_plugin_symbol_resolution
)Sym
.resolution
;
708 ResolutionInfo
&Res
= ResInfo
[Sym
.name
];
710 switch (Resolution
) {
712 llvm_unreachable("Unexpected resolution");
714 case LDPR_RESOLVED_IR
:
715 case LDPR_RESOLVED_EXEC
:
716 case LDPR_RESOLVED_DYN
:
717 case LDPR_PREEMPTED_IR
:
718 case LDPR_PREEMPTED_REG
:
722 case LDPR_PREVAILING_DEF_IRONLY
:
723 R
.Prevailing
= !isUndefined(Sym
);
726 case LDPR_PREVAILING_DEF
:
727 R
.Prevailing
= !isUndefined(Sym
);
728 R
.VisibleToRegularObj
= true;
731 case LDPR_PREVAILING_DEF_IRONLY_EXP
:
732 R
.Prevailing
= !isUndefined(Sym
);
733 if (!Res
.CanOmitFromDynSym
)
734 R
.VisibleToRegularObj
= true;
738 // If the symbol has a C identifier section name, we need to mark
739 // it as visible to a regular object so that LTO will keep it around
740 // to ensure the linker generates special __start_<secname> and
741 // __stop_<secname> symbols which may be used elsewhere.
742 if (isValidCIdentifier(InpSym
.getSectionName()))
743 R
.VisibleToRegularObj
= true;
745 if (Resolution
!= LDPR_RESOLVED_DYN
&& Resolution
!= LDPR_UNDEF
&&
746 (IsExecutable
|| !Res
.DefaultVisibility
))
747 R
.FinalDefinitionInLinkageUnit
= true;
750 R
.LinkerRedefined
= true;
752 if (Res
.IsUsedInRegularObj
)
753 R
.VisibleToRegularObj
= true;
758 check(Lto
.add(std::move(Input
), Resols
),
759 std::string("Failed to link module ") + F
.name
);
762 static void recordFile(const std::string
&Filename
, bool TempOutFile
) {
763 if (add_input_file(Filename
.c_str()) != LDPS_OK
)
765 "Unable to add .o file to the link. File left behind in: %s",
768 Cleanup
.push_back(Filename
);
771 /// Return the desired output filename given a base input name, a flag
772 /// indicating whether a temp file should be generated, and an optional task id.
773 /// The new filename generated is returned in \p NewFilename.
774 static int getOutputFileName(StringRef InFilename
, bool TempOutFile
,
775 SmallString
<128> &NewFilename
, int TaskID
) {
779 sys::fs::createTemporaryFile("lto-llvm", "o", FD
, NewFilename
);
781 message(LDPL_FATAL
, "Could not create temporary file: %s",
782 EC
.message().c_str());
784 NewFilename
= InFilename
;
786 NewFilename
+= utostr(TaskID
);
788 sys::fs::openFileForWrite(NewFilename
, FD
, sys::fs::CD_CreateAlways
);
790 message(LDPL_FATAL
, "Could not open file %s: %s", NewFilename
.c_str(),
791 EC
.message().c_str());
796 static CodeGenOpt::Level
getCGOptLevel() {
797 switch (options::OptLevel
) {
799 return CodeGenOpt::None
;
801 return CodeGenOpt::Less
;
803 return CodeGenOpt::Default
;
805 return CodeGenOpt::Aggressive
;
807 llvm_unreachable("Invalid optimization level");
810 /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
811 /// \p NewPrefix strings, if it was specified.
812 static void getThinLTOOldAndNewPrefix(std::string
&OldPrefix
,
813 std::string
&NewPrefix
) {
814 StringRef PrefixReplace
= options::thinlto_prefix_replace
;
815 assert(PrefixReplace
.empty() || PrefixReplace
.find(";") != StringRef::npos
);
816 std::tie(OldPrefix
, NewPrefix
) = PrefixReplace
.split(';');
819 /// Creates instance of LTO.
820 /// OnIndexWrite is callback to let caller know when LTO writes index files.
821 /// LinkedObjectsFile is an output stream to write the list of object files for
822 /// the final ThinLTO linking. Can be nullptr.
823 static std::unique_ptr
<LTO
> createLTO(IndexWriteCallback OnIndexWrite
,
824 raw_fd_ostream
*LinkedObjectsFile
) {
828 Conf
.CPU
= options::mcpu
;
829 Conf
.Options
= InitTargetOptionsFromCodeGenFlags();
831 // Disable the new X86 relax relocations since gold might not support them.
832 // FIXME: Check the gold version or add a new option to enable them.
833 Conf
.Options
.RelaxELFRelocations
= false;
835 // Toggle function/data sections.
836 Conf
.Options
.FunctionSections
= SplitSections
;
837 Conf
.Options
.DataSections
= SplitSections
;
839 Conf
.MAttrs
= MAttrs
;
840 Conf
.RelocModel
= RelocationModel
;
841 Conf
.CodeModel
= getCodeModel();
842 Conf
.CGOptLevel
= getCGOptLevel();
843 Conf
.DisableVerify
= options::DisableVerify
;
844 Conf
.OptLevel
= options::OptLevel
;
845 if (options::Parallelism
)
846 Backend
= createInProcessThinBackend(options::Parallelism
);
847 if (options::thinlto_index_only
) {
848 std::string OldPrefix
, NewPrefix
;
849 getThinLTOOldAndNewPrefix(OldPrefix
, NewPrefix
);
850 Backend
= createWriteIndexesThinBackend(OldPrefix
, NewPrefix
,
851 options::thinlto_emit_imports_files
,
852 LinkedObjectsFile
, OnIndexWrite
);
855 Conf
.OverrideTriple
= options::triple
;
856 Conf
.DefaultTriple
= sys::getDefaultTargetTriple();
858 Conf
.DiagHandler
= diagnosticHandler
;
860 switch (options::TheOutputType
) {
861 case options::OT_NORMAL
:
864 case options::OT_DISABLE
:
865 Conf
.PreOptModuleHook
= [](size_t Task
, const Module
&M
) { return false; };
868 case options::OT_BC_ONLY
:
869 Conf
.PostInternalizeModuleHook
= [](size_t Task
, const Module
&M
) {
871 raw_fd_ostream
OS(output_name
, EC
, sys::fs::OpenFlags::F_None
);
873 message(LDPL_FATAL
, "Failed to write the output file.");
874 WriteBitcodeToFile(M
, OS
, /* ShouldPreserveUseListOrder */ false);
879 case options::OT_SAVE_TEMPS
:
880 check(Conf
.addSaveTemps(output_name
+ ".",
881 /* UseInputModulePath */ true));
885 if (!options::sample_profile
.empty())
886 Conf
.SampleProfile
= options::sample_profile
;
888 Conf
.DwoDir
= options::dwo_dir
;
890 // Set up optimization remarks handling.
891 Conf
.RemarksFilename
= options::OptRemarksFilename
;
892 Conf
.RemarksWithHotness
= options::OptRemarksWithHotness
;
894 // Use new pass manager if set in driver
895 Conf
.UseNewPM
= options::new_pass_manager
;
896 // Debug new pass manager if requested
897 Conf
.DebugPassManager
= options::debug_pass_manager
;
899 Conf
.StatsFile
= options::stats_file
;
900 return llvm::make_unique
<LTO
>(std::move(Conf
), Backend
,
901 options::ParallelCodeGenParallelismLevel
);
904 // Write empty files that may be expected by a distributed build
905 // system when invoked with thinlto_index_only. This is invoked when
906 // the linker has decided not to include the given module in the
907 // final link. Frequently the distributed build system will want to
908 // confirm that all expected outputs are created based on all of the
909 // modules provided to the linker.
910 // If SkipModule is true then .thinlto.bc should contain just
911 // SkipModuleByDistributedBackend flag which requests distributed backend
912 // to skip the compilation of the corresponding module and produce an empty
914 static void writeEmptyDistributedBuildOutputs(const std::string
&ModulePath
,
915 const std::string
&OldPrefix
,
916 const std::string
&NewPrefix
,
918 std::string NewModulePath
=
919 getThinLTOOutputFile(ModulePath
, OldPrefix
, NewPrefix
);
922 raw_fd_ostream
OS(NewModulePath
+ ".thinlto.bc", EC
,
923 sys::fs::OpenFlags::F_None
);
925 message(LDPL_FATAL
, "Failed to write '%s': %s",
926 (NewModulePath
+ ".thinlto.bc").c_str(), EC
.message().c_str());
929 ModuleSummaryIndex
Index(/*HaveGVs*/ false);
930 Index
.setSkipModuleByDistributedBackend();
931 WriteIndexToFile(Index
, OS
, nullptr);
934 if (options::thinlto_emit_imports_files
) {
935 raw_fd_ostream
OS(NewModulePath
+ ".imports", EC
,
936 sys::fs::OpenFlags::F_None
);
938 message(LDPL_FATAL
, "Failed to write '%s': %s",
939 (NewModulePath
+ ".imports").c_str(), EC
.message().c_str());
943 // Creates and returns output stream with a list of object files for final
944 // linking of distributed ThinLTO.
945 static std::unique_ptr
<raw_fd_ostream
> CreateLinkedObjectsFile() {
946 if (options::thinlto_linked_objects_file
.empty())
948 assert(options::thinlto_index_only
);
950 auto LinkedObjectsFile
= llvm::make_unique
<raw_fd_ostream
>(
951 options::thinlto_linked_objects_file
, EC
, sys::fs::OpenFlags::F_None
);
953 message(LDPL_FATAL
, "Failed to create '%s': %s",
954 options::thinlto_linked_objects_file
.c_str(), EC
.message().c_str());
955 return LinkedObjectsFile
;
958 /// Runs LTO and return a list of pairs <FileName, IsTemporary>.
959 static std::vector
<std::pair
<SmallString
<128>, bool>> runLTO() {
960 // Map to own RAII objects that manage the file opening and releasing
961 // interfaces with gold. This is needed only for ThinLTO mode, since
962 // unlike regular LTO, where addModule will result in the opened file
963 // being merged into a new combined module, we need to keep these files open
964 // through Lto->run().
965 DenseMap
<void *, std::unique_ptr
<PluginInputFile
>> HandleToInputFile
;
967 // Owns string objects and tells if index file was already created.
968 StringMap
<bool> ObjectToIndexFileState
;
970 std::unique_ptr
<raw_fd_ostream
> LinkedObjects
= CreateLinkedObjectsFile();
971 std::unique_ptr
<LTO
> Lto
= createLTO(
972 [&ObjectToIndexFileState
](const std::string
&Identifier
) {
973 ObjectToIndexFileState
[Identifier
] = true;
975 LinkedObjects
.get());
977 std::string OldPrefix
, NewPrefix
;
978 if (options::thinlto_index_only
)
979 getThinLTOOldAndNewPrefix(OldPrefix
, NewPrefix
);
981 std::string OldSuffix
, NewSuffix
;
982 getThinLTOOldAndNewSuffix(OldSuffix
, NewSuffix
);
984 for (claimed_file
&F
: Modules
) {
985 if (options::thinlto
&& !HandleToInputFile
.count(F
.leader_handle
))
986 HandleToInputFile
.insert(std::make_pair(
987 F
.leader_handle
, llvm::make_unique
<PluginInputFile
>(F
.handle
)));
988 // In case we are thin linking with a minimized bitcode file, ensure
989 // the module paths encoded in the index reflect where the backends
990 // will locate the full bitcode files for compiling/importing.
991 std::string Identifier
=
992 getThinLTOObjectFileName(F
.name
, OldSuffix
, NewSuffix
);
993 auto ObjFilename
= ObjectToIndexFileState
.insert({Identifier
, false});
994 assert(ObjFilename
.second
);
995 if (const void *View
= getSymbolsAndView(F
))
996 addModule(*Lto
, F
, View
, ObjFilename
.first
->first());
997 else if (options::thinlto_index_only
) {
998 ObjFilename
.first
->second
= true;
999 writeEmptyDistributedBuildOutputs(Identifier
, OldPrefix
, NewPrefix
,
1000 /* SkipModule */ true);
1004 SmallString
<128> Filename
;
1005 // Note that getOutputFileName will append a unique ID for each task
1006 if (!options::obj_path
.empty())
1007 Filename
= options::obj_path
;
1008 else if (options::TheOutputType
== options::OT_SAVE_TEMPS
)
1009 Filename
= output_name
+ ".o";
1010 bool SaveTemps
= !Filename
.empty();
1012 size_t MaxTasks
= Lto
->getMaxTasks();
1013 std::vector
<std::pair
<SmallString
<128>, bool>> Files(MaxTasks
);
1016 [&](size_t Task
) -> std::unique_ptr
<lto::NativeObjectStream
> {
1017 Files
[Task
].second
= !SaveTemps
;
1018 int FD
= getOutputFileName(Filename
, /* TempOutFile */ !SaveTemps
,
1019 Files
[Task
].first
, Task
);
1020 return llvm::make_unique
<lto::NativeObjectStream
>(
1021 llvm::make_unique
<llvm::raw_fd_ostream
>(FD
, true));
1024 auto AddBuffer
= [&](size_t Task
, std::unique_ptr
<MemoryBuffer
> MB
) {
1025 *AddStream(Task
)->OS
<< MB
->getBuffer();
1028 NativeObjectCache Cache
;
1029 if (!options::cache_dir
.empty())
1030 Cache
= check(localCache(options::cache_dir
, AddBuffer
));
1032 check(Lto
->run(AddStream
, Cache
));
1034 // Write empty output files that may be expected by the distributed build
1036 if (options::thinlto_index_only
)
1037 for (auto &Identifier
: ObjectToIndexFileState
)
1038 if (!Identifier
.getValue())
1039 writeEmptyDistributedBuildOutputs(Identifier
.getKey(), OldPrefix
,
1040 NewPrefix
, /* SkipModule */ false);
1045 /// gold informs us that all symbols have been read. At this point, we use
1046 /// get_symbols to see if any of our definitions have been overridden by a
1047 /// native object file. Then, perform optimization and codegen.
1048 static ld_plugin_status
allSymbolsReadHook() {
1049 if (Modules
.empty())
1052 if (unsigned NumOpts
= options::extra
.size())
1053 cl::ParseCommandLineOptions(NumOpts
, &options::extra
[0]);
1055 std::vector
<std::pair
<SmallString
<128>, bool>> Files
= runLTO();
1057 if (options::TheOutputType
== options::OT_DISABLE
||
1058 options::TheOutputType
== options::OT_BC_ONLY
)
1061 if (options::thinlto_index_only
) {
1067 for (const auto &F
: Files
)
1068 if (!F
.first
.empty())
1069 recordFile(F
.first
.str(), F
.second
);
1071 if (!options::extra_library_path
.empty() &&
1072 set_extra_library_path(options::extra_library_path
.c_str()) != LDPS_OK
)
1073 message(LDPL_FATAL
, "Unable to set the extra library path.");
1078 static ld_plugin_status
all_symbols_read_hook(void) {
1079 ld_plugin_status Ret
= allSymbolsReadHook();
1082 if (options::TheOutputType
== options::OT_BC_ONLY
||
1083 options::TheOutputType
== options::OT_DISABLE
) {
1084 if (options::TheOutputType
== options::OT_DISABLE
) {
1085 // Remove the output file here since ld.bfd creates the output file
1087 std::error_code EC
= sys::fs::remove(output_name
);
1089 message(LDPL_ERROR
, "Failed to delete '%s': %s", output_name
.c_str(),
1090 EC
.message().c_str());
1098 static ld_plugin_status
cleanup_hook(void) {
1099 for (std::string
&Name
: Cleanup
) {
1100 std::error_code EC
= sys::fs::remove(Name
);
1102 message(LDPL_ERROR
, "Failed to delete '%s': %s", Name
.c_str(),
1103 EC
.message().c_str());
1107 if (!options::cache_dir
.empty()) {
1108 CachePruningPolicy policy
= check(parseCachePruningPolicy(options::cache_policy
));
1109 pruneCache(options::cache_dir
, policy
);