blob: d2fc892d6a9dc5d906b69c585a76c4d0e9751d35 [file] [log] [blame]
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001//===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Thin Link Time Optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne5c732202016-07-14 21:21:16 +000015#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000016
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000017#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000018#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000019#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000020#include "llvm/Analysis/ProfileSummaryInfo.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000025#include "llvm/Bitcode/BitcodeWriterPass.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000026#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000027#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000029#include "llvm/IR/LegacyPassManager.h"
30#include "llvm/IR/Mangler.h"
31#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000032#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/Linker/Linker.h"
34#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000035#include "llvm/Object/IRObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000036#include "llvm/Support/CachePruning.h"
37#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000038#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000039#include "llvm/Support/Path.h"
40#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000041#include "llvm/Support/TargetRegistry.h"
42#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000043#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000044#include "llvm/Support/ToolOutputFile.h"
Peter Collingbourne942fa562017-04-13 01:26:12 +000045#include "llvm/Support/VCSRevision.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000046#include "llvm/Target/TargetMachine.h"
47#include "llvm/Transforms/IPO.h"
48#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000049#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000050#include "llvm/Transforms/IPO/PassManagerBuilder.h"
51#include "llvm/Transforms/ObjCARC.h"
52#include "llvm/Transforms/Utils/FunctionImportUtils.h"
53
Mehdi Amini819e9cd2016-05-16 19:33:07 +000054#include <numeric>
55
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000056using namespace llvm;
57
Mehdi Amini1aafabf2016-04-16 07:02:16 +000058#define DEBUG_TYPE "thinlto"
59
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000060namespace llvm {
61// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
62extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000063extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000064extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000065}
66
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000067namespace {
68
Teresa Johnsonec544c52016-10-19 17:35:01 +000069static cl::opt<int>
70 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000071
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000072// Simple helper to save temporary files for debug.
73static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
74 unsigned count, StringRef Suffix) {
75 if (TempDir.empty())
76 return;
77 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000078 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000079 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000080 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081 if (EC)
82 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
83 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000084 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000085}
86
Teresa Johnson4d2613f2016-05-24 17:24:25 +000087static const GlobalValueSummary *
88getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
89 // If there is any strong definition anywhere, get it.
90 auto StrongDefForLinker = llvm::find_if(
91 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
92 auto Linkage = Summary->linkage();
93 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
94 !GlobalValue::isWeakForLinker(Linkage);
95 });
96 if (StrongDefForLinker != GVSummaryList.end())
97 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +000098 // Get the first *linker visible* definition for this global in the summary
99 // list.
100 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000101 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
102 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000103 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
104 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000105 // Extern templates can be emitted as available_externally.
106 if (FirstDefForLinker == GVSummaryList.end())
107 return nullptr;
108 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000109}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000110
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000111// Populate map of GUID to the prevailing copy for any multiply defined
112// symbols. Currently assume first copy is prevailing, or any strong
113// definition. Can be refined with Linker information in the future.
114static void computePrevailingCopies(
115 const ModuleSummaryIndex &Index,
116 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000117 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
118 return GVSummaryList.size() > 1;
119 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000120
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000121 for (auto &I : Index) {
122 if (HasMultipleCopies(I.second))
123 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000124 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000125}
126
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000127static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000128generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000129 StringMap<MemoryBufferRef> ModuleMap;
130 for (auto &ModuleBuffer : Modules) {
131 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
132 ModuleMap.end() &&
133 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000134 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000135 }
136 return ModuleMap;
137}
138
Teresa Johnson26ab5772016-03-15 00:04:37 +0000139static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000140 if (renameModuleForThinLTO(TheModule, Index))
141 report_fatal_error("renameModuleForThinLTO failed");
142}
143
Peter Collingbournedac43b42016-12-01 05:52:32 +0000144static std::unique_ptr<Module>
145loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000146 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000147 SMDiagnostic Err;
148 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000149 Lazy
150 ? getLazyBitcodeModule(Buffer, Context,
151 /* ShouldLazyLoadMetadata */ true, IsImporting)
152 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000153 if (!ModuleOrErr) {
154 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
155 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
156 SourceMgr::DK_Error, EIB.message());
157 Err.print("ThinLTO", errs());
158 });
159 report_fatal_error("Can't load module, abort.");
160 }
161 return std::move(ModuleOrErr.get());
162}
163
Mehdi Amini01e32132016-03-26 05:40:34 +0000164static void
165crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
166 StringMap<MemoryBufferRef> &ModuleMap,
167 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000168 auto Loader = [&](StringRef Identifier) {
169 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000170 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000171 };
172
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000173 FunctionImporter Importer(Index, Loader);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000174 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
175 if (!Result) {
176 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
177 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
178 SourceMgr::DK_Error, EIB.message());
179 Err.print("ThinLTO", errs());
180 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000181 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000182 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000183}
184
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000185static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000186 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000187 // Populate the PassManager
188 PassManagerBuilder PMB;
189 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000190 if (Freestanding)
191 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000192 PMB.Inliner = createFunctionInliningPass();
193 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000194 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000195 PMB.LoopVectorize = true;
196 PMB.SLPVectorize = true;
197 PMB.VerifyInput = true;
198 PMB.VerifyOutput = false;
199
200 legacy::PassManager PM;
201
202 // Add the TTI (required to inform the vectorizer about register size for
203 // instance)
204 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
205
206 // Add optimizations
207 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000208
209 PM.run(TheModule);
210}
211
Mehdi Amini059464f2016-04-24 03:18:01 +0000212// Convert the PreservedSymbols map from "Name" based to "GUID" based.
213static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000214computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
215 const Triple &TheTriple) {
216 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
217 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000218 StringRef Name = Entry.first();
219 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
220 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000221 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000222 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000223 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000224}
225
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000226std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
227 TargetMachine &TM) {
228 SmallVector<char, 128> OutputBuffer;
229
230 // CodeGen
231 {
232 raw_svector_ostream OS(OutputBuffer);
233 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000234
235 // If the bitcode files contain ARC code and were compiled with optimization,
236 // the ObjCARCContractPass must be run, so do it unconditionally here.
237 PM.add(createObjCARCContractPass());
238
239 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000240 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
241 /* DisableVerify */ true))
242 report_fatal_error("Failed to setup codegen");
243
244 // Run codegen now. resulting binary is in OutputBuffer.
245 PM.run(TheModule);
246 }
247 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
248}
249
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000250/// Manage caching for a single Module.
251class ModuleCacheEntry {
252 SmallString<128> EntryPath;
253
254public:
255 // Create a cache entry. This compute a unique hash for the Module considering
256 // the current list of export/import, and offer an interface to query to
257 // access the content in the cache.
258 ModuleCacheEntry(
259 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
260 const FunctionImporter::ImportMapTy &ImportList,
261 const FunctionImporter::ExportSetTy &ExportList,
262 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000263 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000264 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000265 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000266 if (CachePath.empty())
267 return;
268
Mehdi Amini00fa1402016-10-08 04:44:18 +0000269 if (!Index.modulePaths().count(ModuleID))
270 // The module does not have an entry, it can't have a hash at all
271 return;
272
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000273 // Compute the unique hash for this entry
274 // This is based on the current compiler version, the module itself, the
275 // export list, the hash for every single module in the import list, the
276 // list of ResolvedODR for the module, and the list of preserved symbols.
277
Mehdi Aminif82bda02016-10-08 04:44:23 +0000278 // Include the hash for the current module
279 auto ModHash = Index.getModuleHash(ModuleID);
280
281 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
282 // No hash entry, no caching!
283 return;
284
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000285 SHA1 Hasher;
286
Mehdi Aminic92b6122017-01-10 00:55:47 +0000287 // Include the parts of the LTO configuration that affect code generation.
288 auto AddString = [&](StringRef Str) {
289 Hasher.update(Str);
290 Hasher.update(ArrayRef<uint8_t>{0});
291 };
292 auto AddUnsigned = [&](unsigned I) {
293 uint8_t Data[4];
294 Data[0] = I;
295 Data[1] = I >> 8;
296 Data[2] = I >> 16;
297 Data[3] = I >> 24;
298 Hasher.update(ArrayRef<uint8_t>{Data, 4});
299 };
300
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000301 // Start with the compiler revision
302 Hasher.update(LLVM_VERSION_STRING);
Peter Collingbourne942fa562017-04-13 01:26:12 +0000303#ifdef LLVM_REVISION
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000304 Hasher.update(LLVM_REVISION);
305#endif
306
Mehdi Aminic92b6122017-01-10 00:55:47 +0000307 // Hash the optimization level and the target machine settings.
308 AddString(TMBuilder.MCpu);
309 // FIXME: Hash more of Options. For now all clients initialize Options from
310 // command-line flags (which is unsupported in production), but may set
311 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
312 // DataSections and DebuggerTuning via command line flags.
313 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
314 AddUnsigned(TMBuilder.Options.FunctionSections);
315 AddUnsigned(TMBuilder.Options.DataSections);
316 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
317 AddString(TMBuilder.MAttr);
318 if (TMBuilder.RelocModel)
319 AddUnsigned(*TMBuilder.RelocModel);
320 AddUnsigned(TMBuilder.CGOptLevel);
321 AddUnsigned(OptLevel);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000322 AddUnsigned(Freestanding);
Mehdi Aminic92b6122017-01-10 00:55:47 +0000323
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000324 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
325 for (auto F : ExportList)
326 // The export list can impact the internalization, be conservative here
327 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
328
329 // Include the hash for every module we import functions from
330 for (auto &Entry : ImportList) {
331 auto ModHash = Index.getModuleHash(Entry.first());
332 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
333 }
334
335 // Include the hash for the resolved ODR.
336 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000337 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000338 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000339 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000340 sizeof(GlobalValue::LinkageTypes)));
341 }
342
343 // Include the hash for the preserved symbols.
344 for (auto &Entry : PreservedSymbols) {
345 if (DefinedFunctions.count(Entry))
346 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000347 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000348 }
349
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000350 // This choice of file name allows the cache to be pruned (see pruneCache()
351 // in include/llvm/Support/CachePruning.h).
352 sys::path::append(EntryPath, CachePath,
353 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000354 }
355
Mehdi Amini059464f2016-04-24 03:18:01 +0000356 // Access the path to this entry in the cache.
357 StringRef getEntryPath() { return EntryPath; }
358
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000359 // Try loading the buffer for this cache entry.
360 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
361 if (EntryPath.empty())
362 return std::error_code();
363 return MemoryBuffer::getFile(EntryPath);
364 }
365
366 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000367 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000368 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000369 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000370
371 // Write to a temporary to avoid race condition
372 SmallString<128> TempFilename;
373 int TempFD;
374 std::error_code EC =
375 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
376 if (EC) {
377 errs() << "Error: " << EC.message() << "\n";
378 report_fatal_error("ThinLTO: Can't get a temporary file");
379 }
380 {
381 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000382 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000383 }
384 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000385 EC = sys::fs::rename(TempFilename, EntryPath);
386 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000387 sys::fs::remove(TempFilename);
388 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
389 if (EC)
390 report_fatal_error(Twine("Failed to open ") + EntryPath +
391 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000392 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000393 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000394 }
395};
396
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000397static std::unique_ptr<MemoryBuffer>
398ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
399 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
400 const FunctionImporter::ImportMapTy &ImportList,
401 const FunctionImporter::ExportSetTy &ExportList,
402 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
403 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000404 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000405 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000406 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000407
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000408 // "Benchmark"-like optimization: single-source case
409 bool SingleModule = (ModuleMap.size() == 1);
410
411 if (!SingleModule) {
412 promoteModule(TheModule, Index);
413
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000414 // Apply summary-based LinkOnce/Weak resolution decisions.
415 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000416
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000417 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000418 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000419 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000420
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000421 // Be friendly and don't nuke totally the module when the client didn't
422 // supply anything to preserve.
423 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
424 // Apply summary-based internalization decisions.
425 thinLTOInternalizeModule(TheModule, DefinedGlobals);
426 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000427
428 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000429 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000430
431 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000432 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000433
434 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000435 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000436 }
437
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000438 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000439
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000440 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000441
Mehdi Amini43b657b2016-04-01 06:47:02 +0000442 if (DisableCodeGen) {
443 // Configured to stop before CodeGen, serialize the bitcode and return.
444 SmallVector<char, 128> OutputBuffer;
445 {
446 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000447 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000448 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000449 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000450 }
451 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
452 }
453
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000454 return codegenModule(TheModule, TM);
455}
456
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000457/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
458/// for caching, and in the \p Index for application during the ThinLTO
459/// backends. This is needed for correctness for exported symbols (ensure
460/// at least one copy kept) and a compile-time optimization (to drop duplicate
461/// copies when possible).
462static void resolveWeakForLinkerInIndex(
463 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000464 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
465 &ResolvedODR) {
466
467 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
468 computePrevailingCopies(Index, PrevailingCopy);
469
470 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
471 const auto &Prevailing = PrevailingCopy.find(GUID);
472 // Not in map means that there was only one copy, which must be prevailing.
473 if (Prevailing == PrevailingCopy.end())
474 return true;
475 return Prevailing->second == S;
476 };
477
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000478 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
479 GlobalValue::GUID GUID,
480 GlobalValue::LinkageTypes NewLinkage) {
481 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
482 };
483
Peter Collingbourne73589f32016-07-07 18:31:51 +0000484 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000485}
486
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000487// Initialize the TargetMachine builder for a given Triple
488static void initTMBuilder(TargetMachineBuilder &TMBuilder,
489 const Triple &TheTriple) {
490 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
491 // FIXME this looks pretty terrible...
492 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
493 if (TheTriple.getArch() == llvm::Triple::x86_64)
494 TMBuilder.MCpu = "core2";
495 else if (TheTriple.getArch() == llvm::Triple::x86)
496 TMBuilder.MCpu = "yonah";
497 else if (TheTriple.getArch() == llvm::Triple::aarch64)
498 TMBuilder.MCpu = "cyclone";
499 }
500 TMBuilder.TheTriple = std::move(TheTriple);
501}
502
503} // end anonymous namespace
504
505void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000506 ThinLTOBuffer Buffer(Data, Identifier);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000507 if (Modules.empty()) {
508 // First module added, so initialize the triple and some options
509 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000510 StringRef TripleStr;
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000511 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
512 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
Peter Collingbournecd513a42016-11-11 19:50:24 +0000513 if (TripleOrErr)
514 TripleStr = *TripleOrErr;
515 Triple TheTriple(TripleStr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000516 initTMBuilder(TMBuilder, Triple(TheTriple));
517 }
518#ifndef NDEBUG
519 else {
520 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000521 StringRef TripleStr;
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000522 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
523 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
Peter Collingbournecd513a42016-11-11 19:50:24 +0000524 if (TripleOrErr)
525 TripleStr = *TripleOrErr;
526 assert(TMBuilder.TheTriple.str() == TripleStr &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000527 "ThinLTO modules with different triple not supported");
528 }
529#endif
530 Modules.push_back(Buffer);
531}
532
533void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
534 PreservedSymbols.insert(Name);
535}
536
537void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000538 // FIXME: At the moment, we don't take advantage of this extra information,
539 // we're conservatively considering cross-references as preserved.
540 // CrossReferencedSymbols.insert(Name);
541 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000542}
543
544// TargetMachine factory
545std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
546 std::string ErrMsg;
547 const Target *TheTarget =
548 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
549 if (!TheTarget) {
550 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
551 }
552
553 // Use MAttr as the default set of features.
554 SubtargetFeatures Features(MAttr);
555 Features.getDefaultSubtargetFeatures(TheTriple);
556 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000557
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000558 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
559 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
560 CodeModel::Default, CGOptLevel));
561}
562
563/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000564 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000565 * "thin-link".
566 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000567std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
568 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000569 uint64_t NextModuleId = 0;
570 for (auto &ModuleBuffer : Modules) {
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000571 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
572 getModuleSummaryIndex(ModuleBuffer.getMemBuffer());
573 if (!IndexOrErr) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000574 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000575 logAllUnhandledErrors(
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000576 IndexOrErr.takeError(), errs(),
577 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000578 return nullptr;
579 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000580 if (CombinedIndex) {
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000581 CombinedIndex->mergeFrom(std::move(*IndexOrErr), ++NextModuleId);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000582 } else {
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000583 CombinedIndex = std::move(*IndexOrErr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000584 }
585 }
586 return CombinedIndex;
587}
588
589/**
590 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000591 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000592 */
593void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000594 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000595 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000596 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000597
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000598 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000599 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000600 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000601
Teresa Johnson6c475a72017-01-05 21:34:18 +0000602 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000603 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000604 PreservedSymbols, Triple(TheModule.getTargetTriple()));
605
606 // Compute "dead" symbols, we don't want to import/export these!
607 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
608
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000609 // Generate import/export list
610 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
611 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
612 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000613 ExportLists, &DeadSymbols);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000614
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000615 // Resolve LinkOnce/Weak symbols.
616 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000617 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000618
619 thinLTOResolveWeakForLinkerModule(
620 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000621
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000622 // Promote the exported values in the index, so that they are promoted
623 // in the module.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000624 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000625 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000626 return (ExportList != ExportLists.end() &&
627 ExportList->second.count(GUID)) ||
628 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000629 };
630 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
631
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000632 promoteModule(TheModule, Index);
633}
634
635/**
636 * Perform cross-module importing for the module identified by ModuleIdentifier.
637 */
638void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000639 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000640 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000641 auto ModuleCount = Index.modulePaths().size();
642
643 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000644 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000645 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000646
Teresa Johnson6c475a72017-01-05 21:34:18 +0000647 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000648 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000649 PreservedSymbols, Triple(TheModule.getTargetTriple()));
650
651 // Compute "dead" symbols, we don't want to import/export these!
652 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
653
Mehdi Amini01e32132016-03-26 05:40:34 +0000654 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000655 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
656 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000657 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000658 ExportLists, &DeadSymbols);
Mehdi Amini01e32132016-03-26 05:40:34 +0000659 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
660
661 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000662}
663
664/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000665 * Compute the list of summaries needed for importing into module.
666 */
667void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
668 StringRef ModulePath, ModuleSummaryIndex &Index,
669 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
670 auto ModuleCount = Index.modulePaths().size();
671
672 // Collect for each module the list of function it defines (GUID -> Summary).
673 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
674 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
675
676 // Generate import/export list
677 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
678 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
679 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
680 ExportLists);
681
682 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000683 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000684 ModuleToSummariesForIndex);
685}
686
687/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000688 * Emit the list of files needed for importing into module.
689 */
690void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
691 StringRef OutputName,
692 ModuleSummaryIndex &Index) {
693 auto ModuleCount = Index.modulePaths().size();
694
695 // Collect for each module the list of function it defines (GUID -> Summary).
696 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
697 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
698
699 // Generate import/export list
700 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
701 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
702 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
703 ExportLists);
704
705 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000706 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000707 report_fatal_error(Twine("Failed to open ") + OutputName +
708 " to save imports lists\n");
709}
710
711/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000712 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000713 */
714void ThinLTOCodeGenerator::internalize(Module &TheModule,
715 ModuleSummaryIndex &Index) {
716 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
717 auto ModuleCount = Index.modulePaths().size();
718 auto ModuleIdentifier = TheModule.getModuleIdentifier();
719
720 // Convert the preserved symbols set from string to GUID
721 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000722 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000723
724 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000725 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000726 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
727
Teresa Johnson6c475a72017-01-05 21:34:18 +0000728 // Compute "dead" symbols, we don't want to import/export these!
729 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
730
Mehdi Amini059464f2016-04-24 03:18:01 +0000731 // Generate import/export list
732 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
733 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
734 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000735 ExportLists, &DeadSymbols);
Mehdi Amini059464f2016-04-24 03:18:01 +0000736 auto &ExportList = ExportLists[ModuleIdentifier];
737
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000738 // Be friendly and don't nuke totally the module when the client didn't
739 // supply anything to preserve.
740 if (ExportList.empty() && GUIDPreservedSymbols.empty())
741 return;
742
Mehdi Amini059464f2016-04-24 03:18:01 +0000743 // Internalization
Mehdi Amini1380edf2017-02-03 07:41:43 +0000744 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000745 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000746 return (ExportList != ExportLists.end() &&
747 ExportList->second.count(GUID)) ||
748 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000749 };
750 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
751 thinLTOInternalizeModule(TheModule,
752 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000753}
754
755/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000756 * Perform post-importing ThinLTO optimizations.
757 */
758void ThinLTOCodeGenerator::optimize(Module &TheModule) {
759 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000760
761 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000762 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000763}
764
765/**
766 * Perform ThinLTO CodeGen.
767 */
768std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
769 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
770 return codegenModule(TheModule, *TMBuilder.create());
771}
772
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000773/// Write out the generated object file, either from CacheEntryPath or from
774/// OutputBuffer, preferring hard-link when possible.
775/// Returns the path to the generated file in SavedObjectsDirectoryPath.
776static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
777 StringRef SavedObjectsDirectoryPath,
778 const MemoryBuffer &OutputBuffer) {
779 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
780 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
781 OutputPath.c_str(); // Ensure the string is null terminated.
782 if (sys::fs::exists(OutputPath))
783 sys::fs::remove(OutputPath);
784
785 // We don't return a memory buffer to the linker, just a list of files.
786 if (!CacheEntryPath.empty()) {
787 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
788 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
789 if (!Err)
790 return OutputPath.str();
791 // Hard linking failed, try to copy.
792 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
793 if (!Err)
794 return OutputPath.str();
795 // Copy failed (could be because the CacheEntry was removed from the cache
796 // in the meantime by another process), fall back and try to write down the
797 // buffer to the output.
798 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
799 << "' to '" << OutputPath << "'\n";
800 }
801 // No cache entry, just write out the buffer.
802 std::error_code Err;
803 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
804 if (Err)
805 report_fatal_error("Can't open output '" + OutputPath + "'\n");
806 OS << OutputBuffer.getBuffer();
807 return OutputPath.str();
808}
809
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000810// Main entry point for the ThinLTO processing
811void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000812 // Prepare the resulting object vector
813 assert(ProducedBinaries.empty() && "The generator should not be reused");
814 if (SavedObjectsDirectoryPath.empty())
815 ProducedBinaries.resize(Modules.size());
816 else {
817 sys::fs::create_directories(SavedObjectsDirectoryPath);
818 bool IsDir;
819 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
820 if (!IsDir)
821 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
822 ProducedBinaryFiles.resize(Modules.size());
823 }
824
Mehdi Amini43b657b2016-04-01 06:47:02 +0000825 if (CodeGenOnly) {
826 // Perform only parallel codegen and return.
827 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000828 int count = 0;
829 for (auto &ModuleBuffer : Modules) {
830 Pool.async([&](int count) {
831 LLVMContext Context;
832 Context.setDiscardValueNames(LTODiscardValueNames);
833
834 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000835 auto TheModule =
836 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
837 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000838
839 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000840 auto OutputBuffer = codegen(*TheModule);
841 if (SavedObjectsDirectoryPath.empty())
842 ProducedBinaries[count] = std::move(OutputBuffer);
843 else
844 ProducedBinaryFiles[count] = writeGeneratedObject(
845 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000846 }, count++);
847 }
848
849 return;
850 }
851
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000852 // Sequential linking phase
853 auto Index = linkCombinedIndex();
854
855 // Save temps: index.
856 if (!SaveTempsDir.empty()) {
857 auto SaveTempPath = SaveTempsDir + "index.bc";
858 std::error_code EC;
859 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
860 if (EC)
861 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
862 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000863 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000864 }
865
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000866
867 // Prepare the module map.
868 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000869 auto ModuleCount = Modules.size();
870
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000871 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000872 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000873 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
874
Teresa Johnson6c475a72017-01-05 21:34:18 +0000875 // Convert the preserved symbols set from string to GUID, this is needed for
876 // computing the caching hash and the internalization.
877 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000878 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000879
880 // Compute "dead" symbols, we don't want to import/export these!
881 auto DeadSymbols = computeDeadSymbols(*Index, GUIDPreservedSymbols);
882
Mehdi Amini01e32132016-03-26 05:40:34 +0000883 // Collect the import/export lists for all modules from the call-graph in the
884 // combined index.
885 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
886 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000887 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000888 ExportLists, &DeadSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000889
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000890 // We use a std::map here to be able to have a defined ordering when
891 // producing a hash for the cache entry.
892 // FIXME: we should be able to compute the caching hash for the entry based
893 // on the index, and nuke this map.
894 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
895
896 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
897 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000898 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000899
Mehdi Amini1380edf2017-02-03 07:41:43 +0000900 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000901 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000902 return (ExportList != ExportLists.end() &&
903 ExportList->second.count(GUID)) ||
904 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000905 };
906
907 // Use global summary-based analysis to identify symbols that can be
908 // internalized (because they aren't exported or preserved as per callback).
909 // Changes are made in the index, consumed in the ThinLTO backends.
910 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
911
Teresa Johnson141149f2016-05-24 18:44:01 +0000912 // Make sure that every module has an entry in the ExportLists and
913 // ResolvedODR maps to enable threaded access to these maps below.
914 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000915 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000916 ResolvedODR[DefinedGVSummaries.first()];
917 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000918
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000919 // Compute the ordering we will process the inputs: the rough heuristic here
920 // is to sort them per size so that the largest module get schedule as soon as
921 // possible. This is purely a compile-time optimization.
922 std::vector<int> ModulesOrdering;
923 ModulesOrdering.resize(Modules.size());
924 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
925 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
926 [&](int LeftIndex, int RightIndex) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000927 auto LSize = Modules[LeftIndex].getBuffer().size();
928 auto RSize = Modules[RightIndex].getBuffer().size();
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000929 return LSize > RSize;
930 });
931
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000932 // Parallel optimizer + codegen
933 {
934 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000935 for (auto IndexCount : ModulesOrdering) {
936 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000937 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000938 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000939 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000940
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000941 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
942
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000943 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000944 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
945 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000946 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000947 DefinedFunctions, GUIDPreservedSymbols,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000948 OptLevel, Freestanding, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000949 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000950
951 {
952 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000953 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000954 << CacheEntryPath << "' for buffer " << count << " "
955 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000956
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000957 if (ErrOrBuffer) {
958 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000959 if (SavedObjectsDirectoryPath.empty())
960 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
961 else
962 ProducedBinaryFiles[count] = writeGeneratedObject(
963 count, CacheEntryPath, SavedObjectsDirectoryPath,
964 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000965 return;
966 }
967 }
968
969 LLVMContext Context;
970 Context.setDiscardValueNames(LTODiscardValueNames);
971 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000972 auto DiagFileOrErr = lto::setupOptimizationRemarks(
973 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000974 if (!DiagFileOrErr) {
975 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
976 report_fatal_error("ThinLTO: Can't get an output file for the "
977 "remarks");
978 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000979
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000980 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000981 auto TheModule =
982 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
983 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000984
985 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000986 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000987
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000988 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000989 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000990 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000991 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000992 ExportList, GUIDPreservedSymbols,
993 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000994 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000995
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000996 // Commit to the cache (if enabled)
997 CacheEntry.write(*OutputBuffer);
998
999 if (SavedObjectsDirectoryPath.empty()) {
1000 // We need to generated a memory buffer for the linker.
1001 if (!CacheEntryPath.empty()) {
1002 // Cache is enabled, reload from the cache
1003 // We do this to lower memory pressuree: the buffer is on the heap
1004 // and releasing it frees memory that can be used for the next input
1005 // file. The final binary link will read from the VFS cache
1006 // (hopefully!) or from disk if the memory pressure wasn't too high.
1007 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1008 if (auto EC = ReloadedBufferOrErr.getError()) {
1009 // On error, keeping the preexisting buffer and printing a
1010 // diagnostic is more friendly than just crashing.
1011 errs() << "error: can't reload cached file '" << CacheEntryPath
1012 << "': " << EC.message() << "\n";
1013 } else {
1014 OutputBuffer = std::move(*ReloadedBufferOrErr);
1015 }
1016 }
1017 ProducedBinaries[count] = std::move(OutputBuffer);
1018 return;
1019 }
1020 ProducedBinaryFiles[count] = writeGeneratedObject(
1021 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001022 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001023 }
1024 }
1025
Peter Collingbournecead56f2017-03-15 22:54:18 +00001026 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001027
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001028 // If statistics were requested, print them out now.
1029 if (llvm::AreStatisticsEnabled())
1030 llvm::PrintStatistics();
1031}