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