xref: /llvm-project-15.0.7/lld/ELF/LTO.cpp (revision 2bc3449d)
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 "Error.h"
13 #include "InputFiles.h"
14 #include "Symbols.h"
15 #include "lld/Core/TargetOptionsCommandFlags.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/LTO/Caching.h"
23 #include "llvm/LTO/Config.h"
24 #include "llvm/LTO/LTO.h"
25 #include "llvm/Object/SymbolicFile.h"
26 #include "llvm/Support/CodeGen.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 #include <cstddef>
33 #include <memory>
34 #include <string>
35 #include <system_error>
36 #include <vector>
37 
38 using namespace llvm;
39 using namespace llvm::object;
40 using namespace llvm::ELF;
41 
42 using namespace lld;
43 using namespace lld::elf;
44 
45 // This is for use when debugging LTO.
46 static void saveBuffer(StringRef Buffer, const Twine &Path) {
47   std::error_code EC;
48   raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
49   if (EC)
50     error("cannot create " + Path + ": " + EC.message());
51   OS << Buffer;
52 }
53 
54 static void diagnosticHandler(const DiagnosticInfo &DI) {
55   SmallString<128> ErrStorage;
56   raw_svector_ostream OS(ErrStorage);
57   DiagnosticPrinterRawOStream DP(OS);
58   DI.print(DP);
59   warn(ErrStorage);
60 }
61 
62 static void checkError(Error E) {
63   handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
64     error(EIB.message());
65     return Error::success();
66   });
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   if (Config->Relocatable)
77     Conf.RelocModel = None;
78   else if (Config->Pic)
79     Conf.RelocModel = Reloc::PIC_;
80   else
81     Conf.RelocModel = Reloc::Static;
82   Conf.CodeModel = GetCodeModelFromCMModel();
83   Conf.DisableVerify = Config->DisableVerify;
84   Conf.DiagHandler = diagnosticHandler;
85   Conf.OptLevel = Config->LTOO;
86 
87   // Set up a custom pipeline if we've been asked to.
88   Conf.OptPipeline = Config->LTONewPmPasses;
89   Conf.AAPipeline = Config->LTOAAPipeline;
90 
91   // Set up optimization remarks if we've been asked to.
92   Conf.RemarksFilename = Config->OptRemarksFilename;
93   Conf.RemarksWithHotness = Config->OptRemarksWithHotness;
94 
95   if (Config->SaveTemps)
96     checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".",
97                                  /*UseInputModulePath*/ true));
98 
99   lto::ThinBackend Backend;
100   if (Config->ThinLTOJobs != -1u)
101     Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
102   return llvm::make_unique<lto::LTO>(std::move(Conf), Backend,
103                                      Config->LTOPartitions);
104 }
105 
106 BitcodeCompiler::BitcodeCompiler() : LTOObj(createLTO()) {}
107 
108 BitcodeCompiler::~BitcodeCompiler() = default;
109 
110 static void undefine(Symbol *S) {
111   replaceBody<Undefined>(S, S->body()->getName(), /*IsLocal=*/false,
112                          STV_DEFAULT, S->body()->Type, nullptr);
113 }
114 
115 void BitcodeCompiler::add(BitcodeFile &F) {
116   lto::InputFile &Obj = *F.Obj;
117   unsigned SymNum = 0;
118   std::vector<Symbol *> Syms = F.getSymbols();
119   std::vector<lto::SymbolResolution> Resols(Syms.size());
120 
121   // Provide a resolution to the LTO API for each symbol.
122   for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
123     Symbol *Sym = Syms[SymNum];
124     lto::SymbolResolution &R = Resols[SymNum];
125     ++SymNum;
126     SymbolBody *B = Sym->body();
127 
128     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
129     // reports two symbols for module ASM defined. Without this check, lld
130     // flags an undefined in IR with a definition in ASM as prevailing.
131     // Once IRObjectFile is fixed to report only one symbol this hack can
132     // be removed.
133     R.Prevailing = !ObjSym.isUndefined() && B->File == &F;
134 
135     R.VisibleToRegularObj =
136         Sym->IsUsedInRegularObj || (R.Prevailing && Sym->includeInDynsym());
137     if (R.Prevailing)
138       undefine(Sym);
139     R.LinkerRedefined = Config->RenamedSymbols.count(Sym);
140   }
141   checkError(LTOObj->add(std::move(F.Obj), Resols));
142 }
143 
144 // Merge all the bitcode files we have seen, codegen the result
145 // and return the resulting ObjectFile(s).
146 std::vector<InputFile *> BitcodeCompiler::compile() {
147   std::vector<InputFile *> Ret;
148   unsigned MaxTasks = LTOObj->getMaxTasks();
149   Buff.resize(MaxTasks);
150   Files.resize(MaxTasks);
151 
152   // The --thinlto-cache-dir option specifies the path to a directory in which
153   // to cache native object files for ThinLTO incremental builds. If a path was
154   // specified, configure LTO to use it as the cache directory.
155   lto::NativeObjectCache Cache;
156   if (!Config->ThinLTOCacheDir.empty())
157     Cache = check(
158         lto::localCache(Config->ThinLTOCacheDir,
159                         [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
160                           Files[Task] = std::move(MB);
161                         }));
162 
163   checkError(LTOObj->run(
164       [&](size_t Task) {
165         return llvm::make_unique<lto::NativeObjectStream>(
166             llvm::make_unique<raw_svector_ostream>(Buff[Task]));
167       },
168       Cache));
169 
170   if (!Config->ThinLTOCacheDir.empty())
171     pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
172 
173   for (unsigned I = 0; I != MaxTasks; ++I) {
174     if (Buff[I].empty())
175       continue;
176     if (Config->SaveTemps) {
177       if (I == 0)
178         saveBuffer(Buff[I], Config->OutputFile + ".lto.o");
179       else
180         saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o");
181     }
182     InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp"));
183     Ret.push_back(Obj);
184   }
185 
186   for (std::unique_ptr<MemoryBuffer> &File : Files)
187     if (File)
188       Ret.push_back(createObjectFile(*File));
189 
190   return Ret;
191 }
192