blob: f4232dc2f8979b2418e7bbe38129d8856ad1cd12 [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"
46#include "llvm/Target/TargetMachine.h"
47#include "llvm/Transforms/IPO.h"
48#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000049#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000050#include "llvm/Transforms/IPO/PassManagerBuilder.h"
51#include "llvm/Transforms/ObjCARC.h"
52#include "llvm/Transforms/Utils/FunctionImportUtils.h"
53
Mehdi Amini819e9cd2016-05-16 19:33:07 +000054#include <numeric>
55
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000056using namespace llvm;
57
Mehdi Amini1aafabf2016-04-16 07:02:16 +000058#define DEBUG_TYPE "thinlto"
59
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000060namespace llvm {
61// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
62extern cl::opt<bool> LTODiscardValueNames;
63}
64
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000065namespace {
66
67static cl::opt<int> ThreadCount("threads",
68 cl::init(std::thread::hardware_concurrency()));
69
70static void diagnosticHandler(const DiagnosticInfo &DI) {
71 DiagnosticPrinterRawOStream DP(errs());
72 DI.print(DP);
73 errs() << '\n';
74}
75
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000076// Simple helper to save temporary files for debug.
77static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
78 unsigned count, StringRef Suffix) {
79 if (TempDir.empty())
80 return;
81 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000082 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000083 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000084 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000085 if (EC)
86 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
87 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000088 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000089}
90
Teresa Johnson4d2613f2016-05-24 17:24:25 +000091static const GlobalValueSummary *
92getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
93 // If there is any strong definition anywhere, get it.
94 auto StrongDefForLinker = llvm::find_if(
95 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
96 auto Linkage = Summary->linkage();
97 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
98 !GlobalValue::isWeakForLinker(Linkage);
99 });
100 if (StrongDefForLinker != GVSummaryList.end())
101 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000102 // Get the first *linker visible* definition for this global in the summary
103 // list.
104 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000105 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
106 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000107 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
108 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000109 // Extern templates can be emitted as available_externally.
110 if (FirstDefForLinker == GVSummaryList.end())
111 return nullptr;
112 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000113}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000114
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000115// Populate map of GUID to the prevailing copy for any multiply defined
116// symbols. Currently assume first copy is prevailing, or any strong
117// definition. Can be refined with Linker information in the future.
118static void computePrevailingCopies(
119 const ModuleSummaryIndex &Index,
120 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000121 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
122 return GVSummaryList.size() > 1;
123 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000124
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000125 for (auto &I : Index) {
126 if (HasMultipleCopies(I.second))
127 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000128 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000129}
130
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000131static StringMap<MemoryBufferRef>
132generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
133 StringMap<MemoryBufferRef> ModuleMap;
134 for (auto &ModuleBuffer : Modules) {
135 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
136 ModuleMap.end() &&
137 "Expect unique Buffer Identifier");
138 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
139 }
140 return ModuleMap;
141}
142
Teresa Johnson26ab5772016-03-15 00:04:37 +0000143static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000144 if (renameModuleForThinLTO(TheModule, Index))
145 report_fatal_error("renameModuleForThinLTO failed");
146}
147
Mehdi Amini01e32132016-03-26 05:40:34 +0000148static void
149crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
150 StringMap<MemoryBufferRef> &ModuleMap,
151 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000152 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
153 FunctionImporter Importer(Index, Loader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000154 Importer.importFunctions(TheModule, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000155}
156
157static void optimizeModule(Module &TheModule, TargetMachine &TM) {
158 // Populate the PassManager
159 PassManagerBuilder PMB;
160 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
161 PMB.Inliner = createFunctionInliningPass();
162 // FIXME: should get it from the bitcode?
163 PMB.OptLevel = 3;
164 PMB.LoopVectorize = true;
165 PMB.SLPVectorize = true;
166 PMB.VerifyInput = true;
167 PMB.VerifyOutput = false;
168
169 legacy::PassManager PM;
170
171 // Add the TTI (required to inform the vectorizer about register size for
172 // instance)
173 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
174
175 // Add optimizations
176 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000177
178 PM.run(TheModule);
179}
180
Mehdi Amini059464f2016-04-24 03:18:01 +0000181// Convert the PreservedSymbols map from "Name" based to "GUID" based.
182static DenseSet<GlobalValue::GUID>
183computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
184 const Triple &TheTriple) {
185 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
186 for (auto &Entry : PreservedSymbols) {
187 StringRef Name = Entry.first();
188 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
189 Name = Name.drop_front();
190 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
191 }
192 return GUIDPreservedSymbols;
193}
194
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000195std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
196 TargetMachine &TM) {
197 SmallVector<char, 128> OutputBuffer;
198
199 // CodeGen
200 {
201 raw_svector_ostream OS(OutputBuffer);
202 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000203
204 // If the bitcode files contain ARC code and were compiled with optimization,
205 // the ObjCARCContractPass must be run, so do it unconditionally here.
206 PM.add(createObjCARCContractPass());
207
208 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000209 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
210 /* DisableVerify */ true))
211 report_fatal_error("Failed to setup codegen");
212
213 // Run codegen now. resulting binary is in OutputBuffer.
214 PM.run(TheModule);
215 }
216 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
217}
218
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000219/// Manage caching for a single Module.
220class ModuleCacheEntry {
221 SmallString<128> EntryPath;
222
223public:
224 // Create a cache entry. This compute a unique hash for the Module considering
225 // the current list of export/import, and offer an interface to query to
226 // access the content in the cache.
227 ModuleCacheEntry(
228 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
229 const FunctionImporter::ImportMapTy &ImportList,
230 const FunctionImporter::ExportSetTy &ExportList,
231 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000232 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000233 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
234 if (CachePath.empty())
235 return;
236
237 // Compute the unique hash for this entry
238 // This is based on the current compiler version, the module itself, the
239 // export list, the hash for every single module in the import list, the
240 // list of ResolvedODR for the module, and the list of preserved symbols.
241
242 SHA1 Hasher;
243
244 // Start with the compiler revision
245 Hasher.update(LLVM_VERSION_STRING);
246#ifdef HAVE_LLVM_REVISION
247 Hasher.update(LLVM_REVISION);
248#endif
249
250 // Include the hash for the current module
251 auto ModHash = Index.getModuleHash(ModuleID);
252 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
253 for (auto F : ExportList)
254 // The export list can impact the internalization, be conservative here
255 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
256
257 // Include the hash for every module we import functions from
258 for (auto &Entry : ImportList) {
259 auto ModHash = Index.getModuleHash(Entry.first());
260 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
261 }
262
263 // Include the hash for the resolved ODR.
264 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000265 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000266 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000267 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000268 sizeof(GlobalValue::LinkageTypes)));
269 }
270
271 // Include the hash for the preserved symbols.
272 for (auto &Entry : PreservedSymbols) {
273 if (DefinedFunctions.count(Entry))
274 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000275 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000276 }
277
278 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
279 }
280
Mehdi Amini059464f2016-04-24 03:18:01 +0000281 // Access the path to this entry in the cache.
282 StringRef getEntryPath() { return EntryPath; }
283
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000284 // Try loading the buffer for this cache entry.
285 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
286 if (EntryPath.empty())
287 return std::error_code();
288 return MemoryBuffer::getFile(EntryPath);
289 }
290
291 // Cache the Produced object file
Mehdi Amini001bb412016-05-16 19:11:59 +0000292 std::unique_ptr<MemoryBuffer>
293 write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000294 if (EntryPath.empty())
Mehdi Amini001bb412016-05-16 19:11:59 +0000295 return OutputBuffer;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000296
297 // Write to a temporary to avoid race condition
298 SmallString<128> TempFilename;
299 int TempFD;
300 std::error_code EC =
301 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
302 if (EC) {
303 errs() << "Error: " << EC.message() << "\n";
304 report_fatal_error("ThinLTO: Can't get a temporary file");
305 }
306 {
307 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini001bb412016-05-16 19:11:59 +0000308 OS << OutputBuffer->getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000309 }
310 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000311 EC = sys::fs::rename(TempFilename, EntryPath);
312 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000313 sys::fs::remove(TempFilename);
314 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
315 if (EC)
316 report_fatal_error(Twine("Failed to open ") + EntryPath +
317 " to save cached entry\n");
Mehdi Amini001bb412016-05-16 19:11:59 +0000318 OS << OutputBuffer->getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000319 }
Mehdi Amini001bb412016-05-16 19:11:59 +0000320 auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
321 if (auto EC = ReloadedBufferOrErr.getError()) {
322 // FIXME diagnose
323 errs() << "error: can't reload cached file '" << EntryPath
324 << "': " << EC.message() << "\n";
325 return OutputBuffer;
326 }
327 return std::move(*ReloadedBufferOrErr);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000328 }
329};
330
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000331static std::unique_ptr<MemoryBuffer>
332ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
333 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
334 const FunctionImporter::ImportMapTy &ImportList,
335 const FunctionImporter::ExportSetTy &ExportList,
336 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
337 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000338 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000339 bool DisableCodeGen, StringRef SaveTempsDir,
340 unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000341
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000342 // "Benchmark"-like optimization: single-source case
343 bool SingleModule = (ModuleMap.size() == 1);
344
345 if (!SingleModule) {
346 promoteModule(TheModule, Index);
347
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000348 // Apply summary-based LinkOnce/Weak resolution decisions.
349 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000350
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000351 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000352 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000353 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000354
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000355 // Be friendly and don't nuke totally the module when the client didn't
356 // supply anything to preserve.
357 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
358 // Apply summary-based internalization decisions.
359 thinLTOInternalizeModule(TheModule, DefinedGlobals);
360 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000361
362 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000363 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000364
365 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000366 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000367
368 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000369 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000370 }
371
372 optimizeModule(TheModule, TM);
373
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000374 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000375
Mehdi Amini43b657b2016-04-01 06:47:02 +0000376 if (DisableCodeGen) {
377 // Configured to stop before CodeGen, serialize the bitcode and return.
378 SmallVector<char, 128> OutputBuffer;
379 {
380 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000381 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000382 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000383 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000384 }
385 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
386 }
387
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000388 return codegenModule(TheModule, TM);
389}
390
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000391/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
392/// for caching, and in the \p Index for application during the ThinLTO
393/// backends. This is needed for correctness for exported symbols (ensure
394/// at least one copy kept) and a compile-time optimization (to drop duplicate
395/// copies when possible).
396static void resolveWeakForLinkerInIndex(
397 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000398 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
399 &ResolvedODR) {
400
401 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
402 computePrevailingCopies(Index, PrevailingCopy);
403
404 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
405 const auto &Prevailing = PrevailingCopy.find(GUID);
406 // Not in map means that there was only one copy, which must be prevailing.
407 if (Prevailing == PrevailingCopy.end())
408 return true;
409 return Prevailing->second == S;
410 };
411
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000412 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
413 GlobalValue::GUID GUID,
414 GlobalValue::LinkageTypes NewLinkage) {
415 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
416 };
417
Peter Collingbourne73589f32016-07-07 18:31:51 +0000418 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000419}
420
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000421// Initialize the TargetMachine builder for a given Triple
422static void initTMBuilder(TargetMachineBuilder &TMBuilder,
423 const Triple &TheTriple) {
424 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
425 // FIXME this looks pretty terrible...
426 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
427 if (TheTriple.getArch() == llvm::Triple::x86_64)
428 TMBuilder.MCpu = "core2";
429 else if (TheTriple.getArch() == llvm::Triple::x86)
430 TMBuilder.MCpu = "yonah";
431 else if (TheTriple.getArch() == llvm::Triple::aarch64)
432 TMBuilder.MCpu = "cyclone";
433 }
434 TMBuilder.TheTriple = std::move(TheTriple);
435}
436
437} // end anonymous namespace
438
439void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
440 MemoryBufferRef Buffer(Data, Identifier);
441 if (Modules.empty()) {
442 // First module added, so initialize the triple and some options
443 LLVMContext Context;
444 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
445 initTMBuilder(TMBuilder, Triple(TheTriple));
446 }
447#ifndef NDEBUG
448 else {
449 LLVMContext Context;
450 assert(TMBuilder.TheTriple.str() ==
451 getBitcodeTargetTriple(Buffer, Context) &&
452 "ThinLTO modules with different triple not supported");
453 }
454#endif
455 Modules.push_back(Buffer);
456}
457
458void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
459 PreservedSymbols.insert(Name);
460}
461
462void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000463 // FIXME: At the moment, we don't take advantage of this extra information,
464 // we're conservatively considering cross-references as preserved.
465 // CrossReferencedSymbols.insert(Name);
466 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000467}
468
469// TargetMachine factory
470std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
471 std::string ErrMsg;
472 const Target *TheTarget =
473 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
474 if (!TheTarget) {
475 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
476 }
477
478 // Use MAttr as the default set of features.
479 SubtargetFeatures Features(MAttr);
480 Features.getDefaultSubtargetFeatures(TheTriple);
481 std::string FeatureStr = Features.getString();
482 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
483 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
484 CodeModel::Default, CGOptLevel));
485}
486
487/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000488 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000489 * "thin-link".
490 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000491std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
492 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000493 uint64_t NextModuleId = 0;
494 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000495 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
496 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000497 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000498 if (std::error_code EC = ObjOrErr.getError()) {
499 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000500 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000501 << EC.message() << "\n";
502 return nullptr;
503 }
504 auto Index = (*ObjOrErr)->takeIndex();
505 if (CombinedIndex) {
506 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
507 } else {
508 CombinedIndex = std::move(Index);
509 }
510 }
511 return CombinedIndex;
512}
513
514/**
515 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000516 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000517 */
518void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000519 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000520 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000521 auto ModuleIdentifier = TheModule.getModuleIdentifier();
522 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000523 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000524 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000525
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000526 // Generate import/export list
527 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
528 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
529 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
530 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000531
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000532 // Resolve LinkOnce/Weak symbols.
533 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000534 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000535
536 thinLTOResolveWeakForLinkerModule(
537 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000538
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000539 promoteModule(TheModule, Index);
540}
541
542/**
543 * Perform cross-module importing for the module identified by ModuleIdentifier.
544 */
545void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000546 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000547 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000548 auto ModuleCount = Index.modulePaths().size();
549
550 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000551 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000552 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000553
554 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000555 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
556 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000557 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
558 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000559 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
560
561 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000562}
563
564/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000565 * Compute the list of summaries needed for importing into module.
566 */
567void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
568 StringRef ModulePath, ModuleSummaryIndex &Index,
569 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
570 auto ModuleCount = Index.modulePaths().size();
571
572 // Collect for each module the list of function it defines (GUID -> Summary).
573 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
574 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
575
576 // Generate import/export list
577 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
578 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
579 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
580 ExportLists);
581
582 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000583 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000584 ModuleToSummariesForIndex);
585}
586
587/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000588 * Emit the list of files needed for importing into module.
589 */
590void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
591 StringRef OutputName,
592 ModuleSummaryIndex &Index) {
593 auto ModuleCount = Index.modulePaths().size();
594
595 // Collect for each module the list of function it defines (GUID -> Summary).
596 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
597 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
598
599 // Generate import/export list
600 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
601 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
602 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
603 ExportLists);
604
605 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000606 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000607 report_fatal_error(Twine("Failed to open ") + OutputName +
608 " to save imports lists\n");
609}
610
611/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000612 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000613 */
614void ThinLTOCodeGenerator::internalize(Module &TheModule,
615 ModuleSummaryIndex &Index) {
616 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
617 auto ModuleCount = Index.modulePaths().size();
618 auto ModuleIdentifier = TheModule.getModuleIdentifier();
619
620 // Convert the preserved symbols set from string to GUID
621 auto GUIDPreservedSymbols =
622 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
623
624 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000625 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000626 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
627
628 // Generate import/export list
629 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
630 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
631 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
632 ExportLists);
633 auto &ExportList = ExportLists[ModuleIdentifier];
634
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000635 // Be friendly and don't nuke totally the module when the client didn't
636 // supply anything to preserve.
637 if (ExportList.empty() && GUIDPreservedSymbols.empty())
638 return;
639
Mehdi Amini059464f2016-04-24 03:18:01 +0000640 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000641 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
642 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000643 return (ExportList != ExportLists.end() &&
644 ExportList->second.count(GUID)) ||
645 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000646 };
647 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
648 thinLTOInternalizeModule(TheModule,
649 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000650}
651
652/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000653 * Perform post-importing ThinLTO optimizations.
654 */
655void ThinLTOCodeGenerator::optimize(Module &TheModule) {
656 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000657
658 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000659 optimizeModule(TheModule, *TMBuilder.create());
660}
661
662/**
663 * Perform ThinLTO CodeGen.
664 */
665std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
666 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
667 return codegenModule(TheModule, *TMBuilder.create());
668}
669
670// Main entry point for the ThinLTO processing
671void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000672 if (CodeGenOnly) {
673 // Perform only parallel codegen and return.
674 ThreadPool Pool;
675 assert(ProducedBinaries.empty() && "The generator should not be reused");
676 ProducedBinaries.resize(Modules.size());
677 int count = 0;
678 for (auto &ModuleBuffer : Modules) {
679 Pool.async([&](int count) {
680 LLVMContext Context;
681 Context.setDiscardValueNames(LTODiscardValueNames);
682
683 // Parse module now
684 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
685
686 // CodeGen
687 ProducedBinaries[count] = codegen(*TheModule);
688 }, count++);
689 }
690
691 return;
692 }
693
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000694 // Sequential linking phase
695 auto Index = linkCombinedIndex();
696
697 // Save temps: index.
698 if (!SaveTempsDir.empty()) {
699 auto SaveTempPath = SaveTempsDir + "index.bc";
700 std::error_code EC;
701 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
702 if (EC)
703 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
704 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000705 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000706 }
707
708 // Prepare the resulting object vector
709 assert(ProducedBinaries.empty() && "The generator should not be reused");
710 ProducedBinaries.resize(Modules.size());
711
712 // Prepare the module map.
713 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000714 auto ModuleCount = Modules.size();
715
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000716 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000717 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000718 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
719
Mehdi Amini01e32132016-03-26 05:40:34 +0000720 // Collect the import/export lists for all modules from the call-graph in the
721 // combined index.
722 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
723 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000724 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
725 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000726
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000727 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000728 // computing the caching hash and the internalization.
729 auto GUIDPreservedSymbols =
730 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000731
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000732 // We use a std::map here to be able to have a defined ordering when
733 // producing a hash for the cache entry.
734 // FIXME: we should be able to compute the caching hash for the entry based
735 // on the index, and nuke this map.
736 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
737
738 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
739 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000740 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000741
742 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
743 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000744 return (ExportList != ExportLists.end() &&
745 ExportList->second.count(GUID)) ||
746 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000747 };
748
749 // Use global summary-based analysis to identify symbols that can be
750 // internalized (because they aren't exported or preserved as per callback).
751 // Changes are made in the index, consumed in the ThinLTO backends.
752 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
753
Teresa Johnson141149f2016-05-24 18:44:01 +0000754 // Make sure that every module has an entry in the ExportLists and
755 // ResolvedODR maps to enable threaded access to these maps below.
756 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000757 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000758 ResolvedODR[DefinedGVSummaries.first()];
759 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000760
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000761 // Compute the ordering we will process the inputs: the rough heuristic here
762 // is to sort them per size so that the largest module get schedule as soon as
763 // possible. This is purely a compile-time optimization.
764 std::vector<int> ModulesOrdering;
765 ModulesOrdering.resize(Modules.size());
766 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
767 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
768 [&](int LeftIndex, int RightIndex) {
769 auto LSize = Modules[LeftIndex].getBufferSize();
770 auto RSize = Modules[RightIndex].getBufferSize();
771 return LSize > RSize;
772 });
773
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000774 // Parallel optimizer + codegen
775 {
776 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000777 for (auto IndexCount : ModulesOrdering) {
778 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000779 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000780 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000781 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000782
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000783 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
784
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000785 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000786 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
787 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000788 ResolvedODR[ModuleIdentifier],
789 DefinedFunctions, GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000790
791 {
792 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000793 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
794 << CacheEntry.getEntryPath() << "' for buffer " << count
795 << " " << ModuleIdentifier << "\n");
796
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000797 if (ErrOrBuffer) {
798 // Cache Hit!
799 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
800 return;
801 }
802 }
803
804 LLVMContext Context;
805 Context.setDiscardValueNames(LTODiscardValueNames);
806 Context.enableDebugTypeODRUniquing();
807
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000808 // Parse module now
809 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
810
811 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000812 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000813
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000814 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000815 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000816 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000817 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000818 ExportList, GUIDPreservedSymbols,
819 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Amini059464f2016-04-24 03:18:01 +0000820 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000821
Mehdi Amini001bb412016-05-16 19:11:59 +0000822 OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000823 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000824 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000825 }
826 }
827
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000828 CachePruning(CacheOptions.Path)
829 .setPruningInterval(CacheOptions.PruningInterval)
830 .setEntryExpiration(CacheOptions.Expiration)
831 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
832 .prune();
833
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000834 // If statistics were requested, print them out now.
835 if (llvm::AreStatisticsEnabled())
836 llvm::PrintStatistics();
837}