xref: /llvm-project-15.0.7/lld/ELF/LTO.cpp (revision 5fedf7f4)
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   // Check if basic block sections must be used.
80   // Allowed values for --lto-basicblock-sections are "all", "labels",
81   // "<file name specifying basic block ids>", or none.  This is the equivalent
82   // of -fbasicblock-sections= flag in clang.
83   if (!config->ltoBasicBlockSections.empty()) {
84     if (config->ltoBasicBlockSections == "all") {
85       c.Options.BBSections = BasicBlockSection::All;
86     } else if (config->ltoBasicBlockSections == "labels") {
87       c.Options.BBSections = BasicBlockSection::Labels;
88     } else if (config->ltoBasicBlockSections == "none") {
89       c.Options.BBSections = BasicBlockSection::None;
90     } else {
91       ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
92           MemoryBuffer::getFile(config->ltoBasicBlockSections.str());
93       if (!MBOrErr) {
94         error("cannot open " + config->ltoBasicBlockSections + ":" +
95               MBOrErr.getError().message());
96       } else {
97         c.Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
98       }
99       c.Options.BBSections = BasicBlockSection::List;
100     }
101   }
102 
103   c.Options.UniqueBBSectionNames = config->ltoUniqueBBSectionNames;
104 
105   if (auto relocModel = getRelocModelFromCMModel())
106     c.RelocModel = *relocModel;
107   else if (config->relocatable)
108     c.RelocModel = None;
109   else if (config->isPic)
110     c.RelocModel = Reloc::PIC_;
111   else
112     c.RelocModel = Reloc::Static;
113 
114   c.CodeModel = getCodeModelFromCMModel();
115   c.DisableVerify = config->disableVerify;
116   c.DiagHandler = diagnosticHandler;
117   c.OptLevel = config->ltoo;
118   c.CPU = getCPUStr();
119   c.MAttrs = getMAttrs();
120   c.CGOptLevel = args::getCGOptLevel(config->ltoo);
121 
122   c.PTO.LoopVectorization = c.OptLevel > 1;
123   c.PTO.SLPVectorization = c.OptLevel > 1;
124 
125   // Set up a custom pipeline if we've been asked to.
126   c.OptPipeline = std::string(config->ltoNewPmPasses);
127   c.AAPipeline = std::string(config->ltoAAPipeline);
128 
129   // Set up optimization remarks if we've been asked to.
130   c.RemarksFilename = std::string(config->optRemarksFilename);
131   c.RemarksPasses = std::string(config->optRemarksPasses);
132   c.RemarksWithHotness = config->optRemarksWithHotness;
133   c.RemarksFormat = std::string(config->optRemarksFormat);
134 
135   c.SampleProfile = std::string(config->ltoSampleProfile);
136   c.UseNewPM = config->ltoNewPassManager;
137   c.DebugPassManager = config->ltoDebugPassManager;
138   c.DwoDir = std::string(config->dwoDir);
139 
140   c.HasWholeProgramVisibility = config->ltoWholeProgramVisibility;
141 
142   c.TimeTraceEnabled = config->timeTraceEnabled;
143   c.TimeTraceGranularity = config->timeTraceGranularity;
144 
145   c.CSIRProfile = std::string(config->ltoCSProfileFile);
146   c.RunCSIRInstr = config->ltoCSProfileGenerate;
147 
148   if (config->emitLLVM) {
149     c.PostInternalizeModuleHook = [](size_t task, const Module &m) {
150       if (std::unique_ptr<raw_fd_ostream> os = openFile(config->outputFile))
151         WriteBitcodeToFile(m, *os, false);
152       return false;
153     };
154   }
155 
156   if (config->saveTemps)
157     checkError(c.addSaveTemps(config->outputFile.str() + ".",
158                               /*UseInputModulePath*/ true));
159   return c;
160 }
161 
162 BitcodeCompiler::BitcodeCompiler() {
163   // Initialize indexFile.
164   if (!config->thinLTOIndexOnlyArg.empty())
165     indexFile = openFile(config->thinLTOIndexOnlyArg);
166 
167   // Initialize ltoObj.
168   lto::ThinBackend backend;
169   if (config->thinLTOIndexOnly) {
170     auto onIndexWrite = [&](StringRef s) { thinIndices.erase(s); };
171     backend = lto::createWriteIndexesThinBackend(
172         std::string(config->thinLTOPrefixReplace.first),
173         std::string(config->thinLTOPrefixReplace.second),
174         config->thinLTOEmitImportsFiles, indexFile.get(), onIndexWrite);
175   } else {
176     backend = lto::createInProcessThinBackend(
177         llvm::heavyweight_hardware_concurrency(config->thinLTOJobs));
178   }
179 
180   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend,
181                                        config->ltoPartitions);
182 
183   // Initialize usedStartStop.
184   for (Symbol *sym : symtab->symbols()) {
185     StringRef s = sym->getName();
186     for (StringRef prefix : {"__start_", "__stop_"})
187       if (s.startswith(prefix))
188         usedStartStop.insert(s.substr(prefix.size()));
189   }
190 }
191 
192 BitcodeCompiler::~BitcodeCompiler() = default;
193 
194 void BitcodeCompiler::add(BitcodeFile &f) {
195   lto::InputFile &obj = *f.obj;
196   bool isExec = !config->shared && !config->relocatable;
197 
198   if (config->thinLTOIndexOnly)
199     thinIndices.insert(obj.getName());
200 
201   ArrayRef<Symbol *> syms = f.getSymbols();
202   ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols();
203   std::vector<lto::SymbolResolution> resols(syms.size());
204 
205   // Provide a resolution to the LTO API for each symbol.
206   for (size_t i = 0, e = syms.size(); i != e; ++i) {
207     Symbol *sym = syms[i];
208     const lto::InputFile::Symbol &objSym = objSyms[i];
209     lto::SymbolResolution &r = resols[i];
210 
211     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
212     // reports two symbols for module ASM defined. Without this check, lld
213     // flags an undefined in IR with a definition in ASM as prevailing.
214     // Once IRObjectFile is fixed to report only one symbol this hack can
215     // be removed.
216     r.Prevailing = !objSym.isUndefined() && sym->file == &f;
217 
218     // We ask LTO to preserve following global symbols:
219     // 1) All symbols when doing relocatable link, so that them can be used
220     //    for doing final link.
221     // 2) Symbols that are used in regular objects.
222     // 3) C named sections if we have corresponding __start_/__stop_ symbol.
223     // 4) Symbols that are defined in bitcode files and used for dynamic linking.
224     r.VisibleToRegularObj = config->relocatable || sym->isUsedInRegularObj ||
225                             (r.Prevailing && sym->includeInDynsym()) ||
226                             usedStartStop.count(objSym.getSectionName());
227     const auto *dr = dyn_cast<Defined>(sym);
228     r.FinalDefinitionInLinkageUnit =
229         (isExec || sym->visibility != STV_DEFAULT) && dr &&
230         // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
231         // will be generated by for them, triggering linker errors.
232         // Symbol section is always null for bitcode symbols, hence the check
233         // for isElf(). Skip linker script defined symbols as well: they have
234         // no File defined.
235         !(dr->section == nullptr && (!sym->file || sym->file->isElf()));
236 
237     if (r.Prevailing)
238       sym->replace(Undefined{nullptr, sym->getName(), STB_GLOBAL, STV_DEFAULT,
239                              sym->type});
240 
241     // We tell LTO to not apply interprocedural optimization for wrapped
242     // (with --wrap) symbols because otherwise LTO would inline them while
243     // their values are still not final.
244     r.LinkerRedefined = !sym->canInline;
245   }
246   checkError(ltoObj->add(std::move(f.obj), resols));
247 }
248 
249 // If LazyObjFile has not been added to link, emit empty index files.
250 // This is needed because this is what GNU gold plugin does and we have a
251 // distributed build system that depends on that behavior.
252 static void thinLTOCreateEmptyIndexFiles() {
253   for (LazyObjFile *f : lazyObjFiles) {
254     if (!isBitcode(f->mb))
255       continue;
256     std::string path = replaceThinLTOSuffix(getThinLTOOutputFile(f->getName()));
257     std::unique_ptr<raw_fd_ostream> os = openFile(path + ".thinlto.bc");
258     if (!os)
259       continue;
260 
261     ModuleSummaryIndex m(/*HaveGVs*/ false);
262     m.setSkipModuleByDistributedBackend();
263     WriteIndexToFile(m, *os);
264     if (config->thinLTOEmitImportsFiles)
265       openFile(path + ".imports");
266   }
267 }
268 
269 // Merge all the bitcode files we have seen, codegen the result
270 // and return the resulting ObjectFile(s).
271 std::vector<InputFile *> BitcodeCompiler::compile() {
272   unsigned maxTasks = ltoObj->getMaxTasks();
273   buf.resize(maxTasks);
274   files.resize(maxTasks);
275 
276   // The --thinlto-cache-dir option specifies the path to a directory in which
277   // to cache native object files for ThinLTO incremental builds. If a path was
278   // specified, configure LTO to use it as the cache directory.
279   lto::NativeObjectCache cache;
280   if (!config->thinLTOCacheDir.empty())
281     cache = check(
282         lto::localCache(config->thinLTOCacheDir,
283                         [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
284                           files[task] = std::move(mb);
285                         }));
286 
287   if (!bitcodeFiles.empty())
288     checkError(ltoObj->run(
289         [&](size_t task) {
290           return std::make_unique<lto::NativeObjectStream>(
291               std::make_unique<raw_svector_ostream>(buf[task]));
292         },
293         cache));
294 
295   // Emit empty index files for non-indexed files
296   for (StringRef s : thinIndices) {
297     std::string path = getThinLTOOutputFile(s);
298     openFile(path + ".thinlto.bc");
299     if (config->thinLTOEmitImportsFiles)
300       openFile(path + ".imports");
301   }
302 
303   if (config->thinLTOIndexOnly) {
304     thinLTOCreateEmptyIndexFiles();
305 
306     if (!config->ltoObjPath.empty())
307       saveBuffer(buf[0], config->ltoObjPath);
308 
309     // ThinLTO with index only option is required to generate only the index
310     // files. After that, we exit from linker and ThinLTO backend runs in a
311     // distributed environment.
312     if (indexFile)
313       indexFile->close();
314     return {};
315   }
316 
317   if (!config->thinLTOCacheDir.empty())
318     pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy);
319 
320   if (!config->ltoObjPath.empty()) {
321     saveBuffer(buf[0], config->ltoObjPath);
322     for (unsigned i = 1; i != maxTasks; ++i)
323       saveBuffer(buf[i], config->ltoObjPath + Twine(i));
324   }
325 
326   if (config->saveTemps) {
327     saveBuffer(buf[0], config->outputFile + ".lto.o");
328     for (unsigned i = 1; i != maxTasks; ++i)
329       saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o");
330   }
331 
332   std::vector<InputFile *> ret;
333   for (unsigned i = 0; i != maxTasks; ++i)
334     if (!buf[i].empty())
335       ret.push_back(createObjectFile(MemoryBufferRef(buf[i], "lto.tmp")));
336 
337   for (std::unique_ptr<MemoryBuffer> &file : files)
338     if (file)
339       ret.push_back(createObjectFile(*file));
340   return ret;
341 }
342 
343 } // namespace elf
344 } // namespace lld
345