xref: /freebsd/contrib/llvm-project/lld/MachO/LTO.cpp (revision bdd1243d)
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 "Driver.h"
12 #include "InputFiles.h"
13 #include "Symbols.h"
14 #include "Target.h"
15 
16 #include "lld/Common/Args.h"
17 #include "lld/Common/CommonLinkerContext.h"
18 #include "lld/Common/Strings.h"
19 #include "lld/Common/TargetOptionsCommandFlags.h"
20 #include "llvm/Bitcode/BitcodeWriter.h"
21 #include "llvm/LTO/Config.h"
22 #include "llvm/LTO/LTO.h"
23 #include "llvm/Support/Caching.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/ObjCARC.h"
28 
29 using namespace lld;
30 using namespace lld::macho;
31 using namespace llvm;
32 using namespace llvm::MachO;
33 using namespace llvm::sys;
34 
35 // Creates an empty file to store a list of object files for final
36 // linking of distributed ThinLTO.
37 static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) {
38   std::error_code ec;
39   auto ret =
40       std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None);
41   if (ec) {
42     error("cannot open " + file + ": " + ec.message());
43     return nullptr;
44   }
45   return ret;
46 }
47 
48 static std::string getThinLTOOutputFile(StringRef modulePath) {
49   return lto::getThinLTOOutputFile(
50       std::string(modulePath), std::string(config->thinLTOPrefixReplace.first),
51       std::string(config->thinLTOPrefixReplace.second));
52 }
53 
54 static lto::Config createConfig() {
55   lto::Config c;
56   c.Options = initTargetOptionsFromCodeGenFlags();
57   c.Options.EmitAddrsig = config->icfLevel == ICFLevel::safe;
58   for (StringRef C : config->mllvmOpts)
59     c.MllvmArgs.emplace_back(C.str());
60   c.CodeModel = getCodeModelFromCMModel();
61   c.CPU = getCPUStr();
62   c.MAttrs = getMAttrs();
63   c.DiagHandler = diagnosticHandler;
64   c.PreCodeGenPassesHook = [](legacy::PassManager &pm) {
65     pm.add(createObjCARCContractPass());
66   };
67 
68   c.AlwaysEmitRegularLTOObj = !config->ltoObjPath.empty();
69 
70   c.TimeTraceEnabled = config->timeTraceEnabled;
71   c.TimeTraceGranularity = config->timeTraceGranularity;
72   c.OptLevel = config->ltoo;
73   c.CGOptLevel = args::getCGOptLevel(config->ltoo);
74   if (config->saveTemps)
75     checkError(c.addSaveTemps(config->outputFile.str() + ".",
76                               /*UseInputModulePath=*/true));
77   return c;
78 }
79 
80 // If `originalPath` exists, hardlinks `path` to `originalPath`. If that fails,
81 // or `originalPath` is not set, saves `buffer` to `path`.
82 static void saveOrHardlinkBuffer(StringRef buffer, const Twine &path,
83                                  std::optional<StringRef> originalPath) {
84   if (originalPath) {
85     auto err = fs::create_hard_link(*originalPath, path);
86     if (!err)
87       return;
88   }
89   saveBuffer(buffer, path);
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   auto onIndexWrite = [&](StringRef S) { thinIndices.erase(S); };
100   if (config->thinLTOIndexOnly) {
101     backend = lto::createWriteIndexesThinBackend(
102         std::string(config->thinLTOPrefixReplace.first),
103         std::string(config->thinLTOPrefixReplace.second),
104         config->thinLTOEmitImportsFiles, indexFile.get(), onIndexWrite);
105   } else {
106     backend = lto::createInProcessThinBackend(
107         llvm::heavyweight_hardware_concurrency(config->thinLTOJobs),
108         onIndexWrite, config->thinLTOEmitIndexFiles,
109         config->thinLTOEmitImportsFiles);
110   }
111 
112   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend);
113 }
114 
115 void BitcodeCompiler::add(BitcodeFile &f) {
116   lto::InputFile &obj = *f.obj;
117 
118   if (config->thinLTOEmitIndexFiles)
119     thinIndices.insert(obj.getName());
120 
121   ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols();
122   std::vector<lto::SymbolResolution> resols;
123   resols.reserve(objSyms.size());
124 
125   // Provide a resolution to the LTO API for each symbol.
126   bool exportDynamic =
127       config->outputType != MH_EXECUTE || config->exportDynamic;
128   auto symIt = f.symbols.begin();
129   for (const lto::InputFile::Symbol &objSym : objSyms) {
130     resols.emplace_back();
131     lto::SymbolResolution &r = resols.back();
132     Symbol *sym = *symIt++;
133 
134     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
135     // reports two symbols for module ASM defined. Without this check, lld
136     // flags an undefined in IR with a definition in ASM as prevailing.
137     // Once IRObjectFile is fixed to report only one symbol this hack can
138     // be removed.
139     r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
140 
141     if (const auto *defined = dyn_cast<Defined>(sym)) {
142       r.ExportDynamic =
143           defined->isExternal() && !defined->privateExtern && exportDynamic;
144       r.FinalDefinitionInLinkageUnit =
145           !defined->isExternalWeakDef() && !defined->interposable;
146     } else if (const auto *common = dyn_cast<CommonSymbol>(sym)) {
147       r.ExportDynamic = !common->privateExtern && exportDynamic;
148       r.FinalDefinitionInLinkageUnit = true;
149     }
150 
151     r.VisibleToRegularObj =
152         sym->isUsedInRegularObj || (r.Prevailing && r.ExportDynamic);
153 
154     // Un-define the symbol so that we don't get duplicate symbol errors when we
155     // load the ObjFile emitted by LTO compilation.
156     if (r.Prevailing)
157       replaceSymbol<Undefined>(sym, sym->getName(), sym->getFile(),
158                                RefState::Strong, /*wasBitcodeSymbol=*/true);
159 
160     // TODO: set the other resolution configs properly
161   }
162   checkError(ltoObj->add(std::move(f.obj), resols));
163 }
164 
165 // If LazyObjFile has not been added to link, emit empty index files.
166 // This is needed because this is what GNU gold plugin does and we have a
167 // distributed build system that depends on that behavior.
168 static void thinLTOCreateEmptyIndexFiles() {
169   DenseSet<StringRef> linkedBitCodeFiles;
170   for (InputFile *file : inputFiles)
171     if (auto *f = dyn_cast<BitcodeFile>(file))
172       if (!f->lazy)
173         linkedBitCodeFiles.insert(f->getName());
174 
175   for (InputFile *file : inputFiles) {
176     if (auto *f = dyn_cast<BitcodeFile>(file)) {
177       if (!f->lazy)
178         continue;
179       if (linkedBitCodeFiles.contains(f->getName()))
180         continue;
181       std::string path =
182           replaceThinLTOSuffix(getThinLTOOutputFile(f->obj->getName()));
183       std::unique_ptr<raw_fd_ostream> os = openFile(path + ".thinlto.bc");
184       if (!os)
185         continue;
186 
187       ModuleSummaryIndex m(/*HaveGVs=*/false);
188       m.setSkipModuleByDistributedBackend();
189       writeIndexToFile(m, *os);
190       if (config->thinLTOEmitImportsFiles)
191         openFile(path + ".imports");
192     }
193   }
194 }
195 
196 // Merge all the bitcode files we have seen, codegen the result
197 // and return the resulting ObjectFile(s).
198 std::vector<ObjFile *> BitcodeCompiler::compile() {
199   unsigned maxTasks = ltoObj->getMaxTasks();
200   buf.resize(maxTasks);
201   files.resize(maxTasks);
202 
203   // The -cache_path_lto option specifies the path to a directory in which
204   // to cache native object files for ThinLTO incremental builds. If a path was
205   // specified, configure LTO to use it as the cache directory.
206   FileCache cache;
207   if (!config->thinLTOCacheDir.empty())
208     cache = check(localCache("ThinLTO", "Thin", config->thinLTOCacheDir,
209                              [&](size_t task, const Twine &moduleName,
210                                  std::unique_ptr<MemoryBuffer> mb) {
211                                files[task] = std::move(mb);
212                              }));
213 
214   checkError(ltoObj->run(
215       [&](size_t task, const Twine &moduleName) {
216         return std::make_unique<CachedFileStream>(
217             std::make_unique<raw_svector_ostream>(buf[task]));
218       },
219       cache));
220 
221   // Emit empty index files for non-indexed files
222   for (StringRef s : thinIndices) {
223     std::string path = getThinLTOOutputFile(s);
224     openFile(path + ".thinlto.bc");
225     if (config->thinLTOEmitImportsFiles)
226       openFile(path + ".imports");
227   }
228 
229   if (config->thinLTOEmitIndexFiles)
230     thinLTOCreateEmptyIndexFiles();
231 
232   // In ThinLTO mode, Clang passes a temporary directory in -object_path_lto,
233   // while the argument is a single file in FullLTO mode.
234   bool objPathIsDir = true;
235   if (!config->ltoObjPath.empty()) {
236     if (std::error_code ec = fs::create_directories(config->ltoObjPath))
237       fatal("cannot create LTO object path " + config->ltoObjPath + ": " +
238             ec.message());
239 
240     if (!fs::is_directory(config->ltoObjPath)) {
241       objPathIsDir = false;
242       unsigned objCount =
243           count_if(buf, [](const SmallString<0> &b) { return !b.empty(); });
244       if (objCount > 1)
245         fatal("-object_path_lto must specify a directory when using ThinLTO");
246     }
247   }
248 
249   auto outputFilePath = [objPathIsDir](int i) {
250     SmallString<261> filePath("/tmp/lto.tmp");
251     if (!config->ltoObjPath.empty()) {
252       filePath = config->ltoObjPath;
253       if (objPathIsDir)
254         path::append(filePath, Twine(i) + "." +
255                                    getArchitectureName(config->arch()) +
256                                    ".lto.o");
257     }
258     return filePath;
259   };
260 
261   // ThinLTO with index only option is required to generate only the index
262   // files. After that, we exit from linker and ThinLTO backend runs in a
263   // distributed environment.
264   if (config->thinLTOIndexOnly) {
265     if (!config->ltoObjPath.empty())
266       saveBuffer(buf[0], outputFilePath(0));
267     if (indexFile)
268       indexFile->close();
269     return {};
270   }
271 
272   if (!config->thinLTOCacheDir.empty())
273     pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy, files);
274 
275   std::vector<ObjFile *> ret;
276   for (unsigned i = 0; i < maxTasks; ++i) {
277     // Get the native object contents either from the cache or from memory.  Do
278     // not use the cached MemoryBuffer directly to ensure dsymutil does not
279     // race with the cache pruner.
280     StringRef objBuf;
281     std::optional<StringRef> cachePath;
282     if (files[i]) {
283       objBuf = files[i]->getBuffer();
284       cachePath = files[i]->getBufferIdentifier();
285     } else {
286       objBuf = buf[i];
287     }
288     if (objBuf.empty())
289       continue;
290 
291     // FIXME: should `saveTemps` and `ltoObjPath` use the same file name?
292     if (config->saveTemps)
293       saveBuffer(objBuf,
294                  config->outputFile + ((i == 0) ? "" : Twine(i)) + ".lto.o");
295 
296     auto filePath = outputFilePath(i);
297     uint32_t modTime = 0;
298     if (!config->ltoObjPath.empty()) {
299       saveOrHardlinkBuffer(objBuf, filePath, cachePath);
300       modTime = getModTime(filePath);
301     }
302     ret.push_back(make<ObjFile>(
303         MemoryBufferRef(objBuf, saver().save(filePath.str())), modTime, ""));
304   }
305 
306   return ret;
307 }
308