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