blob: 692396eac20129bf90525f676f2e251f7c771774 [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"
Adrian Prantl981a7992017-05-20 00:00:08 +000027#include "llvm/IR/DebugInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000028#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000029#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000030#include "llvm/IR/LegacyPassManager.h"
31#include "llvm/IR/Mangler.h"
Adrian Prantl981a7992017-05-20 00:00:08 +000032#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000034#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000035#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000036#include "llvm/Object/IRObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000037#include "llvm/Support/CachePruning.h"
38#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000039#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000040#include "llvm/Support/Path.h"
41#include "llvm/Support/SHA1.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");
Teresa Johnson3c35e092016-04-04 21:19:31 +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 }
277 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
278}
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;
403 int TempFD;
404 std::error_code EC =
405 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
406 if (EC) {
407 errs() << "Error: " << EC.message() << "\n";
408 report_fatal_error("ThinLTO: Can't get a temporary file");
409 }
410 {
411 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000412 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000413 }
414 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000415 EC = sys::fs::rename(TempFilename, EntryPath);
416 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000417 sys::fs::remove(TempFilename);
418 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
419 if (EC)
420 report_fatal_error(Twine("Failed to open ") + EntryPath +
421 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000422 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000423 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000424 }
425};
426
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000427static std::unique_ptr<MemoryBuffer>
428ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
429 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
430 const FunctionImporter::ImportMapTy &ImportList,
431 const FunctionImporter::ExportSetTy &ExportList,
432 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
433 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000434 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000435 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000436 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000437
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000438 // "Benchmark"-like optimization: single-source case
439 bool SingleModule = (ModuleMap.size() == 1);
440
441 if (!SingleModule) {
442 promoteModule(TheModule, Index);
443
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000444 // Apply summary-based LinkOnce/Weak resolution decisions.
445 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000446
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000447 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000448 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000449 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000450
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000451 // Be friendly and don't nuke totally the module when the client didn't
452 // supply anything to preserve.
453 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
454 // Apply summary-based internalization decisions.
455 thinLTOInternalizeModule(TheModule, DefinedGlobals);
456 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000457
458 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000459 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000460
461 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000462 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000463
464 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000465 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000466 }
467
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000468 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000469
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000470 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000471
Mehdi Amini43b657b2016-04-01 06:47:02 +0000472 if (DisableCodeGen) {
473 // Configured to stop before CodeGen, serialize the bitcode and return.
474 SmallVector<char, 128> OutputBuffer;
475 {
476 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000477 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000478 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000479 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000480 }
481 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
482 }
483
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000484 return codegenModule(TheModule, TM);
485}
486
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000487/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
488/// for caching, and in the \p Index for application during the ThinLTO
489/// backends. This is needed for correctness for exported symbols (ensure
490/// at least one copy kept) and a compile-time optimization (to drop duplicate
491/// copies when possible).
492static void resolveWeakForLinkerInIndex(
493 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000494 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
495 &ResolvedODR) {
496
497 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
498 computePrevailingCopies(Index, PrevailingCopy);
499
500 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
501 const auto &Prevailing = PrevailingCopy.find(GUID);
502 // Not in map means that there was only one copy, which must be prevailing.
503 if (Prevailing == PrevailingCopy.end())
504 return true;
505 return Prevailing->second == S;
506 };
507
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000508 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
509 GlobalValue::GUID GUID,
510 GlobalValue::LinkageTypes NewLinkage) {
511 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
512 };
513
Peter Collingbourne73589f32016-07-07 18:31:51 +0000514 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000515}
516
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000517// Initialize the TargetMachine builder for a given Triple
518static void initTMBuilder(TargetMachineBuilder &TMBuilder,
519 const Triple &TheTriple) {
520 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
521 // FIXME this looks pretty terrible...
522 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
523 if (TheTriple.getArch() == llvm::Triple::x86_64)
524 TMBuilder.MCpu = "core2";
525 else if (TheTriple.getArch() == llvm::Triple::x86)
526 TMBuilder.MCpu = "yonah";
527 else if (TheTriple.getArch() == llvm::Triple::aarch64)
528 TMBuilder.MCpu = "cyclone";
529 }
530 TMBuilder.TheTriple = std::move(TheTriple);
531}
532
533} // end anonymous namespace
534
535void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Johan Engelendcebe4f2017-09-17 18:11:26 +0000536 ThinLTOBuffer Buffer(Data, Identifier);
Akira Hatanakab10bff12017-05-18 03:52:29 +0000537 LLVMContext Context;
538 StringRef TripleStr;
539 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
540 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
541
542 if (TripleOrErr)
543 TripleStr = *TripleOrErr;
544
545 Triple TheTriple(TripleStr);
546
547 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000548 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000549 else if (TMBuilder.TheTriple != TheTriple) {
550 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
551 report_fatal_error("ThinLTO modules with incompatible triples not "
552 "supported");
553 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000554 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000555
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000556 Modules.push_back(Buffer);
557}
558
559void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
560 PreservedSymbols.insert(Name);
561}
562
563void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000564 // FIXME: At the moment, we don't take advantage of this extra information,
565 // we're conservatively considering cross-references as preserved.
566 // CrossReferencedSymbols.insert(Name);
567 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000568}
569
570// TargetMachine factory
571std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
572 std::string ErrMsg;
573 const Target *TheTarget =
574 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
575 if (!TheTarget) {
576 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
577 }
578
579 // Use MAttr as the default set of features.
580 SubtargetFeatures Features(MAttr);
581 Features.getDefaultSubtargetFeatures(TheTriple);
582 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000583
Rafael Espindola79e238a2017-08-03 02:16:21 +0000584 return std::unique_ptr<TargetMachine>(
585 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
586 RelocModel, None, CGOptLevel));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000587}
588
589/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000590 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000591 * "thin-link".
592 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000593std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000594 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
595 llvm::make_unique<ModuleSummaryIndex>();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000596 uint64_t NextModuleId = 0;
597 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000598 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
599 *CombinedIndex, NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000600 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000601 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000602 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000603 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000604 return nullptr;
605 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000606 }
607 return CombinedIndex;
608}
609
George Rimar2421b6f2018-01-17 10:33:05 +0000610static void internalizeAndPromoteInIndex(
611 const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
612 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
613 ModuleSummaryIndex &Index) {
614 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
615 const auto &ExportList = ExportLists.find(ModuleIdentifier);
616 return (ExportList != ExportLists.end() &&
617 ExportList->second.count(GUID)) ||
618 GUIDPreservedSymbols.count(GUID);
619 };
620
621 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
622}
623
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000624/**
625 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000626 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000627 */
628void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000629 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000630 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000631 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000632
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000633 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000634 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000635 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000636
Teresa Johnson6c475a72017-01-05 21:34:18 +0000637 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000638 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000639 PreservedSymbols, Triple(TheModule.getTargetTriple()));
640
641 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000642 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000643
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000644 // Generate import/export list
645 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
646 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
647 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000648 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000649
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000650 // Resolve LinkOnce/Weak symbols.
651 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000652 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000653
654 thinLTOResolveWeakForLinkerModule(
655 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000656
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000657 // Promote the exported values in the index, so that they are promoted
658 // in the module.
George Rimar2421b6f2018-01-17 10:33:05 +0000659 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000660
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000661 promoteModule(TheModule, Index);
662}
663
664/**
665 * Perform cross-module importing for the module identified by ModuleIdentifier.
666 */
667void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000668 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000669 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000670 auto ModuleCount = Index.modulePaths().size();
671
672 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000673 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000674 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000675
Teresa Johnson6c475a72017-01-05 21:34:18 +0000676 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000677 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000678 PreservedSymbols, Triple(TheModule.getTargetTriple()));
679
680 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000681 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000682
Mehdi Amini01e32132016-03-26 05:40:34 +0000683 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000684 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
685 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000686 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000687 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000688 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
689
690 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000691}
692
693/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000694 * Compute the list of summaries needed for importing into module.
695 */
696void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
697 StringRef ModulePath, ModuleSummaryIndex &Index,
698 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
699 auto ModuleCount = Index.modulePaths().size();
700
701 // Collect for each module the list of function it defines (GUID -> Summary).
702 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
703 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
704
705 // Generate import/export list
706 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
707 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
708 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
709 ExportLists);
710
711 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000712 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000713 ModuleToSummariesForIndex);
714}
715
716/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000717 * Emit the list of files needed for importing into module.
718 */
719void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
720 StringRef OutputName,
721 ModuleSummaryIndex &Index) {
722 auto ModuleCount = Index.modulePaths().size();
723
724 // Collect for each module the list of function it defines (GUID -> Summary).
725 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
726 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
727
728 // Generate import/export list
729 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
730 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
731 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
732 ExportLists);
733
734 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000735 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000736 report_fatal_error(Twine("Failed to open ") + OutputName +
737 " to save imports lists\n");
738}
739
740/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000741 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000742 */
743void ThinLTOCodeGenerator::internalize(Module &TheModule,
744 ModuleSummaryIndex &Index) {
745 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
746 auto ModuleCount = Index.modulePaths().size();
747 auto ModuleIdentifier = TheModule.getModuleIdentifier();
748
749 // Convert the preserved symbols set from string to GUID
750 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000751 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000752
753 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000754 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000755 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
756
Teresa Johnson6c475a72017-01-05 21:34:18 +0000757 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000758 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000759
Mehdi Amini059464f2016-04-24 03:18:01 +0000760 // Generate import/export list
761 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
762 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
763 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000764 ExportLists);
Mehdi Amini059464f2016-04-24 03:18:01 +0000765 auto &ExportList = ExportLists[ModuleIdentifier];
766
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000767 // Be friendly and don't nuke totally the module when the client didn't
768 // supply anything to preserve.
769 if (ExportList.empty() && GUIDPreservedSymbols.empty())
770 return;
771
Mehdi Amini059464f2016-04-24 03:18:01 +0000772 // Internalization
George Rimar2421b6f2018-01-17 10:33:05 +0000773 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000774 thinLTOInternalizeModule(TheModule,
775 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000776}
777
778/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000779 * Perform post-importing ThinLTO optimizations.
780 */
781void ThinLTOCodeGenerator::optimize(Module &TheModule) {
782 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000783
784 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000785 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000786}
787
788/**
789 * Perform ThinLTO CodeGen.
790 */
791std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
792 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
793 return codegenModule(TheModule, *TMBuilder.create());
794}
795
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000796/// Write out the generated object file, either from CacheEntryPath or from
797/// OutputBuffer, preferring hard-link when possible.
798/// Returns the path to the generated file in SavedObjectsDirectoryPath.
799static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
800 StringRef SavedObjectsDirectoryPath,
801 const MemoryBuffer &OutputBuffer) {
802 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
803 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
804 OutputPath.c_str(); // Ensure the string is null terminated.
805 if (sys::fs::exists(OutputPath))
806 sys::fs::remove(OutputPath);
807
808 // We don't return a memory buffer to the linker, just a list of files.
809 if (!CacheEntryPath.empty()) {
810 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
811 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
812 if (!Err)
813 return OutputPath.str();
814 // Hard linking failed, try to copy.
815 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
816 if (!Err)
817 return OutputPath.str();
818 // Copy failed (could be because the CacheEntry was removed from the cache
819 // in the meantime by another process), fall back and try to write down the
820 // buffer to the output.
821 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
822 << "' to '" << OutputPath << "'\n";
823 }
824 // No cache entry, just write out the buffer.
825 std::error_code Err;
826 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
827 if (Err)
828 report_fatal_error("Can't open output '" + OutputPath + "'\n");
829 OS << OutputBuffer.getBuffer();
830 return OutputPath.str();
831}
832
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000833// Main entry point for the ThinLTO processing
834void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000835 // Prepare the resulting object vector
836 assert(ProducedBinaries.empty() && "The generator should not be reused");
837 if (SavedObjectsDirectoryPath.empty())
838 ProducedBinaries.resize(Modules.size());
839 else {
840 sys::fs::create_directories(SavedObjectsDirectoryPath);
841 bool IsDir;
842 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
843 if (!IsDir)
844 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
845 ProducedBinaryFiles.resize(Modules.size());
846 }
847
Mehdi Amini43b657b2016-04-01 06:47:02 +0000848 if (CodeGenOnly) {
849 // Perform only parallel codegen and return.
850 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000851 int count = 0;
852 for (auto &ModuleBuffer : Modules) {
853 Pool.async([&](int count) {
854 LLVMContext Context;
855 Context.setDiscardValueNames(LTODiscardValueNames);
856
857 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000858 auto TheModule =
859 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
860 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000861
862 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000863 auto OutputBuffer = codegen(*TheModule);
864 if (SavedObjectsDirectoryPath.empty())
865 ProducedBinaries[count] = std::move(OutputBuffer);
866 else
867 ProducedBinaryFiles[count] = writeGeneratedObject(
868 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000869 }, count++);
870 }
871
872 return;
873 }
874
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000875 // Sequential linking phase
876 auto Index = linkCombinedIndex();
877
878 // Save temps: index.
879 if (!SaveTempsDir.empty()) {
880 auto SaveTempPath = SaveTempsDir + "index.bc";
881 std::error_code EC;
882 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
883 if (EC)
884 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
885 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000886 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000887 }
888
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000889
890 // Prepare the module map.
891 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000892 auto ModuleCount = Modules.size();
893
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000894 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000895 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000896 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
897
Teresa Johnson6c475a72017-01-05 21:34:18 +0000898 // Convert the preserved symbols set from string to GUID, this is needed for
899 // computing the caching hash and the internalization.
900 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000901 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000902
903 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000904 computeDeadSymbols(*Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000905
Mehdi Amini01e32132016-03-26 05:40:34 +0000906 // Collect the import/export lists for all modules from the call-graph in the
907 // combined index.
908 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
909 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000910 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000911 ExportLists);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000912
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000913 // We use a std::map here to be able to have a defined ordering when
914 // producing a hash for the cache entry.
915 // FIXME: we should be able to compute the caching hash for the entry based
916 // on the index, and nuke this map.
917 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
918
919 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
920 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000921 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000922
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000923 // Use global summary-based analysis to identify symbols that can be
924 // internalized (because they aren't exported or preserved as per callback).
925 // Changes are made in the index, consumed in the ThinLTO backends.
George Rimar2421b6f2018-01-17 10:33:05 +0000926 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000927
Teresa Johnson141149f2016-05-24 18:44:01 +0000928 // Make sure that every module has an entry in the ExportLists and
929 // ResolvedODR maps to enable threaded access to these maps below.
930 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000931 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000932 ResolvedODR[DefinedGVSummaries.first()];
933 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000934
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000935 // Compute the ordering we will process the inputs: the rough heuristic here
936 // is to sort them per size so that the largest module get schedule as soon as
937 // possible. This is purely a compile-time optimization.
938 std::vector<int> ModulesOrdering;
939 ModulesOrdering.resize(Modules.size());
940 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
941 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
942 [&](int LeftIndex, int RightIndex) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000943 auto LSize = Modules[LeftIndex].getBuffer().size();
944 auto RSize = Modules[RightIndex].getBuffer().size();
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000945 return LSize > RSize;
946 });
947
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000948 // Parallel optimizer + codegen
949 {
950 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000951 for (auto IndexCount : ModulesOrdering) {
952 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000953 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000954 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000955 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000956
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000957 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
958
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000959 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000960 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
961 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000962 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000963 DefinedFunctions, GUIDPreservedSymbols,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000964 OptLevel, Freestanding, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000965 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000966
967 {
968 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000969 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000970 << CacheEntryPath << "' for buffer " << count << " "
971 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000972
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000973 if (ErrOrBuffer) {
974 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000975 if (SavedObjectsDirectoryPath.empty())
976 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
977 else
978 ProducedBinaryFiles[count] = writeGeneratedObject(
979 count, CacheEntryPath, SavedObjectsDirectoryPath,
980 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000981 return;
982 }
983 }
984
985 LLVMContext Context;
986 Context.setDiscardValueNames(LTODiscardValueNames);
987 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000988 auto DiagFileOrErr = lto::setupOptimizationRemarks(
989 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000990 if (!DiagFileOrErr) {
991 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
992 report_fatal_error("ThinLTO: Can't get an output file for the "
993 "remarks");
994 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000995
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000996 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000997 auto TheModule =
998 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
999 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001000
1001 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +00001002 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001003
Mehdi Amini1aafabf2016-04-16 07:02:16 +00001004 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +00001005 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001006 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001007 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001008 ExportList, GUIDPreservedSymbols,
1009 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +00001010 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001011
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001012 // Commit to the cache (if enabled)
1013 CacheEntry.write(*OutputBuffer);
1014
1015 if (SavedObjectsDirectoryPath.empty()) {
1016 // We need to generated a memory buffer for the linker.
1017 if (!CacheEntryPath.empty()) {
1018 // Cache is enabled, reload from the cache
1019 // We do this to lower memory pressuree: the buffer is on the heap
1020 // and releasing it frees memory that can be used for the next input
1021 // file. The final binary link will read from the VFS cache
1022 // (hopefully!) or from disk if the memory pressure wasn't too high.
1023 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1024 if (auto EC = ReloadedBufferOrErr.getError()) {
1025 // On error, keeping the preexisting buffer and printing a
1026 // diagnostic is more friendly than just crashing.
1027 errs() << "error: can't reload cached file '" << CacheEntryPath
1028 << "': " << EC.message() << "\n";
1029 } else {
1030 OutputBuffer = std::move(*ReloadedBufferOrErr);
1031 }
1032 }
1033 ProducedBinaries[count] = std::move(OutputBuffer);
1034 return;
1035 }
1036 ProducedBinaryFiles[count] = writeGeneratedObject(
1037 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001038 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001039 }
1040 }
1041
Peter Collingbournecead56f2017-03-15 22:54:18 +00001042 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001043
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001044 // If statistics were requested, print them out now.
1045 if (llvm::AreStatisticsEnabled())
1046 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +00001047 reportAndResetTimings();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001048}