blob: 9500b2ded70ea8de4d05c969ede91d1e1800ff65 [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
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000017#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000018#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000019#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000020#include "llvm/Analysis/ProfileSummaryInfo.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000025#include "llvm/Bitcode/BitcodeWriterPass.h"
Nico Weber432a3882018-04-30 14:59:11 +000026#include "llvm/Config/llvm-config.h"
Adrian Prantl981a7992017-05-20 00:00:08 +000027#include "llvm/IR/DebugInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000028#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000029#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000030#include "llvm/IR/LegacyPassManager.h"
31#include "llvm/IR/Mangler.h"
Fedor Sergeeva43fd952018-09-26 13:01:43 +000032#include "llvm/IR/PassTimingInfo.h"
Adrian Prantl981a7992017-05-20 00:00:08 +000033#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000034#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/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000037#include "llvm/Object/IRObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000038#include "llvm/Support/CachePruning.h"
39#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000040#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000041#include "llvm/Support/Path.h"
42#include "llvm/Support/SHA1.h"
Weiming Zhao79f2d092018-04-16 03:44:03 +000043#include "llvm/Support/SmallVectorMemoryBuffer.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 Amini19f176b2016-11-19 18:20:05 +000047#include "llvm/Support/ToolOutputFile.h"
Peter Collingbourne942fa562017-04-13 01:26:12 +000048#include "llvm/Support/VCSRevision.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000049#include "llvm/Target/TargetMachine.h"
50#include "llvm/Transforms/IPO.h"
51#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000052#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000053#include "llvm/Transforms/IPO/PassManagerBuilder.h"
54#include "llvm/Transforms/ObjCARC.h"
55#include "llvm/Transforms/Utils/FunctionImportUtils.h"
56
Mehdi Amini819e9cd2016-05-16 19:33:07 +000057#include <numeric>
58
Andrew Ng089303d2018-07-04 14:17:10 +000059#if !defined(_MSC_VER) && !defined(__MINGW32__)
60#include <unistd.h>
61#else
62#include <io.h>
63#endif
64
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000065using namespace llvm;
66
Mehdi Amini1aafabf2016-04-16 07:02:16 +000067#define DEBUG_TYPE "thinlto"
68
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000069namespace llvm {
70// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
71extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000072extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000073extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000074}
75
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000076namespace {
77
Teresa Johnsonec544c52016-10-19 17:35:01 +000078static cl::opt<int>
79 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000080
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081// Simple helper to save temporary files for debug.
82static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
83 unsigned count, StringRef Suffix) {
84 if (TempDir.empty())
85 return;
86 // User asked to save temps, let dump the bitcode file after import.
Benjamin Kramer3a13ed62017-12-28 16:58:54 +000087 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000088 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000089 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000090 if (EC)
91 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
92 " to save optimized bitcode\n");
Rafael Espindola6a86e252018-02-14 19:11:32 +000093 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000094}
95
Teresa Johnson4d2613f2016-05-24 17:24:25 +000096static const GlobalValueSummary *
97getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
98 // If there is any strong definition anywhere, get it.
99 auto StrongDefForLinker = llvm::find_if(
100 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
101 auto Linkage = Summary->linkage();
102 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
103 !GlobalValue::isWeakForLinker(Linkage);
104 });
105 if (StrongDefForLinker != GVSummaryList.end())
106 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000107 // Get the first *linker visible* definition for this global in the summary
108 // list.
109 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000110 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
111 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000112 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
113 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000114 // Extern templates can be emitted as available_externally.
115 if (FirstDefForLinker == GVSummaryList.end())
116 return nullptr;
117 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000118}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000119
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000120// Populate map of GUID to the prevailing copy for any multiply defined
121// symbols. Currently assume first copy is prevailing, or any strong
122// definition. Can be refined with Linker information in the future.
123static void computePrevailingCopies(
124 const ModuleSummaryIndex &Index,
125 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000126 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
127 return GVSummaryList.size() > 1;
128 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000129
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000130 for (auto &I : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000131 if (HasMultipleCopies(I.second.SummaryList))
132 PrevailingCopy[I.first] =
133 getFirstDefinitionForLinker(I.second.SummaryList);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000134 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000135}
136
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000137static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000138generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000139 StringMap<MemoryBufferRef> ModuleMap;
140 for (auto &ModuleBuffer : Modules) {
141 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
142 ModuleMap.end() &&
143 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000144 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000145 }
146 return ModuleMap;
147}
148
Teresa Johnson26ab5772016-03-15 00:04:37 +0000149static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000150 if (renameModuleForThinLTO(TheModule, Index))
151 report_fatal_error("renameModuleForThinLTO failed");
152}
153
Adrian Prantl981a7992017-05-20 00:00:08 +0000154namespace {
155class ThinLTODiagnosticInfo : public DiagnosticInfo {
156 const Twine &Msg;
157public:
158 ThinLTODiagnosticInfo(const Twine &DiagMsg,
159 DiagnosticSeverity Severity = DS_Error)
160 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
161 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
162};
163}
164
165/// Verify the module and strip broken debug info.
166static void verifyLoadedModule(Module &TheModule) {
167 bool BrokenDebugInfo = false;
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000168 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
Adrian Prantl981a7992017-05-20 00:00:08 +0000169 report_fatal_error("Broken module found, compilation aborted!");
170 if (BrokenDebugInfo) {
171 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
172 "Invalid debug info found, debug info will be stripped", DS_Warning));
173 StripDebugInfo(TheModule);
174 }
175}
176
Peter Collingbournedac43b42016-12-01 05:52:32 +0000177static std::unique_ptr<Module>
178loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000179 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000180 SMDiagnostic Err;
181 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000182 Lazy
183 ? getLazyBitcodeModule(Buffer, Context,
184 /* ShouldLazyLoadMetadata */ true, IsImporting)
185 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000186 if (!ModuleOrErr) {
187 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
188 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
189 SourceMgr::DK_Error, EIB.message());
190 Err.print("ThinLTO", errs());
191 });
192 report_fatal_error("Can't load module, abort.");
193 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000194 if (!Lazy)
195 verifyLoadedModule(*ModuleOrErr.get());
Peter Collingbournedac43b42016-12-01 05:52:32 +0000196 return std::move(ModuleOrErr.get());
197}
198
Mehdi Amini01e32132016-03-26 05:40:34 +0000199static void
200crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
201 StringMap<MemoryBufferRef> &ModuleMap,
202 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000203 auto Loader = [&](StringRef Identifier) {
204 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000205 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000206 };
207
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000208 FunctionImporter Importer(Index, Loader);
Adrian Prantl66043792017-05-19 23:32:21 +0000209 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000210 if (!Result) {
211 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
212 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
213 SourceMgr::DK_Error, EIB.message());
214 Err.print("ThinLTO", errs());
215 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000216 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000217 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000218 // Verify again after cross-importing.
219 verifyLoadedModule(TheModule);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000220}
221
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000222static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000223 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000224 // Populate the PassManager
225 PassManagerBuilder PMB;
226 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000227 if (Freestanding)
228 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000229 PMB.Inliner = createFunctionInliningPass();
230 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000231 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000232 PMB.LoopVectorize = true;
233 PMB.SLPVectorize = true;
Adrian Prantl981a7992017-05-20 00:00:08 +0000234 // Already did this in verifyLoadedModule().
235 PMB.VerifyInput = false;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000236 PMB.VerifyOutput = false;
237
238 legacy::PassManager PM;
239
240 // Add the TTI (required to inform the vectorizer about register size for
241 // instance)
242 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
243
244 // Add optimizations
245 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000246
247 PM.run(TheModule);
248}
249
Mehdi Amini059464f2016-04-24 03:18:01 +0000250// Convert the PreservedSymbols map from "Name" based to "GUID" based.
251static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000252computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
253 const Triple &TheTriple) {
254 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
255 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000256 StringRef Name = Entry.first();
257 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
258 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000259 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000260 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000261 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000262}
263
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000264std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
265 TargetMachine &TM) {
266 SmallVector<char, 128> OutputBuffer;
267
268 // CodeGen
269 {
270 raw_svector_ostream OS(OutputBuffer);
271 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000272
273 // If the bitcode files contain ARC code and were compiled with optimization,
274 // the ObjCARCContractPass must be run, so do it unconditionally here.
275 PM.add(createObjCARCContractPass());
276
277 // Setup the codegen now.
Peter Collingbourne9a451142018-05-21 20:16:41 +0000278 if (TM.addPassesToEmitFile(PM, OS, nullptr, TargetMachine::CGFT_ObjectFile,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000279 /* DisableVerify */ true))
280 report_fatal_error("Failed to setup codegen");
281
282 // Run codegen now. resulting binary is in OutputBuffer.
283 PM.run(TheModule);
284 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000285 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000286}
287
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000288/// Manage caching for a single Module.
289class ModuleCacheEntry {
290 SmallString<128> EntryPath;
291
292public:
293 // Create a cache entry. This compute a unique hash for the Module considering
294 // the current list of export/import, and offer an interface to query to
295 // access the content in the cache.
296 ModuleCacheEntry(
297 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
298 const FunctionImporter::ImportMapTy &ImportList,
299 const FunctionImporter::ExportSetTy &ExportList,
300 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000301 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000302 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000303 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000304 if (CachePath.empty())
305 return;
306
Mehdi Amini00fa1402016-10-08 04:44:18 +0000307 if (!Index.modulePaths().count(ModuleID))
308 // The module does not have an entry, it can't have a hash at all
309 return;
310
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000311 // Compute the unique hash for this entry
312 // This is based on the current compiler version, the module itself, the
313 // export list, the hash for every single module in the import list, the
314 // list of ResolvedODR for the module, and the list of preserved symbols.
315
Mehdi Aminif82bda02016-10-08 04:44:23 +0000316 // Include the hash for the current module
317 auto ModHash = Index.getModuleHash(ModuleID);
318
319 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
320 // No hash entry, no caching!
321 return;
322
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000323 SHA1 Hasher;
324
Mehdi Aminic92b6122017-01-10 00:55:47 +0000325 // Include the parts of the LTO configuration that affect code generation.
326 auto AddString = [&](StringRef Str) {
327 Hasher.update(Str);
328 Hasher.update(ArrayRef<uint8_t>{0});
329 };
330 auto AddUnsigned = [&](unsigned I) {
331 uint8_t Data[4];
332 Data[0] = I;
333 Data[1] = I >> 8;
334 Data[2] = I >> 16;
335 Data[3] = I >> 24;
336 Hasher.update(ArrayRef<uint8_t>{Data, 4});
337 };
338
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000339 // Start with the compiler revision
340 Hasher.update(LLVM_VERSION_STRING);
Peter Collingbourne942fa562017-04-13 01:26:12 +0000341#ifdef LLVM_REVISION
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000342 Hasher.update(LLVM_REVISION);
343#endif
344
Mehdi Aminic92b6122017-01-10 00:55:47 +0000345 // Hash the optimization level and the target machine settings.
346 AddString(TMBuilder.MCpu);
347 // FIXME: Hash more of Options. For now all clients initialize Options from
348 // command-line flags (which is unsupported in production), but may set
349 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
350 // DataSections and DebuggerTuning via command line flags.
351 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
352 AddUnsigned(TMBuilder.Options.FunctionSections);
353 AddUnsigned(TMBuilder.Options.DataSections);
354 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
355 AddString(TMBuilder.MAttr);
356 if (TMBuilder.RelocModel)
357 AddUnsigned(*TMBuilder.RelocModel);
358 AddUnsigned(TMBuilder.CGOptLevel);
359 AddUnsigned(OptLevel);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000360 AddUnsigned(Freestanding);
Mehdi Aminic92b6122017-01-10 00:55:47 +0000361
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000362 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
363 for (auto F : ExportList)
364 // The export list can impact the internalization, be conservative here
365 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
366
367 // Include the hash for every module we import functions from
368 for (auto &Entry : ImportList) {
369 auto ModHash = Index.getModuleHash(Entry.first());
370 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
371 }
372
373 // Include the hash for the resolved ODR.
374 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000375 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000376 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000377 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000378 sizeof(GlobalValue::LinkageTypes)));
379 }
380
381 // Include the hash for the preserved symbols.
382 for (auto &Entry : PreservedSymbols) {
383 if (DefinedFunctions.count(Entry))
384 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000385 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000386 }
387
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000388 // This choice of file name allows the cache to be pruned (see pruneCache()
389 // in include/llvm/Support/CachePruning.h).
390 sys::path::append(EntryPath, CachePath,
391 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000392 }
393
Mehdi Amini059464f2016-04-24 03:18:01 +0000394 // Access the path to this entry in the cache.
395 StringRef getEntryPath() { return EntryPath; }
396
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000397 // Try loading the buffer for this cache entry.
398 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
399 if (EntryPath.empty())
400 return std::error_code();
Andrew Ng089303d2018-07-04 14:17:10 +0000401 int FD;
402 SmallString<64> ResultPath;
403 std::error_code EC = sys::fs::openFileForRead(
404 Twine(EntryPath), FD, sys::fs::OF_UpdateAtime, &ResultPath);
405 if (EC)
406 return EC;
407 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
408 MemoryBuffer::getOpenFile(FD, EntryPath,
409 /*FileSize*/ -1,
410 /*RequiresNullTerminator*/ false);
411 close(FD);
412 return MBOrErr;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000413 }
414
415 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000416 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000417 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000418 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000419
420 // Write to a temporary to avoid race condition
421 SmallString<128> TempFilename;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000422 SmallString<128> CachePath(EntryPath);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000423 int TempFD;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000424 llvm::sys::path::remove_filename(CachePath);
425 sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
Fangrui Songf78650a2018-07-30 19:41:25 +0000426 std::error_code EC =
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000427 sys::fs::createUniqueFile(TempFilename, TempFD, TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000428 if (EC) {
429 errs() << "Error: " << EC.message() << "\n";
430 report_fatal_error("ThinLTO: Can't get a temporary file");
431 }
432 {
433 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000434 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000435 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000436 // Rename temp file to final destination; rename is atomic
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000437 EC = sys::fs::rename(TempFilename, EntryPath);
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000438 if (EC)
Mehdi Aminib02139d2016-05-14 05:16:35 +0000439 sys::fs::remove(TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000440 }
441};
442
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000443static std::unique_ptr<MemoryBuffer>
444ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
445 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
446 const FunctionImporter::ImportMapTy &ImportList,
447 const FunctionImporter::ExportSetTy &ExportList,
448 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
449 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000450 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000451 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000452 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000453
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000454 // "Benchmark"-like optimization: single-source case
455 bool SingleModule = (ModuleMap.size() == 1);
456
457 if (!SingleModule) {
458 promoteModule(TheModule, Index);
459
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000460 // Apply summary-based LinkOnce/Weak resolution decisions.
461 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000462
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000463 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000464 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000465 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000466
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000467 // Be friendly and don't nuke totally the module when the client didn't
468 // supply anything to preserve.
469 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
470 // Apply summary-based internalization decisions.
471 thinLTOInternalizeModule(TheModule, DefinedGlobals);
472 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000473
474 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000475 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000476
477 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000478 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000479
480 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000481 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000482 }
483
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000484 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000485
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000486 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000487
Mehdi Amini43b657b2016-04-01 06:47:02 +0000488 if (DisableCodeGen) {
489 // Configured to stop before CodeGen, serialize the bitcode and return.
490 SmallVector<char, 128> OutputBuffer;
491 {
492 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000493 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000494 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000495 WriteBitcodeToFile(TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000496 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000497 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini43b657b2016-04-01 06:47:02 +0000498 }
499
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000500 return codegenModule(TheModule, TM);
501}
502
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000503/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
504/// for caching, and in the \p Index for application during the ThinLTO
505/// backends. This is needed for correctness for exported symbols (ensure
506/// at least one copy kept) and a compile-time optimization (to drop duplicate
507/// copies when possible).
508static void resolveWeakForLinkerInIndex(
509 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000510 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
511 &ResolvedODR) {
512
513 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
514 computePrevailingCopies(Index, PrevailingCopy);
515
516 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
517 const auto &Prevailing = PrevailingCopy.find(GUID);
518 // Not in map means that there was only one copy, which must be prevailing.
519 if (Prevailing == PrevailingCopy.end())
520 return true;
521 return Prevailing->second == S;
522 };
523
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000524 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
525 GlobalValue::GUID GUID,
526 GlobalValue::LinkageTypes NewLinkage) {
527 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
528 };
529
Peter Collingbourne73589f32016-07-07 18:31:51 +0000530 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000531}
532
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000533// Initialize the TargetMachine builder for a given Triple
534static void initTMBuilder(TargetMachineBuilder &TMBuilder,
535 const Triple &TheTriple) {
536 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
537 // FIXME this looks pretty terrible...
538 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
539 if (TheTriple.getArch() == llvm::Triple::x86_64)
540 TMBuilder.MCpu = "core2";
541 else if (TheTriple.getArch() == llvm::Triple::x86)
542 TMBuilder.MCpu = "yonah";
543 else if (TheTriple.getArch() == llvm::Triple::aarch64)
544 TMBuilder.MCpu = "cyclone";
545 }
546 TMBuilder.TheTriple = std::move(TheTriple);
547}
548
549} // end anonymous namespace
550
551void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Johan Engelendcebe4f2017-09-17 18:11:26 +0000552 ThinLTOBuffer Buffer(Data, Identifier);
Akira Hatanakab10bff12017-05-18 03:52:29 +0000553 LLVMContext Context;
554 StringRef TripleStr;
555 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
556 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
557
558 if (TripleOrErr)
559 TripleStr = *TripleOrErr;
560
561 Triple TheTriple(TripleStr);
562
563 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000564 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000565 else if (TMBuilder.TheTriple != TheTriple) {
566 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
567 report_fatal_error("ThinLTO modules with incompatible triples not "
568 "supported");
569 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000570 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000571
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000572 Modules.push_back(Buffer);
573}
574
575void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
576 PreservedSymbols.insert(Name);
577}
578
579void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000580 // FIXME: At the moment, we don't take advantage of this extra information,
581 // we're conservatively considering cross-references as preserved.
582 // CrossReferencedSymbols.insert(Name);
583 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000584}
585
586// TargetMachine factory
587std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
588 std::string ErrMsg;
589 const Target *TheTarget =
590 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
591 if (!TheTarget) {
592 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
593 }
594
595 // Use MAttr as the default set of features.
596 SubtargetFeatures Features(MAttr);
597 Features.getDefaultSubtargetFeatures(TheTriple);
598 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000599
Rafael Espindola79e238a2017-08-03 02:16:21 +0000600 return std::unique_ptr<TargetMachine>(
601 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
602 RelocModel, None, CGOptLevel));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000603}
604
605/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000606 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000607 * "thin-link".
608 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000609std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000610 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
Teresa Johnson4ffc3e72018-06-06 22:22:01 +0000611 llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000612 uint64_t NextModuleId = 0;
613 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000614 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
615 *CombinedIndex, NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000616 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000617 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000618 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000619 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000620 return nullptr;
621 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000622 }
623 return CombinedIndex;
624}
625
George Rimar2421b6f2018-01-17 10:33:05 +0000626static void internalizeAndPromoteInIndex(
627 const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
628 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
629 ModuleSummaryIndex &Index) {
630 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
631 const auto &ExportList = ExportLists.find(ModuleIdentifier);
632 return (ExportList != ExportLists.end() &&
633 ExportList->second.count(GUID)) ||
634 GUIDPreservedSymbols.count(GUID);
635 };
636
637 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
638}
639
George Rimareaf51722018-01-29 08:03:30 +0000640static void computeDeadSymbolsInIndex(
641 ModuleSummaryIndex &Index,
642 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
643 // We have no symbols resolution available. And can't do any better now in the
644 // case where the prevailing symbol is in a native object. It can be refined
645 // with linker information in the future.
646 auto isPrevailing = [&](GlobalValue::GUID G) {
647 return PrevailingType::Unknown;
648 };
649 computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
650}
651
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000652/**
653 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000654 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000655 */
656void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000657 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000658 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000659 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000660
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000661 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000662 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000663 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000664
Teresa Johnson6c475a72017-01-05 21:34:18 +0000665 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000666 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000667 PreservedSymbols, Triple(TheModule.getTargetTriple()));
668
669 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000670 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000671
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000672 // Generate import/export list
673 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
674 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
675 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000676 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000677
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000678 // Resolve LinkOnce/Weak symbols.
679 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000680 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000681
682 thinLTOResolveWeakForLinkerModule(
683 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000684
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000685 // Promote the exported values in the index, so that they are promoted
686 // in the module.
George Rimar2421b6f2018-01-17 10:33:05 +0000687 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000688
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000689 promoteModule(TheModule, Index);
690}
691
692/**
693 * Perform cross-module importing for the module identified by ModuleIdentifier.
694 */
695void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000696 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000697 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000698 auto ModuleCount = Index.modulePaths().size();
699
700 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000701 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000702 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000703
Teresa Johnson6c475a72017-01-05 21:34:18 +0000704 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000705 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000706 PreservedSymbols, Triple(TheModule.getTargetTriple()));
707
708 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000709 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000710
Mehdi Amini01e32132016-03-26 05:40:34 +0000711 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000712 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
713 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000714 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000715 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000716 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
717
718 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000719}
720
721/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000722 * Compute the list of summaries needed for importing into module.
723 */
724void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
725 StringRef ModulePath, ModuleSummaryIndex &Index,
726 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
727 auto ModuleCount = Index.modulePaths().size();
728
729 // Collect for each module the list of function it defines (GUID -> Summary).
730 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
731 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
732
733 // Generate import/export list
734 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
735 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
736 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
737 ExportLists);
738
739 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000740 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000741 ModuleToSummariesForIndex);
742}
743
744/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000745 * Emit the list of files needed for importing into module.
746 */
747void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
748 StringRef OutputName,
749 ModuleSummaryIndex &Index) {
750 auto ModuleCount = Index.modulePaths().size();
751
752 // Collect for each module the list of function it defines (GUID -> Summary).
753 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
754 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
755
756 // Generate import/export list
757 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
758 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
759 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
760 ExportLists);
761
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000762 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
763 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
764 ImportLists[ModulePath],
765 ModuleToSummariesForIndex);
766
Teresa Johnson8570fe42016-05-10 15:54:09 +0000767 std::error_code EC;
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000768 if ((EC =
769 EmitImportsFiles(ModulePath, OutputName, ModuleToSummariesForIndex)))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000770 report_fatal_error(Twine("Failed to open ") + OutputName +
771 " to save imports lists\n");
772}
773
774/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000775 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000776 */
777void ThinLTOCodeGenerator::internalize(Module &TheModule,
778 ModuleSummaryIndex &Index) {
779 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
780 auto ModuleCount = Index.modulePaths().size();
781 auto ModuleIdentifier = TheModule.getModuleIdentifier();
782
783 // Convert the preserved symbols set from string to GUID
784 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000785 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000786
787 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000788 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000789 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
790
Teresa Johnson6c475a72017-01-05 21:34:18 +0000791 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000792 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000793
Mehdi Amini059464f2016-04-24 03:18:01 +0000794 // Generate import/export list
795 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
796 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
797 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000798 ExportLists);
Mehdi Amini059464f2016-04-24 03:18:01 +0000799 auto &ExportList = ExportLists[ModuleIdentifier];
800
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000801 // Be friendly and don't nuke totally the module when the client didn't
802 // supply anything to preserve.
803 if (ExportList.empty() && GUIDPreservedSymbols.empty())
804 return;
805
Mehdi Amini059464f2016-04-24 03:18:01 +0000806 // Internalization
George Rimar2421b6f2018-01-17 10:33:05 +0000807 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000808 thinLTOInternalizeModule(TheModule,
809 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000810}
811
812/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000813 * Perform post-importing ThinLTO optimizations.
814 */
815void ThinLTOCodeGenerator::optimize(Module &TheModule) {
816 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000817
818 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000819 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000820}
821
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000822/// Write out the generated object file, either from CacheEntryPath or from
823/// OutputBuffer, preferring hard-link when possible.
824/// Returns the path to the generated file in SavedObjectsDirectoryPath.
825static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
826 StringRef SavedObjectsDirectoryPath,
827 const MemoryBuffer &OutputBuffer) {
828 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
829 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
830 OutputPath.c_str(); // Ensure the string is null terminated.
831 if (sys::fs::exists(OutputPath))
832 sys::fs::remove(OutputPath);
833
834 // We don't return a memory buffer to the linker, just a list of files.
835 if (!CacheEntryPath.empty()) {
836 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
837 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
838 if (!Err)
839 return OutputPath.str();
840 // Hard linking failed, try to copy.
841 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
842 if (!Err)
843 return OutputPath.str();
844 // Copy failed (could be because the CacheEntry was removed from the cache
845 // in the meantime by another process), fall back and try to write down the
846 // buffer to the output.
847 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
848 << "' to '" << OutputPath << "'\n";
849 }
850 // No cache entry, just write out the buffer.
851 std::error_code Err;
852 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
853 if (Err)
854 report_fatal_error("Can't open output '" + OutputPath + "'\n");
855 OS << OutputBuffer.getBuffer();
856 return OutputPath.str();
857}
858
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000859// Main entry point for the ThinLTO processing
860void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000861 // Prepare the resulting object vector
862 assert(ProducedBinaries.empty() && "The generator should not be reused");
863 if (SavedObjectsDirectoryPath.empty())
864 ProducedBinaries.resize(Modules.size());
865 else {
866 sys::fs::create_directories(SavedObjectsDirectoryPath);
867 bool IsDir;
868 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
869 if (!IsDir)
870 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
871 ProducedBinaryFiles.resize(Modules.size());
872 }
873
Mehdi Amini43b657b2016-04-01 06:47:02 +0000874 if (CodeGenOnly) {
875 // Perform only parallel codegen and return.
876 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000877 int count = 0;
878 for (auto &ModuleBuffer : Modules) {
879 Pool.async([&](int count) {
880 LLVMContext Context;
881 Context.setDiscardValueNames(LTODiscardValueNames);
882
883 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000884 auto TheModule =
885 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
886 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000887
888 // CodeGen
Steven Wucf902032018-09-04 22:54:17 +0000889 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
Mehdi Aminib2990462017-01-20 22:45:34 +0000890 if (SavedObjectsDirectoryPath.empty())
891 ProducedBinaries[count] = std::move(OutputBuffer);
892 else
893 ProducedBinaryFiles[count] = writeGeneratedObject(
894 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000895 }, count++);
896 }
897
898 return;
899 }
900
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000901 // Sequential linking phase
902 auto Index = linkCombinedIndex();
903
904 // Save temps: index.
905 if (!SaveTempsDir.empty()) {
906 auto SaveTempPath = SaveTempsDir + "index.bc";
907 std::error_code EC;
908 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
909 if (EC)
910 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
911 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000912 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000913 }
914
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000915
916 // Prepare the module map.
917 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000918 auto ModuleCount = Modules.size();
919
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000920 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000921 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000922 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
923
Teresa Johnson6c475a72017-01-05 21:34:18 +0000924 // Convert the preserved symbols set from string to GUID, this is needed for
925 // computing the caching hash and the internalization.
926 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000927 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000928
929 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000930 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000931
Mehdi Amini01e32132016-03-26 05:40:34 +0000932 // Collect the import/export lists for all modules from the call-graph in the
933 // combined index.
934 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
935 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000936 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000937 ExportLists);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000938
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000939 // We use a std::map here to be able to have a defined ordering when
940 // producing a hash for the cache entry.
941 // FIXME: we should be able to compute the caching hash for the entry based
942 // on the index, and nuke this map.
943 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
944
945 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
946 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000947 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000948
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000949 // Use global summary-based analysis to identify symbols that can be
950 // internalized (because they aren't exported or preserved as per callback).
951 // Changes are made in the index, consumed in the ThinLTO backends.
George Rimar2421b6f2018-01-17 10:33:05 +0000952 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000953
Steven Wuec53c892018-09-14 19:38:21 +0000954 // Make sure that every module has an entry in the ExportLists, ImportList,
955 // GVSummary and ResolvedODR maps to enable threaded access to these maps
956 // below.
957 for (auto &Module : Modules) {
958 auto ModuleIdentifier = Module.getBufferIdentifier();
959 ExportLists[ModuleIdentifier];
960 ImportLists[ModuleIdentifier];
961 ResolvedODR[ModuleIdentifier];
962 ModuleToDefinedGVSummaries[ModuleIdentifier];
Teresa Johnson141149f2016-05-24 18:44:01 +0000963 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000964
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000965 // Compute the ordering we will process the inputs: the rough heuristic here
966 // is to sort them per size so that the largest module get schedule as soon as
967 // possible. This is purely a compile-time optimization.
968 std::vector<int> ModulesOrdering;
969 ModulesOrdering.resize(Modules.size());
970 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
Fangrui Song0cac7262018-09-27 02:13:45 +0000971 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
972 auto LSize = Modules[LeftIndex].getBuffer().size();
973 auto RSize = Modules[RightIndex].getBuffer().size();
974 return LSize > RSize;
975 });
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000976
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000977 // Parallel optimizer + codegen
978 {
979 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000980 for (auto IndexCount : ModulesOrdering) {
981 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000982 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000983 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000984 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000985
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000986 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
987
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000988 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000989 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
990 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000991 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000992 DefinedFunctions, GUIDPreservedSymbols,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000993 OptLevel, Freestanding, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000994 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000995
996 {
997 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000998 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
999 << " '" << CacheEntryPath << "' for buffer "
1000 << count << " " << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +00001001
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001002 if (ErrOrBuffer) {
1003 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001004 if (SavedObjectsDirectoryPath.empty())
1005 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1006 else
1007 ProducedBinaryFiles[count] = writeGeneratedObject(
1008 count, CacheEntryPath, SavedObjectsDirectoryPath,
1009 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001010 return;
1011 }
1012 }
1013
1014 LLVMContext Context;
1015 Context.setDiscardValueNames(LTODiscardValueNames);
1016 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +00001017 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarmanfb2d3422018-03-08 01:13:10 +00001018 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +00001019 if (!DiagFileOrErr) {
1020 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1021 report_fatal_error("ThinLTO: Can't get an output file for the "
1022 "remarks");
1023 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001024
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001025 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +00001026 auto TheModule =
1027 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
1028 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001029
1030 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +00001031 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001032
Mehdi Amini1aafabf2016-04-16 07:02:16 +00001033 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +00001034 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001035 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001036 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001037 ExportList, GUIDPreservedSymbols,
1038 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +00001039 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001040
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001041 // Commit to the cache (if enabled)
1042 CacheEntry.write(*OutputBuffer);
1043
1044 if (SavedObjectsDirectoryPath.empty()) {
1045 // We need to generated a memory buffer for the linker.
1046 if (!CacheEntryPath.empty()) {
Fangrui Songf78650a2018-07-30 19:41:25 +00001047 // When cache is enabled, reload from the cache if possible.
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001048 // Releasing the buffer from the heap and reloading it from the
Fangrui Songf78650a2018-07-30 19:41:25 +00001049 // cache file with mmap helps us to lower memory pressure.
1050 // The freed memory can be used for the next input file.
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001051 // The final binary link will read from the VFS cache (hopefully!)
1052 // or from disk (if the memory pressure was too high).
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001053 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1054 if (auto EC = ReloadedBufferOrErr.getError()) {
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001055 // On error, keep the preexisting buffer and print a diagnostic.
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001056 errs() << "error: can't reload cached file '" << CacheEntryPath
1057 << "': " << EC.message() << "\n";
1058 } else {
1059 OutputBuffer = std::move(*ReloadedBufferOrErr);
1060 }
1061 }
1062 ProducedBinaries[count] = std::move(OutputBuffer);
1063 return;
1064 }
1065 ProducedBinaryFiles[count] = writeGeneratedObject(
1066 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001067 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001068 }
1069 }
1070
Peter Collingbournecead56f2017-03-15 22:54:18 +00001071 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001072
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001073 // If statistics were requested, print them out now.
1074 if (llvm::AreStatisticsEnabled())
1075 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +00001076 reportAndResetTimings();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001077}