xref: /llvm-project-15.0.7/lld/COFF/LTO.cpp (revision feefb087)
1 //===- LTO.cpp ------------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "LTO.h"
11 #include "Config.h"
12 #include "Error.h"
13 #include "InputFiles.h"
14 #include "Symbols.h"
15 #include "lld/Common/TargetOptionsCommandFlags.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/LTO/Caching.h"
22 #include "llvm/LTO/Config.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/Object/SymbolicFile.h"
25 #include "llvm/Support/CodeGen.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <cstddef>
32 #include <memory>
33 #include <string>
34 #include <system_error>
35 #include <vector>
36 
37 using namespace llvm;
38 using namespace llvm::object;
39 
40 using namespace lld;
41 using namespace lld::coff;
42 
43 static void diagnosticHandler(const DiagnosticInfo &DI) {
44   SmallString<128> ErrStorage;
45   raw_svector_ostream OS(ErrStorage);
46   DiagnosticPrinterRawOStream DP(OS);
47   DI.print(DP);
48   warn(ErrStorage);
49 }
50 
51 static void checkError(Error E) {
52   handleAllErrors(std::move(E),
53                   [&](ErrorInfoBase &EIB) { error(EIB.message()); });
54 }
55 
56 static void saveBuffer(StringRef Buffer, const Twine &Path) {
57   std::error_code EC;
58   raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
59   if (EC)
60     error("cannot create " + Path + ": " + EC.message());
61   OS << Buffer;
62 }
63 
64 static std::unique_ptr<lto::LTO> createLTO() {
65   lto::Config Conf;
66   Conf.Options = InitTargetOptionsFromCodeGenFlags();
67   Conf.RelocModel = Reloc::PIC_;
68   Conf.DisableVerify = true;
69   Conf.DiagHandler = diagnosticHandler;
70   Conf.OptLevel = Config->LTOOptLevel;
71   if (Config->SaveTemps)
72     checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".",
73                                  /*UseInputModulePath*/ true));
74   lto::ThinBackend Backend;
75   if (Config->LTOJobs != 0)
76     Backend = lto::createInProcessThinBackend(Config->LTOJobs);
77   return llvm::make_unique<lto::LTO>(std::move(Conf), Backend,
78                                      Config->LTOPartitions);
79 }
80 
81 BitcodeCompiler::BitcodeCompiler() : LTOObj(createLTO()) {}
82 
83 BitcodeCompiler::~BitcodeCompiler() = default;
84 
85 static void undefine(Symbol *S) {
86   replaceBody<Undefined>(S, S->body()->getName());
87 }
88 
89 void BitcodeCompiler::add(BitcodeFile &F) {
90   lto::InputFile &Obj = *F.Obj;
91   unsigned SymNum = 0;
92   std::vector<SymbolBody *> SymBodies = F.getSymbols();
93   std::vector<lto::SymbolResolution> Resols(SymBodies.size());
94 
95   // Provide a resolution to the LTO API for each symbol.
96   for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
97     SymbolBody *B = SymBodies[SymNum];
98     Symbol *Sym = B->symbol();
99     lto::SymbolResolution &R = Resols[SymNum];
100     ++SymNum;
101 
102     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
103     // reports two symbols for module ASM defined. Without this check, lld
104     // flags an undefined in IR with a definition in ASM as prevailing.
105     // Once IRObjectFile is fixed to report only one symbol this hack can
106     // be removed.
107     R.Prevailing = !ObjSym.isUndefined() && B->getFile() == &F;
108     R.VisibleToRegularObj = Sym->IsUsedInRegularObj;
109     if (R.Prevailing)
110       undefine(Sym);
111   }
112   checkError(LTOObj->add(std::move(F.Obj), Resols));
113 }
114 
115 // Merge all the bitcode files we have seen, codegen the result
116 // and return the resulting objects.
117 std::vector<StringRef> BitcodeCompiler::compile() {
118   unsigned MaxTasks = LTOObj->getMaxTasks();
119   Buff.resize(MaxTasks);
120   Files.resize(MaxTasks);
121 
122   // The /lldltocache option specifies the path to a directory in which to cache
123   // native object files for ThinLTO incremental builds. If a path was
124   // specified, configure LTO to use it as the cache directory.
125   lto::NativeObjectCache Cache;
126   if (!Config->LTOCache.empty())
127     Cache = check(
128         lto::localCache(Config->LTOCache,
129                         [&](size_t Task, std::unique_ptr<MemoryBuffer> MB,
130                             StringRef Path) { Files[Task] = std::move(MB); }));
131 
132   checkError(LTOObj->run(
133       [&](size_t Task) {
134         return llvm::make_unique<lto::NativeObjectStream>(
135             llvm::make_unique<raw_svector_ostream>(Buff[Task]));
136       },
137       Cache));
138 
139   if (!Config->LTOCache.empty())
140     pruneCache(Config->LTOCache, Config->LTOCachePolicy);
141 
142   std::vector<StringRef> Ret;
143   for (unsigned I = 0; I != MaxTasks; ++I) {
144     if (Buff[I].empty())
145       continue;
146     if (Config->SaveTemps) {
147       if (I == 0)
148         saveBuffer(Buff[I], Config->OutputFile + ".lto.obj");
149       else
150         saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.obj");
151     }
152     Ret.emplace_back(Buff[I].data(), Buff[I].size());
153   }
154 
155   for (std::unique_ptr<MemoryBuffer> &File : Files)
156     if (File)
157       Ret.push_back(File->getBuffer());
158 
159   return Ret;
160 }
161