1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
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 // 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 
14 #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
15 #include "llvm/Support/CommandLine.h"
16 
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
20 #include "llvm/Analysis/ProfileSummaryInfo.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/BitcodeWriter.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/Config/llvm-config.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LLVMRemarkStreamer.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/IR/PassTimingInfo.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/LTO/LTO.h"
37 #include "llvm/LTO/SummaryBasedOptimizations.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Object/IRObjectFile.h"
40 #include "llvm/Support/CachePruning.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Error.h"
43 #include "llvm/Support/FileUtilities.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/SHA1.h"
46 #include "llvm/Support/SmallVectorMemoryBuffer.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/ThreadPool.h"
49 #include "llvm/Support/Threading.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/FunctionImport.h"
54 #include "llvm/Transforms/IPO/Internalize.h"
55 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
56 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
57 #include "llvm/Transforms/ObjCARC.h"
58 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
59 
60 #include <numeric>
61 
62 #if !defined(_MSC_VER) && !defined(__MINGW32__)
63 #include <unistd.h>
64 #else
65 #include <io.h>
66 #endif
67 
68 using namespace llvm;
69 
70 #define DEBUG_TYPE "thinlto"
71 
72 namespace llvm {
73 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
74 extern cl::opt<bool> LTODiscardValueNames;
75 extern cl::opt<std::string> RemarksFilename;
76 extern cl::opt<std::string> RemarksPasses;
77 extern cl::opt<bool> RemarksWithHotness;
78 extern cl::opt<std::string> RemarksFormat;
79 }
80 
81 namespace {
82 
83 // Default to using all available threads in the system, but using only one
84 // thred per core, as indicated by the usage of
85 // heavyweight_hardware_concurrency() below.
86 static cl::opt<int> ThreadCount("threads", cl::init(0));
87 
88 // Simple helper to save temporary files for debug.
89 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
90                             unsigned count, StringRef Suffix) {
91   if (TempDir.empty())
92     return;
93   // User asked to save temps, let dump the bitcode file after import.
94   std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
95   std::error_code EC;
96   raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
97   if (EC)
98     report_fatal_error(Twine("Failed to open ") + SaveTempPath +
99                        " to save optimized bitcode\n");
100   WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
101 }
102 
103 static const GlobalValueSummary *
104 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
105   // If there is any strong definition anywhere, get it.
106   auto StrongDefForLinker = llvm::find_if(
107       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
108         auto Linkage = Summary->linkage();
109         return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
110                !GlobalValue::isWeakForLinker(Linkage);
111       });
112   if (StrongDefForLinker != GVSummaryList.end())
113     return StrongDefForLinker->get();
114   // Get the first *linker visible* definition for this global in the summary
115   // list.
116   auto FirstDefForLinker = llvm::find_if(
117       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
118         auto Linkage = Summary->linkage();
119         return !GlobalValue::isAvailableExternallyLinkage(Linkage);
120       });
121   // Extern templates can be emitted as available_externally.
122   if (FirstDefForLinker == GVSummaryList.end())
123     return nullptr;
124   return FirstDefForLinker->get();
125 }
126 
127 // Populate map of GUID to the prevailing copy for any multiply defined
128 // symbols. Currently assume first copy is prevailing, or any strong
129 // definition. Can be refined with Linker information in the future.
130 static void computePrevailingCopies(
131     const ModuleSummaryIndex &Index,
132     DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
133   auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
134     return GVSummaryList.size() > 1;
135   };
136 
137   for (auto &I : Index) {
138     if (HasMultipleCopies(I.second.SummaryList))
139       PrevailingCopy[I.first] =
140           getFirstDefinitionForLinker(I.second.SummaryList);
141   }
142 }
143 
144 static StringMap<lto::InputFile *>
145 generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) {
146   StringMap<lto::InputFile *> ModuleMap;
147   for (auto &M : Modules) {
148     assert(ModuleMap.find(M->getName()) == ModuleMap.end() &&
149            "Expect unique Buffer Identifier");
150     ModuleMap[M->getName()] = M.get();
151   }
152   return ModuleMap;
153 }
154 
155 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
156   if (renameModuleForThinLTO(TheModule, Index))
157     report_fatal_error("renameModuleForThinLTO failed");
158 }
159 
160 namespace {
161 class ThinLTODiagnosticInfo : public DiagnosticInfo {
162   const Twine &Msg;
163 public:
164   ThinLTODiagnosticInfo(const Twine &DiagMsg,
165                         DiagnosticSeverity Severity = DS_Error)
166       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
167   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
168 };
169 }
170 
171 /// Verify the module and strip broken debug info.
172 static void verifyLoadedModule(Module &TheModule) {
173   bool BrokenDebugInfo = false;
174   if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
175     report_fatal_error("Broken module found, compilation aborted!");
176   if (BrokenDebugInfo) {
177     TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
178         "Invalid debug info found, debug info will be stripped", DS_Warning));
179     StripDebugInfo(TheModule);
180   }
181 }
182 
183 static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile *Input,
184                                                    LLVMContext &Context,
185                                                    bool Lazy,
186                                                    bool IsImporting) {
187   auto &Mod = Input->getSingleBitcodeModule();
188   SMDiagnostic Err;
189   Expected<std::unique_ptr<Module>> ModuleOrErr =
190       Lazy ? Mod.getLazyModule(Context,
191                                /* ShouldLazyLoadMetadata */ true, IsImporting)
192            : Mod.parseModule(Context);
193   if (!ModuleOrErr) {
194     handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
195       SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(),
196                                       SourceMgr::DK_Error, EIB.message());
197       Err.print("ThinLTO", errs());
198     });
199     report_fatal_error("Can't load module, abort.");
200   }
201   if (!Lazy)
202     verifyLoadedModule(*ModuleOrErr.get());
203   return std::move(*ModuleOrErr);
204 }
205 
206 static void
207 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
208                       StringMap<lto::InputFile*> &ModuleMap,
209                       const FunctionImporter::ImportMapTy &ImportList) {
210   auto Loader = [&](StringRef Identifier) {
211     auto &Input = ModuleMap[Identifier];
212     return loadModuleFromInput(Input, TheModule.getContext(),
213                                /*Lazy=*/true, /*IsImporting*/ true);
214   };
215 
216   FunctionImporter Importer(Index, Loader);
217   Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
218   if (!Result) {
219     handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
220       SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
221                                       SourceMgr::DK_Error, EIB.message());
222       Err.print("ThinLTO", errs());
223     });
224     report_fatal_error("importFunctions failed");
225   }
226   // Verify again after cross-importing.
227   verifyLoadedModule(TheModule);
228 }
229 
230 static void optimizeModule(Module &TheModule, TargetMachine &TM,
231                            unsigned OptLevel, bool Freestanding,
232                            ModuleSummaryIndex *Index) {
233   // Populate the PassManager
234   PassManagerBuilder PMB;
235   PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
236   if (Freestanding)
237     PMB.LibraryInfo->disableAllFunctions();
238   PMB.Inliner = createFunctionInliningPass();
239   // FIXME: should get it from the bitcode?
240   PMB.OptLevel = OptLevel;
241   PMB.LoopVectorize = true;
242   PMB.SLPVectorize = true;
243   // Already did this in verifyLoadedModule().
244   PMB.VerifyInput = false;
245   PMB.VerifyOutput = false;
246   PMB.ImportSummary = Index;
247 
248   legacy::PassManager PM;
249 
250   // Add the TTI (required to inform the vectorizer about register size for
251   // instance)
252   PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
253 
254   // Add optimizations
255   PMB.populateThinLTOPassManager(PM);
256 
257   PM.run(TheModule);
258 }
259 
260 static void
261 addUsedSymbolToPreservedGUID(const lto::InputFile &File,
262                              DenseSet<GlobalValue::GUID> &PreservedGUID) {
263   for (const auto &Sym : File.symbols()) {
264     if (Sym.isUsed())
265       PreservedGUID.insert(GlobalValue::getGUID(Sym.getIRName()));
266   }
267 }
268 
269 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
270 static DenseSet<GlobalValue::GUID>
271 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
272                             const Triple &TheTriple) {
273   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
274   for (auto &Entry : PreservedSymbols) {
275     StringRef Name = Entry.first();
276     if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
277       Name = Name.drop_front();
278     GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
279   }
280   return GUIDPreservedSymbols;
281 }
282 
283 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
284                                             TargetMachine &TM) {
285   SmallVector<char, 128> OutputBuffer;
286 
287   // CodeGen
288   {
289     raw_svector_ostream OS(OutputBuffer);
290     legacy::PassManager PM;
291 
292     // If the bitcode files contain ARC code and were compiled with optimization,
293     // the ObjCARCContractPass must be run, so do it unconditionally here.
294     PM.add(createObjCARCContractPass());
295 
296     // Setup the codegen now.
297     if (TM.addPassesToEmitFile(PM, OS, nullptr, CGFT_ObjectFile,
298                                /* DisableVerify */ true))
299       report_fatal_error("Failed to setup codegen");
300 
301     // Run codegen now. resulting binary is in OutputBuffer.
302     PM.run(TheModule);
303   }
304   return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
305 }
306 
307 /// Manage caching for a single Module.
308 class ModuleCacheEntry {
309   SmallString<128> EntryPath;
310 
311 public:
312   // Create a cache entry. This compute a unique hash for the Module considering
313   // the current list of export/import, and offer an interface to query to
314   // access the content in the cache.
315   ModuleCacheEntry(
316       StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
317       const FunctionImporter::ImportMapTy &ImportList,
318       const FunctionImporter::ExportSetTy &ExportList,
319       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
320       const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel,
321       bool Freestanding, const TargetMachineBuilder &TMBuilder) {
322     if (CachePath.empty())
323       return;
324 
325     if (!Index.modulePaths().count(ModuleID))
326       // The module does not have an entry, it can't have a hash at all
327       return;
328 
329     if (all_of(Index.getModuleHash(ModuleID),
330                [](uint32_t V) { return V == 0; }))
331       // No hash entry, no caching!
332       return;
333 
334     llvm::lto::Config Conf;
335     Conf.OptLevel = OptLevel;
336     Conf.Options = TMBuilder.Options;
337     Conf.CPU = TMBuilder.MCpu;
338     Conf.MAttrs.push_back(TMBuilder.MAttr);
339     Conf.RelocModel = TMBuilder.RelocModel;
340     Conf.CGOptLevel = TMBuilder.CGOptLevel;
341     Conf.Freestanding = Freestanding;
342     SmallString<40> Key;
343     computeLTOCacheKey(Key, Conf, Index, ModuleID, ImportList, ExportList,
344                        ResolvedODR, DefinedGVSummaries);
345 
346     // This choice of file name allows the cache to be pruned (see pruneCache()
347     // in include/llvm/Support/CachePruning.h).
348     sys::path::append(EntryPath, CachePath, "llvmcache-" + Key);
349   }
350 
351   // Access the path to this entry in the cache.
352   StringRef getEntryPath() { return EntryPath; }
353 
354   // Try loading the buffer for this cache entry.
355   ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
356     if (EntryPath.empty())
357       return std::error_code();
358     SmallString<64> ResultPath;
359     Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
360         Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
361     if (!FDOrErr)
362       return errorToErrorCode(FDOrErr.takeError());
363     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getOpenFile(
364         *FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
365     sys::fs::closeFile(*FDOrErr);
366     return MBOrErr;
367   }
368 
369   // Cache the Produced object file
370   void write(const MemoryBuffer &OutputBuffer) {
371     if (EntryPath.empty())
372       return;
373 
374     // Write to a temporary to avoid race condition
375     SmallString<128> TempFilename;
376     SmallString<128> CachePath(EntryPath);
377     llvm::sys::path::remove_filename(CachePath);
378     sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
379 
380     if (auto Err = handleErrors(
381             llvm::writeFileAtomically(TempFilename, EntryPath,
382                                       OutputBuffer.getBuffer()),
383             [](const llvm::AtomicFileWriteError &E) {
384               std::string ErrorMsgBuffer;
385               llvm::raw_string_ostream S(ErrorMsgBuffer);
386               E.log(S);
387 
388               if (E.Error ==
389                   llvm::atomic_write_error::failed_to_create_uniq_file) {
390                 errs() << "Error: " << ErrorMsgBuffer << "\n";
391                 report_fatal_error("ThinLTO: Can't get a temporary file");
392               }
393             })) {
394       // FIXME
395       consumeError(std::move(Err));
396     }
397   }
398 };
399 
400 static std::unique_ptr<MemoryBuffer>
401 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
402                      StringMap<lto::InputFile *> &ModuleMap, TargetMachine &TM,
403                      const FunctionImporter::ImportMapTy &ImportList,
404                      const FunctionImporter::ExportSetTy &ExportList,
405                      const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
406                      const GVSummaryMapTy &DefinedGlobals,
407                      const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
408                      bool DisableCodeGen, StringRef SaveTempsDir,
409                      bool Freestanding, unsigned OptLevel, unsigned count) {
410 
411   // "Benchmark"-like optimization: single-source case
412   bool SingleModule = (ModuleMap.size() == 1);
413 
414   if (!SingleModule) {
415     promoteModule(TheModule, Index);
416 
417     // Apply summary-based prevailing-symbol resolution decisions.
418     thinLTOResolvePrevailingInModule(TheModule, DefinedGlobals);
419 
420     // Save temps: after promotion.
421     saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
422   }
423 
424   // Be friendly and don't nuke totally the module when the client didn't
425   // supply anything to preserve.
426   if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
427     // Apply summary-based internalization decisions.
428     thinLTOInternalizeModule(TheModule, DefinedGlobals);
429   }
430 
431   // Save internalized bitcode
432   saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
433 
434   if (!SingleModule) {
435     crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
436 
437     // Save temps: after cross-module import.
438     saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
439   }
440 
441   optimizeModule(TheModule, TM, OptLevel, Freestanding, &Index);
442 
443   saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
444 
445   if (DisableCodeGen) {
446     // Configured to stop before CodeGen, serialize the bitcode and return.
447     SmallVector<char, 128> OutputBuffer;
448     {
449       raw_svector_ostream OS(OutputBuffer);
450       ProfileSummaryInfo PSI(TheModule);
451       auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
452       WriteBitcodeToFile(TheModule, OS, true, &Index);
453     }
454     return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
455   }
456 
457   return codegenModule(TheModule, TM);
458 }
459 
460 /// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
461 /// for caching, and in the \p Index for application during the ThinLTO
462 /// backends. This is needed for correctness for exported symbols (ensure
463 /// at least one copy kept) and a compile-time optimization (to drop duplicate
464 /// copies when possible).
465 static void resolvePrevailingInIndex(
466     ModuleSummaryIndex &Index,
467     StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
468         &ResolvedODR,
469     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
470     const DenseMap<GlobalValue::GUID, const GlobalValueSummary *>
471         &PrevailingCopy) {
472 
473   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
474     const auto &Prevailing = PrevailingCopy.find(GUID);
475     // Not in map means that there was only one copy, which must be prevailing.
476     if (Prevailing == PrevailingCopy.end())
477       return true;
478     return Prevailing->second == S;
479   };
480 
481   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
482                               GlobalValue::GUID GUID,
483                               GlobalValue::LinkageTypes NewLinkage) {
484     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
485   };
486 
487   thinLTOResolvePrevailingInIndex(Index, isPrevailing, recordNewLinkage,
488                                   GUIDPreservedSymbols);
489 }
490 
491 // Initialize the TargetMachine builder for a given Triple
492 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
493                           const Triple &TheTriple) {
494   // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
495   // FIXME this looks pretty terrible...
496   if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
497     if (TheTriple.getArch() == llvm::Triple::x86_64)
498       TMBuilder.MCpu = "core2";
499     else if (TheTriple.getArch() == llvm::Triple::x86)
500       TMBuilder.MCpu = "yonah";
501     else if (TheTriple.getArch() == llvm::Triple::aarch64 ||
502              TheTriple.getArch() == llvm::Triple::aarch64_32)
503       TMBuilder.MCpu = "cyclone";
504   }
505   TMBuilder.TheTriple = std::move(TheTriple);
506 }
507 
508 } // end anonymous namespace
509 
510 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
511   MemoryBufferRef Buffer(Data, Identifier);
512 
513   auto InputOrError = lto::InputFile::create(Buffer);
514   if (!InputOrError)
515     report_fatal_error("ThinLTO cannot create input file: " +
516                        toString(InputOrError.takeError()));
517 
518   auto TripleStr = (*InputOrError)->getTargetTriple();
519   Triple TheTriple(TripleStr);
520 
521   if (Modules.empty())
522     initTMBuilder(TMBuilder, Triple(TheTriple));
523   else if (TMBuilder.TheTriple != TheTriple) {
524     if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
525       report_fatal_error("ThinLTO modules with incompatible triples not "
526                          "supported");
527     initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
528   }
529 
530   Modules.emplace_back(std::move(*InputOrError));
531 }
532 
533 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
534   PreservedSymbols.insert(Name);
535 }
536 
537 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
538   // FIXME: At the moment, we don't take advantage of this extra information,
539   // we're conservatively considering cross-references as preserved.
540   //  CrossReferencedSymbols.insert(Name);
541   PreservedSymbols.insert(Name);
542 }
543 
544 // TargetMachine factory
545 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
546   std::string ErrMsg;
547   const Target *TheTarget =
548       TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
549   if (!TheTarget) {
550     report_fatal_error("Can't load target for this Triple: " + ErrMsg);
551   }
552 
553   // Use MAttr as the default set of features.
554   SubtargetFeatures Features(MAttr);
555   Features.getDefaultSubtargetFeatures(TheTriple);
556   std::string FeatureStr = Features.getString();
557 
558   return std::unique_ptr<TargetMachine>(
559       TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
560                                      RelocModel, None, CGOptLevel));
561 }
562 
563 /**
564  * Produce the combined summary index from all the bitcode files:
565  * "thin-link".
566  */
567 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
568   std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
569       std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
570   uint64_t NextModuleId = 0;
571   for (auto &Mod : Modules) {
572     auto &M = Mod->getSingleBitcodeModule();
573     if (Error Err =
574             M.readSummary(*CombinedIndex, Mod->getName(), NextModuleId++)) {
575       // FIXME diagnose
576       logAllUnhandledErrors(
577           std::move(Err), errs(),
578           "error: can't create module summary index for buffer: ");
579       return nullptr;
580     }
581   }
582   return CombinedIndex;
583 }
584 
585 namespace {
586 struct IsExported {
587   const StringMap<FunctionImporter::ExportSetTy> &ExportLists;
588   const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols;
589 
590   IsExported(const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
591              const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)
592       : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {}
593 
594   bool operator()(StringRef ModuleIdentifier, ValueInfo VI) const {
595     const auto &ExportList = ExportLists.find(ModuleIdentifier);
596     return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
597            GUIDPreservedSymbols.count(VI.getGUID());
598   }
599 };
600 
601 struct IsPrevailing {
602   const DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy;
603   IsPrevailing(const DenseMap<GlobalValue::GUID, const GlobalValueSummary *>
604                    &PrevailingCopy)
605       : PrevailingCopy(PrevailingCopy) {}
606 
607   bool operator()(GlobalValue::GUID GUID, const GlobalValueSummary *S) const {
608     const auto &Prevailing = PrevailingCopy.find(GUID);
609     // Not in map means that there was only one copy, which must be prevailing.
610     if (Prevailing == PrevailingCopy.end())
611       return true;
612     return Prevailing->second == S;
613   };
614 };
615 } // namespace
616 
617 static void computeDeadSymbolsInIndex(
618     ModuleSummaryIndex &Index,
619     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
620   // We have no symbols resolution available. And can't do any better now in the
621   // case where the prevailing symbol is in a native object. It can be refined
622   // with linker information in the future.
623   auto isPrevailing = [&](GlobalValue::GUID G) {
624     return PrevailingType::Unknown;
625   };
626   computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
627                                   /* ImportEnabled = */ true);
628 }
629 
630 /**
631  * Perform promotion and renaming of exported internal functions.
632  * Index is updated to reflect linkage changes from weak resolution.
633  */
634 void ThinLTOCodeGenerator::promote(Module &TheModule, ModuleSummaryIndex &Index,
635                                    const lto::InputFile &File) {
636   auto ModuleCount = Index.modulePaths().size();
637   auto ModuleIdentifier = TheModule.getModuleIdentifier();
638 
639   // Collect for each module the list of function it defines (GUID -> Summary).
640   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
641   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
642 
643   // Convert the preserved symbols set from string to GUID
644   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
645       PreservedSymbols, Triple(TheModule.getTargetTriple()));
646 
647   // Add used symbol to the preserved symbols.
648   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
649 
650   // Compute "dead" symbols, we don't want to import/export these!
651   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
652 
653   // Generate import/export list
654   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
655   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
656   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
657                            ExportLists);
658 
659   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
660   computePrevailingCopies(Index, PrevailingCopy);
661 
662   // Resolve prevailing symbols
663   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
664   resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
665                            PrevailingCopy);
666 
667   thinLTOResolvePrevailingInModule(
668       TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
669 
670   // Promote the exported values in the index, so that they are promoted
671   // in the module.
672   thinLTOInternalizeAndPromoteInIndex(
673       Index, IsExported(ExportLists, GUIDPreservedSymbols),
674       IsPrevailing(PrevailingCopy));
675 
676   promoteModule(TheModule, Index);
677 }
678 
679 /**
680  * Perform cross-module importing for the module identified by ModuleIdentifier.
681  */
682 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
683                                              ModuleSummaryIndex &Index,
684                                              const lto::InputFile &File) {
685   auto ModuleMap = generateModuleMap(Modules);
686   auto ModuleCount = Index.modulePaths().size();
687 
688   // Collect for each module the list of function it defines (GUID -> Summary).
689   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
690   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
691 
692   // Convert the preserved symbols set from string to GUID
693   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
694       PreservedSymbols, Triple(TheModule.getTargetTriple()));
695 
696   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
697 
698   // Compute "dead" symbols, we don't want to import/export these!
699   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
700 
701   // Generate import/export list
702   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
703   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
704   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
705                            ExportLists);
706   auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
707 
708   crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
709 }
710 
711 /**
712  * Compute the list of summaries needed for importing into module.
713  */
714 void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
715     Module &TheModule, ModuleSummaryIndex &Index,
716     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex,
717     const lto::InputFile &File) {
718   auto ModuleCount = Index.modulePaths().size();
719   auto ModuleIdentifier = TheModule.getModuleIdentifier();
720 
721   // Collect for each module the list of function it defines (GUID -> Summary).
722   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
723   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
724 
725   // Convert the preserved symbols set from string to GUID
726   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
727       PreservedSymbols, Triple(TheModule.getTargetTriple()));
728 
729   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
730 
731   // Compute "dead" symbols, we don't want to import/export these!
732   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
733 
734   // Generate import/export list
735   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
736   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
737   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
738                            ExportLists);
739 
740   llvm::gatherImportedSummariesForModule(
741       ModuleIdentifier, ModuleToDefinedGVSummaries,
742       ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
743 }
744 
745 /**
746  * Emit the list of files needed for importing into module.
747  */
748 void ThinLTOCodeGenerator::emitImports(Module &TheModule, StringRef OutputName,
749                                        ModuleSummaryIndex &Index,
750                                        const lto::InputFile &File) {
751   auto ModuleCount = Index.modulePaths().size();
752   auto ModuleIdentifier = TheModule.getModuleIdentifier();
753 
754   // Collect for each module the list of function it defines (GUID -> Summary).
755   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
756   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
757 
758   // Convert the preserved symbols set from string to GUID
759   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
760       PreservedSymbols, Triple(TheModule.getTargetTriple()));
761 
762   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
763 
764   // Compute "dead" symbols, we don't want to import/export these!
765   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
766 
767   // Generate import/export list
768   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
769   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
770   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
771                            ExportLists);
772 
773   std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
774   llvm::gatherImportedSummariesForModule(
775       ModuleIdentifier, ModuleToDefinedGVSummaries,
776       ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
777 
778   std::error_code EC;
779   if ((EC = EmitImportsFiles(ModuleIdentifier, OutputName,
780                              ModuleToSummariesForIndex)))
781     report_fatal_error(Twine("Failed to open ") + OutputName +
782                        " to save imports lists\n");
783 }
784 
785 /**
786  * Perform internalization. Runs promote and internalization together.
787  * Index is updated to reflect linkage changes.
788  */
789 void ThinLTOCodeGenerator::internalize(Module &TheModule,
790                                        ModuleSummaryIndex &Index,
791                                        const lto::InputFile &File) {
792   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
793   auto ModuleCount = Index.modulePaths().size();
794   auto ModuleIdentifier = TheModule.getModuleIdentifier();
795 
796   // Convert the preserved symbols set from string to GUID
797   auto GUIDPreservedSymbols =
798       computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
799 
800   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
801 
802   // Collect for each module the list of function it defines (GUID -> Summary).
803   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
804   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
805 
806   // Compute "dead" symbols, we don't want to import/export these!
807   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
808 
809   // Generate import/export list
810   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
811   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
812   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
813                            ExportLists);
814   auto &ExportList = ExportLists[ModuleIdentifier];
815 
816   // Be friendly and don't nuke totally the module when the client didn't
817   // supply anything to preserve.
818   if (ExportList.empty() && GUIDPreservedSymbols.empty())
819     return;
820 
821   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
822   computePrevailingCopies(Index, PrevailingCopy);
823 
824   // Resolve prevailing symbols
825   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
826   resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
827                            PrevailingCopy);
828 
829   // Promote the exported values in the index, so that they are promoted
830   // in the module.
831   thinLTOInternalizeAndPromoteInIndex(
832       Index, IsExported(ExportLists, GUIDPreservedSymbols),
833       IsPrevailing(PrevailingCopy));
834 
835   promoteModule(TheModule, Index);
836 
837   // Internalization
838   thinLTOResolvePrevailingInModule(
839       TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
840 
841   thinLTOInternalizeModule(TheModule,
842                            ModuleToDefinedGVSummaries[ModuleIdentifier]);
843 }
844 
845 /**
846  * Perform post-importing ThinLTO optimizations.
847  */
848 void ThinLTOCodeGenerator::optimize(Module &TheModule) {
849   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
850 
851   // Optimize now
852   optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
853                  nullptr);
854 }
855 
856 /// Write out the generated object file, either from CacheEntryPath or from
857 /// OutputBuffer, preferring hard-link when possible.
858 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
859 std::string
860 ThinLTOCodeGenerator::writeGeneratedObject(int count, StringRef CacheEntryPath,
861                                            const MemoryBuffer &OutputBuffer) {
862   auto ArchName = TMBuilder.TheTriple.getArchName();
863   SmallString<128> OutputPath(SavedObjectsDirectoryPath);
864   llvm::sys::path::append(OutputPath,
865                           Twine(count) + "." + ArchName + ".thinlto.o");
866   OutputPath.c_str(); // Ensure the string is null terminated.
867   if (sys::fs::exists(OutputPath))
868     sys::fs::remove(OutputPath);
869 
870   // We don't return a memory buffer to the linker, just a list of files.
871   if (!CacheEntryPath.empty()) {
872     // Cache is enabled, hard-link the entry (or copy if hard-link fails).
873     auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
874     if (!Err)
875       return std::string(OutputPath.str());
876     // Hard linking failed, try to copy.
877     Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
878     if (!Err)
879       return std::string(OutputPath.str());
880     // Copy failed (could be because the CacheEntry was removed from the cache
881     // in the meantime by another process), fall back and try to write down the
882     // buffer to the output.
883     errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
884            << "' to '" << OutputPath << "'\n";
885   }
886   // No cache entry, just write out the buffer.
887   std::error_code Err;
888   raw_fd_ostream OS(OutputPath, Err, sys::fs::OF_None);
889   if (Err)
890     report_fatal_error("Can't open output '" + OutputPath + "'\n");
891   OS << OutputBuffer.getBuffer();
892   return std::string(OutputPath.str());
893 }
894 
895 // Main entry point for the ThinLTO processing
896 void ThinLTOCodeGenerator::run() {
897   // Prepare the resulting object vector
898   assert(ProducedBinaries.empty() && "The generator should not be reused");
899   if (SavedObjectsDirectoryPath.empty())
900     ProducedBinaries.resize(Modules.size());
901   else {
902     sys::fs::create_directories(SavedObjectsDirectoryPath);
903     bool IsDir;
904     sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
905     if (!IsDir)
906       report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
907     ProducedBinaryFiles.resize(Modules.size());
908   }
909 
910   if (CodeGenOnly) {
911     // Perform only parallel codegen and return.
912     ThreadPool Pool;
913     int count = 0;
914     for (auto &Mod : Modules) {
915       Pool.async([&](int count) {
916         LLVMContext Context;
917         Context.setDiscardValueNames(LTODiscardValueNames);
918 
919         // Parse module now
920         auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
921                                              /*IsImporting*/ false);
922 
923         // CodeGen
924         auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
925         if (SavedObjectsDirectoryPath.empty())
926           ProducedBinaries[count] = std::move(OutputBuffer);
927         else
928           ProducedBinaryFiles[count] =
929               writeGeneratedObject(count, "", *OutputBuffer);
930       }, count++);
931     }
932 
933     return;
934   }
935 
936   // Sequential linking phase
937   auto Index = linkCombinedIndex();
938 
939   // Save temps: index.
940   if (!SaveTempsDir.empty()) {
941     auto SaveTempPath = SaveTempsDir + "index.bc";
942     std::error_code EC;
943     raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
944     if (EC)
945       report_fatal_error(Twine("Failed to open ") + SaveTempPath +
946                          " to save optimized bitcode\n");
947     WriteIndexToFile(*Index, OS);
948   }
949 
950 
951   // Prepare the module map.
952   auto ModuleMap = generateModuleMap(Modules);
953   auto ModuleCount = Modules.size();
954 
955   // Collect for each module the list of function it defines (GUID -> Summary).
956   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
957   Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
958 
959   // Convert the preserved symbols set from string to GUID, this is needed for
960   // computing the caching hash and the internalization.
961   auto GUIDPreservedSymbols =
962       computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
963 
964   // Add used symbol from inputs to the preserved symbols.
965   for (const auto &M : Modules)
966     addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
967 
968   // Compute "dead" symbols, we don't want to import/export these!
969   computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
970 
971   // Synthesize entry counts for functions in the combined index.
972   computeSyntheticCounts(*Index);
973 
974   // Currently there is no support for enabling whole program visibility via a
975   // linker option in the old LTO API, but this call allows it to be specified
976   // via the internal option. Must be done before WPD below.
977   updateVCallVisibilityInIndex(*Index,
978                                /* WholeProgramVisibilityEnabledInLTO */ false);
979 
980   // Perform index-based WPD. This will return immediately if there are
981   // no index entries in the typeIdMetadata map (e.g. if we are instead
982   // performing IR-based WPD in hybrid regular/thin LTO mode).
983   std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
984   std::set<GlobalValue::GUID> ExportedGUIDs;
985   runWholeProgramDevirtOnIndex(*Index, ExportedGUIDs, LocalWPDTargetsMap);
986   for (auto GUID : ExportedGUIDs)
987     GUIDPreservedSymbols.insert(GUID);
988 
989   // Collect the import/export lists for all modules from the call-graph in the
990   // combined index.
991   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
992   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
993   ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
994                            ExportLists);
995 
996   // We use a std::map here to be able to have a defined ordering when
997   // producing a hash for the cache entry.
998   // FIXME: we should be able to compute the caching hash for the entry based
999   // on the index, and nuke this map.
1000   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1001 
1002   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
1003   computePrevailingCopies(*Index, PrevailingCopy);
1004 
1005   // Resolve prevailing symbols, this has to be computed early because it
1006   // impacts the caching.
1007   resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols,
1008                            PrevailingCopy);
1009 
1010   // Use global summary-based analysis to identify symbols that can be
1011   // internalized (because they aren't exported or preserved as per callback).
1012   // Changes are made in the index, consumed in the ThinLTO backends.
1013   updateIndexWPDForExports(*Index,
1014                            IsExported(ExportLists, GUIDPreservedSymbols),
1015                            LocalWPDTargetsMap);
1016   thinLTOInternalizeAndPromoteInIndex(
1017       *Index, IsExported(ExportLists, GUIDPreservedSymbols),
1018       IsPrevailing(PrevailingCopy));
1019 
1020   // Make sure that every module has an entry in the ExportLists, ImportList,
1021   // GVSummary and ResolvedODR maps to enable threaded access to these maps
1022   // below.
1023   for (auto &Module : Modules) {
1024     auto ModuleIdentifier = Module->getName();
1025     ExportLists[ModuleIdentifier];
1026     ImportLists[ModuleIdentifier];
1027     ResolvedODR[ModuleIdentifier];
1028     ModuleToDefinedGVSummaries[ModuleIdentifier];
1029   }
1030 
1031   // Compute the ordering we will process the inputs: the rough heuristic here
1032   // is to sort them per size so that the largest module get schedule as soon as
1033   // possible. This is purely a compile-time optimization.
1034   std::vector<int> ModulesOrdering;
1035   ModulesOrdering.resize(Modules.size());
1036   std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
1037   llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
1038     auto LSize =
1039         Modules[LeftIndex]->getSingleBitcodeModule().getBuffer().size();
1040     auto RSize =
1041         Modules[RightIndex]->getSingleBitcodeModule().getBuffer().size();
1042     return LSize > RSize;
1043   });
1044 
1045   // Parallel optimizer + codegen
1046   {
1047     ThreadPool Pool(heavyweight_hardware_concurrency(ThreadCount));
1048     for (auto IndexCount : ModulesOrdering) {
1049       auto &Mod = Modules[IndexCount];
1050       Pool.async([&](int count) {
1051         auto ModuleIdentifier = Mod->getName();
1052         auto &ExportList = ExportLists[ModuleIdentifier];
1053 
1054         auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
1055 
1056         // The module may be cached, this helps handling it.
1057         ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
1058                                     ImportLists[ModuleIdentifier], ExportList,
1059                                     ResolvedODR[ModuleIdentifier],
1060                                     DefinedGVSummaries, OptLevel, Freestanding,
1061                                     TMBuilder);
1062         auto CacheEntryPath = CacheEntry.getEntryPath();
1063 
1064         {
1065           auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1066           LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1067                             << " '" << CacheEntryPath << "' for buffer "
1068                             << count << " " << ModuleIdentifier << "\n");
1069 
1070           if (ErrOrBuffer) {
1071             // Cache Hit!
1072             if (SavedObjectsDirectoryPath.empty())
1073               ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1074             else
1075               ProducedBinaryFiles[count] = writeGeneratedObject(
1076                   count, CacheEntryPath, *ErrOrBuffer.get());
1077             return;
1078           }
1079         }
1080 
1081         LLVMContext Context;
1082         Context.setDiscardValueNames(LTODiscardValueNames);
1083         Context.enableDebugTypeODRUniquing();
1084         auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1085             Context, RemarksFilename, RemarksPasses, RemarksFormat,
1086             RemarksWithHotness, count);
1087         if (!DiagFileOrErr) {
1088           errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1089           report_fatal_error("ThinLTO: Can't get an output file for the "
1090                              "remarks");
1091         }
1092 
1093         // Parse module now
1094         auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1095                                              /*IsImporting*/ false);
1096 
1097         // Save temps: original file.
1098         saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1099 
1100         auto &ImportList = ImportLists[ModuleIdentifier];
1101         // Run the main process now, and generates a binary
1102         auto OutputBuffer = ProcessThinLTOModule(
1103             *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1104             ExportList, GUIDPreservedSymbols,
1105             ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1106             DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
1107 
1108         // Commit to the cache (if enabled)
1109         CacheEntry.write(*OutputBuffer);
1110 
1111         if (SavedObjectsDirectoryPath.empty()) {
1112           // We need to generated a memory buffer for the linker.
1113           if (!CacheEntryPath.empty()) {
1114             // When cache is enabled, reload from the cache if possible.
1115             // Releasing the buffer from the heap and reloading it from the
1116             // cache file with mmap helps us to lower memory pressure.
1117             // The freed memory can be used for the next input file.
1118             // The final binary link will read from the VFS cache (hopefully!)
1119             // or from disk (if the memory pressure was too high).
1120             auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1121             if (auto EC = ReloadedBufferOrErr.getError()) {
1122               // On error, keep the preexisting buffer and print a diagnostic.
1123               errs() << "error: can't reload cached file '" << CacheEntryPath
1124                      << "': " << EC.message() << "\n";
1125             } else {
1126               OutputBuffer = std::move(*ReloadedBufferOrErr);
1127             }
1128           }
1129           ProducedBinaries[count] = std::move(OutputBuffer);
1130           return;
1131         }
1132         ProducedBinaryFiles[count] = writeGeneratedObject(
1133             count, CacheEntryPath, *OutputBuffer);
1134       }, IndexCount);
1135     }
1136   }
1137 
1138   pruneCache(CacheOptions.Path, CacheOptions.Policy);
1139 
1140   // If statistics were requested, print them out now.
1141   if (llvm::AreStatisticsEnabled())
1142     llvm::PrintStatistics();
1143   reportAndResetTimings();
1144 }
1145