blob: 21ba1e92a3ab4fa9e6bbe203cf5be0336236e636 [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,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000190 const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedGlobals,
191 StringRef ModuleIdentifier,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000192 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
Mehdi Amini8dcc8082016-04-14 08:46:22 +0000193 if (Index.modulePaths().size() == 1)
194 // Nothing to do if we don't have multiple modules
195 return;
196
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000197 // We won't optimize the globals that are referenced by an alias for now
198 // Ideally we should turn the alias into a global and duplicate the definition
199 // when needed.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000200 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
201 for (auto &GA : DefinedGlobals) {
202 if (auto AS = dyn_cast<AliasSummary>(GA.second))
203 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000204 }
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000205
206 for (auto &GV : DefinedGlobals) {
207 if (GlobalInvolvedWithAlias.count(GV.second))
208 continue;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000209 auto NewLinkage =
210 ResolveODR(Index, ExportList, ModuleIdentifier, GV.first, *GV.second);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000211 if (NewLinkage != GV.second->linkage()) {
212 ResolvedODR[GV.first] = NewLinkage;
213 }
214 }
215}
216
217/// Fixup linkage, see ResolveODR() above.
218void fixupODR(
219 Module &TheModule,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000220 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000221 // Process functions and global now
222 for (auto &GV : TheModule) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000223 auto NewLinkage = ResolvedODR.find(GV.getGUID());
224 if (NewLinkage == ResolvedODR.end())
225 continue;
226 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
227 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
228 GV.setLinkage(NewLinkage->second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000229 }
230 for (auto &GV : TheModule.globals()) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000231 auto NewLinkage = ResolvedODR.find(GV.getGUID());
232 if (NewLinkage == ResolvedODR.end())
233 continue;
234 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
235 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
236 GV.setLinkage(NewLinkage->second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000237 }
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000238 for (auto &GV : TheModule.aliases()) {
239 auto NewLinkage = ResolvedODR.find(GV.getGUID());
240 if (NewLinkage == ResolvedODR.end())
241 continue;
242 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
243 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
244 GV.setLinkage(NewLinkage->second);
245 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000246}
247
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000248static StringMap<MemoryBufferRef>
249generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
250 StringMap<MemoryBufferRef> ModuleMap;
251 for (auto &ModuleBuffer : Modules) {
252 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
253 ModuleMap.end() &&
254 "Expect unique Buffer Identifier");
255 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
256 }
257 return ModuleMap;
258}
259
260/// Provide a "loader" for the FunctionImporter to access function from other
261/// modules.
262class ModuleLoader {
263 /// The context that will be used for importing.
264 LLVMContext &Context;
265
266 /// Map from Module identifier to MemoryBuffer. Used by clients like the
267 /// FunctionImported to request loading a Module.
268 StringMap<MemoryBufferRef> &ModuleMap;
269
270public:
271 ModuleLoader(LLVMContext &Context, StringMap<MemoryBufferRef> &ModuleMap)
272 : Context(Context), ModuleMap(ModuleMap) {}
273
274 /// Load a module on demand.
275 std::unique_ptr<Module> operator()(StringRef Identifier) {
276 return loadModuleFromBuffer(ModuleMap[Identifier], Context, /*Lazy*/ true);
277 }
278};
279
Teresa Johnson26ab5772016-03-15 00:04:37 +0000280static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000281 if (renameModuleForThinLTO(TheModule, Index))
282 report_fatal_error("renameModuleForThinLTO failed");
283}
284
Mehdi Amini01e32132016-03-26 05:40:34 +0000285static void
286crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
287 StringMap<MemoryBufferRef> &ModuleMap,
288 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000289 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
290 FunctionImporter Importer(Index, Loader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000291 Importer.importFunctions(TheModule, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000292}
293
294static void optimizeModule(Module &TheModule, TargetMachine &TM) {
295 // Populate the PassManager
296 PassManagerBuilder PMB;
297 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
298 PMB.Inliner = createFunctionInliningPass();
299 // FIXME: should get it from the bitcode?
300 PMB.OptLevel = 3;
301 PMB.LoopVectorize = true;
302 PMB.SLPVectorize = true;
303 PMB.VerifyInput = true;
304 PMB.VerifyOutput = false;
305
306 legacy::PassManager PM;
307
308 // Add the TTI (required to inform the vectorizer about register size for
309 // instance)
310 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
311
312 // Add optimizations
313 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000314
315 PM.run(TheModule);
316}
317
Mehdi Amini059464f2016-04-24 03:18:01 +0000318// Create a DenseSet of GlobalValue to be used with the Internalizer.
319static DenseSet<const GlobalValue *> computePreservedSymbolsForModule(
320 Module &TheModule, const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
321 const FunctionImporter::ExportSetTy &ExportList) {
322 DenseSet<const GlobalValue *> PreservedGV;
323 if (GUIDPreservedSymbols.empty())
324 // Early exit: internalize is disabled when there is nothing to preserve.
325 return PreservedGV;
326
327 auto AddPreserveGV = [&](const GlobalValue &GV) {
328 auto GUID = GV.getGUID();
329 if (GUIDPreservedSymbols.count(GUID) || ExportList.count(GUID))
330 PreservedGV.insert(&GV);
331 };
332
333 for (auto &GV : TheModule)
334 AddPreserveGV(GV);
335 for (auto &GV : TheModule.globals())
336 AddPreserveGV(GV);
337 for (auto &GV : TheModule.aliases())
338 AddPreserveGV(GV);
339
340 return PreservedGV;
341}
342
343// Run internalization on \p TheModule
344static void
345doInternalizeModule(Module &TheModule, const TargetMachine &TM,
346 const DenseSet<const GlobalValue *> &PreservedGV) {
347 if (PreservedGV.empty()) {
348 // Be friendly and don't nuke totally the module when the client didn't
349 // supply anything to preserve.
350 return;
351 }
352
353 // Parse inline ASM and collect the list of symbols that are not defined in
354 // the current module.
355 StringSet<> AsmUndefinedRefs;
356 object::IRObjectFile::CollectAsmUndefinedRefs(
357 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
358 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
359 if (Flags & object::BasicSymbolRef::SF_Undefined)
360 AsmUndefinedRefs.insert(Name);
361 });
362
363 // Update the llvm.compiler_used globals to force preserving libcalls and
364 // symbols referenced from asm
365 UpdateCompilerUsed(TheModule, TM, AsmUndefinedRefs);
366
367 // Declare a callback for the internalize pass that will ask for every
368 // candidate GlobalValue if it can be internalized or not.
369 auto MustPreserveGV =
370 [&](const GlobalValue &GV) -> bool { return PreservedGV.count(&GV); };
371
372 llvm::internalizeModule(TheModule, MustPreserveGV);
373}
374
375// Convert the PreservedSymbols map from "Name" based to "GUID" based.
376static DenseSet<GlobalValue::GUID>
377computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
378 const Triple &TheTriple) {
379 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
380 for (auto &Entry : PreservedSymbols) {
381 StringRef Name = Entry.first();
382 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
383 Name = Name.drop_front();
384 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
385 }
386 return GUIDPreservedSymbols;
387}
388
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000389std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
390 TargetMachine &TM) {
391 SmallVector<char, 128> OutputBuffer;
392
393 // CodeGen
394 {
395 raw_svector_ostream OS(OutputBuffer);
396 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000397
398 // If the bitcode files contain ARC code and were compiled with optimization,
399 // the ObjCARCContractPass must be run, so do it unconditionally here.
400 PM.add(createObjCARCContractPass());
401
402 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000403 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
404 /* DisableVerify */ true))
405 report_fatal_error("Failed to setup codegen");
406
407 // Run codegen now. resulting binary is in OutputBuffer.
408 PM.run(TheModule);
409 }
410 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
411}
412
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000413/// Manage caching for a single Module.
414class ModuleCacheEntry {
415 SmallString<128> EntryPath;
416
417public:
418 // Create a cache entry. This compute a unique hash for the Module considering
419 // the current list of export/import, and offer an interface to query to
420 // access the content in the cache.
421 ModuleCacheEntry(
422 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
423 const FunctionImporter::ImportMapTy &ImportList,
424 const FunctionImporter::ExportSetTy &ExportList,
425 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
426 const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedFunctions,
427 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
428 if (CachePath.empty())
429 return;
430
431 // Compute the unique hash for this entry
432 // This is based on the current compiler version, the module itself, the
433 // export list, the hash for every single module in the import list, the
434 // list of ResolvedODR for the module, and the list of preserved symbols.
435
436 SHA1 Hasher;
437
438 // Start with the compiler revision
439 Hasher.update(LLVM_VERSION_STRING);
440#ifdef HAVE_LLVM_REVISION
441 Hasher.update(LLVM_REVISION);
442#endif
443
444 // Include the hash for the current module
445 auto ModHash = Index.getModuleHash(ModuleID);
446 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
447 for (auto F : ExportList)
448 // The export list can impact the internalization, be conservative here
449 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
450
451 // Include the hash for every module we import functions from
452 for (auto &Entry : ImportList) {
453 auto ModHash = Index.getModuleHash(Entry.first());
454 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
455 }
456
457 // Include the hash for the resolved ODR.
458 for (auto &Entry : ResolvedODR) {
459 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Entry.first,
460 sizeof(GlobalValue::GUID)));
461 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Entry.second,
462 sizeof(GlobalValue::LinkageTypes)));
463 }
464
465 // Include the hash for the preserved symbols.
466 for (auto &Entry : PreservedSymbols) {
467 if (DefinedFunctions.count(Entry))
468 Hasher.update(
469 ArrayRef<uint8_t>((uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
470 }
471
472 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
473 }
474
Mehdi Amini059464f2016-04-24 03:18:01 +0000475 // Access the path to this entry in the cache.
476 StringRef getEntryPath() { return EntryPath; }
477
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000478 // Try loading the buffer for this cache entry.
479 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
480 if (EntryPath.empty())
481 return std::error_code();
482 return MemoryBuffer::getFile(EntryPath);
483 }
484
485 // Cache the Produced object file
486 void write(MemoryBufferRef OutputBuffer) {
487 if (EntryPath.empty())
488 return;
489
490 // Write to a temporary to avoid race condition
491 SmallString<128> TempFilename;
492 int TempFD;
493 std::error_code EC =
494 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
495 if (EC) {
496 errs() << "Error: " << EC.message() << "\n";
497 report_fatal_error("ThinLTO: Can't get a temporary file");
498 }
499 {
500 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
501 OS << OutputBuffer.getBuffer();
502 }
503 // Rename to final destination (hopefully race condition won't matter here)
504 sys::fs::rename(TempFilename, EntryPath);
505 }
506};
507
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000508static std::unique_ptr<MemoryBuffer> ProcessThinLTOModule(
509 Module &TheModule, const ModuleSummaryIndex &Index,
510 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
511 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Amini059464f2016-04-24 03:18:01 +0000512 const FunctionImporter::ExportSetTy &ExportList,
513 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000514 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000515 ThinLTOCodeGenerator::CachingOptions CacheOptions, bool DisableCodeGen,
516 StringRef SaveTempsDir, unsigned count) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000517
518 // Save temps: after IPO.
519 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.IPO.bc");
520
Mehdi Amini059464f2016-04-24 03:18:01 +0000521 // Prepare for internalization by computing the set of symbols to preserve.
522 // We need to compute the list of symbols to preserve during internalization
523 // before doing any promotion because after renaming we won't (easily) match
524 // to the original name.
525 auto PreservedGV = computePreservedSymbolsForModule(
526 TheModule, GUIDPreservedSymbols, ExportList);
527
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000528 // "Benchmark"-like optimization: single-source case
529 bool SingleModule = (ModuleMap.size() == 1);
530
531 if (!SingleModule) {
532 promoteModule(TheModule, Index);
533
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000534 // Resolve the LinkOnce/Weak ODR, trying to turn them into
535 // "available_externally" when possible.
536 // This is a compile-time optimization.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000537 fixupODR(TheModule, ResolvedODR);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000538
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000539 // Save temps: after promotion.
540 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000541 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000542
Mehdi Amini059464f2016-04-24 03:18:01 +0000543 // Internalization
544 doInternalizeModule(TheModule, TM, PreservedGV);
545
546 // Save internalized bitcode
547 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.internalized.bc");
548
549 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000550 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000551
552 // Save temps: after cross-module import.
Mehdi Amini059464f2016-04-24 03:18:01 +0000553 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000554 }
555
556 optimizeModule(TheModule, TM);
557
Mehdi Amini059464f2016-04-24 03:18:01 +0000558 saveTempBitcode(TheModule, SaveTempsDir, count, ".5.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000559
Mehdi Amini43b657b2016-04-01 06:47:02 +0000560 if (DisableCodeGen) {
561 // Configured to stop before CodeGen, serialize the bitcode and return.
562 SmallVector<char, 128> OutputBuffer;
563 {
564 raw_svector_ostream OS(OutputBuffer);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000565 ModuleSummaryIndexBuilder IndexBuilder(&TheModule);
566 WriteBitcodeToFile(&TheModule, OS, true, &IndexBuilder.getIndex());
Mehdi Amini43b657b2016-04-01 06:47:02 +0000567 }
568 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
569 }
570
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000571 return codegenModule(TheModule, TM);
572}
573
574// Initialize the TargetMachine builder for a given Triple
575static void initTMBuilder(TargetMachineBuilder &TMBuilder,
576 const Triple &TheTriple) {
577 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
578 // FIXME this looks pretty terrible...
579 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
580 if (TheTriple.getArch() == llvm::Triple::x86_64)
581 TMBuilder.MCpu = "core2";
582 else if (TheTriple.getArch() == llvm::Triple::x86)
583 TMBuilder.MCpu = "yonah";
584 else if (TheTriple.getArch() == llvm::Triple::aarch64)
585 TMBuilder.MCpu = "cyclone";
586 }
587 TMBuilder.TheTriple = std::move(TheTriple);
588}
589
590} // end anonymous namespace
591
592void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
593 MemoryBufferRef Buffer(Data, Identifier);
594 if (Modules.empty()) {
595 // First module added, so initialize the triple and some options
596 LLVMContext Context;
597 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
598 initTMBuilder(TMBuilder, Triple(TheTriple));
599 }
600#ifndef NDEBUG
601 else {
602 LLVMContext Context;
603 assert(TMBuilder.TheTriple.str() ==
604 getBitcodeTargetTriple(Buffer, Context) &&
605 "ThinLTO modules with different triple not supported");
606 }
607#endif
608 Modules.push_back(Buffer);
609}
610
611void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
612 PreservedSymbols.insert(Name);
613}
614
615void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000616 // FIXME: At the moment, we don't take advantage of this extra information,
617 // we're conservatively considering cross-references as preserved.
618 // CrossReferencedSymbols.insert(Name);
619 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000620}
621
622// TargetMachine factory
623std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
624 std::string ErrMsg;
625 const Target *TheTarget =
626 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
627 if (!TheTarget) {
628 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
629 }
630
631 // Use MAttr as the default set of features.
632 SubtargetFeatures Features(MAttr);
633 Features.getDefaultSubtargetFeatures(TheTriple);
634 std::string FeatureStr = Features.getString();
635 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
636 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
637 CodeModel::Default, CGOptLevel));
638}
639
640/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000641 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000642 * "thin-link".
643 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000644std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
645 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000646 uint64_t NextModuleId = 0;
647 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000648 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
649 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000650 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000651 if (std::error_code EC = ObjOrErr.getError()) {
652 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000653 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000654 << EC.message() << "\n";
655 return nullptr;
656 }
657 auto Index = (*ObjOrErr)->takeIndex();
658 if (CombinedIndex) {
659 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
660 } else {
661 CombinedIndex = std::move(Index);
662 }
663 }
664 return CombinedIndex;
665}
666
667/**
668 * Perform promotion and renaming of exported internal functions.
669 */
670void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000671 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000672 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000673 auto ModuleIdentifier = TheModule.getModuleIdentifier();
674 // Collect for each module the list of function it defines (GUID -> Summary).
675 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
676 ModuleToDefinedGVSummaries;
677 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000678
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000679 // Generate import/export list
680 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
681 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
682 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
683 ExportLists);
684 auto &ExportList = ExportLists[ModuleIdentifier];
685
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000686 // Resolve the LinkOnceODR, trying to turn them into "available_externally"
687 // where possible.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000688 // This is a compile-time optimization.
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000689 // We use a std::map here to be able to have a defined ordering when
690 // producing a hash for the cache entry.
691 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000692 ResolveODR(Index, ExportList, ModuleToDefinedGVSummaries[ModuleIdentifier],
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000693 ModuleIdentifier, ResolvedODR);
694 fixupODR(TheModule, ResolvedODR);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000695
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000696 promoteModule(TheModule, Index);
697}
698
699/**
700 * Perform cross-module importing for the module identified by ModuleIdentifier.
701 */
702void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000703 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000704 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000705 auto ModuleCount = Index.modulePaths().size();
706
707 // Collect for each module the list of function it defines (GUID -> Summary).
708 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
709 ModuleToDefinedGVSummaries(ModuleCount);
710 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000711
712 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000713 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
714 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000715 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
716 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000717 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
718
719 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000720}
721
722/**
Mehdi Amini059464f2016-04-24 03:18:01 +0000723 * Perform internalization.
724 */
725void ThinLTOCodeGenerator::internalize(Module &TheModule,
726 ModuleSummaryIndex &Index) {
727 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
728 auto ModuleCount = Index.modulePaths().size();
729 auto ModuleIdentifier = TheModule.getModuleIdentifier();
730
731 // Convert the preserved symbols set from string to GUID
732 auto GUIDPreservedSymbols =
733 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
734
735 // Collect for each module the list of function it defines (GUID -> Summary).
736 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
737 ModuleToDefinedGVSummaries(ModuleCount);
738 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
739
740 // Generate import/export list
741 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
742 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
743 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
744 ExportLists);
745 auto &ExportList = ExportLists[ModuleIdentifier];
746
747 // Internalization
748 auto PreservedGV = computePreservedSymbolsForModule(
749 TheModule, GUIDPreservedSymbols, ExportList);
750 doInternalizeModule(TheModule, *TMBuilder.create(), PreservedGV);
751}
752
753/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000754 * Perform post-importing ThinLTO optimizations.
755 */
756void ThinLTOCodeGenerator::optimize(Module &TheModule) {
757 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000758
759 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000760 optimizeModule(TheModule, *TMBuilder.create());
761}
762
763/**
764 * Perform ThinLTO CodeGen.
765 */
766std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
767 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
768 return codegenModule(TheModule, *TMBuilder.create());
769}
770
771// Main entry point for the ThinLTO processing
772void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000773 if (CodeGenOnly) {
774 // Perform only parallel codegen and return.
775 ThreadPool Pool;
776 assert(ProducedBinaries.empty() && "The generator should not be reused");
777 ProducedBinaries.resize(Modules.size());
778 int count = 0;
779 for (auto &ModuleBuffer : Modules) {
780 Pool.async([&](int count) {
781 LLVMContext Context;
782 Context.setDiscardValueNames(LTODiscardValueNames);
783
784 // Parse module now
785 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
786
787 // CodeGen
788 ProducedBinaries[count] = codegen(*TheModule);
789 }, count++);
790 }
791
792 return;
793 }
794
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000795 // Sequential linking phase
796 auto Index = linkCombinedIndex();
797
798 // Save temps: index.
799 if (!SaveTempsDir.empty()) {
800 auto SaveTempPath = SaveTempsDir + "index.bc";
801 std::error_code EC;
802 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
803 if (EC)
804 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
805 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000806 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000807 }
808
809 // Prepare the resulting object vector
810 assert(ProducedBinaries.empty() && "The generator should not be reused");
811 ProducedBinaries.resize(Modules.size());
812
813 // Prepare the module map.
814 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000815 auto ModuleCount = Modules.size();
816
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000817 // Collect for each module the list of function it defines (GUID -> Summary).
818 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
819 ModuleToDefinedGVSummaries(ModuleCount);
820 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
821
Mehdi Amini01e32132016-03-26 05:40:34 +0000822 // Collect the import/export lists for all modules from the call-graph in the
823 // combined index.
824 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
825 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000826 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
827 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000828
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000829 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000830 // computing the caching hash and the internalization.
831 auto GUIDPreservedSymbols =
832 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000833
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000834 // Parallel optimizer + codegen
835 {
836 ThreadPool Pool(ThreadCount);
837 int count = 0;
838 for (auto &ModuleBuffer : Modules) {
839 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000840 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000841 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000842
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000843 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
844
845 // Resolve ODR, this has to be done early because it impacts the caching
846 // We use a std::map here to be able to have a defined ordering when
847 // producing a hash for the cache entry.
848 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
Mehdi Amini059464f2016-04-24 03:18:01 +0000849 ResolveODR(*Index, ExportList, DefinedFunctions, ModuleIdentifier,
850 ResolvedODR);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000851
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000852 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000853 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
854 ImportLists[ModuleIdentifier], ExportList,
855 ResolvedODR, DefinedFunctions,
856 GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000857
858 {
859 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000860 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
861 << CacheEntry.getEntryPath() << "' for buffer " << count
862 << " " << ModuleIdentifier << "\n");
863
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000864 if (ErrOrBuffer) {
865 // Cache Hit!
866 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
867 return;
868 }
869 }
870
871 LLVMContext Context;
872 Context.setDiscardValueNames(LTODiscardValueNames);
873 Context.enableDebugTypeODRUniquing();
874
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000875 // Parse module now
876 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
877
878 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000879 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000880
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000881 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000882 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000883 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000884 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Mehdi Amini059464f2016-04-24 03:18:01 +0000885 ExportList, GUIDPreservedSymbols, ResolvedODR, CacheOptions,
886 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000887
888 CacheEntry.write(*OutputBuffer);
889 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000890 }, count);
891 count++;
892 }
893 }
894
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000895 CachePruning(CacheOptions.Path)
896 .setPruningInterval(CacheOptions.PruningInterval)
897 .setEntryExpiration(CacheOptions.Expiration)
898 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
899 .prune();
900
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000901 // If statistics were requested, print them out now.
902 if (llvm::AreStatisticsEnabled())
903 llvm::PrintStatistics();
904}