blob: 9fef1326610c0e54630880ac48327172833d5932 [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
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000112bool IsFirstDefinitionForLinker(const GlobalValueInfoList &GVInfo,
113 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(
118 GVInfo, [](const std::unique_ptr<GlobalValueInfo> &FuncInfo) {
119 auto Linkage = FuncInfo->summary()->linkage();
120 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
121 });
122 // If \p GV is not the first definition, give up...
123 if ((*FirstDefForLinker)->summary()->modulePath() != ModulePath)
124 return false;
125 // If there is any strong definition anywhere, do not bother emitting this.
126 if (llvm::any_of(
127 GVInfo, [](const std::unique_ptr<GlobalValueInfo> &FuncInfo) {
128 auto Linkage = FuncInfo->summary()->linkage();
129 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
130 !GlobalValue::isWeakForLinker(Linkage);
131 }))
132 return false;
133 return true;
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000134}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000135
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000136static GlobalValue::LinkageTypes
137ResolveODR(const ModuleSummaryIndex &Index,
138 const FunctionImporter::ExportSetTy &ExportList,
139 StringRef ModuleIdentifier, GlobalValue::GUID GUID,
140 const GlobalValueSummary &GV) {
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000141 auto HasMultipleCopies =
142 [&](const GlobalValueInfoList &GVInfo) { return GVInfo.size() > 1; };
143
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000144 auto OriginalLinkage = GV.linkage();
145 switch (OriginalLinkage) {
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000146 case GlobalValue::ExternalLinkage:
147 case GlobalValue::AvailableExternallyLinkage:
148 case GlobalValue::AppendingLinkage:
149 case GlobalValue::InternalLinkage:
150 case GlobalValue::PrivateLinkage:
151 case GlobalValue::ExternalWeakLinkage:
152 case GlobalValue::CommonLinkage:
153 case GlobalValue::LinkOnceAnyLinkage:
154 case GlobalValue::WeakAnyLinkage:
155 break;
156 case GlobalValue::LinkOnceODRLinkage:
157 case GlobalValue::WeakODRLinkage: {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000158 auto &GVInfo = Index.findGlobalValueInfoList(GUID)->second;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000159 // We need to emit only one of these, the first module will keep
160 // it, but turned into a weak while the others will drop it.
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000161 if (!HasMultipleCopies(GVInfo)) {
162 // Exported LinkonceODR needs to be promoted to not be discarded
163 if (GlobalValue::isDiscardableIfUnused(OriginalLinkage) &&
164 ExportList.count(GUID))
165 return GlobalValue::WeakODRLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000166 break;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000167 }
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000168 if (IsFirstDefinitionForLinker(GVInfo, Index, ModuleIdentifier))
169 return GlobalValue::WeakODRLinkage;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000170 else if (isa<AliasSummary>(&GV))
171 // Alias can't be turned into available_externally.
172 return OriginalLinkage;
173 return GlobalValue::AvailableExternallyLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000174 }
175 }
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000176 return OriginalLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000177}
178
179/// Resolve LinkOnceODR and WeakODR.
180///
181/// We'd like to drop these function if they are no longer referenced in the
182/// current module. However there is a chance that another module is still
183/// referencing them because of the import. We make sure we always emit at least
184/// one copy.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000185static void ResolveODR(
186 const ModuleSummaryIndex &Index,
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000187 const FunctionImporter::ExportSetTy &ExportList,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000188 const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedGlobals,
189 StringRef ModuleIdentifier,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000190 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
Mehdi Amini8dcc8082016-04-14 08:46:22 +0000191 if (Index.modulePaths().size() == 1)
192 // Nothing to do if we don't have multiple modules
193 return;
194
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000195 // We won't optimize the globals that are referenced by an alias for now
196 // Ideally we should turn the alias into a global and duplicate the definition
197 // when needed.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000198 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
199 for (auto &GA : DefinedGlobals) {
200 if (auto AS = dyn_cast<AliasSummary>(GA.second))
201 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000202 }
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000203
204 for (auto &GV : DefinedGlobals) {
205 if (GlobalInvolvedWithAlias.count(GV.second))
206 continue;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000207 auto NewLinkage =
208 ResolveODR(Index, ExportList, ModuleIdentifier, GV.first, *GV.second);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000209 if (NewLinkage != GV.second->linkage()) {
210 ResolvedODR[GV.first] = NewLinkage;
211 }
212 }
213}
214
215/// Fixup linkage, see ResolveODR() above.
216void fixupODR(
217 Module &TheModule,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000218 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000219 // Process functions and global now
220 for (auto &GV : TheModule) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000221 auto NewLinkage = ResolvedODR.find(GV.getGUID());
222 if (NewLinkage == ResolvedODR.end())
223 continue;
224 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
225 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
226 GV.setLinkage(NewLinkage->second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000227 }
228 for (auto &GV : TheModule.globals()) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000229 auto NewLinkage = ResolvedODR.find(GV.getGUID());
230 if (NewLinkage == ResolvedODR.end())
231 continue;
232 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
233 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
234 GV.setLinkage(NewLinkage->second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000235 }
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000236 for (auto &GV : TheModule.aliases()) {
237 auto NewLinkage = ResolvedODR.find(GV.getGUID());
238 if (NewLinkage == ResolvedODR.end())
239 continue;
240 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
241 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
242 GV.setLinkage(NewLinkage->second);
243 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000244}
245
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000246static StringMap<MemoryBufferRef>
247generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
248 StringMap<MemoryBufferRef> ModuleMap;
249 for (auto &ModuleBuffer : Modules) {
250 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
251 ModuleMap.end() &&
252 "Expect unique Buffer Identifier");
253 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
254 }
255 return ModuleMap;
256}
257
258/// Provide a "loader" for the FunctionImporter to access function from other
259/// modules.
260class ModuleLoader {
261 /// The context that will be used for importing.
262 LLVMContext &Context;
263
264 /// Map from Module identifier to MemoryBuffer. Used by clients like the
265 /// FunctionImported to request loading a Module.
266 StringMap<MemoryBufferRef> &ModuleMap;
267
268public:
269 ModuleLoader(LLVMContext &Context, StringMap<MemoryBufferRef> &ModuleMap)
270 : Context(Context), ModuleMap(ModuleMap) {}
271
272 /// Load a module on demand.
273 std::unique_ptr<Module> operator()(StringRef Identifier) {
274 return loadModuleFromBuffer(ModuleMap[Identifier], Context, /*Lazy*/ true);
275 }
276};
277
Teresa Johnson26ab5772016-03-15 00:04:37 +0000278static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000279 if (renameModuleForThinLTO(TheModule, Index))
280 report_fatal_error("renameModuleForThinLTO failed");
281}
282
Mehdi Amini01e32132016-03-26 05:40:34 +0000283static void
284crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
285 StringMap<MemoryBufferRef> &ModuleMap,
286 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000287 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
288 FunctionImporter Importer(Index, Loader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000289 Importer.importFunctions(TheModule, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000290}
291
292static void optimizeModule(Module &TheModule, TargetMachine &TM) {
293 // Populate the PassManager
294 PassManagerBuilder PMB;
295 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
296 PMB.Inliner = createFunctionInliningPass();
297 // FIXME: should get it from the bitcode?
298 PMB.OptLevel = 3;
299 PMB.LoopVectorize = true;
300 PMB.SLPVectorize = true;
301 PMB.VerifyInput = true;
302 PMB.VerifyOutput = false;
303
304 legacy::PassManager PM;
305
306 // Add the TTI (required to inform the vectorizer about register size for
307 // instance)
308 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
309
310 // Add optimizations
311 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000312
313 PM.run(TheModule);
314}
315
Mehdi Amini059464f2016-04-24 03:18:01 +0000316// Create a DenseSet of GlobalValue to be used with the Internalizer.
317static DenseSet<const GlobalValue *> computePreservedSymbolsForModule(
318 Module &TheModule, const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
319 const FunctionImporter::ExportSetTy &ExportList) {
320 DenseSet<const GlobalValue *> PreservedGV;
321 if (GUIDPreservedSymbols.empty())
322 // Early exit: internalize is disabled when there is nothing to preserve.
323 return PreservedGV;
324
325 auto AddPreserveGV = [&](const GlobalValue &GV) {
326 auto GUID = GV.getGUID();
327 if (GUIDPreservedSymbols.count(GUID) || ExportList.count(GUID))
328 PreservedGV.insert(&GV);
329 };
330
331 for (auto &GV : TheModule)
332 AddPreserveGV(GV);
333 for (auto &GV : TheModule.globals())
334 AddPreserveGV(GV);
335 for (auto &GV : TheModule.aliases())
336 AddPreserveGV(GV);
337
338 return PreservedGV;
339}
340
341// Run internalization on \p TheModule
342static void
343doInternalizeModule(Module &TheModule, const TargetMachine &TM,
344 const DenseSet<const GlobalValue *> &PreservedGV) {
345 if (PreservedGV.empty()) {
346 // Be friendly and don't nuke totally the module when the client didn't
347 // supply anything to preserve.
348 return;
349 }
350
351 // Parse inline ASM and collect the list of symbols that are not defined in
352 // the current module.
353 StringSet<> AsmUndefinedRefs;
354 object::IRObjectFile::CollectAsmUndefinedRefs(
355 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
356 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
357 if (Flags & object::BasicSymbolRef::SF_Undefined)
358 AsmUndefinedRefs.insert(Name);
359 });
360
361 // Update the llvm.compiler_used globals to force preserving libcalls and
362 // symbols referenced from asm
363 UpdateCompilerUsed(TheModule, TM, AsmUndefinedRefs);
364
365 // Declare a callback for the internalize pass that will ask for every
366 // candidate GlobalValue if it can be internalized or not.
367 auto MustPreserveGV =
368 [&](const GlobalValue &GV) -> bool { return PreservedGV.count(&GV); };
369
370 llvm::internalizeModule(TheModule, MustPreserveGV);
371}
372
373// Convert the PreservedSymbols map from "Name" based to "GUID" based.
374static DenseSet<GlobalValue::GUID>
375computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
376 const Triple &TheTriple) {
377 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
378 for (auto &Entry : PreservedSymbols) {
379 StringRef Name = Entry.first();
380 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
381 Name = Name.drop_front();
382 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
383 }
384 return GUIDPreservedSymbols;
385}
386
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000387std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
388 TargetMachine &TM) {
389 SmallVector<char, 128> OutputBuffer;
390
391 // CodeGen
392 {
393 raw_svector_ostream OS(OutputBuffer);
394 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000395
396 // If the bitcode files contain ARC code and were compiled with optimization,
397 // the ObjCARCContractPass must be run, so do it unconditionally here.
398 PM.add(createObjCARCContractPass());
399
400 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000401 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
402 /* DisableVerify */ true))
403 report_fatal_error("Failed to setup codegen");
404
405 // Run codegen now. resulting binary is in OutputBuffer.
406 PM.run(TheModule);
407 }
408 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
409}
410
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000411/// Manage caching for a single Module.
412class ModuleCacheEntry {
413 SmallString<128> EntryPath;
414
415public:
416 // Create a cache entry. This compute a unique hash for the Module considering
417 // the current list of export/import, and offer an interface to query to
418 // access the content in the cache.
419 ModuleCacheEntry(
420 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
421 const FunctionImporter::ImportMapTy &ImportList,
422 const FunctionImporter::ExportSetTy &ExportList,
423 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
424 const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedFunctions,
425 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
426 if (CachePath.empty())
427 return;
428
429 // Compute the unique hash for this entry
430 // This is based on the current compiler version, the module itself, the
431 // export list, the hash for every single module in the import list, the
432 // list of ResolvedODR for the module, and the list of preserved symbols.
433
434 SHA1 Hasher;
435
436 // Start with the compiler revision
437 Hasher.update(LLVM_VERSION_STRING);
438#ifdef HAVE_LLVM_REVISION
439 Hasher.update(LLVM_REVISION);
440#endif
441
442 // Include the hash for the current module
443 auto ModHash = Index.getModuleHash(ModuleID);
444 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
445 for (auto F : ExportList)
446 // The export list can impact the internalization, be conservative here
447 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
448
449 // Include the hash for every module we import functions from
450 for (auto &Entry : ImportList) {
451 auto ModHash = Index.getModuleHash(Entry.first());
452 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
453 }
454
455 // Include the hash for the resolved ODR.
456 for (auto &Entry : ResolvedODR) {
457 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Entry.first,
458 sizeof(GlobalValue::GUID)));
459 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Entry.second,
460 sizeof(GlobalValue::LinkageTypes)));
461 }
462
463 // Include the hash for the preserved symbols.
464 for (auto &Entry : PreservedSymbols) {
465 if (DefinedFunctions.count(Entry))
466 Hasher.update(
467 ArrayRef<uint8_t>((uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
468 }
469
470 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
471 }
472
Mehdi Amini059464f2016-04-24 03:18:01 +0000473 // Access the path to this entry in the cache.
474 StringRef getEntryPath() { return EntryPath; }
475
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000476 // Try loading the buffer for this cache entry.
477 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
478 if (EntryPath.empty())
479 return std::error_code();
480 return MemoryBuffer::getFile(EntryPath);
481 }
482
483 // Cache the Produced object file
484 void write(MemoryBufferRef OutputBuffer) {
485 if (EntryPath.empty())
486 return;
487
488 // Write to a temporary to avoid race condition
489 SmallString<128> TempFilename;
490 int TempFD;
491 std::error_code EC =
492 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
493 if (EC) {
494 errs() << "Error: " << EC.message() << "\n";
495 report_fatal_error("ThinLTO: Can't get a temporary file");
496 }
497 {
498 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
499 OS << OutputBuffer.getBuffer();
500 }
501 // Rename to final destination (hopefully race condition won't matter here)
502 sys::fs::rename(TempFilename, EntryPath);
503 }
504};
505
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000506static std::unique_ptr<MemoryBuffer> ProcessThinLTOModule(
507 Module &TheModule, const ModuleSummaryIndex &Index,
508 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
509 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Amini059464f2016-04-24 03:18:01 +0000510 const FunctionImporter::ExportSetTy &ExportList,
511 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000512 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000513 ThinLTOCodeGenerator::CachingOptions CacheOptions, bool DisableCodeGen,
514 StringRef SaveTempsDir, unsigned count) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000515
516 // Save temps: after IPO.
517 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.IPO.bc");
518
Mehdi Amini059464f2016-04-24 03:18:01 +0000519 // Prepare for internalization by computing the set of symbols to preserve.
520 // We need to compute the list of symbols to preserve during internalization
521 // before doing any promotion because after renaming we won't (easily) match
522 // to the original name.
523 auto PreservedGV = computePreservedSymbolsForModule(
524 TheModule, GUIDPreservedSymbols, ExportList);
525
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000526 // "Benchmark"-like optimization: single-source case
527 bool SingleModule = (ModuleMap.size() == 1);
528
529 if (!SingleModule) {
530 promoteModule(TheModule, Index);
531
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000532 // Resolve the LinkOnce/Weak ODR, trying to turn them into
533 // "available_externally" when possible.
534 // This is a compile-time optimization.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000535 fixupODR(TheModule, ResolvedODR);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000536
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000537 // Save temps: after promotion.
538 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000539 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000540
Mehdi Amini059464f2016-04-24 03:18:01 +0000541 // Internalization
542 doInternalizeModule(TheModule, TM, PreservedGV);
543
544 // Save internalized bitcode
545 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.internalized.bc");
546
547 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000548 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000549
550 // Save temps: after cross-module import.
Mehdi Amini059464f2016-04-24 03:18:01 +0000551 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000552 }
553
554 optimizeModule(TheModule, TM);
555
Mehdi Amini059464f2016-04-24 03:18:01 +0000556 saveTempBitcode(TheModule, SaveTempsDir, count, ".5.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000557
Mehdi Amini43b657b2016-04-01 06:47:02 +0000558 if (DisableCodeGen) {
559 // Configured to stop before CodeGen, serialize the bitcode and return.
560 SmallVector<char, 128> OutputBuffer;
561 {
562 raw_svector_ostream OS(OutputBuffer);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000563 ModuleSummaryIndexBuilder IndexBuilder(&TheModule);
564 WriteBitcodeToFile(&TheModule, OS, true, &IndexBuilder.getIndex());
Mehdi Amini43b657b2016-04-01 06:47:02 +0000565 }
566 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
567 }
568
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000569 return codegenModule(TheModule, TM);
570}
571
572// Initialize the TargetMachine builder for a given Triple
573static void initTMBuilder(TargetMachineBuilder &TMBuilder,
574 const Triple &TheTriple) {
575 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
576 // FIXME this looks pretty terrible...
577 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
578 if (TheTriple.getArch() == llvm::Triple::x86_64)
579 TMBuilder.MCpu = "core2";
580 else if (TheTriple.getArch() == llvm::Triple::x86)
581 TMBuilder.MCpu = "yonah";
582 else if (TheTriple.getArch() == llvm::Triple::aarch64)
583 TMBuilder.MCpu = "cyclone";
584 }
585 TMBuilder.TheTriple = std::move(TheTriple);
586}
587
588} // end anonymous namespace
589
590void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
591 MemoryBufferRef Buffer(Data, Identifier);
592 if (Modules.empty()) {
593 // First module added, so initialize the triple and some options
594 LLVMContext Context;
595 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
596 initTMBuilder(TMBuilder, Triple(TheTriple));
597 }
598#ifndef NDEBUG
599 else {
600 LLVMContext Context;
601 assert(TMBuilder.TheTriple.str() ==
602 getBitcodeTargetTriple(Buffer, Context) &&
603 "ThinLTO modules with different triple not supported");
604 }
605#endif
606 Modules.push_back(Buffer);
607}
608
609void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
610 PreservedSymbols.insert(Name);
611}
612
613void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000614 // FIXME: At the moment, we don't take advantage of this extra information,
615 // we're conservatively considering cross-references as preserved.
616 // CrossReferencedSymbols.insert(Name);
617 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000618}
619
620// TargetMachine factory
621std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
622 std::string ErrMsg;
623 const Target *TheTarget =
624 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
625 if (!TheTarget) {
626 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
627 }
628
629 // Use MAttr as the default set of features.
630 SubtargetFeatures Features(MAttr);
631 Features.getDefaultSubtargetFeatures(TheTriple);
632 std::string FeatureStr = Features.getString();
633 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
634 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
635 CodeModel::Default, CGOptLevel));
636}
637
638/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000639 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000640 * "thin-link".
641 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000642std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
643 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000644 uint64_t NextModuleId = 0;
645 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000646 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
647 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000648 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000649 if (std::error_code EC = ObjOrErr.getError()) {
650 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000651 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000652 << EC.message() << "\n";
653 return nullptr;
654 }
655 auto Index = (*ObjOrErr)->takeIndex();
656 if (CombinedIndex) {
657 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
658 } else {
659 CombinedIndex = std::move(Index);
660 }
661 }
662 return CombinedIndex;
663}
664
665/**
666 * Perform promotion and renaming of exported internal functions.
667 */
668void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000669 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000670 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000671 auto ModuleIdentifier = TheModule.getModuleIdentifier();
672 // Collect for each module the list of function it defines (GUID -> Summary).
673 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
674 ModuleToDefinedGVSummaries;
675 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).
706 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
707 ModuleToDefinedGVSummaries(ModuleCount);
708 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000709
710 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000711 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
712 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000713 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
714 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000715 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
716
717 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000718}
719
720/**
Mehdi Amini059464f2016-04-24 03:18:01 +0000721 * Perform internalization.
722 */
723void ThinLTOCodeGenerator::internalize(Module &TheModule,
724 ModuleSummaryIndex &Index) {
725 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
726 auto ModuleCount = Index.modulePaths().size();
727 auto ModuleIdentifier = TheModule.getModuleIdentifier();
728
729 // Convert the preserved symbols set from string to GUID
730 auto GUIDPreservedSymbols =
731 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
732
733 // Collect for each module the list of function it defines (GUID -> Summary).
734 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
735 ModuleToDefinedGVSummaries(ModuleCount);
736 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
737
738 // Generate import/export list
739 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
740 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
741 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
742 ExportLists);
743 auto &ExportList = ExportLists[ModuleIdentifier];
744
745 // Internalization
746 auto PreservedGV = computePreservedSymbolsForModule(
747 TheModule, GUIDPreservedSymbols, ExportList);
748 doInternalizeModule(TheModule, *TMBuilder.create(), PreservedGV);
749}
750
751/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000752 * Perform post-importing ThinLTO optimizations.
753 */
754void ThinLTOCodeGenerator::optimize(Module &TheModule) {
755 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000756
757 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000758 optimizeModule(TheModule, *TMBuilder.create());
759}
760
761/**
762 * Perform ThinLTO CodeGen.
763 */
764std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
765 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
766 return codegenModule(TheModule, *TMBuilder.create());
767}
768
769// Main entry point for the ThinLTO processing
770void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000771 if (CodeGenOnly) {
772 // Perform only parallel codegen and return.
773 ThreadPool Pool;
774 assert(ProducedBinaries.empty() && "The generator should not be reused");
775 ProducedBinaries.resize(Modules.size());
776 int count = 0;
777 for (auto &ModuleBuffer : Modules) {
778 Pool.async([&](int count) {
779 LLVMContext Context;
780 Context.setDiscardValueNames(LTODiscardValueNames);
781
782 // Parse module now
783 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
784
785 // CodeGen
786 ProducedBinaries[count] = codegen(*TheModule);
787 }, count++);
788 }
789
790 return;
791 }
792
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000793 // Sequential linking phase
794 auto Index = linkCombinedIndex();
795
796 // Save temps: index.
797 if (!SaveTempsDir.empty()) {
798 auto SaveTempPath = SaveTempsDir + "index.bc";
799 std::error_code EC;
800 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
801 if (EC)
802 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
803 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000804 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000805 }
806
807 // Prepare the resulting object vector
808 assert(ProducedBinaries.empty() && "The generator should not be reused");
809 ProducedBinaries.resize(Modules.size());
810
811 // Prepare the module map.
812 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000813 auto ModuleCount = Modules.size();
814
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000815 // Collect for each module the list of function it defines (GUID -> Summary).
816 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
817 ModuleToDefinedGVSummaries(ModuleCount);
818 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
819
Mehdi Amini01e32132016-03-26 05:40:34 +0000820 // Collect the import/export lists for all modules from the call-graph in the
821 // combined index.
822 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
823 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000824 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
825 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000826
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000827 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000828 // computing the caching hash and the internalization.
829 auto GUIDPreservedSymbols =
830 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000831
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000832 // Parallel optimizer + codegen
833 {
834 ThreadPool Pool(ThreadCount);
835 int count = 0;
836 for (auto &ModuleBuffer : Modules) {
837 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000838 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000839 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000840
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000841 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
842
843 // Resolve ODR, this has to be done early because it impacts the caching
844 // We use a std::map here to be able to have a defined ordering when
845 // producing a hash for the cache entry.
846 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
Mehdi Amini059464f2016-04-24 03:18:01 +0000847 ResolveODR(*Index, ExportList, DefinedFunctions, ModuleIdentifier,
848 ResolvedODR);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000849
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000850 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000851 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
852 ImportLists[ModuleIdentifier], ExportList,
853 ResolvedODR, DefinedFunctions,
854 GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000855
856 {
857 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000858 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
859 << CacheEntry.getEntryPath() << "' for buffer " << count
860 << " " << ModuleIdentifier << "\n");
861
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000862 if (ErrOrBuffer) {
863 // Cache Hit!
864 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
865 return;
866 }
867 }
868
869 LLVMContext Context;
870 Context.setDiscardValueNames(LTODiscardValueNames);
871 Context.enableDebugTypeODRUniquing();
872
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000873 // Parse module now
874 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
875
876 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000877 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000878
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000879 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000880 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000881 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000882 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Mehdi Amini059464f2016-04-24 03:18:01 +0000883 ExportList, GUIDPreservedSymbols, ResolvedODR, CacheOptions,
884 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000885
886 CacheEntry.write(*OutputBuffer);
887 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000888 }, count);
889 count++;
890 }
891 }
892
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000893 CachePruning(CacheOptions.Path)
894 .setPruningInterval(CacheOptions.PruningInterval)
895 .setEntryExpiration(CacheOptions.Expiration)
896 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
897 .prune();
898
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000899 // If statistics were requested, print them out now.
900 if (llvm::AreStatisticsEnabled())
901 llvm::PrintStatistics();
902}