blob: df18dd3f9cac04c36bbca83c1716da8a49ed5642 [file] [log] [blame]
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001//===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Thin Link Time Optimization library. This library is
10// intended to be used by linker to optimize code at link time.
11//
12//===----------------------------------------------------------------------===//
13
Peter Collingbourne5c732202016-07-14 21:21:16 +000014#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000015
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000016#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000017#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000018#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000019#include "llvm/Analysis/ProfileSummaryInfo.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
21#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000022#include "llvm/Bitcode/BitcodeReader.h"
23#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000024#include "llvm/Bitcode/BitcodeWriterPass.h"
Nico Weber432a3882018-04-30 14:59:11 +000025#include "llvm/Config/llvm-config.h"
Adrian Prantl981a7992017-05-20 00:00:08 +000026#include "llvm/IR/DebugInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000027#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000029#include "llvm/IR/LegacyPassManager.h"
30#include "llvm/IR/Mangler.h"
Fedor Sergeeva43fd952018-09-26 13:01:43 +000031#include "llvm/IR/PassTimingInfo.h"
Adrian Prantl981a7992017-05-20 00:00:08 +000032#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000034#include "llvm/LTO/LTO.h"
Easwaran Raman5a7056f2018-12-13 19:54:27 +000035#include "llvm/LTO/SummaryBasedOptimizations.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000036#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000037#include "llvm/Object/IRObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000038#include "llvm/Support/CachePruning.h"
39#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000040#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000041#include "llvm/Support/Path.h"
42#include "llvm/Support/SHA1.h"
Weiming Zhao79f2d092018-04-16 03:44:03 +000043#include "llvm/Support/SmallVectorMemoryBuffer.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000046#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000047#include "llvm/Support/ToolOutputFile.h"
Peter Collingbourne942fa562017-04-13 01:26:12 +000048#include "llvm/Support/VCSRevision.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000049#include "llvm/Target/TargetMachine.h"
50#include "llvm/Transforms/IPO.h"
51#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000052#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000053#include "llvm/Transforms/IPO/PassManagerBuilder.h"
54#include "llvm/Transforms/ObjCARC.h"
55#include "llvm/Transforms/Utils/FunctionImportUtils.h"
56
Mehdi Amini819e9cd2016-05-16 19:33:07 +000057#include <numeric>
58
Andrew Ng089303d2018-07-04 14:17:10 +000059#if !defined(_MSC_VER) && !defined(__MINGW32__)
60#include <unistd.h>
61#else
62#include <io.h>
63#endif
64
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000065using namespace llvm;
66
Mehdi Amini1aafabf2016-04-16 07:02:16 +000067#define DEBUG_TYPE "thinlto"
68
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000069namespace llvm {
70// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
71extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000072extern cl::opt<std::string> LTORemarksFilename;
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +000073extern cl::opt<std::string> LTORemarksPasses;
Adam Nemet4c207a62016-12-02 17:53:56 +000074extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000075}
76
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000077namespace {
78
Teresa Johnsonec544c52016-10-19 17:35:01 +000079static cl::opt<int>
80 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000082// Simple helper to save temporary files for debug.
83static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
84 unsigned count, StringRef Suffix) {
85 if (TempDir.empty())
86 return;
87 // User asked to save temps, let dump the bitcode file after import.
Benjamin Kramer3a13ed62017-12-28 16:58:54 +000088 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000089 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000090 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000091 if (EC)
92 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
93 " to save optimized bitcode\n");
Rafael Espindola6a86e252018-02-14 19:11:32 +000094 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000095}
96
Teresa Johnson4d2613f2016-05-24 17:24:25 +000097static const GlobalValueSummary *
98getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
99 // If there is any strong definition anywhere, get it.
100 auto StrongDefForLinker = llvm::find_if(
101 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
102 auto Linkage = Summary->linkage();
103 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
104 !GlobalValue::isWeakForLinker(Linkage);
105 });
106 if (StrongDefForLinker != GVSummaryList.end())
107 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000108 // Get the first *linker visible* definition for this global in the summary
109 // list.
110 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000111 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
112 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000113 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
114 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000115 // Extern templates can be emitted as available_externally.
116 if (FirstDefForLinker == GVSummaryList.end())
117 return nullptr;
118 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000119}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000120
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000121// Populate map of GUID to the prevailing copy for any multiply defined
122// symbols. Currently assume first copy is prevailing, or any strong
123// definition. Can be refined with Linker information in the future.
124static void computePrevailingCopies(
125 const ModuleSummaryIndex &Index,
126 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000127 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
128 return GVSummaryList.size() > 1;
129 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000130
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000131 for (auto &I : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000132 if (HasMultipleCopies(I.second.SummaryList))
133 PrevailingCopy[I.first] =
134 getFirstDefinitionForLinker(I.second.SummaryList);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000135 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000136}
137
Steven Wu05a358c2019-04-17 17:38:09 +0000138static StringMap<lto::InputFile *>
139generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) {
140 StringMap<lto::InputFile *> ModuleMap;
141 for (auto &M : Modules) {
142 assert(ModuleMap.find(M->getName()) == ModuleMap.end() &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000143 "Expect unique Buffer Identifier");
Steven Wu05a358c2019-04-17 17:38:09 +0000144 ModuleMap[M->getName()] = M.get();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000145 }
146 return ModuleMap;
147}
148
Teresa Johnson26ab5772016-03-15 00:04:37 +0000149static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000150 if (renameModuleForThinLTO(TheModule, Index))
151 report_fatal_error("renameModuleForThinLTO failed");
152}
153
Adrian Prantl981a7992017-05-20 00:00:08 +0000154namespace {
155class ThinLTODiagnosticInfo : public DiagnosticInfo {
156 const Twine &Msg;
157public:
158 ThinLTODiagnosticInfo(const Twine &DiagMsg,
159 DiagnosticSeverity Severity = DS_Error)
160 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
161 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
162};
163}
164
165/// Verify the module and strip broken debug info.
166static void verifyLoadedModule(Module &TheModule) {
167 bool BrokenDebugInfo = false;
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000168 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
Adrian Prantl981a7992017-05-20 00:00:08 +0000169 report_fatal_error("Broken module found, compilation aborted!");
170 if (BrokenDebugInfo) {
171 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
172 "Invalid debug info found, debug info will be stripped", DS_Warning));
173 StripDebugInfo(TheModule);
174 }
175}
176
Steven Wu05a358c2019-04-17 17:38:09 +0000177static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile *Input,
178 LLVMContext &Context,
179 bool Lazy,
180 bool IsImporting) {
181 auto &Mod = Input->getSingleBitcodeModule();
Peter Collingbournedac43b42016-12-01 05:52:32 +0000182 SMDiagnostic Err;
183 Expected<std::unique_ptr<Module>> ModuleOrErr =
Steven Wu05a358c2019-04-17 17:38:09 +0000184 Lazy ? Mod.getLazyModule(Context,
185 /* ShouldLazyLoadMetadata */ true, IsImporting)
186 : Mod.parseModule(Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000187 if (!ModuleOrErr) {
188 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
Steven Wu05a358c2019-04-17 17:38:09 +0000189 SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(),
Peter Collingbournedac43b42016-12-01 05:52:32 +0000190 SourceMgr::DK_Error, EIB.message());
191 Err.print("ThinLTO", errs());
192 });
193 report_fatal_error("Can't load module, abort.");
194 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000195 if (!Lazy)
196 verifyLoadedModule(*ModuleOrErr.get());
Steven Wu05a358c2019-04-17 17:38:09 +0000197 return std::move(*ModuleOrErr);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000198}
199
Mehdi Amini01e32132016-03-26 05:40:34 +0000200static void
201crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
Steven Wu05a358c2019-04-17 17:38:09 +0000202 StringMap<lto::InputFile*> &ModuleMap,
Mehdi Amini01e32132016-03-26 05:40:34 +0000203 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000204 auto Loader = [&](StringRef Identifier) {
Steven Wu05a358c2019-04-17 17:38:09 +0000205 auto &Input = ModuleMap[Identifier];
206 return loadModuleFromInput(Input, TheModule.getContext(),
207 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000208 };
209
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000210 FunctionImporter Importer(Index, Loader);
Adrian Prantl66043792017-05-19 23:32:21 +0000211 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000212 if (!Result) {
213 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
214 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
215 SourceMgr::DK_Error, EIB.message());
216 Err.print("ThinLTO", errs());
217 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000218 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000219 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000220 // Verify again after cross-importing.
221 verifyLoadedModule(TheModule);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000222}
223
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000224static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000225 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000226 // Populate the PassManager
227 PassManagerBuilder PMB;
228 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000229 if (Freestanding)
230 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000231 PMB.Inliner = createFunctionInliningPass();
232 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000233 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000234 PMB.LoopVectorize = true;
235 PMB.SLPVectorize = true;
Adrian Prantl981a7992017-05-20 00:00:08 +0000236 // Already did this in verifyLoadedModule().
237 PMB.VerifyInput = false;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000238 PMB.VerifyOutput = false;
239
240 legacy::PassManager PM;
241
242 // Add the TTI (required to inform the vectorizer about register size for
243 // instance)
244 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
245
246 // Add optimizations
247 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000248
249 PM.run(TheModule);
250}
251
Steven Wu05a358c2019-04-17 17:38:09 +0000252static void
253addUsedSymbolToPreservedGUID(const lto::InputFile &File,
254 DenseSet<GlobalValue::GUID> &PreservedGUID) {
255 for (const auto &Sym : File.symbols()) {
256 if (Sym.isUsed())
257 PreservedGUID.insert(GlobalValue::getGUID(Sym.getIRName()));
258 }
259}
260
Mehdi Amini059464f2016-04-24 03:18:01 +0000261// Convert the PreservedSymbols map from "Name" based to "GUID" based.
262static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000263computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
264 const Triple &TheTriple) {
265 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
266 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000267 StringRef Name = Entry.first();
268 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
269 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000270 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000271 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000272 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000273}
274
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000275std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
276 TargetMachine &TM) {
277 SmallVector<char, 128> OutputBuffer;
278
279 // CodeGen
280 {
281 raw_svector_ostream OS(OutputBuffer);
282 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000283
284 // If the bitcode files contain ARC code and were compiled with optimization,
285 // the ObjCARCContractPass must be run, so do it unconditionally here.
286 PM.add(createObjCARCContractPass());
287
288 // Setup the codegen now.
Peter Collingbourne9a451142018-05-21 20:16:41 +0000289 if (TM.addPassesToEmitFile(PM, OS, nullptr, TargetMachine::CGFT_ObjectFile,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000290 /* DisableVerify */ true))
291 report_fatal_error("Failed to setup codegen");
292
293 // Run codegen now. resulting binary is in OutputBuffer.
294 PM.run(TheModule);
295 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000296 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000297}
298
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000299/// Manage caching for a single Module.
300class ModuleCacheEntry {
301 SmallString<128> EntryPath;
302
303public:
304 // Create a cache entry. This compute a unique hash for the Module considering
305 // the current list of export/import, and offer an interface to query to
306 // access the content in the cache.
307 ModuleCacheEntry(
308 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
309 const FunctionImporter::ImportMapTy &ImportList,
310 const FunctionImporter::ExportSetTy &ExportList,
311 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnson5f312ad2018-11-26 20:40:37 +0000312 const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000313 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000314 if (CachePath.empty())
315 return;
316
Mehdi Amini00fa1402016-10-08 04:44:18 +0000317 if (!Index.modulePaths().count(ModuleID))
318 // The module does not have an entry, it can't have a hash at all
319 return;
320
Teresa Johnson5f312ad2018-11-26 20:40:37 +0000321 if (all_of(Index.getModuleHash(ModuleID),
322 [](uint32_t V) { return V == 0; }))
Mehdi Aminif82bda02016-10-08 04:44:23 +0000323 // No hash entry, no caching!
324 return;
325
Teresa Johnson5f312ad2018-11-26 20:40:37 +0000326 llvm::lto::Config Conf;
327 Conf.OptLevel = OptLevel;
328 Conf.Options = TMBuilder.Options;
329 Conf.CPU = TMBuilder.MCpu;
330 Conf.MAttrs.push_back(TMBuilder.MAttr);
331 Conf.RelocModel = TMBuilder.RelocModel;
332 Conf.CGOptLevel = TMBuilder.CGOptLevel;
333 Conf.Freestanding = Freestanding;
334 SmallString<40> Key;
335 computeLTOCacheKey(Key, Conf, Index, ModuleID, ImportList, ExportList,
336 ResolvedODR, DefinedGVSummaries);
Eugene Leviantbf46e742018-11-16 07:08:00 +0000337
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000338 // This choice of file name allows the cache to be pruned (see pruneCache()
339 // in include/llvm/Support/CachePruning.h).
Teresa Johnson5f312ad2018-11-26 20:40:37 +0000340 sys::path::append(EntryPath, CachePath, "llvmcache-" + Key);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000341 }
342
Mehdi Amini059464f2016-04-24 03:18:01 +0000343 // Access the path to this entry in the cache.
344 StringRef getEntryPath() { return EntryPath; }
345
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000346 // Try loading the buffer for this cache entry.
347 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
348 if (EntryPath.empty())
349 return std::error_code();
Andrew Ng089303d2018-07-04 14:17:10 +0000350 int FD;
351 SmallString<64> ResultPath;
352 std::error_code EC = sys::fs::openFileForRead(
353 Twine(EntryPath), FD, sys::fs::OF_UpdateAtime, &ResultPath);
354 if (EC)
355 return EC;
356 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
357 MemoryBuffer::getOpenFile(FD, EntryPath,
358 /*FileSize*/ -1,
359 /*RequiresNullTerminator*/ false);
360 close(FD);
361 return MBOrErr;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000362 }
363
364 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000365 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000366 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000367 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000368
369 // Write to a temporary to avoid race condition
370 SmallString<128> TempFilename;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000371 SmallString<128> CachePath(EntryPath);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000372 int TempFD;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000373 llvm::sys::path::remove_filename(CachePath);
374 sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
Fangrui Songf78650a2018-07-30 19:41:25 +0000375 std::error_code EC =
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000376 sys::fs::createUniqueFile(TempFilename, TempFD, TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000377 if (EC) {
378 errs() << "Error: " << EC.message() << "\n";
379 report_fatal_error("ThinLTO: Can't get a temporary file");
380 }
381 {
382 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000383 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000384 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000385 // Rename temp file to final destination; rename is atomic
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000386 EC = sys::fs::rename(TempFilename, EntryPath);
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000387 if (EC)
Mehdi Aminib02139d2016-05-14 05:16:35 +0000388 sys::fs::remove(TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000389 }
390};
391
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000392static std::unique_ptr<MemoryBuffer>
393ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
Steven Wu05a358c2019-04-17 17:38:09 +0000394 StringMap<lto::InputFile *> &ModuleMap, TargetMachine &TM,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000395 const FunctionImporter::ImportMapTy &ImportList,
396 const FunctionImporter::ExportSetTy &ExportList,
397 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
398 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000399 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000400 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000401 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000402
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000403 // "Benchmark"-like optimization: single-source case
404 bool SingleModule = (ModuleMap.size() == 1);
405
406 if (!SingleModule) {
407 promoteModule(TheModule, Index);
408
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000409 // Apply summary-based prevailing-symbol resolution decisions.
410 thinLTOResolvePrevailingInModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000411
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000412 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000413 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000414 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000415
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000416 // Be friendly and don't nuke totally the module when the client didn't
417 // supply anything to preserve.
418 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
419 // Apply summary-based internalization decisions.
420 thinLTOInternalizeModule(TheModule, DefinedGlobals);
421 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000422
423 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000424 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000425
426 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000427 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000428
429 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000430 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000431 }
432
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000433 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000434
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000435 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000436
Mehdi Amini43b657b2016-04-01 06:47:02 +0000437 if (DisableCodeGen) {
438 // Configured to stop before CodeGen, serialize the bitcode and return.
439 SmallVector<char, 128> OutputBuffer;
440 {
441 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000442 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000443 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000444 WriteBitcodeToFile(TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000445 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000446 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini43b657b2016-04-01 06:47:02 +0000447 }
448
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000449 return codegenModule(TheModule, TM);
450}
451
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000452/// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000453/// for caching, and in the \p Index for application during the ThinLTO
454/// backends. This is needed for correctness for exported symbols (ensure
455/// at least one copy kept) and a compile-time optimization (to drop duplicate
456/// copies when possible).
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000457static void resolvePrevailingInIndex(
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000458 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000459 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
Teresa Johnson37b80122019-05-10 20:08:24 +0000460 &ResolvedODR,
461 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000462
463 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
464 computePrevailingCopies(Index, PrevailingCopy);
465
466 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
467 const auto &Prevailing = PrevailingCopy.find(GUID);
468 // Not in map means that there was only one copy, which must be prevailing.
469 if (Prevailing == PrevailingCopy.end())
470 return true;
471 return Prevailing->second == S;
472 };
473
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000474 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
475 GlobalValue::GUID GUID,
476 GlobalValue::LinkageTypes NewLinkage) {
477 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
478 };
479
Teresa Johnson37b80122019-05-10 20:08:24 +0000480 thinLTOResolvePrevailingInIndex(Index, isPrevailing, recordNewLinkage,
481 GUIDPreservedSymbols);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000482}
483
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000484// Initialize the TargetMachine builder for a given Triple
485static void initTMBuilder(TargetMachineBuilder &TMBuilder,
486 const Triple &TheTriple) {
487 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
488 // FIXME this looks pretty terrible...
489 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
490 if (TheTriple.getArch() == llvm::Triple::x86_64)
491 TMBuilder.MCpu = "core2";
492 else if (TheTriple.getArch() == llvm::Triple::x86)
493 TMBuilder.MCpu = "yonah";
494 else if (TheTriple.getArch() == llvm::Triple::aarch64)
495 TMBuilder.MCpu = "cyclone";
496 }
497 TMBuilder.TheTriple = std::move(TheTriple);
498}
499
500} // end anonymous namespace
501
502void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Steven Wu05a358c2019-04-17 17:38:09 +0000503 MemoryBufferRef Buffer(Data, Identifier);
Akira Hatanakab10bff12017-05-18 03:52:29 +0000504
Steven Wu05a358c2019-04-17 17:38:09 +0000505 auto InputOrError = lto::InputFile::create(Buffer);
506 if (!InputOrError)
507 report_fatal_error("ThinLTO cannot create input file: " +
508 toString(InputOrError.takeError()));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000509
Steven Wu05a358c2019-04-17 17:38:09 +0000510 auto TripleStr = (*InputOrError)->getTargetTriple();
Akira Hatanakab10bff12017-05-18 03:52:29 +0000511 Triple TheTriple(TripleStr);
512
513 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000514 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000515 else if (TMBuilder.TheTriple != TheTriple) {
516 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
517 report_fatal_error("ThinLTO modules with incompatible triples not "
518 "supported");
519 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000520 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000521
Steven Wu05a358c2019-04-17 17:38:09 +0000522 Modules.emplace_back(std::move(*InputOrError));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000523}
524
525void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
526 PreservedSymbols.insert(Name);
527}
528
529void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000530 // FIXME: At the moment, we don't take advantage of this extra information,
531 // we're conservatively considering cross-references as preserved.
532 // CrossReferencedSymbols.insert(Name);
533 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000534}
535
536// TargetMachine factory
537std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
538 std::string ErrMsg;
539 const Target *TheTarget =
540 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
541 if (!TheTarget) {
542 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
543 }
544
545 // Use MAttr as the default set of features.
546 SubtargetFeatures Features(MAttr);
547 Features.getDefaultSubtargetFeatures(TheTriple);
548 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000549
Rafael Espindola79e238a2017-08-03 02:16:21 +0000550 return std::unique_ptr<TargetMachine>(
551 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
552 RelocModel, None, CGOptLevel));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000553}
554
555/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000556 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000557 * "thin-link".
558 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000559std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000560 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
Teresa Johnson4ffc3e72018-06-06 22:22:01 +0000561 llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000562 uint64_t NextModuleId = 0;
Steven Wu05a358c2019-04-17 17:38:09 +0000563 for (auto &Mod : Modules) {
564 auto &M = Mod->getSingleBitcodeModule();
565 if (Error Err =
566 M.readSummary(*CombinedIndex, Mod->getName(), NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000567 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000568 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000569 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000570 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000571 return nullptr;
572 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000573 }
574 return CombinedIndex;
575}
576
George Rimar2421b6f2018-01-17 10:33:05 +0000577static void internalizeAndPromoteInIndex(
578 const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
579 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
580 ModuleSummaryIndex &Index) {
581 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
582 const auto &ExportList = ExportLists.find(ModuleIdentifier);
583 return (ExportList != ExportLists.end() &&
584 ExportList->second.count(GUID)) ||
585 GUIDPreservedSymbols.count(GUID);
586 };
587
588 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
589}
590
George Rimareaf51722018-01-29 08:03:30 +0000591static void computeDeadSymbolsInIndex(
592 ModuleSummaryIndex &Index,
593 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
594 // We have no symbols resolution available. And can't do any better now in the
595 // case where the prevailing symbol is in a native object. It can be refined
596 // with linker information in the future.
597 auto isPrevailing = [&](GlobalValue::GUID G) {
598 return PrevailingType::Unknown;
599 };
Eugene Leviantbf46e742018-11-16 07:08:00 +0000600 computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
601 /* ImportEnabled = */ true);
George Rimareaf51722018-01-29 08:03:30 +0000602}
603
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000604/**
605 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000606 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000607 */
Steven Wu05a358c2019-04-17 17:38:09 +0000608void ThinLTOCodeGenerator::promote(Module &TheModule, ModuleSummaryIndex &Index,
609 const lto::InputFile &File) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000610 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000611 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000612
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000613 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000614 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000615 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000616
Teresa Johnson6c475a72017-01-05 21:34:18 +0000617 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000618 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000619 PreservedSymbols, Triple(TheModule.getTargetTriple()));
620
Steven Wu05a358c2019-04-17 17:38:09 +0000621 // Add used symbol to the preserved symbols.
622 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
623
Teresa Johnson6c475a72017-01-05 21:34:18 +0000624 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000625 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000626
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000627 // Generate import/export list
628 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
629 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
630 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000631 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000632
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000633 // Resolve prevailing symbols
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000634 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Teresa Johnson37b80122019-05-10 20:08:24 +0000635 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000636
Steven Wuf41e70d2019-04-08 18:53:21 +0000637 thinLTOResolvePrevailingInModule(
638 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
639
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000640 // Promote the exported values in the index, so that they are promoted
641 // in the module.
George Rimar2421b6f2018-01-17 10:33:05 +0000642 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000643
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000644 promoteModule(TheModule, Index);
645}
646
647/**
648 * Perform cross-module importing for the module identified by ModuleIdentifier.
649 */
650void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Steven Wu05a358c2019-04-17 17:38:09 +0000651 ModuleSummaryIndex &Index,
652 const lto::InputFile &File) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000653 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000654 auto ModuleCount = Index.modulePaths().size();
655
656 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000657 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000658 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000659
Teresa Johnson6c475a72017-01-05 21:34:18 +0000660 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000661 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000662 PreservedSymbols, Triple(TheModule.getTargetTriple()));
663
Steven Wu05a358c2019-04-17 17:38:09 +0000664 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
665
Teresa Johnson6c475a72017-01-05 21:34:18 +0000666 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000667 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000668
Mehdi Amini01e32132016-03-26 05:40:34 +0000669 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000670 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
671 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000672 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000673 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000674 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
675
676 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000677}
678
679/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000680 * Compute the list of summaries needed for importing into module.
681 */
682void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
Teresa Johnson93f99962018-11-29 17:02:42 +0000683 Module &TheModule, ModuleSummaryIndex &Index,
Steven Wu05a358c2019-04-17 17:38:09 +0000684 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex,
685 const lto::InputFile &File) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000686 auto ModuleCount = Index.modulePaths().size();
Teresa Johnson93f99962018-11-29 17:02:42 +0000687 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson84174c32016-05-10 13:48:23 +0000688
689 // Collect for each module the list of function it defines (GUID -> Summary).
690 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
691 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
692
Teresa Johnson93f99962018-11-29 17:02:42 +0000693 // Convert the preserved symbols set from string to GUID
694 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
695 PreservedSymbols, Triple(TheModule.getTargetTriple()));
696
Steven Wu05a358c2019-04-17 17:38:09 +0000697 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
698
Teresa Johnson93f99962018-11-29 17:02:42 +0000699 // Compute "dead" symbols, we don't want to import/export these!
700 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
701
Teresa Johnson84174c32016-05-10 13:48:23 +0000702 // Generate import/export list
703 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
704 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
705 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
706 ExportLists);
707
Teresa Johnson93f99962018-11-29 17:02:42 +0000708 llvm::gatherImportedSummariesForModule(
709 ModuleIdentifier, ModuleToDefinedGVSummaries,
710 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
Teresa Johnson84174c32016-05-10 13:48:23 +0000711}
712
713/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000714 * Emit the list of files needed for importing into module.
715 */
Teresa Johnson93f99962018-11-29 17:02:42 +0000716void ThinLTOCodeGenerator::emitImports(Module &TheModule, StringRef OutputName,
Steven Wu05a358c2019-04-17 17:38:09 +0000717 ModuleSummaryIndex &Index,
718 const lto::InputFile &File) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000719 auto ModuleCount = Index.modulePaths().size();
Teresa Johnson93f99962018-11-29 17:02:42 +0000720 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000721
722 // Collect for each module the list of function it defines (GUID -> Summary).
723 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
724 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
725
Teresa Johnson93f99962018-11-29 17:02:42 +0000726 // Convert the preserved symbols set from string to GUID
727 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
728 PreservedSymbols, Triple(TheModule.getTargetTriple()));
729
Steven Wu05a358c2019-04-17 17:38:09 +0000730 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
731
Teresa Johnson93f99962018-11-29 17:02:42 +0000732 // Compute "dead" symbols, we don't want to import/export these!
733 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
734
Teresa Johnson8570fe42016-05-10 15:54:09 +0000735 // Generate import/export list
736 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
737 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
738 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
739 ExportLists);
740
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000741 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
Teresa Johnson93f99962018-11-29 17:02:42 +0000742 llvm::gatherImportedSummariesForModule(
743 ModuleIdentifier, ModuleToDefinedGVSummaries,
744 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000745
Teresa Johnson8570fe42016-05-10 15:54:09 +0000746 std::error_code EC;
Teresa Johnson93f99962018-11-29 17:02:42 +0000747 if ((EC = EmitImportsFiles(ModuleIdentifier, OutputName,
748 ModuleToSummariesForIndex)))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000749 report_fatal_error(Twine("Failed to open ") + OutputName +
750 " to save imports lists\n");
751}
752
753/**
Steven Wu05a358c2019-04-17 17:38:09 +0000754 * Perform internalization. Runs promote and internalization together.
755 * Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000756 */
757void ThinLTOCodeGenerator::internalize(Module &TheModule,
Steven Wu05a358c2019-04-17 17:38:09 +0000758 ModuleSummaryIndex &Index,
759 const lto::InputFile &File) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000760 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
761 auto ModuleCount = Index.modulePaths().size();
762 auto ModuleIdentifier = TheModule.getModuleIdentifier();
763
764 // Convert the preserved symbols set from string to GUID
765 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000766 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000767
Steven Wu05a358c2019-04-17 17:38:09 +0000768 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
769
Mehdi Amini059464f2016-04-24 03:18:01 +0000770 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000771 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000772 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
773
Teresa Johnson6c475a72017-01-05 21:34:18 +0000774 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000775 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000776
Mehdi Amini059464f2016-04-24 03:18:01 +0000777 // Generate import/export list
778 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
779 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
780 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000781 ExportLists);
Mehdi Amini059464f2016-04-24 03:18:01 +0000782 auto &ExportList = ExportLists[ModuleIdentifier];
783
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000784 // Be friendly and don't nuke totally the module when the client didn't
785 // supply anything to preserve.
786 if (ExportList.empty() && GUIDPreservedSymbols.empty())
787 return;
788
Steven Wu05a358c2019-04-17 17:38:09 +0000789 // Resolve prevailing symbols
790 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Teresa Johnson37b80122019-05-10 20:08:24 +0000791 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols);
Steven Wu05a358c2019-04-17 17:38:09 +0000792
793 // Promote the exported values in the index, so that they are promoted
794 // in the module.
George Rimar2421b6f2018-01-17 10:33:05 +0000795 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Steven Wu05a358c2019-04-17 17:38:09 +0000796
797 promoteModule(TheModule, Index);
798
799 // Internalization
800 thinLTOResolvePrevailingInModule(
801 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
802
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000803 thinLTOInternalizeModule(TheModule,
804 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000805}
806
807/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000808 * Perform post-importing ThinLTO optimizations.
809 */
810void ThinLTOCodeGenerator::optimize(Module &TheModule) {
811 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000812
813 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000814 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000815}
816
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000817/// Write out the generated object file, either from CacheEntryPath or from
818/// OutputBuffer, preferring hard-link when possible.
819/// Returns the path to the generated file in SavedObjectsDirectoryPath.
Steven Wu6c9f6fd2019-04-29 21:39:54 +0000820std::string
821ThinLTOCodeGenerator::writeGeneratedObject(int count, StringRef CacheEntryPath,
822 const MemoryBuffer &OutputBuffer) {
823 auto ArchName = TMBuilder.TheTriple.getArchName();
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000824 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
Steven Wu6c9f6fd2019-04-29 21:39:54 +0000825 llvm::sys::path::append(OutputPath,
826 Twine(count) + "." + ArchName + ".thinlto.o");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000827 OutputPath.c_str(); // Ensure the string is null terminated.
828 if (sys::fs::exists(OutputPath))
829 sys::fs::remove(OutputPath);
830
831 // We don't return a memory buffer to the linker, just a list of files.
832 if (!CacheEntryPath.empty()) {
833 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
834 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
835 if (!Err)
836 return OutputPath.str();
837 // Hard linking failed, try to copy.
838 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
839 if (!Err)
840 return OutputPath.str();
841 // Copy failed (could be because the CacheEntry was removed from the cache
842 // in the meantime by another process), fall back and try to write down the
843 // buffer to the output.
844 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
845 << "' to '" << OutputPath << "'\n";
846 }
847 // No cache entry, just write out the buffer.
848 std::error_code Err;
849 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
850 if (Err)
851 report_fatal_error("Can't open output '" + OutputPath + "'\n");
852 OS << OutputBuffer.getBuffer();
853 return OutputPath.str();
854}
855
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000856// Main entry point for the ThinLTO processing
857void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000858 // Prepare the resulting object vector
859 assert(ProducedBinaries.empty() && "The generator should not be reused");
860 if (SavedObjectsDirectoryPath.empty())
861 ProducedBinaries.resize(Modules.size());
862 else {
863 sys::fs::create_directories(SavedObjectsDirectoryPath);
864 bool IsDir;
865 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
866 if (!IsDir)
867 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
868 ProducedBinaryFiles.resize(Modules.size());
869 }
870
Mehdi Amini43b657b2016-04-01 06:47:02 +0000871 if (CodeGenOnly) {
872 // Perform only parallel codegen and return.
873 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000874 int count = 0;
Steven Wu05a358c2019-04-17 17:38:09 +0000875 for (auto &Mod : Modules) {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000876 Pool.async([&](int count) {
877 LLVMContext Context;
878 Context.setDiscardValueNames(LTODiscardValueNames);
879
880 // Parse module now
Steven Wu05a358c2019-04-17 17:38:09 +0000881 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
882 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000883
884 // CodeGen
Steven Wucf902032018-09-04 22:54:17 +0000885 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
Mehdi Aminib2990462017-01-20 22:45:34 +0000886 if (SavedObjectsDirectoryPath.empty())
887 ProducedBinaries[count] = std::move(OutputBuffer);
888 else
Steven Wu6c9f6fd2019-04-29 21:39:54 +0000889 ProducedBinaryFiles[count] =
890 writeGeneratedObject(count, "", *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000891 }, count++);
892 }
893
894 return;
895 }
896
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000897 // Sequential linking phase
898 auto Index = linkCombinedIndex();
899
900 // Save temps: index.
901 if (!SaveTempsDir.empty()) {
902 auto SaveTempPath = SaveTempsDir + "index.bc";
903 std::error_code EC;
904 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
905 if (EC)
906 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
907 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000908 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000909 }
910
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000911
912 // Prepare the module map.
913 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000914 auto ModuleCount = Modules.size();
915
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000916 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000917 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000918 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
919
Teresa Johnson6c475a72017-01-05 21:34:18 +0000920 // Convert the preserved symbols set from string to GUID, this is needed for
921 // computing the caching hash and the internalization.
922 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000923 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000924
Steven Wu05a358c2019-04-17 17:38:09 +0000925 // Add used symbol from inputs to the preserved symbols.
926 for (const auto &M : Modules)
927 addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
928
Teresa Johnson6c475a72017-01-05 21:34:18 +0000929 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000930 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000931
Easwaran Raman5a7056f2018-12-13 19:54:27 +0000932 // Synthesize entry counts for functions in the combined index.
933 computeSyntheticCounts(*Index);
934
Mehdi Amini01e32132016-03-26 05:40:34 +0000935 // Collect the import/export lists for all modules from the call-graph in the
936 // combined index.
937 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
938 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000939 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000940 ExportLists);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000941
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000942 // We use a std::map here to be able to have a defined ordering when
943 // producing a hash for the cache entry.
944 // FIXME: we should be able to compute the caching hash for the entry based
945 // on the index, and nuke this map.
946 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
947
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000948 // Resolve prevailing symbols, this has to be computed early because it
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000949 // impacts the caching.
Teresa Johnson37b80122019-05-10 20:08:24 +0000950 resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000951
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000952 // Use global summary-based analysis to identify symbols that can be
953 // internalized (because they aren't exported or preserved as per callback).
954 // Changes are made in the index, consumed in the ThinLTO backends.
George Rimar2421b6f2018-01-17 10:33:05 +0000955 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000956
Steven Wuec53c892018-09-14 19:38:21 +0000957 // Make sure that every module has an entry in the ExportLists, ImportList,
958 // GVSummary and ResolvedODR maps to enable threaded access to these maps
959 // below.
960 for (auto &Module : Modules) {
Steven Wu05a358c2019-04-17 17:38:09 +0000961 auto ModuleIdentifier = Module->getName();
Steven Wuec53c892018-09-14 19:38:21 +0000962 ExportLists[ModuleIdentifier];
963 ImportLists[ModuleIdentifier];
964 ResolvedODR[ModuleIdentifier];
965 ModuleToDefinedGVSummaries[ModuleIdentifier];
Teresa Johnson141149f2016-05-24 18:44:01 +0000966 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000967
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000968 // Compute the ordering we will process the inputs: the rough heuristic here
969 // is to sort them per size so that the largest module get schedule as soon as
970 // possible. This is purely a compile-time optimization.
971 std::vector<int> ModulesOrdering;
972 ModulesOrdering.resize(Modules.size());
973 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
Fangrui Song0cac7262018-09-27 02:13:45 +0000974 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
Steven Wu05a358c2019-04-17 17:38:09 +0000975 auto LSize =
976 Modules[LeftIndex]->getSingleBitcodeModule().getBuffer().size();
977 auto RSize =
978 Modules[RightIndex]->getSingleBitcodeModule().getBuffer().size();
Fangrui Song0cac7262018-09-27 02:13:45 +0000979 return LSize > RSize;
980 });
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000981
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000982 // Parallel optimizer + codegen
983 {
984 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000985 for (auto IndexCount : ModulesOrdering) {
Steven Wu05a358c2019-04-17 17:38:09 +0000986 auto &Mod = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000987 Pool.async([&](int count) {
Steven Wu05a358c2019-04-17 17:38:09 +0000988 auto ModuleIdentifier = Mod->getName();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000989 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000990
Eugene Leviantbf46e742018-11-16 07:08:00 +0000991 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000992
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000993 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000994 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
995 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000996 ResolvedODR[ModuleIdentifier],
Teresa Johnson5f312ad2018-11-26 20:40:37 +0000997 DefinedGVSummaries, OptLevel, Freestanding,
998 TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000999 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001000
1001 {
1002 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001003 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1004 << " '" << CacheEntryPath << "' for buffer "
1005 << count << " " << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +00001006
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001007 if (ErrOrBuffer) {
1008 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001009 if (SavedObjectsDirectoryPath.empty())
1010 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1011 else
1012 ProducedBinaryFiles[count] = writeGeneratedObject(
Steven Wu6c9f6fd2019-04-29 21:39:54 +00001013 count, CacheEntryPath, *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001014 return;
1015 }
1016 }
1017
1018 LLVMContext Context;
1019 Context.setDiscardValueNames(LTODiscardValueNames);
1020 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +00001021 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00001022 Context, LTORemarksFilename, LTORemarksPasses,
1023 LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +00001024 if (!DiagFileOrErr) {
1025 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1026 report_fatal_error("ThinLTO: Can't get an output file for the "
1027 "remarks");
1028 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001029
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001030 // Parse module now
Steven Wu05a358c2019-04-17 17:38:09 +00001031 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1032 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001033
1034 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +00001035 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001036
Mehdi Amini1aafabf2016-04-16 07:02:16 +00001037 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +00001038 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001039 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001040 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001041 ExportList, GUIDPreservedSymbols,
1042 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +00001043 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001044
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001045 // Commit to the cache (if enabled)
1046 CacheEntry.write(*OutputBuffer);
1047
1048 if (SavedObjectsDirectoryPath.empty()) {
1049 // We need to generated a memory buffer for the linker.
1050 if (!CacheEntryPath.empty()) {
Fangrui Songf78650a2018-07-30 19:41:25 +00001051 // When cache is enabled, reload from the cache if possible.
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001052 // Releasing the buffer from the heap and reloading it from the
Fangrui Songf78650a2018-07-30 19:41:25 +00001053 // cache file with mmap helps us to lower memory pressure.
1054 // The freed memory can be used for the next input file.
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001055 // The final binary link will read from the VFS cache (hopefully!)
1056 // or from disk (if the memory pressure was too high).
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001057 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1058 if (auto EC = ReloadedBufferOrErr.getError()) {
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001059 // On error, keep the preexisting buffer and print a diagnostic.
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001060 errs() << "error: can't reload cached file '" << CacheEntryPath
1061 << "': " << EC.message() << "\n";
1062 } else {
1063 OutputBuffer = std::move(*ReloadedBufferOrErr);
1064 }
1065 }
1066 ProducedBinaries[count] = std::move(OutputBuffer);
1067 return;
1068 }
1069 ProducedBinaryFiles[count] = writeGeneratedObject(
Steven Wu6c9f6fd2019-04-29 21:39:54 +00001070 count, CacheEntryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001071 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001072 }
1073 }
1074
Peter Collingbournecead56f2017-03-15 22:54:18 +00001075 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001076
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001077 // If statistics were requested, print them out now.
1078 if (llvm::AreStatisticsEnabled())
1079 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +00001080 reportAndResetTimings();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001081}