xref: /llvm-project-15.0.7/lld/MachO/LTO.cpp (revision 715ca752)
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/ErrorHandler.h"
18 #include "lld/Common/Strings.h"
19 #include "lld/Common/TargetOptionsCommandFlags.h"
20 #include "llvm/LTO/LTO.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Transforms/ObjCARC.h"
25 
26 using namespace lld;
27 using namespace lld::macho;
28 using namespace llvm;
29 using namespace llvm::MachO;
30 using namespace llvm::sys;
31 
32 static lto::Config createConfig() {
33   lto::Config c;
34   c.Options = initTargetOptionsFromCodeGenFlags();
35   c.CodeModel = getCodeModelFromCMModel();
36   c.CPU = getCPUStr();
37   c.MAttrs = getMAttrs();
38   c.UseNewPM = config->ltoNewPassManager;
39   c.PreCodeGenPassesHook = [](legacy::PassManager &pm) {
40     pm.add(createObjCARCContractPass());
41   };
42   c.TimeTraceEnabled = config->timeTraceEnabled;
43   c.TimeTraceGranularity = config->timeTraceGranularity;
44   c.OptLevel = config->ltoo;
45   c.CGOptLevel = args::getCGOptLevel(config->ltoo);
46   if (config->saveTemps)
47     checkError(c.addSaveTemps(config->outputFile.str() + ".",
48                               /*UseInputModulePath=*/true));
49   return c;
50 }
51 
52 BitcodeCompiler::BitcodeCompiler() {
53   lto::ThinBackend backend = lto::createInProcessThinBackend(
54       heavyweight_hardware_concurrency(config->thinLTOJobs));
55   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend);
56 }
57 
58 void BitcodeCompiler::add(BitcodeFile &f) {
59   ArrayRef<lto::InputFile::Symbol> objSyms = f.obj->symbols();
60   std::vector<lto::SymbolResolution> resols;
61   resols.reserve(objSyms.size());
62 
63   // Provide a resolution to the LTO API for each symbol.
64   auto symIt = f.symbols.begin();
65   for (const lto::InputFile::Symbol &objSym : objSyms) {
66     resols.emplace_back();
67     lto::SymbolResolution &r = resols.back();
68     Symbol *sym = *symIt++;
69 
70     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
71     // reports two symbols for module ASM defined. Without this check, lld
72     // flags an undefined in IR with a definition in ASM as prevailing.
73     // Once IRObjectFile is fixed to report only one symbol this hack can
74     // be removed.
75     r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
76 
77     // FIXME: What about other output types? And we can probably be less
78     // restrictive with -flat_namespace, but it's an infrequent use case.
79     // FIXME: Honor config->exportDynamic.
80     r.VisibleToRegularObj = config->outputType != MH_EXECUTE ||
81                             config->namespaceKind == NamespaceKind::flat ||
82                             sym->isUsedInRegularObj;
83 
84     // Un-define the symbol so that we don't get duplicate symbol errors when we
85     // load the ObjFile emitted by LTO compilation.
86     if (r.Prevailing)
87       replaceSymbol<Undefined>(sym, sym->getName(), sym->getFile(),
88                                RefState::Strong);
89 
90     // TODO: set the other resolution configs properly
91   }
92   checkError(ltoObj->add(std::move(f.obj), resols));
93 }
94 
95 // Merge all the bitcode files we have seen, codegen the result
96 // and return the resulting ObjectFile(s).
97 std::vector<ObjFile *> BitcodeCompiler::compile() {
98   unsigned maxTasks = ltoObj->getMaxTasks();
99   buf.resize(maxTasks);
100 
101   checkError(ltoObj->run([&](size_t task) {
102     return std::make_unique<lto::NativeObjectStream>(
103         std::make_unique<raw_svector_ostream>(buf[task]));
104   }));
105 
106   if (config->saveTemps) {
107     if (!buf[0].empty())
108       saveBuffer(buf[0], config->outputFile + ".lto.o");
109     for (unsigned i = 1; i != maxTasks; ++i)
110       saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o");
111   }
112 
113   if (!config->ltoObjPath.empty())
114     fs::create_directories(config->ltoObjPath);
115 
116   std::vector<ObjFile *> ret;
117   for (unsigned i = 0; i != maxTasks; ++i) {
118     if (buf[i].empty())
119       continue;
120     SmallString<261> filePath("/tmp/lto.tmp");
121     uint32_t modTime = 0;
122     if (!config->ltoObjPath.empty()) {
123       filePath = config->ltoObjPath;
124       path::append(filePath, Twine(i) + "." +
125                                  getArchitectureName(config->arch()) +
126                                  ".lto.o");
127       saveBuffer(buf[i], filePath);
128       modTime = getModTime(filePath);
129     }
130     ret.push_back(make<ObjFile>(
131         MemoryBufferRef(buf[i], saver.save(filePath.str())), modTime, ""));
132   }
133 
134   return ret;
135 }
136