xref: /llvm-project-15.0.7/lld/ELF/LTO.cpp (revision 9e5283f2)
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/IR/DiagnosticPrinter.h"
24 #include "llvm/LTO/Caching.h"
25 #include "llvm/LTO/Config.h"
26 #include "llvm/LTO/LTO.h"
27 #include "llvm/Object/SymbolicFile.h"
28 #include "llvm/Support/CodeGen.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 #include <cstddef>
35 #include <memory>
36 #include <string>
37 #include <system_error>
38 #include <vector>
39 
40 using namespace llvm;
41 using namespace llvm::object;
42 using namespace llvm::ELF;
43 
44 using namespace lld;
45 using namespace lld::elf;
46 
47 // This is for use when debugging LTO.
48 static void saveBuffer(StringRef Buffer, const Twine &Path) {
49   std::error_code EC;
50   raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
51   if (EC)
52     error("cannot create " + Path + ": " + EC.message());
53   OS << Buffer;
54 }
55 
56 static void diagnosticHandler(const DiagnosticInfo &DI) {
57   SmallString<128> ErrStorage;
58   raw_svector_ostream OS(ErrStorage);
59   DiagnosticPrinterRawOStream DP(OS);
60   DI.print(DP);
61   warn(ErrStorage);
62 }
63 
64 static void checkError(Error E) {
65   handleAllErrors(std::move(E),
66                   [&](ErrorInfoBase &EIB) { error(EIB.message()); });
67 }
68 
69 static std::unique_ptr<lto::LTO> createLTO() {
70   lto::Config Conf;
71 
72   // LLD supports the new relocations.
73   Conf.Options = InitTargetOptionsFromCodeGenFlags();
74   Conf.Options.RelaxELFRelocations = true;
75 
76   // Always emit a section per function/datum with LTO.
77   Conf.Options.FunctionSections = true;
78   Conf.Options.DataSections = true;
79 
80   if (Config->Relocatable)
81     Conf.RelocModel = None;
82   else if (Config->Pic)
83     Conf.RelocModel = Reloc::PIC_;
84   else
85     Conf.RelocModel = Reloc::Static;
86   Conf.CodeModel = GetCodeModelFromCMModel();
87   Conf.DisableVerify = Config->DisableVerify;
88   Conf.DiagHandler = diagnosticHandler;
89   Conf.OptLevel = Config->LTOO;
90   Conf.CPU = GetCPUStr();
91 
92   // Set up a custom pipeline if we've been asked to.
93   Conf.OptPipeline = Config->LTONewPmPasses;
94   Conf.AAPipeline = Config->LTOAAPipeline;
95 
96   // Set up optimization remarks if we've been asked to.
97   Conf.RemarksFilename = Config->OptRemarksFilename;
98   Conf.RemarksWithHotness = Config->OptRemarksWithHotness;
99 
100   if (Config->SaveTemps)
101     checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".",
102                                  /*UseInputModulePath*/ true));
103 
104   lto::ThinBackend Backend;
105   if (Config->ThinLTOJobs != -1u)
106     Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
107 
108   Conf.SampleProfile = Config->LTOSampleProfile;
109   Conf.UseNewPM = Config->LTONewPassManager;
110   Conf.DebugPassManager = Config->LTODebugPassManager;
111 
112   return llvm::make_unique<lto::LTO>(std::move(Conf), Backend,
113                                      Config->LTOPartitions);
114 }
115 
116 BitcodeCompiler::BitcodeCompiler() : LTOObj(createLTO()) {
117   for (Symbol *Sym : Symtab->getSymbols()) {
118     StringRef Name = Sym->getName();
119     for (StringRef Prefix : {"__start_", "__stop_"})
120       if (Name.startswith(Prefix))
121         UsedStartStop.insert(Name.substr(Prefix.size()));
122   }
123 }
124 
125 BitcodeCompiler::~BitcodeCompiler() = default;
126 
127 static void undefine(Symbol *S) {
128   replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_GLOBAL, STV_DEFAULT,
129                            S->Type);
130 }
131 
132 void BitcodeCompiler::add(BitcodeFile &F) {
133   lto::InputFile &Obj = *F.Obj;
134   unsigned SymNum = 0;
135   std::vector<Symbol *> Syms = F.getSymbols();
136   std::vector<lto::SymbolResolution> Resols(Syms.size());
137 
138   bool IsExecutable = !Config->Shared && !Config->Relocatable;
139 
140   // Provide a resolution to the LTO API for each symbol.
141   for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
142     Symbol *Sym = Syms[SymNum];
143     lto::SymbolResolution &R = Resols[SymNum];
144     ++SymNum;
145 
146     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
147     // reports two symbols for module ASM defined. Without this check, lld
148     // flags an undefined in IR with a definition in ASM as prevailing.
149     // Once IRObjectFile is fixed to report only one symbol this hack can
150     // be removed.
151     R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F;
152 
153     // We ask LTO to preserve following global symbols:
154     // 1) All symbols when doing relocatable link, so that them can be used
155     //    for doing final link.
156     // 2) Symbols that are used in regular objects.
157     // 3) C named sections if we have corresponding __start_/__stop_ symbol.
158     // 4) Symbols that are defined in bitcode files and used for dynamic linking.
159     R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
160                             (R.Prevailing && Sym->includeInDynsym()) ||
161                             UsedStartStop.count(ObjSym.getSectionName());
162     const auto *DR = dyn_cast<Defined>(Sym);
163     R.FinalDefinitionInLinkageUnit =
164         (IsExecutable || Sym->Visibility != STV_DEFAULT) && DR &&
165         // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
166         // will be generated by for them, triggering linker errors.
167         // Symbol section is always null for bitcode symbols, hence the check
168         // for isElf(). Skip linker script defined symbols as well: they have
169         // no File defined.
170         !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf()));
171 
172     if (R.Prevailing)
173       undefine(Sym);
174 
175     // We tell LTO to not apply interprocedural optimization for wrapped
176     // (with --wrap) symbols because otherwise LTO would inline them while
177     // their values are still not final.
178     R.LinkerRedefined = !Sym->CanInline;
179   }
180   checkError(LTOObj->add(std::move(F.Obj), Resols));
181 }
182 
183 // Merge all the bitcode files we have seen, codegen the result
184 // and return the resulting ObjectFile(s).
185 std::vector<InputFile *> BitcodeCompiler::compile() {
186   std::vector<InputFile *> Ret;
187   unsigned MaxTasks = LTOObj->getMaxTasks();
188   Buff.resize(MaxTasks);
189   Files.resize(MaxTasks);
190 
191   // The --thinlto-cache-dir option specifies the path to a directory in which
192   // to cache native object files for ThinLTO incremental builds. If a path was
193   // specified, configure LTO to use it as the cache directory.
194   lto::NativeObjectCache Cache;
195   if (!Config->ThinLTOCacheDir.empty())
196     Cache = check(
197         lto::localCache(Config->ThinLTOCacheDir,
198                         [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
199                           Files[Task] = std::move(MB);
200                         }));
201 
202   checkError(LTOObj->run(
203       [&](size_t Task) {
204         return llvm::make_unique<lto::NativeObjectStream>(
205             llvm::make_unique<raw_svector_ostream>(Buff[Task]));
206       },
207       Cache));
208 
209   if (!Config->ThinLTOCacheDir.empty())
210     pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
211 
212   for (unsigned I = 0; I != MaxTasks; ++I) {
213     if (Buff[I].empty())
214       continue;
215     if (Config->SaveTemps) {
216       if (I == 0)
217         saveBuffer(Buff[I], Config->OutputFile + ".lto.o");
218       else
219         saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o");
220     }
221     InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp"));
222     Ret.push_back(Obj);
223   }
224 
225   for (std::unique_ptr<MemoryBuffer> &File : Files)
226     if (File)
227       Ret.push_back(createObjectFile(*File));
228 
229   return Ret;
230 }
231