xref: /freebsd/contrib/llvm-project/lld/COFF/LTO.cpp (revision 85868e8a1daeaae7a0e48effb2ea2310ae3b02c6)
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(path,
59                                    config->thinLTOPrefixReplace.first,
60                                    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         config->thinLTOPrefixReplace.first, config->thinLTOPrefixReplace.second,
103         config->thinLTOEmitImportsFiles, indexFile.get(), OnIndexWrite);
104   } else if (config->thinLTOJobs != 0) {
105     backend = lto::createInProcessThinBackend(config->thinLTOJobs);
106   }
107 
108   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend,
109                                        config->ltoPartitions);
110 }
111 
112 BitcodeCompiler::~BitcodeCompiler() = default;
113 
114 static void undefine(Symbol *s) { replaceSymbol<Undefined>(s, s->getName()); }
115 
116 void BitcodeCompiler::add(BitcodeFile &f) {
117   lto::InputFile &obj = *f.obj;
118   unsigned symNum = 0;
119   std::vector<Symbol *> symBodies = f.getSymbols();
120   std::vector<lto::SymbolResolution> resols(symBodies.size());
121 
122   if (config->thinLTOIndexOnly)
123     thinIndices.insert(obj.getName());
124 
125   // Provide a resolution to the LTO API for each symbol.
126   for (const lto::InputFile::Symbol &objSym : obj.symbols()) {
127     Symbol *sym = symBodies[symNum];
128     lto::SymbolResolution &r = resols[symNum];
129     ++symNum;
130 
131     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
132     // reports two symbols for module ASM defined. Without this check, lld
133     // flags an undefined in IR with a definition in ASM as prevailing.
134     // Once IRObjectFile is fixed to report only one symbol this hack can
135     // be removed.
136     r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
137     r.VisibleToRegularObj = sym->isUsedInRegularObj;
138     if (r.Prevailing)
139       undefine(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 objects.
146 std::vector<StringRef> BitcodeCompiler::compile() {
147   unsigned maxTasks = ltoObj->getMaxTasks();
148   buf.resize(maxTasks);
149   files.resize(maxTasks);
150 
151   // The /lldltocache option specifies the path to a directory in which to cache
152   // native object files for ThinLTO incremental builds. If a path was
153   // specified, configure LTO to use it as the cache directory.
154   lto::NativeObjectCache cache;
155   if (!config->ltoCache.empty())
156     cache = check(lto::localCache(
157         config->ltoCache, [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
158           files[task] = std::move(mb);
159         }));
160 
161   checkError(ltoObj->run(
162       [&](size_t task) {
163         return std::make_unique<lto::NativeObjectStream>(
164             std::make_unique<raw_svector_ostream>(buf[task]));
165       },
166       cache));
167 
168   // Emit empty index files for non-indexed files
169   for (StringRef s : thinIndices) {
170     std::string path = getThinLTOOutputFile(s);
171     openFile(path + ".thinlto.bc");
172     if (config->thinLTOEmitImportsFiles)
173       openFile(path + ".imports");
174   }
175 
176   // ThinLTO with index only option is required to generate only the index
177   // files. After that, we exit from linker and ThinLTO backend runs in a
178   // distributed environment.
179   if (config->thinLTOIndexOnly) {
180     if (!config->ltoObjPath.empty())
181       saveBuffer(buf[0], config->ltoObjPath);
182     if (indexFile)
183       indexFile->close();
184     return {};
185   }
186 
187   if (!config->ltoCache.empty())
188     pruneCache(config->ltoCache, config->ltoCachePolicy);
189 
190   std::vector<StringRef> ret;
191   for (unsigned i = 0; i != maxTasks; ++i) {
192     if (buf[i].empty())
193       continue;
194     if (config->saveTemps) {
195       if (i == 0)
196         saveBuffer(buf[i], config->outputFile + ".lto.obj");
197       else
198         saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.obj");
199     }
200     ret.emplace_back(buf[i].data(), buf[i].size());
201   }
202 
203   for (std::unique_ptr<MemoryBuffer> &file : files)
204     if (file)
205       ret.push_back(file->getBuffer());
206 
207   return ret;
208 }
209 
210 } // namespace coff
211 } // namespace lld
212