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 .
12 //
13 //===----------------------------------------------------------------------===//
14 
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_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>
40 
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
44 
45 #define LDPT_GET_SYMBOLS_V3 28
46 
47 using namespace llvm;
48 using namespace lto;
49 
50 static ld_plugin_status discard_message(int level, const char *format, ...) {
51   // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
52   // callback in the transfer vector. This should never be called.
53   abort();
54 }
55 
56 static ld_plugin_release_input_file release_input_file = nullptr;
57 static ld_plugin_get_input_file get_input_file = nullptr;
58 static ld_plugin_message message = discard_message;
59 
60 namespace {
61 struct claimed_file {
62   void *handle;
63   void *leader_handle;
64   std::vector<ld_plugin_symbol> syms;
65   off_t filesize;
66   std::string name;
67 };
68 
69 /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
70 struct PluginInputFile {
71   void *Handle;
72   std::unique_ptr<ld_plugin_input_file> File;
73 
74   PluginInputFile(void *Handle) : Handle(Handle) {
75     File = llvm::make_unique<ld_plugin_input_file>();
76     if (get_input_file(Handle, File.get()) != LDPS_OK)
77       message(LDPL_FATAL, "Failed to get file information");
78   }
79   ~PluginInputFile() {
80     // File would have been reset to nullptr if we moved this object
81     // to a new owner.
82     if (File)
83       if (release_input_file(Handle) != LDPS_OK)
84         message(LDPL_FATAL, "Failed to release file information");
85   }
86 
87   ld_plugin_input_file &file() { return *File; }
88 
89   PluginInputFile(PluginInputFile &&RHS) = default;
90   PluginInputFile &operator=(PluginInputFile &&RHS) = default;
91 };
92 
93 struct ResolutionInfo {
94   bool CanOmitFromDynSym = true;
95   bool DefaultVisibility = true;
96 };
97 
98 }
99 
100 static ld_plugin_add_symbols add_symbols = nullptr;
101 static ld_plugin_get_symbols get_symbols = nullptr;
102 static ld_plugin_add_input_file add_input_file = nullptr;
103 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
104 static ld_plugin_get_view get_view = nullptr;
105 static bool IsExecutable = false;
106 static Optional<Reloc::Model> RelocationModel = None;
107 static std::string output_name = "";
108 static std::list<claimed_file> Modules;
109 static DenseMap<int, void *> FDToLeaderHandle;
110 static StringMap<ResolutionInfo> ResInfo;
111 static std::vector<std::string> Cleanup;
112 
113 namespace options {
114   enum OutputType {
115     OT_NORMAL,
116     OT_DISABLE,
117     OT_BC_ONLY,
118     OT_SAVE_TEMPS
119   };
120   static OutputType TheOutputType = OT_NORMAL;
121   static unsigned OptLevel = 2;
122   // Default parallelism of 0 used to indicate that user did not specify.
123   // Actual parallelism default value depends on implementation.
124   // Currently only affects ThinLTO, where the default is
125   // llvm::heavyweight_hardware_concurrency.
126   static unsigned Parallelism = 0;
127   // Default regular LTO codegen parallelism (number of partitions).
128   static unsigned ParallelCodeGenParallelismLevel = 1;
129 #ifdef NDEBUG
130   static bool DisableVerify = true;
131 #else
132   static bool DisableVerify = false;
133 #endif
134   static std::string obj_path;
135   static std::string extra_library_path;
136   static std::string triple;
137   static std::string mcpu;
138   // When the thinlto plugin option is specified, only read the function
139   // the information from intermediate files and write a combined
140   // global index for the ThinLTO backends.
141   static bool thinlto = false;
142   // If false, all ThinLTO backend compilations through code gen are performed
143   // using multiple threads in the gold-plugin, before handing control back to
144   // gold. If true, write individual backend index files which reflect
145   // the import decisions, and exit afterwards. The assumption is
146   // that the build system will launch the backend processes.
147   static bool thinlto_index_only = false;
148   // If non-empty, holds the name of a file in which to write the list of
149   // oject files gold selected for inclusion in the link after symbol
150   // resolution (i.e. they had selected symbols). This will only be non-empty
151   // in the thinlto_index_only case. It is used to identify files, which may
152   // have originally been within archive libraries specified via
153   // --start-lib/--end-lib pairs, that should be included in the final
154   // native link process (since intervening function importing and inlining
155   // may change the symbol resolution detected in the final link and which
156   // files to include out of --start-lib/--end-lib libraries as a result).
157   static std::string thinlto_linked_objects_file;
158   // If true, when generating individual index files for distributed backends,
159   // also generate a "${bitcodefile}.imports" file at the same location for each
160   // bitcode file, listing the files it imports from in plain text. This is to
161   // support distributed build file staging.
162   static bool thinlto_emit_imports_files = false;
163   // Option to control where files for a distributed backend (the individual
164   // index files and optional imports files) are created.
165   // If specified, expects a string of the form "oldprefix:newprefix", and
166   // instead of generating these files in the same directory path as the
167   // corresponding bitcode file, will use a path formed by replacing the
168   // bitcode file's path prefix matching oldprefix with newprefix.
169   static std::string thinlto_prefix_replace;
170   // Option to control the name of modules encoded in the individual index
171   // files for a distributed backend. This enables the use of minimized
172   // bitcode files for the thin link, assuming the name of the full bitcode
173   // file used in the backend differs just in some part of the file suffix.
174   // If specified, expects a string of the form "oldsuffix:newsuffix".
175   static std::string thinlto_object_suffix_replace;
176   // Optional path to a directory for caching ThinLTO objects.
177   static std::string cache_dir;
178   // Optional pruning policy for ThinLTO caches.
179   static std::string cache_policy;
180   // Additional options to pass into the code generator.
181   // Note: This array will contain all plugin options which are not claimed
182   // as plugin exclusive to pass to the code generator.
183   static std::vector<const char *> extra;
184   // Sample profile file path
185   static std::string sample_profile;
186 
187   static void process_plugin_option(const char *opt_)
188   {
189     if (opt_ == nullptr)
190       return;
191     llvm::StringRef opt = opt_;
192 
193     if (opt.startswith("mcpu=")) {
194       mcpu = opt.substr(strlen("mcpu="));
195     } else if (opt.startswith("extra-library-path=")) {
196       extra_library_path = opt.substr(strlen("extra_library_path="));
197     } else if (opt.startswith("mtriple=")) {
198       triple = opt.substr(strlen("mtriple="));
199     } else if (opt.startswith("obj-path=")) {
200       obj_path = opt.substr(strlen("obj-path="));
201     } else if (opt == "emit-llvm") {
202       TheOutputType = OT_BC_ONLY;
203     } else if (opt == "save-temps") {
204       TheOutputType = OT_SAVE_TEMPS;
205     } else if (opt == "disable-output") {
206       TheOutputType = OT_DISABLE;
207     } else if (opt == "thinlto") {
208       thinlto = true;
209     } else if (opt == "thinlto-index-only") {
210       thinlto_index_only = true;
211     } else if (opt.startswith("thinlto-index-only=")) {
212       thinlto_index_only = true;
213       thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
214     } else if (opt == "thinlto-emit-imports-files") {
215       thinlto_emit_imports_files = true;
216     } else if (opt.startswith("thinlto-prefix-replace=")) {
217       thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
218       if (thinlto_prefix_replace.find(';') == std::string::npos)
219         message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
220     } else if (opt.startswith("thinlto-object-suffix-replace=")) {
221       thinlto_object_suffix_replace =
222           opt.substr(strlen("thinlto-object-suffix-replace="));
223       if (thinlto_object_suffix_replace.find(';') == std::string::npos)
224         message(LDPL_FATAL,
225                 "thinlto-object-suffix-replace expects 'old;new' format");
226     } else if (opt.startswith("cache-dir=")) {
227       cache_dir = opt.substr(strlen("cache-dir="));
228     } else if (opt.startswith("cache-policy=")) {
229       cache_policy = opt.substr(strlen("cache-policy="));
230     } else if (opt.size() == 2 && opt[0] == 'O') {
231       if (opt[1] < '0' || opt[1] > '3')
232         message(LDPL_FATAL, "Optimization level must be between 0 and 3");
233       OptLevel = opt[1] - '0';
234     } else if (opt.startswith("jobs=")) {
235       if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
236         message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
237     } else if (opt.startswith("lto-partitions=")) {
238       if (opt.substr(strlen("lto-partitions="))
239               .getAsInteger(10, ParallelCodeGenParallelismLevel))
240         message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
241     } else if (opt == "disable-verify") {
242       DisableVerify = true;
243     } else if (opt.startswith("sample-profile=")) {
244       sample_profile= opt.substr(strlen("sample-profile="));
245     } else {
246       // Save this option to pass to the code generator.
247       // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
248       // add that.
249       if (extra.empty())
250         extra.push_back("LLVMgold");
251 
252       extra.push_back(opt_);
253     }
254   }
255 }
256 
257 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
258                                         int *claimed);
259 static ld_plugin_status all_symbols_read_hook(void);
260 static ld_plugin_status cleanup_hook(void);
261 
262 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
263 ld_plugin_status onload(ld_plugin_tv *tv) {
264   InitializeAllTargetInfos();
265   InitializeAllTargets();
266   InitializeAllTargetMCs();
267   InitializeAllAsmParsers();
268   InitializeAllAsmPrinters();
269 
270   // We're given a pointer to the first transfer vector. We read through them
271   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
272   // contain pointers to functions that we need to call to register our own
273   // hooks. The others are addresses of functions we can use to call into gold
274   // for services.
275 
276   bool registeredClaimFile = false;
277   bool RegisteredAllSymbolsRead = false;
278 
279   for (; tv->tv_tag != LDPT_NULL; ++tv) {
280     // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
281     // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
282     // header.
283     switch (static_cast<int>(tv->tv_tag)) {
284     case LDPT_OUTPUT_NAME:
285       output_name = tv->tv_u.tv_string;
286       break;
287     case LDPT_LINKER_OUTPUT:
288       switch (tv->tv_u.tv_val) {
289       case LDPO_REL: // .o
290         IsExecutable = false;
291         break;
292       case LDPO_DYN: // .so
293         IsExecutable = false;
294         RelocationModel = Reloc::PIC_;
295         break;
296       case LDPO_PIE: // position independent executable
297         IsExecutable = true;
298         RelocationModel = Reloc::PIC_;
299         break;
300       case LDPO_EXEC: // .exe
301         IsExecutable = true;
302         RelocationModel = Reloc::Static;
303         break;
304       default:
305         message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
306         return LDPS_ERR;
307       }
308       break;
309     case LDPT_OPTION:
310       options::process_plugin_option(tv->tv_u.tv_string);
311       break;
312     case LDPT_REGISTER_CLAIM_FILE_HOOK: {
313       ld_plugin_register_claim_file callback;
314       callback = tv->tv_u.tv_register_claim_file;
315 
316       if (callback(claim_file_hook) != LDPS_OK)
317         return LDPS_ERR;
318 
319       registeredClaimFile = true;
320     } break;
321     case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
322       ld_plugin_register_all_symbols_read callback;
323       callback = tv->tv_u.tv_register_all_symbols_read;
324 
325       if (callback(all_symbols_read_hook) != LDPS_OK)
326         return LDPS_ERR;
327 
328       RegisteredAllSymbolsRead = true;
329     } break;
330     case LDPT_REGISTER_CLEANUP_HOOK: {
331       ld_plugin_register_cleanup callback;
332       callback = tv->tv_u.tv_register_cleanup;
333 
334       if (callback(cleanup_hook) != LDPS_OK)
335         return LDPS_ERR;
336     } break;
337     case LDPT_GET_INPUT_FILE:
338       get_input_file = tv->tv_u.tv_get_input_file;
339       break;
340     case LDPT_RELEASE_INPUT_FILE:
341       release_input_file = tv->tv_u.tv_release_input_file;
342       break;
343     case LDPT_ADD_SYMBOLS:
344       add_symbols = tv->tv_u.tv_add_symbols;
345       break;
346     case LDPT_GET_SYMBOLS_V2:
347       // Do not override get_symbols_v3 with get_symbols_v2.
348       if (!get_symbols)
349         get_symbols = tv->tv_u.tv_get_symbols;
350       break;
351     case LDPT_GET_SYMBOLS_V3:
352       get_symbols = tv->tv_u.tv_get_symbols;
353       break;
354     case LDPT_ADD_INPUT_FILE:
355       add_input_file = tv->tv_u.tv_add_input_file;
356       break;
357     case LDPT_SET_EXTRA_LIBRARY_PATH:
358       set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
359       break;
360     case LDPT_GET_VIEW:
361       get_view = tv->tv_u.tv_get_view;
362       break;
363     case LDPT_MESSAGE:
364       message = tv->tv_u.tv_message;
365       break;
366     default:
367       break;
368     }
369   }
370 
371   if (!registeredClaimFile) {
372     message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
373     return LDPS_ERR;
374   }
375   if (!add_symbols) {
376     message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
377     return LDPS_ERR;
378   }
379 
380   if (!RegisteredAllSymbolsRead)
381     return LDPS_OK;
382 
383   if (!get_input_file) {
384     message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
385     return LDPS_ERR;
386   }
387   if (!release_input_file) {
388     message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
389     return LDPS_ERR;
390   }
391 
392   return LDPS_OK;
393 }
394 
395 static void diagnosticHandler(const DiagnosticInfo &DI) {
396   std::string ErrStorage;
397   {
398     raw_string_ostream OS(ErrStorage);
399     DiagnosticPrinterRawOStream DP(OS);
400     DI.print(DP);
401   }
402   ld_plugin_level Level;
403   switch (DI.getSeverity()) {
404   case DS_Error:
405     message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
406             ErrStorage.c_str());
407   case DS_Warning:
408     Level = LDPL_WARNING;
409     break;
410   case DS_Note:
411   case DS_Remark:
412     Level = LDPL_INFO;
413     break;
414   }
415   message(Level, "LLVM gold plugin: %s",  ErrStorage.c_str());
416 }
417 
418 static void check(Error E, std::string Msg = "LLVM gold plugin") {
419   handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
420     message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
421     return Error::success();
422   });
423 }
424 
425 template <typename T> static T check(Expected<T> E) {
426   if (E)
427     return std::move(*E);
428   check(E.takeError());
429   return T();
430 }
431 
432 /// Called by gold to see whether this file is one that our plugin can handle.
433 /// We'll try to open it and register all the symbols with add_symbol if
434 /// possible.
435 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
436                                         int *claimed) {
437   MemoryBufferRef BufferRef;
438   std::unique_ptr<MemoryBuffer> Buffer;
439   if (get_view) {
440     const void *view;
441     if (get_view(file->handle, &view) != LDPS_OK) {
442       message(LDPL_ERROR, "Failed to get a view of %s", file->name);
443       return LDPS_ERR;
444     }
445     BufferRef =
446         MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
447   } else {
448     int64_t offset = 0;
449     // Gold has found what might be IR part-way inside of a file, such as
450     // an .a archive.
451     if (file->offset) {
452       offset = file->offset;
453     }
454     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
455         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
456                                        offset);
457     if (std::error_code EC = BufferOrErr.getError()) {
458       message(LDPL_ERROR, EC.message().c_str());
459       return LDPS_ERR;
460     }
461     Buffer = std::move(BufferOrErr.get());
462     BufferRef = Buffer->getMemBufferRef();
463   }
464 
465   *claimed = 1;
466 
467   Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
468   if (!ObjOrErr) {
469     handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
470       std::error_code EC = EI.convertToErrorCode();
471       if (EC == object::object_error::invalid_file_type ||
472           EC == object::object_error::bitcode_section_not_found)
473         *claimed = 0;
474       else
475         message(LDPL_FATAL,
476                 "LLVM gold plugin has failed to create LTO module: %s",
477                 EI.message().c_str());
478     });
479 
480     return *claimed ? LDPS_ERR : LDPS_OK;
481   }
482 
483   std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
484 
485   Modules.emplace_back();
486   claimed_file &cf = Modules.back();
487 
488   cf.handle = file->handle;
489   // Keep track of the first handle for each file descriptor, since there are
490   // multiple in the case of an archive. This is used later in the case of
491   // ThinLTO parallel backends to ensure that each file is only opened and
492   // released once.
493   auto LeaderHandle =
494       FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
495   cf.leader_handle = LeaderHandle->second;
496   // Save the filesize since for parallel ThinLTO backends we can only
497   // invoke get_input_file once per archive (only for the leader handle).
498   cf.filesize = file->filesize;
499   // In the case of an archive library, all but the first member must have a
500   // non-zero offset, which we can append to the file name to obtain a
501   // unique name.
502   cf.name = file->name;
503   if (file->offset)
504     cf.name += ".llvm." + std::to_string(file->offset) + "." +
505                sys::path::filename(Obj->getSourceFileName()).str();
506 
507   for (auto &Sym : Obj->symbols()) {
508     cf.syms.push_back(ld_plugin_symbol());
509     ld_plugin_symbol &sym = cf.syms.back();
510     sym.version = nullptr;
511     StringRef Name = Sym.getName();
512     sym.name = strdup(Name.str().c_str());
513 
514     ResolutionInfo &Res = ResInfo[Name];
515 
516     Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
517 
518     sym.visibility = LDPV_DEFAULT;
519     GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
520     if (Vis != GlobalValue::DefaultVisibility)
521       Res.DefaultVisibility = false;
522     switch (Vis) {
523     case GlobalValue::DefaultVisibility:
524       break;
525     case GlobalValue::HiddenVisibility:
526       sym.visibility = LDPV_HIDDEN;
527       break;
528     case GlobalValue::ProtectedVisibility:
529       sym.visibility = LDPV_PROTECTED;
530       break;
531     }
532 
533     if (Sym.isUndefined()) {
534       sym.def = LDPK_UNDEF;
535       if (Sym.isWeak())
536         sym.def = LDPK_WEAKUNDEF;
537     } else if (Sym.isCommon())
538       sym.def = LDPK_COMMON;
539     else if (Sym.isWeak())
540       sym.def = LDPK_WEAKDEF;
541     else
542       sym.def = LDPK_DEF;
543 
544     sym.size = 0;
545     sym.comdat_key = nullptr;
546     int CI = Sym.getComdatIndex();
547     if (CI != -1) {
548       StringRef C = Obj->getComdatTable()[CI];
549       sym.comdat_key = strdup(C.str().c_str());
550     }
551 
552     sym.resolution = LDPR_UNKNOWN;
553   }
554 
555   if (!cf.syms.empty()) {
556     if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
557       message(LDPL_ERROR, "Unable to add symbols!");
558       return LDPS_ERR;
559     }
560   }
561 
562   return LDPS_OK;
563 }
564 
565 static void freeSymName(ld_plugin_symbol &Sym) {
566   free(Sym.name);
567   free(Sym.comdat_key);
568   Sym.name = nullptr;
569   Sym.comdat_key = nullptr;
570 }
571 
572 /// Helper to get a file's symbols and a view into it via gold callbacks.
573 static const void *getSymbolsAndView(claimed_file &F) {
574   ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
575   if (status == LDPS_NO_SYMS)
576     return nullptr;
577 
578   if (status != LDPS_OK)
579     message(LDPL_FATAL, "Failed to get symbol information");
580 
581   const void *View;
582   if (get_view(F.handle, &View) != LDPS_OK)
583     message(LDPL_FATAL, "Failed to get a view of file");
584 
585   return View;
586 }
587 
588 /// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
589 /// \p NewSuffix strings, if it was specified.
590 static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
591                                       std::string &NewSuffix) {
592   assert(options::thinlto_object_suffix_replace.empty() ||
593          options::thinlto_object_suffix_replace.find(";") != StringRef::npos);
594   StringRef SuffixReplace = options::thinlto_object_suffix_replace;
595   std::tie(OldSuffix, NewSuffix) = SuffixReplace.split(';');
596 }
597 
598 /// Given the original \p Path to an output file, replace any filename
599 /// suffix matching \p OldSuffix with \p NewSuffix.
600 static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
601                                             StringRef NewSuffix) {
602   if (OldSuffix.empty() && NewSuffix.empty())
603     return Path;
604   StringRef NewPath = Path;
605   NewPath.consume_back(OldSuffix);
606   std::string NewNewPath = NewPath;
607   NewNewPath += NewSuffix;
608   return NewNewPath;
609 }
610 
611 // Returns true if S is valid as a C language identifier.
612 static bool isValidCIdentifier(StringRef S) {
613   return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
614          std::all_of(S.begin() + 1, S.end(),
615                      [](char C) { return C == '_' || isAlnum(C); });
616 }
617 
618 static void addModule(LTO &Lto, claimed_file &F, const void *View,
619                       StringRef Filename) {
620   MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
621                             Filename);
622   Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
623 
624   if (!ObjOrErr)
625     message(LDPL_FATAL, "Could not read bitcode from file : %s",
626             toString(ObjOrErr.takeError()).c_str());
627 
628   unsigned SymNum = 0;
629   std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
630   auto InputFileSyms = Input->symbols();
631   assert(InputFileSyms.size() == F.syms.size());
632   std::vector<SymbolResolution> Resols(F.syms.size());
633   for (ld_plugin_symbol &Sym : F.syms) {
634     const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
635     SymbolResolution &R = Resols[SymNum++];
636 
637     ld_plugin_symbol_resolution Resolution =
638         (ld_plugin_symbol_resolution)Sym.resolution;
639 
640     ResolutionInfo &Res = ResInfo[Sym.name];
641 
642     switch (Resolution) {
643     case LDPR_UNKNOWN:
644       llvm_unreachable("Unexpected resolution");
645 
646     case LDPR_RESOLVED_IR:
647     case LDPR_RESOLVED_EXEC:
648     case LDPR_RESOLVED_DYN:
649     case LDPR_PREEMPTED_IR:
650     case LDPR_PREEMPTED_REG:
651     case LDPR_UNDEF:
652       break;
653 
654     case LDPR_PREVAILING_DEF_IRONLY:
655       R.Prevailing = true;
656       break;
657 
658     case LDPR_PREVAILING_DEF:
659       R.Prevailing = true;
660       R.VisibleToRegularObj = true;
661       break;
662 
663     case LDPR_PREVAILING_DEF_IRONLY_EXP:
664       R.Prevailing = true;
665       if (!Res.CanOmitFromDynSym)
666         R.VisibleToRegularObj = true;
667       break;
668     }
669 
670     // If the symbol has a C identifier section name, we need to mark
671     // it as visible to a regular object so that LTO will keep it around
672     // to ensure the linker generates special __start_<secname> and
673     // __stop_<secname> symbols which may be used elsewhere.
674     if (isValidCIdentifier(InpSym.getSectionName()))
675       R.VisibleToRegularObj = true;
676 
677     if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
678         (IsExecutable || !Res.DefaultVisibility))
679       R.FinalDefinitionInLinkageUnit = true;
680 
681     freeSymName(Sym);
682   }
683 
684   check(Lto.add(std::move(Input), Resols),
685         std::string("Failed to link module ") + F.name);
686 }
687 
688 static void recordFile(const std::string &Filename, bool TempOutFile) {
689   if (add_input_file(Filename.c_str()) != LDPS_OK)
690     message(LDPL_FATAL,
691             "Unable to add .o file to the link. File left behind in: %s",
692             Filename.c_str());
693   if (TempOutFile)
694     Cleanup.push_back(Filename);
695 }
696 
697 /// Return the desired output filename given a base input name, a flag
698 /// indicating whether a temp file should be generated, and an optional task id.
699 /// The new filename generated is returned in \p NewFilename.
700 static int getOutputFileName(StringRef InFilename, bool TempOutFile,
701                              SmallString<128> &NewFilename, int TaskID) {
702   int FD = -1;
703   if (TempOutFile) {
704     std::error_code EC =
705         sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
706     if (EC)
707       message(LDPL_FATAL, "Could not create temporary file: %s",
708               EC.message().c_str());
709   } else {
710     NewFilename = InFilename;
711     if (TaskID > 0)
712       NewFilename += utostr(TaskID);
713     std::error_code EC =
714         sys::fs::openFileForWrite(NewFilename, FD, sys::fs::F_None);
715     if (EC)
716       message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
717               EC.message().c_str());
718   }
719   return FD;
720 }
721 
722 static CodeGenOpt::Level getCGOptLevel() {
723   switch (options::OptLevel) {
724   case 0:
725     return CodeGenOpt::None;
726   case 1:
727     return CodeGenOpt::Less;
728   case 2:
729     return CodeGenOpt::Default;
730   case 3:
731     return CodeGenOpt::Aggressive;
732   }
733   llvm_unreachable("Invalid optimization level");
734 }
735 
736 /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
737 /// \p NewPrefix strings, if it was specified.
738 static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
739                                       std::string &NewPrefix) {
740   StringRef PrefixReplace = options::thinlto_prefix_replace;
741   assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
742   std::tie(OldPrefix, NewPrefix) = PrefixReplace.split(';');
743 }
744 
745 static std::unique_ptr<LTO> createLTO() {
746   Config Conf;
747   ThinBackend Backend;
748 
749   Conf.CPU = options::mcpu;
750   Conf.Options = InitTargetOptionsFromCodeGenFlags();
751 
752   // Disable the new X86 relax relocations since gold might not support them.
753   // FIXME: Check the gold version or add a new option to enable them.
754   Conf.Options.RelaxELFRelocations = false;
755 
756   // Enable function/data sections by default.
757   Conf.Options.FunctionSections = true;
758   Conf.Options.DataSections = true;
759 
760   Conf.MAttrs = MAttrs;
761   Conf.RelocModel = RelocationModel;
762   Conf.CGOptLevel = getCGOptLevel();
763   Conf.DisableVerify = options::DisableVerify;
764   Conf.OptLevel = options::OptLevel;
765   if (options::Parallelism)
766     Backend = createInProcessThinBackend(options::Parallelism);
767   if (options::thinlto_index_only) {
768     std::string OldPrefix, NewPrefix;
769     getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
770     Backend = createWriteIndexesThinBackend(
771         OldPrefix, NewPrefix, options::thinlto_emit_imports_files,
772         options::thinlto_linked_objects_file);
773   }
774 
775   Conf.OverrideTriple = options::triple;
776   Conf.DefaultTriple = sys::getDefaultTargetTriple();
777 
778   Conf.DiagHandler = diagnosticHandler;
779 
780   switch (options::TheOutputType) {
781   case options::OT_NORMAL:
782     break;
783 
784   case options::OT_DISABLE:
785     Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
786     break;
787 
788   case options::OT_BC_ONLY:
789     Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
790       std::error_code EC;
791       raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
792       if (EC)
793         message(LDPL_FATAL, "Failed to write the output file.");
794       WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ false);
795       return false;
796     };
797     break;
798 
799   case options::OT_SAVE_TEMPS:
800     check(Conf.addSaveTemps(output_name + ".",
801                             /* UseInputModulePath */ true));
802     break;
803   }
804 
805   if (!options::sample_profile.empty())
806     Conf.SampleProfile = options::sample_profile;
807 
808   return llvm::make_unique<LTO>(std::move(Conf), Backend,
809                                 options::ParallelCodeGenParallelismLevel);
810 }
811 
812 // Write empty files that may be expected by a distributed build
813 // system when invoked with thinlto_index_only. This is invoked when
814 // the linker has decided not to include the given module in the
815 // final link. Frequently the distributed build system will want to
816 // confirm that all expected outputs are created based on all of the
817 // modules provided to the linker.
818 static void writeEmptyDistributedBuildOutputs(std::string &ModulePath,
819                                               std::string &OldPrefix,
820                                               std::string &NewPrefix) {
821   std::string NewModulePath =
822       getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
823   std::error_code EC;
824   {
825     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
826                       sys::fs::OpenFlags::F_None);
827     if (EC)
828       message(LDPL_FATAL, "Failed to write '%s': %s",
829               (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
830   }
831   if (options::thinlto_emit_imports_files) {
832     raw_fd_ostream OS(NewModulePath + ".imports", EC,
833                       sys::fs::OpenFlags::F_None);
834     if (EC)
835       message(LDPL_FATAL, "Failed to write '%s': %s",
836               (NewModulePath + ".imports").c_str(), EC.message().c_str());
837   }
838 }
839 
840 /// gold informs us that all symbols have been read. At this point, we use
841 /// get_symbols to see if any of our definitions have been overridden by a
842 /// native object file. Then, perform optimization and codegen.
843 static ld_plugin_status allSymbolsReadHook() {
844   if (Modules.empty())
845     return LDPS_OK;
846 
847   if (unsigned NumOpts = options::extra.size())
848     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
849 
850   // Map to own RAII objects that manage the file opening and releasing
851   // interfaces with gold. This is needed only for ThinLTO mode, since
852   // unlike regular LTO, where addModule will result in the opened file
853   // being merged into a new combined module, we need to keep these files open
854   // through Lto->run().
855   DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
856 
857   std::unique_ptr<LTO> Lto = createLTO();
858 
859   std::string OldPrefix, NewPrefix;
860   if (options::thinlto_index_only)
861     getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
862 
863   std::string OldSuffix, NewSuffix;
864   getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
865   // Set for owning string objects used as buffer identifiers.
866   StringSet<> ObjectFilenames;
867 
868   for (claimed_file &F : Modules) {
869     if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
870       HandleToInputFile.insert(std::make_pair(
871           F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
872     const void *View = getSymbolsAndView(F);
873     // In case we are thin linking with a minimized bitcode file, ensure
874     // the module paths encoded in the index reflect where the backends
875     // will locate the full bitcode files for compiling/importing.
876     std::string Identifier =
877         getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
878     auto ObjFilename = ObjectFilenames.insert(Identifier);
879     assert(ObjFilename.second);
880     if (!View) {
881       if (options::thinlto_index_only)
882         // Write empty output files that may be expected by the distributed
883         // build system.
884         writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix);
885       continue;
886     }
887     addModule(*Lto, F, View, ObjFilename.first->first());
888   }
889 
890   SmallString<128> Filename;
891   // Note that getOutputFileName will append a unique ID for each task
892   if (!options::obj_path.empty())
893     Filename = options::obj_path;
894   else if (options::TheOutputType == options::OT_SAVE_TEMPS)
895     Filename = output_name + ".o";
896   bool SaveTemps = !Filename.empty();
897 
898   size_t MaxTasks = Lto->getMaxTasks();
899   std::vector<uintptr_t> IsTemporary(MaxTasks);
900   std::vector<SmallString<128>> Filenames(MaxTasks);
901 
902   auto AddStream =
903       [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
904     IsTemporary[Task] = !SaveTemps;
905     int FD = getOutputFileName(Filename, /*TempOutFile=*/!SaveTemps,
906                                Filenames[Task], Task);
907     return llvm::make_unique<lto::NativeObjectStream>(
908         llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
909   };
910 
911   auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB,
912                        StringRef Path) {
913     // Note that this requires that the memory buffers provided to AddBuffer are
914     // backed by a file.
915     Filenames[Task] = Path;
916   };
917 
918   NativeObjectCache Cache;
919   if (!options::cache_dir.empty())
920     Cache = check(localCache(options::cache_dir, AddBuffer));
921 
922   check(Lto->run(AddStream, Cache));
923 
924   if (options::TheOutputType == options::OT_DISABLE ||
925       options::TheOutputType == options::OT_BC_ONLY)
926     return LDPS_OK;
927 
928   if (options::thinlto_index_only) {
929     if (llvm::AreStatisticsEnabled())
930       llvm::PrintStatistics();
931     cleanup_hook();
932     exit(0);
933   }
934 
935   for (unsigned I = 0; I != MaxTasks; ++I)
936     if (!Filenames[I].empty())
937       recordFile(Filenames[I].str(), IsTemporary[I]);
938 
939   if (!options::extra_library_path.empty() &&
940       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
941     message(LDPL_FATAL, "Unable to set the extra library path.");
942 
943   return LDPS_OK;
944 }
945 
946 static ld_plugin_status all_symbols_read_hook(void) {
947   ld_plugin_status Ret = allSymbolsReadHook();
948   llvm_shutdown();
949 
950   if (options::TheOutputType == options::OT_BC_ONLY ||
951       options::TheOutputType == options::OT_DISABLE) {
952     if (options::TheOutputType == options::OT_DISABLE) {
953       // Remove the output file here since ld.bfd creates the output file
954       // early.
955       std::error_code EC = sys::fs::remove(output_name);
956       if (EC)
957         message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
958                 EC.message().c_str());
959     }
960     exit(0);
961   }
962 
963   return Ret;
964 }
965 
966 static ld_plugin_status cleanup_hook(void) {
967   for (std::string &Name : Cleanup) {
968     std::error_code EC = sys::fs::remove(Name);
969     if (EC)
970       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
971               EC.message().c_str());
972   }
973 
974   // Prune cache
975   if (!options::cache_policy.empty()) {
976     CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
977     pruneCache(options::cache_dir, policy);
978   }
979 
980   return LDPS_OK;
981 }
982