xref: /llvm-project-15.0.7/lld/COFF/LTO.cpp (revision 90e4ebdc)
1 //===- LTO.cpp ------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "LTO.h"
10 #include "Config.h"
11 #include "InputFiles.h"
12 #include "Symbols.h"
13 #include "lld/Common/Args.h"
14 #include "lld/Common/ErrorHandler.h"
15 #include "lld/Common/Strings.h"
16 #include "lld/Common/TargetOptionsCommandFlags.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Bitcode/BitcodeWriter.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/LTO/Caching.h"
24 #include "llvm/LTO/Config.h"
25 #include "llvm/LTO/LTO.h"
26 #include "llvm/Object/SymbolicFile.h"
27 #include "llvm/Support/CodeGen.h"
28 #include "llvm/Support/Error.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <cstddef>
34 #include <memory>
35 #include <string>
36 #include <system_error>
37 #include <vector>
38 
39 using namespace llvm;
40 using namespace llvm::object;
41 
42 namespace lld {
43 namespace coff {
44 
45 // Creates an empty file to and returns a raw_fd_ostream to write to it.
46 static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) {
47   std::error_code ec;
48   auto ret =
49       std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None);
50   if (ec) {
51     error("cannot open " + file + ": " + ec.message());
52     return nullptr;
53   }
54   return ret;
55 }
56 
57 static std::string getThinLTOOutputFile(StringRef path) {
58   return lto::getThinLTOOutputFile(
59       std::string(path), std::string(config->thinLTOPrefixReplace.first),
60       std::string(config->thinLTOPrefixReplace.second));
61 }
62 
63 static lto::Config createConfig() {
64   lto::Config c;
65   c.Options = initTargetOptionsFromCodeGenFlags();
66 
67   // Always emit a section per function/datum with LTO. LLVM LTO should get most
68   // of the benefit of linker GC, but there are still opportunities for ICF.
69   c.Options.FunctionSections = true;
70   c.Options.DataSections = true;
71 
72   // Use static reloc model on 32-bit x86 because it usually results in more
73   // compact code, and because there are also known code generation bugs when
74   // using the PIC model (see PR34306).
75   if (config->machine == COFF::IMAGE_FILE_MACHINE_I386)
76     c.RelocModel = Reloc::Static;
77   else
78     c.RelocModel = Reloc::PIC_;
79   c.DisableVerify = true;
80   c.DiagHandler = diagnosticHandler;
81   c.OptLevel = config->ltoo;
82   c.CPU = getCPUStr();
83   c.MAttrs = getMAttrs();
84   c.CGOptLevel = args::getCGOptLevel(config->ltoo);
85 
86   if (config->saveTemps)
87     checkError(c.addSaveTemps(std::string(config->outputFile) + ".",
88                               /*UseInputModulePath*/ true));
89   return c;
90 }
91 
92 BitcodeCompiler::BitcodeCompiler() {
93   // Initialize indexFile.
94   if (!config->thinLTOIndexOnlyArg.empty())
95     indexFile = openFile(config->thinLTOIndexOnlyArg);
96 
97   // Initialize ltoObj.
98   lto::ThinBackend backend;
99   if (config->thinLTOIndexOnly) {
100     auto OnIndexWrite = [&](StringRef S) { thinIndices.erase(S); };
101     backend = lto::createWriteIndexesThinBackend(
102         std::string(config->thinLTOPrefixReplace.first),
103         std::string(config->thinLTOPrefixReplace.second),
104         config->thinLTOEmitImportsFiles, indexFile.get(), OnIndexWrite);
105   } else if (config->thinLTOJobs != 0) {
106     backend = lto::createInProcessThinBackend(config->thinLTOJobs);
107   }
108 
109   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend,
110                                        config->ltoPartitions);
111 }
112 
113 BitcodeCompiler::~BitcodeCompiler() = default;
114 
115 static void undefine(Symbol *s) { replaceSymbol<Undefined>(s, s->getName()); }
116 
117 void BitcodeCompiler::add(BitcodeFile &f) {
118   lto::InputFile &obj = *f.obj;
119   unsigned symNum = 0;
120   std::vector<Symbol *> symBodies = f.getSymbols();
121   std::vector<lto::SymbolResolution> resols(symBodies.size());
122 
123   if (config->thinLTOIndexOnly)
124     thinIndices.insert(obj.getName());
125 
126   // Provide a resolution to the LTO API for each symbol.
127   for (const lto::InputFile::Symbol &objSym : obj.symbols()) {
128     Symbol *sym = symBodies[symNum];
129     lto::SymbolResolution &r = resols[symNum];
130     ++symNum;
131 
132     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
133     // reports two symbols for module ASM defined. Without this check, lld
134     // flags an undefined in IR with a definition in ASM as prevailing.
135     // Once IRObjectFile is fixed to report only one symbol this hack can
136     // be removed.
137     r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
138     r.VisibleToRegularObj = sym->isUsedInRegularObj;
139     if (r.Prevailing)
140       undefine(sym);
141   }
142   checkError(ltoObj->add(std::move(f.obj), resols));
143 }
144 
145 // Merge all the bitcode files we have seen, codegen the result
146 // and return the resulting objects.
147 std::vector<StringRef> BitcodeCompiler::compile() {
148   unsigned maxTasks = ltoObj->getMaxTasks();
149   buf.resize(maxTasks);
150   files.resize(maxTasks);
151 
152   // The /lldltocache option specifies the path to a directory in which to cache
153   // 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->ltoCache.empty())
157     cache = check(lto::localCache(
158         config->ltoCache, [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
159           files[task] = std::move(mb);
160         }));
161 
162   checkError(ltoObj->run(
163       [&](size_t task) {
164         return std::make_unique<lto::NativeObjectStream>(
165             std::make_unique<raw_svector_ostream>(buf[task]));
166       },
167       cache));
168 
169   // Emit empty index files for non-indexed files
170   for (StringRef s : thinIndices) {
171     std::string path = getThinLTOOutputFile(s);
172     openFile(path + ".thinlto.bc");
173     if (config->thinLTOEmitImportsFiles)
174       openFile(path + ".imports");
175   }
176 
177   // ThinLTO with index only option is required to generate only the index
178   // files. After that, we exit from linker and ThinLTO backend runs in a
179   // distributed environment.
180   if (config->thinLTOIndexOnly) {
181     if (!config->ltoObjPath.empty())
182       saveBuffer(buf[0], config->ltoObjPath);
183     if (indexFile)
184       indexFile->close();
185     return {};
186   }
187 
188   if (!config->ltoCache.empty())
189     pruneCache(config->ltoCache, config->ltoCachePolicy);
190 
191   std::vector<StringRef> ret;
192   for (unsigned i = 0; i != maxTasks; ++i) {
193     if (buf[i].empty())
194       continue;
195     if (config->saveTemps) {
196       if (i == 0)
197         saveBuffer(buf[i], config->outputFile + ".lto.obj");
198       else
199         saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.obj");
200     }
201     ret.emplace_back(buf[i].data(), buf[i].size());
202   }
203 
204   for (std::unique_ptr<MemoryBuffer> &file : files)
205     if (file)
206       ret.push_back(file->getBuffer());
207 
208   return ret;
209 }
210 
211 } // namespace coff
212 } // namespace lld
213