xref: /llvm-project-15.0.7/lld/ELF/LTO.cpp (revision 22bdb331)
1 //===- 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"
12 #include "InputFiles.h"
13 #include "LinkerScript.h"
14 #include "SymbolTable.h"
15 #include "Symbols.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 using namespace lld;
46 using namespace lld::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       llvm::make_unique<raw_fd_ostream>(File, EC, sys::fs::OpenFlags::F_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(ModulePath,
63                                    Config->ThinLTOPrefixReplace.first,
64                                    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 (Config->Relocatable)
80     C.RelocModel = None;
81   else if (Config->Pic)
82     C.RelocModel = Reloc::PIC_;
83   else
84     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();
91   C.MAttrs = GetMAttrs();
92 
93   // Set up a custom pipeline if we've been asked to.
94   C.OptPipeline = Config->LTONewPmPasses;
95   C.AAPipeline = Config->LTOAAPipeline;
96 
97   // Set up optimization remarks if we've been asked to.
98   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;
104   C.DwoDir = Config->DwoDir;
105 
106   if (Config->SaveTemps)
107     checkError(C.addSaveTemps(Config->OutputFile.str() + ".",
108                               /*UseInputModulePath*/ true));
109   return C;
110 }
111 
112 BitcodeCompiler::BitcodeCompiler() {
113   // Initialize IndexFile.
114   if (!Config->ThinLTOIndexOnlyArg.empty())
115     IndexFile = openFile(Config->ThinLTOIndexOnlyArg);
116 
117   // Initialize LTOObj.
118   lto::ThinBackend Backend;
119   if (Config->ThinLTOIndexOnly) {
120     auto OnIndexWrite = [&](StringRef S) { ThinIndices.erase(S); };
121     Backend = lto::createWriteIndexesThinBackend(
122         Config->ThinLTOPrefixReplace.first, Config->ThinLTOPrefixReplace.second,
123         Config->ThinLTOEmitImportsFiles, IndexFile.get(), OnIndexWrite);
124   } else if (Config->ThinLTOJobs != -1U) {
125     Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
126   }
127 
128   LTOObj = llvm::make_unique<lto::LTO>(createConfig(), Backend,
129                                        Config->LTOPartitions);
130 
131   // Initialize UsedStartStop.
132   for (Symbol *Sym : Symtab->getSymbols()) {
133     StringRef S = Sym->getName();
134     for (StringRef Prefix : {"__start_", "__stop_"})
135       if (S.startswith(Prefix))
136         UsedStartStop.insert(S.substr(Prefix.size()));
137   }
138 }
139 
140 BitcodeCompiler::~BitcodeCompiler() = default;
141 
142 static void undefine(Symbol *S) {
143   replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_GLOBAL, STV_DEFAULT,
144                            S->Type);
145 }
146 
147 void BitcodeCompiler::add(BitcodeFile &F) {
148   lto::InputFile &Obj = *F.Obj;
149   bool IsExec = !Config->Shared && !Config->Relocatable;
150 
151   if (Config->ThinLTOIndexOnly)
152     ThinIndices.insert(Obj.getName());
153 
154   ArrayRef<Symbol *> Syms = F.getSymbols();
155   ArrayRef<lto::InputFile::Symbol> ObjSyms = Obj.symbols();
156   std::vector<lto::SymbolResolution> Resols(Syms.size());
157 
158   // Provide a resolution to the LTO API for each symbol.
159   for (size_t I = 0, E = Syms.size(); I != E; ++I) {
160     Symbol *Sym = Syms[I];
161     const lto::InputFile::Symbol &ObjSym = ObjSyms[I];
162     lto::SymbolResolution &R = Resols[I];
163 
164     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
165     // reports two symbols for module ASM defined. Without this check, lld
166     // flags an undefined in IR with a definition in ASM as prevailing.
167     // Once IRObjectFile is fixed to report only one symbol this hack can
168     // be removed.
169     R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F;
170 
171     // We ask LTO to preserve following global symbols:
172     // 1) All symbols when doing relocatable link, so that them can be used
173     //    for doing final link.
174     // 2) Symbols that are used in regular objects.
175     // 3) C named sections if we have corresponding __start_/__stop_ symbol.
176     // 4) Symbols that are defined in bitcode files and used for dynamic linking.
177     R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
178                             (R.Prevailing && Sym->includeInDynsym()) ||
179                             UsedStartStop.count(ObjSym.getSectionName());
180     const auto *DR = dyn_cast<Defined>(Sym);
181     R.FinalDefinitionInLinkageUnit =
182         (IsExec || Sym->Visibility != STV_DEFAULT) && DR &&
183         // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
184         // will be generated by for them, triggering linker errors.
185         // Symbol section is always null for bitcode symbols, hence the check
186         // for isElf(). Skip linker script defined symbols as well: they have
187         // no File defined.
188         !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf()));
189 
190     if (R.Prevailing)
191       undefine(Sym);
192 
193     // We tell LTO to not apply interprocedural optimization for wrapped
194     // (with --wrap) symbols because otherwise LTO would inline them while
195     // their values are still not final.
196     R.LinkerRedefined = !Sym->CanInline;
197   }
198   checkError(LTOObj->add(std::move(F.Obj), Resols));
199 }
200 
201 static void createEmptyIndex(StringRef ModulePath) {
202   std::string Path = replaceThinLTOSuffix(getThinLTOOutputFile(ModulePath));
203   std::unique_ptr<raw_fd_ostream> OS = openFile(Path + ".thinlto.bc");
204   if (!OS)
205     return;
206 
207   ModuleSummaryIndex M(/*HaveGVs*/ false);
208   M.setSkipModuleByDistributedBackend();
209   WriteIndexToFile(M, *OS);
210 
211   if (Config->ThinLTOEmitImportsFiles)
212     openFile(Path + ".imports");
213 }
214 
215 // Merge all the bitcode files we have seen, codegen the result
216 // and return the resulting ObjectFile(s).
217 std::vector<InputFile *> BitcodeCompiler::compile() {
218   unsigned MaxTasks = LTOObj->getMaxTasks();
219   Buf.resize(MaxTasks);
220   Files.resize(MaxTasks);
221 
222   // The --thinlto-cache-dir option specifies the path to a directory in which
223   // to cache native object files for ThinLTO incremental builds. If a path was
224   // specified, configure LTO to use it as the cache directory.
225   lto::NativeObjectCache Cache;
226   if (!Config->ThinLTOCacheDir.empty())
227     Cache = check(
228         lto::localCache(Config->ThinLTOCacheDir,
229                         [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
230                           Files[Task] = std::move(MB);
231                         }));
232 
233   checkError(LTOObj->run(
234       [&](size_t Task) {
235         return llvm::make_unique<lto::NativeObjectStream>(
236             llvm::make_unique<raw_svector_ostream>(Buf[Task]));
237       },
238       Cache));
239 
240   // Emit empty index files for non-indexed files
241   for (StringRef S : ThinIndices) {
242     std::string Path = getThinLTOOutputFile(S);
243     openFile(Path + ".thinlto.bc");
244     if (Config->ThinLTOEmitImportsFiles)
245       openFile(Path + ".imports");
246   }
247 
248   // If LazyObjFile has not been added to link, emit empty index files.
249   // This is needed because this is what GNU gold plugin does and we have a
250   // distributed build system that depends on that behavior.
251   if (Config->ThinLTOIndexOnly) {
252     for (LazyObjFile *F : LazyObjFiles)
253       if (!F->AddedToLink && isBitcode(F->MB))
254         createEmptyIndex(F->getName());
255 
256     if (!Config->LTOObjPath.empty())
257       saveBuffer(Buf[0], Config->LTOObjPath);
258 
259     // ThinLTO with index only option is required to generate only the index
260     // files. After that, we exit from linker and ThinLTO backend runs in a
261     // distributed environment.
262     if (IndexFile)
263       IndexFile->close();
264     return {};
265   }
266 
267   if (!Config->ThinLTOCacheDir.empty())
268     pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
269 
270   std::vector<InputFile *> Ret;
271   for (unsigned I = 0; I != MaxTasks; ++I) {
272     if (Buf[I].empty())
273       continue;
274     if (Config->SaveTemps) {
275       if (I == 0)
276         saveBuffer(Buf[I], Config->OutputFile + ".lto.o");
277       else
278         saveBuffer(Buf[I], Config->OutputFile + Twine(I) + ".lto.o");
279     }
280     InputFile *Obj = createObjectFile(MemoryBufferRef(Buf[I], "lto.tmp"));
281     Ret.push_back(Obj);
282   }
283 
284   for (std::unique_ptr<MemoryBuffer> &File : Files)
285     if (File)
286       Ret.push_back(createObjectFile(*File));
287   return Ret;
288 }
289