xref: /freebsd/contrib/llvm-project/lld/COFF/LTO.cpp (revision af23369a6deaaeb612ab266eb88b8bb8d560c322)
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/CommonLinkerContext.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/Config.h"
24 #include "llvm/LTO/LTO.h"
25 #include "llvm/Object/SymbolicFile.h"
26 #include "llvm/Support/Caching.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 using namespace lld;
42 using namespace lld::coff;
43 
44 // Creates an empty file to and returns a raw_fd_ostream to write to it.
45 static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) {
46   std::error_code ec;
47   auto ret =
48       std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None);
49   if (ec) {
50     error("cannot open " + file + ": " + ec.message());
51     return nullptr;
52   }
53   return ret;
54 }
55 
56 static std::string getThinLTOOutputFile(StringRef path) {
57   return lto::getThinLTOOutputFile(
58       std::string(path), std::string(config->thinLTOPrefixReplace.first),
59       std::string(config->thinLTOPrefixReplace.second));
60 }
61 
62 static lto::Config createConfig() {
63   lto::Config c;
64   c.Options = initTargetOptionsFromCodeGenFlags();
65   c.Options.EmitAddrsig = true;
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   c.AlwaysEmitRegularLTOObj = !config->ltoObjPath.empty();
86   c.DebugPassManager = config->ltoDebugPassManager;
87   c.CSIRProfile = std::string(config->ltoCSProfileFile);
88   c.RunCSIRInstr = config->ltoCSProfileGenerate;
89   c.PGOWarnMismatch = config->ltoPGOWarnMismatch;
90 
91   if (config->saveTemps)
92     checkError(c.addSaveTemps(std::string(config->outputFile) + ".",
93                               /*UseInputModulePath*/ true));
94   return c;
95 }
96 
97 BitcodeCompiler::BitcodeCompiler() {
98   // Initialize indexFile.
99   if (!config->thinLTOIndexOnlyArg.empty())
100     indexFile = openFile(config->thinLTOIndexOnlyArg);
101 
102   // Initialize ltoObj.
103   lto::ThinBackend backend;
104   if (config->thinLTOIndexOnly) {
105     auto OnIndexWrite = [&](StringRef S) { thinIndices.erase(S); };
106     backend = lto::createWriteIndexesThinBackend(
107         std::string(config->thinLTOPrefixReplace.first),
108         std::string(config->thinLTOPrefixReplace.second),
109         config->thinLTOEmitImportsFiles, indexFile.get(), OnIndexWrite);
110   } else {
111     backend = lto::createInProcessThinBackend(
112         llvm::heavyweight_hardware_concurrency(config->thinLTOJobs));
113   }
114 
115   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend,
116                                        config->ltoPartitions);
117 }
118 
119 BitcodeCompiler::~BitcodeCompiler() = default;
120 
121 static void undefine(Symbol *s) { replaceSymbol<Undefined>(s, s->getName()); }
122 
123 void BitcodeCompiler::add(BitcodeFile &f) {
124   lto::InputFile &obj = *f.obj;
125   unsigned symNum = 0;
126   std::vector<Symbol *> symBodies = f.getSymbols();
127   std::vector<lto::SymbolResolution> resols(symBodies.size());
128 
129   if (config->thinLTOIndexOnly)
130     thinIndices.insert(obj.getName());
131 
132   // Provide a resolution to the LTO API for each symbol.
133   for (const lto::InputFile::Symbol &objSym : obj.symbols()) {
134     Symbol *sym = symBodies[symNum];
135     lto::SymbolResolution &r = resols[symNum];
136     ++symNum;
137 
138     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
139     // reports two symbols for module ASM defined. Without this check, lld
140     // flags an undefined in IR with a definition in ASM as prevailing.
141     // Once IRObjectFile is fixed to report only one symbol this hack can
142     // be removed.
143     r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
144     r.VisibleToRegularObj = sym->isUsedInRegularObj;
145     if (r.Prevailing)
146       undefine(sym);
147 
148     // We tell LTO to not apply interprocedural optimization for wrapped
149     // (with -wrap) symbols because otherwise LTO would inline them while
150     // their values are still not final.
151     r.LinkerRedefined = !sym->canInline;
152   }
153   checkError(ltoObj->add(std::move(f.obj), resols));
154 }
155 
156 // Merge all the bitcode files we have seen, codegen the result
157 // and return the resulting objects.
158 std::vector<InputFile *> BitcodeCompiler::compile(COFFLinkerContext &ctx) {
159   unsigned maxTasks = ltoObj->getMaxTasks();
160   buf.resize(maxTasks);
161   files.resize(maxTasks);
162 
163   // The /lldltocache option specifies the path to a directory in which to cache
164   // native object files for ThinLTO incremental builds. If a path was
165   // specified, configure LTO to use it as the cache directory.
166   FileCache cache;
167   if (!config->ltoCache.empty())
168     cache =
169         check(localCache("ThinLTO", "Thin", config->ltoCache,
170                          [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
171                            files[task] = std::move(mb);
172                          }));
173 
174   checkError(ltoObj->run(
175       [&](size_t task) {
176         return std::make_unique<CachedFileStream>(
177             std::make_unique<raw_svector_ostream>(buf[task]));
178       },
179       cache));
180 
181   // Emit empty index files for non-indexed files
182   for (StringRef s : thinIndices) {
183     std::string path = getThinLTOOutputFile(s);
184     openFile(path + ".thinlto.bc");
185     if (config->thinLTOEmitImportsFiles)
186       openFile(path + ".imports");
187   }
188 
189   // ThinLTO with index only option is required to generate only the index
190   // files. After that, we exit from linker and ThinLTO backend runs in a
191   // distributed environment.
192   if (config->thinLTOIndexOnly) {
193     if (!config->ltoObjPath.empty())
194       saveBuffer(buf[0], config->ltoObjPath);
195     if (indexFile)
196       indexFile->close();
197     return {};
198   }
199 
200   if (!config->ltoCache.empty())
201     pruneCache(config->ltoCache, config->ltoCachePolicy);
202 
203   std::vector<InputFile *> ret;
204   for (unsigned i = 0; i != maxTasks; ++i) {
205     // Assign unique names to LTO objects. This ensures they have unique names
206     // in the PDB if one is produced. The names should look like:
207     // - foo.exe.lto.obj
208     // - foo.exe.lto.1.obj
209     // - ...
210     StringRef ltoObjName =
211         saver().save(Twine(config->outputFile) + ".lto" +
212                      (i == 0 ? Twine("") : Twine('.') + Twine(i)) + ".obj");
213 
214     // Get the native object contents either from the cache or from memory.  Do
215     // not use the cached MemoryBuffer directly, or the PDB will not be
216     // deterministic.
217     StringRef objBuf;
218     if (files[i])
219       objBuf = files[i]->getBuffer();
220     else
221       objBuf = buf[i];
222     if (objBuf.empty())
223       continue;
224 
225     if (config->saveTemps)
226       saveBuffer(buf[i], ltoObjName);
227     ret.push_back(make<ObjFile>(ctx, MemoryBufferRef(objBuf, ltoObjName)));
228   }
229 
230   return ret;
231 }
232