blob: 5baecc2bdacd3822d7dae0a83c77f321239cd190 [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
Peter Collingbourne5c732202016-07-14 21:21:16 +000015#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000016
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
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000021#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000022#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000023#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000024#include "llvm/Analysis/ProfileSummaryInfo.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 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/TargetRegistry.h"
45#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000046#include "llvm/Support/Threading.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000047#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
Teresa Johnsonec544c52016-10-19 17:35:01 +000068static cl::opt<int>
69 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000070
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.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000083 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000084 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000085 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000086 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 Johnson4d2613f2016-05-24 17:24:25 +000092static const GlobalValueSummary *
93getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
94 // If there is any strong definition anywhere, get it.
95 auto StrongDefForLinker = llvm::find_if(
96 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
97 auto Linkage = Summary->linkage();
98 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
99 !GlobalValue::isWeakForLinker(Linkage);
100 });
101 if (StrongDefForLinker != GVSummaryList.end())
102 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000103 // Get the first *linker visible* definition for this global in the summary
104 // list.
105 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000106 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
107 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000108 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
109 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000110 // Extern templates can be emitted as available_externally.
111 if (FirstDefForLinker == GVSummaryList.end())
112 return nullptr;
113 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000114}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000115
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000116// Populate map of GUID to the prevailing copy for any multiply defined
117// symbols. Currently assume first copy is prevailing, or any strong
118// definition. Can be refined with Linker information in the future.
119static void computePrevailingCopies(
120 const ModuleSummaryIndex &Index,
121 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000122 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
123 return GVSummaryList.size() > 1;
124 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000125
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000126 for (auto &I : Index) {
127 if (HasMultipleCopies(I.second))
128 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000129 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000130}
131
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000132static StringMap<MemoryBufferRef>
133generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
134 StringMap<MemoryBufferRef> ModuleMap;
135 for (auto &ModuleBuffer : Modules) {
136 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
137 ModuleMap.end() &&
138 "Expect unique Buffer Identifier");
139 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
140 }
141 return ModuleMap;
142}
143
Teresa Johnson26ab5772016-03-15 00:04:37 +0000144static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000145 if (renameModuleForThinLTO(TheModule, Index))
146 report_fatal_error("renameModuleForThinLTO failed");
147}
148
Mehdi Amini01e32132016-03-26 05:40:34 +0000149static void
150crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
151 StringMap<MemoryBufferRef> &ModuleMap,
152 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000153 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
154 FunctionImporter Importer(Index, Loader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000155 if (!Importer.importFunctions(TheModule, ImportList))
156 report_fatal_error("importFunctions failed");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000157}
158
159static void optimizeModule(Module &TheModule, TargetMachine &TM) {
160 // Populate the PassManager
161 PassManagerBuilder PMB;
162 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
163 PMB.Inliner = createFunctionInliningPass();
164 // FIXME: should get it from the bitcode?
165 PMB.OptLevel = 3;
166 PMB.LoopVectorize = true;
167 PMB.SLPVectorize = true;
168 PMB.VerifyInput = true;
169 PMB.VerifyOutput = false;
170
171 legacy::PassManager PM;
172
173 // Add the TTI (required to inform the vectorizer about register size for
174 // instance)
175 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
176
177 // Add optimizations
178 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000179
180 PM.run(TheModule);
181}
182
Mehdi Amini059464f2016-04-24 03:18:01 +0000183// Convert the PreservedSymbols map from "Name" based to "GUID" based.
184static DenseSet<GlobalValue::GUID>
185computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
186 const Triple &TheTriple) {
187 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
188 for (auto &Entry : PreservedSymbols) {
189 StringRef Name = Entry.first();
190 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
191 Name = Name.drop_front();
192 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
193 }
194 return GUIDPreservedSymbols;
195}
196
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000197std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
198 TargetMachine &TM) {
199 SmallVector<char, 128> OutputBuffer;
200
201 // CodeGen
202 {
203 raw_svector_ostream OS(OutputBuffer);
204 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000205
206 // If the bitcode files contain ARC code and were compiled with optimization,
207 // the ObjCARCContractPass must be run, so do it unconditionally here.
208 PM.add(createObjCARCContractPass());
209
210 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000211 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
212 /* DisableVerify */ true))
213 report_fatal_error("Failed to setup codegen");
214
215 // Run codegen now. resulting binary is in OutputBuffer.
216 PM.run(TheModule);
217 }
218 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
219}
220
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000221/// Manage caching for a single Module.
222class ModuleCacheEntry {
223 SmallString<128> EntryPath;
224
225public:
226 // Create a cache entry. This compute a unique hash for the Module considering
227 // the current list of export/import, and offer an interface to query to
228 // access the content in the cache.
229 ModuleCacheEntry(
230 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
231 const FunctionImporter::ImportMapTy &ImportList,
232 const FunctionImporter::ExportSetTy &ExportList,
233 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000234 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000235 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
236 if (CachePath.empty())
237 return;
238
Mehdi Amini00fa1402016-10-08 04:44:18 +0000239 if (!Index.modulePaths().count(ModuleID))
240 // The module does not have an entry, it can't have a hash at all
241 return;
242
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000243 // Compute the unique hash for this entry
244 // This is based on the current compiler version, the module itself, the
245 // export list, the hash for every single module in the import list, the
246 // list of ResolvedODR for the module, and the list of preserved symbols.
247
Mehdi Aminif82bda02016-10-08 04:44:23 +0000248 // Include the hash for the current module
249 auto ModHash = Index.getModuleHash(ModuleID);
250
251 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
252 // No hash entry, no caching!
253 return;
254
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000255 SHA1 Hasher;
256
257 // Start with the compiler revision
258 Hasher.update(LLVM_VERSION_STRING);
259#ifdef HAVE_LLVM_REVISION
260 Hasher.update(LLVM_REVISION);
261#endif
262
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000263 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
264 for (auto F : ExportList)
265 // The export list can impact the internalization, be conservative here
266 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
267
268 // Include the hash for every module we import functions from
269 for (auto &Entry : ImportList) {
270 auto ModHash = Index.getModuleHash(Entry.first());
271 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
272 }
273
274 // Include the hash for the resolved ODR.
275 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000276 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000277 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000278 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000279 sizeof(GlobalValue::LinkageTypes)));
280 }
281
282 // Include the hash for the preserved symbols.
283 for (auto &Entry : PreservedSymbols) {
284 if (DefinedFunctions.count(Entry))
285 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000286 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000287 }
288
289 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
290 }
291
Mehdi Amini059464f2016-04-24 03:18:01 +0000292 // Access the path to this entry in the cache.
293 StringRef getEntryPath() { return EntryPath; }
294
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000295 // Try loading the buffer for this cache entry.
296 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
297 if (EntryPath.empty())
298 return std::error_code();
299 return MemoryBuffer::getFile(EntryPath);
300 }
301
302 // Cache the Produced object file
Mehdi Amini001bb412016-05-16 19:11:59 +0000303 std::unique_ptr<MemoryBuffer>
304 write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000305 if (EntryPath.empty())
Mehdi Amini001bb412016-05-16 19:11:59 +0000306 return OutputBuffer;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000307
308 // Write to a temporary to avoid race condition
309 SmallString<128> TempFilename;
310 int TempFD;
311 std::error_code EC =
312 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
313 if (EC) {
314 errs() << "Error: " << EC.message() << "\n";
315 report_fatal_error("ThinLTO: Can't get a temporary file");
316 }
317 {
318 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini001bb412016-05-16 19:11:59 +0000319 OS << OutputBuffer->getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000320 }
321 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000322 EC = sys::fs::rename(TempFilename, EntryPath);
323 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000324 sys::fs::remove(TempFilename);
325 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
326 if (EC)
327 report_fatal_error(Twine("Failed to open ") + EntryPath +
328 " to save cached entry\n");
Mehdi Amini001bb412016-05-16 19:11:59 +0000329 OS << OutputBuffer->getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000330 }
Mehdi Amini001bb412016-05-16 19:11:59 +0000331 auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
332 if (auto EC = ReloadedBufferOrErr.getError()) {
333 // FIXME diagnose
334 errs() << "error: can't reload cached file '" << EntryPath
335 << "': " << EC.message() << "\n";
336 return OutputBuffer;
337 }
338 return std::move(*ReloadedBufferOrErr);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000339 }
340};
341
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000342static std::unique_ptr<MemoryBuffer>
343ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
344 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
345 const FunctionImporter::ImportMapTy &ImportList,
346 const FunctionImporter::ExportSetTy &ExportList,
347 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
348 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000349 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000350 bool DisableCodeGen, StringRef SaveTempsDir,
351 unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000352
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000353 // "Benchmark"-like optimization: single-source case
354 bool SingleModule = (ModuleMap.size() == 1);
355
356 if (!SingleModule) {
357 promoteModule(TheModule, Index);
358
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000359 // Apply summary-based LinkOnce/Weak resolution decisions.
360 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000361
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000362 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000363 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000364 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000365
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000366 // Be friendly and don't nuke totally the module when the client didn't
367 // supply anything to preserve.
368 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
369 // Apply summary-based internalization decisions.
370 thinLTOInternalizeModule(TheModule, DefinedGlobals);
371 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000372
373 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000374 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000375
376 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000377 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000378
379 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000380 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000381 }
382
383 optimizeModule(TheModule, TM);
384
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000385 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000386
Mehdi Amini43b657b2016-04-01 06:47:02 +0000387 if (DisableCodeGen) {
388 // Configured to stop before CodeGen, serialize the bitcode and return.
389 SmallVector<char, 128> OutputBuffer;
390 {
391 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000392 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000393 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000394 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000395 }
396 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
397 }
398
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000399 return codegenModule(TheModule, TM);
400}
401
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000402/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
403/// for caching, and in the \p Index for application during the ThinLTO
404/// backends. This is needed for correctness for exported symbols (ensure
405/// at least one copy kept) and a compile-time optimization (to drop duplicate
406/// copies when possible).
407static void resolveWeakForLinkerInIndex(
408 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000409 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
410 &ResolvedODR) {
411
412 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
413 computePrevailingCopies(Index, PrevailingCopy);
414
415 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
416 const auto &Prevailing = PrevailingCopy.find(GUID);
417 // Not in map means that there was only one copy, which must be prevailing.
418 if (Prevailing == PrevailingCopy.end())
419 return true;
420 return Prevailing->second == S;
421 };
422
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000423 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
424 GlobalValue::GUID GUID,
425 GlobalValue::LinkageTypes NewLinkage) {
426 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
427 };
428
Peter Collingbourne73589f32016-07-07 18:31:51 +0000429 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000430}
431
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000432// Initialize the TargetMachine builder for a given Triple
433static void initTMBuilder(TargetMachineBuilder &TMBuilder,
434 const Triple &TheTriple) {
435 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
436 // FIXME this looks pretty terrible...
437 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
438 if (TheTriple.getArch() == llvm::Triple::x86_64)
439 TMBuilder.MCpu = "core2";
440 else if (TheTriple.getArch() == llvm::Triple::x86)
441 TMBuilder.MCpu = "yonah";
442 else if (TheTriple.getArch() == llvm::Triple::aarch64)
443 TMBuilder.MCpu = "cyclone";
444 }
445 TMBuilder.TheTriple = std::move(TheTriple);
446}
447
448} // end anonymous namespace
449
450void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
451 MemoryBufferRef Buffer(Data, Identifier);
452 if (Modules.empty()) {
453 // First module added, so initialize the triple and some options
454 LLVMContext Context;
455 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
456 initTMBuilder(TMBuilder, Triple(TheTriple));
457 }
458#ifndef NDEBUG
459 else {
460 LLVMContext Context;
461 assert(TMBuilder.TheTriple.str() ==
462 getBitcodeTargetTriple(Buffer, Context) &&
463 "ThinLTO modules with different triple not supported");
464 }
465#endif
466 Modules.push_back(Buffer);
467}
468
469void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
470 PreservedSymbols.insert(Name);
471}
472
473void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000474 // FIXME: At the moment, we don't take advantage of this extra information,
475 // we're conservatively considering cross-references as preserved.
476 // CrossReferencedSymbols.insert(Name);
477 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000478}
479
480// TargetMachine factory
481std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
482 std::string ErrMsg;
483 const Target *TheTarget =
484 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
485 if (!TheTarget) {
486 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
487 }
488
489 // Use MAttr as the default set of features.
490 SubtargetFeatures Features(MAttr);
491 Features.getDefaultSubtargetFeatures(TheTriple);
492 std::string FeatureStr = Features.getString();
493 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
494 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
495 CodeModel::Default, CGOptLevel));
496}
497
498/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000499 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000500 * "thin-link".
501 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000502std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
503 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000504 uint64_t NextModuleId = 0;
505 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000506 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
507 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000508 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000509 if (std::error_code EC = ObjOrErr.getError()) {
510 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000511 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000512 << EC.message() << "\n";
513 return nullptr;
514 }
515 auto Index = (*ObjOrErr)->takeIndex();
516 if (CombinedIndex) {
517 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
518 } else {
519 CombinedIndex = std::move(Index);
520 }
521 }
522 return CombinedIndex;
523}
524
525/**
526 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000527 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000528 */
529void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000530 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000531 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000532 auto ModuleIdentifier = TheModule.getModuleIdentifier();
533 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000534 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000535 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000536
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000537 // Generate import/export list
538 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
539 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
540 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
541 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000542
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000543 // Resolve LinkOnce/Weak symbols.
544 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000545 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000546
547 thinLTOResolveWeakForLinkerModule(
548 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000549
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000550 promoteModule(TheModule, Index);
551}
552
553/**
554 * Perform cross-module importing for the module identified by ModuleIdentifier.
555 */
556void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000557 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000558 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000559 auto ModuleCount = Index.modulePaths().size();
560
561 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000562 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000563 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000564
565 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000566 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
567 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000568 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
569 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000570 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
571
572 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000573}
574
575/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000576 * Compute the list of summaries needed for importing into module.
577 */
578void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
579 StringRef ModulePath, ModuleSummaryIndex &Index,
580 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
581 auto ModuleCount = Index.modulePaths().size();
582
583 // Collect for each module the list of function it defines (GUID -> Summary).
584 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
585 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
586
587 // Generate import/export list
588 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
589 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
590 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
591 ExportLists);
592
593 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000594 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000595 ModuleToSummariesForIndex);
596}
597
598/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000599 * Emit the list of files needed for importing into module.
600 */
601void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
602 StringRef OutputName,
603 ModuleSummaryIndex &Index) {
604 auto ModuleCount = Index.modulePaths().size();
605
606 // Collect for each module the list of function it defines (GUID -> Summary).
607 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
608 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
609
610 // Generate import/export list
611 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
612 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
613 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
614 ExportLists);
615
616 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000617 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000618 report_fatal_error(Twine("Failed to open ") + OutputName +
619 " to save imports lists\n");
620}
621
622/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000623 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000624 */
625void ThinLTOCodeGenerator::internalize(Module &TheModule,
626 ModuleSummaryIndex &Index) {
627 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
628 auto ModuleCount = Index.modulePaths().size();
629 auto ModuleIdentifier = TheModule.getModuleIdentifier();
630
631 // Convert the preserved symbols set from string to GUID
632 auto GUIDPreservedSymbols =
633 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
634
635 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000636 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000637 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
638
639 // Generate import/export list
640 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
641 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
642 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
643 ExportLists);
644 auto &ExportList = ExportLists[ModuleIdentifier];
645
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000646 // Be friendly and don't nuke totally the module when the client didn't
647 // supply anything to preserve.
648 if (ExportList.empty() && GUIDPreservedSymbols.empty())
649 return;
650
Mehdi Amini059464f2016-04-24 03:18:01 +0000651 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000652 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
653 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000654 return (ExportList != ExportLists.end() &&
655 ExportList->second.count(GUID)) ||
656 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000657 };
658 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
659 thinLTOInternalizeModule(TheModule,
660 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000661}
662
663/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000664 * Perform post-importing ThinLTO optimizations.
665 */
666void ThinLTOCodeGenerator::optimize(Module &TheModule) {
667 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000668
669 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000670 optimizeModule(TheModule, *TMBuilder.create());
671}
672
673/**
674 * Perform ThinLTO CodeGen.
675 */
676std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
677 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
678 return codegenModule(TheModule, *TMBuilder.create());
679}
680
681// Main entry point for the ThinLTO processing
682void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000683 if (CodeGenOnly) {
684 // Perform only parallel codegen and return.
685 ThreadPool Pool;
686 assert(ProducedBinaries.empty() && "The generator should not be reused");
687 ProducedBinaries.resize(Modules.size());
688 int count = 0;
689 for (auto &ModuleBuffer : Modules) {
690 Pool.async([&](int count) {
691 LLVMContext Context;
692 Context.setDiscardValueNames(LTODiscardValueNames);
693
694 // Parse module now
695 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
696
697 // CodeGen
698 ProducedBinaries[count] = codegen(*TheModule);
699 }, count++);
700 }
701
702 return;
703 }
704
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000705 // Sequential linking phase
706 auto Index = linkCombinedIndex();
707
708 // Save temps: index.
709 if (!SaveTempsDir.empty()) {
710 auto SaveTempPath = SaveTempsDir + "index.bc";
711 std::error_code EC;
712 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
713 if (EC)
714 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
715 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000716 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000717 }
718
719 // Prepare the resulting object vector
720 assert(ProducedBinaries.empty() && "The generator should not be reused");
721 ProducedBinaries.resize(Modules.size());
722
723 // Prepare the module map.
724 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000725 auto ModuleCount = Modules.size();
726
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000727 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000728 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000729 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
730
Mehdi Amini01e32132016-03-26 05:40:34 +0000731 // Collect the import/export lists for all modules from the call-graph in the
732 // combined index.
733 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
734 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000735 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
736 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000737
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000738 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000739 // computing the caching hash and the internalization.
740 auto GUIDPreservedSymbols =
741 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000742
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000743 // We use a std::map here to be able to have a defined ordering when
744 // producing a hash for the cache entry.
745 // FIXME: we should be able to compute the caching hash for the entry based
746 // on the index, and nuke this map.
747 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
748
749 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
750 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000751 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000752
753 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
754 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000755 return (ExportList != ExportLists.end() &&
756 ExportList->second.count(GUID)) ||
757 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000758 };
759
760 // Use global summary-based analysis to identify symbols that can be
761 // internalized (because they aren't exported or preserved as per callback).
762 // Changes are made in the index, consumed in the ThinLTO backends.
763 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
764
Teresa Johnson141149f2016-05-24 18:44:01 +0000765 // Make sure that every module has an entry in the ExportLists and
766 // ResolvedODR maps to enable threaded access to these maps below.
767 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000768 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000769 ResolvedODR[DefinedGVSummaries.first()];
770 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000771
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000772 // Compute the ordering we will process the inputs: the rough heuristic here
773 // is to sort them per size so that the largest module get schedule as soon as
774 // possible. This is purely a compile-time optimization.
775 std::vector<int> ModulesOrdering;
776 ModulesOrdering.resize(Modules.size());
777 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
778 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
779 [&](int LeftIndex, int RightIndex) {
780 auto LSize = Modules[LeftIndex].getBufferSize();
781 auto RSize = Modules[RightIndex].getBufferSize();
782 return LSize > RSize;
783 });
784
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000785 // Parallel optimizer + codegen
786 {
787 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000788 for (auto IndexCount : ModulesOrdering) {
789 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000790 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000791 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000792 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000793
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000794 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
795
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000796 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000797 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
798 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000799 ResolvedODR[ModuleIdentifier],
800 DefinedFunctions, GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000801
802 {
803 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000804 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
805 << CacheEntry.getEntryPath() << "' for buffer " << count
806 << " " << ModuleIdentifier << "\n");
807
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000808 if (ErrOrBuffer) {
809 // Cache Hit!
810 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
811 return;
812 }
813 }
814
815 LLVMContext Context;
816 Context.setDiscardValueNames(LTODiscardValueNames);
817 Context.enableDebugTypeODRUniquing();
818
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000819 // Parse module now
820 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
821
822 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000823 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000824
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000825 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000826 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000827 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000828 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000829 ExportList, GUIDPreservedSymbols,
830 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Amini059464f2016-04-24 03:18:01 +0000831 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000832
Mehdi Amini001bb412016-05-16 19:11:59 +0000833 OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000834 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000835 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000836 }
837 }
838
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000839 CachePruning(CacheOptions.Path)
Pavel Labath757ca882016-10-24 10:59:17 +0000840 .setPruningInterval(std::chrono::seconds(CacheOptions.PruningInterval))
841 .setEntryExpiration(std::chrono::seconds(CacheOptions.Expiration))
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000842 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
843 .prune();
844
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000845 // If statistics were requested, print them out now.
846 if (llvm::AreStatisticsEnabled())
847 llvm::PrintStatistics();
848}