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