blob: b90d0d81b60c9b78ba921797e73ec833ab0c48f3 [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"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000035#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000036#include "llvm/Linker/Linker.h"
37#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000038#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000039#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Amini1aafabf2016-04-16 07:02:16 +000040#include "llvm/Support/Debug.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000041#include "llvm/Support/CachePruning.h"
42#include "llvm/Support/Debug.h"
43#include "llvm/Support/Path.h"
44#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000045#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
Mehdi Amini819e9cd2016-05-16 19:33:07 +000055#include <numeric>
56
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000057using namespace llvm;
58
Mehdi Amini1aafabf2016-04-16 07:02:16 +000059#define DEBUG_TYPE "thinlto"
60
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000061namespace llvm {
62// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
63extern cl::opt<bool> LTODiscardValueNames;
64}
65
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000066namespace {
67
68static cl::opt<int> ThreadCount("threads",
69 cl::init(std::thread::hardware_concurrency()));
70
71static void diagnosticHandler(const DiagnosticInfo &DI) {
72 DiagnosticPrinterRawOStream DP(errs());
73 DI.print(DP);
74 errs() << '\n';
75}
76
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000077// Simple helper to save temporary files for debug.
78static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
79 unsigned count, StringRef Suffix) {
80 if (TempDir.empty())
81 return;
82 // User asked to save temps, let dump the bitcode file after import.
83 auto SaveTempPath = TempDir + llvm::utostr(count) + Suffix;
84 std::error_code EC;
85 raw_fd_ostream OS(SaveTempPath.str(), EC, sys::fs::F_None);
86 if (EC)
87 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
88 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000089 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000090}
91
Teresa Johnson28e457b2016-04-24 14:57:11 +000092bool IsFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList,
Mehdi Amini5a2e5d32016-04-01 21:53:50 +000093 const ModuleSummaryIndex &Index,
94 StringRef ModulePath) {
95 // Get the first *linker visible* definition for this global in the summary
96 // list.
97 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +000098 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
99 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000100 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
101 });
102 // If \p GV is not the first definition, give up...
Teresa Johnson28e457b2016-04-24 14:57:11 +0000103 if ((*FirstDefForLinker)->modulePath() != ModulePath)
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000104 return false;
105 // If there is any strong definition anywhere, do not bother emitting this.
106 if (llvm::any_of(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000107 GVSummaryList,
108 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
109 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000110 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
111 !GlobalValue::isWeakForLinker(Linkage);
112 }))
113 return false;
114 return true;
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000115}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000116
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000117static GlobalValue::LinkageTypes
118ResolveODR(const ModuleSummaryIndex &Index,
119 const FunctionImporter::ExportSetTy &ExportList,
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000120 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000121 StringRef ModuleIdentifier, GlobalValue::GUID GUID,
122 const GlobalValueSummary &GV) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000123 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
124 return GVSummaryList.size() > 1;
125 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000126
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000127 auto OriginalLinkage = GV.linkage();
128 switch (OriginalLinkage) {
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000129 case GlobalValue::ExternalLinkage:
130 case GlobalValue::AvailableExternallyLinkage:
131 case GlobalValue::AppendingLinkage:
132 case GlobalValue::InternalLinkage:
133 case GlobalValue::PrivateLinkage:
134 case GlobalValue::ExternalWeakLinkage:
135 case GlobalValue::CommonLinkage:
136 case GlobalValue::LinkOnceAnyLinkage:
137 case GlobalValue::WeakAnyLinkage:
138 break;
139 case GlobalValue::LinkOnceODRLinkage:
140 case GlobalValue::WeakODRLinkage: {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000141 auto &GVSummaryList = Index.findGlobalValueSummaryList(GUID)->second;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000142 // We need to emit only one of these, the first module will keep
143 // it, but turned into a weak while the others will drop it.
Teresa Johnson28e457b2016-04-24 14:57:11 +0000144 if (!HasMultipleCopies(GVSummaryList)) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000145 // Exported LinkonceODR needs to be promoted to not be discarded
146 if (GlobalValue::isDiscardableIfUnused(OriginalLinkage) &&
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000147 (ExportList.count(GUID) || GUIDPreservedSymbols.count(GUID)))
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000148 return GlobalValue::WeakODRLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000149 break;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000150 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000151 if (IsFirstDefinitionForLinker(GVSummaryList, Index, ModuleIdentifier))
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000152 return GlobalValue::WeakODRLinkage;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000153 else if (isa<AliasSummary>(&GV))
154 // Alias can't be turned into available_externally.
155 return OriginalLinkage;
156 return GlobalValue::AvailableExternallyLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000157 }
158 }
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000159 return OriginalLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000160}
161
162/// Resolve LinkOnceODR and WeakODR.
163///
164/// We'd like to drop these function if they are no longer referenced in the
165/// current module. However there is a chance that another module is still
166/// referencing them because of the import. We make sure we always emit at least
167/// one copy.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000168static void ResolveODR(
169 const ModuleSummaryIndex &Index,
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000170 const FunctionImporter::ExportSetTy &ExportList,
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000171 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000172 const GVSummaryMapTy &DefinedGlobals, StringRef ModuleIdentifier,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000173 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
Mehdi Amini8dcc8082016-04-14 08:46:22 +0000174 if (Index.modulePaths().size() == 1)
175 // Nothing to do if we don't have multiple modules
176 return;
177
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000178 // We won't optimize the globals that are referenced by an alias for now
179 // Ideally we should turn the alias into a global and duplicate the definition
180 // when needed.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000181 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
182 for (auto &GA : DefinedGlobals) {
183 if (auto AS = dyn_cast<AliasSummary>(GA.second))
184 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000185 }
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000186
187 for (auto &GV : DefinedGlobals) {
188 if (GlobalInvolvedWithAlias.count(GV.second))
189 continue;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000190 auto NewLinkage =
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000191 ResolveODR(Index, ExportList, GUIDPreservedSymbols, ModuleIdentifier, GV.first, *GV.second);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000192 if (NewLinkage != GV.second->linkage()) {
193 ResolvedODR[GV.first] = NewLinkage;
194 }
195 }
196}
197
198/// Fixup linkage, see ResolveODR() above.
199void fixupODR(
200 Module &TheModule,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000201 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000202 // Process functions and global now
203 for (auto &GV : TheModule) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000204 auto NewLinkage = ResolvedODR.find(GV.getGUID());
205 if (NewLinkage == ResolvedODR.end())
206 continue;
207 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
208 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
209 GV.setLinkage(NewLinkage->second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000210 }
211 for (auto &GV : TheModule.globals()) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000212 auto NewLinkage = ResolvedODR.find(GV.getGUID());
213 if (NewLinkage == ResolvedODR.end())
214 continue;
215 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
216 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
217 GV.setLinkage(NewLinkage->second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000218 }
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000219 for (auto &GV : TheModule.aliases()) {
220 auto NewLinkage = ResolvedODR.find(GV.getGUID());
221 if (NewLinkage == ResolvedODR.end())
222 continue;
223 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
224 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
225 GV.setLinkage(NewLinkage->second);
226 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000227}
228
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000229static StringMap<MemoryBufferRef>
230generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
231 StringMap<MemoryBufferRef> ModuleMap;
232 for (auto &ModuleBuffer : Modules) {
233 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
234 ModuleMap.end() &&
235 "Expect unique Buffer Identifier");
236 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
237 }
238 return ModuleMap;
239}
240
Teresa Johnson26ab5772016-03-15 00:04:37 +0000241static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000242 if (renameModuleForThinLTO(TheModule, Index))
243 report_fatal_error("renameModuleForThinLTO failed");
244}
245
Mehdi Amini01e32132016-03-26 05:40:34 +0000246static void
247crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
248 StringMap<MemoryBufferRef> &ModuleMap,
249 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000250 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
251 FunctionImporter Importer(Index, Loader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000252 Importer.importFunctions(TheModule, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000253}
254
255static void optimizeModule(Module &TheModule, TargetMachine &TM) {
256 // Populate the PassManager
257 PassManagerBuilder PMB;
258 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
259 PMB.Inliner = createFunctionInliningPass();
260 // FIXME: should get it from the bitcode?
261 PMB.OptLevel = 3;
262 PMB.LoopVectorize = true;
263 PMB.SLPVectorize = true;
264 PMB.VerifyInput = true;
265 PMB.VerifyOutput = false;
266
267 legacy::PassManager PM;
268
269 // Add the TTI (required to inform the vectorizer about register size for
270 // instance)
271 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
272
273 // Add optimizations
274 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000275
276 PM.run(TheModule);
277}
278
Mehdi Amini059464f2016-04-24 03:18:01 +0000279// Create a DenseSet of GlobalValue to be used with the Internalizer.
280static DenseSet<const GlobalValue *> computePreservedSymbolsForModule(
281 Module &TheModule, const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
282 const FunctionImporter::ExportSetTy &ExportList) {
283 DenseSet<const GlobalValue *> PreservedGV;
284 if (GUIDPreservedSymbols.empty())
285 // Early exit: internalize is disabled when there is nothing to preserve.
286 return PreservedGV;
287
288 auto AddPreserveGV = [&](const GlobalValue &GV) {
289 auto GUID = GV.getGUID();
290 if (GUIDPreservedSymbols.count(GUID) || ExportList.count(GUID))
291 PreservedGV.insert(&GV);
292 };
293
294 for (auto &GV : TheModule)
295 AddPreserveGV(GV);
296 for (auto &GV : TheModule.globals())
297 AddPreserveGV(GV);
298 for (auto &GV : TheModule.aliases())
299 AddPreserveGV(GV);
300
301 return PreservedGV;
302}
303
304// Run internalization on \p TheModule
305static void
306doInternalizeModule(Module &TheModule, const TargetMachine &TM,
307 const DenseSet<const GlobalValue *> &PreservedGV) {
308 if (PreservedGV.empty()) {
309 // Be friendly and don't nuke totally the module when the client didn't
310 // supply anything to preserve.
311 return;
312 }
313
314 // Parse inline ASM and collect the list of symbols that are not defined in
315 // the current module.
316 StringSet<> AsmUndefinedRefs;
317 object::IRObjectFile::CollectAsmUndefinedRefs(
318 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
319 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
320 if (Flags & object::BasicSymbolRef::SF_Undefined)
321 AsmUndefinedRefs.insert(Name);
322 });
323
324 // Update the llvm.compiler_used globals to force preserving libcalls and
325 // symbols referenced from asm
326 UpdateCompilerUsed(TheModule, TM, AsmUndefinedRefs);
327
328 // Declare a callback for the internalize pass that will ask for every
329 // candidate GlobalValue if it can be internalized or not.
330 auto MustPreserveGV =
331 [&](const GlobalValue &GV) -> bool { return PreservedGV.count(&GV); };
332
333 llvm::internalizeModule(TheModule, MustPreserveGV);
334}
335
336// Convert the PreservedSymbols map from "Name" based to "GUID" based.
337static DenseSet<GlobalValue::GUID>
338computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
339 const Triple &TheTriple) {
340 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
341 for (auto &Entry : PreservedSymbols) {
342 StringRef Name = Entry.first();
343 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
344 Name = Name.drop_front();
345 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
346 }
347 return GUIDPreservedSymbols;
348}
349
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000350std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
351 TargetMachine &TM) {
352 SmallVector<char, 128> OutputBuffer;
353
354 // CodeGen
355 {
356 raw_svector_ostream OS(OutputBuffer);
357 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000358
359 // If the bitcode files contain ARC code and were compiled with optimization,
360 // the ObjCARCContractPass must be run, so do it unconditionally here.
361 PM.add(createObjCARCContractPass());
362
363 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000364 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
365 /* DisableVerify */ true))
366 report_fatal_error("Failed to setup codegen");
367
368 // Run codegen now. resulting binary is in OutputBuffer.
369 PM.run(TheModule);
370 }
371 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
372}
373
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000374/// Manage caching for a single Module.
375class ModuleCacheEntry {
376 SmallString<128> EntryPath;
377
378public:
379 // Create a cache entry. This compute a unique hash for the Module considering
380 // the current list of export/import, and offer an interface to query to
381 // access the content in the cache.
382 ModuleCacheEntry(
383 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
384 const FunctionImporter::ImportMapTy &ImportList,
385 const FunctionImporter::ExportSetTy &ExportList,
386 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000387 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000388 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
389 if (CachePath.empty())
390 return;
391
392 // Compute the unique hash for this entry
393 // This is based on the current compiler version, the module itself, the
394 // export list, the hash for every single module in the import list, the
395 // list of ResolvedODR for the module, and the list of preserved symbols.
396
397 SHA1 Hasher;
398
399 // Start with the compiler revision
400 Hasher.update(LLVM_VERSION_STRING);
401#ifdef HAVE_LLVM_REVISION
402 Hasher.update(LLVM_REVISION);
403#endif
404
405 // Include the hash for the current module
406 auto ModHash = Index.getModuleHash(ModuleID);
407 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
408 for (auto F : ExportList)
409 // The export list can impact the internalization, be conservative here
410 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
411
412 // Include the hash for every module we import functions from
413 for (auto &Entry : ImportList) {
414 auto ModHash = Index.getModuleHash(Entry.first());
415 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
416 }
417
418 // Include the hash for the resolved ODR.
419 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000420 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000421 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000422 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000423 sizeof(GlobalValue::LinkageTypes)));
424 }
425
426 // Include the hash for the preserved symbols.
427 for (auto &Entry : PreservedSymbols) {
428 if (DefinedFunctions.count(Entry))
429 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000430 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000431 }
432
433 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
434 }
435
Mehdi Amini059464f2016-04-24 03:18:01 +0000436 // Access the path to this entry in the cache.
437 StringRef getEntryPath() { return EntryPath; }
438
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000439 // Try loading the buffer for this cache entry.
440 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
441 if (EntryPath.empty())
442 return std::error_code();
443 return MemoryBuffer::getFile(EntryPath);
444 }
445
446 // Cache the Produced object file
Mehdi Amini001bb412016-05-16 19:11:59 +0000447 std::unique_ptr<MemoryBuffer>
448 write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000449 if (EntryPath.empty())
Mehdi Amini001bb412016-05-16 19:11:59 +0000450 return OutputBuffer;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000451
452 // Write to a temporary to avoid race condition
453 SmallString<128> TempFilename;
454 int TempFD;
455 std::error_code EC =
456 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
457 if (EC) {
458 errs() << "Error: " << EC.message() << "\n";
459 report_fatal_error("ThinLTO: Can't get a temporary file");
460 }
461 {
462 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini001bb412016-05-16 19:11:59 +0000463 OS << OutputBuffer->getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000464 }
465 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000466 EC = sys::fs::rename(TempFilename, EntryPath);
467 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000468 sys::fs::remove(TempFilename);
469 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
470 if (EC)
471 report_fatal_error(Twine("Failed to open ") + EntryPath +
472 " to save cached entry\n");
Mehdi Amini001bb412016-05-16 19:11:59 +0000473 OS << OutputBuffer->getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000474 }
Mehdi Amini001bb412016-05-16 19:11:59 +0000475 auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
476 if (auto EC = ReloadedBufferOrErr.getError()) {
477 // FIXME diagnose
478 errs() << "error: can't reload cached file '" << EntryPath
479 << "': " << EC.message() << "\n";
480 return OutputBuffer;
481 }
482 return std::move(*ReloadedBufferOrErr);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000483 }
484};
485
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000486static std::unique_ptr<MemoryBuffer> ProcessThinLTOModule(
487 Module &TheModule, const ModuleSummaryIndex &Index,
488 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
489 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Amini059464f2016-04-24 03:18:01 +0000490 const FunctionImporter::ExportSetTy &ExportList,
491 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000492 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000493 ThinLTOCodeGenerator::CachingOptions CacheOptions, bool DisableCodeGen,
494 StringRef SaveTempsDir, unsigned count) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000495
Mehdi Amini059464f2016-04-24 03:18:01 +0000496 // Prepare for internalization by computing the set of symbols to preserve.
497 // We need to compute the list of symbols to preserve during internalization
498 // before doing any promotion because after renaming we won't (easily) match
499 // to the original name.
500 auto PreservedGV = computePreservedSymbolsForModule(
501 TheModule, GUIDPreservedSymbols, ExportList);
502
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000503 // "Benchmark"-like optimization: single-source case
504 bool SingleModule = (ModuleMap.size() == 1);
505
506 if (!SingleModule) {
507 promoteModule(TheModule, Index);
508
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000509 // Resolve the LinkOnce/Weak ODR, trying to turn them into
510 // "available_externally" when possible.
511 // This is a compile-time optimization.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000512 fixupODR(TheModule, ResolvedODR);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000513
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000514 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000515 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000516 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000517
Mehdi Amini059464f2016-04-24 03:18:01 +0000518 // Internalization
519 doInternalizeModule(TheModule, TM, PreservedGV);
520
521 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000522 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000523
524 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000525 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000526
527 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000528 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000529 }
530
531 optimizeModule(TheModule, TM);
532
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000533 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000534
Mehdi Amini43b657b2016-04-01 06:47:02 +0000535 if (DisableCodeGen) {
536 // Configured to stop before CodeGen, serialize the bitcode and return.
537 SmallVector<char, 128> OutputBuffer;
538 {
539 raw_svector_ostream OS(OutputBuffer);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000540 ModuleSummaryIndexBuilder IndexBuilder(&TheModule);
541 WriteBitcodeToFile(&TheModule, OS, true, &IndexBuilder.getIndex());
Mehdi Amini43b657b2016-04-01 06:47:02 +0000542 }
543 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
544 }
545
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000546 return codegenModule(TheModule, TM);
547}
548
549// Initialize the TargetMachine builder for a given Triple
550static void initTMBuilder(TargetMachineBuilder &TMBuilder,
551 const Triple &TheTriple) {
552 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
553 // FIXME this looks pretty terrible...
554 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
555 if (TheTriple.getArch() == llvm::Triple::x86_64)
556 TMBuilder.MCpu = "core2";
557 else if (TheTriple.getArch() == llvm::Triple::x86)
558 TMBuilder.MCpu = "yonah";
559 else if (TheTriple.getArch() == llvm::Triple::aarch64)
560 TMBuilder.MCpu = "cyclone";
561 }
562 TMBuilder.TheTriple = std::move(TheTriple);
563}
564
565} // end anonymous namespace
566
567void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
568 MemoryBufferRef Buffer(Data, Identifier);
569 if (Modules.empty()) {
570 // First module added, so initialize the triple and some options
571 LLVMContext Context;
572 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
573 initTMBuilder(TMBuilder, Triple(TheTriple));
574 }
575#ifndef NDEBUG
576 else {
577 LLVMContext Context;
578 assert(TMBuilder.TheTriple.str() ==
579 getBitcodeTargetTriple(Buffer, Context) &&
580 "ThinLTO modules with different triple not supported");
581 }
582#endif
583 Modules.push_back(Buffer);
584}
585
586void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
587 PreservedSymbols.insert(Name);
588}
589
590void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000591 // FIXME: At the moment, we don't take advantage of this extra information,
592 // we're conservatively considering cross-references as preserved.
593 // CrossReferencedSymbols.insert(Name);
594 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000595}
596
597// TargetMachine factory
598std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
599 std::string ErrMsg;
600 const Target *TheTarget =
601 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
602 if (!TheTarget) {
603 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
604 }
605
606 // Use MAttr as the default set of features.
607 SubtargetFeatures Features(MAttr);
608 Features.getDefaultSubtargetFeatures(TheTriple);
609 std::string FeatureStr = Features.getString();
610 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
611 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
612 CodeModel::Default, CGOptLevel));
613}
614
615/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000616 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000617 * "thin-link".
618 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000619std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
620 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000621 uint64_t NextModuleId = 0;
622 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000623 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
624 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000625 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000626 if (std::error_code EC = ObjOrErr.getError()) {
627 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000628 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000629 << EC.message() << "\n";
630 return nullptr;
631 }
632 auto Index = (*ObjOrErr)->takeIndex();
633 if (CombinedIndex) {
634 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
635 } else {
636 CombinedIndex = std::move(Index);
637 }
638 }
639 return CombinedIndex;
640}
641
642/**
643 * Perform promotion and renaming of exported internal functions.
644 */
645void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000646 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000647 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000648 auto ModuleIdentifier = TheModule.getModuleIdentifier();
649 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000650 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000651 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000652
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000653 // Generate import/export list
654 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
655 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
656 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
657 ExportLists);
658 auto &ExportList = ExportLists[ModuleIdentifier];
659
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000660 // Convert the preserved symbols set from string to GUID
661 auto GUIDPreservedSymbols =
662 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
663
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000664 // Resolve the LinkOnceODR, trying to turn them into "available_externally"
665 // where possible.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000666 // This is a compile-time optimization.
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000667 // We use a std::map here to be able to have a defined ordering when
668 // producing a hash for the cache entry.
669 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000670 ResolveODR(Index, ExportList, GUIDPreservedSymbols, ModuleToDefinedGVSummaries[ModuleIdentifier],
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000671 ModuleIdentifier, ResolvedODR);
672 fixupODR(TheModule, ResolvedODR);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000673
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000674 promoteModule(TheModule, Index);
675}
676
677/**
678 * Perform cross-module importing for the module identified by ModuleIdentifier.
679 */
680void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000681 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000682 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000683 auto ModuleCount = Index.modulePaths().size();
684
685 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000686 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000687 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000688
689 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000690 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
691 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000692 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
693 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000694 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
695
696 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000697}
698
699/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000700 * Compute the list of summaries needed for importing into module.
701 */
702void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
703 StringRef ModulePath, ModuleSummaryIndex &Index,
704 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
705 auto ModuleCount = Index.modulePaths().size();
706
707 // Collect for each module the list of function it defines (GUID -> Summary).
708 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
709 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
710
711 // Generate import/export list
712 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
713 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
714 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
715 ExportLists);
716
717 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
718 ImportLists,
719 ModuleToSummariesForIndex);
720}
721
722/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000723 * Emit the list of files needed for importing into module.
724 */
725void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
726 StringRef OutputName,
727 ModuleSummaryIndex &Index) {
728 auto ModuleCount = Index.modulePaths().size();
729
730 // Collect for each module the list of function it defines (GUID -> Summary).
731 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
732 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
733
734 // Generate import/export list
735 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
736 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
737 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
738 ExportLists);
739
740 std::error_code EC;
741 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists)))
742 report_fatal_error(Twine("Failed to open ") + OutputName +
743 " to save imports lists\n");
744}
745
746/**
Mehdi Amini059464f2016-04-24 03:18:01 +0000747 * Perform internalization.
748 */
749void ThinLTOCodeGenerator::internalize(Module &TheModule,
750 ModuleSummaryIndex &Index) {
751 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
752 auto ModuleCount = Index.modulePaths().size();
753 auto ModuleIdentifier = TheModule.getModuleIdentifier();
754
755 // Convert the preserved symbols set from string to GUID
756 auto GUIDPreservedSymbols =
757 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
758
759 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000760 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000761 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
762
763 // Generate import/export list
764 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
765 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
766 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
767 ExportLists);
768 auto &ExportList = ExportLists[ModuleIdentifier];
769
770 // Internalization
771 auto PreservedGV = computePreservedSymbolsForModule(
772 TheModule, GUIDPreservedSymbols, ExportList);
773 doInternalizeModule(TheModule, *TMBuilder.create(), PreservedGV);
774}
775
776/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000777 * Perform post-importing ThinLTO optimizations.
778 */
779void ThinLTOCodeGenerator::optimize(Module &TheModule) {
780 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000781
782 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000783 optimizeModule(TheModule, *TMBuilder.create());
784}
785
786/**
787 * Perform ThinLTO CodeGen.
788 */
789std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
790 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
791 return codegenModule(TheModule, *TMBuilder.create());
792}
793
794// Main entry point for the ThinLTO processing
795void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000796 if (CodeGenOnly) {
797 // Perform only parallel codegen and return.
798 ThreadPool Pool;
799 assert(ProducedBinaries.empty() && "The generator should not be reused");
800 ProducedBinaries.resize(Modules.size());
801 int count = 0;
802 for (auto &ModuleBuffer : Modules) {
803 Pool.async([&](int count) {
804 LLVMContext Context;
805 Context.setDiscardValueNames(LTODiscardValueNames);
806
807 // Parse module now
808 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
809
810 // CodeGen
811 ProducedBinaries[count] = codegen(*TheModule);
812 }, count++);
813 }
814
815 return;
816 }
817
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000818 // Sequential linking phase
819 auto Index = linkCombinedIndex();
820
821 // Save temps: index.
822 if (!SaveTempsDir.empty()) {
823 auto SaveTempPath = SaveTempsDir + "index.bc";
824 std::error_code EC;
825 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
826 if (EC)
827 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
828 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000829 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000830 }
831
832 // Prepare the resulting object vector
833 assert(ProducedBinaries.empty() && "The generator should not be reused");
834 ProducedBinaries.resize(Modules.size());
835
836 // Prepare the module map.
837 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000838 auto ModuleCount = Modules.size();
839
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000840 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000841 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000842 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
843
Mehdi Amini01e32132016-03-26 05:40:34 +0000844 // Collect the import/export lists for all modules from the call-graph in the
845 // combined index.
846 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
847 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000848 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
849 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000850
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000851 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000852 // computing the caching hash and the internalization.
853 auto GUIDPreservedSymbols =
854 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000855
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000856 // Make sure that every module has an entry in the ExportLists to enable
857 // threaded access to this map below
858 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries)
859 ExportLists[DefinedGVSummaries.first()];
860
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000861 // Compute the ordering we will process the inputs: the rough heuristic here
862 // is to sort them per size so that the largest module get schedule as soon as
863 // possible. This is purely a compile-time optimization.
864 std::vector<int> ModulesOrdering;
865 ModulesOrdering.resize(Modules.size());
866 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
867 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
868 [&](int LeftIndex, int RightIndex) {
869 auto LSize = Modules[LeftIndex].getBufferSize();
870 auto RSize = Modules[RightIndex].getBufferSize();
871 return LSize > RSize;
872 });
873
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000874 // Parallel optimizer + codegen
875 {
876 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000877 for (auto IndexCount : ModulesOrdering) {
878 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000879 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000880 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000881 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000882
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000883 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
884
885 // Resolve ODR, this has to be done early because it impacts the caching
886 // We use a std::map here to be able to have a defined ordering when
887 // producing a hash for the cache entry.
888 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000889 ResolveODR(*Index, ExportList, GUIDPreservedSymbols, DefinedFunctions, ModuleIdentifier,
Mehdi Amini059464f2016-04-24 03:18:01 +0000890 ResolvedODR);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000891
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000892 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000893 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
894 ImportLists[ModuleIdentifier], ExportList,
895 ResolvedODR, DefinedFunctions,
896 GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000897
898 {
899 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000900 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
901 << CacheEntry.getEntryPath() << "' for buffer " << count
902 << " " << ModuleIdentifier << "\n");
903
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000904 if (ErrOrBuffer) {
905 // Cache Hit!
906 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
907 return;
908 }
909 }
910
911 LLVMContext Context;
912 Context.setDiscardValueNames(LTODiscardValueNames);
913 Context.enableDebugTypeODRUniquing();
914
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000915 // Parse module now
916 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
917
918 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000919 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000920
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000921 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000922 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000923 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000924 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Mehdi Amini059464f2016-04-24 03:18:01 +0000925 ExportList, GUIDPreservedSymbols, ResolvedODR, CacheOptions,
926 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000927
Mehdi Amini001bb412016-05-16 19:11:59 +0000928 OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000929 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000930 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000931 }
932 }
933
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000934 CachePruning(CacheOptions.Path)
935 .setPruningInterval(CacheOptions.PruningInterval)
936 .setEntryExpiration(CacheOptions.Expiration)
937 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
938 .prune();
939
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000940 // If statistics were requested, print them out now.
941 if (llvm::AreStatisticsEnabled())
942 llvm::PrintStatistics();
943}