1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Thin Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/LTO/ThinLTOCodeGenerator.h"
16 
17 #ifdef HAVE_LLVM_REVISION
18 #include "LLVMLTORevision.h"
19 #endif
20 
21 #include "UpdateCompilerUsed.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Bitcode/BitcodeWriterPass.h"
28 #include "llvm/Bitcode/ReaderWriter.h"
29 #include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
30 #include "llvm/IR/DiagnosticPrinter.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IRReader/IRReader.h"
35 #include "llvm/LTO/LTO.h"
36 #include "llvm/Linker/Linker.h"
37 #include "llvm/MC/SubtargetFeature.h"
38 #include "llvm/Object/IRObjectFile.h"
39 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
40 #include "llvm/Support/CachePruning.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/SHA1.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/ThreadPool.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Transforms/IPO.h"
48 #include "llvm/Transforms/IPO/FunctionImport.h"
49 #include "llvm/Transforms/IPO/Internalize.h"
50 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
51 #include "llvm/Transforms/ObjCARC.h"
52 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
53 
54 #include <numeric>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "thinlto"
59 
60 namespace llvm {
61 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
62 extern cl::opt<bool> LTODiscardValueNames;
63 }
64 
65 namespace {
66 
67 static cl::opt<int> ThreadCount("threads",
68                                 cl::init(std::thread::hardware_concurrency()));
69 
70 static void diagnosticHandler(const DiagnosticInfo &DI) {
71   DiagnosticPrinterRawOStream DP(errs());
72   DI.print(DP);
73   errs() << '\n';
74 }
75 
76 // Simple helper to save temporary files for debug.
77 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
78                             unsigned count, StringRef Suffix) {
79   if (TempDir.empty())
80     return;
81   // User asked to save temps, let dump the bitcode file after import.
82   auto SaveTempPath = TempDir + llvm::utostr(count) + Suffix;
83   std::error_code EC;
84   raw_fd_ostream OS(SaveTempPath.str(), EC, sys::fs::F_None);
85   if (EC)
86     report_fatal_error(Twine("Failed to open ") + SaveTempPath +
87                        " to save optimized bitcode\n");
88   WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
89 }
90 
91 static const GlobalValueSummary *
92 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
93   // If there is any strong definition anywhere, get it.
94   auto StrongDefForLinker = llvm::find_if(
95       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
96         auto Linkage = Summary->linkage();
97         return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
98                !GlobalValue::isWeakForLinker(Linkage);
99       });
100   if (StrongDefForLinker != GVSummaryList.end())
101     return StrongDefForLinker->get();
102   // Get the first *linker visible* definition for this global in the summary
103   // list.
104   auto FirstDefForLinker = llvm::find_if(
105       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
106         auto Linkage = Summary->linkage();
107         return !GlobalValue::isAvailableExternallyLinkage(Linkage);
108       });
109   // Extern templates can be emitted as available_externally.
110   if (FirstDefForLinker == GVSummaryList.end())
111     return nullptr;
112   return FirstDefForLinker->get();
113 }
114 
115 // Populate map of GUID to the prevailing copy for any multiply defined
116 // symbols. Currently assume first copy is prevailing, or any strong
117 // definition. Can be refined with Linker information in the future.
118 static void computePrevailingCopies(
119     const ModuleSummaryIndex &Index,
120     DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
121   auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
122     return GVSummaryList.size() > 1;
123   };
124 
125   for (auto &I : Index) {
126     if (HasMultipleCopies(I.second))
127       PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
128   }
129 }
130 
131 static StringMap<MemoryBufferRef>
132 generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
133   StringMap<MemoryBufferRef> ModuleMap;
134   for (auto &ModuleBuffer : Modules) {
135     assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
136                ModuleMap.end() &&
137            "Expect unique Buffer Identifier");
138     ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
139   }
140   return ModuleMap;
141 }
142 
143 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
144   if (renameModuleForThinLTO(TheModule, Index))
145     report_fatal_error("renameModuleForThinLTO failed");
146 }
147 
148 static void
149 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
150                       StringMap<MemoryBufferRef> &ModuleMap,
151                       const FunctionImporter::ImportMapTy &ImportList) {
152   ModuleLoader Loader(TheModule.getContext(), ModuleMap);
153   FunctionImporter Importer(Index, Loader);
154   Importer.importFunctions(TheModule, ImportList);
155 }
156 
157 static void optimizeModule(Module &TheModule, TargetMachine &TM) {
158   // Populate the PassManager
159   PassManagerBuilder PMB;
160   PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
161   PMB.Inliner = createFunctionInliningPass();
162   // FIXME: should get it from the bitcode?
163   PMB.OptLevel = 3;
164   PMB.LoopVectorize = true;
165   PMB.SLPVectorize = true;
166   PMB.VerifyInput = true;
167   PMB.VerifyOutput = false;
168 
169   legacy::PassManager PM;
170 
171   // Add the TTI (required to inform the vectorizer about register size for
172   // instance)
173   PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
174 
175   // Add optimizations
176   PMB.populateThinLTOPassManager(PM);
177 
178   PM.run(TheModule);
179 }
180 
181 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
182 static DenseSet<GlobalValue::GUID>
183 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
184                             const Triple &TheTriple) {
185   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
186   for (auto &Entry : PreservedSymbols) {
187     StringRef Name = Entry.first();
188     if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
189       Name = Name.drop_front();
190     GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
191   }
192   return GUIDPreservedSymbols;
193 }
194 
195 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
196                                             TargetMachine &TM) {
197   SmallVector<char, 128> OutputBuffer;
198 
199   // CodeGen
200   {
201     raw_svector_ostream OS(OutputBuffer);
202     legacy::PassManager PM;
203 
204     // If the bitcode files contain ARC code and were compiled with optimization,
205     // the ObjCARCContractPass must be run, so do it unconditionally here.
206     PM.add(createObjCARCContractPass());
207 
208     // Setup the codegen now.
209     if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
210                                /* DisableVerify */ true))
211       report_fatal_error("Failed to setup codegen");
212 
213     // Run codegen now. resulting binary is in OutputBuffer.
214     PM.run(TheModule);
215   }
216   return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
217 }
218 
219 /// Manage caching for a single Module.
220 class ModuleCacheEntry {
221   SmallString<128> EntryPath;
222 
223 public:
224   // Create a cache entry. This compute a unique hash for the Module considering
225   // the current list of export/import, and offer an interface to query to
226   // access the content in the cache.
227   ModuleCacheEntry(
228       StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
229       const FunctionImporter::ImportMapTy &ImportList,
230       const FunctionImporter::ExportSetTy &ExportList,
231       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
232       const GVSummaryMapTy &DefinedFunctions,
233       const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
234     if (CachePath.empty())
235       return;
236 
237     // Compute the unique hash for this entry
238     // This is based on the current compiler version, the module itself, the
239     // export list, the hash for every single module in the import list, the
240     // list of ResolvedODR for the module, and the list of preserved symbols.
241 
242     SHA1 Hasher;
243 
244     // Start with the compiler revision
245     Hasher.update(LLVM_VERSION_STRING);
246 #ifdef HAVE_LLVM_REVISION
247     Hasher.update(LLVM_REVISION);
248 #endif
249 
250     // Include the hash for the current module
251     auto ModHash = Index.getModuleHash(ModuleID);
252     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
253     for (auto F : ExportList)
254       // The export list can impact the internalization, be conservative here
255       Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
256 
257     // Include the hash for every module we import functions from
258     for (auto &Entry : ImportList) {
259       auto ModHash = Index.getModuleHash(Entry.first());
260       Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
261     }
262 
263     // Include the hash for the resolved ODR.
264     for (auto &Entry : ResolvedODR) {
265       Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
266                                       sizeof(GlobalValue::GUID)));
267       Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
268                                       sizeof(GlobalValue::LinkageTypes)));
269     }
270 
271     // Include the hash for the preserved symbols.
272     for (auto &Entry : PreservedSymbols) {
273       if (DefinedFunctions.count(Entry))
274         Hasher.update(
275             ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
276     }
277 
278     sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
279   }
280 
281   // Access the path to this entry in the cache.
282   StringRef getEntryPath() { return EntryPath; }
283 
284   // Try loading the buffer for this cache entry.
285   ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
286     if (EntryPath.empty())
287       return std::error_code();
288     return MemoryBuffer::getFile(EntryPath);
289   }
290 
291   // Cache the Produced object file
292   std::unique_ptr<MemoryBuffer>
293   write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
294     if (EntryPath.empty())
295       return OutputBuffer;
296 
297     // Write to a temporary to avoid race condition
298     SmallString<128> TempFilename;
299     int TempFD;
300     std::error_code EC =
301         sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
302     if (EC) {
303       errs() << "Error: " << EC.message() << "\n";
304       report_fatal_error("ThinLTO: Can't get a temporary file");
305     }
306     {
307       raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
308       OS << OutputBuffer->getBuffer();
309     }
310     // Rename to final destination (hopefully race condition won't matter here)
311     EC = sys::fs::rename(TempFilename, EntryPath);
312     if (EC) {
313       sys::fs::remove(TempFilename);
314       raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
315       if (EC)
316         report_fatal_error(Twine("Failed to open ") + EntryPath +
317                            " to save cached entry\n");
318       OS << OutputBuffer->getBuffer();
319     }
320     auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
321     if (auto EC = ReloadedBufferOrErr.getError()) {
322       // FIXME diagnose
323       errs() << "error: can't reload cached file '" << EntryPath
324              << "': " << EC.message() << "\n";
325       return OutputBuffer;
326     }
327     return std::move(*ReloadedBufferOrErr);
328   }
329 };
330 
331 static std::unique_ptr<MemoryBuffer>
332 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
333                      StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
334                      const FunctionImporter::ImportMapTy &ImportList,
335                      const FunctionImporter::ExportSetTy &ExportList,
336                      const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
337                      const GVSummaryMapTy &DefinedGlobals,
338                      const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
339                      bool DisableCodeGen, StringRef SaveTempsDir,
340                      unsigned count) {
341 
342   // "Benchmark"-like optimization: single-source case
343   bool SingleModule = (ModuleMap.size() == 1);
344 
345   if (!SingleModule) {
346     promoteModule(TheModule, Index);
347 
348     // Apply summary-based LinkOnce/Weak resolution decisions.
349     thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
350 
351     // Save temps: after promotion.
352     saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
353   }
354 
355   // Be friendly and don't nuke totally the module when the client didn't
356   // supply anything to preserve.
357   if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
358     // Apply summary-based internalization decisions.
359     thinLTOInternalizeModule(TheModule, DefinedGlobals);
360   }
361 
362   // Save internalized bitcode
363   saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
364 
365   if (!SingleModule) {
366     crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
367 
368     // Save temps: after cross-module import.
369     saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
370   }
371 
372   optimizeModule(TheModule, TM);
373 
374   saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
375 
376   if (DisableCodeGen) {
377     // Configured to stop before CodeGen, serialize the bitcode and return.
378     SmallVector<char, 128> OutputBuffer;
379     {
380       raw_svector_ostream OS(OutputBuffer);
381       ModuleSummaryIndexBuilder IndexBuilder(&TheModule);
382       WriteBitcodeToFile(&TheModule, OS, true, &IndexBuilder.getIndex());
383     }
384     return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
385   }
386 
387   return codegenModule(TheModule, TM);
388 }
389 
390 /// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
391 /// for caching, and in the \p Index for application during the ThinLTO
392 /// backends. This is needed for correctness for exported symbols (ensure
393 /// at least one copy kept) and a compile-time optimization (to drop duplicate
394 /// copies when possible).
395 static void resolveWeakForLinkerInIndex(
396     ModuleSummaryIndex &Index,
397     const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
398     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
399     StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
400         &ResolvedODR) {
401 
402   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
403   computePrevailingCopies(Index, PrevailingCopy);
404 
405   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
406     const auto &Prevailing = PrevailingCopy.find(GUID);
407     // Not in map means that there was only one copy, which must be prevailing.
408     if (Prevailing == PrevailingCopy.end())
409       return true;
410     return Prevailing->second == S;
411   };
412 
413   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
414     const auto &ExportList = ExportLists.find(ModuleIdentifier);
415     return (ExportList != ExportLists.end() &&
416             ExportList->second.count(GUID)) ||
417            GUIDPreservedSymbols.count(GUID);
418   };
419 
420   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
421                               GlobalValue::GUID GUID,
422                               GlobalValue::LinkageTypes NewLinkage) {
423     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
424   };
425 
426   thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, isExported,
427                                      recordNewLinkage);
428 }
429 
430 // Initialize the TargetMachine builder for a given Triple
431 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
432                           const Triple &TheTriple) {
433   // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
434   // FIXME this looks pretty terrible...
435   if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
436     if (TheTriple.getArch() == llvm::Triple::x86_64)
437       TMBuilder.MCpu = "core2";
438     else if (TheTriple.getArch() == llvm::Triple::x86)
439       TMBuilder.MCpu = "yonah";
440     else if (TheTriple.getArch() == llvm::Triple::aarch64)
441       TMBuilder.MCpu = "cyclone";
442   }
443   TMBuilder.TheTriple = std::move(TheTriple);
444 }
445 
446 } // end anonymous namespace
447 
448 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
449   MemoryBufferRef Buffer(Data, Identifier);
450   if (Modules.empty()) {
451     // First module added, so initialize the triple and some options
452     LLVMContext Context;
453     Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
454     initTMBuilder(TMBuilder, Triple(TheTriple));
455   }
456 #ifndef NDEBUG
457   else {
458     LLVMContext Context;
459     assert(TMBuilder.TheTriple.str() ==
460                getBitcodeTargetTriple(Buffer, Context) &&
461            "ThinLTO modules with different triple not supported");
462   }
463 #endif
464   Modules.push_back(Buffer);
465 }
466 
467 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
468   PreservedSymbols.insert(Name);
469 }
470 
471 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
472   // FIXME: At the moment, we don't take advantage of this extra information,
473   // we're conservatively considering cross-references as preserved.
474   //  CrossReferencedSymbols.insert(Name);
475   PreservedSymbols.insert(Name);
476 }
477 
478 // TargetMachine factory
479 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
480   std::string ErrMsg;
481   const Target *TheTarget =
482       TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
483   if (!TheTarget) {
484     report_fatal_error("Can't load target for this Triple: " + ErrMsg);
485   }
486 
487   // Use MAttr as the default set of features.
488   SubtargetFeatures Features(MAttr);
489   Features.getDefaultSubtargetFeatures(TheTriple);
490   std::string FeatureStr = Features.getString();
491   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
492       TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
493       CodeModel::Default, CGOptLevel));
494 }
495 
496 /**
497  * Produce the combined summary index from all the bitcode files:
498  * "thin-link".
499  */
500 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
501   std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
502   uint64_t NextModuleId = 0;
503   for (auto &ModuleBuffer : Modules) {
504     ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
505         object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
506                                                      diagnosticHandler);
507     if (std::error_code EC = ObjOrErr.getError()) {
508       // FIXME diagnose
509       errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
510              << EC.message() << "\n";
511       return nullptr;
512     }
513     auto Index = (*ObjOrErr)->takeIndex();
514     if (CombinedIndex) {
515       CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
516     } else {
517       CombinedIndex = std::move(Index);
518     }
519   }
520   return CombinedIndex;
521 }
522 
523 /**
524  * Perform promotion and renaming of exported internal functions.
525  * Index is updated to reflect linkage changes from weak resolution.
526  */
527 void ThinLTOCodeGenerator::promote(Module &TheModule,
528                                    ModuleSummaryIndex &Index) {
529   auto ModuleCount = Index.modulePaths().size();
530   auto ModuleIdentifier = TheModule.getModuleIdentifier();
531   // Collect for each module the list of function it defines (GUID -> Summary).
532   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
533   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
534 
535   // Generate import/export list
536   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
537   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
538   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
539                            ExportLists);
540 
541   // Convert the preserved symbols set from string to GUID
542   auto GUIDPreservedSymbols =
543   computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
544 
545   // Resolve LinkOnce/Weak symbols.
546   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
547   resolveWeakForLinkerInIndex(Index, ExportLists, GUIDPreservedSymbols,
548                               ResolvedODR);
549 
550   thinLTOResolveWeakForLinkerModule(
551       TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
552 
553   promoteModule(TheModule, Index);
554 }
555 
556 /**
557  * Perform cross-module importing for the module identified by ModuleIdentifier.
558  */
559 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
560                                              ModuleSummaryIndex &Index) {
561   auto ModuleMap = generateModuleMap(Modules);
562   auto ModuleCount = Index.modulePaths().size();
563 
564   // Collect for each module the list of function it defines (GUID -> Summary).
565   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
566   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
567 
568   // Generate import/export list
569   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
570   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
571   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
572                            ExportLists);
573   auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
574 
575   crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
576 }
577 
578 /**
579  * Compute the list of summaries needed for importing into module.
580  */
581 void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
582     StringRef ModulePath, ModuleSummaryIndex &Index,
583     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
584   auto ModuleCount = Index.modulePaths().size();
585 
586   // Collect for each module the list of function it defines (GUID -> Summary).
587   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
588   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
589 
590   // Generate import/export list
591   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
592   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
593   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
594                            ExportLists);
595 
596   llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
597                                          ImportLists,
598                                          ModuleToSummariesForIndex);
599 }
600 
601 /**
602  * Emit the list of files needed for importing into module.
603  */
604 void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
605                                        StringRef OutputName,
606                                        ModuleSummaryIndex &Index) {
607   auto ModuleCount = Index.modulePaths().size();
608 
609   // Collect for each module the list of function it defines (GUID -> Summary).
610   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
611   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
612 
613   // Generate import/export list
614   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
615   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
616   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
617                            ExportLists);
618 
619   std::error_code EC;
620   if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists)))
621     report_fatal_error(Twine("Failed to open ") + OutputName +
622                        " to save imports lists\n");
623 }
624 
625 /**
626  * Perform internalization. Index is updated to reflect linkage changes.
627  */
628 void ThinLTOCodeGenerator::internalize(Module &TheModule,
629                                        ModuleSummaryIndex &Index) {
630   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
631   auto ModuleCount = Index.modulePaths().size();
632   auto ModuleIdentifier = TheModule.getModuleIdentifier();
633 
634   // Convert the preserved symbols set from string to GUID
635   auto GUIDPreservedSymbols =
636       computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
637 
638   // Collect for each module the list of function it defines (GUID -> Summary).
639   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
640   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
641 
642   // Generate import/export list
643   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
644   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
645   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
646                            ExportLists);
647   auto &ExportList = ExportLists[ModuleIdentifier];
648 
649   // Be friendly and don't nuke totally the module when the client didn't
650   // supply anything to preserve.
651   if (ExportList.empty() && GUIDPreservedSymbols.empty())
652     return;
653 
654   // Internalization
655   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
656     const auto &ExportList = ExportLists.find(ModuleIdentifier);
657     return (ExportList != ExportLists.end() &&
658             ExportList->second.count(GUID)) ||
659            GUIDPreservedSymbols.count(GUID);
660   };
661   thinLTOInternalizeAndPromoteInIndex(Index, isExported);
662   thinLTOInternalizeModule(TheModule,
663                            ModuleToDefinedGVSummaries[ModuleIdentifier]);
664 }
665 
666 /**
667  * Perform post-importing ThinLTO optimizations.
668  */
669 void ThinLTOCodeGenerator::optimize(Module &TheModule) {
670   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
671 
672   // Optimize now
673   optimizeModule(TheModule, *TMBuilder.create());
674 }
675 
676 /**
677  * Perform ThinLTO CodeGen.
678  */
679 std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
680   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
681   return codegenModule(TheModule, *TMBuilder.create());
682 }
683 
684 // Main entry point for the ThinLTO processing
685 void ThinLTOCodeGenerator::run() {
686   if (CodeGenOnly) {
687     // Perform only parallel codegen and return.
688     ThreadPool Pool;
689     assert(ProducedBinaries.empty() && "The generator should not be reused");
690     ProducedBinaries.resize(Modules.size());
691     int count = 0;
692     for (auto &ModuleBuffer : Modules) {
693       Pool.async([&](int count) {
694         LLVMContext Context;
695         Context.setDiscardValueNames(LTODiscardValueNames);
696 
697         // Parse module now
698         auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
699 
700         // CodeGen
701         ProducedBinaries[count] = codegen(*TheModule);
702       }, count++);
703     }
704 
705     return;
706   }
707 
708   // Sequential linking phase
709   auto Index = linkCombinedIndex();
710 
711   // Save temps: index.
712   if (!SaveTempsDir.empty()) {
713     auto SaveTempPath = SaveTempsDir + "index.bc";
714     std::error_code EC;
715     raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
716     if (EC)
717       report_fatal_error(Twine("Failed to open ") + SaveTempPath +
718                          " to save optimized bitcode\n");
719     WriteIndexToFile(*Index, OS);
720   }
721 
722   // Prepare the resulting object vector
723   assert(ProducedBinaries.empty() && "The generator should not be reused");
724   ProducedBinaries.resize(Modules.size());
725 
726   // Prepare the module map.
727   auto ModuleMap = generateModuleMap(Modules);
728   auto ModuleCount = Modules.size();
729 
730   // Collect for each module the list of function it defines (GUID -> Summary).
731   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
732   Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
733 
734   // Collect the import/export lists for all modules from the call-graph in the
735   // combined index.
736   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
737   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
738   ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
739                            ExportLists);
740 
741   // Convert the preserved symbols set from string to GUID, this is needed for
742   // computing the caching hash and the internalization.
743   auto GUIDPreservedSymbols =
744       computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
745 
746   // We use a std::map here to be able to have a defined ordering when
747   // producing a hash for the cache entry.
748   // FIXME: we should be able to compute the caching hash for the entry based
749   // on the index, and nuke this map.
750   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
751 
752   // Resolve LinkOnce/Weak symbols, this has to be computed early because it
753   // impacts the caching.
754   resolveWeakForLinkerInIndex(*Index, ExportLists, GUIDPreservedSymbols,
755                               ResolvedODR);
756 
757   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
758     const auto &ExportList = ExportLists.find(ModuleIdentifier);
759     return (ExportList != ExportLists.end() &&
760             ExportList->second.count(GUID)) ||
761            GUIDPreservedSymbols.count(GUID);
762   };
763 
764   // Use global summary-based analysis to identify symbols that can be
765   // internalized (because they aren't exported or preserved as per callback).
766   // Changes are made in the index, consumed in the ThinLTO backends.
767   thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
768 
769   // Make sure that every module has an entry in the ExportLists and
770   // ResolvedODR maps to enable threaded access to these maps below.
771   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
772     ExportLists[DefinedGVSummaries.first()];
773     ResolvedODR[DefinedGVSummaries.first()];
774   }
775 
776   // Compute the ordering we will process the inputs: the rough heuristic here
777   // is to sort them per size so that the largest module get schedule as soon as
778   // possible. This is purely a compile-time optimization.
779   std::vector<int> ModulesOrdering;
780   ModulesOrdering.resize(Modules.size());
781   std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
782   std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
783             [&](int LeftIndex, int RightIndex) {
784               auto LSize = Modules[LeftIndex].getBufferSize();
785               auto RSize = Modules[RightIndex].getBufferSize();
786               return LSize > RSize;
787             });
788 
789   // Parallel optimizer + codegen
790   {
791     ThreadPool Pool(ThreadCount);
792     for (auto IndexCount : ModulesOrdering) {
793       auto &ModuleBuffer = Modules[IndexCount];
794       Pool.async([&](int count) {
795         auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
796         auto &ExportList = ExportLists[ModuleIdentifier];
797 
798         auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
799 
800         // The module may be cached, this helps handling it.
801         ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
802                                     ImportLists[ModuleIdentifier], ExportList,
803                                     ResolvedODR[ModuleIdentifier],
804                                     DefinedFunctions, GUIDPreservedSymbols);
805 
806         {
807           auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
808           DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
809                        << CacheEntry.getEntryPath() << "' for buffer " << count
810                        << " " << ModuleIdentifier << "\n");
811 
812           if (ErrOrBuffer) {
813             // Cache Hit!
814             ProducedBinaries[count] = std::move(ErrOrBuffer.get());
815             return;
816           }
817         }
818 
819         LLVMContext Context;
820         Context.setDiscardValueNames(LTODiscardValueNames);
821         Context.enableDebugTypeODRUniquing();
822 
823         // Parse module now
824         auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
825 
826         // Save temps: original file.
827         saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
828 
829         auto &ImportList = ImportLists[ModuleIdentifier];
830         // Run the main process now, and generates a binary
831         auto OutputBuffer = ProcessThinLTOModule(
832             *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
833             ExportList, GUIDPreservedSymbols,
834             ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
835             DisableCodeGen, SaveTempsDir, count);
836 
837         OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
838         ProducedBinaries[count] = std::move(OutputBuffer);
839       }, IndexCount);
840     }
841   }
842 
843   CachePruning(CacheOptions.Path)
844       .setPruningInterval(CacheOptions.PruningInterval)
845       .setEntryExpiration(CacheOptions.Expiration)
846       .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
847       .prune();
848 
849   // If statistics were requested, print them out now.
850   if (llvm::AreStatisticsEnabled())
851     llvm::PrintStatistics();
852 }
853