xref: /openbsd/gnu/llvm/lld/COFF/LTO.cpp (revision dfe94b16)
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 "COFFLinkerContext.h"
11 #include "Config.h"
12 #include "InputFiles.h"
13 #include "Symbols.h"
14 #include "lld/Common/Args.h"
15 #include "lld/Common/CommonLinkerContext.h"
16 #include "lld/Common/Strings.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/Bitcode/BitcodeWriter.h"
23 #include "llvm/IR/DiagnosticPrinter.h"
24 #include "llvm/LTO/Config.h"
25 #include "llvm/LTO/LTO.h"
26 #include "llvm/Object/SymbolicFile.h"
27 #include "llvm/Support/Caching.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 lld;
43 using namespace lld::coff;
44 
45 // Creates an empty file to and returns a raw_fd_ostream to write to it.
openFile(StringRef file)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 
getThinLTOOutputFile(StringRef path)57 std::string BitcodeCompiler::getThinLTOOutputFile(StringRef path) {
58   return lto::getThinLTOOutputFile(
59       std::string(path), std::string(ctx.config.thinLTOPrefixReplace.first),
60       std::string(ctx.config.thinLTOPrefixReplace.second));
61 }
62 
createConfig()63 lto::Config BitcodeCompiler::createConfig() {
64   lto::Config c;
65   c.Options = initTargetOptionsFromCodeGenFlags();
66   c.Options.EmitAddrsig = true;
67   for (StringRef C : ctx.config.mllvmOpts)
68     c.MllvmArgs.emplace_back(C.str());
69 
70   // Always emit a section per function/datum with LTO. LLVM LTO should get most
71   // of the benefit of linker GC, but there are still opportunities for ICF.
72   c.Options.FunctionSections = true;
73   c.Options.DataSections = true;
74 
75   // Use static reloc model on 32-bit x86 because it usually results in more
76   // compact code, and because there are also known code generation bugs when
77   // using the PIC model (see PR34306).
78   if (ctx.config.machine == COFF::IMAGE_FILE_MACHINE_I386)
79     c.RelocModel = Reloc::Static;
80   else
81     c.RelocModel = Reloc::PIC_;
82 #ifndef NDEBUG
83   c.DisableVerify = false;
84 #else
85   c.DisableVerify = true;
86 #endif
87   c.DiagHandler = diagnosticHandler;
88   c.OptLevel = ctx.config.ltoo;
89   c.CPU = getCPUStr();
90   c.MAttrs = getMAttrs();
91   c.CGOptLevel = args::getCGOptLevel(ctx.config.ltoo);
92   c.AlwaysEmitRegularLTOObj = !ctx.config.ltoObjPath.empty();
93   c.DebugPassManager = ctx.config.ltoDebugPassManager;
94   c.CSIRProfile = std::string(ctx.config.ltoCSProfileFile);
95   c.RunCSIRInstr = ctx.config.ltoCSProfileGenerate;
96   c.PGOWarnMismatch = ctx.config.ltoPGOWarnMismatch;
97 
98   if (ctx.config.saveTemps)
99     checkError(c.addSaveTemps(std::string(ctx.config.outputFile) + ".",
100                               /*UseInputModulePath*/ true));
101   return c;
102 }
103 
BitcodeCompiler(COFFLinkerContext & c)104 BitcodeCompiler::BitcodeCompiler(COFFLinkerContext &c) : ctx(c) {
105   // Initialize indexFile.
106   if (!ctx.config.thinLTOIndexOnlyArg.empty())
107     indexFile = openFile(ctx.config.thinLTOIndexOnlyArg);
108 
109   // Initialize ltoObj.
110   lto::ThinBackend backend;
111   if (ctx.config.thinLTOIndexOnly) {
112     auto OnIndexWrite = [&](StringRef S) { thinIndices.erase(S); };
113     backend = lto::createWriteIndexesThinBackend(
114         std::string(ctx.config.thinLTOPrefixReplace.first),
115         std::string(ctx.config.thinLTOPrefixReplace.second),
116         ctx.config.thinLTOEmitImportsFiles, indexFile.get(), OnIndexWrite);
117   } else {
118     backend = lto::createInProcessThinBackend(
119         llvm::heavyweight_hardware_concurrency(ctx.config.thinLTOJobs));
120   }
121 
122   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend,
123                                       ctx.config.ltoPartitions);
124 }
125 
126 BitcodeCompiler::~BitcodeCompiler() = default;
127 
undefine(Symbol * s)128 static void undefine(Symbol *s) { replaceSymbol<Undefined>(s, s->getName()); }
129 
add(BitcodeFile & f)130 void BitcodeCompiler::add(BitcodeFile &f) {
131   lto::InputFile &obj = *f.obj;
132   unsigned symNum = 0;
133   std::vector<Symbol *> symBodies = f.getSymbols();
134   std::vector<lto::SymbolResolution> resols(symBodies.size());
135 
136   if (ctx.config.thinLTOIndexOnly)
137     thinIndices.insert(obj.getName());
138 
139   // Provide a resolution to the LTO API for each symbol.
140   for (const lto::InputFile::Symbol &objSym : obj.symbols()) {
141     Symbol *sym = symBodies[symNum];
142     lto::SymbolResolution &r = resols[symNum];
143     ++symNum;
144 
145     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
146     // reports two symbols for module ASM defined. Without this check, lld
147     // flags an undefined in IR with a definition in ASM as prevailing.
148     // Once IRObjectFile is fixed to report only one symbol this hack can
149     // be removed.
150     r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
151     r.VisibleToRegularObj = sym->isUsedInRegularObj;
152     if (r.Prevailing)
153       undefine(sym);
154 
155     // We tell LTO to not apply interprocedural optimization for wrapped
156     // (with -wrap) symbols because otherwise LTO would inline them while
157     // their values are still not final.
158     r.LinkerRedefined = !sym->canInline;
159   }
160   checkError(ltoObj->add(std::move(f.obj), resols));
161 }
162 
163 // Merge all the bitcode files we have seen, codegen the result
164 // and return the resulting objects.
compile()165 std::vector<InputFile *> BitcodeCompiler::compile() {
166   unsigned maxTasks = ltoObj->getMaxTasks();
167   buf.resize(maxTasks);
168   files.resize(maxTasks);
169   file_names.resize(maxTasks);
170 
171   // The /lldltocache option specifies the path to a directory in which to cache
172   // native object files for ThinLTO incremental builds. If a path was
173   // specified, configure LTO to use it as the cache directory.
174   FileCache cache;
175   if (!ctx.config.ltoCache.empty())
176     cache = check(localCache("ThinLTO", "Thin", ctx.config.ltoCache,
177                              [&](size_t task, const Twine &moduleName,
178                                  std::unique_ptr<MemoryBuffer> mb) {
179                                files[task] = std::move(mb);
180                                file_names[task] = moduleName.str();
181                              }));
182 
183   checkError(ltoObj->run(
184       [&](size_t task, const Twine &moduleName) {
185         buf[task].first = moduleName.str();
186         return std::make_unique<CachedFileStream>(
187             std::make_unique<raw_svector_ostream>(buf[task].second));
188       },
189       cache));
190 
191   // Emit empty index files for non-indexed files
192   for (StringRef s : thinIndices) {
193     std::string path = getThinLTOOutputFile(s);
194     openFile(path + ".thinlto.bc");
195     if (ctx.config.thinLTOEmitImportsFiles)
196       openFile(path + ".imports");
197   }
198 
199   // ThinLTO with index only option is required to generate only the index
200   // files. After that, we exit from linker and ThinLTO backend runs in a
201   // distributed environment.
202   if (ctx.config.thinLTOIndexOnly) {
203     if (!ctx.config.ltoObjPath.empty())
204       saveBuffer(buf[0].second, ctx.config.ltoObjPath);
205     if (indexFile)
206       indexFile->close();
207     return {};
208   }
209 
210   if (!ctx.config.ltoCache.empty())
211     pruneCache(ctx.config.ltoCache, ctx.config.ltoCachePolicy, files);
212 
213   std::vector<InputFile *> ret;
214   for (unsigned i = 0; i != maxTasks; ++i) {
215     StringRef bitcodeFilePath;
216     // Get the native object contents either from the cache or from memory.  Do
217     // not use the cached MemoryBuffer directly, or the PDB will not be
218     // deterministic.
219     StringRef objBuf;
220     if (files[i]) {
221       objBuf = files[i]->getBuffer();
222       bitcodeFilePath = file_names[i];
223     } else {
224       objBuf = buf[i].second;
225       bitcodeFilePath = buf[i].first;
226     }
227     if (objBuf.empty())
228       continue;
229 
230     // If the input bitcode file is path/to/a.obj, then the corresponding lto
231     // object file name will look something like: path/to/main.exe.lto.a.obj.
232     StringRef ltoObjName;
233     if (bitcodeFilePath == "ld-temp.o") {
234       ltoObjName =
235           saver().save(Twine(ctx.config.outputFile) + ".lto" +
236                        (i == 0 ? Twine("") : Twine('.') + Twine(i)) + ".obj");
237     } else {
238       StringRef directory = sys::path::parent_path(bitcodeFilePath);
239       StringRef baseName = sys::path::filename(bitcodeFilePath);
240       StringRef outputFileBaseName = sys::path::filename(ctx.config.outputFile);
241       SmallString<64> path;
242       sys::path::append(path, directory,
243                         outputFileBaseName + ".lto." + baseName);
244       sys::path::remove_dots(path, true);
245       ltoObjName = saver().save(path.str());
246     }
247     if (ctx.config.saveTemps)
248       saveBuffer(buf[i].second, ltoObjName);
249     ret.push_back(make<ObjFile>(ctx, MemoryBufferRef(objBuf, ltoObjName)));
250   }
251 
252   return ret;
253 }
254