blob: 46423bf026ff57c070db803907703ea6e2696e5a [file] [log] [blame]
Rui Ueyama25992482016-03-22 20:52:10 +00001//===- LTO.cpp ------------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "LTO.h"
11#include "Config.h"
Rui Ueyama25992482016-03-22 20:52:10 +000012#include "InputFiles.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000013#include "LinkerScript.h"
Rafael Espindola4b075bb2017-07-26 23:39:10 +000014#include "SymbolTable.h"
Rui Ueyama25992482016-03-22 20:52:10 +000015#include "Symbols.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000016#include "lld/Common/ErrorHandler.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000017#include "lld/Common/TargetOptionsCommandFlags.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000018#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000019#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000020#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000022#include "llvm/BinaryFormat/ELF.h"
Rumeet Dhindsad366e362018-05-02 21:40:07 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
Davide Italiano786d8e32016-09-29 00:40:08 +000025#include "llvm/IR/DiagnosticPrinter.h"
Peter Collingbournee02775f2017-03-01 23:00:10 +000026#include "llvm/LTO/Caching.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000027#include "llvm/LTO/Config.h"
Davide Italiano786d8e32016-09-29 00:40:08 +000028#include "llvm/LTO/LTO.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000029#include "llvm/Object/SymbolicFile.h"
30#include "llvm/Support/CodeGen.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000031#include "llvm/Support/Error.h"
32#include "llvm/Support/FileSystem.h"
33#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000034#include <algorithm>
35#include <cstddef>
36#include <memory>
37#include <string>
38#include <system_error>
39#include <vector>
Rui Ueyama25992482016-03-22 20:52:10 +000040
41using namespace llvm;
42using namespace llvm::object;
43using namespace llvm::ELF;
44
45using namespace lld;
46using namespace lld::elf;
47
48// This is for use when debugging LTO.
Rui Ueyama48da5cf2016-07-15 02:17:13 +000049static void saveBuffer(StringRef Buffer, const Twine &Path) {
Rui Ueyama25992482016-03-22 20:52:10 +000050 std::error_code EC;
Rui Ueyama48da5cf2016-07-15 02:17:13 +000051 raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
Rui Ueyamaf8292e92016-07-15 02:01:03 +000052 if (EC)
Rui Ueyamac8d3a832017-01-12 22:18:04 +000053 error("cannot create " + Path + ": " + EC.message());
Rui Ueyama25992482016-03-22 20:52:10 +000054 OS << Buffer;
55}
56
Davide Italiano786d8e32016-09-29 00:40:08 +000057static void diagnosticHandler(const DiagnosticInfo &DI) {
58 SmallString<128> ErrStorage;
59 raw_svector_ostream OS(ErrStorage);
60 DiagnosticPrinterRawOStream DP(OS);
61 DI.print(DP);
Rui Ueyamad31e13f2016-09-29 21:00:23 +000062 warn(ErrStorage);
Rui Ueyama25992482016-03-22 20:52:10 +000063}
64
Rui Ueyama6c5cbff2016-09-29 21:00:26 +000065static void checkError(Error E) {
Rafael Espindola5329c752017-09-21 22:50:52 +000066 handleAllErrors(std::move(E),
67 [&](ErrorInfoBase &EIB) { error(EIB.message()); });
Rui Ueyama6c5cbff2016-09-29 21:00:26 +000068}
69
Rumeet Dhindsad366e362018-05-02 21:40:07 +000070// With the ThinLTOIndexOnly option, only the thin link is performed, and will
71// generate index files for the ThinLTO backends in a distributed build system.
72// The distributed build system may expect that index files are created for all
73// input bitcode objects provided to the linker for the thin link. However,
74// index files will not normally be created for input bitcode objects that
75// either aren't selected by the linker (i.e. in a static library and not
76// needed), or because they don't have a summary. Therefore we need to create
77// empty dummy index file outputs in those cases.
78// If SkipModule is true then .thinlto.bc should contain just
79// SkipModuleByDistributedBackend flag which requests distributed backend
80// to skip the compilation of the corresponding module and produce an empty
81// object file.
82static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
83 const std::string &OldPrefix,
84 const std::string &NewPrefix,
85 bool SkipModule) {
86 std::string NewModulePath =
87 lto::getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
88 std::error_code EC;
89
90 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
91 sys::fs::OpenFlags::F_None);
92 if (EC)
93 error("failed to write " + NewModulePath + ".thinlto.bc" + ": " +
94 EC.message());
95
96 if (SkipModule) {
97 ModuleSummaryIndex Index(false);
98 Index.setSkipModuleByDistributedBackend();
99 WriteIndexToFile(Index, OS);
100 }
101}
102
Rui Ueyama66a9f252018-05-07 17:46:28 +0000103// Creates an empty file to store a list of object files for final
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000104// linking of distributed ThinLTO.
Rui Ueyama66a9f252018-05-07 17:46:28 +0000105static std::unique_ptr<raw_fd_ostream> openFile(StringRef File) {
106 if (File.empty())
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000107 return nullptr;
Rui Ueyama66a9f252018-05-07 17:46:28 +0000108
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000109 std::error_code EC;
Rui Ueyama66a9f252018-05-07 17:46:28 +0000110 auto Ret =
111 llvm::make_unique<raw_fd_ostream>(File, EC, sys::fs::OpenFlags::F_None);
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000112 if (EC)
Rui Ueyama66a9f252018-05-07 17:46:28 +0000113 error("cannot create " + File + ": " + EC.message());
114 return Ret;
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000115}
116
Rui Ueyama66a9f252018-05-07 17:46:28 +0000117// Initializes IndexFile, Backend and LTOObj members.
118void BitcodeCompiler::init() {
Davide Italiano786d8e32016-09-29 00:40:08 +0000119 lto::Config Conf;
Davide Italianod26c4a12016-05-15 19:29:38 +0000120
Davide Italiano786d8e32016-09-29 00:40:08 +0000121 // LLD supports the new relocations.
122 Conf.Options = InitTargetOptionsFromCodeGenFlags();
123 Conf.Options.RelaxELFRelocations = true;
Davide Italianodf24d5b2016-06-02 22:58:11 +0000124
Davide Italiano957f1202017-07-24 20:15:07 +0000125 // Always emit a section per function/datum with LTO.
Davide Italiano1f4e29c2017-07-24 19:38:13 +0000126 Conf.Options.FunctionSections = true;
Davide Italiano957f1202017-07-24 20:15:07 +0000127 Conf.Options.DataSections = true;
Davide Italiano1f4e29c2017-07-24 19:38:13 +0000128
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +0000129 if (Config->Relocatable)
130 Conf.RelocModel = None;
131 else if (Config->Pic)
132 Conf.RelocModel = Reloc::PIC_;
133 else
134 Conf.RelocModel = Reloc::Static;
Martell Malone6b43b7a2017-02-28 23:43:26 +0000135 Conf.CodeModel = GetCodeModelFromCMModel();
Davide Italiano786d8e32016-09-29 00:40:08 +0000136 Conf.DisableVerify = Config->DisableVerify;
137 Conf.DiagHandler = diagnosticHandler;
Davide Italiano3bfa0812016-11-26 05:37:04 +0000138 Conf.OptLevel = Config->LTOO;
Rafael Espindola3a730d82018-01-30 18:18:59 +0000139 Conf.CPU = GetCPUStr();
Davide Italianodf24d5b2016-06-02 22:58:11 +0000140
Davide Italiano786d8e32016-09-29 00:40:08 +0000141 // Set up a custom pipeline if we've been asked to.
Davide Italiano3bfa0812016-11-26 05:37:04 +0000142 Conf.OptPipeline = Config->LTONewPmPasses;
143 Conf.AAPipeline = Config->LTOAAPipeline;
Rui Ueyama25992482016-03-22 20:52:10 +0000144
Davide Italianodb4b0a72017-02-13 17:49:18 +0000145 // Set up optimization remarks if we've been asked to.
146 Conf.RemarksFilename = Config->OptRemarksFilename;
147 Conf.RemarksWithHotness = Config->OptRemarksWithHotness;
148
Rui Ueyama25992482016-03-22 20:52:10 +0000149 if (Config->SaveTemps)
Rui Ueyama6c5cbff2016-09-29 21:00:26 +0000150 checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".",
George Rimara4c7e742016-10-20 08:36:42 +0000151 /*UseInputModulePath*/ true));
Davide Italiano786d8e32016-09-29 00:40:08 +0000152
Davide Italiano7a7b35a2016-10-10 18:12:53 +0000153 lto::ThinBackend Backend;
Davide Italiano3bfa0812016-11-26 05:37:04 +0000154 if (Config->ThinLTOJobs != -1u)
155 Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
Rumeet Dhindsa682a4172018-04-09 17:56:07 +0000156
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000157 if (Config->ThinLTOIndexOnly) {
Rui Ueyama66a9f252018-05-07 17:46:28 +0000158 std::string OldPrefix;
159 std::string NewPrefix;
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000160 std::tie(OldPrefix, NewPrefix) = Config->ThinLTOPrefixReplace.split(';');
Rui Ueyama66a9f252018-05-07 17:46:28 +0000161
162 IndexFile = openFile(Config->ThinLTOIndexOnlyObjectsFile);
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000163 Backend = lto::createWriteIndexesThinBackend(OldPrefix, NewPrefix, true,
Rui Ueyama66a9f252018-05-07 17:46:28 +0000164 IndexFile.get(), nullptr);
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000165 }
166
Rumeet Dhindsa682a4172018-04-09 17:56:07 +0000167 Conf.SampleProfile = Config->LTOSampleProfile;
168 Conf.UseNewPM = Config->LTONewPassManager;
169 Conf.DebugPassManager = Config->LTODebugPassManager;
170
Rui Ueyama66a9f252018-05-07 17:46:28 +0000171 LTOObj = llvm::make_unique<lto::LTO>(std::move(Conf), Backend,
172 Config->LTOPartitions);
Rui Ueyama25992482016-03-22 20:52:10 +0000173}
174
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000175BitcodeCompiler::BitcodeCompiler() {
Rui Ueyama66a9f252018-05-07 17:46:28 +0000176 init();
177
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000178 for (Symbol *Sym : Symtab->getSymbols()) {
Rui Ueyamaf1f00842017-10-31 16:07:41 +0000179 StringRef Name = Sym->getName();
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000180 for (StringRef Prefix : {"__start_", "__stop_"})
181 if (Name.startswith(Prefix))
182 UsedStartStop.insert(Name.substr(Prefix.size()));
183 }
184}
Rafael Espindolaae605c12016-04-21 20:35:25 +0000185
Eugene Zelenko22886a22016-11-05 01:00:56 +0000186BitcodeCompiler::~BitcodeCompiler() = default;
Rui Ueyama412c8022016-04-22 21:16:18 +0000187
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000188static void undefine(Symbol *S) {
Rafael Espindolabec37652017-11-17 01:37:50 +0000189 replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_GLOBAL, STV_DEFAULT,
190 S->Type);
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000191}
192
Peter Smith3a52eb02017-02-01 10:26:03 +0000193void BitcodeCompiler::add(BitcodeFile &F) {
Davide Italiano786d8e32016-09-29 00:40:08 +0000194 lto::InputFile &Obj = *F.Obj;
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000195
196 std::string OldPrefix, NewPrefix;
197 std::tie(OldPrefix, NewPrefix) = Config->ThinLTOPrefixReplace.split(';');
198
199 // Create the empty files which, if indexed, will be overwritten later.
Rumeet Dhindsab082a872018-05-03 00:28:51 +0000200 if (Config->ThinLTOIndexOnly)
201 writeEmptyDistributedBuildOutputs(Obj.getName(), OldPrefix, NewPrefix,
202 false);
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000203
Davide Italiano786d8e32016-09-29 00:40:08 +0000204 unsigned SymNum = 0;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000205 std::vector<Symbol *> Syms = F.getSymbols();
Davide Italiano786d8e32016-09-29 00:40:08 +0000206 std::vector<lto::SymbolResolution> Resols(Syms.size());
Davide Italiano334fce92016-05-11 01:07:22 +0000207
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000208 bool IsExecutable = !Config->Shared && !Config->Relocatable;
209
Davide Italiano786d8e32016-09-29 00:40:08 +0000210 // Provide a resolution to the LTO API for each symbol.
211 for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000212 Symbol *Sym = Syms[SymNum];
Davide Italiano786d8e32016-09-29 00:40:08 +0000213 lto::SymbolResolution &R = Resols[SymNum];
214 ++SymNum;
Davide Italiano86f2bd52016-03-29 21:46:35 +0000215
Davide Italiano786d8e32016-09-29 00:40:08 +0000216 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
217 // reports two symbols for module ASM defined. Without this check, lld
218 // flags an undefined in IR with a definition in ASM as prevailing.
219 // Once IRObjectFile is fixed to report only one symbol this hack can
220 // be removed.
Rafael Espindoladfebd362017-11-29 22:47:35 +0000221 R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000222
George Rimar3a1af222017-08-22 08:36:54 +0000223 // We ask LTO to preserve following global symbols:
224 // 1) All symbols when doing relocatable link, so that them can be used
225 // for doing final link.
226 // 2) Symbols that are used in regular objects.
227 // 3) C named sections if we have corresponding __start_/__stop_ symbol.
228 // 4) Symbols that are defined in bitcode files and used for dynamic linking.
229 R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
Rafael Espindolaaffe7202017-07-25 22:51:05 +0000230 (R.Prevailing && Sym->includeInDynsym()) ||
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000231 UsedStartStop.count(ObjSym.getSectionName());
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000232 const auto *DR = dyn_cast<Defined>(Sym);
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000233 R.FinalDefinitionInLinkageUnit =
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000234 (IsExecutable || Sym->Visibility != STV_DEFAULT) && DR &&
235 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
236 // will be generated by for them, triggering linker errors.
237 // Symbol section is always null for bitcode symbols, hence the check
Dmitry Mikulin8ddd9222018-02-08 04:25:52 +0000238 // for isElf(). Skip linker script defined symbols as well: they have
239 // no File defined.
240 !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf()));
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000241
Davide Italiano786d8e32016-09-29 00:40:08 +0000242 if (R.Prevailing)
Peter Smith3a52eb02017-02-01 10:26:03 +0000243 undefine(Sym);
George Rimard28c26b2017-09-25 09:31:43 +0000244
George Rimarc4ccfb52018-01-30 09:04:27 +0000245 // We tell LTO to not apply interprocedural optimization for wrapped
246 // (with --wrap) symbols because otherwise LTO would inline them while
247 // their values are still not final.
248 R.LinkerRedefined = !Sym->CanInline;
Rui Ueyama25992482016-03-22 20:52:10 +0000249 }
Davide Italiano3bfa0812016-11-26 05:37:04 +0000250 checkError(LTOObj->add(std::move(F.Obj), Resols));
Davide Italianobc176632016-04-15 22:38:10 +0000251}
252
Rui Ueyama25992482016-03-22 20:52:10 +0000253// Merge all the bitcode files we have seen, codegen the result
Davide Italiano786d8e32016-09-29 00:40:08 +0000254// and return the resulting ObjectFile(s).
Rui Ueyama38dbd3e2016-09-14 00:05:51 +0000255std::vector<InputFile *> BitcodeCompiler::compile() {
Davide Italiano786d8e32016-09-29 00:40:08 +0000256 std::vector<InputFile *> Ret;
Davide Italiano3bfa0812016-11-26 05:37:04 +0000257 unsigned MaxTasks = LTOObj->getMaxTasks();
Davide Italiano786d8e32016-09-29 00:40:08 +0000258 Buff.resize(MaxTasks);
Peter Collingbournee02775f2017-03-01 23:00:10 +0000259 Files.resize(MaxTasks);
Davide Italiano828ac5412016-03-28 15:44:21 +0000260
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000261 // If LazyObjFile has not been added to link, emit empty index files
262 if (Config->ThinLTOIndexOnly)
263 for (LazyObjFile *F : LazyObjFiles)
264 if (!F->AddedToLink && isBitcode(F->MB))
265 addLazyObjFile(F);
266
Peter Collingbournee02775f2017-03-01 23:00:10 +0000267 // The --thinlto-cache-dir option specifies the path to a directory in which
268 // to cache native object files for ThinLTO incremental builds. If a path was
269 // specified, configure LTO to use it as the cache directory.
270 lto::NativeObjectCache Cache;
271 if (!Config->ThinLTOCacheDir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +0000272 Cache = check(
273 lto::localCache(Config->ThinLTOCacheDir,
Teresa Johnson2c2ed3c2018-02-20 20:21:59 +0000274 [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
275 Files[Task] = std::move(MB);
276 }));
Peter Collingbournee02775f2017-03-01 23:00:10 +0000277
278 checkError(LTOObj->run(
279 [&](size_t Task) {
280 return llvm::make_unique<lto::NativeObjectStream>(
281 llvm::make_unique<raw_svector_ostream>(Buff[Task]));
282 },
283 Cache));
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000284
Peter Collingbourneee59e432017-03-17 02:24:16 +0000285 if (!Config->ThinLTOCacheDir.empty())
286 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
287
Davide Italiano786d8e32016-09-29 00:40:08 +0000288 for (unsigned I = 0; I != MaxTasks; ++I) {
289 if (Buff[I].empty())
290 continue;
291 if (Config->SaveTemps) {
Peter Collingbourned22ec642017-01-26 02:18:28 +0000292 if (I == 0)
Davide Italiano786d8e32016-09-29 00:40:08 +0000293 saveBuffer(Buff[I], Config->OutputFile + ".lto.o");
294 else
295 saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o");
296 }
Rui Ueyama55518e72016-10-28 20:57:25 +0000297 InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp"));
Davide Italiano786d8e32016-09-29 00:40:08 +0000298 Ret.push_back(Obj);
299 }
Peter Collingbournee02775f2017-03-01 23:00:10 +0000300
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000301 // ThinLTO with index only option is required to generate only the index
302 // files. After that, we exit from linker and ThinLTO backend runs in a
303 // distributed environment.
304 if (Config->ThinLTOIndexOnly)
305 exit(0);
306
Peter Collingbournee02775f2017-03-01 23:00:10 +0000307 for (std::unique_ptr<MemoryBuffer> &File : Files)
308 if (File)
309 Ret.push_back(createObjectFile(*File));
310
Davide Italiano786d8e32016-09-29 00:40:08 +0000311 return Ret;
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000312}
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000313
314// For lazy object files not added to link, adds empty index files
315void BitcodeCompiler::addLazyObjFile(LazyObjFile *File) {
316 StringRef Identifier = File->getBuffer().getBufferIdentifier();
317 std::string OldPrefix, NewPrefix;
318 std::tie(OldPrefix, NewPrefix) = Config->ThinLTOPrefixReplace.split(';');
319 writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
320 /* SkipModule */ true);
321}