blob: 928f69a17de90b78a2aadf7666f80e69f2859743 [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);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000199 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
200 if (!Result) {
201 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
202 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
203 SourceMgr::DK_Error, EIB.message());
204 Err.print("ThinLTO", errs());
205 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000206 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000207 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000208}
209
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000210static void optimizeModule(Module &TheModule, TargetMachine &TM,
211 unsigned OptLevel) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000212 // Populate the PassManager
213 PassManagerBuilder PMB;
214 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
215 PMB.Inliner = createFunctionInliningPass();
216 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000217 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000218 PMB.LoopVectorize = true;
219 PMB.SLPVectorize = true;
220 PMB.VerifyInput = true;
221 PMB.VerifyOutput = false;
222
223 legacy::PassManager PM;
224
225 // Add the TTI (required to inform the vectorizer about register size for
226 // instance)
227 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
228
229 // Add optimizations
230 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000231
232 PM.run(TheModule);
233}
234
Mehdi Amini059464f2016-04-24 03:18:01 +0000235// Convert the PreservedSymbols map from "Name" based to "GUID" based.
236static DenseSet<GlobalValue::GUID>
237computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
238 const Triple &TheTriple) {
239 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
240 for (auto &Entry : PreservedSymbols) {
241 StringRef Name = Entry.first();
242 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
243 Name = Name.drop_front();
244 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
245 }
246 return GUIDPreservedSymbols;
247}
248
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000249std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
250 TargetMachine &TM) {
251 SmallVector<char, 128> OutputBuffer;
252
253 // CodeGen
254 {
255 raw_svector_ostream OS(OutputBuffer);
256 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000257
258 // If the bitcode files contain ARC code and were compiled with optimization,
259 // the ObjCARCContractPass must be run, so do it unconditionally here.
260 PM.add(createObjCARCContractPass());
261
262 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000263 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
264 /* DisableVerify */ true))
265 report_fatal_error("Failed to setup codegen");
266
267 // Run codegen now. resulting binary is in OutputBuffer.
268 PM.run(TheModule);
269 }
270 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
271}
272
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000273/// Manage caching for a single Module.
274class ModuleCacheEntry {
275 SmallString<128> EntryPath;
276
277public:
278 // Create a cache entry. This compute a unique hash for the Module considering
279 // the current list of export/import, and offer an interface to query to
280 // access the content in the cache.
281 ModuleCacheEntry(
282 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
283 const FunctionImporter::ImportMapTy &ImportList,
284 const FunctionImporter::ExportSetTy &ExportList,
285 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000286 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000287 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
288 if (CachePath.empty())
289 return;
290
Mehdi Amini00fa1402016-10-08 04:44:18 +0000291 if (!Index.modulePaths().count(ModuleID))
292 // The module does not have an entry, it can't have a hash at all
293 return;
294
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000295 // Compute the unique hash for this entry
296 // This is based on the current compiler version, the module itself, the
297 // export list, the hash for every single module in the import list, the
298 // list of ResolvedODR for the module, and the list of preserved symbols.
299
Mehdi Aminif82bda02016-10-08 04:44:23 +0000300 // Include the hash for the current module
301 auto ModHash = Index.getModuleHash(ModuleID);
302
303 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
304 // No hash entry, no caching!
305 return;
306
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000307 SHA1 Hasher;
308
309 // Start with the compiler revision
310 Hasher.update(LLVM_VERSION_STRING);
311#ifdef HAVE_LLVM_REVISION
312 Hasher.update(LLVM_REVISION);
313#endif
314
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000315 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
316 for (auto F : ExportList)
317 // The export list can impact the internalization, be conservative here
318 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
319
320 // Include the hash for every module we import functions from
321 for (auto &Entry : ImportList) {
322 auto ModHash = Index.getModuleHash(Entry.first());
323 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
324 }
325
326 // Include the hash for the resolved ODR.
327 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000328 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000329 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000330 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000331 sizeof(GlobalValue::LinkageTypes)));
332 }
333
334 // Include the hash for the preserved symbols.
335 for (auto &Entry : PreservedSymbols) {
336 if (DefinedFunctions.count(Entry))
337 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000338 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000339 }
340
341 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
342 }
343
Mehdi Amini059464f2016-04-24 03:18:01 +0000344 // Access the path to this entry in the cache.
345 StringRef getEntryPath() { return EntryPath; }
346
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000347 // Try loading the buffer for this cache entry.
348 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
349 if (EntryPath.empty())
350 return std::error_code();
351 return MemoryBuffer::getFile(EntryPath);
352 }
353
354 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000355 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000356 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000357 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000358
359 // Write to a temporary to avoid race condition
360 SmallString<128> TempFilename;
361 int TempFD;
362 std::error_code EC =
363 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
364 if (EC) {
365 errs() << "Error: " << EC.message() << "\n";
366 report_fatal_error("ThinLTO: Can't get a temporary file");
367 }
368 {
369 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000370 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000371 }
372 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000373 EC = sys::fs::rename(TempFilename, EntryPath);
374 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000375 sys::fs::remove(TempFilename);
376 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
377 if (EC)
378 report_fatal_error(Twine("Failed to open ") + EntryPath +
379 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000380 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000381 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000382 }
383};
384
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000385static std::unique_ptr<MemoryBuffer>
386ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
387 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
388 const FunctionImporter::ImportMapTy &ImportList,
389 const FunctionImporter::ExportSetTy &ExportList,
390 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
391 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000392 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000393 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000394 unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000395
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000396 // "Benchmark"-like optimization: single-source case
397 bool SingleModule = (ModuleMap.size() == 1);
398
399 if (!SingleModule) {
400 promoteModule(TheModule, Index);
401
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000402 // Apply summary-based LinkOnce/Weak resolution decisions.
403 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000404
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000405 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000406 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000407 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000408
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000409 // Be friendly and don't nuke totally the module when the client didn't
410 // supply anything to preserve.
411 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
412 // Apply summary-based internalization decisions.
413 thinLTOInternalizeModule(TheModule, DefinedGlobals);
414 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000415
416 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000417 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000418
419 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000420 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000421
422 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000423 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000424 }
425
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000426 optimizeModule(TheModule, TM, OptLevel);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000427
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000428 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000429
Mehdi Amini43b657b2016-04-01 06:47:02 +0000430 if (DisableCodeGen) {
431 // Configured to stop before CodeGen, serialize the bitcode and return.
432 SmallVector<char, 128> OutputBuffer;
433 {
434 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000435 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000436 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000437 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000438 }
439 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
440 }
441
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000442 return codegenModule(TheModule, TM);
443}
444
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000445/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
446/// for caching, and in the \p Index for application during the ThinLTO
447/// backends. This is needed for correctness for exported symbols (ensure
448/// at least one copy kept) and a compile-time optimization (to drop duplicate
449/// copies when possible).
450static void resolveWeakForLinkerInIndex(
451 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000452 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
453 &ResolvedODR) {
454
455 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
456 computePrevailingCopies(Index, PrevailingCopy);
457
458 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
459 const auto &Prevailing = PrevailingCopy.find(GUID);
460 // Not in map means that there was only one copy, which must be prevailing.
461 if (Prevailing == PrevailingCopy.end())
462 return true;
463 return Prevailing->second == S;
464 };
465
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000466 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
467 GlobalValue::GUID GUID,
468 GlobalValue::LinkageTypes NewLinkage) {
469 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
470 };
471
Peter Collingbourne73589f32016-07-07 18:31:51 +0000472 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000473}
474
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000475// Initialize the TargetMachine builder for a given Triple
476static void initTMBuilder(TargetMachineBuilder &TMBuilder,
477 const Triple &TheTriple) {
478 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
479 // FIXME this looks pretty terrible...
480 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
481 if (TheTriple.getArch() == llvm::Triple::x86_64)
482 TMBuilder.MCpu = "core2";
483 else if (TheTriple.getArch() == llvm::Triple::x86)
484 TMBuilder.MCpu = "yonah";
485 else if (TheTriple.getArch() == llvm::Triple::aarch64)
486 TMBuilder.MCpu = "cyclone";
487 }
488 TMBuilder.TheTriple = std::move(TheTriple);
489}
490
491} // end anonymous namespace
492
493void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
494 MemoryBufferRef Buffer(Data, Identifier);
495 if (Modules.empty()) {
496 // First module added, so initialize the triple and some options
497 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000498 StringRef TripleStr;
499 ErrorOr<std::string> TripleOrErr =
500 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
501 if (TripleOrErr)
502 TripleStr = *TripleOrErr;
503 Triple TheTriple(TripleStr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000504 initTMBuilder(TMBuilder, Triple(TheTriple));
505 }
506#ifndef NDEBUG
507 else {
508 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000509 StringRef TripleStr;
510 ErrorOr<std::string> TripleOrErr =
511 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
512 if (TripleOrErr)
513 TripleStr = *TripleOrErr;
514 assert(TMBuilder.TheTriple.str() == TripleStr &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000515 "ThinLTO modules with different triple not supported");
516 }
517#endif
518 Modules.push_back(Buffer);
519}
520
521void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
522 PreservedSymbols.insert(Name);
523}
524
525void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000526 // FIXME: At the moment, we don't take advantage of this extra information,
527 // we're conservatively considering cross-references as preserved.
528 // CrossReferencedSymbols.insert(Name);
529 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000530}
531
532// TargetMachine factory
533std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
534 std::string ErrMsg;
535 const Target *TheTarget =
536 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
537 if (!TheTarget) {
538 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
539 }
540
541 // Use MAttr as the default set of features.
542 SubtargetFeatures Features(MAttr);
543 Features.getDefaultSubtargetFeatures(TheTriple);
544 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000545
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000546 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
547 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
548 CodeModel::Default, CGOptLevel));
549}
550
551/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000552 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000553 * "thin-link".
554 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000555std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
556 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000557 uint64_t NextModuleId = 0;
558 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000559 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
560 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer);
561 if (!ObjOrErr) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000562 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000563 logAllUnhandledErrors(
564 ObjOrErr.takeError(), errs(),
565 "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000566 return nullptr;
567 }
568 auto Index = (*ObjOrErr)->takeIndex();
569 if (CombinedIndex) {
570 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
571 } else {
572 CombinedIndex = std::move(Index);
573 }
574 }
575 return CombinedIndex;
576}
577
578/**
579 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000580 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000581 */
582void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000583 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000584 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000585 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000586
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000587 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000588 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000589 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000590
Teresa Johnson6c475a72017-01-05 21:34:18 +0000591 // Convert the preserved symbols set from string to GUID
592 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
593 PreservedSymbols, Triple(TheModule.getTargetTriple()));
594
595 // Compute "dead" symbols, we don't want to import/export these!
596 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
597
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000598 // Generate import/export list
599 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
600 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
601 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000602 ExportLists, &DeadSymbols);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000603
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000604 // Resolve LinkOnce/Weak symbols.
605 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000606 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000607
608 thinLTOResolveWeakForLinkerModule(
609 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000610
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000611 // Promote the exported values in the index, so that they are promoted
612 // in the module.
613 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
614 const auto &ExportList = ExportLists.find(ModuleIdentifier);
615 return (ExportList != ExportLists.end() &&
616 ExportList->second.count(GUID)) ||
617 GUIDPreservedSymbols.count(GUID);
618 };
619 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
620
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000621 promoteModule(TheModule, Index);
622}
623
624/**
625 * Perform cross-module importing for the module identified by ModuleIdentifier.
626 */
627void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000628 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000629 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000630 auto ModuleCount = Index.modulePaths().size();
631
632 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000633 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000634 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000635
Teresa Johnson6c475a72017-01-05 21:34:18 +0000636 // Convert the preserved symbols set from string to GUID
637 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
638 PreservedSymbols, Triple(TheModule.getTargetTriple()));
639
640 // Compute "dead" symbols, we don't want to import/export these!
641 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
642
Mehdi Amini01e32132016-03-26 05:40:34 +0000643 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000644 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
645 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000646 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000647 ExportLists, &DeadSymbols);
Mehdi Amini01e32132016-03-26 05:40:34 +0000648 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
649
650 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000651}
652
653/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000654 * Compute the list of summaries needed for importing into module.
655 */
656void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
657 StringRef ModulePath, ModuleSummaryIndex &Index,
658 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
659 auto ModuleCount = Index.modulePaths().size();
660
661 // Collect for each module the list of function it defines (GUID -> Summary).
662 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
663 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
664
665 // Generate import/export list
666 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
667 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
668 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
669 ExportLists);
670
671 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000672 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000673 ModuleToSummariesForIndex);
674}
675
676/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000677 * Emit the list of files needed for importing into module.
678 */
679void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
680 StringRef OutputName,
681 ModuleSummaryIndex &Index) {
682 auto ModuleCount = Index.modulePaths().size();
683
684 // Collect for each module the list of function it defines (GUID -> Summary).
685 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
686 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
687
688 // Generate import/export list
689 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
690 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
691 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
692 ExportLists);
693
694 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000695 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000696 report_fatal_error(Twine("Failed to open ") + OutputName +
697 " to save imports lists\n");
698}
699
700/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000701 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000702 */
703void ThinLTOCodeGenerator::internalize(Module &TheModule,
704 ModuleSummaryIndex &Index) {
705 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
706 auto ModuleCount = Index.modulePaths().size();
707 auto ModuleIdentifier = TheModule.getModuleIdentifier();
708
709 // Convert the preserved symbols set from string to GUID
710 auto GUIDPreservedSymbols =
711 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
712
713 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000714 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000715 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
716
Teresa Johnson6c475a72017-01-05 21:34:18 +0000717 // Compute "dead" symbols, we don't want to import/export these!
718 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
719
Mehdi Amini059464f2016-04-24 03:18:01 +0000720 // Generate import/export list
721 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
722 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
723 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000724 ExportLists, &DeadSymbols);
Mehdi Amini059464f2016-04-24 03:18:01 +0000725 auto &ExportList = ExportLists[ModuleIdentifier];
726
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000727 // Be friendly and don't nuke totally the module when the client didn't
728 // supply anything to preserve.
729 if (ExportList.empty() && GUIDPreservedSymbols.empty())
730 return;
731
Mehdi Amini059464f2016-04-24 03:18:01 +0000732 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000733 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
734 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000735 return (ExportList != ExportLists.end() &&
736 ExportList->second.count(GUID)) ||
737 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000738 };
739 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
740 thinLTOInternalizeModule(TheModule,
741 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000742}
743
744/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000745 * Perform post-importing ThinLTO optimizations.
746 */
747void ThinLTOCodeGenerator::optimize(Module &TheModule) {
748 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000749
750 // Optimize now
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000751 optimizeModule(TheModule, *TMBuilder.create(), OptLevel);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000752}
753
754/**
755 * Perform ThinLTO CodeGen.
756 */
757std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
758 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
759 return codegenModule(TheModule, *TMBuilder.create());
760}
761
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000762/// Write out the generated object file, either from CacheEntryPath or from
763/// OutputBuffer, preferring hard-link when possible.
764/// Returns the path to the generated file in SavedObjectsDirectoryPath.
765static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
766 StringRef SavedObjectsDirectoryPath,
767 const MemoryBuffer &OutputBuffer) {
768 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
769 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
770 OutputPath.c_str(); // Ensure the string is null terminated.
771 if (sys::fs::exists(OutputPath))
772 sys::fs::remove(OutputPath);
773
774 // We don't return a memory buffer to the linker, just a list of files.
775 if (!CacheEntryPath.empty()) {
776 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
777 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
778 if (!Err)
779 return OutputPath.str();
780 // Hard linking failed, try to copy.
781 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
782 if (!Err)
783 return OutputPath.str();
784 // Copy failed (could be because the CacheEntry was removed from the cache
785 // in the meantime by another process), fall back and try to write down the
786 // buffer to the output.
787 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
788 << "' to '" << OutputPath << "'\n";
789 }
790 // No cache entry, just write out the buffer.
791 std::error_code Err;
792 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
793 if (Err)
794 report_fatal_error("Can't open output '" + OutputPath + "'\n");
795 OS << OutputBuffer.getBuffer();
796 return OutputPath.str();
797}
798
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000799// Main entry point for the ThinLTO processing
800void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000801 if (CodeGenOnly) {
802 // Perform only parallel codegen and return.
803 ThreadPool Pool;
804 assert(ProducedBinaries.empty() && "The generator should not be reused");
805 ProducedBinaries.resize(Modules.size());
806 int count = 0;
807 for (auto &ModuleBuffer : Modules) {
808 Pool.async([&](int count) {
809 LLVMContext Context;
810 Context.setDiscardValueNames(LTODiscardValueNames);
811
812 // Parse module now
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000813 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false,
814 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000815
816 // CodeGen
817 ProducedBinaries[count] = codegen(*TheModule);
818 }, count++);
819 }
820
821 return;
822 }
823
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000824 // Sequential linking phase
825 auto Index = linkCombinedIndex();
826
827 // Save temps: index.
828 if (!SaveTempsDir.empty()) {
829 auto SaveTempPath = SaveTempsDir + "index.bc";
830 std::error_code EC;
831 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
832 if (EC)
833 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
834 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000835 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000836 }
837
838 // Prepare the resulting object vector
839 assert(ProducedBinaries.empty() && "The generator should not be reused");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000840 if (SavedObjectsDirectoryPath.empty())
841 ProducedBinaries.resize(Modules.size());
842 else {
843 sys::fs::create_directories(SavedObjectsDirectoryPath);
844 bool IsDir;
845 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
846 if (!IsDir)
847 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
848 ProducedBinaryFiles.resize(Modules.size());
849 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000850
851 // Prepare the module map.
852 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000853 auto ModuleCount = Modules.size();
854
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000855 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000856 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000857 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
858
Teresa Johnson6c475a72017-01-05 21:34:18 +0000859 // Convert the preserved symbols set from string to GUID, this is needed for
860 // computing the caching hash and the internalization.
861 auto GUIDPreservedSymbols =
862 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
863
864 // Compute "dead" symbols, we don't want to import/export these!
865 auto DeadSymbols = computeDeadSymbols(*Index, GUIDPreservedSymbols);
866
Mehdi Amini01e32132016-03-26 05:40:34 +0000867 // Collect the import/export lists for all modules from the call-graph in the
868 // combined index.
869 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
870 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000871 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000872 ExportLists, &DeadSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000873
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000874 // We use a std::map here to be able to have a defined ordering when
875 // producing a hash for the cache entry.
876 // FIXME: we should be able to compute the caching hash for the entry based
877 // on the index, and nuke this map.
878 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
879
880 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
881 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000882 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000883
884 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
885 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000886 return (ExportList != ExportLists.end() &&
887 ExportList->second.count(GUID)) ||
888 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000889 };
890
891 // Use global summary-based analysis to identify symbols that can be
892 // internalized (because they aren't exported or preserved as per callback).
893 // Changes are made in the index, consumed in the ThinLTO backends.
894 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
895
Teresa Johnson141149f2016-05-24 18:44:01 +0000896 // Make sure that every module has an entry in the ExportLists and
897 // ResolvedODR maps to enable threaded access to these maps below.
898 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000899 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000900 ResolvedODR[DefinedGVSummaries.first()];
901 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000902
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000903 // Compute the ordering we will process the inputs: the rough heuristic here
904 // is to sort them per size so that the largest module get schedule as soon as
905 // possible. This is purely a compile-time optimization.
906 std::vector<int> ModulesOrdering;
907 ModulesOrdering.resize(Modules.size());
908 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
909 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
910 [&](int LeftIndex, int RightIndex) {
911 auto LSize = Modules[LeftIndex].getBufferSize();
912 auto RSize = Modules[RightIndex].getBufferSize();
913 return LSize > RSize;
914 });
915
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000916 // Parallel optimizer + codegen
917 {
918 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000919 for (auto IndexCount : ModulesOrdering) {
920 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000921 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000922 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000923 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000924
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000925 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
926
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000927 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000928 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
929 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000930 ResolvedODR[ModuleIdentifier],
931 DefinedFunctions, GUIDPreservedSymbols);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000932 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000933
934 {
935 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000936 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000937 << CacheEntryPath << "' for buffer " << count << " "
938 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000939
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000940 if (ErrOrBuffer) {
941 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000942 if (SavedObjectsDirectoryPath.empty())
943 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
944 else
945 ProducedBinaryFiles[count] = writeGeneratedObject(
946 count, CacheEntryPath, SavedObjectsDirectoryPath,
947 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000948 return;
949 }
950 }
951
952 LLVMContext Context;
953 Context.setDiscardValueNames(LTODiscardValueNames);
954 Context.enableDebugTypeODRUniquing();
Mehdi Amini19f176b2016-11-19 18:20:05 +0000955 auto DiagFileOrErr = setupOptimizationRemarks(Context, count);
956 if (!DiagFileOrErr) {
957 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
958 report_fatal_error("ThinLTO: Can't get an output file for the "
959 "remarks");
960 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000961
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000962 // Parse module now
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000963 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false,
964 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000965
966 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000967 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000968
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000969 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000970 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000971 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000972 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000973 ExportList, GUIDPreservedSymbols,
974 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000975 DisableCodeGen, SaveTempsDir, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000976
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000977 // Commit to the cache (if enabled)
978 CacheEntry.write(*OutputBuffer);
979
980 if (SavedObjectsDirectoryPath.empty()) {
981 // We need to generated a memory buffer for the linker.
982 if (!CacheEntryPath.empty()) {
983 // Cache is enabled, reload from the cache
984 // We do this to lower memory pressuree: the buffer is on the heap
985 // and releasing it frees memory that can be used for the next input
986 // file. The final binary link will read from the VFS cache
987 // (hopefully!) or from disk if the memory pressure wasn't too high.
988 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
989 if (auto EC = ReloadedBufferOrErr.getError()) {
990 // On error, keeping the preexisting buffer and printing a
991 // diagnostic is more friendly than just crashing.
992 errs() << "error: can't reload cached file '" << CacheEntryPath
993 << "': " << EC.message() << "\n";
994 } else {
995 OutputBuffer = std::move(*ReloadedBufferOrErr);
996 }
997 }
998 ProducedBinaries[count] = std::move(OutputBuffer);
999 return;
1000 }
1001 ProducedBinaryFiles[count] = writeGeneratedObject(
1002 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001003 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001004 }
1005 }
1006
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001007 CachePruning(CacheOptions.Path)
Pavel Labath757ca882016-10-24 10:59:17 +00001008 .setPruningInterval(std::chrono::seconds(CacheOptions.PruningInterval))
1009 .setEntryExpiration(std::chrono::seconds(CacheOptions.Expiration))
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001010 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
1011 .prune();
1012
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001013 // If statistics were requested, print them out now.
1014 if (llvm::AreStatisticsEnabled())
1015 llvm::PrintStatistics();
1016}