blob: d6e5d4d0c213ff652f52680bb8aee95d024c6b4a [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;
Adrian Prantl981a7992017-05-20 00:00:08 +000066extern cl::opt<bool> LTOStripInvalidDebugInfo;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000067}
68
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000069namespace {
70
Teresa Johnsonec544c52016-10-19 17:35:01 +000071static cl::opt<int>
72 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000073
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000074// Simple helper to save temporary files for debug.
75static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
76 unsigned count, StringRef Suffix) {
77 if (TempDir.empty())
78 return;
79 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000080 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000082 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000083 if (EC)
84 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
85 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000086 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000087}
88
Teresa Johnson4d2613f2016-05-24 17:24:25 +000089static const GlobalValueSummary *
90getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
91 // If there is any strong definition anywhere, get it.
92 auto StrongDefForLinker = llvm::find_if(
93 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
94 auto Linkage = Summary->linkage();
95 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
96 !GlobalValue::isWeakForLinker(Linkage);
97 });
98 if (StrongDefForLinker != GVSummaryList.end())
99 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000100 // Get the first *linker visible* definition for this global in the summary
101 // list.
102 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000103 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
104 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000105 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
106 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000107 // Extern templates can be emitted as available_externally.
108 if (FirstDefForLinker == GVSummaryList.end())
109 return nullptr;
110 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000111}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000112
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000113// Populate map of GUID to the prevailing copy for any multiply defined
114// symbols. Currently assume first copy is prevailing, or any strong
115// definition. Can be refined with Linker information in the future.
116static void computePrevailingCopies(
117 const ModuleSummaryIndex &Index,
118 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000119 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
120 return GVSummaryList.size() > 1;
121 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000122
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000123 for (auto &I : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000124 if (HasMultipleCopies(I.second.SummaryList))
125 PrevailingCopy[I.first] =
126 getFirstDefinitionForLinker(I.second.SummaryList);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000127 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000128}
129
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000130static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000131generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000132 StringMap<MemoryBufferRef> ModuleMap;
133 for (auto &ModuleBuffer : Modules) {
134 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
135 ModuleMap.end() &&
136 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000137 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000138 }
139 return ModuleMap;
140}
141
Teresa Johnson26ab5772016-03-15 00:04:37 +0000142static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000143 if (renameModuleForThinLTO(TheModule, Index))
144 report_fatal_error("renameModuleForThinLTO failed");
145}
146
Adrian Prantl981a7992017-05-20 00:00:08 +0000147namespace {
148class ThinLTODiagnosticInfo : public DiagnosticInfo {
149 const Twine &Msg;
150public:
151 ThinLTODiagnosticInfo(const Twine &DiagMsg,
152 DiagnosticSeverity Severity = DS_Error)
153 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
154 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
155};
156}
157
158/// Verify the module and strip broken debug info.
159static void verifyLoadedModule(Module &TheModule) {
160 bool BrokenDebugInfo = false;
161 if (verifyModule(TheModule, &dbgs(),
162 LTOStripInvalidDebugInfo ? &BrokenDebugInfo : nullptr))
163 report_fatal_error("Broken module found, compilation aborted!");
164 if (BrokenDebugInfo) {
165 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
166 "Invalid debug info found, debug info will be stripped", DS_Warning));
167 StripDebugInfo(TheModule);
168 }
169}
170
Peter Collingbournedac43b42016-12-01 05:52:32 +0000171static std::unique_ptr<Module>
172loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000173 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000174 SMDiagnostic Err;
175 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000176 Lazy
177 ? getLazyBitcodeModule(Buffer, Context,
178 /* ShouldLazyLoadMetadata */ true, IsImporting)
179 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000180 if (!ModuleOrErr) {
181 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
182 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
183 SourceMgr::DK_Error, EIB.message());
184 Err.print("ThinLTO", errs());
185 });
186 report_fatal_error("Can't load module, abort.");
187 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000188 if (!Lazy)
189 verifyLoadedModule(*ModuleOrErr.get());
Peter Collingbournedac43b42016-12-01 05:52:32 +0000190 return std::move(ModuleOrErr.get());
191}
192
Mehdi Amini01e32132016-03-26 05:40:34 +0000193static void
194crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
195 StringMap<MemoryBufferRef> &ModuleMap,
196 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000197 auto Loader = [&](StringRef Identifier) {
198 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000199 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000200 };
201
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000202 FunctionImporter Importer(Index, Loader);
Adrian Prantl66043792017-05-19 23:32:21 +0000203 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000204 if (!Result) {
205 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
206 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
207 SourceMgr::DK_Error, EIB.message());
208 Err.print("ThinLTO", errs());
209 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000210 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000211 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000212 // Verify again after cross-importing.
213 verifyLoadedModule(TheModule);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000214}
215
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000216static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000217 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000218 // Populate the PassManager
219 PassManagerBuilder PMB;
220 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000221 if (Freestanding)
222 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000223 PMB.Inliner = createFunctionInliningPass();
224 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000225 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000226 PMB.LoopVectorize = true;
227 PMB.SLPVectorize = true;
Adrian Prantl981a7992017-05-20 00:00:08 +0000228 // Already did this in verifyLoadedModule().
229 PMB.VerifyInput = false;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000230 PMB.VerifyOutput = false;
231
232 legacy::PassManager PM;
233
234 // Add the TTI (required to inform the vectorizer about register size for
235 // instance)
236 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
237
238 // Add optimizations
239 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000240
241 PM.run(TheModule);
242}
243
Mehdi Amini059464f2016-04-24 03:18:01 +0000244// Convert the PreservedSymbols map from "Name" based to "GUID" based.
245static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000246computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
247 const Triple &TheTriple) {
248 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
249 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000250 StringRef Name = Entry.first();
251 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
252 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000253 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000254 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000255 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000256}
257
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000258std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
259 TargetMachine &TM) {
260 SmallVector<char, 128> OutputBuffer;
261
262 // CodeGen
263 {
264 raw_svector_ostream OS(OutputBuffer);
265 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000266
267 // If the bitcode files contain ARC code and were compiled with optimization,
268 // the ObjCARCContractPass must be run, so do it unconditionally here.
269 PM.add(createObjCARCContractPass());
270
271 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000272 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
273 /* DisableVerify */ true))
274 report_fatal_error("Failed to setup codegen");
275
276 // Run codegen now. resulting binary is in OutputBuffer.
277 PM.run(TheModule);
278 }
279 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
280}
281
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000282/// Manage caching for a single Module.
283class ModuleCacheEntry {
284 SmallString<128> EntryPath;
285
286public:
287 // Create a cache entry. This compute a unique hash for the Module considering
288 // the current list of export/import, and offer an interface to query to
289 // access the content in the cache.
290 ModuleCacheEntry(
291 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
292 const FunctionImporter::ImportMapTy &ImportList,
293 const FunctionImporter::ExportSetTy &ExportList,
294 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000295 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000296 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000297 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000298 if (CachePath.empty())
299 return;
300
Mehdi Amini00fa1402016-10-08 04:44:18 +0000301 if (!Index.modulePaths().count(ModuleID))
302 // The module does not have an entry, it can't have a hash at all
303 return;
304
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000305 // Compute the unique hash for this entry
306 // This is based on the current compiler version, the module itself, the
307 // export list, the hash for every single module in the import list, the
308 // list of ResolvedODR for the module, and the list of preserved symbols.
309
Mehdi Aminif82bda02016-10-08 04:44:23 +0000310 // Include the hash for the current module
311 auto ModHash = Index.getModuleHash(ModuleID);
312
313 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
314 // No hash entry, no caching!
315 return;
316
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000317 SHA1 Hasher;
318
Mehdi Aminic92b6122017-01-10 00:55:47 +0000319 // Include the parts of the LTO configuration that affect code generation.
320 auto AddString = [&](StringRef Str) {
321 Hasher.update(Str);
322 Hasher.update(ArrayRef<uint8_t>{0});
323 };
324 auto AddUnsigned = [&](unsigned I) {
325 uint8_t Data[4];
326 Data[0] = I;
327 Data[1] = I >> 8;
328 Data[2] = I >> 16;
329 Data[3] = I >> 24;
330 Hasher.update(ArrayRef<uint8_t>{Data, 4});
331 };
332
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000333 // Start with the compiler revision
334 Hasher.update(LLVM_VERSION_STRING);
Peter Collingbourne942fa562017-04-13 01:26:12 +0000335#ifdef LLVM_REVISION
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000336 Hasher.update(LLVM_REVISION);
337#endif
338
Mehdi Aminic92b6122017-01-10 00:55:47 +0000339 // Hash the optimization level and the target machine settings.
340 AddString(TMBuilder.MCpu);
341 // FIXME: Hash more of Options. For now all clients initialize Options from
342 // command-line flags (which is unsupported in production), but may set
343 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
344 // DataSections and DebuggerTuning via command line flags.
345 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
346 AddUnsigned(TMBuilder.Options.FunctionSections);
347 AddUnsigned(TMBuilder.Options.DataSections);
348 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
349 AddString(TMBuilder.MAttr);
350 if (TMBuilder.RelocModel)
351 AddUnsigned(*TMBuilder.RelocModel);
352 AddUnsigned(TMBuilder.CGOptLevel);
353 AddUnsigned(OptLevel);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000354 AddUnsigned(Freestanding);
Mehdi Aminic92b6122017-01-10 00:55:47 +0000355
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000356 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
357 for (auto F : ExportList)
358 // The export list can impact the internalization, be conservative here
359 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
360
361 // Include the hash for every module we import functions from
362 for (auto &Entry : ImportList) {
363 auto ModHash = Index.getModuleHash(Entry.first());
364 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
365 }
366
367 // Include the hash for the resolved ODR.
368 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000369 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000370 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000371 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000372 sizeof(GlobalValue::LinkageTypes)));
373 }
374
375 // Include the hash for the preserved symbols.
376 for (auto &Entry : PreservedSymbols) {
377 if (DefinedFunctions.count(Entry))
378 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000379 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000380 }
381
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000382 // This choice of file name allows the cache to be pruned (see pruneCache()
383 // in include/llvm/Support/CachePruning.h).
384 sys::path::append(EntryPath, CachePath,
385 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000386 }
387
Mehdi Amini059464f2016-04-24 03:18:01 +0000388 // Access the path to this entry in the cache.
389 StringRef getEntryPath() { return EntryPath; }
390
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000391 // Try loading the buffer for this cache entry.
392 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
393 if (EntryPath.empty())
394 return std::error_code();
395 return MemoryBuffer::getFile(EntryPath);
396 }
397
398 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000399 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000400 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000401 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000402
403 // Write to a temporary to avoid race condition
404 SmallString<128> TempFilename;
405 int TempFD;
406 std::error_code EC =
407 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
408 if (EC) {
409 errs() << "Error: " << EC.message() << "\n";
410 report_fatal_error("ThinLTO: Can't get a temporary file");
411 }
412 {
413 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000414 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000415 }
416 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000417 EC = sys::fs::rename(TempFilename, EntryPath);
418 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000419 sys::fs::remove(TempFilename);
420 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
421 if (EC)
422 report_fatal_error(Twine("Failed to open ") + EntryPath +
423 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000424 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000425 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000426 }
427};
428
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000429static std::unique_ptr<MemoryBuffer>
430ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
431 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
432 const FunctionImporter::ImportMapTy &ImportList,
433 const FunctionImporter::ExportSetTy &ExportList,
434 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
435 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000436 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000437 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000438 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000439
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000440 // "Benchmark"-like optimization: single-source case
441 bool SingleModule = (ModuleMap.size() == 1);
442
443 if (!SingleModule) {
444 promoteModule(TheModule, Index);
445
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000446 // Apply summary-based LinkOnce/Weak resolution decisions.
447 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000448
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000449 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000450 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000451 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000452
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000453 // Be friendly and don't nuke totally the module when the client didn't
454 // supply anything to preserve.
455 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
456 // Apply summary-based internalization decisions.
457 thinLTOInternalizeModule(TheModule, DefinedGlobals);
458 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000459
460 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000461 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000462
463 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000464 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000465
466 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000467 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000468 }
469
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000470 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000471
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000472 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000473
Mehdi Amini43b657b2016-04-01 06:47:02 +0000474 if (DisableCodeGen) {
475 // Configured to stop before CodeGen, serialize the bitcode and return.
476 SmallVector<char, 128> OutputBuffer;
477 {
478 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000479 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000480 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000481 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000482 }
483 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
484 }
485
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000486 return codegenModule(TheModule, TM);
487}
488
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000489/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
490/// for caching, and in the \p Index for application during the ThinLTO
491/// backends. This is needed for correctness for exported symbols (ensure
492/// at least one copy kept) and a compile-time optimization (to drop duplicate
493/// copies when possible).
494static void resolveWeakForLinkerInIndex(
495 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000496 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
497 &ResolvedODR) {
498
499 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
500 computePrevailingCopies(Index, PrevailingCopy);
501
502 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
503 const auto &Prevailing = PrevailingCopy.find(GUID);
504 // Not in map means that there was only one copy, which must be prevailing.
505 if (Prevailing == PrevailingCopy.end())
506 return true;
507 return Prevailing->second == S;
508 };
509
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000510 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
511 GlobalValue::GUID GUID,
512 GlobalValue::LinkageTypes NewLinkage) {
513 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
514 };
515
Peter Collingbourne73589f32016-07-07 18:31:51 +0000516 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000517}
518
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000519// Initialize the TargetMachine builder for a given Triple
520static void initTMBuilder(TargetMachineBuilder &TMBuilder,
521 const Triple &TheTriple) {
522 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
523 // FIXME this looks pretty terrible...
524 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
525 if (TheTriple.getArch() == llvm::Triple::x86_64)
526 TMBuilder.MCpu = "core2";
527 else if (TheTriple.getArch() == llvm::Triple::x86)
528 TMBuilder.MCpu = "yonah";
529 else if (TheTriple.getArch() == llvm::Triple::aarch64)
530 TMBuilder.MCpu = "cyclone";
531 }
532 TMBuilder.TheTriple = std::move(TheTriple);
533}
534
535} // end anonymous namespace
536
537void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Johan Engelend3a82712017-09-17 17:38:26 +0000538 std::string Id =
539 (Twine(Identifier) + "_" + std::to_string(Modules.size())).str();
540 ThinLTOBuffer Buffer(Data, std::move(Id));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000541 LLVMContext Context;
542 StringRef TripleStr;
543 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
544 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
545
546 if (TripleOrErr)
547 TripleStr = *TripleOrErr;
548
549 Triple TheTriple(TripleStr);
550
551 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000552 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000553 else if (TMBuilder.TheTriple != TheTriple) {
554 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
555 report_fatal_error("ThinLTO modules with incompatible triples not "
556 "supported");
557 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000558 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000559
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000560 Modules.push_back(Buffer);
561}
562
563void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
564 PreservedSymbols.insert(Name);
565}
566
567void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000568 // FIXME: At the moment, we don't take advantage of this extra information,
569 // we're conservatively considering cross-references as preserved.
570 // CrossReferencedSymbols.insert(Name);
571 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000572}
573
574// TargetMachine factory
575std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
576 std::string ErrMsg;
577 const Target *TheTarget =
578 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
579 if (!TheTarget) {
580 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
581 }
582
583 // Use MAttr as the default set of features.
584 SubtargetFeatures Features(MAttr);
585 Features.getDefaultSubtargetFeatures(TheTriple);
586 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000587
Rafael Espindola79e238a2017-08-03 02:16:21 +0000588 return std::unique_ptr<TargetMachine>(
589 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
590 RelocModel, None, CGOptLevel));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000591}
592
593/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000594 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000595 * "thin-link".
596 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000597std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000598 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
599 llvm::make_unique<ModuleSummaryIndex>();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000600 uint64_t NextModuleId = 0;
601 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000602 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
603 *CombinedIndex, NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000604 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000605 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000606 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000607 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000608 return nullptr;
609 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000610 }
611 return CombinedIndex;
612}
613
614/**
615 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000616 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000617 */
618void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000619 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000620 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000621 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000622
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000623 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000624 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000625 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000626
Teresa Johnson6c475a72017-01-05 21:34:18 +0000627 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000628 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000629 PreservedSymbols, Triple(TheModule.getTargetTriple()));
630
631 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000632 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000633
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000634 // Generate import/export list
635 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
636 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
637 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000638 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000639
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000640 // Resolve LinkOnce/Weak symbols.
641 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000642 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000643
644 thinLTOResolveWeakForLinkerModule(
645 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000646
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000647 // Promote the exported values in the index, so that they are promoted
648 // in the module.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000649 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000650 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000651 return (ExportList != ExportLists.end() &&
652 ExportList->second.count(GUID)) ||
653 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000654 };
655 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
656
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000657 promoteModule(TheModule, Index);
658}
659
660/**
661 * Perform cross-module importing for the module identified by ModuleIdentifier.
662 */
663void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000664 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000665 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000666 auto ModuleCount = Index.modulePaths().size();
667
668 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000669 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000670 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000671
Teresa Johnson6c475a72017-01-05 21:34:18 +0000672 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000673 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000674 PreservedSymbols, Triple(TheModule.getTargetTriple()));
675
676 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000677 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000678
Mehdi Amini01e32132016-03-26 05:40:34 +0000679 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000680 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
681 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000682 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000683 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000684 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
685
686 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000687}
688
689/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000690 * Compute the list of summaries needed for importing into module.
691 */
692void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
693 StringRef ModulePath, ModuleSummaryIndex &Index,
694 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
695 auto ModuleCount = Index.modulePaths().size();
696
697 // Collect for each module the list of function it defines (GUID -> Summary).
698 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
699 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
700
701 // Generate import/export list
702 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
703 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
704 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
705 ExportLists);
706
707 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000708 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000709 ModuleToSummariesForIndex);
710}
711
712/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000713 * Emit the list of files needed for importing into module.
714 */
715void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
716 StringRef OutputName,
717 ModuleSummaryIndex &Index) {
718 auto ModuleCount = Index.modulePaths().size();
719
720 // Collect for each module the list of function it defines (GUID -> Summary).
721 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
722 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
723
724 // Generate import/export list
725 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
726 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
727 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
728 ExportLists);
729
730 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000731 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000732 report_fatal_error(Twine("Failed to open ") + OutputName +
733 " to save imports lists\n");
734}
735
736/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000737 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000738 */
739void ThinLTOCodeGenerator::internalize(Module &TheModule,
740 ModuleSummaryIndex &Index) {
741 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
742 auto ModuleCount = Index.modulePaths().size();
743 auto ModuleIdentifier = TheModule.getModuleIdentifier();
744
745 // Convert the preserved symbols set from string to GUID
746 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000747 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000748
749 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000750 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000751 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
752
Teresa Johnson6c475a72017-01-05 21:34:18 +0000753 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000754 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000755
Mehdi Amini059464f2016-04-24 03:18:01 +0000756 // Generate import/export list
757 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
758 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
759 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000760 ExportLists);
Mehdi Amini059464f2016-04-24 03:18:01 +0000761 auto &ExportList = ExportLists[ModuleIdentifier];
762
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000763 // Be friendly and don't nuke totally the module when the client didn't
764 // supply anything to preserve.
765 if (ExportList.empty() && GUIDPreservedSymbols.empty())
766 return;
767
Mehdi Amini059464f2016-04-24 03:18:01 +0000768 // Internalization
Mehdi Amini1380edf2017-02-03 07:41:43 +0000769 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000770 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000771 return (ExportList != ExportLists.end() &&
772 ExportList->second.count(GUID)) ||
773 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000774 };
775 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
776 thinLTOInternalizeModule(TheModule,
777 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000778}
779
780/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000781 * Perform post-importing ThinLTO optimizations.
782 */
783void ThinLTOCodeGenerator::optimize(Module &TheModule) {
784 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000785
786 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000787 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000788}
789
790/**
791 * Perform ThinLTO CodeGen.
792 */
793std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
794 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
795 return codegenModule(TheModule, *TMBuilder.create());
796}
797
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000798/// Write out the generated object file, either from CacheEntryPath or from
799/// OutputBuffer, preferring hard-link when possible.
800/// Returns the path to the generated file in SavedObjectsDirectoryPath.
801static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
802 StringRef SavedObjectsDirectoryPath,
803 const MemoryBuffer &OutputBuffer) {
804 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
805 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
806 OutputPath.c_str(); // Ensure the string is null terminated.
807 if (sys::fs::exists(OutputPath))
808 sys::fs::remove(OutputPath);
809
810 // We don't return a memory buffer to the linker, just a list of files.
811 if (!CacheEntryPath.empty()) {
812 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
813 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
814 if (!Err)
815 return OutputPath.str();
816 // Hard linking failed, try to copy.
817 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
818 if (!Err)
819 return OutputPath.str();
820 // Copy failed (could be because the CacheEntry was removed from the cache
821 // in the meantime by another process), fall back and try to write down the
822 // buffer to the output.
823 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
824 << "' to '" << OutputPath << "'\n";
825 }
826 // No cache entry, just write out the buffer.
827 std::error_code Err;
828 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
829 if (Err)
830 report_fatal_error("Can't open output '" + OutputPath + "'\n");
831 OS << OutputBuffer.getBuffer();
832 return OutputPath.str();
833}
834
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000835// Main entry point for the ThinLTO processing
836void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000837 // Prepare the resulting object vector
838 assert(ProducedBinaries.empty() && "The generator should not be reused");
839 if (SavedObjectsDirectoryPath.empty())
840 ProducedBinaries.resize(Modules.size());
841 else {
842 sys::fs::create_directories(SavedObjectsDirectoryPath);
843 bool IsDir;
844 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
845 if (!IsDir)
846 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
847 ProducedBinaryFiles.resize(Modules.size());
848 }
849
Mehdi Amini43b657b2016-04-01 06:47:02 +0000850 if (CodeGenOnly) {
851 // Perform only parallel codegen and return.
852 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000853 int count = 0;
854 for (auto &ModuleBuffer : Modules) {
855 Pool.async([&](int count) {
856 LLVMContext Context;
857 Context.setDiscardValueNames(LTODiscardValueNames);
858
859 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000860 auto TheModule =
861 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
862 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000863
864 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000865 auto OutputBuffer = codegen(*TheModule);
866 if (SavedObjectsDirectoryPath.empty())
867 ProducedBinaries[count] = std::move(OutputBuffer);
868 else
869 ProducedBinaryFiles[count] = writeGeneratedObject(
870 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000871 }, count++);
872 }
873
874 return;
875 }
876
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000877 // Sequential linking phase
878 auto Index = linkCombinedIndex();
879
880 // Save temps: index.
881 if (!SaveTempsDir.empty()) {
882 auto SaveTempPath = SaveTempsDir + "index.bc";
883 std::error_code EC;
884 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
885 if (EC)
886 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
887 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000888 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000889 }
890
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000891
892 // Prepare the module map.
893 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000894 auto ModuleCount = Modules.size();
895
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000896 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000897 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000898 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
899
Teresa Johnson6c475a72017-01-05 21:34:18 +0000900 // Convert the preserved symbols set from string to GUID, this is needed for
901 // computing the caching hash and the internalization.
902 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000903 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000904
905 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000906 computeDeadSymbols(*Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000907
Mehdi Amini01e32132016-03-26 05:40:34 +0000908 // Collect the import/export lists for all modules from the call-graph in the
909 // combined index.
910 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
911 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000912 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000913 ExportLists);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000914
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000915 // We use a std::map here to be able to have a defined ordering when
916 // producing a hash for the cache entry.
917 // FIXME: we should be able to compute the caching hash for the entry based
918 // on the index, and nuke this map.
919 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
920
921 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
922 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000923 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000924
Mehdi Amini1380edf2017-02-03 07:41:43 +0000925 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000926 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000927 return (ExportList != ExportLists.end() &&
928 ExportList->second.count(GUID)) ||
929 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000930 };
931
932 // 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.
935 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
936
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);
950 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
951 [&](int LeftIndex, int RightIndex) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000952 auto LSize = Modules[LeftIndex].getBuffer().size();
953 auto RSize = Modules[RightIndex].getBuffer().size();
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000954 return LSize > RSize;
955 });
956
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(
998 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()) {
1027 // Cache is enabled, reload from the cache
1028 // We do this to lower memory pressuree: the buffer is on the heap
1029 // and releasing it frees memory that can be used for the next input
1030 // file. The final binary link will read from the VFS cache
1031 // (hopefully!) or from disk if the memory pressure wasn't too high.
1032 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1033 if (auto EC = ReloadedBufferOrErr.getError()) {
1034 // On error, keeping the preexisting buffer and printing a
1035 // diagnostic is more friendly than just crashing.
1036 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}