1 //===- LTO.cpp ------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
11 #include "InputFiles.h"
12 #include "LinkerScript.h"
13 #include "SymbolTable.h"
15 #include "lld/Common/Args.h"
16 #include "lld/Common/ErrorHandler.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/BinaryFormat/ELF.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/BitcodeWriter.h"
25 #include "llvm/IR/DiagnosticPrinter.h"
26 #include "llvm/LTO/Caching.h"
27 #include "llvm/LTO/Config.h"
28 #include "llvm/LTO/LTO.h"
29 #include "llvm/Object/SymbolicFile.h"
30 #include "llvm/Support/CodeGen.h"
31 #include "llvm/Support/Error.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
38 #include <system_error>
42 using namespace llvm::object;
43 using namespace llvm::ELF;
46 using namespace lld::elf;
48 // Creates an empty file to store a list of object files for final
49 // linking of distributed ThinLTO.
50 static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) {
53 llvm::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::F_None);
55 error("cannot open " + file + ": " + ec.message());
61 static std::string getThinLTOOutputFile(StringRef modulePath) {
62 return lto::getThinLTOOutputFile(modulePath,
63 config->thinLTOPrefixReplace.first,
64 config->thinLTOPrefixReplace.second);
67 static lto::Config createConfig() {
70 // LLD supports the new relocations and address-significance tables.
71 c.Options = initTargetOptionsFromCodeGenFlags();
72 c.Options.RelaxELFRelocations = true;
73 c.Options.EmitAddrsig = true;
75 // Always emit a section per function/datum with LTO.
76 c.Options.FunctionSections = true;
77 c.Options.DataSections = true;
79 if (config->relocatable)
81 else if (config->isPic)
82 c.RelocModel = Reloc::PIC_;
84 c.RelocModel = Reloc::Static;
86 c.CodeModel = getCodeModelFromCMModel();
87 c.DisableVerify = config->disableVerify;
88 c.DiagHandler = diagnosticHandler;
89 c.OptLevel = config->ltoo;
91 c.MAttrs = getMAttrs();
92 c.CGOptLevel = args::getCGOptLevel(config->ltoo);
94 // Set up a custom pipeline if we've been asked to.
95 c.OptPipeline = config->ltoNewPmPasses;
96 c.AAPipeline = config->ltoAAPipeline;
98 // Set up optimization remarks if we've been asked to.
99 c.RemarksFilename = config->optRemarksFilename;
100 c.RemarksPasses = config->optRemarksPasses;
101 c.RemarksWithHotness = config->optRemarksWithHotness;
102 c.RemarksFormat = config->optRemarksFormat;
104 c.SampleProfile = config->ltoSampleProfile;
105 c.UseNewPM = config->ltoNewPassManager;
106 c.DebugPassManager = config->ltoDebugPassManager;
107 c.DwoDir = config->dwoDir;
109 c.CSIRProfile = config->ltoCSProfileFile;
110 c.RunCSIRInstr = config->ltoCSProfileGenerate;
112 if (config->emitLLVM) {
113 c.PostInternalizeModuleHook = [](size_t task, const Module &m) {
114 if (std::unique_ptr<raw_fd_ostream> os = openFile(config->outputFile))
115 WriteBitcodeToFile(m, *os, false);
120 if (config->saveTemps)
121 checkError(c.addSaveTemps(config->outputFile.str() + ".",
122 /*UseInputModulePath*/ true));
126 BitcodeCompiler::BitcodeCompiler() {
127 // Initialize indexFile.
128 if (!config->thinLTOIndexOnlyArg.empty())
129 indexFile = openFile(config->thinLTOIndexOnlyArg);
131 // Initialize ltoObj.
132 lto::ThinBackend backend;
133 if (config->thinLTOIndexOnly) {
134 auto onIndexWrite = [&](StringRef s) { thinIndices.erase(s); };
135 backend = lto::createWriteIndexesThinBackend(
136 config->thinLTOPrefixReplace.first, config->thinLTOPrefixReplace.second,
137 config->thinLTOEmitImportsFiles, indexFile.get(), onIndexWrite);
138 } else if (config->thinLTOJobs != -1U) {
139 backend = lto::createInProcessThinBackend(config->thinLTOJobs);
142 ltoObj = llvm::make_unique<lto::LTO>(createConfig(), backend,
143 config->ltoPartitions);
145 // Initialize usedStartStop.
146 symtab->forEachSymbol([&](Symbol *sym) {
147 StringRef s = sym->getName();
148 for (StringRef prefix : {"__start_", "__stop_"})
149 if (s.startswith(prefix))
150 usedStartStop.insert(s.substr(prefix.size()));
154 BitcodeCompiler::~BitcodeCompiler() = default;
156 void BitcodeCompiler::add(BitcodeFile &f) {
157 lto::InputFile &obj = *f.obj;
158 bool isExec = !config->shared && !config->relocatable;
160 if (config->thinLTOIndexOnly)
161 thinIndices.insert(obj.getName());
163 ArrayRef<Symbol *> syms = f.getSymbols();
164 ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols();
165 std::vector<lto::SymbolResolution> resols(syms.size());
167 // Provide a resolution to the LTO API for each symbol.
168 for (size_t i = 0, e = syms.size(); i != e; ++i) {
169 Symbol *sym = syms[i];
170 const lto::InputFile::Symbol &objSym = objSyms[i];
171 lto::SymbolResolution &r = resols[i];
173 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
174 // reports two symbols for module ASM defined. Without this check, lld
175 // flags an undefined in IR with a definition in ASM as prevailing.
176 // Once IRObjectFile is fixed to report only one symbol this hack can
178 r.Prevailing = !objSym.isUndefined() && sym->file == &f;
180 // We ask LTO to preserve following global symbols:
181 // 1) All symbols when doing relocatable link, so that them can be used
182 // for doing final link.
183 // 2) Symbols that are used in regular objects.
184 // 3) C named sections if we have corresponding __start_/__stop_ symbol.
185 // 4) Symbols that are defined in bitcode files and used for dynamic linking.
186 r.VisibleToRegularObj = config->relocatable || sym->isUsedInRegularObj ||
187 (r.Prevailing && sym->includeInDynsym()) ||
188 usedStartStop.count(objSym.getSectionName());
189 const auto *dr = dyn_cast<Defined>(sym);
190 r.FinalDefinitionInLinkageUnit =
191 (isExec || sym->visibility != STV_DEFAULT) && dr &&
192 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
193 // will be generated by for them, triggering linker errors.
194 // Symbol section is always null for bitcode symbols, hence the check
195 // for isElf(). Skip linker script defined symbols as well: they have
197 !(dr->section == nullptr && (!sym->file || sym->file->isElf()));
200 sym->replace(Undefined{nullptr, sym->getName(), STB_GLOBAL, STV_DEFAULT,
203 // We tell LTO to not apply interprocedural optimization for wrapped
204 // (with --wrap) symbols because otherwise LTO would inline them while
205 // their values are still not final.
206 r.LinkerRedefined = !sym->canInline;
208 checkError(ltoObj->add(std::move(f.obj), resols));
211 // If LazyObjFile has not been added to link, emit empty index files.
212 // This is needed because this is what GNU gold plugin does and we have a
213 // distributed build system that depends on that behavior.
214 static void thinLTOCreateEmptyIndexFiles() {
215 for (LazyObjFile *f : lazyObjFiles) {
216 if (!isBitcode(f->mb))
218 std::string path = replaceThinLTOSuffix(getThinLTOOutputFile(f->getName()));
219 std::unique_ptr<raw_fd_ostream> os = openFile(path + ".thinlto.bc");
223 ModuleSummaryIndex m(/*HaveGVs*/ false);
224 m.setSkipModuleByDistributedBackend();
225 WriteIndexToFile(m, *os);
226 if (config->thinLTOEmitImportsFiles)
227 openFile(path + ".imports");
231 // Merge all the bitcode files we have seen, codegen the result
232 // and return the resulting ObjectFile(s).
233 std::vector<InputFile *> BitcodeCompiler::compile() {
234 unsigned maxTasks = ltoObj->getMaxTasks();
235 buf.resize(maxTasks);
236 files.resize(maxTasks);
238 // The --thinlto-cache-dir option specifies the path to a directory in which
239 // to cache native object files for ThinLTO incremental builds. If a path was
240 // specified, configure LTO to use it as the cache directory.
241 lto::NativeObjectCache cache;
242 if (!config->thinLTOCacheDir.empty())
244 lto::localCache(config->thinLTOCacheDir,
245 [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
246 files[task] = std::move(mb);
249 if (!bitcodeFiles.empty())
250 checkError(ltoObj->run(
252 return llvm::make_unique<lto::NativeObjectStream>(
253 llvm::make_unique<raw_svector_ostream>(buf[task]));
257 // Emit empty index files for non-indexed files
258 for (StringRef s : thinIndices) {
259 std::string path = getThinLTOOutputFile(s);
260 openFile(path + ".thinlto.bc");
261 if (config->thinLTOEmitImportsFiles)
262 openFile(path + ".imports");
265 if (config->thinLTOIndexOnly) {
266 thinLTOCreateEmptyIndexFiles();
268 if (!config->ltoObjPath.empty())
269 saveBuffer(buf[0], config->ltoObjPath);
271 // ThinLTO with index only option is required to generate only the index
272 // files. After that, we exit from linker and ThinLTO backend runs in a
273 // distributed environment.
279 if (!config->thinLTOCacheDir.empty())
280 pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy);
282 if (!config->ltoObjPath.empty()) {
283 saveBuffer(buf[0], config->ltoObjPath);
284 for (unsigned i = 1; i != maxTasks; ++i)
285 saveBuffer(buf[i], config->ltoObjPath + Twine(i));
288 if (config->saveTemps) {
289 saveBuffer(buf[0], config->outputFile + ".lto.o");
290 for (unsigned i = 1; i != maxTasks; ++i)
291 saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o");
294 std::vector<InputFile *> ret;
295 for (unsigned i = 0; i != maxTasks; ++i)
297 ret.push_back(createObjectFile(MemoryBufferRef(buf[i], "lto.tmp")));
299 for (std::unique_ptr<MemoryBuffer> &file : files)
301 ret.push_back(createObjectFile(*file));