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