blob: 51dcc084b4935da540c502351df59ae4c7bcbba6 [file] [log] [blame]
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001//===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Thin Link Time Optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/LTO/ThinLTOCodeGenerator.h"
16
Mehdi Aminif95f77a2016-04-21 05:54:23 +000017#ifdef HAVE_LLVM_REVISION
18#include "LLVMLTORevision.h"
19#endif
Mehdi Amini059464f2016-04-24 03:18:01 +000020
21#include "UpdateCompilerUsed.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000022#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000023#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000024#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000027#include "llvm/Bitcode/BitcodeWriterPass.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/Bitcode/ReaderWriter.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000029#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000030#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000031#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000032#include "llvm/IR/LegacyPassManager.h"
33#include "llvm/IR/Mangler.h"
34#include "llvm/IRReader/IRReader.h"
35#include "llvm/Linker/Linker.h"
36#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000037#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000038#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Amini1aafabf2016-04-16 07:02:16 +000039#include "llvm/Support/Debug.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000040#include "llvm/Support/CachePruning.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000044#include "llvm/Support/SourceMgr.h"
45#include "llvm/Support/TargetRegistry.h"
46#include "llvm/Support/ThreadPool.h"
47#include "llvm/Target/TargetMachine.h"
48#include "llvm/Transforms/IPO.h"
49#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000050#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000051#include "llvm/Transforms/IPO/PassManagerBuilder.h"
52#include "llvm/Transforms/ObjCARC.h"
53#include "llvm/Transforms/Utils/FunctionImportUtils.h"
54
55using namespace llvm;
56
Mehdi Amini1aafabf2016-04-16 07:02:16 +000057#define DEBUG_TYPE "thinlto"
58
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000059namespace llvm {
60// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
61extern cl::opt<bool> LTODiscardValueNames;
62}
63
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000064namespace {
65
66static cl::opt<int> ThreadCount("threads",
67 cl::init(std::thread::hardware_concurrency()));
68
69static void diagnosticHandler(const DiagnosticInfo &DI) {
70 DiagnosticPrinterRawOStream DP(errs());
71 DI.print(DP);
72 errs() << '\n';
73}
74
75// Simple helper to load a module from bitcode
76static std::unique_ptr<Module>
77loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
78 bool Lazy) {
79 SMDiagnostic Err;
80 ErrorOr<std::unique_ptr<Module>> ModuleOrErr(nullptr);
81 if (Lazy) {
82 ModuleOrErr =
83 getLazyBitcodeModule(MemoryBuffer::getMemBuffer(Buffer, false), Context,
84 /* ShouldLazyLoadMetadata */ Lazy);
85 } else {
86 ModuleOrErr = parseBitcodeFile(Buffer, Context);
87 }
88 if (std::error_code EC = ModuleOrErr.getError()) {
89 Err = SMDiagnostic(Buffer.getBufferIdentifier(), SourceMgr::DK_Error,
90 EC.message());
91 Err.print("ThinLTO", errs());
92 report_fatal_error("Can't load module, abort.");
93 }
94 return std::move(ModuleOrErr.get());
95}
96
97// Simple helper to save temporary files for debug.
98static 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 auto SaveTempPath = TempDir + llvm::utostr(count) + Suffix;
104 std::error_code EC;
105 raw_fd_ostream OS(SaveTempPath.str(), EC, sys::fs::F_None);
106 if (EC)
107 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
108 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +0000109 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000110}
111
Teresa Johnson28e457b2016-04-24 14:57:11 +0000112bool IsFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList,
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000113 const ModuleSummaryIndex &Index,
114 StringRef ModulePath) {
115 // Get the first *linker visible* definition for this global in the summary
116 // list.
117 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000118 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
119 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000120 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
121 });
122 // If \p GV is not the first definition, give up...
Teresa Johnson28e457b2016-04-24 14:57:11 +0000123 if ((*FirstDefForLinker)->modulePath() != ModulePath)
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000124 return false;
125 // If there is any strong definition anywhere, do not bother emitting this.
126 if (llvm::any_of(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000127 GVSummaryList,
128 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
129 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000130 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
131 !GlobalValue::isWeakForLinker(Linkage);
132 }))
133 return false;
134 return true;
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000135}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000136
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000137static GlobalValue::LinkageTypes
138ResolveODR(const ModuleSummaryIndex &Index,
139 const FunctionImporter::ExportSetTy &ExportList,
140 StringRef ModuleIdentifier, GlobalValue::GUID GUID,
141 const GlobalValueSummary &GV) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000142 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
143 return GVSummaryList.size() > 1;
144 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000145
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000146 auto OriginalLinkage = GV.linkage();
147 switch (OriginalLinkage) {
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000148 case GlobalValue::ExternalLinkage:
149 case GlobalValue::AvailableExternallyLinkage:
150 case GlobalValue::AppendingLinkage:
151 case GlobalValue::InternalLinkage:
152 case GlobalValue::PrivateLinkage:
153 case GlobalValue::ExternalWeakLinkage:
154 case GlobalValue::CommonLinkage:
155 case GlobalValue::LinkOnceAnyLinkage:
156 case GlobalValue::WeakAnyLinkage:
157 break;
158 case GlobalValue::LinkOnceODRLinkage:
159 case GlobalValue::WeakODRLinkage: {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000160 auto &GVSummaryList = Index.findGlobalValueSummaryList(GUID)->second;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000161 // We need to emit only one of these, the first module will keep
162 // it, but turned into a weak while the others will drop it.
Teresa Johnson28e457b2016-04-24 14:57:11 +0000163 if (!HasMultipleCopies(GVSummaryList)) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000164 // Exported LinkonceODR needs to be promoted to not be discarded
165 if (GlobalValue::isDiscardableIfUnused(OriginalLinkage) &&
166 ExportList.count(GUID))
167 return GlobalValue::WeakODRLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000168 break;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000169 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000170 if (IsFirstDefinitionForLinker(GVSummaryList, Index, ModuleIdentifier))
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000171 return GlobalValue::WeakODRLinkage;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000172 else if (isa<AliasSummary>(&GV))
173 // Alias can't be turned into available_externally.
174 return OriginalLinkage;
175 return GlobalValue::AvailableExternallyLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000176 }
177 }
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000178 return OriginalLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000179}
180
181/// Resolve LinkOnceODR and WeakODR.
182///
183/// We'd like to drop these function if they are no longer referenced in the
184/// current module. However there is a chance that another module is still
185/// referencing them because of the import. We make sure we always emit at least
186/// one copy.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000187static void ResolveODR(
188 const ModuleSummaryIndex &Index,
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000189 const FunctionImporter::ExportSetTy &ExportList,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000190 const GVSummaryMapTy &DefinedGlobals, StringRef ModuleIdentifier,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000191 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
Mehdi Amini8dcc8082016-04-14 08:46:22 +0000192 if (Index.modulePaths().size() == 1)
193 // Nothing to do if we don't have multiple modules
194 return;
195
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000196 // We won't optimize the globals that are referenced by an alias for now
197 // Ideally we should turn the alias into a global and duplicate the definition
198 // when needed.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000199 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
200 for (auto &GA : DefinedGlobals) {
201 if (auto AS = dyn_cast<AliasSummary>(GA.second))
202 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000203 }
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000204
205 for (auto &GV : DefinedGlobals) {
206 if (GlobalInvolvedWithAlias.count(GV.second))
207 continue;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000208 auto NewLinkage =
209 ResolveODR(Index, ExportList, ModuleIdentifier, GV.first, *GV.second);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000210 if (NewLinkage != GV.second->linkage()) {
211 ResolvedODR[GV.first] = NewLinkage;
212 }
213 }
214}
215
216/// Fixup linkage, see ResolveODR() above.
217void fixupODR(
218 Module &TheModule,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000219 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000220 // Process functions and global now
221 for (auto &GV : TheModule) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000222 auto NewLinkage = ResolvedODR.find(GV.getGUID());
223 if (NewLinkage == ResolvedODR.end())
224 continue;
225 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
226 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
227 GV.setLinkage(NewLinkage->second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000228 }
229 for (auto &GV : TheModule.globals()) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000230 auto NewLinkage = ResolvedODR.find(GV.getGUID());
231 if (NewLinkage == ResolvedODR.end())
232 continue;
233 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
234 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
235 GV.setLinkage(NewLinkage->second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000236 }
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000237 for (auto &GV : TheModule.aliases()) {
238 auto NewLinkage = ResolvedODR.find(GV.getGUID());
239 if (NewLinkage == ResolvedODR.end())
240 continue;
241 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
242 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
243 GV.setLinkage(NewLinkage->second);
244 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000245}
246
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000247static StringMap<MemoryBufferRef>
248generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
249 StringMap<MemoryBufferRef> ModuleMap;
250 for (auto &ModuleBuffer : Modules) {
251 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
252 ModuleMap.end() &&
253 "Expect unique Buffer Identifier");
254 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
255 }
256 return ModuleMap;
257}
258
259/// Provide a "loader" for the FunctionImporter to access function from other
260/// modules.
261class ModuleLoader {
262 /// The context that will be used for importing.
263 LLVMContext &Context;
264
265 /// Map from Module identifier to MemoryBuffer. Used by clients like the
266 /// FunctionImported to request loading a Module.
267 StringMap<MemoryBufferRef> &ModuleMap;
268
269public:
270 ModuleLoader(LLVMContext &Context, StringMap<MemoryBufferRef> &ModuleMap)
271 : Context(Context), ModuleMap(ModuleMap) {}
272
273 /// Load a module on demand.
274 std::unique_ptr<Module> operator()(StringRef Identifier) {
275 return loadModuleFromBuffer(ModuleMap[Identifier], Context, /*Lazy*/ true);
276 }
277};
278
Teresa Johnson26ab5772016-03-15 00:04:37 +0000279static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000280 if (renameModuleForThinLTO(TheModule, Index))
281 report_fatal_error("renameModuleForThinLTO failed");
282}
283
Mehdi Amini01e32132016-03-26 05:40:34 +0000284static void
285crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
286 StringMap<MemoryBufferRef> &ModuleMap,
287 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000288 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
289 FunctionImporter Importer(Index, Loader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000290 Importer.importFunctions(TheModule, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000291}
292
293static void optimizeModule(Module &TheModule, TargetMachine &TM) {
294 // Populate the PassManager
295 PassManagerBuilder PMB;
296 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
297 PMB.Inliner = createFunctionInliningPass();
298 // FIXME: should get it from the bitcode?
299 PMB.OptLevel = 3;
300 PMB.LoopVectorize = true;
301 PMB.SLPVectorize = true;
302 PMB.VerifyInput = true;
303 PMB.VerifyOutput = false;
304
305 legacy::PassManager PM;
306
307 // Add the TTI (required to inform the vectorizer about register size for
308 // instance)
309 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
310
311 // Add optimizations
312 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000313
314 PM.run(TheModule);
315}
316
Mehdi Amini059464f2016-04-24 03:18:01 +0000317// Create a DenseSet of GlobalValue to be used with the Internalizer.
318static DenseSet<const GlobalValue *> computePreservedSymbolsForModule(
319 Module &TheModule, const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
320 const FunctionImporter::ExportSetTy &ExportList) {
321 DenseSet<const GlobalValue *> PreservedGV;
322 if (GUIDPreservedSymbols.empty())
323 // Early exit: internalize is disabled when there is nothing to preserve.
324 return PreservedGV;
325
326 auto AddPreserveGV = [&](const GlobalValue &GV) {
327 auto GUID = GV.getGUID();
328 if (GUIDPreservedSymbols.count(GUID) || ExportList.count(GUID))
329 PreservedGV.insert(&GV);
330 };
331
332 for (auto &GV : TheModule)
333 AddPreserveGV(GV);
334 for (auto &GV : TheModule.globals())
335 AddPreserveGV(GV);
336 for (auto &GV : TheModule.aliases())
337 AddPreserveGV(GV);
338
339 return PreservedGV;
340}
341
342// Run internalization on \p TheModule
343static void
344doInternalizeModule(Module &TheModule, const TargetMachine &TM,
345 const DenseSet<const GlobalValue *> &PreservedGV) {
346 if (PreservedGV.empty()) {
347 // Be friendly and don't nuke totally the module when the client didn't
348 // supply anything to preserve.
349 return;
350 }
351
352 // Parse inline ASM and collect the list of symbols that are not defined in
353 // the current module.
354 StringSet<> AsmUndefinedRefs;
355 object::IRObjectFile::CollectAsmUndefinedRefs(
356 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
357 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
358 if (Flags & object::BasicSymbolRef::SF_Undefined)
359 AsmUndefinedRefs.insert(Name);
360 });
361
362 // Update the llvm.compiler_used globals to force preserving libcalls and
363 // symbols referenced from asm
364 UpdateCompilerUsed(TheModule, TM, AsmUndefinedRefs);
365
366 // Declare a callback for the internalize pass that will ask for every
367 // candidate GlobalValue if it can be internalized or not.
368 auto MustPreserveGV =
369 [&](const GlobalValue &GV) -> bool { return PreservedGV.count(&GV); };
370
371 llvm::internalizeModule(TheModule, MustPreserveGV);
372}
373
374// Convert the PreservedSymbols map from "Name" based to "GUID" based.
375static DenseSet<GlobalValue::GUID>
376computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
377 const Triple &TheTriple) {
378 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
379 for (auto &Entry : PreservedSymbols) {
380 StringRef Name = Entry.first();
381 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
382 Name = Name.drop_front();
383 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
384 }
385 return GUIDPreservedSymbols;
386}
387
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000388std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
389 TargetMachine &TM) {
390 SmallVector<char, 128> OutputBuffer;
391
392 // CodeGen
393 {
394 raw_svector_ostream OS(OutputBuffer);
395 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000396
397 // If the bitcode files contain ARC code and were compiled with optimization,
398 // the ObjCARCContractPass must be run, so do it unconditionally here.
399 PM.add(createObjCARCContractPass());
400
401 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000402 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
403 /* DisableVerify */ true))
404 report_fatal_error("Failed to setup codegen");
405
406 // Run codegen now. resulting binary is in OutputBuffer.
407 PM.run(TheModule);
408 }
409 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
410}
411
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000412/// Manage caching for a single Module.
413class ModuleCacheEntry {
414 SmallString<128> EntryPath;
415
416public:
417 // Create a cache entry. This compute a unique hash for the Module considering
418 // the current list of export/import, and offer an interface to query to
419 // access the content in the cache.
420 ModuleCacheEntry(
421 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
422 const FunctionImporter::ImportMapTy &ImportList,
423 const FunctionImporter::ExportSetTy &ExportList,
424 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000425 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000426 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
427 if (CachePath.empty())
428 return;
429
430 // Compute the unique hash for this entry
431 // This is based on the current compiler version, the module itself, the
432 // export list, the hash for every single module in the import list, the
433 // list of ResolvedODR for the module, and the list of preserved symbols.
434
435 SHA1 Hasher;
436
437 // Start with the compiler revision
438 Hasher.update(LLVM_VERSION_STRING);
439#ifdef HAVE_LLVM_REVISION
440 Hasher.update(LLVM_REVISION);
441#endif
442
443 // Include the hash for the current module
444 auto ModHash = Index.getModuleHash(ModuleID);
445 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
446 for (auto F : ExportList)
447 // The export list can impact the internalization, be conservative here
448 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
449
450 // Include the hash for every module we import functions from
451 for (auto &Entry : ImportList) {
452 auto ModHash = Index.getModuleHash(Entry.first());
453 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
454 }
455
456 // Include the hash for the resolved ODR.
457 for (auto &Entry : ResolvedODR) {
458 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Entry.first,
459 sizeof(GlobalValue::GUID)));
460 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Entry.second,
461 sizeof(GlobalValue::LinkageTypes)));
462 }
463
464 // Include the hash for the preserved symbols.
465 for (auto &Entry : PreservedSymbols) {
466 if (DefinedFunctions.count(Entry))
467 Hasher.update(
468 ArrayRef<uint8_t>((uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
469 }
470
471 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
472 }
473
Mehdi Amini059464f2016-04-24 03:18:01 +0000474 // Access the path to this entry in the cache.
475 StringRef getEntryPath() { return EntryPath; }
476
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000477 // Try loading the buffer for this cache entry.
478 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
479 if (EntryPath.empty())
480 return std::error_code();
481 return MemoryBuffer::getFile(EntryPath);
482 }
483
484 // Cache the Produced object file
485 void write(MemoryBufferRef OutputBuffer) {
486 if (EntryPath.empty())
487 return;
488
489 // Write to a temporary to avoid race condition
490 SmallString<128> TempFilename;
491 int TempFD;
492 std::error_code EC =
493 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
494 if (EC) {
495 errs() << "Error: " << EC.message() << "\n";
496 report_fatal_error("ThinLTO: Can't get a temporary file");
497 }
498 {
499 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
500 OS << OutputBuffer.getBuffer();
501 }
502 // Rename to final destination (hopefully race condition won't matter here)
503 sys::fs::rename(TempFilename, EntryPath);
504 }
505};
506
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000507static std::unique_ptr<MemoryBuffer> ProcessThinLTOModule(
508 Module &TheModule, const ModuleSummaryIndex &Index,
509 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
510 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Amini059464f2016-04-24 03:18:01 +0000511 const FunctionImporter::ExportSetTy &ExportList,
512 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000513 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000514 ThinLTOCodeGenerator::CachingOptions CacheOptions, bool DisableCodeGen,
515 StringRef SaveTempsDir, unsigned count) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000516
517 // Save temps: after IPO.
518 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.IPO.bc");
519
Mehdi Amini059464f2016-04-24 03:18:01 +0000520 // Prepare for internalization by computing the set of symbols to preserve.
521 // We need to compute the list of symbols to preserve during internalization
522 // before doing any promotion because after renaming we won't (easily) match
523 // to the original name.
524 auto PreservedGV = computePreservedSymbolsForModule(
525 TheModule, GUIDPreservedSymbols, ExportList);
526
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000527 // "Benchmark"-like optimization: single-source case
528 bool SingleModule = (ModuleMap.size() == 1);
529
530 if (!SingleModule) {
531 promoteModule(TheModule, Index);
532
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000533 // Resolve the LinkOnce/Weak ODR, trying to turn them into
534 // "available_externally" when possible.
535 // This is a compile-time optimization.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000536 fixupODR(TheModule, ResolvedODR);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000537
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000538 // Save temps: after promotion.
539 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000540 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000541
Mehdi Amini059464f2016-04-24 03:18:01 +0000542 // Internalization
543 doInternalizeModule(TheModule, TM, PreservedGV);
544
545 // Save internalized bitcode
546 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.internalized.bc");
547
548 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000549 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000550
551 // Save temps: after cross-module import.
Mehdi Amini059464f2016-04-24 03:18:01 +0000552 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000553 }
554
555 optimizeModule(TheModule, TM);
556
Mehdi Amini059464f2016-04-24 03:18:01 +0000557 saveTempBitcode(TheModule, SaveTempsDir, count, ".5.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000558
Mehdi Amini43b657b2016-04-01 06:47:02 +0000559 if (DisableCodeGen) {
560 // Configured to stop before CodeGen, serialize the bitcode and return.
561 SmallVector<char, 128> OutputBuffer;
562 {
563 raw_svector_ostream OS(OutputBuffer);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000564 ModuleSummaryIndexBuilder IndexBuilder(&TheModule);
565 WriteBitcodeToFile(&TheModule, OS, true, &IndexBuilder.getIndex());
Mehdi Amini43b657b2016-04-01 06:47:02 +0000566 }
567 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
568 }
569
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000570 return codegenModule(TheModule, TM);
571}
572
573// Initialize the TargetMachine builder for a given Triple
574static void initTMBuilder(TargetMachineBuilder &TMBuilder,
575 const Triple &TheTriple) {
576 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
577 // FIXME this looks pretty terrible...
578 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
579 if (TheTriple.getArch() == llvm::Triple::x86_64)
580 TMBuilder.MCpu = "core2";
581 else if (TheTriple.getArch() == llvm::Triple::x86)
582 TMBuilder.MCpu = "yonah";
583 else if (TheTriple.getArch() == llvm::Triple::aarch64)
584 TMBuilder.MCpu = "cyclone";
585 }
586 TMBuilder.TheTriple = std::move(TheTriple);
587}
588
589} // end anonymous namespace
590
591void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
592 MemoryBufferRef Buffer(Data, Identifier);
593 if (Modules.empty()) {
594 // First module added, so initialize the triple and some options
595 LLVMContext Context;
596 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
597 initTMBuilder(TMBuilder, Triple(TheTriple));
598 }
599#ifndef NDEBUG
600 else {
601 LLVMContext Context;
602 assert(TMBuilder.TheTriple.str() ==
603 getBitcodeTargetTriple(Buffer, Context) &&
604 "ThinLTO modules with different triple not supported");
605 }
606#endif
607 Modules.push_back(Buffer);
608}
609
610void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
611 PreservedSymbols.insert(Name);
612}
613
614void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000615 // FIXME: At the moment, we don't take advantage of this extra information,
616 // we're conservatively considering cross-references as preserved.
617 // CrossReferencedSymbols.insert(Name);
618 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000619}
620
621// TargetMachine factory
622std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
623 std::string ErrMsg;
624 const Target *TheTarget =
625 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
626 if (!TheTarget) {
627 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
628 }
629
630 // Use MAttr as the default set of features.
631 SubtargetFeatures Features(MAttr);
632 Features.getDefaultSubtargetFeatures(TheTriple);
633 std::string FeatureStr = Features.getString();
634 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
635 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
636 CodeModel::Default, CGOptLevel));
637}
638
639/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000640 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000641 * "thin-link".
642 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000643std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
644 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000645 uint64_t NextModuleId = 0;
646 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000647 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
648 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000649 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000650 if (std::error_code EC = ObjOrErr.getError()) {
651 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000652 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000653 << EC.message() << "\n";
654 return nullptr;
655 }
656 auto Index = (*ObjOrErr)->takeIndex();
657 if (CombinedIndex) {
658 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
659 } else {
660 CombinedIndex = std::move(Index);
661 }
662 }
663 return CombinedIndex;
664}
665
666/**
667 * Perform promotion and renaming of exported internal functions.
668 */
669void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000670 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000671 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000672 auto ModuleIdentifier = TheModule.getModuleIdentifier();
673 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000674 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000675 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000676
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000677 // Generate import/export list
678 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
679 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
680 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
681 ExportLists);
682 auto &ExportList = ExportLists[ModuleIdentifier];
683
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000684 // Resolve the LinkOnceODR, trying to turn them into "available_externally"
685 // where possible.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000686 // This is a compile-time optimization.
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000687 // We use a std::map here to be able to have a defined ordering when
688 // producing a hash for the cache entry.
689 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000690 ResolveODR(Index, ExportList, ModuleToDefinedGVSummaries[ModuleIdentifier],
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000691 ModuleIdentifier, ResolvedODR);
692 fixupODR(TheModule, ResolvedODR);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000693
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000694 promoteModule(TheModule, Index);
695}
696
697/**
698 * Perform cross-module importing for the module identified by ModuleIdentifier.
699 */
700void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000701 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000702 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000703 auto ModuleCount = Index.modulePaths().size();
704
705 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000706 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000707 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000708
709 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000710 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
711 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000712 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
713 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000714 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
715
716 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000717}
718
719/**
Mehdi Amini059464f2016-04-24 03:18:01 +0000720 * Perform internalization.
721 */
722void ThinLTOCodeGenerator::internalize(Module &TheModule,
723 ModuleSummaryIndex &Index) {
724 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
725 auto ModuleCount = Index.modulePaths().size();
726 auto ModuleIdentifier = TheModule.getModuleIdentifier();
727
728 // Convert the preserved symbols set from string to GUID
729 auto GUIDPreservedSymbols =
730 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
731
732 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000733 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000734 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
735
736 // Generate import/export list
737 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
738 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
739 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
740 ExportLists);
741 auto &ExportList = ExportLists[ModuleIdentifier];
742
743 // Internalization
744 auto PreservedGV = computePreservedSymbolsForModule(
745 TheModule, GUIDPreservedSymbols, ExportList);
746 doInternalizeModule(TheModule, *TMBuilder.create(), PreservedGV);
747}
748
749/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000750 * Perform post-importing ThinLTO optimizations.
751 */
752void ThinLTOCodeGenerator::optimize(Module &TheModule) {
753 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000754
755 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000756 optimizeModule(TheModule, *TMBuilder.create());
757}
758
759/**
760 * Perform ThinLTO CodeGen.
761 */
762std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
763 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
764 return codegenModule(TheModule, *TMBuilder.create());
765}
766
767// Main entry point for the ThinLTO processing
768void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000769 if (CodeGenOnly) {
770 // Perform only parallel codegen and return.
771 ThreadPool Pool;
772 assert(ProducedBinaries.empty() && "The generator should not be reused");
773 ProducedBinaries.resize(Modules.size());
774 int count = 0;
775 for (auto &ModuleBuffer : Modules) {
776 Pool.async([&](int count) {
777 LLVMContext Context;
778 Context.setDiscardValueNames(LTODiscardValueNames);
779
780 // Parse module now
781 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
782
783 // CodeGen
784 ProducedBinaries[count] = codegen(*TheModule);
785 }, count++);
786 }
787
788 return;
789 }
790
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000791 // Sequential linking phase
792 auto Index = linkCombinedIndex();
793
794 // Save temps: index.
795 if (!SaveTempsDir.empty()) {
796 auto SaveTempPath = SaveTempsDir + "index.bc";
797 std::error_code EC;
798 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
799 if (EC)
800 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
801 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000802 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000803 }
804
805 // Prepare the resulting object vector
806 assert(ProducedBinaries.empty() && "The generator should not be reused");
807 ProducedBinaries.resize(Modules.size());
808
809 // Prepare the module map.
810 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000811 auto ModuleCount = Modules.size();
812
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000813 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000814 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000815 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
816
Mehdi Amini01e32132016-03-26 05:40:34 +0000817 // Collect the import/export lists for all modules from the call-graph in the
818 // combined index.
819 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
820 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000821 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
822 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000823
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000824 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000825 // computing the caching hash and the internalization.
826 auto GUIDPreservedSymbols =
827 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000828
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000829 // Parallel optimizer + codegen
830 {
831 ThreadPool Pool(ThreadCount);
832 int count = 0;
833 for (auto &ModuleBuffer : Modules) {
834 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000835 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000836 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000837
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000838 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
839
840 // Resolve ODR, this has to be done early because it impacts the caching
841 // We use a std::map here to be able to have a defined ordering when
842 // producing a hash for the cache entry.
843 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
Mehdi Amini059464f2016-04-24 03:18:01 +0000844 ResolveODR(*Index, ExportList, DefinedFunctions, ModuleIdentifier,
845 ResolvedODR);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000846
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000847 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000848 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
849 ImportLists[ModuleIdentifier], ExportList,
850 ResolvedODR, DefinedFunctions,
851 GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000852
853 {
854 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000855 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
856 << CacheEntry.getEntryPath() << "' for buffer " << count
857 << " " << ModuleIdentifier << "\n");
858
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000859 if (ErrOrBuffer) {
860 // Cache Hit!
861 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
862 return;
863 }
864 }
865
866 LLVMContext Context;
867 Context.setDiscardValueNames(LTODiscardValueNames);
868 Context.enableDebugTypeODRUniquing();
869
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000870 // Parse module now
871 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
872
873 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000874 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000875
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000876 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000877 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000878 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000879 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Mehdi Amini059464f2016-04-24 03:18:01 +0000880 ExportList, GUIDPreservedSymbols, ResolvedODR, CacheOptions,
881 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000882
883 CacheEntry.write(*OutputBuffer);
884 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000885 }, count);
886 count++;
887 }
888 }
889
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000890 CachePruning(CacheOptions.Path)
891 .setPruningInterval(CacheOptions.PruningInterval)
892 .setEntryExpiration(CacheOptions.Expiration)
893 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
894 .prune();
895
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000896 // If statistics were requested, print them out now.
897 if (llvm::AreStatisticsEnabled())
898 llvm::PrintStatistics();
899}