blob: ab01957f583e2d43d1af06e8db09a67913ce05b1 [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"
Adrian Prantl981a7992017-05-20 00:00:08 +000026#include "llvm/IR/DebugInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +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"
Adrian Prantl981a7992017-05-20 00:00:08 +000031#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000032#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000033#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000034#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"
Weiming Zhao79f2d092018-04-16 03:44:03 +000041#include "llvm/Support/SmallVectorMemoryBuffer.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000042#include "llvm/Support/TargetRegistry.h"
43#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000044#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000045#include "llvm/Support/ToolOutputFile.h"
Peter Collingbourne942fa562017-04-13 01:26:12 +000046#include "llvm/Support/VCSRevision.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000047#include "llvm/Target/TargetMachine.h"
48#include "llvm/Transforms/IPO.h"
49#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000050#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000051#include "llvm/Transforms/IPO/PassManagerBuilder.h"
52#include "llvm/Transforms/ObjCARC.h"
53#include "llvm/Transforms/Utils/FunctionImportUtils.h"
54
Mehdi Amini819e9cd2016-05-16 19:33:07 +000055#include <numeric>
56
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000057using namespace llvm;
58
Mehdi Amini1aafabf2016-04-16 07:02:16 +000059#define DEBUG_TYPE "thinlto"
60
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000061namespace llvm {
62// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
63extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000064extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000065extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000066}
67
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000068namespace {
69
Teresa Johnsonec544c52016-10-19 17:35:01 +000070static cl::opt<int>
71 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000072
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000073// Simple helper to save temporary files for debug.
74static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
75 unsigned count, StringRef Suffix) {
76 if (TempDir.empty())
77 return;
78 // User asked to save temps, let dump the bitcode file after import.
Benjamin Kramer3a13ed62017-12-28 16:58:54 +000079 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000080 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000081 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000082 if (EC)
83 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
84 " to save optimized bitcode\n");
Rafael Espindola6a86e252018-02-14 19:11:32 +000085 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000086}
87
Teresa Johnson4d2613f2016-05-24 17:24:25 +000088static const GlobalValueSummary *
89getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
90 // If there is any strong definition anywhere, get it.
91 auto StrongDefForLinker = llvm::find_if(
92 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
93 auto Linkage = Summary->linkage();
94 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
95 !GlobalValue::isWeakForLinker(Linkage);
96 });
97 if (StrongDefForLinker != GVSummaryList.end())
98 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +000099 // Get the first *linker visible* definition for this global in the summary
100 // list.
101 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000102 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
103 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000104 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
105 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000106 // Extern templates can be emitted as available_externally.
107 if (FirstDefForLinker == GVSummaryList.end())
108 return nullptr;
109 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000110}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000111
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000112// Populate map of GUID to the prevailing copy for any multiply defined
113// symbols. Currently assume first copy is prevailing, or any strong
114// definition. Can be refined with Linker information in the future.
115static void computePrevailingCopies(
116 const ModuleSummaryIndex &Index,
117 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000118 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
119 return GVSummaryList.size() > 1;
120 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000121
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000122 for (auto &I : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000123 if (HasMultipleCopies(I.second.SummaryList))
124 PrevailingCopy[I.first] =
125 getFirstDefinitionForLinker(I.second.SummaryList);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000126 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000127}
128
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000129static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000130generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000131 StringMap<MemoryBufferRef> ModuleMap;
132 for (auto &ModuleBuffer : Modules) {
133 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
134 ModuleMap.end() &&
135 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000136 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000137 }
138 return ModuleMap;
139}
140
Teresa Johnson26ab5772016-03-15 00:04:37 +0000141static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000142 if (renameModuleForThinLTO(TheModule, Index))
143 report_fatal_error("renameModuleForThinLTO failed");
144}
145
Adrian Prantl981a7992017-05-20 00:00:08 +0000146namespace {
147class ThinLTODiagnosticInfo : public DiagnosticInfo {
148 const Twine &Msg;
149public:
150 ThinLTODiagnosticInfo(const Twine &DiagMsg,
151 DiagnosticSeverity Severity = DS_Error)
152 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
153 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
154};
155}
156
157/// Verify the module and strip broken debug info.
158static void verifyLoadedModule(Module &TheModule) {
159 bool BrokenDebugInfo = false;
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000160 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
Adrian Prantl981a7992017-05-20 00:00:08 +0000161 report_fatal_error("Broken module found, compilation aborted!");
162 if (BrokenDebugInfo) {
163 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
164 "Invalid debug info found, debug info will be stripped", DS_Warning));
165 StripDebugInfo(TheModule);
166 }
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 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000186 if (!Lazy)
187 verifyLoadedModule(*ModuleOrErr.get());
Peter Collingbournedac43b42016-12-01 05:52:32 +0000188 return std::move(ModuleOrErr.get());
189}
190
Mehdi Amini01e32132016-03-26 05:40:34 +0000191static void
192crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
193 StringMap<MemoryBufferRef> &ModuleMap,
194 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000195 auto Loader = [&](StringRef Identifier) {
196 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000197 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000198 };
199
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000200 FunctionImporter Importer(Index, Loader);
Adrian Prantl66043792017-05-19 23:32:21 +0000201 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000202 if (!Result) {
203 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
204 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
205 SourceMgr::DK_Error, EIB.message());
206 Err.print("ThinLTO", errs());
207 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000208 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000209 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000210 // Verify again after cross-importing.
211 verifyLoadedModule(TheModule);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000212}
213
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000214static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000215 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000216 // Populate the PassManager
217 PassManagerBuilder PMB;
218 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000219 if (Freestanding)
220 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000221 PMB.Inliner = createFunctionInliningPass();
222 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000223 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000224 PMB.LoopVectorize = true;
225 PMB.SLPVectorize = true;
Adrian Prantl981a7992017-05-20 00:00:08 +0000226 // Already did this in verifyLoadedModule().
227 PMB.VerifyInput = false;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000228 PMB.VerifyOutput = false;
229
230 legacy::PassManager PM;
231
232 // Add the TTI (required to inform the vectorizer about register size for
233 // instance)
234 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
235
236 // Add optimizations
237 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000238
239 PM.run(TheModule);
240}
241
Mehdi Amini059464f2016-04-24 03:18:01 +0000242// Convert the PreservedSymbols map from "Name" based to "GUID" based.
243static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000244computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
245 const Triple &TheTriple) {
246 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
247 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000248 StringRef Name = Entry.first();
249 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
250 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000251 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000252 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000253 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000254}
255
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000256std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
257 TargetMachine &TM) {
258 SmallVector<char, 128> OutputBuffer;
259
260 // CodeGen
261 {
262 raw_svector_ostream OS(OutputBuffer);
263 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000264
265 // If the bitcode files contain ARC code and were compiled with optimization,
266 // the ObjCARCContractPass must be run, so do it unconditionally here.
267 PM.add(createObjCARCContractPass());
268
269 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000270 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
271 /* DisableVerify */ true))
272 report_fatal_error("Failed to setup codegen");
273
274 // Run codegen now. resulting binary is in OutputBuffer.
275 PM.run(TheModule);
276 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000277 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000278}
279
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000280/// Manage caching for a single Module.
281class ModuleCacheEntry {
282 SmallString<128> EntryPath;
283
284public:
285 // Create a cache entry. This compute a unique hash for the Module considering
286 // the current list of export/import, and offer an interface to query to
287 // access the content in the cache.
288 ModuleCacheEntry(
289 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
290 const FunctionImporter::ImportMapTy &ImportList,
291 const FunctionImporter::ExportSetTy &ExportList,
292 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000293 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000294 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000295 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000296 if (CachePath.empty())
297 return;
298
Mehdi Amini00fa1402016-10-08 04:44:18 +0000299 if (!Index.modulePaths().count(ModuleID))
300 // The module does not have an entry, it can't have a hash at all
301 return;
302
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000303 // Compute the unique hash for this entry
304 // This is based on the current compiler version, the module itself, the
305 // export list, the hash for every single module in the import list, the
306 // list of ResolvedODR for the module, and the list of preserved symbols.
307
Mehdi Aminif82bda02016-10-08 04:44:23 +0000308 // Include the hash for the current module
309 auto ModHash = Index.getModuleHash(ModuleID);
310
311 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
312 // No hash entry, no caching!
313 return;
314
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000315 SHA1 Hasher;
316
Mehdi Aminic92b6122017-01-10 00:55:47 +0000317 // Include the parts of the LTO configuration that affect code generation.
318 auto AddString = [&](StringRef Str) {
319 Hasher.update(Str);
320 Hasher.update(ArrayRef<uint8_t>{0});
321 };
322 auto AddUnsigned = [&](unsigned I) {
323 uint8_t Data[4];
324 Data[0] = I;
325 Data[1] = I >> 8;
326 Data[2] = I >> 16;
327 Data[3] = I >> 24;
328 Hasher.update(ArrayRef<uint8_t>{Data, 4});
329 };
330
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000331 // Start with the compiler revision
332 Hasher.update(LLVM_VERSION_STRING);
Peter Collingbourne942fa562017-04-13 01:26:12 +0000333#ifdef LLVM_REVISION
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000334 Hasher.update(LLVM_REVISION);
335#endif
336
Mehdi Aminic92b6122017-01-10 00:55:47 +0000337 // Hash the optimization level and the target machine settings.
338 AddString(TMBuilder.MCpu);
339 // FIXME: Hash more of Options. For now all clients initialize Options from
340 // command-line flags (which is unsupported in production), but may set
341 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
342 // DataSections and DebuggerTuning via command line flags.
343 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
344 AddUnsigned(TMBuilder.Options.FunctionSections);
345 AddUnsigned(TMBuilder.Options.DataSections);
346 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
347 AddString(TMBuilder.MAttr);
348 if (TMBuilder.RelocModel)
349 AddUnsigned(*TMBuilder.RelocModel);
350 AddUnsigned(TMBuilder.CGOptLevel);
351 AddUnsigned(OptLevel);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000352 AddUnsigned(Freestanding);
Mehdi Aminic92b6122017-01-10 00:55:47 +0000353
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000354 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
355 for (auto F : ExportList)
356 // The export list can impact the internalization, be conservative here
357 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
358
359 // Include the hash for every module we import functions from
360 for (auto &Entry : ImportList) {
361 auto ModHash = Index.getModuleHash(Entry.first());
362 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
363 }
364
365 // Include the hash for the resolved ODR.
366 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000367 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000368 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000369 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000370 sizeof(GlobalValue::LinkageTypes)));
371 }
372
373 // Include the hash for the preserved symbols.
374 for (auto &Entry : PreservedSymbols) {
375 if (DefinedFunctions.count(Entry))
376 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000377 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000378 }
379
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000380 // This choice of file name allows the cache to be pruned (see pruneCache()
381 // in include/llvm/Support/CachePruning.h).
382 sys::path::append(EntryPath, CachePath,
383 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000384 }
385
Mehdi Amini059464f2016-04-24 03:18:01 +0000386 // Access the path to this entry in the cache.
387 StringRef getEntryPath() { return EntryPath; }
388
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000389 // Try loading the buffer for this cache entry.
390 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
391 if (EntryPath.empty())
392 return std::error_code();
393 return MemoryBuffer::getFile(EntryPath);
394 }
395
396 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000397 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000398 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000399 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000400
401 // Write to a temporary to avoid race condition
402 SmallString<128> TempFilename;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000403 SmallString<128> CachePath(EntryPath);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000404 int TempFD;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000405 llvm::sys::path::remove_filename(CachePath);
406 sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
407 std::error_code EC =
408 sys::fs::createUniqueFile(TempFilename, TempFD, TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000409 if (EC) {
410 errs() << "Error: " << EC.message() << "\n";
411 report_fatal_error("ThinLTO: Can't get a temporary file");
412 }
413 {
414 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000415 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000416 }
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000417 // Rename temp file to final destination; rename is atomic
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000418 EC = sys::fs::rename(TempFilename, EntryPath);
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000419 if (EC)
Mehdi Aminib02139d2016-05-14 05:16:35 +0000420 sys::fs::remove(TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000421 }
422};
423
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000424static std::unique_ptr<MemoryBuffer>
425ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
426 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
427 const FunctionImporter::ImportMapTy &ImportList,
428 const FunctionImporter::ExportSetTy &ExportList,
429 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
430 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000431 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000432 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000433 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000434
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000435 // "Benchmark"-like optimization: single-source case
436 bool SingleModule = (ModuleMap.size() == 1);
437
438 if (!SingleModule) {
439 promoteModule(TheModule, Index);
440
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000441 // Apply summary-based LinkOnce/Weak resolution decisions.
442 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000443
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000444 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000445 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000446 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000447
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000448 // Be friendly and don't nuke totally the module when the client didn't
449 // supply anything to preserve.
450 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
451 // Apply summary-based internalization decisions.
452 thinLTOInternalizeModule(TheModule, DefinedGlobals);
453 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000454
455 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000456 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000457
458 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000459 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000460
461 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000462 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000463 }
464
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000465 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000466
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000467 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000468
Mehdi Amini43b657b2016-04-01 06:47:02 +0000469 if (DisableCodeGen) {
470 // Configured to stop before CodeGen, serialize the bitcode and return.
471 SmallVector<char, 128> OutputBuffer;
472 {
473 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000474 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000475 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000476 WriteBitcodeToFile(TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000477 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000478 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini43b657b2016-04-01 06:47:02 +0000479 }
480
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000481 return codegenModule(TheModule, TM);
482}
483
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000484/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
485/// for caching, and in the \p Index for application during the ThinLTO
486/// backends. This is needed for correctness for exported symbols (ensure
487/// at least one copy kept) and a compile-time optimization (to drop duplicate
488/// copies when possible).
489static void resolveWeakForLinkerInIndex(
490 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000491 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
492 &ResolvedODR) {
493
494 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
495 computePrevailingCopies(Index, PrevailingCopy);
496
497 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
498 const auto &Prevailing = PrevailingCopy.find(GUID);
499 // Not in map means that there was only one copy, which must be prevailing.
500 if (Prevailing == PrevailingCopy.end())
501 return true;
502 return Prevailing->second == S;
503 };
504
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000505 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
506 GlobalValue::GUID GUID,
507 GlobalValue::LinkageTypes NewLinkage) {
508 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
509 };
510
Peter Collingbourne73589f32016-07-07 18:31:51 +0000511 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000512}
513
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000514// Initialize the TargetMachine builder for a given Triple
515static void initTMBuilder(TargetMachineBuilder &TMBuilder,
516 const Triple &TheTriple) {
517 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
518 // FIXME this looks pretty terrible...
519 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
520 if (TheTriple.getArch() == llvm::Triple::x86_64)
521 TMBuilder.MCpu = "core2";
522 else if (TheTriple.getArch() == llvm::Triple::x86)
523 TMBuilder.MCpu = "yonah";
524 else if (TheTriple.getArch() == llvm::Triple::aarch64)
525 TMBuilder.MCpu = "cyclone";
526 }
527 TMBuilder.TheTriple = std::move(TheTriple);
528}
529
530} // end anonymous namespace
531
532void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Johan Engelendcebe4f2017-09-17 18:11:26 +0000533 ThinLTOBuffer Buffer(Data, Identifier);
Akira Hatanakab10bff12017-05-18 03:52:29 +0000534 LLVMContext Context;
535 StringRef TripleStr;
536 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
537 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
538
539 if (TripleOrErr)
540 TripleStr = *TripleOrErr;
541
542 Triple TheTriple(TripleStr);
543
544 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000545 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000546 else if (TMBuilder.TheTriple != TheTriple) {
547 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
548 report_fatal_error("ThinLTO modules with incompatible triples not "
549 "supported");
550 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000551 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000552
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000553 Modules.push_back(Buffer);
554}
555
556void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
557 PreservedSymbols.insert(Name);
558}
559
560void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000561 // FIXME: At the moment, we don't take advantage of this extra information,
562 // we're conservatively considering cross-references as preserved.
563 // CrossReferencedSymbols.insert(Name);
564 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000565}
566
567// TargetMachine factory
568std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
569 std::string ErrMsg;
570 const Target *TheTarget =
571 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
572 if (!TheTarget) {
573 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
574 }
575
576 // Use MAttr as the default set of features.
577 SubtargetFeatures Features(MAttr);
578 Features.getDefaultSubtargetFeatures(TheTriple);
579 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000580
Rafael Espindola79e238a2017-08-03 02:16:21 +0000581 return std::unique_ptr<TargetMachine>(
582 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
583 RelocModel, None, CGOptLevel));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000584}
585
586/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000587 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000588 * "thin-link".
589 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000590std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000591 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
Eugene Leviant28d8a492018-01-22 13:35:40 +0000592 llvm::make_unique<ModuleSummaryIndex>(/*IsPeformingAnalysis=*/false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000593 uint64_t NextModuleId = 0;
594 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000595 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
596 *CombinedIndex, NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000597 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000598 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000599 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000600 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000601 return nullptr;
602 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000603 }
604 return CombinedIndex;
605}
606
George Rimar2421b6f2018-01-17 10:33:05 +0000607static void internalizeAndPromoteInIndex(
608 const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
609 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
610 ModuleSummaryIndex &Index) {
611 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
612 const auto &ExportList = ExportLists.find(ModuleIdentifier);
613 return (ExportList != ExportLists.end() &&
614 ExportList->second.count(GUID)) ||
615 GUIDPreservedSymbols.count(GUID);
616 };
617
618 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
619}
620
George Rimareaf51722018-01-29 08:03:30 +0000621static void computeDeadSymbolsInIndex(
622 ModuleSummaryIndex &Index,
623 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
624 // We have no symbols resolution available. And can't do any better now in the
625 // case where the prevailing symbol is in a native object. It can be refined
626 // with linker information in the future.
627 auto isPrevailing = [&](GlobalValue::GUID G) {
628 return PrevailingType::Unknown;
629 };
630 computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
631}
632
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000633/**
634 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000635 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000636 */
637void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000638 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000639 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000640 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000641
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000642 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000643 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000644 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000645
Teresa Johnson6c475a72017-01-05 21:34:18 +0000646 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000647 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000648 PreservedSymbols, Triple(TheModule.getTargetTriple()));
649
650 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000651 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000652
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000653 // Generate import/export list
654 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
655 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
656 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000657 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000658
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000659 // Resolve LinkOnce/Weak symbols.
660 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000661 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000662
663 thinLTOResolveWeakForLinkerModule(
664 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000665
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000666 // Promote the exported values in the index, so that they are promoted
667 // in the module.
George Rimar2421b6f2018-01-17 10:33:05 +0000668 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000669
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000670 promoteModule(TheModule, Index);
671}
672
673/**
674 * Perform cross-module importing for the module identified by ModuleIdentifier.
675 */
676void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000677 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000678 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000679 auto ModuleCount = Index.modulePaths().size();
680
681 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000682 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000683 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000684
Teresa Johnson6c475a72017-01-05 21:34:18 +0000685 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000686 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000687 PreservedSymbols, Triple(TheModule.getTargetTriple()));
688
689 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000690 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000691
Mehdi Amini01e32132016-03-26 05:40:34 +0000692 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000693 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
694 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000695 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000696 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000697 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
698
699 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000700}
701
702/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000703 * Compute the list of summaries needed for importing into module.
704 */
705void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
706 StringRef ModulePath, ModuleSummaryIndex &Index,
707 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
708 auto ModuleCount = Index.modulePaths().size();
709
710 // Collect for each module the list of function it defines (GUID -> Summary).
711 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
712 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
713
714 // Generate import/export list
715 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
716 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
717 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
718 ExportLists);
719
720 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000721 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000722 ModuleToSummariesForIndex);
723}
724
725/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000726 * Emit the list of files needed for importing into module.
727 */
728void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
729 StringRef OutputName,
730 ModuleSummaryIndex &Index) {
731 auto ModuleCount = Index.modulePaths().size();
732
733 // Collect for each module the list of function it defines (GUID -> Summary).
734 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
735 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
736
737 // Generate import/export list
738 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
739 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
740 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
741 ExportLists);
742
743 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000744 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000745 report_fatal_error(Twine("Failed to open ") + OutputName +
746 " to save imports lists\n");
747}
748
749/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000750 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000751 */
752void ThinLTOCodeGenerator::internalize(Module &TheModule,
753 ModuleSummaryIndex &Index) {
754 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
755 auto ModuleCount = Index.modulePaths().size();
756 auto ModuleIdentifier = TheModule.getModuleIdentifier();
757
758 // Convert the preserved symbols set from string to GUID
759 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000760 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000761
762 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000763 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000764 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
765
Teresa Johnson6c475a72017-01-05 21:34:18 +0000766 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000767 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000768
Mehdi Amini059464f2016-04-24 03:18:01 +0000769 // Generate import/export list
770 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
771 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
772 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000773 ExportLists);
Mehdi Amini059464f2016-04-24 03:18:01 +0000774 auto &ExportList = ExportLists[ModuleIdentifier];
775
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000776 // Be friendly and don't nuke totally the module when the client didn't
777 // supply anything to preserve.
778 if (ExportList.empty() && GUIDPreservedSymbols.empty())
779 return;
780
Mehdi Amini059464f2016-04-24 03:18:01 +0000781 // Internalization
George Rimar2421b6f2018-01-17 10:33:05 +0000782 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000783 thinLTOInternalizeModule(TheModule,
784 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000785}
786
787/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000788 * Perform post-importing ThinLTO optimizations.
789 */
790void ThinLTOCodeGenerator::optimize(Module &TheModule) {
791 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000792
793 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000794 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000795}
796
797/**
798 * Perform ThinLTO CodeGen.
799 */
800std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
801 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
802 return codegenModule(TheModule, *TMBuilder.create());
803}
804
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000805/// Write out the generated object file, either from CacheEntryPath or from
806/// OutputBuffer, preferring hard-link when possible.
807/// Returns the path to the generated file in SavedObjectsDirectoryPath.
808static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
809 StringRef SavedObjectsDirectoryPath,
810 const MemoryBuffer &OutputBuffer) {
811 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
812 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
813 OutputPath.c_str(); // Ensure the string is null terminated.
814 if (sys::fs::exists(OutputPath))
815 sys::fs::remove(OutputPath);
816
817 // We don't return a memory buffer to the linker, just a list of files.
818 if (!CacheEntryPath.empty()) {
819 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
820 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
821 if (!Err)
822 return OutputPath.str();
823 // Hard linking failed, try to copy.
824 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
825 if (!Err)
826 return OutputPath.str();
827 // Copy failed (could be because the CacheEntry was removed from the cache
828 // in the meantime by another process), fall back and try to write down the
829 // buffer to the output.
830 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
831 << "' to '" << OutputPath << "'\n";
832 }
833 // No cache entry, just write out the buffer.
834 std::error_code Err;
835 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
836 if (Err)
837 report_fatal_error("Can't open output '" + OutputPath + "'\n");
838 OS << OutputBuffer.getBuffer();
839 return OutputPath.str();
840}
841
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000842// Main entry point for the ThinLTO processing
843void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000844 // Prepare the resulting object vector
845 assert(ProducedBinaries.empty() && "The generator should not be reused");
846 if (SavedObjectsDirectoryPath.empty())
847 ProducedBinaries.resize(Modules.size());
848 else {
849 sys::fs::create_directories(SavedObjectsDirectoryPath);
850 bool IsDir;
851 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
852 if (!IsDir)
853 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
854 ProducedBinaryFiles.resize(Modules.size());
855 }
856
Mehdi Amini43b657b2016-04-01 06:47:02 +0000857 if (CodeGenOnly) {
858 // Perform only parallel codegen and return.
859 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000860 int count = 0;
861 for (auto &ModuleBuffer : Modules) {
862 Pool.async([&](int count) {
863 LLVMContext Context;
864 Context.setDiscardValueNames(LTODiscardValueNames);
865
866 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000867 auto TheModule =
868 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
869 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000870
871 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000872 auto OutputBuffer = codegen(*TheModule);
873 if (SavedObjectsDirectoryPath.empty())
874 ProducedBinaries[count] = std::move(OutputBuffer);
875 else
876 ProducedBinaryFiles[count] = writeGeneratedObject(
877 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000878 }, count++);
879 }
880
881 return;
882 }
883
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000884 // Sequential linking phase
885 auto Index = linkCombinedIndex();
886
887 // Save temps: index.
888 if (!SaveTempsDir.empty()) {
889 auto SaveTempPath = SaveTempsDir + "index.bc";
890 std::error_code EC;
891 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
892 if (EC)
893 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
894 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000895 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000896 }
897
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000898
899 // Prepare the module map.
900 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000901 auto ModuleCount = Modules.size();
902
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000903 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000904 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000905 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
906
Teresa Johnson6c475a72017-01-05 21:34:18 +0000907 // Convert the preserved symbols set from string to GUID, this is needed for
908 // computing the caching hash and the internalization.
909 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000910 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000911
912 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000913 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000914
Mehdi Amini01e32132016-03-26 05:40:34 +0000915 // Collect the import/export lists for all modules from the call-graph in the
916 // combined index.
917 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
918 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000919 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000920 ExportLists);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000921
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000922 // We use a std::map here to be able to have a defined ordering when
923 // producing a hash for the cache entry.
924 // FIXME: we should be able to compute the caching hash for the entry based
925 // on the index, and nuke this map.
926 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
927
928 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
929 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000930 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000931
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000932 // Use global summary-based analysis to identify symbols that can be
933 // internalized (because they aren't exported or preserved as per callback).
934 // Changes are made in the index, consumed in the ThinLTO backends.
George Rimar2421b6f2018-01-17 10:33:05 +0000935 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000936
Teresa Johnson141149f2016-05-24 18:44:01 +0000937 // Make sure that every module has an entry in the ExportLists and
938 // ResolvedODR maps to enable threaded access to these maps below.
939 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000940 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000941 ResolvedODR[DefinedGVSummaries.first()];
942 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000943
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000944 // Compute the ordering we will process the inputs: the rough heuristic here
945 // is to sort them per size so that the largest module get schedule as soon as
946 // possible. This is purely a compile-time optimization.
947 std::vector<int> ModulesOrdering;
948 ModulesOrdering.resize(Modules.size());
949 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
Mandeep Singh Grang5416af72018-04-13 19:12:20 +0000950 llvm::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
951 [&](int LeftIndex, int RightIndex) {
952 auto LSize = Modules[LeftIndex].getBuffer().size();
953 auto RSize = Modules[RightIndex].getBuffer().size();
954 return LSize > RSize;
955 });
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000956
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000957 // Parallel optimizer + codegen
958 {
959 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000960 for (auto IndexCount : ModulesOrdering) {
961 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000962 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000963 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000964 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000965
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000966 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
967
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000968 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000969 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
970 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000971 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000972 DefinedFunctions, GUIDPreservedSymbols,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000973 OptLevel, Freestanding, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000974 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000975
976 {
977 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000978 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000979 << CacheEntryPath << "' for buffer " << count << " "
980 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000981
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000982 if (ErrOrBuffer) {
983 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000984 if (SavedObjectsDirectoryPath.empty())
985 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
986 else
987 ProducedBinaryFiles[count] = writeGeneratedObject(
988 count, CacheEntryPath, SavedObjectsDirectoryPath,
989 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000990 return;
991 }
992 }
993
994 LLVMContext Context;
995 Context.setDiscardValueNames(LTODiscardValueNames);
996 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000997 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarmanfb2d3422018-03-08 01:13:10 +0000998 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000999 if (!DiagFileOrErr) {
1000 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1001 report_fatal_error("ThinLTO: Can't get an output file for the "
1002 "remarks");
1003 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001004
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001005 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +00001006 auto TheModule =
1007 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
1008 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001009
1010 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +00001011 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001012
Mehdi Amini1aafabf2016-04-16 07:02:16 +00001013 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +00001014 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001015 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001016 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001017 ExportList, GUIDPreservedSymbols,
1018 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +00001019 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001020
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001021 // Commit to the cache (if enabled)
1022 CacheEntry.write(*OutputBuffer);
1023
1024 if (SavedObjectsDirectoryPath.empty()) {
1025 // We need to generated a memory buffer for the linker.
1026 if (!CacheEntryPath.empty()) {
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001027 // When cache is enabled, reload from the cache if possible.
1028 // Releasing the buffer from the heap and reloading it from the
1029 // cache file with mmap helps us to lower memory pressure.
1030 // The freed memory can be used for the next input file.
1031 // The final binary link will read from the VFS cache (hopefully!)
1032 // or from disk (if the memory pressure was too high).
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001033 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1034 if (auto EC = ReloadedBufferOrErr.getError()) {
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001035 // On error, keep the preexisting buffer and print a diagnostic.
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001036 errs() << "error: can't reload cached file '" << CacheEntryPath
1037 << "': " << EC.message() << "\n";
1038 } else {
1039 OutputBuffer = std::move(*ReloadedBufferOrErr);
1040 }
1041 }
1042 ProducedBinaries[count] = std::move(OutputBuffer);
1043 return;
1044 }
1045 ProducedBinaryFiles[count] = writeGeneratedObject(
1046 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001047 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001048 }
1049 }
1050
Peter Collingbournecead56f2017-03-15 22:54:18 +00001051 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001052
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001053 // If statistics were requested, print them out now.
1054 if (llvm::AreStatisticsEnabled())
1055 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +00001056 reportAndResetTimings();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001057}