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