blob: 86968a736e6a5faea629e8722a5d4acbb5042aad [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 Johnsonad176792016-11-11 05:34:58 +000027#include "llvm/Bitcode/BitcodeReader.h"
28#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000029#include "llvm/Bitcode/BitcodeWriterPass.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000030#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000031#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000032#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/IR/LegacyPassManager.h"
34#include "llvm/IR/Mangler.h"
35#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000036#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000037#include "llvm/Linker/Linker.h"
38#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000039#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000040#include "llvm/Object/ModuleSummaryIndexObjectFile.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"
Teresa Johnsonec544c52016-10-19 17:35:01 +000047#include "llvm/Support/Threading.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000048#include "llvm/Target/TargetMachine.h"
49#include "llvm/Transforms/IPO.h"
50#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000051#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000052#include "llvm/Transforms/IPO/PassManagerBuilder.h"
53#include "llvm/Transforms/ObjCARC.h"
54#include "llvm/Transforms/Utils/FunctionImportUtils.h"
55
Mehdi Amini819e9cd2016-05-16 19:33:07 +000056#include <numeric>
57
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000058using namespace llvm;
59
Mehdi Amini1aafabf2016-04-16 07:02:16 +000060#define DEBUG_TYPE "thinlto"
61
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000062namespace llvm {
63// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
64extern cl::opt<bool> LTODiscardValueNames;
65}
66
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000067namespace {
68
Teresa Johnsonec544c52016-10-19 17:35:01 +000069static cl::opt<int>
70 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000071
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000072// Simple helper to save temporary files for debug.
73static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
74 unsigned count, StringRef Suffix) {
75 if (TempDir.empty())
76 return;
77 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000078 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000079 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000080 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081 if (EC)
82 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
83 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000084 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000085}
86
Teresa Johnson4d2613f2016-05-24 17:24:25 +000087static const GlobalValueSummary *
88getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
89 // If there is any strong definition anywhere, get it.
90 auto StrongDefForLinker = llvm::find_if(
91 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
92 auto Linkage = Summary->linkage();
93 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
94 !GlobalValue::isWeakForLinker(Linkage);
95 });
96 if (StrongDefForLinker != GVSummaryList.end())
97 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +000098 // Get the first *linker visible* definition for this global in the summary
99 // list.
100 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000101 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
102 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000103 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
104 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000105 // Extern templates can be emitted as available_externally.
106 if (FirstDefForLinker == GVSummaryList.end())
107 return nullptr;
108 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000109}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000110
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000111// Populate map of GUID to the prevailing copy for any multiply defined
112// symbols. Currently assume first copy is prevailing, or any strong
113// definition. Can be refined with Linker information in the future.
114static void computePrevailingCopies(
115 const ModuleSummaryIndex &Index,
116 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000117 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
118 return GVSummaryList.size() > 1;
119 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000120
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000121 for (auto &I : Index) {
122 if (HasMultipleCopies(I.second))
123 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000124 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000125}
126
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000127static StringMap<MemoryBufferRef>
128generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
129 StringMap<MemoryBufferRef> ModuleMap;
130 for (auto &ModuleBuffer : Modules) {
131 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
132 ModuleMap.end() &&
133 "Expect unique Buffer Identifier");
134 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
135 }
136 return ModuleMap;
137}
138
Teresa Johnson26ab5772016-03-15 00:04:37 +0000139static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000140 if (renameModuleForThinLTO(TheModule, Index))
141 report_fatal_error("renameModuleForThinLTO failed");
142}
143
Mehdi Amini01e32132016-03-26 05:40:34 +0000144static void
145crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
146 StringMap<MemoryBufferRef> &ModuleMap,
147 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000148 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
149 FunctionImporter Importer(Index, Loader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000150 if (!Importer.importFunctions(TheModule, ImportList))
151 report_fatal_error("importFunctions failed");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000152}
153
154static void optimizeModule(Module &TheModule, TargetMachine &TM) {
155 // Populate the PassManager
156 PassManagerBuilder PMB;
157 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
158 PMB.Inliner = createFunctionInliningPass();
159 // FIXME: should get it from the bitcode?
160 PMB.OptLevel = 3;
161 PMB.LoopVectorize = true;
162 PMB.SLPVectorize = true;
163 PMB.VerifyInput = true;
164 PMB.VerifyOutput = false;
165
166 legacy::PassManager PM;
167
168 // Add the TTI (required to inform the vectorizer about register size for
169 // instance)
170 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
171
172 // Add optimizations
173 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000174
175 PM.run(TheModule);
176}
177
Mehdi Amini059464f2016-04-24 03:18:01 +0000178// Convert the PreservedSymbols map from "Name" based to "GUID" based.
179static DenseSet<GlobalValue::GUID>
180computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
181 const Triple &TheTriple) {
182 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
183 for (auto &Entry : PreservedSymbols) {
184 StringRef Name = Entry.first();
185 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
186 Name = Name.drop_front();
187 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
188 }
189 return GUIDPreservedSymbols;
190}
191
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000192std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
193 TargetMachine &TM) {
194 SmallVector<char, 128> OutputBuffer;
195
196 // CodeGen
197 {
198 raw_svector_ostream OS(OutputBuffer);
199 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000200
201 // If the bitcode files contain ARC code and were compiled with optimization,
202 // the ObjCARCContractPass must be run, so do it unconditionally here.
203 PM.add(createObjCARCContractPass());
204
205 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000206 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
207 /* DisableVerify */ true))
208 report_fatal_error("Failed to setup codegen");
209
210 // Run codegen now. resulting binary is in OutputBuffer.
211 PM.run(TheModule);
212 }
213 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
214}
215
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000216/// Manage caching for a single Module.
217class ModuleCacheEntry {
218 SmallString<128> EntryPath;
219
220public:
221 // Create a cache entry. This compute a unique hash for the Module considering
222 // the current list of export/import, and offer an interface to query to
223 // access the content in the cache.
224 ModuleCacheEntry(
225 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
226 const FunctionImporter::ImportMapTy &ImportList,
227 const FunctionImporter::ExportSetTy &ExportList,
228 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000229 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000230 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
231 if (CachePath.empty())
232 return;
233
Mehdi Amini00fa1402016-10-08 04:44:18 +0000234 if (!Index.modulePaths().count(ModuleID))
235 // The module does not have an entry, it can't have a hash at all
236 return;
237
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000238 // Compute the unique hash for this entry
239 // This is based on the current compiler version, the module itself, the
240 // export list, the hash for every single module in the import list, the
241 // list of ResolvedODR for the module, and the list of preserved symbols.
242
Mehdi Aminif82bda02016-10-08 04:44:23 +0000243 // Include the hash for the current module
244 auto ModHash = Index.getModuleHash(ModuleID);
245
246 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
247 // No hash entry, no caching!
248 return;
249
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000250 SHA1 Hasher;
251
252 // Start with the compiler revision
253 Hasher.update(LLVM_VERSION_STRING);
254#ifdef HAVE_LLVM_REVISION
255 Hasher.update(LLVM_REVISION);
256#endif
257
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000258 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
259 for (auto F : ExportList)
260 // The export list can impact the internalization, be conservative here
261 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
262
263 // Include the hash for every module we import functions from
264 for (auto &Entry : ImportList) {
265 auto ModHash = Index.getModuleHash(Entry.first());
266 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
267 }
268
269 // Include the hash for the resolved ODR.
270 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000271 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000272 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000273 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000274 sizeof(GlobalValue::LinkageTypes)));
275 }
276
277 // Include the hash for the preserved symbols.
278 for (auto &Entry : PreservedSymbols) {
279 if (DefinedFunctions.count(Entry))
280 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000281 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000282 }
283
284 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
285 }
286
Mehdi Amini059464f2016-04-24 03:18:01 +0000287 // Access the path to this entry in the cache.
288 StringRef getEntryPath() { return EntryPath; }
289
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000290 // Try loading the buffer for this cache entry.
291 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
292 if (EntryPath.empty())
293 return std::error_code();
294 return MemoryBuffer::getFile(EntryPath);
295 }
296
297 // Cache the Produced object file
Mehdi Amini001bb412016-05-16 19:11:59 +0000298 std::unique_ptr<MemoryBuffer>
299 write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000300 if (EntryPath.empty())
Mehdi Amini001bb412016-05-16 19:11:59 +0000301 return OutputBuffer;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000302
303 // Write to a temporary to avoid race condition
304 SmallString<128> TempFilename;
305 int TempFD;
306 std::error_code EC =
307 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
308 if (EC) {
309 errs() << "Error: " << EC.message() << "\n";
310 report_fatal_error("ThinLTO: Can't get a temporary file");
311 }
312 {
313 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini001bb412016-05-16 19:11:59 +0000314 OS << OutputBuffer->getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000315 }
316 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000317 EC = sys::fs::rename(TempFilename, EntryPath);
318 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000319 sys::fs::remove(TempFilename);
320 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
321 if (EC)
322 report_fatal_error(Twine("Failed to open ") + EntryPath +
323 " to save cached entry\n");
Mehdi Amini001bb412016-05-16 19:11:59 +0000324 OS << OutputBuffer->getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000325 }
Mehdi Amini001bb412016-05-16 19:11:59 +0000326 auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
327 if (auto EC = ReloadedBufferOrErr.getError()) {
328 // FIXME diagnose
329 errs() << "error: can't reload cached file '" << EntryPath
330 << "': " << EC.message() << "\n";
331 return OutputBuffer;
332 }
333 return std::move(*ReloadedBufferOrErr);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000334 }
335};
336
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000337static std::unique_ptr<MemoryBuffer>
338ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
339 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
340 const FunctionImporter::ImportMapTy &ImportList,
341 const FunctionImporter::ExportSetTy &ExportList,
342 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
343 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000344 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000345 bool DisableCodeGen, StringRef SaveTempsDir,
346 unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000347
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000348 // "Benchmark"-like optimization: single-source case
349 bool SingleModule = (ModuleMap.size() == 1);
350
351 if (!SingleModule) {
352 promoteModule(TheModule, Index);
353
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000354 // Apply summary-based LinkOnce/Weak resolution decisions.
355 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000356
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000357 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000358 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000359 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000360
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000361 // Be friendly and don't nuke totally the module when the client didn't
362 // supply anything to preserve.
363 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
364 // Apply summary-based internalization decisions.
365 thinLTOInternalizeModule(TheModule, DefinedGlobals);
366 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000367
368 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000369 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000370
371 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000372 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000373
374 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000375 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000376 }
377
378 optimizeModule(TheModule, TM);
379
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000380 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000381
Mehdi Amini43b657b2016-04-01 06:47:02 +0000382 if (DisableCodeGen) {
383 // Configured to stop before CodeGen, serialize the bitcode and return.
384 SmallVector<char, 128> OutputBuffer;
385 {
386 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000387 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000388 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000389 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000390 }
391 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
392 }
393
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000394 return codegenModule(TheModule, TM);
395}
396
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000397/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
398/// for caching, and in the \p Index for application during the ThinLTO
399/// backends. This is needed for correctness for exported symbols (ensure
400/// at least one copy kept) and a compile-time optimization (to drop duplicate
401/// copies when possible).
402static void resolveWeakForLinkerInIndex(
403 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000404 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
405 &ResolvedODR) {
406
407 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
408 computePrevailingCopies(Index, PrevailingCopy);
409
410 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
411 const auto &Prevailing = PrevailingCopy.find(GUID);
412 // Not in map means that there was only one copy, which must be prevailing.
413 if (Prevailing == PrevailingCopy.end())
414 return true;
415 return Prevailing->second == S;
416 };
417
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000418 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
419 GlobalValue::GUID GUID,
420 GlobalValue::LinkageTypes NewLinkage) {
421 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
422 };
423
Peter Collingbourne73589f32016-07-07 18:31:51 +0000424 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000425}
426
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000427// Initialize the TargetMachine builder for a given Triple
428static void initTMBuilder(TargetMachineBuilder &TMBuilder,
429 const Triple &TheTriple) {
430 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
431 // FIXME this looks pretty terrible...
432 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
433 if (TheTriple.getArch() == llvm::Triple::x86_64)
434 TMBuilder.MCpu = "core2";
435 else if (TheTriple.getArch() == llvm::Triple::x86)
436 TMBuilder.MCpu = "yonah";
437 else if (TheTriple.getArch() == llvm::Triple::aarch64)
438 TMBuilder.MCpu = "cyclone";
439 }
440 TMBuilder.TheTriple = std::move(TheTriple);
441}
442
443} // end anonymous namespace
444
445void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
446 MemoryBufferRef Buffer(Data, Identifier);
447 if (Modules.empty()) {
448 // First module added, so initialize the triple and some options
449 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000450 StringRef TripleStr;
451 ErrorOr<std::string> TripleOrErr =
452 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
453 if (TripleOrErr)
454 TripleStr = *TripleOrErr;
455 Triple TheTriple(TripleStr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000456 initTMBuilder(TMBuilder, Triple(TheTriple));
457 }
458#ifndef NDEBUG
459 else {
460 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000461 StringRef TripleStr;
462 ErrorOr<std::string> TripleOrErr =
463 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
464 if (TripleOrErr)
465 TripleStr = *TripleOrErr;
466 assert(TMBuilder.TheTriple.str() == TripleStr &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000467 "ThinLTO modules with different triple not supported");
468 }
469#endif
470 Modules.push_back(Buffer);
471}
472
473void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
474 PreservedSymbols.insert(Name);
475}
476
477void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000478 // FIXME: At the moment, we don't take advantage of this extra information,
479 // we're conservatively considering cross-references as preserved.
480 // CrossReferencedSymbols.insert(Name);
481 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000482}
483
484// TargetMachine factory
485std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
486 std::string ErrMsg;
487 const Target *TheTarget =
488 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
489 if (!TheTarget) {
490 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
491 }
492
493 // Use MAttr as the default set of features.
494 SubtargetFeatures Features(MAttr);
495 Features.getDefaultSubtargetFeatures(TheTriple);
496 std::string FeatureStr = Features.getString();
497 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
498 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
499 CodeModel::Default, CGOptLevel));
500}
501
502/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000503 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000504 * "thin-link".
505 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000506std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
507 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000508 uint64_t NextModuleId = 0;
509 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000510 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
511 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer);
512 if (!ObjOrErr) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000513 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000514 logAllUnhandledErrors(
515 ObjOrErr.takeError(), errs(),
516 "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000517 return nullptr;
518 }
519 auto Index = (*ObjOrErr)->takeIndex();
520 if (CombinedIndex) {
521 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
522 } else {
523 CombinedIndex = std::move(Index);
524 }
525 }
526 return CombinedIndex;
527}
528
529/**
530 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000531 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000532 */
533void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000534 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000535 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000536 auto ModuleIdentifier = TheModule.getModuleIdentifier();
537 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000538 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000539 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000540
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000541 // Generate import/export list
542 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
543 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
544 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
545 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000546
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000547 // Resolve LinkOnce/Weak symbols.
548 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000549 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000550
551 thinLTOResolveWeakForLinkerModule(
552 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000553
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000554 promoteModule(TheModule, Index);
555}
556
557/**
558 * Perform cross-module importing for the module identified by ModuleIdentifier.
559 */
560void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000561 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000562 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000563 auto ModuleCount = Index.modulePaths().size();
564
565 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000566 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000567 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000568
569 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000570 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
571 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000572 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
573 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000574 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
575
576 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000577}
578
579/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000580 * Compute the list of summaries needed for importing into module.
581 */
582void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
583 StringRef ModulePath, ModuleSummaryIndex &Index,
584 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
585 auto ModuleCount = Index.modulePaths().size();
586
587 // Collect for each module the list of function it defines (GUID -> Summary).
588 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
589 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
590
591 // Generate import/export list
592 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
593 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
594 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
595 ExportLists);
596
597 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000598 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000599 ModuleToSummariesForIndex);
600}
601
602/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000603 * Emit the list of files needed for importing into module.
604 */
605void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
606 StringRef OutputName,
607 ModuleSummaryIndex &Index) {
608 auto ModuleCount = Index.modulePaths().size();
609
610 // Collect for each module the list of function it defines (GUID -> Summary).
611 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
612 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
613
614 // Generate import/export list
615 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
616 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
617 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
618 ExportLists);
619
620 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000621 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000622 report_fatal_error(Twine("Failed to open ") + OutputName +
623 " to save imports lists\n");
624}
625
626/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000627 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000628 */
629void ThinLTOCodeGenerator::internalize(Module &TheModule,
630 ModuleSummaryIndex &Index) {
631 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
632 auto ModuleCount = Index.modulePaths().size();
633 auto ModuleIdentifier = TheModule.getModuleIdentifier();
634
635 // Convert the preserved symbols set from string to GUID
636 auto GUIDPreservedSymbols =
637 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
638
639 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000640 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000641 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
642
643 // Generate import/export list
644 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
645 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
646 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
647 ExportLists);
648 auto &ExportList = ExportLists[ModuleIdentifier];
649
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000650 // Be friendly and don't nuke totally the module when the client didn't
651 // supply anything to preserve.
652 if (ExportList.empty() && GUIDPreservedSymbols.empty())
653 return;
654
Mehdi Amini059464f2016-04-24 03:18:01 +0000655 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000656 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
657 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000658 return (ExportList != ExportLists.end() &&
659 ExportList->second.count(GUID)) ||
660 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000661 };
662 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
663 thinLTOInternalizeModule(TheModule,
664 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000665}
666
667/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000668 * Perform post-importing ThinLTO optimizations.
669 */
670void ThinLTOCodeGenerator::optimize(Module &TheModule) {
671 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000672
673 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000674 optimizeModule(TheModule, *TMBuilder.create());
675}
676
677/**
678 * Perform ThinLTO CodeGen.
679 */
680std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
681 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
682 return codegenModule(TheModule, *TMBuilder.create());
683}
684
685// Main entry point for the ThinLTO processing
686void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000687 if (CodeGenOnly) {
688 // Perform only parallel codegen and return.
689 ThreadPool Pool;
690 assert(ProducedBinaries.empty() && "The generator should not be reused");
691 ProducedBinaries.resize(Modules.size());
692 int count = 0;
693 for (auto &ModuleBuffer : Modules) {
694 Pool.async([&](int count) {
695 LLVMContext Context;
696 Context.setDiscardValueNames(LTODiscardValueNames);
697
698 // Parse module now
699 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
700
701 // CodeGen
702 ProducedBinaries[count] = codegen(*TheModule);
703 }, count++);
704 }
705
706 return;
707 }
708
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000709 // Sequential linking phase
710 auto Index = linkCombinedIndex();
711
712 // Save temps: index.
713 if (!SaveTempsDir.empty()) {
714 auto SaveTempPath = SaveTempsDir + "index.bc";
715 std::error_code EC;
716 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
717 if (EC)
718 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
719 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000720 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000721 }
722
723 // Prepare the resulting object vector
724 assert(ProducedBinaries.empty() && "The generator should not be reused");
725 ProducedBinaries.resize(Modules.size());
726
727 // Prepare the module map.
728 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000729 auto ModuleCount = Modules.size();
730
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000731 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000732 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000733 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
734
Mehdi Amini01e32132016-03-26 05:40:34 +0000735 // Collect the import/export lists for all modules from the call-graph in the
736 // combined index.
737 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
738 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000739 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
740 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000741
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000742 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000743 // computing the caching hash and the internalization.
744 auto GUIDPreservedSymbols =
745 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000746
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000747 // We use a std::map here to be able to have a defined ordering when
748 // producing a hash for the cache entry.
749 // FIXME: we should be able to compute the caching hash for the entry based
750 // on the index, and nuke this map.
751 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
752
753 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
754 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000755 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000756
757 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
758 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000759 return (ExportList != ExportLists.end() &&
760 ExportList->second.count(GUID)) ||
761 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000762 };
763
764 // Use global summary-based analysis to identify symbols that can be
765 // internalized (because they aren't exported or preserved as per callback).
766 // Changes are made in the index, consumed in the ThinLTO backends.
767 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
768
Teresa Johnson141149f2016-05-24 18:44:01 +0000769 // Make sure that every module has an entry in the ExportLists and
770 // ResolvedODR maps to enable threaded access to these maps below.
771 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000772 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000773 ResolvedODR[DefinedGVSummaries.first()];
774 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000775
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000776 // Compute the ordering we will process the inputs: the rough heuristic here
777 // is to sort them per size so that the largest module get schedule as soon as
778 // possible. This is purely a compile-time optimization.
779 std::vector<int> ModulesOrdering;
780 ModulesOrdering.resize(Modules.size());
781 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
782 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
783 [&](int LeftIndex, int RightIndex) {
784 auto LSize = Modules[LeftIndex].getBufferSize();
785 auto RSize = Modules[RightIndex].getBufferSize();
786 return LSize > RSize;
787 });
788
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000789 // Parallel optimizer + codegen
790 {
791 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000792 for (auto IndexCount : ModulesOrdering) {
793 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000794 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000795 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000796 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000797
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000798 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
799
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000800 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000801 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
802 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000803 ResolvedODR[ModuleIdentifier],
804 DefinedFunctions, GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000805
806 {
807 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000808 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
809 << CacheEntry.getEntryPath() << "' for buffer " << count
810 << " " << ModuleIdentifier << "\n");
811
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000812 if (ErrOrBuffer) {
813 // Cache Hit!
814 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
815 return;
816 }
817 }
818
819 LLVMContext Context;
820 Context.setDiscardValueNames(LTODiscardValueNames);
821 Context.enableDebugTypeODRUniquing();
822
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000823 // Parse module now
824 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
825
826 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000827 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000828
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000829 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000830 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000831 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000832 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000833 ExportList, GUIDPreservedSymbols,
834 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Amini059464f2016-04-24 03:18:01 +0000835 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000836
Mehdi Amini001bb412016-05-16 19:11:59 +0000837 OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000838 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000839 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000840 }
841 }
842
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000843 CachePruning(CacheOptions.Path)
Pavel Labath757ca882016-10-24 10:59:17 +0000844 .setPruningInterval(std::chrono::seconds(CacheOptions.PruningInterval))
845 .setEntryExpiration(std::chrono::seconds(CacheOptions.Expiration))
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000846 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
847 .prune();
848
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000849 // If statistics were requested, print them out now.
850 if (llvm::AreStatisticsEnabled())
851 llvm::PrintStatistics();
852}