blob: ca44581780e47ae50259ffd97a4217b38f012910 [file] [log] [blame]
Rui Ueyama25992482016-03-22 20:52:101//===- 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:1012#include "InputFiles.h"
Rui Ueyama3f851702017-10-02 21:00:4113#include "LinkerScript.h"
Rafael Espindola4b075bb2017-07-26 23:39:1014#include "SymbolTable.h"
Rui Ueyama25992482016-03-22 20:52:1015#include "Symbols.h"
Bob Haarmanb8a59c82017-10-25 22:28:3816#include "lld/Common/ErrorHandler.h"
Rui Ueyama3f851702017-10-02 21:00:4117#include "lld/Common/TargetOptionsCommandFlags.h"
Eugene Zelenko22886a22016-11-05 01:00:5618#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:5919#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:5620#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:5622#include "llvm/BinaryFormat/ELF.h"
Rumeet Dhindsad366e362018-05-02 21:40:0723#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
Davide Italiano786d8e32016-09-29 00:40:0825#include "llvm/IR/DiagnosticPrinter.h"
Peter Collingbournee02775f2017-03-01 23:00:1026#include "llvm/LTO/Caching.h"
Eugene Zelenko22886a22016-11-05 01:00:5627#include "llvm/LTO/Config.h"
Davide Italiano786d8e32016-09-29 00:40:0828#include "llvm/LTO/LTO.h"
Eugene Zelenko22886a22016-11-05 01:00:5629#include "llvm/Object/SymbolicFile.h"
30#include "llvm/Support/CodeGen.h"
Eugene Zelenko22886a22016-11-05 01:00:5631#include "llvm/Support/Error.h"
32#include "llvm/Support/FileSystem.h"
33#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko22886a22016-11-05 01:00:5634#include <algorithm>
35#include <cstddef>
36#include <memory>
37#include <string>
38#include <system_error>
39#include <vector>
Rui Ueyama25992482016-03-22 20:52:1040
41using namespace llvm;
42using namespace llvm::object;
43using namespace llvm::ELF;
44
45using namespace lld;
46using namespace lld::elf;
47
Rui Ueyama66a9f252018-05-07 17:46:2848// Creates an empty file to store a list of object files for final
Rumeet Dhindsad366e362018-05-02 21:40:0749// linking of distributed ThinLTO.
Rui Ueyama66a9f252018-05-07 17:46:2850static std::unique_ptr<raw_fd_ostream> openFile(StringRef File) {
Rumeet Dhindsad366e362018-05-02 21:40:0751 std::error_code EC;
Rui Ueyama66a9f252018-05-07 17:46:2852 auto Ret =
53 llvm::make_unique<raw_fd_ostream>(File, EC, sys::fs::OpenFlags::F_None);
Rui Ueyamad54f1c22018-05-07 22:11:2454 if (EC) {
55 error("cannot open " + File + ": " + EC.message());
56 return nullptr;
57 }
Rui Ueyama66a9f252018-05-07 17:46:2858 return Ret;
Rumeet Dhindsad366e362018-05-02 21:40:0759}
60
Rui Ueyamad54f1c22018-05-07 22:11:2461static std::string getThinLTOOutputFile(StringRef ModulePath) {
62 return lto::getThinLTOOutputFile(ModulePath,
63 Config->ThinLTOPrefixReplace.first,
Rumeet Dhindsa4fb51192018-05-07 23:14:1264 Config->ThinLTOPrefixReplace.second);
Rui Ueyamad54f1c22018-05-07 22:11:2465}
66
Rui Ueyama397dffd2018-05-07 23:24:0767static lto::Config createConfig() {
68 lto::Config C;
Davide Italianod26c4a12016-05-15 19:29:3869
Peter Collingbourne82a7f142018-08-06 20:12:1270 // LLD supports the new relocations and address-significance tables.
Rui Ueyama397dffd2018-05-07 23:24:0771 C.Options = InitTargetOptionsFromCodeGenFlags();
72 C.Options.RelaxELFRelocations = true;
Peter Collingbourne82a7f142018-08-06 20:12:1273 C.Options.EmitAddrsig = true;
Davide Italianodf24d5b2016-06-02 22:58:1174
Davide Italiano957f1202017-07-24 20:15:0775 // Always emit a section per function/datum with LTO.
Rui Ueyama397dffd2018-05-07 23:24:0776 C.Options.FunctionSections = true;
77 C.Options.DataSections = true;
Davide Italiano1f4e29c2017-07-24 19:38:1378
Evgeniy Stepanovf12ac5b2017-05-22 21:11:4479 if (Config->Relocatable)
Rui Ueyama397dffd2018-05-07 23:24:0780 C.RelocModel = None;
Evgeniy Stepanovf12ac5b2017-05-22 21:11:4481 else if (Config->Pic)
Rui Ueyama397dffd2018-05-07 23:24:0782 C.RelocModel = Reloc::PIC_;
Evgeniy Stepanovf12ac5b2017-05-22 21:11:4483 else
Rui Ueyama397dffd2018-05-07 23:24:0784 C.RelocModel = Reloc::Static;
85
86 C.CodeModel = GetCodeModelFromCMModel();
87 C.DisableVerify = Config->DisableVerify;
88 C.DiagHandler = diagnosticHandler;
89 C.OptLevel = Config->LTOO;
90 C.CPU = GetCPUStr();
Fangrui Songccfc8412018-11-01 20:02:4991 C.MAttrs = GetMAttrs();
Davide Italianodf24d5b2016-06-02 22:58:1192
Davide Italiano786d8e32016-09-29 00:40:0893 // Set up a custom pipeline if we've been asked to.
Rui Ueyama397dffd2018-05-07 23:24:0794 C.OptPipeline = Config->LTONewPmPasses;
95 C.AAPipeline = Config->LTOAAPipeline;
Rui Ueyama25992482016-03-22 20:52:1096
Davide Italianodb4b0a72017-02-13 17:49:1897 // Set up optimization remarks if we've been asked to.
Rui Ueyama397dffd2018-05-07 23:24:0798 C.RemarksFilename = Config->OptRemarksFilename;
99 C.RemarksWithHotness = Config->OptRemarksWithHotness;
100
101 C.SampleProfile = Config->LTOSampleProfile;
102 C.UseNewPM = Config->LTONewPassManager;
103 C.DebugPassManager = Config->LTODebugPassManager;
Yunlian Jiang496fb3e2018-07-16 17:55:48104 C.DwoDir = Config->DwoDir;
Davide Italianodb4b0a72017-02-13 17:49:18105
Rui Ueyama9f499902018-12-14 21:58:49106 if (Config->EmitLLVM) {
107 C.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
108 if (std::unique_ptr<raw_fd_ostream> OS = openFile(Config->OutputFile))
109 WriteBitcodeToFile(M, *OS, false);
110 return false;
111 };
112 }
113
Rui Ueyama25992482016-03-22 20:52:10114 if (Config->SaveTemps)
Rui Ueyama397dffd2018-05-07 23:24:07115 checkError(C.addSaveTemps(Config->OutputFile.str() + ".",
116 /*UseInputModulePath*/ true));
117 return C;
118}
Davide Italiano786d8e32016-09-29 00:40:08119
Rui Ueyama397dffd2018-05-07 23:24:07120BitcodeCompiler::BitcodeCompiler() {
Rui Ueyama98e4a5c2018-09-11 14:37:27121 // Initialize IndexFile.
122 if (!Config->ThinLTOIndexOnlyArg.empty())
123 IndexFile = openFile(Config->ThinLTOIndexOnlyArg);
124
Rui Ueyama397dffd2018-05-07 23:24:07125 // Initialize LTOObj.
Davide Italiano7a7b35a2016-10-10 18:12:53126 lto::ThinBackend Backend;
Rumeet Dhindsad366e362018-05-02 21:40:07127 if (Config->ThinLTOIndexOnly) {
Rui Ueyama98e4a5c2018-09-11 14:37:27128 auto OnIndexWrite = [&](StringRef S) { ThinIndices.erase(S); };
Rui Ueyama4454b3d2018-05-07 17:59:43129 Backend = lto::createWriteIndexesThinBackend(
130 Config->ThinLTOPrefixReplace.first, Config->ThinLTOPrefixReplace.second,
Rumeet Dhindsa18883262018-05-08 20:12:07131 Config->ThinLTOEmitImportsFiles, IndexFile.get(), OnIndexWrite);
Rui Ueyama397dffd2018-05-07 23:24:07132 } else if (Config->ThinLTOJobs != -1U) {
133 Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
Rumeet Dhindsad366e362018-05-02 21:40:07134 }
135
Rui Ueyama397dffd2018-05-07 23:24:07136 LTOObj = llvm::make_unique<lto::LTO>(createConfig(), Backend,
Rui Ueyama66a9f252018-05-07 17:46:28137 Config->LTOPartitions);
Rui Ueyama25992482016-03-22 20:52:10138
Rui Ueyama397dffd2018-05-07 23:24:07139 // Initialize UsedStartStop.
Rui Ueyamaf52496e2017-11-03 21:21:47140 for (Symbol *Sym : Symtab->getSymbols()) {
Rui Ueyama98e4a5c2018-09-11 14:37:27141 StringRef S = Sym->getName();
Rafael Espindola4b075bb2017-07-26 23:39:10142 for (StringRef Prefix : {"__start_", "__stop_"})
Rui Ueyama98e4a5c2018-09-11 14:37:27143 if (S.startswith(Prefix))
144 UsedStartStop.insert(S.substr(Prefix.size()));
Rafael Espindola4b075bb2017-07-26 23:39:10145 }
146}
Rafael Espindolaae605c12016-04-21 20:35:25147
Eugene Zelenko22886a22016-11-05 01:00:56148BitcodeCompiler::~BitcodeCompiler() = default;
Rui Ueyama412c802b2016-04-22 21:16:18149
Rui Ueyamaf52496e2017-11-03 21:21:47150static void undefine(Symbol *S) {
Rafael Espindolabec37652017-11-17 01:37:50151 replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_GLOBAL, STV_DEFAULT,
152 S->Type);
Peter Collingbourne0ef38742016-05-12 19:46:14153}
154
Peter Smith3a52eb02017-02-01 10:26:03155void BitcodeCompiler::add(BitcodeFile &F) {
Davide Italiano786d8e32016-09-29 00:40:08156 lto::InputFile &Obj = *F.Obj;
Rui Ueyamad31b54b2018-05-08 17:50:54157 bool IsExec = !Config->Shared && !Config->Relocatable;
Rumeet Dhindsad366e362018-05-02 21:40:07158
Rumeet Dhindsa18883262018-05-08 20:12:07159 if (Config->ThinLTOIndexOnly)
Rui Ueyama98e4a5c2018-09-11 14:37:27160 ThinIndices.insert(Obj.getName());
Rumeet Dhindsad366e362018-05-02 21:40:07161
Rui Ueyama2f9fa422018-05-08 17:50:43162 ArrayRef<Symbol *> Syms = F.getSymbols();
Rui Ueyamad31b54b2018-05-08 17:50:54163 ArrayRef<lto::InputFile::Symbol> ObjSyms = Obj.symbols();
Davide Italiano786d8e32016-09-29 00:40:08164 std::vector<lto::SymbolResolution> Resols(Syms.size());
Davide Italiano334fce92016-05-11 01:07:22165
Davide Italiano786d8e32016-09-29 00:40:08166 // Provide a resolution to the LTO API for each symbol.
Rui Ueyamad31b54b2018-05-08 17:50:54167 for (size_t I = 0, E = Syms.size(); I != E; ++I) {
168 Symbol *Sym = Syms[I];
169 const lto::InputFile::Symbol &ObjSym = ObjSyms[I];
170 lto::SymbolResolution &R = Resols[I];
Davide Italiano86f2bd52016-03-29 21:46:35171
Davide Italiano786d8e32016-09-29 00:40:08172 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
173 // reports two symbols for module ASM defined. Without this check, lld
174 // flags an undefined in IR with a definition in ASM as prevailing.
175 // Once IRObjectFile is fixed to report only one symbol this hack can
176 // be removed.
Rafael Espindoladfebd362017-11-29 22:47:35177 R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49178
George Rimar3a1af222017-08-22 08:36:54179 // We ask LTO to preserve following global symbols:
180 // 1) All symbols when doing relocatable link, so that them can be used
181 // for doing final link.
182 // 2) Symbols that are used in regular objects.
183 // 3) C named sections if we have corresponding __start_/__stop_ symbol.
184 // 4) Symbols that are defined in bitcode files and used for dynamic linking.
185 R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
Rafael Espindolaaffe7202017-07-25 22:51:05186 (R.Prevailing && Sym->includeInDynsym()) ||
Rafael Espindola4b075bb2017-07-26 23:39:10187 UsedStartStop.count(ObjSym.getSectionName());
Dmitry Mikulinc84e0ee2018-02-07 00:49:51188 const auto *DR = dyn_cast<Defined>(Sym);
Rafael Espindolac6df38c2018-01-16 16:49:05189 R.FinalDefinitionInLinkageUnit =
Rui Ueyamad31b54b2018-05-08 17:50:54190 (IsExec || Sym->Visibility != STV_DEFAULT) && DR &&
Dmitry Mikulinc84e0ee2018-02-07 00:49:51191 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
192 // will be generated by for them, triggering linker errors.
193 // Symbol section is always null for bitcode symbols, hence the check
Dmitry Mikulin8ddd9222018-02-08 04:25:52194 // for isElf(). Skip linker script defined symbols as well: they have
195 // no File defined.
196 !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf()));
Rafael Espindolac6df38c2018-01-16 16:49:05197
Davide Italiano786d8e32016-09-29 00:40:08198 if (R.Prevailing)
Peter Smith3a52eb02017-02-01 10:26:03199 undefine(Sym);
George Rimard28c26b2017-09-25 09:31:43200
George Rimarc4ccfb52018-01-30 09:04:27201 // We tell LTO to not apply interprocedural optimization for wrapped
202 // (with --wrap) symbols because otherwise LTO would inline them while
203 // their values are still not final.
204 R.LinkerRedefined = !Sym->CanInline;
Rui Ueyama25992482016-03-22 20:52:10205 }
Davide Italiano3bfa0812016-11-26 05:37:04206 checkError(LTOObj->add(std::move(F.Obj), Resols));
Davide Italianobc176632016-04-15 22:38:10207}
208
Rui Ueyamaf06d4942018-05-17 18:27:12209static void createEmptyIndex(StringRef ModulePath) {
210 std::string Path = replaceThinLTOSuffix(getThinLTOOutputFile(ModulePath));
Rui Ueyamaf06d4942018-05-17 18:27:12211 std::unique_ptr<raw_fd_ostream> OS = openFile(Path + ".thinlto.bc");
212 if (!OS)
213 return;
214
Teresa Johnson566b4022018-06-06 22:22:13215 ModuleSummaryIndex M(/*HaveGVs*/ false);
Rui Ueyamaf06d4942018-05-17 18:27:12216 M.setSkipModuleByDistributedBackend();
217 WriteIndexToFile(M, *OS);
218
219 if (Config->ThinLTOEmitImportsFiles)
220 openFile(Path + ".imports");
221}
222
Rui Ueyama25992482016-03-22 20:52:10223// Merge all the bitcode files we have seen, codegen the result
Davide Italiano786d8e32016-09-29 00:40:08224// and return the resulting ObjectFile(s).
Rui Ueyama38dbd3e2016-09-14 00:05:51225std::vector<InputFile *> BitcodeCompiler::compile() {
Davide Italiano3bfa0812016-11-26 05:37:04226 unsigned MaxTasks = LTOObj->getMaxTasks();
Rui Ueyamaf06d4942018-05-17 18:27:12227 Buf.resize(MaxTasks);
Peter Collingbournee02775f2017-03-01 23:00:10228 Files.resize(MaxTasks);
Davide Italiano828ac5412016-03-28 15:44:21229
Peter Collingbournee02775f2017-03-01 23:00:10230 // The --thinlto-cache-dir option specifies the path to a directory in which
231 // to cache native object files for ThinLTO incremental builds. If a path was
232 // specified, configure LTO to use it as the cache directory.
233 lto::NativeObjectCache Cache;
234 if (!Config->ThinLTOCacheDir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07235 Cache = check(
236 lto::localCache(Config->ThinLTOCacheDir,
Teresa Johnson2c2ed3c2018-02-20 20:21:59237 [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
238 Files[Task] = std::move(MB);
239 }));
Peter Collingbournee02775f2017-03-01 23:00:10240
241 checkError(LTOObj->run(
242 [&](size_t Task) {
243 return llvm::make_unique<lto::NativeObjectStream>(
Rui Ueyamaf06d4942018-05-17 18:27:12244 llvm::make_unique<raw_svector_ostream>(Buf[Task]));
Peter Collingbournee02775f2017-03-01 23:00:10245 },
246 Cache));
Rafael Espindolaabf6c652016-04-17 23:20:08247
Rumeet Dhindsa18883262018-05-08 20:12:07248 // Emit empty index files for non-indexed files
Rui Ueyama98e4a5c2018-09-11 14:37:27249 for (StringRef S : ThinIndices) {
250 std::string Path = getThinLTOOutputFile(S);
251 openFile(Path + ".thinlto.bc");
252 if (Config->ThinLTOEmitImportsFiles)
253 openFile(Path + ".imports");
Davide Italiano786d8e32016-09-29 00:40:08254 }
Peter Collingbournee02775f2017-03-01 23:00:10255
Rui Ueyamad54f1c22018-05-07 22:11:24256 // If LazyObjFile has not been added to link, emit empty index files.
257 // This is needed because this is what GNU gold plugin does and we have a
258 // distributed build system that depends on that behavior.
259 if (Config->ThinLTOIndexOnly) {
Rui Ueyamaf06d4942018-05-17 18:27:12260 for (LazyObjFile *F : LazyObjFiles)
261 if (!F->AddedToLink && isBitcode(F->MB))
262 createEmptyIndex(F->getName());
Rui Ueyamad54f1c22018-05-07 22:11:24263
Rumeet Dhindsab5b7d6e2018-05-08 22:37:57264 if (!Config->LTOObjPath.empty())
Rui Ueyamaf06d4942018-05-17 18:27:12265 saveBuffer(Buf[0], Config->LTOObjPath);
Rumeet Dhindsa18883262018-05-08 20:12:07266
Rui Ueyamad54f1c22018-05-07 22:11:24267 // ThinLTO with index only option is required to generate only the index
268 // files. After that, we exit from linker and ThinLTO backend runs in a
269 // distributed environment.
Rui Ueyama554adb22018-05-07 22:11:34270 if (IndexFile)
271 IndexFile->close();
272 return {};
Rui Ueyamad54f1c22018-05-07 22:11:24273 }
Rui Ueyamaf06d4942018-05-17 18:27:12274
Rumeet Dhindsa18883262018-05-08 20:12:07275 if (!Config->ThinLTOCacheDir.empty())
276 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
277
278 std::vector<InputFile *> Ret;
279 for (unsigned I = 0; I != MaxTasks; ++I) {
Rui Ueyamaf06d4942018-05-17 18:27:12280 if (Buf[I].empty())
Rumeet Dhindsa18883262018-05-08 20:12:07281 continue;
282 if (Config->SaveTemps) {
283 if (I == 0)
Rui Ueyamaf06d4942018-05-17 18:27:12284 saveBuffer(Buf[I], Config->OutputFile + ".lto.o");
Rumeet Dhindsa18883262018-05-08 20:12:07285 else
Rui Ueyamaf06d4942018-05-17 18:27:12286 saveBuffer(Buf[I], Config->OutputFile + Twine(I) + ".lto.o");
Rumeet Dhindsa18883262018-05-08 20:12:07287 }
Rui Ueyamaf06d4942018-05-17 18:27:12288 InputFile *Obj = createObjectFile(MemoryBufferRef(Buf[I], "lto.tmp"));
Rumeet Dhindsa18883262018-05-08 20:12:07289 Ret.push_back(Obj);
290 }
Rumeet Dhindsad366e362018-05-02 21:40:07291
Peter Collingbournee02775f2017-03-01 23:00:10292 for (std::unique_ptr<MemoryBuffer> &File : Files)
293 if (File)
294 Ret.push_back(createObjectFile(*File));
Davide Italiano786d8e32016-09-29 00:40:08295 return Ret;
Rui Ueyama961f2ff2016-03-23 21:19:27296}