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