blob: 2791efc69cda0d721a3b6199612f469f4c0c43a9 [file] [log] [blame]
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001//===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Thin Link Time Optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne5c732202016-07-14 21:21:16 +000015#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000016
Mehdi Aminif95f77a2016-04-21 05:54:23 +000017#ifdef HAVE_LLVM_REVISION
18#include "LLVMLTORevision.h"
19#endif
Mehdi Amini059464f2016-04-24 03:18:01 +000020
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000021#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000022#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000023#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000024#include "llvm/Analysis/ProfileSummaryInfo.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000027#include "llvm/Bitcode/BitcodeReader.h"
28#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000029#include "llvm/Bitcode/BitcodeWriterPass.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000030#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000031#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000032#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/IR/LegacyPassManager.h"
34#include "llvm/IR/Mangler.h"
35#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000036#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000037#include "llvm/Linker/Linker.h"
38#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000039#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000040#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000041#include "llvm/Support/CachePruning.h"
42#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000043#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000046#include "llvm/Support/TargetRegistry.h"
47#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000048#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000049#include "llvm/Support/ToolOutputFile.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000050#include "llvm/Target/TargetMachine.h"
51#include "llvm/Transforms/IPO.h"
52#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000053#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000054#include "llvm/Transforms/IPO/PassManagerBuilder.h"
55#include "llvm/Transforms/ObjCARC.h"
56#include "llvm/Transforms/Utils/FunctionImportUtils.h"
57
Mehdi Amini819e9cd2016-05-16 19:33:07 +000058#include <numeric>
59
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000060using namespace llvm;
61
Mehdi Amini1aafabf2016-04-16 07:02:16 +000062#define DEBUG_TYPE "thinlto"
63
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000064namespace llvm {
65// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
66extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000067extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000068extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000069}
70
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000071namespace {
72
Teresa Johnsonec544c52016-10-19 17:35:01 +000073static cl::opt<int>
74 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000075
Mehdi Amini19f176b2016-11-19 18:20:05 +000076Expected<std::unique_ptr<tool_output_file>>
77setupOptimizationRemarks(LLVMContext &Ctx, int Count) {
Adam Nemet4c207a62016-12-02 17:53:56 +000078 if (LTOPassRemarksWithHotness)
79 Ctx.setDiagnosticHotnessRequested(true);
80
Mehdi Amini19f176b2016-11-19 18:20:05 +000081 if (LTORemarksFilename.empty())
82 return nullptr;
83
84 std::string FileName =
85 LTORemarksFilename + ".thin." + llvm::utostr(Count) + ".yaml";
86 std::error_code EC;
87 auto DiagnosticOutputFile =
88 llvm::make_unique<tool_output_file>(FileName, EC, sys::fs::F_None);
89 if (EC)
90 return errorCodeToError(EC);
91 Ctx.setDiagnosticsOutputFile(
92 llvm::make_unique<yaml::Output>(DiagnosticOutputFile->os()));
93 DiagnosticOutputFile->keep();
94 return std::move(DiagnosticOutputFile);
95}
96
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000097// Simple helper to save temporary files for debug.
98static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
99 unsigned count, StringRef Suffix) {
100 if (TempDir.empty())
101 return;
102 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000103 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000104 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000105 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000106 if (EC)
107 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
108 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +0000109 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000110}
111
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000112static const GlobalValueSummary *
113getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
114 // If there is any strong definition anywhere, get it.
115 auto StrongDefForLinker = llvm::find_if(
116 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
117 auto Linkage = Summary->linkage();
118 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
119 !GlobalValue::isWeakForLinker(Linkage);
120 });
121 if (StrongDefForLinker != GVSummaryList.end())
122 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000123 // Get the first *linker visible* definition for this global in the summary
124 // list.
125 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000126 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
127 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000128 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
129 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000130 // Extern templates can be emitted as available_externally.
131 if (FirstDefForLinker == GVSummaryList.end())
132 return nullptr;
133 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000134}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000135
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000136// Populate map of GUID to the prevailing copy for any multiply defined
137// symbols. Currently assume first copy is prevailing, or any strong
138// definition. Can be refined with Linker information in the future.
139static void computePrevailingCopies(
140 const ModuleSummaryIndex &Index,
141 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000142 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
143 return GVSummaryList.size() > 1;
144 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000145
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000146 for (auto &I : Index) {
147 if (HasMultipleCopies(I.second))
148 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000149 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000150}
151
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000152static StringMap<MemoryBufferRef>
153generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
154 StringMap<MemoryBufferRef> ModuleMap;
155 for (auto &ModuleBuffer : Modules) {
156 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
157 ModuleMap.end() &&
158 "Expect unique Buffer Identifier");
159 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
160 }
161 return ModuleMap;
162}
163
Teresa Johnson26ab5772016-03-15 00:04:37 +0000164static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000165 if (renameModuleForThinLTO(TheModule, Index))
166 report_fatal_error("renameModuleForThinLTO failed");
167}
168
Peter Collingbournedac43b42016-12-01 05:52:32 +0000169static std::unique_ptr<Module>
170loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000171 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000172 SMDiagnostic Err;
173 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000174 Lazy
175 ? getLazyBitcodeModule(Buffer, Context,
176 /* ShouldLazyLoadMetadata */ true, IsImporting)
177 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000178 if (!ModuleOrErr) {
179 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
180 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
181 SourceMgr::DK_Error, EIB.message());
182 Err.print("ThinLTO", errs());
183 });
184 report_fatal_error("Can't load module, abort.");
185 }
186 return std::move(ModuleOrErr.get());
187}
188
Mehdi Amini01e32132016-03-26 05:40:34 +0000189static void
190crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
191 StringMap<MemoryBufferRef> &ModuleMap,
192 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000193 auto Loader = [&](StringRef Identifier) {
194 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000195 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000196 };
197
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000198 FunctionImporter Importer(Index, Loader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000199 if (!Importer.importFunctions(TheModule, ImportList))
200 report_fatal_error("importFunctions failed");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000201}
202
203static void optimizeModule(Module &TheModule, TargetMachine &TM) {
204 // Populate the PassManager
205 PassManagerBuilder PMB;
206 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
207 PMB.Inliner = createFunctionInliningPass();
208 // FIXME: should get it from the bitcode?
209 PMB.OptLevel = 3;
210 PMB.LoopVectorize = true;
211 PMB.SLPVectorize = true;
212 PMB.VerifyInput = true;
213 PMB.VerifyOutput = false;
214
215 legacy::PassManager PM;
216
217 // Add the TTI (required to inform the vectorizer about register size for
218 // instance)
219 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
220
221 // Add optimizations
222 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000223
224 PM.run(TheModule);
225}
226
Mehdi Amini059464f2016-04-24 03:18:01 +0000227// Convert the PreservedSymbols map from "Name" based to "GUID" based.
228static DenseSet<GlobalValue::GUID>
229computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
230 const Triple &TheTriple) {
231 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
232 for (auto &Entry : PreservedSymbols) {
233 StringRef Name = Entry.first();
234 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
235 Name = Name.drop_front();
236 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
237 }
238 return GUIDPreservedSymbols;
239}
240
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000241std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
242 TargetMachine &TM) {
243 SmallVector<char, 128> OutputBuffer;
244
245 // CodeGen
246 {
247 raw_svector_ostream OS(OutputBuffer);
248 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000249
250 // If the bitcode files contain ARC code and were compiled with optimization,
251 // the ObjCARCContractPass must be run, so do it unconditionally here.
252 PM.add(createObjCARCContractPass());
253
254 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000255 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
256 /* DisableVerify */ true))
257 report_fatal_error("Failed to setup codegen");
258
259 // Run codegen now. resulting binary is in OutputBuffer.
260 PM.run(TheModule);
261 }
262 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
263}
264
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000265/// Manage caching for a single Module.
266class ModuleCacheEntry {
267 SmallString<128> EntryPath;
268
269public:
270 // Create a cache entry. This compute a unique hash for the Module considering
271 // the current list of export/import, and offer an interface to query to
272 // access the content in the cache.
273 ModuleCacheEntry(
274 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
275 const FunctionImporter::ImportMapTy &ImportList,
276 const FunctionImporter::ExportSetTy &ExportList,
277 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000278 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000279 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
280 if (CachePath.empty())
281 return;
282
Mehdi Amini00fa1402016-10-08 04:44:18 +0000283 if (!Index.modulePaths().count(ModuleID))
284 // The module does not have an entry, it can't have a hash at all
285 return;
286
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000287 // Compute the unique hash for this entry
288 // This is based on the current compiler version, the module itself, the
289 // export list, the hash for every single module in the import list, the
290 // list of ResolvedODR for the module, and the list of preserved symbols.
291
Mehdi Aminif82bda02016-10-08 04:44:23 +0000292 // Include the hash for the current module
293 auto ModHash = Index.getModuleHash(ModuleID);
294
295 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
296 // No hash entry, no caching!
297 return;
298
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000299 SHA1 Hasher;
300
301 // Start with the compiler revision
302 Hasher.update(LLVM_VERSION_STRING);
303#ifdef HAVE_LLVM_REVISION
304 Hasher.update(LLVM_REVISION);
305#endif
306
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000307 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
308 for (auto F : ExportList)
309 // The export list can impact the internalization, be conservative here
310 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
311
312 // Include the hash for every module we import functions from
313 for (auto &Entry : ImportList) {
314 auto ModHash = Index.getModuleHash(Entry.first());
315 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
316 }
317
318 // Include the hash for the resolved ODR.
319 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000320 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000321 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000322 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000323 sizeof(GlobalValue::LinkageTypes)));
324 }
325
326 // Include the hash for the preserved symbols.
327 for (auto &Entry : PreservedSymbols) {
328 if (DefinedFunctions.count(Entry))
329 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000330 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000331 }
332
333 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
334 }
335
Mehdi Amini059464f2016-04-24 03:18:01 +0000336 // Access the path to this entry in the cache.
337 StringRef getEntryPath() { return EntryPath; }
338
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000339 // Try loading the buffer for this cache entry.
340 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
341 if (EntryPath.empty())
342 return std::error_code();
343 return MemoryBuffer::getFile(EntryPath);
344 }
345
346 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000347 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000348 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000349 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000350
351 // Write to a temporary to avoid race condition
352 SmallString<128> TempFilename;
353 int TempFD;
354 std::error_code EC =
355 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
356 if (EC) {
357 errs() << "Error: " << EC.message() << "\n";
358 report_fatal_error("ThinLTO: Can't get a temporary file");
359 }
360 {
361 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000362 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000363 }
364 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000365 EC = sys::fs::rename(TempFilename, EntryPath);
366 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000367 sys::fs::remove(TempFilename);
368 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
369 if (EC)
370 report_fatal_error(Twine("Failed to open ") + EntryPath +
371 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000372 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000373 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000374 }
375};
376
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000377static std::unique_ptr<MemoryBuffer>
378ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
379 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
380 const FunctionImporter::ImportMapTy &ImportList,
381 const FunctionImporter::ExportSetTy &ExportList,
382 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
383 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000384 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000385 bool DisableCodeGen, StringRef SaveTempsDir,
386 unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000387
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000388 // "Benchmark"-like optimization: single-source case
389 bool SingleModule = (ModuleMap.size() == 1);
390
391 if (!SingleModule) {
392 promoteModule(TheModule, Index);
393
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000394 // Apply summary-based LinkOnce/Weak resolution decisions.
395 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000396
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000397 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000398 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000399 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000400
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000401 // Be friendly and don't nuke totally the module when the client didn't
402 // supply anything to preserve.
403 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
404 // Apply summary-based internalization decisions.
405 thinLTOInternalizeModule(TheModule, DefinedGlobals);
406 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000407
408 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000409 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000410
411 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000412 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000413
414 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000415 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000416 }
417
418 optimizeModule(TheModule, TM);
419
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000420 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000421
Mehdi Amini43b657b2016-04-01 06:47:02 +0000422 if (DisableCodeGen) {
423 // Configured to stop before CodeGen, serialize the bitcode and return.
424 SmallVector<char, 128> OutputBuffer;
425 {
426 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000427 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000428 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000429 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000430 }
431 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
432 }
433
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000434 return codegenModule(TheModule, TM);
435}
436
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000437/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
438/// for caching, and in the \p Index for application during the ThinLTO
439/// backends. This is needed for correctness for exported symbols (ensure
440/// at least one copy kept) and a compile-time optimization (to drop duplicate
441/// copies when possible).
442static void resolveWeakForLinkerInIndex(
443 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000444 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
445 &ResolvedODR) {
446
447 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
448 computePrevailingCopies(Index, PrevailingCopy);
449
450 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
451 const auto &Prevailing = PrevailingCopy.find(GUID);
452 // Not in map means that there was only one copy, which must be prevailing.
453 if (Prevailing == PrevailingCopy.end())
454 return true;
455 return Prevailing->second == S;
456 };
457
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000458 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
459 GlobalValue::GUID GUID,
460 GlobalValue::LinkageTypes NewLinkage) {
461 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
462 };
463
Peter Collingbourne73589f32016-07-07 18:31:51 +0000464 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000465}
466
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000467// Initialize the TargetMachine builder for a given Triple
468static void initTMBuilder(TargetMachineBuilder &TMBuilder,
469 const Triple &TheTriple) {
470 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
471 // FIXME this looks pretty terrible...
472 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
473 if (TheTriple.getArch() == llvm::Triple::x86_64)
474 TMBuilder.MCpu = "core2";
475 else if (TheTriple.getArch() == llvm::Triple::x86)
476 TMBuilder.MCpu = "yonah";
477 else if (TheTriple.getArch() == llvm::Triple::aarch64)
478 TMBuilder.MCpu = "cyclone";
479 }
480 TMBuilder.TheTriple = std::move(TheTriple);
481}
482
483} // end anonymous namespace
484
485void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
486 MemoryBufferRef Buffer(Data, Identifier);
487 if (Modules.empty()) {
488 // First module added, so initialize the triple and some options
489 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000490 StringRef TripleStr;
491 ErrorOr<std::string> TripleOrErr =
492 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
493 if (TripleOrErr)
494 TripleStr = *TripleOrErr;
495 Triple TheTriple(TripleStr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000496 initTMBuilder(TMBuilder, Triple(TheTriple));
497 }
498#ifndef NDEBUG
499 else {
500 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000501 StringRef TripleStr;
502 ErrorOr<std::string> TripleOrErr =
503 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
504 if (TripleOrErr)
505 TripleStr = *TripleOrErr;
506 assert(TMBuilder.TheTriple.str() == TripleStr &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000507 "ThinLTO modules with different triple not supported");
508 }
509#endif
510 Modules.push_back(Buffer);
511}
512
513void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
514 PreservedSymbols.insert(Name);
515}
516
517void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000518 // FIXME: At the moment, we don't take advantage of this extra information,
519 // we're conservatively considering cross-references as preserved.
520 // CrossReferencedSymbols.insert(Name);
521 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000522}
523
524// TargetMachine factory
525std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
526 std::string ErrMsg;
527 const Target *TheTarget =
528 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
529 if (!TheTarget) {
530 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
531 }
532
533 // Use MAttr as the default set of features.
534 SubtargetFeatures Features(MAttr);
535 Features.getDefaultSubtargetFeatures(TheTriple);
536 std::string FeatureStr = Features.getString();
537 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
538 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
539 CodeModel::Default, CGOptLevel));
540}
541
542/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000543 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000544 * "thin-link".
545 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000546std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
547 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000548 uint64_t NextModuleId = 0;
549 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000550 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
551 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer);
552 if (!ObjOrErr) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000553 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000554 logAllUnhandledErrors(
555 ObjOrErr.takeError(), errs(),
556 "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000557 return nullptr;
558 }
559 auto Index = (*ObjOrErr)->takeIndex();
560 if (CombinedIndex) {
561 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
562 } else {
563 CombinedIndex = std::move(Index);
564 }
565 }
566 return CombinedIndex;
567}
568
569/**
570 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000571 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000572 */
573void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000574 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000575 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000576 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000577
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000578 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000579 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000580 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000581
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000582 // Generate import/export list
583 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
584 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
585 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
586 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000587
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000588 // Resolve LinkOnce/Weak symbols.
589 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000590 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000591
592 thinLTOResolveWeakForLinkerModule(
593 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000594
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000595 // Convert the preserved symbols set from string to GUID
596 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
597 PreservedSymbols, Triple(TheModule.getTargetTriple()));
598
599 // Promote the exported values in the index, so that they are promoted
600 // in the module.
601 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
602 const auto &ExportList = ExportLists.find(ModuleIdentifier);
603 return (ExportList != ExportLists.end() &&
604 ExportList->second.count(GUID)) ||
605 GUIDPreservedSymbols.count(GUID);
606 };
607 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
608
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000609 promoteModule(TheModule, Index);
610}
611
612/**
613 * Perform cross-module importing for the module identified by ModuleIdentifier.
614 */
615void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000616 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000617 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000618 auto ModuleCount = Index.modulePaths().size();
619
620 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000621 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000622 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000623
624 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000625 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
626 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000627 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
628 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000629 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
630
631 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000632}
633
634/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000635 * Compute the list of summaries needed for importing into module.
636 */
637void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
638 StringRef ModulePath, ModuleSummaryIndex &Index,
639 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
640 auto ModuleCount = Index.modulePaths().size();
641
642 // Collect for each module the list of function it defines (GUID -> Summary).
643 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
644 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
645
646 // Generate import/export list
647 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
648 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
649 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
650 ExportLists);
651
652 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000653 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000654 ModuleToSummariesForIndex);
655}
656
657/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000658 * Emit the list of files needed for importing into module.
659 */
660void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
661 StringRef OutputName,
662 ModuleSummaryIndex &Index) {
663 auto ModuleCount = Index.modulePaths().size();
664
665 // Collect for each module the list of function it defines (GUID -> Summary).
666 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
667 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
668
669 // Generate import/export list
670 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
671 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
672 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
673 ExportLists);
674
675 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000676 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000677 report_fatal_error(Twine("Failed to open ") + OutputName +
678 " to save imports lists\n");
679}
680
681/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000682 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000683 */
684void ThinLTOCodeGenerator::internalize(Module &TheModule,
685 ModuleSummaryIndex &Index) {
686 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
687 auto ModuleCount = Index.modulePaths().size();
688 auto ModuleIdentifier = TheModule.getModuleIdentifier();
689
690 // Convert the preserved symbols set from string to GUID
691 auto GUIDPreservedSymbols =
692 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
693
694 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000695 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000696 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
697
698 // Generate import/export list
699 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
700 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
701 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
702 ExportLists);
703 auto &ExportList = ExportLists[ModuleIdentifier];
704
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000705 // Be friendly and don't nuke totally the module when the client didn't
706 // supply anything to preserve.
707 if (ExportList.empty() && GUIDPreservedSymbols.empty())
708 return;
709
Mehdi Amini059464f2016-04-24 03:18:01 +0000710 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000711 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
712 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000713 return (ExportList != ExportLists.end() &&
714 ExportList->second.count(GUID)) ||
715 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000716 };
717 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
718 thinLTOInternalizeModule(TheModule,
719 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000720}
721
722/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000723 * Perform post-importing ThinLTO optimizations.
724 */
725void ThinLTOCodeGenerator::optimize(Module &TheModule) {
726 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000727
728 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000729 optimizeModule(TheModule, *TMBuilder.create());
730}
731
732/**
733 * Perform ThinLTO CodeGen.
734 */
735std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
736 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
737 return codegenModule(TheModule, *TMBuilder.create());
738}
739
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000740/// Write out the generated object file, either from CacheEntryPath or from
741/// OutputBuffer, preferring hard-link when possible.
742/// Returns the path to the generated file in SavedObjectsDirectoryPath.
743static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
744 StringRef SavedObjectsDirectoryPath,
745 const MemoryBuffer &OutputBuffer) {
746 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
747 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
748 OutputPath.c_str(); // Ensure the string is null terminated.
749 if (sys::fs::exists(OutputPath))
750 sys::fs::remove(OutputPath);
751
752 // We don't return a memory buffer to the linker, just a list of files.
753 if (!CacheEntryPath.empty()) {
754 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
755 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
756 if (!Err)
757 return OutputPath.str();
758 // Hard linking failed, try to copy.
759 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
760 if (!Err)
761 return OutputPath.str();
762 // Copy failed (could be because the CacheEntry was removed from the cache
763 // in the meantime by another process), fall back and try to write down the
764 // buffer to the output.
765 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
766 << "' to '" << OutputPath << "'\n";
767 }
768 // No cache entry, just write out the buffer.
769 std::error_code Err;
770 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
771 if (Err)
772 report_fatal_error("Can't open output '" + OutputPath + "'\n");
773 OS << OutputBuffer.getBuffer();
774 return OutputPath.str();
775}
776
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000777// Main entry point for the ThinLTO processing
778void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000779 if (CodeGenOnly) {
780 // Perform only parallel codegen and return.
781 ThreadPool Pool;
782 assert(ProducedBinaries.empty() && "The generator should not be reused");
783 ProducedBinaries.resize(Modules.size());
784 int count = 0;
785 for (auto &ModuleBuffer : Modules) {
786 Pool.async([&](int count) {
787 LLVMContext Context;
788 Context.setDiscardValueNames(LTODiscardValueNames);
789
790 // Parse module now
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000791 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false,
792 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000793
794 // CodeGen
795 ProducedBinaries[count] = codegen(*TheModule);
796 }, count++);
797 }
798
799 return;
800 }
801
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000802 // Sequential linking phase
803 auto Index = linkCombinedIndex();
804
805 // Save temps: index.
806 if (!SaveTempsDir.empty()) {
807 auto SaveTempPath = SaveTempsDir + "index.bc";
808 std::error_code EC;
809 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
810 if (EC)
811 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
812 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000813 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000814 }
815
816 // Prepare the resulting object vector
817 assert(ProducedBinaries.empty() && "The generator should not be reused");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000818 if (SavedObjectsDirectoryPath.empty())
819 ProducedBinaries.resize(Modules.size());
820 else {
821 sys::fs::create_directories(SavedObjectsDirectoryPath);
822 bool IsDir;
823 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
824 if (!IsDir)
825 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
826 ProducedBinaryFiles.resize(Modules.size());
827 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000828
829 // Prepare the module map.
830 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000831 auto ModuleCount = Modules.size();
832
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000833 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000834 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000835 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
836
Mehdi Amini01e32132016-03-26 05:40:34 +0000837 // Collect the import/export lists for all modules from the call-graph in the
838 // combined index.
839 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
840 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000841 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
842 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000843
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000844 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000845 // computing the caching hash and the internalization.
846 auto GUIDPreservedSymbols =
847 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000848
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000849 // We use a std::map here to be able to have a defined ordering when
850 // producing a hash for the cache entry.
851 // FIXME: we should be able to compute the caching hash for the entry based
852 // on the index, and nuke this map.
853 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
854
855 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
856 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000857 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000858
859 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
860 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000861 return (ExportList != ExportLists.end() &&
862 ExportList->second.count(GUID)) ||
863 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000864 };
865
866 // Use global summary-based analysis to identify symbols that can be
867 // internalized (because they aren't exported or preserved as per callback).
868 // Changes are made in the index, consumed in the ThinLTO backends.
869 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
870
Teresa Johnson141149f2016-05-24 18:44:01 +0000871 // Make sure that every module has an entry in the ExportLists and
872 // ResolvedODR maps to enable threaded access to these maps below.
873 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000874 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000875 ResolvedODR[DefinedGVSummaries.first()];
876 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000877
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000878 // Compute the ordering we will process the inputs: the rough heuristic here
879 // is to sort them per size so that the largest module get schedule as soon as
880 // possible. This is purely a compile-time optimization.
881 std::vector<int> ModulesOrdering;
882 ModulesOrdering.resize(Modules.size());
883 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
884 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
885 [&](int LeftIndex, int RightIndex) {
886 auto LSize = Modules[LeftIndex].getBufferSize();
887 auto RSize = Modules[RightIndex].getBufferSize();
888 return LSize > RSize;
889 });
890
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000891 // Parallel optimizer + codegen
892 {
893 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000894 for (auto IndexCount : ModulesOrdering) {
895 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000896 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000897 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000898 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000899
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000900 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
901
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000902 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000903 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
904 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000905 ResolvedODR[ModuleIdentifier],
906 DefinedFunctions, GUIDPreservedSymbols);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000907 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000908
909 {
910 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000911 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000912 << CacheEntryPath << "' for buffer " << count << " "
913 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000914
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000915 if (ErrOrBuffer) {
916 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000917 if (SavedObjectsDirectoryPath.empty())
918 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
919 else
920 ProducedBinaryFiles[count] = writeGeneratedObject(
921 count, CacheEntryPath, SavedObjectsDirectoryPath,
922 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000923 return;
924 }
925 }
926
927 LLVMContext Context;
928 Context.setDiscardValueNames(LTODiscardValueNames);
929 Context.enableDebugTypeODRUniquing();
Mehdi Amini19f176b2016-11-19 18:20:05 +0000930 auto DiagFileOrErr = setupOptimizationRemarks(Context, count);
931 if (!DiagFileOrErr) {
932 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
933 report_fatal_error("ThinLTO: Can't get an output file for the "
934 "remarks");
935 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000936
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000937 // Parse module now
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000938 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false,
939 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000940
941 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000942 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000943
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000944 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000945 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000946 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000947 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000948 ExportList, GUIDPreservedSymbols,
949 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Amini059464f2016-04-24 03:18:01 +0000950 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000951
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000952 // Commit to the cache (if enabled)
953 CacheEntry.write(*OutputBuffer);
954
955 if (SavedObjectsDirectoryPath.empty()) {
956 // We need to generated a memory buffer for the linker.
957 if (!CacheEntryPath.empty()) {
958 // Cache is enabled, reload from the cache
959 // We do this to lower memory pressuree: the buffer is on the heap
960 // and releasing it frees memory that can be used for the next input
961 // file. The final binary link will read from the VFS cache
962 // (hopefully!) or from disk if the memory pressure wasn't too high.
963 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
964 if (auto EC = ReloadedBufferOrErr.getError()) {
965 // On error, keeping the preexisting buffer and printing a
966 // diagnostic is more friendly than just crashing.
967 errs() << "error: can't reload cached file '" << CacheEntryPath
968 << "': " << EC.message() << "\n";
969 } else {
970 OutputBuffer = std::move(*ReloadedBufferOrErr);
971 }
972 }
973 ProducedBinaries[count] = std::move(OutputBuffer);
974 return;
975 }
976 ProducedBinaryFiles[count] = writeGeneratedObject(
977 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000978 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000979 }
980 }
981
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000982 CachePruning(CacheOptions.Path)
Pavel Labath757ca882016-10-24 10:59:17 +0000983 .setPruningInterval(std::chrono::seconds(CacheOptions.PruningInterval))
984 .setEntryExpiration(std::chrono::seconds(CacheOptions.Expiration))
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000985 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
986 .prune();
987
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000988 // If statistics were requested, print them out now.
989 if (llvm::AreStatisticsEnabled())
990 llvm::PrintStatistics();
991}