xref: /llvm-project-15.0.7/lld/ELF/LTO.cpp (revision 0570de73)
1 //===- LTO.cpp ------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "LTO.h"
10 #include "Config.h"
11 #include "InputFiles.h"
12 #include "LinkerScript.h"
13 #include "SymbolTable.h"
14 #include "Symbols.h"
15 #include "lld/Common/Args.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/TargetOptionsCommandFlags.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/BitcodeWriter.h"
25 #include "llvm/IR/DiagnosticPrinter.h"
26 #include "llvm/LTO/Caching.h"
27 #include "llvm/LTO/Config.h"
28 #include "llvm/LTO/LTO.h"
29 #include "llvm/Object/SymbolicFile.h"
30 #include "llvm/Support/CodeGen.h"
31 #include "llvm/Support/Error.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include <algorithm>
35 #include <cstddef>
36 #include <memory>
37 #include <string>
38 #include <system_error>
39 #include <vector>
40 
41 using namespace llvm;
42 using namespace llvm::object;
43 using namespace llvm::ELF;
44 
45 namespace lld {
46 namespace elf {
47 
48 // Creates an empty file to store a list of object files for final
49 // linking of distributed ThinLTO.
50 static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) {
51   std::error_code ec;
52   auto ret =
53       std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None);
54   if (ec) {
55     error("cannot open " + file + ": " + ec.message());
56     return nullptr;
57   }
58   return ret;
59 }
60 
61 static std::string getThinLTOOutputFile(StringRef modulePath) {
62   return lto::getThinLTOOutputFile(
63       std::string(modulePath), std::string(config->thinLTOPrefixReplace.first),
64       std::string(config->thinLTOPrefixReplace.second));
65 }
66 
67 static lto::Config createConfig() {
68   lto::Config c;
69 
70   // LLD supports the new relocations and address-significance tables.
71   c.Options = initTargetOptionsFromCodeGenFlags();
72   c.Options.RelaxELFRelocations = true;
73   c.Options.EmitAddrsig = true;
74 
75   // Always emit a section per function/datum with LTO.
76   c.Options.FunctionSections = true;
77   c.Options.DataSections = true;
78 
79   if (auto relocModel = getRelocModelFromCMModel())
80     c.RelocModel = *relocModel;
81   else if (config->relocatable)
82     c.RelocModel = None;
83   else if (config->isPic)
84     c.RelocModel = Reloc::PIC_;
85   else
86     c.RelocModel = Reloc::Static;
87 
88   c.CodeModel = getCodeModelFromCMModel();
89   c.DisableVerify = config->disableVerify;
90   c.DiagHandler = diagnosticHandler;
91   c.OptLevel = config->ltoo;
92   c.CPU = getCPUStr();
93   c.MAttrs = getMAttrs();
94   c.CGOptLevel = args::getCGOptLevel(config->ltoo);
95 
96   c.PTO.LoopVectorization = c.OptLevel > 1;
97   c.PTO.SLPVectorization = c.OptLevel > 1;
98 
99   // Set up a custom pipeline if we've been asked to.
100   c.OptPipeline = std::string(config->ltoNewPmPasses);
101   c.AAPipeline = std::string(config->ltoAAPipeline);
102 
103   // Set up optimization remarks if we've been asked to.
104   c.RemarksFilename = std::string(config->optRemarksFilename);
105   c.RemarksPasses = std::string(config->optRemarksPasses);
106   c.RemarksWithHotness = config->optRemarksWithHotness;
107   c.RemarksFormat = std::string(config->optRemarksFormat);
108 
109   c.SampleProfile = std::string(config->ltoSampleProfile);
110   c.UseNewPM = config->ltoNewPassManager;
111   c.DebugPassManager = config->ltoDebugPassManager;
112   c.DwoDir = std::string(config->dwoDir);
113 
114   c.HasWholeProgramVisibility = config->ltoWholeProgramVisibility;
115 
116   c.TimeTraceEnabled = config->timeTraceEnabled;
117   c.TimeTraceGranularity = config->timeTraceGranularity;
118 
119   c.CSIRProfile = std::string(config->ltoCSProfileFile);
120   c.RunCSIRInstr = config->ltoCSProfileGenerate;
121 
122   if (config->emitLLVM) {
123     c.PostInternalizeModuleHook = [](size_t task, const Module &m) {
124       if (std::unique_ptr<raw_fd_ostream> os = openFile(config->outputFile))
125         WriteBitcodeToFile(m, *os, false);
126       return false;
127     };
128   }
129 
130   if (config->saveTemps)
131     checkError(c.addSaveTemps(config->outputFile.str() + ".",
132                               /*UseInputModulePath*/ true));
133   return c;
134 }
135 
136 BitcodeCompiler::BitcodeCompiler() {
137   // Initialize indexFile.
138   if (!config->thinLTOIndexOnlyArg.empty())
139     indexFile = openFile(config->thinLTOIndexOnlyArg);
140 
141   // Initialize ltoObj.
142   lto::ThinBackend backend;
143   if (config->thinLTOIndexOnly) {
144     auto onIndexWrite = [&](StringRef s) { thinIndices.erase(s); };
145     backend = lto::createWriteIndexesThinBackend(
146         std::string(config->thinLTOPrefixReplace.first),
147         std::string(config->thinLTOPrefixReplace.second),
148         config->thinLTOEmitImportsFiles, indexFile.get(), onIndexWrite);
149   } else {
150     backend = lto::createInProcessThinBackend(
151         llvm::heavyweight_hardware_concurrency(config->thinLTOJobs));
152   }
153 
154   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend,
155                                        config->ltoPartitions);
156 
157   // Initialize usedStartStop.
158   for (Symbol *sym : symtab->symbols()) {
159     StringRef s = sym->getName();
160     for (StringRef prefix : {"__start_", "__stop_"})
161       if (s.startswith(prefix))
162         usedStartStop.insert(s.substr(prefix.size()));
163   }
164 }
165 
166 BitcodeCompiler::~BitcodeCompiler() = default;
167 
168 void BitcodeCompiler::add(BitcodeFile &f) {
169   lto::InputFile &obj = *f.obj;
170   bool isExec = !config->shared && !config->relocatable;
171 
172   if (config->thinLTOIndexOnly)
173     thinIndices.insert(obj.getName());
174 
175   ArrayRef<Symbol *> syms = f.getSymbols();
176   ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols();
177   std::vector<lto::SymbolResolution> resols(syms.size());
178 
179   // Provide a resolution to the LTO API for each symbol.
180   for (size_t i = 0, e = syms.size(); i != e; ++i) {
181     Symbol *sym = syms[i];
182     const lto::InputFile::Symbol &objSym = objSyms[i];
183     lto::SymbolResolution &r = resols[i];
184 
185     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
186     // reports two symbols for module ASM defined. Without this check, lld
187     // flags an undefined in IR with a definition in ASM as prevailing.
188     // Once IRObjectFile is fixed to report only one symbol this hack can
189     // be removed.
190     r.Prevailing = !objSym.isUndefined() && sym->file == &f;
191 
192     // We ask LTO to preserve following global symbols:
193     // 1) All symbols when doing relocatable link, so that them can be used
194     //    for doing final link.
195     // 2) Symbols that are used in regular objects.
196     // 3) C named sections if we have corresponding __start_/__stop_ symbol.
197     // 4) Symbols that are defined in bitcode files and used for dynamic linking.
198     r.VisibleToRegularObj = config->relocatable || sym->isUsedInRegularObj ||
199                             (r.Prevailing && sym->includeInDynsym()) ||
200                             usedStartStop.count(objSym.getSectionName());
201     const auto *dr = dyn_cast<Defined>(sym);
202     r.FinalDefinitionInLinkageUnit =
203         (isExec || sym->visibility != STV_DEFAULT) && dr &&
204         // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
205         // will be generated by for them, triggering linker errors.
206         // Symbol section is always null for bitcode symbols, hence the check
207         // for isElf(). Skip linker script defined symbols as well: they have
208         // no File defined.
209         !(dr->section == nullptr && (!sym->file || sym->file->isElf()));
210 
211     if (r.Prevailing)
212       sym->replace(Undefined{nullptr, sym->getName(), STB_GLOBAL, STV_DEFAULT,
213                              sym->type});
214 
215     // We tell LTO to not apply interprocedural optimization for wrapped
216     // (with --wrap) symbols because otherwise LTO would inline them while
217     // their values are still not final.
218     r.LinkerRedefined = !sym->canInline;
219   }
220   checkError(ltoObj->add(std::move(f.obj), resols));
221 }
222 
223 // If LazyObjFile has not been added to link, emit empty index files.
224 // This is needed because this is what GNU gold plugin does and we have a
225 // distributed build system that depends on that behavior.
226 static void thinLTOCreateEmptyIndexFiles() {
227   for (LazyObjFile *f : lazyObjFiles) {
228     if (!isBitcode(f->mb))
229       continue;
230     std::string path = replaceThinLTOSuffix(getThinLTOOutputFile(f->getName()));
231     std::unique_ptr<raw_fd_ostream> os = openFile(path + ".thinlto.bc");
232     if (!os)
233       continue;
234 
235     ModuleSummaryIndex m(/*HaveGVs*/ false);
236     m.setSkipModuleByDistributedBackend();
237     WriteIndexToFile(m, *os);
238     if (config->thinLTOEmitImportsFiles)
239       openFile(path + ".imports");
240   }
241 }
242 
243 // Merge all the bitcode files we have seen, codegen the result
244 // and return the resulting ObjectFile(s).
245 std::vector<InputFile *> BitcodeCompiler::compile() {
246   unsigned maxTasks = ltoObj->getMaxTasks();
247   buf.resize(maxTasks);
248   files.resize(maxTasks);
249 
250   // The --thinlto-cache-dir option specifies the path to a directory in which
251   // to cache native object files for ThinLTO incremental builds. If a path was
252   // specified, configure LTO to use it as the cache directory.
253   lto::NativeObjectCache cache;
254   if (!config->thinLTOCacheDir.empty())
255     cache = check(
256         lto::localCache(config->thinLTOCacheDir,
257                         [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
258                           files[task] = std::move(mb);
259                         }));
260 
261   if (!bitcodeFiles.empty())
262     checkError(ltoObj->run(
263         [&](size_t task) {
264           return std::make_unique<lto::NativeObjectStream>(
265               std::make_unique<raw_svector_ostream>(buf[task]));
266         },
267         cache));
268 
269   // Emit empty index files for non-indexed files
270   for (StringRef s : thinIndices) {
271     std::string path = getThinLTOOutputFile(s);
272     openFile(path + ".thinlto.bc");
273     if (config->thinLTOEmitImportsFiles)
274       openFile(path + ".imports");
275   }
276 
277   if (config->thinLTOIndexOnly) {
278     thinLTOCreateEmptyIndexFiles();
279 
280     if (!config->ltoObjPath.empty())
281       saveBuffer(buf[0], config->ltoObjPath);
282 
283     // ThinLTO with index only option is required to generate only the index
284     // files. After that, we exit from linker and ThinLTO backend runs in a
285     // distributed environment.
286     if (indexFile)
287       indexFile->close();
288     return {};
289   }
290 
291   if (!config->thinLTOCacheDir.empty())
292     pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy);
293 
294   if (!config->ltoObjPath.empty()) {
295     saveBuffer(buf[0], config->ltoObjPath);
296     for (unsigned i = 1; i != maxTasks; ++i)
297       saveBuffer(buf[i], config->ltoObjPath + Twine(i));
298   }
299 
300   if (config->saveTemps) {
301     saveBuffer(buf[0], config->outputFile + ".lto.o");
302     for (unsigned i = 1; i != maxTasks; ++i)
303       saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o");
304   }
305 
306   std::vector<InputFile *> ret;
307   for (unsigned i = 0; i != maxTasks; ++i)
308     if (!buf[i].empty())
309       ret.push_back(createObjectFile(MemoryBufferRef(buf[i], "lto.tmp")));
310 
311   for (std::unique_ptr<MemoryBuffer> &file : files)
312     if (file)
313       ret.push_back(createObjectFile(*file));
314   return ret;
315 }
316 
317 } // namespace elf
318 } // namespace lld
319