xref: /openbsd-src/gnu/llvm/lld/wasm/LTO.cpp (revision 4e1ee0786f11cc571bd0be17d38e46f635c719fc)
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/IR/DiagnosticPrinter.h"
22 #include "llvm/LTO/Caching.h"
23 #include "llvm/LTO/Config.h"
24 #include "llvm/LTO/LTO.h"
25 #include "llvm/Object/SymbolicFile.h"
26 #include "llvm/Support/CodeGen.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 #include <cstddef>
33 #include <memory>
34 #include <string>
35 #include <system_error>
36 #include <vector>
37 
38 using namespace llvm;
39 
40 namespace lld {
41 namespace wasm {
42 static std::unique_ptr<lto::LTO> createLTO() {
43   lto::Config c;
44   c.Options = initTargetOptionsFromCodeGenFlags();
45 
46   // Always emit a section per function/data with LTO.
47   c.Options.FunctionSections = true;
48   c.Options.DataSections = true;
49 
50   c.DisableVerify = config->disableVerify;
51   c.DiagHandler = diagnosticHandler;
52   c.OptLevel = config->ltoo;
53   c.MAttrs = getMAttrs();
54   c.CGOptLevel = args::getCGOptLevel(config->ltoo);
55 
56   if (config->relocatable)
57     c.RelocModel = None;
58   else if (config->isPic)
59     c.RelocModel = Reloc::PIC_;
60   else
61     c.RelocModel = Reloc::Static;
62 
63   if (config->saveTemps)
64     checkError(c.addSaveTemps(config->outputFile.str() + ".",
65                               /*UseInputModulePath*/ true));
66   lto::ThinBackend backend = lto::createInProcessThinBackend(
67       llvm::heavyweight_hardware_concurrency(config->thinLTOJobs));
68   return std::make_unique<lto::LTO>(std::move(c), backend,
69                                      config->ltoPartitions);
70 }
71 
72 BitcodeCompiler::BitcodeCompiler() : ltoObj(createLTO()) {}
73 
74 BitcodeCompiler::~BitcodeCompiler() = default;
75 
76 static void undefine(Symbol *s) {
77   if (auto f = dyn_cast<DefinedFunction>(s))
78     replaceSymbol<UndefinedFunction>(f, f->getName(), None, None, 0,
79                                      f->getFile(), f->signature);
80   else if (isa<DefinedData>(s))
81     replaceSymbol<UndefinedData>(s, s->getName(), 0, s->getFile());
82   else
83     llvm_unreachable("unexpected symbol kind");
84 }
85 
86 void BitcodeCompiler::add(BitcodeFile &f) {
87   lto::InputFile &obj = *f.obj;
88   unsigned symNum = 0;
89   ArrayRef<Symbol *> syms = f.getSymbols();
90   std::vector<lto::SymbolResolution> resols(syms.size());
91 
92   // Provide a resolution to the LTO API for each symbol.
93   for (const lto::InputFile::Symbol &objSym : obj.symbols()) {
94     Symbol *sym = syms[symNum];
95     lto::SymbolResolution &r = resols[symNum];
96     ++symNum;
97 
98     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
99     // reports two symbols for module ASM defined. Without this check, lld
100     // flags an undefined in IR with a definition in ASM as prevailing.
101     // Once IRObjectFile is fixed to report only one symbol this hack can
102     // be removed.
103     r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
104     r.VisibleToRegularObj = config->relocatable || sym->isUsedInRegularObj ||
105                             sym->isNoStrip() ||
106                             (r.Prevailing && sym->isExported());
107     if (r.Prevailing)
108       undefine(sym);
109 
110     // We tell LTO to not apply interprocedural optimization for wrapped
111     // (with --wrap) symbols because otherwise LTO would inline them while
112     // their values are still not final.
113     r.LinkerRedefined = !sym->canInline;
114   }
115   checkError(ltoObj->add(std::move(f.obj), resols));
116 }
117 
118 // Merge all the bitcode files we have seen, codegen the result
119 // and return the resulting objects.
120 std::vector<StringRef> BitcodeCompiler::compile() {
121   unsigned maxTasks = ltoObj->getMaxTasks();
122   buf.resize(maxTasks);
123   files.resize(maxTasks);
124 
125   // The --thinlto-cache-dir option specifies the path to a directory in which
126   // to cache native object files for ThinLTO incremental builds. If a path was
127   // specified, configure LTO to use it as the cache directory.
128   lto::NativeObjectCache cache;
129   if (!config->thinLTOCacheDir.empty())
130     cache = check(
131         lto::localCache(config->thinLTOCacheDir,
132                         [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
133                           files[task] = std::move(mb);
134                         }));
135 
136   checkError(ltoObj->run(
137       [&](size_t task) {
138         return std::make_unique<lto::NativeObjectStream>(
139             std::make_unique<raw_svector_ostream>(buf[task]));
140       },
141       cache));
142 
143   if (!config->thinLTOCacheDir.empty())
144     pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy);
145 
146   std::vector<StringRef> ret;
147   for (unsigned i = 0; i != maxTasks; ++i) {
148     if (buf[i].empty())
149       continue;
150     if (config->saveTemps) {
151       if (i == 0)
152         saveBuffer(buf[i], config->outputFile + ".lto.o");
153       else
154         saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o");
155     }
156     ret.emplace_back(buf[i].data(), buf[i].size());
157   }
158 
159   for (std::unique_ptr<MemoryBuffer> &file : files)
160     if (file)
161       ret.push_back(file->getBuffer());
162 
163   return ret;
164 }
165 
166 } // namespace wasm
167 } // namespace lld
168