blob: 861f73c4329fdbeec5069243915fe1c3eb93b5c5 [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"
Davide Italiano786d8e32016-09-29 00:40:08 +000023#include "llvm/IR/DiagnosticPrinter.h"
Peter Collingbournee02775f2017-03-01 23:00:10 +000024#include "llvm/LTO/Caching.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000025#include "llvm/LTO/Config.h"
Davide Italiano786d8e32016-09-29 00:40:08 +000026#include "llvm/LTO/LTO.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000027#include "llvm/Object/SymbolicFile.h"
28#include "llvm/Support/CodeGen.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000029#include "llvm/Support/Error.h"
30#include "llvm/Support/FileSystem.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include "llvm/Support/raw_ostream.h"
33#include <algorithm>
34#include <cstddef>
35#include <memory>
36#include <string>
37#include <system_error>
38#include <vector>
Rui Ueyama25992482016-03-22 20:52:10 +000039
40using namespace llvm;
41using namespace llvm::object;
42using namespace llvm::ELF;
43
44using namespace lld;
45using namespace lld::elf;
46
47// This is for use when debugging LTO.
Rui Ueyama48da5cf2016-07-15 02:17:13 +000048static void saveBuffer(StringRef Buffer, const Twine &Path) {
Rui Ueyama25992482016-03-22 20:52:10 +000049 std::error_code EC;
Rui Ueyama48da5cf2016-07-15 02:17:13 +000050 raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
Rui Ueyamaf8292e92016-07-15 02:01:03 +000051 if (EC)
Rui Ueyamac8d3a832017-01-12 22:18:04 +000052 error("cannot create " + Path + ": " + EC.message());
Rui Ueyama25992482016-03-22 20:52:10 +000053 OS << Buffer;
54}
55
Davide Italiano786d8e32016-09-29 00:40:08 +000056static void diagnosticHandler(const DiagnosticInfo &DI) {
57 SmallString<128> ErrStorage;
58 raw_svector_ostream OS(ErrStorage);
59 DiagnosticPrinterRawOStream DP(OS);
60 DI.print(DP);
Rui Ueyamad31e13f2016-09-29 21:00:23 +000061 warn(ErrStorage);
Rui Ueyama25992482016-03-22 20:52:10 +000062}
63
Rui Ueyama6c5cbff2016-09-29 21:00:26 +000064static void checkError(Error E) {
Rafael Espindola5329c752017-09-21 22:50:52 +000065 handleAllErrors(std::move(E),
66 [&](ErrorInfoBase &EIB) { error(EIB.message()); });
Rui Ueyama6c5cbff2016-09-29 21:00:26 +000067}
68
Davide Italiano786d8e32016-09-29 00:40:08 +000069static std::unique_ptr<lto::LTO> createLTO() {
70 lto::Config Conf;
Davide Italianod26c4a12016-05-15 19:29:38 +000071
Davide Italiano786d8e32016-09-29 00:40:08 +000072 // LLD supports the new relocations.
73 Conf.Options = InitTargetOptionsFromCodeGenFlags();
74 Conf.Options.RelaxELFRelocations = true;
Davide Italianodf24d5b2016-06-02 22:58:11 +000075
Davide Italiano957f1202017-07-24 20:15:07 +000076 // Always emit a section per function/datum with LTO.
Davide Italiano1f4e29c2017-07-24 19:38:13 +000077 Conf.Options.FunctionSections = true;
Davide Italiano957f1202017-07-24 20:15:07 +000078 Conf.Options.DataSections = true;
Davide Italiano1f4e29c2017-07-24 19:38:13 +000079
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +000080 if (Config->Relocatable)
81 Conf.RelocModel = None;
82 else if (Config->Pic)
83 Conf.RelocModel = Reloc::PIC_;
84 else
85 Conf.RelocModel = Reloc::Static;
Martell Malone6b43b7a2017-02-28 23:43:26 +000086 Conf.CodeModel = GetCodeModelFromCMModel();
Davide Italiano786d8e32016-09-29 00:40:08 +000087 Conf.DisableVerify = Config->DisableVerify;
88 Conf.DiagHandler = diagnosticHandler;
Davide Italiano3bfa0812016-11-26 05:37:04 +000089 Conf.OptLevel = Config->LTOO;
Rafael Espindola3a730d82018-01-30 18:18:59 +000090 Conf.CPU = GetCPUStr();
Davide Italianodf24d5b2016-06-02 22:58:11 +000091
Davide Italiano786d8e32016-09-29 00:40:08 +000092 // Set up a custom pipeline if we've been asked to.
Davide Italiano3bfa0812016-11-26 05:37:04 +000093 Conf.OptPipeline = Config->LTONewPmPasses;
94 Conf.AAPipeline = Config->LTOAAPipeline;
Rui Ueyama25992482016-03-22 20:52:10 +000095
Davide Italianodb4b0a72017-02-13 17:49:18 +000096 // Set up optimization remarks if we've been asked to.
97 Conf.RemarksFilename = Config->OptRemarksFilename;
98 Conf.RemarksWithHotness = Config->OptRemarksWithHotness;
99
Rui Ueyama25992482016-03-22 20:52:10 +0000100 if (Config->SaveTemps)
Rui Ueyama6c5cbff2016-09-29 21:00:26 +0000101 checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".",
George Rimara4c7e742016-10-20 08:36:42 +0000102 /*UseInputModulePath*/ true));
Davide Italiano786d8e32016-09-29 00:40:08 +0000103
Davide Italiano7a7b35a2016-10-10 18:12:53 +0000104 lto::ThinBackend Backend;
Davide Italiano3bfa0812016-11-26 05:37:04 +0000105 if (Config->ThinLTOJobs != -1u)
106 Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
Rumeet Dhindsa682a4172018-04-09 17:56:07 +0000107
108 Conf.SampleProfile = Config->LTOSampleProfile;
109 Conf.UseNewPM = Config->LTONewPassManager;
110 Conf.DebugPassManager = Config->LTODebugPassManager;
111
Davide Italianob6e6e4a2016-10-10 23:12:14 +0000112 return llvm::make_unique<lto::LTO>(std::move(Conf), Backend,
Davide Italiano3bfa0812016-11-26 05:37:04 +0000113 Config->LTOPartitions);
Rui Ueyama25992482016-03-22 20:52:10 +0000114}
115
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000116BitcodeCompiler::BitcodeCompiler() : LTOObj(createLTO()) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000117 for (Symbol *Sym : Symtab->getSymbols()) {
Rui Ueyamaf1f00842017-10-31 16:07:41 +0000118 StringRef Name = Sym->getName();
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000119 for (StringRef Prefix : {"__start_", "__stop_"})
120 if (Name.startswith(Prefix))
121 UsedStartStop.insert(Name.substr(Prefix.size()));
122 }
123}
Rafael Espindolaae605c12016-04-21 20:35:25 +0000124
Eugene Zelenko22886a22016-11-05 01:00:56 +0000125BitcodeCompiler::~BitcodeCompiler() = default;
Rui Ueyama412c8022016-04-22 21:16:18 +0000126
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000127static void undefine(Symbol *S) {
Rafael Espindolabec37652017-11-17 01:37:50 +0000128 replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_GLOBAL, STV_DEFAULT,
129 S->Type);
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000130}
131
Peter Smith3a52eb02017-02-01 10:26:03 +0000132void BitcodeCompiler::add(BitcodeFile &F) {
Davide Italiano786d8e32016-09-29 00:40:08 +0000133 lto::InputFile &Obj = *F.Obj;
Davide Italiano786d8e32016-09-29 00:40:08 +0000134 unsigned SymNum = 0;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000135 std::vector<Symbol *> Syms = F.getSymbols();
Davide Italiano786d8e32016-09-29 00:40:08 +0000136 std::vector<lto::SymbolResolution> Resols(Syms.size());
Davide Italiano334fce92016-05-11 01:07:22 +0000137
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000138 bool IsExecutable = !Config->Shared && !Config->Relocatable;
139
Davide Italiano786d8e32016-09-29 00:40:08 +0000140 // Provide a resolution to the LTO API for each symbol.
141 for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000142 Symbol *Sym = Syms[SymNum];
Davide Italiano786d8e32016-09-29 00:40:08 +0000143 lto::SymbolResolution &R = Resols[SymNum];
144 ++SymNum;
Davide Italiano86f2bd52016-03-29 21:46:35 +0000145
Davide Italiano786d8e32016-09-29 00:40:08 +0000146 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
147 // reports two symbols for module ASM defined. Without this check, lld
148 // flags an undefined in IR with a definition in ASM as prevailing.
149 // Once IRObjectFile is fixed to report only one symbol this hack can
150 // be removed.
Rafael Espindoladfebd362017-11-29 22:47:35 +0000151 R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000152
George Rimar3a1af222017-08-22 08:36:54 +0000153 // We ask LTO to preserve following global symbols:
154 // 1) All symbols when doing relocatable link, so that them can be used
155 // for doing final link.
156 // 2) Symbols that are used in regular objects.
157 // 3) C named sections if we have corresponding __start_/__stop_ symbol.
158 // 4) Symbols that are defined in bitcode files and used for dynamic linking.
159 R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
Rafael Espindolaaffe7202017-07-25 22:51:05 +0000160 (R.Prevailing && Sym->includeInDynsym()) ||
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000161 UsedStartStop.count(ObjSym.getSectionName());
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000162 const auto *DR = dyn_cast<Defined>(Sym);
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000163 R.FinalDefinitionInLinkageUnit =
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000164 (IsExecutable || Sym->Visibility != STV_DEFAULT) && DR &&
165 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
166 // will be generated by for them, triggering linker errors.
167 // Symbol section is always null for bitcode symbols, hence the check
Dmitry Mikulin8ddd9222018-02-08 04:25:52 +0000168 // for isElf(). Skip linker script defined symbols as well: they have
169 // no File defined.
170 !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf()));
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000171
Davide Italiano786d8e32016-09-29 00:40:08 +0000172 if (R.Prevailing)
Peter Smith3a52eb02017-02-01 10:26:03 +0000173 undefine(Sym);
George Rimard28c26b2017-09-25 09:31:43 +0000174
George Rimarc4ccfb52018-01-30 09:04:27 +0000175 // We tell LTO to not apply interprocedural optimization for wrapped
176 // (with --wrap) symbols because otherwise LTO would inline them while
177 // their values are still not final.
178 R.LinkerRedefined = !Sym->CanInline;
Rui Ueyama25992482016-03-22 20:52:10 +0000179 }
Davide Italiano3bfa0812016-11-26 05:37:04 +0000180 checkError(LTOObj->add(std::move(F.Obj), Resols));
Davide Italianobc176632016-04-15 22:38:10 +0000181}
182
Rui Ueyama25992482016-03-22 20:52:10 +0000183// Merge all the bitcode files we have seen, codegen the result
Davide Italiano786d8e32016-09-29 00:40:08 +0000184// and return the resulting ObjectFile(s).
Rui Ueyama38dbd3e2016-09-14 00:05:51 +0000185std::vector<InputFile *> BitcodeCompiler::compile() {
Davide Italiano786d8e32016-09-29 00:40:08 +0000186 std::vector<InputFile *> Ret;
Davide Italiano3bfa0812016-11-26 05:37:04 +0000187 unsigned MaxTasks = LTOObj->getMaxTasks();
Davide Italiano786d8e32016-09-29 00:40:08 +0000188 Buff.resize(MaxTasks);
Peter Collingbournee02775f2017-03-01 23:00:10 +0000189 Files.resize(MaxTasks);
Davide Italiano828ac5412016-03-28 15:44:21 +0000190
Peter Collingbournee02775f2017-03-01 23:00:10 +0000191 // The --thinlto-cache-dir option specifies the path to a directory in which
192 // to cache native object files for ThinLTO incremental builds. If a path was
193 // specified, configure LTO to use it as the cache directory.
194 lto::NativeObjectCache Cache;
195 if (!Config->ThinLTOCacheDir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +0000196 Cache = check(
197 lto::localCache(Config->ThinLTOCacheDir,
Teresa Johnson2c2ed3c2018-02-20 20:21:59 +0000198 [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
199 Files[Task] = std::move(MB);
200 }));
Peter Collingbournee02775f2017-03-01 23:00:10 +0000201
202 checkError(LTOObj->run(
203 [&](size_t Task) {
204 return llvm::make_unique<lto::NativeObjectStream>(
205 llvm::make_unique<raw_svector_ostream>(Buff[Task]));
206 },
207 Cache));
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000208
Peter Collingbourneee59e432017-03-17 02:24:16 +0000209 if (!Config->ThinLTOCacheDir.empty())
210 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
211
Davide Italiano786d8e32016-09-29 00:40:08 +0000212 for (unsigned I = 0; I != MaxTasks; ++I) {
213 if (Buff[I].empty())
214 continue;
215 if (Config->SaveTemps) {
Peter Collingbourned22ec642017-01-26 02:18:28 +0000216 if (I == 0)
Davide Italiano786d8e32016-09-29 00:40:08 +0000217 saveBuffer(Buff[I], Config->OutputFile + ".lto.o");
218 else
219 saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o");
220 }
Rui Ueyama55518e72016-10-28 20:57:25 +0000221 InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp"));
Davide Italiano786d8e32016-09-29 00:40:08 +0000222 Ret.push_back(Obj);
223 }
Peter Collingbournee02775f2017-03-01 23:00:10 +0000224
225 for (std::unique_ptr<MemoryBuffer> &File : Files)
226 if (File)
227 Ret.push_back(createObjectFile(*File));
228
Davide Italiano786d8e32016-09-29 00:40:08 +0000229 return Ret;
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000230}