blob: 327f2377d91b820913c4f89296df68eae2b81d14 [file] [log] [blame]
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001//===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Thin Link Time Optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne5c732202016-07-14 21:21:16 +000015#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000016
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000017#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000018#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000019#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000020#include "llvm/Analysis/ProfileSummaryInfo.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000025#include "llvm/Bitcode/BitcodeWriterPass.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000026#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000027#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000029#include "llvm/IR/LegacyPassManager.h"
30#include "llvm/IR/Mangler.h"
31#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000032#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/Linker/Linker.h"
34#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000035#include "llvm/Object/IRObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000036#include "llvm/Support/CachePruning.h"
37#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000038#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000039#include "llvm/Support/Path.h"
40#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000041#include "llvm/Support/TargetRegistry.h"
42#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000043#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000044#include "llvm/Support/ToolOutputFile.h"
Peter Collingbourne942fa562017-04-13 01:26:12 +000045#include "llvm/Support/VCSRevision.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000046#include "llvm/Target/TargetMachine.h"
47#include "llvm/Transforms/IPO.h"
48#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000049#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000050#include "llvm/Transforms/IPO/PassManagerBuilder.h"
51#include "llvm/Transforms/ObjCARC.h"
52#include "llvm/Transforms/Utils/FunctionImportUtils.h"
53
Mehdi Amini819e9cd2016-05-16 19:33:07 +000054#include <numeric>
55
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000056using namespace llvm;
57
Mehdi Amini1aafabf2016-04-16 07:02:16 +000058#define DEBUG_TYPE "thinlto"
59
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000060namespace llvm {
61// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
62extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000063extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000064extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000065}
66
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000067namespace {
68
Teresa Johnsonec544c52016-10-19 17:35:01 +000069static cl::opt<int>
70 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000071
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000072// Simple helper to save temporary files for debug.
73static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
74 unsigned count, StringRef Suffix) {
75 if (TempDir.empty())
76 return;
77 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000078 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000079 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000080 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081 if (EC)
82 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
83 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000084 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000085}
86
Teresa Johnson4d2613f2016-05-24 17:24:25 +000087static const GlobalValueSummary *
88getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
89 // If there is any strong definition anywhere, get it.
90 auto StrongDefForLinker = llvm::find_if(
91 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
92 auto Linkage = Summary->linkage();
93 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
94 !GlobalValue::isWeakForLinker(Linkage);
95 });
96 if (StrongDefForLinker != GVSummaryList.end())
97 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +000098 // Get the first *linker visible* definition for this global in the summary
99 // list.
100 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000101 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
102 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000103 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
104 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000105 // Extern templates can be emitted as available_externally.
106 if (FirstDefForLinker == GVSummaryList.end())
107 return nullptr;
108 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000109}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000110
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000111// Populate map of GUID to the prevailing copy for any multiply defined
112// symbols. Currently assume first copy is prevailing, or any strong
113// definition. Can be refined with Linker information in the future.
114static void computePrevailingCopies(
115 const ModuleSummaryIndex &Index,
116 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000117 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
118 return GVSummaryList.size() > 1;
119 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000120
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000121 for (auto &I : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000122 if (HasMultipleCopies(I.second.SummaryList))
123 PrevailingCopy[I.first] =
124 getFirstDefinitionForLinker(I.second.SummaryList);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000125 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000126}
127
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000128static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000129generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000130 StringMap<MemoryBufferRef> ModuleMap;
131 for (auto &ModuleBuffer : Modules) {
132 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
133 ModuleMap.end() &&
134 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000135 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000136 }
137 return ModuleMap;
138}
139
Teresa Johnson26ab5772016-03-15 00:04:37 +0000140static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000141 if (renameModuleForThinLTO(TheModule, Index))
142 report_fatal_error("renameModuleForThinLTO failed");
143}
144
Peter Collingbournedac43b42016-12-01 05:52:32 +0000145static std::unique_ptr<Module>
146loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000147 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000148 SMDiagnostic Err;
149 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000150 Lazy
151 ? getLazyBitcodeModule(Buffer, Context,
152 /* ShouldLazyLoadMetadata */ true, IsImporting)
153 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000154 if (!ModuleOrErr) {
155 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
156 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
157 SourceMgr::DK_Error, EIB.message());
158 Err.print("ThinLTO", errs());
159 });
160 report_fatal_error("Can't load module, abort.");
161 }
162 return std::move(ModuleOrErr.get());
163}
164
Mehdi Amini01e32132016-03-26 05:40:34 +0000165static void
166crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
167 StringMap<MemoryBufferRef> &ModuleMap,
168 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000169 auto Loader = [&](StringRef Identifier) {
170 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000171 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000172 };
173
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000174 FunctionImporter Importer(Index, Loader);
Adrian Prantl66043792017-05-19 23:32:21 +0000175 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000176 if (!Result) {
177 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
178 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
179 SourceMgr::DK_Error, EIB.message());
180 Err.print("ThinLTO", errs());
181 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000182 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000183 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000184}
185
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000186static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000187 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000188 // Populate the PassManager
189 PassManagerBuilder PMB;
190 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000191 if (Freestanding)
192 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000193 PMB.Inliner = createFunctionInliningPass();
194 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000195 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000196 PMB.LoopVectorize = true;
197 PMB.SLPVectorize = true;
Adrian Prantl66043792017-05-19 23:32:21 +0000198 PMB.VerifyInput = true;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000199 PMB.VerifyOutput = false;
200
201 legacy::PassManager PM;
202
203 // Add the TTI (required to inform the vectorizer about register size for
204 // instance)
205 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
206
207 // Add optimizations
208 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000209
210 PM.run(TheModule);
211}
212
Mehdi Amini059464f2016-04-24 03:18:01 +0000213// Convert the PreservedSymbols map from "Name" based to "GUID" based.
214static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000215computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
216 const Triple &TheTriple) {
217 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
218 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000219 StringRef Name = Entry.first();
220 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
221 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000222 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000223 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000224 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000225}
226
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000227std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
228 TargetMachine &TM) {
229 SmallVector<char, 128> OutputBuffer;
230
231 // CodeGen
232 {
233 raw_svector_ostream OS(OutputBuffer);
234 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000235
236 // If the bitcode files contain ARC code and were compiled with optimization,
237 // the ObjCARCContractPass must be run, so do it unconditionally here.
238 PM.add(createObjCARCContractPass());
239
240 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000241 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
242 /* DisableVerify */ true))
243 report_fatal_error("Failed to setup codegen");
244
245 // Run codegen now. resulting binary is in OutputBuffer.
246 PM.run(TheModule);
247 }
248 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
249}
250
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000251/// Manage caching for a single Module.
252class ModuleCacheEntry {
253 SmallString<128> EntryPath;
254
255public:
256 // Create a cache entry. This compute a unique hash for the Module considering
257 // the current list of export/import, and offer an interface to query to
258 // access the content in the cache.
259 ModuleCacheEntry(
260 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
261 const FunctionImporter::ImportMapTy &ImportList,
262 const FunctionImporter::ExportSetTy &ExportList,
263 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000264 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000265 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000266 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000267 if (CachePath.empty())
268 return;
269
Mehdi Amini00fa1402016-10-08 04:44:18 +0000270 if (!Index.modulePaths().count(ModuleID))
271 // The module does not have an entry, it can't have a hash at all
272 return;
273
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000274 // Compute the unique hash for this entry
275 // This is based on the current compiler version, the module itself, the
276 // export list, the hash for every single module in the import list, the
277 // list of ResolvedODR for the module, and the list of preserved symbols.
278
Mehdi Aminif82bda02016-10-08 04:44:23 +0000279 // Include the hash for the current module
280 auto ModHash = Index.getModuleHash(ModuleID);
281
282 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
283 // No hash entry, no caching!
284 return;
285
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000286 SHA1 Hasher;
287
Mehdi Aminic92b6122017-01-10 00:55:47 +0000288 // Include the parts of the LTO configuration that affect code generation.
289 auto AddString = [&](StringRef Str) {
290 Hasher.update(Str);
291 Hasher.update(ArrayRef<uint8_t>{0});
292 };
293 auto AddUnsigned = [&](unsigned I) {
294 uint8_t Data[4];
295 Data[0] = I;
296 Data[1] = I >> 8;
297 Data[2] = I >> 16;
298 Data[3] = I >> 24;
299 Hasher.update(ArrayRef<uint8_t>{Data, 4});
300 };
301
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000302 // Start with the compiler revision
303 Hasher.update(LLVM_VERSION_STRING);
Peter Collingbourne942fa562017-04-13 01:26:12 +0000304#ifdef LLVM_REVISION
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000305 Hasher.update(LLVM_REVISION);
306#endif
307
Mehdi Aminic92b6122017-01-10 00:55:47 +0000308 // Hash the optimization level and the target machine settings.
309 AddString(TMBuilder.MCpu);
310 // FIXME: Hash more of Options. For now all clients initialize Options from
311 // command-line flags (which is unsupported in production), but may set
312 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
313 // DataSections and DebuggerTuning via command line flags.
314 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
315 AddUnsigned(TMBuilder.Options.FunctionSections);
316 AddUnsigned(TMBuilder.Options.DataSections);
317 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
318 AddString(TMBuilder.MAttr);
319 if (TMBuilder.RelocModel)
320 AddUnsigned(*TMBuilder.RelocModel);
321 AddUnsigned(TMBuilder.CGOptLevel);
322 AddUnsigned(OptLevel);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000323 AddUnsigned(Freestanding);
Mehdi Aminic92b6122017-01-10 00:55:47 +0000324
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000325 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
326 for (auto F : ExportList)
327 // The export list can impact the internalization, be conservative here
328 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
329
330 // Include the hash for every module we import functions from
331 for (auto &Entry : ImportList) {
332 auto ModHash = Index.getModuleHash(Entry.first());
333 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
334 }
335
336 // Include the hash for the resolved ODR.
337 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000338 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000339 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000340 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000341 sizeof(GlobalValue::LinkageTypes)));
342 }
343
344 // Include the hash for the preserved symbols.
345 for (auto &Entry : PreservedSymbols) {
346 if (DefinedFunctions.count(Entry))
347 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000348 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000349 }
350
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000351 // This choice of file name allows the cache to be pruned (see pruneCache()
352 // in include/llvm/Support/CachePruning.h).
353 sys::path::append(EntryPath, CachePath,
354 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000355 }
356
Mehdi Amini059464f2016-04-24 03:18:01 +0000357 // Access the path to this entry in the cache.
358 StringRef getEntryPath() { return EntryPath; }
359
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000360 // Try loading the buffer for this cache entry.
361 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
362 if (EntryPath.empty())
363 return std::error_code();
364 return MemoryBuffer::getFile(EntryPath);
365 }
366
367 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000368 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000369 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000370 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000371
372 // Write to a temporary to avoid race condition
373 SmallString<128> TempFilename;
374 int TempFD;
375 std::error_code EC =
376 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
377 if (EC) {
378 errs() << "Error: " << EC.message() << "\n";
379 report_fatal_error("ThinLTO: Can't get a temporary file");
380 }
381 {
382 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000383 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000384 }
385 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000386 EC = sys::fs::rename(TempFilename, EntryPath);
387 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000388 sys::fs::remove(TempFilename);
389 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
390 if (EC)
391 report_fatal_error(Twine("Failed to open ") + EntryPath +
392 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000393 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000394 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000395 }
396};
397
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000398static std::unique_ptr<MemoryBuffer>
399ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
400 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
401 const FunctionImporter::ImportMapTy &ImportList,
402 const FunctionImporter::ExportSetTy &ExportList,
403 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
404 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000405 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000406 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000407 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000408
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000409 // "Benchmark"-like optimization: single-source case
410 bool SingleModule = (ModuleMap.size() == 1);
411
412 if (!SingleModule) {
413 promoteModule(TheModule, Index);
414
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000415 // Apply summary-based LinkOnce/Weak resolution decisions.
416 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000417
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000418 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000419 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000420 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000421
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000422 // Be friendly and don't nuke totally the module when the client didn't
423 // supply anything to preserve.
424 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
425 // Apply summary-based internalization decisions.
426 thinLTOInternalizeModule(TheModule, DefinedGlobals);
427 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000428
429 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000430 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000431
432 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000433 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000434
435 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000436 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000437 }
438
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000439 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000440
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000441 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000442
Mehdi Amini43b657b2016-04-01 06:47:02 +0000443 if (DisableCodeGen) {
444 // Configured to stop before CodeGen, serialize the bitcode and return.
445 SmallVector<char, 128> OutputBuffer;
446 {
447 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000448 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000449 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000450 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000451 }
452 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
453 }
454
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000455 return codegenModule(TheModule, TM);
456}
457
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000458/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
459/// for caching, and in the \p Index for application during the ThinLTO
460/// backends. This is needed for correctness for exported symbols (ensure
461/// at least one copy kept) and a compile-time optimization (to drop duplicate
462/// copies when possible).
463static void resolveWeakForLinkerInIndex(
464 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000465 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
466 &ResolvedODR) {
467
468 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
469 computePrevailingCopies(Index, PrevailingCopy);
470
471 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
472 const auto &Prevailing = PrevailingCopy.find(GUID);
473 // Not in map means that there was only one copy, which must be prevailing.
474 if (Prevailing == PrevailingCopy.end())
475 return true;
476 return Prevailing->second == S;
477 };
478
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000479 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
480 GlobalValue::GUID GUID,
481 GlobalValue::LinkageTypes NewLinkage) {
482 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
483 };
484
Peter Collingbourne73589f32016-07-07 18:31:51 +0000485 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000486}
487
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000488// Initialize the TargetMachine builder for a given Triple
489static void initTMBuilder(TargetMachineBuilder &TMBuilder,
490 const Triple &TheTriple) {
491 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
492 // FIXME this looks pretty terrible...
493 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
494 if (TheTriple.getArch() == llvm::Triple::x86_64)
495 TMBuilder.MCpu = "core2";
496 else if (TheTriple.getArch() == llvm::Triple::x86)
497 TMBuilder.MCpu = "yonah";
498 else if (TheTriple.getArch() == llvm::Triple::aarch64)
499 TMBuilder.MCpu = "cyclone";
500 }
501 TMBuilder.TheTriple = std::move(TheTriple);
502}
503
504} // end anonymous namespace
505
506void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000507 ThinLTOBuffer Buffer(Data, Identifier);
Akira Hatanakab10bff12017-05-18 03:52:29 +0000508 LLVMContext Context;
509 StringRef TripleStr;
510 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
511 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
512
513 if (TripleOrErr)
514 TripleStr = *TripleOrErr;
515
516 Triple TheTriple(TripleStr);
517
518 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000519 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000520 else if (TMBuilder.TheTriple != TheTriple) {
521 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
522 report_fatal_error("ThinLTO modules with incompatible triples not "
523 "supported");
524 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000525 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000526
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000527 Modules.push_back(Buffer);
528}
529
530void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
531 PreservedSymbols.insert(Name);
532}
533
534void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000535 // FIXME: At the moment, we don't take advantage of this extra information,
536 // we're conservatively considering cross-references as preserved.
537 // CrossReferencedSymbols.insert(Name);
538 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000539}
540
541// TargetMachine factory
542std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
543 std::string ErrMsg;
544 const Target *TheTarget =
545 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
546 if (!TheTarget) {
547 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
548 }
549
550 // Use MAttr as the default set of features.
551 SubtargetFeatures Features(MAttr);
552 Features.getDefaultSubtargetFeatures(TheTriple);
553 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000554
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000555 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
556 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
557 CodeModel::Default, CGOptLevel));
558}
559
560/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000561 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000562 * "thin-link".
563 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000564std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000565 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
566 llvm::make_unique<ModuleSummaryIndex>();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000567 uint64_t NextModuleId = 0;
568 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000569 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
570 *CombinedIndex, NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000571 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000572 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000573 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000574 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000575 return nullptr;
576 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000577 }
578 return CombinedIndex;
579}
580
581/**
582 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000583 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000584 */
585void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000586 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000587 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000588 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000589
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000590 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000591 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000592 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000593
Teresa Johnson6c475a72017-01-05 21:34:18 +0000594 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000595 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000596 PreservedSymbols, Triple(TheModule.getTargetTriple()));
597
598 // Compute "dead" symbols, we don't want to import/export these!
599 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
600
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000601 // Generate import/export list
602 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
603 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
604 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000605 ExportLists, &DeadSymbols);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000606
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000607 // Resolve LinkOnce/Weak symbols.
608 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000609 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000610
611 thinLTOResolveWeakForLinkerModule(
612 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000613
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000614 // Promote the exported values in the index, so that they are promoted
615 // in the module.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000616 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000617 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000618 return (ExportList != ExportLists.end() &&
619 ExportList->second.count(GUID)) ||
620 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000621 };
622 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
623
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000624 promoteModule(TheModule, Index);
625}
626
627/**
628 * Perform cross-module importing for the module identified by ModuleIdentifier.
629 */
630void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000631 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000632 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000633 auto ModuleCount = Index.modulePaths().size();
634
635 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000636 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000637 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000638
Teresa Johnson6c475a72017-01-05 21:34:18 +0000639 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000640 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000641 PreservedSymbols, Triple(TheModule.getTargetTriple()));
642
643 // Compute "dead" symbols, we don't want to import/export these!
644 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
645
Mehdi Amini01e32132016-03-26 05:40:34 +0000646 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000647 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
648 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000649 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000650 ExportLists, &DeadSymbols);
Mehdi Amini01e32132016-03-26 05:40:34 +0000651 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
652
653 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000654}
655
656/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000657 * Compute the list of summaries needed for importing into module.
658 */
659void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
660 StringRef ModulePath, ModuleSummaryIndex &Index,
661 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
662 auto ModuleCount = Index.modulePaths().size();
663
664 // Collect for each module the list of function it defines (GUID -> Summary).
665 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
666 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
667
668 // Generate import/export list
669 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
670 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
671 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
672 ExportLists);
673
674 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000675 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000676 ModuleToSummariesForIndex);
677}
678
679/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000680 * Emit the list of files needed for importing into module.
681 */
682void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
683 StringRef OutputName,
684 ModuleSummaryIndex &Index) {
685 auto ModuleCount = Index.modulePaths().size();
686
687 // Collect for each module the list of function it defines (GUID -> Summary).
688 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
689 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
690
691 // Generate import/export list
692 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
693 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
694 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
695 ExportLists);
696
697 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000698 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000699 report_fatal_error(Twine("Failed to open ") + OutputName +
700 " to save imports lists\n");
701}
702
703/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000704 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000705 */
706void ThinLTOCodeGenerator::internalize(Module &TheModule,
707 ModuleSummaryIndex &Index) {
708 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
709 auto ModuleCount = Index.modulePaths().size();
710 auto ModuleIdentifier = TheModule.getModuleIdentifier();
711
712 // Convert the preserved symbols set from string to GUID
713 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000714 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000715
716 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000717 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000718 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
719
Teresa Johnson6c475a72017-01-05 21:34:18 +0000720 // Compute "dead" symbols, we don't want to import/export these!
721 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
722
Mehdi Amini059464f2016-04-24 03:18:01 +0000723 // Generate import/export list
724 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
725 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
726 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000727 ExportLists, &DeadSymbols);
Mehdi Amini059464f2016-04-24 03:18:01 +0000728 auto &ExportList = ExportLists[ModuleIdentifier];
729
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000730 // Be friendly and don't nuke totally the module when the client didn't
731 // supply anything to preserve.
732 if (ExportList.empty() && GUIDPreservedSymbols.empty())
733 return;
734
Mehdi Amini059464f2016-04-24 03:18:01 +0000735 // Internalization
Mehdi Amini1380edf2017-02-03 07:41:43 +0000736 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000737 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000738 return (ExportList != ExportLists.end() &&
739 ExportList->second.count(GUID)) ||
740 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000741 };
742 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
743 thinLTOInternalizeModule(TheModule,
744 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000745}
746
747/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000748 * Perform post-importing ThinLTO optimizations.
749 */
750void ThinLTOCodeGenerator::optimize(Module &TheModule) {
751 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000752
753 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000754 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000755}
756
757/**
758 * Perform ThinLTO CodeGen.
759 */
760std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
761 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
762 return codegenModule(TheModule, *TMBuilder.create());
763}
764
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000765/// Write out the generated object file, either from CacheEntryPath or from
766/// OutputBuffer, preferring hard-link when possible.
767/// Returns the path to the generated file in SavedObjectsDirectoryPath.
768static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
769 StringRef SavedObjectsDirectoryPath,
770 const MemoryBuffer &OutputBuffer) {
771 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
772 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
773 OutputPath.c_str(); // Ensure the string is null terminated.
774 if (sys::fs::exists(OutputPath))
775 sys::fs::remove(OutputPath);
776
777 // We don't return a memory buffer to the linker, just a list of files.
778 if (!CacheEntryPath.empty()) {
779 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
780 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
781 if (!Err)
782 return OutputPath.str();
783 // Hard linking failed, try to copy.
784 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
785 if (!Err)
786 return OutputPath.str();
787 // Copy failed (could be because the CacheEntry was removed from the cache
788 // in the meantime by another process), fall back and try to write down the
789 // buffer to the output.
790 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
791 << "' to '" << OutputPath << "'\n";
792 }
793 // No cache entry, just write out the buffer.
794 std::error_code Err;
795 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
796 if (Err)
797 report_fatal_error("Can't open output '" + OutputPath + "'\n");
798 OS << OutputBuffer.getBuffer();
799 return OutputPath.str();
800}
801
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000802// Main entry point for the ThinLTO processing
803void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000804 // Prepare the resulting object vector
805 assert(ProducedBinaries.empty() && "The generator should not be reused");
806 if (SavedObjectsDirectoryPath.empty())
807 ProducedBinaries.resize(Modules.size());
808 else {
809 sys::fs::create_directories(SavedObjectsDirectoryPath);
810 bool IsDir;
811 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
812 if (!IsDir)
813 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
814 ProducedBinaryFiles.resize(Modules.size());
815 }
816
Mehdi Amini43b657b2016-04-01 06:47:02 +0000817 if (CodeGenOnly) {
818 // Perform only parallel codegen and return.
819 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000820 int count = 0;
821 for (auto &ModuleBuffer : Modules) {
822 Pool.async([&](int count) {
823 LLVMContext Context;
824 Context.setDiscardValueNames(LTODiscardValueNames);
825
826 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000827 auto TheModule =
828 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
829 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000830
831 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000832 auto OutputBuffer = codegen(*TheModule);
833 if (SavedObjectsDirectoryPath.empty())
834 ProducedBinaries[count] = std::move(OutputBuffer);
835 else
836 ProducedBinaryFiles[count] = writeGeneratedObject(
837 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000838 }, count++);
839 }
840
841 return;
842 }
843
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000844 // Sequential linking phase
845 auto Index = linkCombinedIndex();
846
847 // Save temps: index.
848 if (!SaveTempsDir.empty()) {
849 auto SaveTempPath = SaveTempsDir + "index.bc";
850 std::error_code EC;
851 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
852 if (EC)
853 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
854 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000855 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000856 }
857
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000858
859 // Prepare the module map.
860 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000861 auto ModuleCount = Modules.size();
862
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000863 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000864 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000865 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
866
Teresa Johnson6c475a72017-01-05 21:34:18 +0000867 // Convert the preserved symbols set from string to GUID, this is needed for
868 // computing the caching hash and the internalization.
869 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000870 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000871
872 // Compute "dead" symbols, we don't want to import/export these!
873 auto DeadSymbols = computeDeadSymbols(*Index, GUIDPreservedSymbols);
874
Mehdi Amini01e32132016-03-26 05:40:34 +0000875 // Collect the import/export lists for all modules from the call-graph in the
876 // combined index.
877 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
878 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000879 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000880 ExportLists, &DeadSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000881
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000882 // We use a std::map here to be able to have a defined ordering when
883 // producing a hash for the cache entry.
884 // FIXME: we should be able to compute the caching hash for the entry based
885 // on the index, and nuke this map.
886 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
887
888 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
889 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000890 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000891
Mehdi Amini1380edf2017-02-03 07:41:43 +0000892 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000893 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000894 return (ExportList != ExportLists.end() &&
895 ExportList->second.count(GUID)) ||
896 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000897 };
898
899 // Use global summary-based analysis to identify symbols that can be
900 // internalized (because they aren't exported or preserved as per callback).
901 // Changes are made in the index, consumed in the ThinLTO backends.
902 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
903
Teresa Johnson141149f2016-05-24 18:44:01 +0000904 // Make sure that every module has an entry in the ExportLists and
905 // ResolvedODR maps to enable threaded access to these maps below.
906 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000907 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000908 ResolvedODR[DefinedGVSummaries.first()];
909 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000910
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000911 // Compute the ordering we will process the inputs: the rough heuristic here
912 // is to sort them per size so that the largest module get schedule as soon as
913 // possible. This is purely a compile-time optimization.
914 std::vector<int> ModulesOrdering;
915 ModulesOrdering.resize(Modules.size());
916 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
917 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
918 [&](int LeftIndex, int RightIndex) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000919 auto LSize = Modules[LeftIndex].getBuffer().size();
920 auto RSize = Modules[RightIndex].getBuffer().size();
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000921 return LSize > RSize;
922 });
923
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000924 // Parallel optimizer + codegen
925 {
926 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000927 for (auto IndexCount : ModulesOrdering) {
928 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000929 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000930 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000931 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000932
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000933 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
934
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000935 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000936 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
937 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000938 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000939 DefinedFunctions, GUIDPreservedSymbols,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000940 OptLevel, Freestanding, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000941 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000942
943 {
944 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000945 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000946 << CacheEntryPath << "' for buffer " << count << " "
947 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000948
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000949 if (ErrOrBuffer) {
950 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000951 if (SavedObjectsDirectoryPath.empty())
952 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
953 else
954 ProducedBinaryFiles[count] = writeGeneratedObject(
955 count, CacheEntryPath, SavedObjectsDirectoryPath,
956 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000957 return;
958 }
959 }
960
961 LLVMContext Context;
962 Context.setDiscardValueNames(LTODiscardValueNames);
963 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000964 auto DiagFileOrErr = lto::setupOptimizationRemarks(
965 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000966 if (!DiagFileOrErr) {
967 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
968 report_fatal_error("ThinLTO: Can't get an output file for the "
969 "remarks");
970 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000971
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000972 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000973 auto TheModule =
974 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
975 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000976
977 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000978 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000979
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000980 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000981 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000982 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000983 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000984 ExportList, GUIDPreservedSymbols,
985 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000986 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000987
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000988 // Commit to the cache (if enabled)
989 CacheEntry.write(*OutputBuffer);
990
991 if (SavedObjectsDirectoryPath.empty()) {
992 // We need to generated a memory buffer for the linker.
993 if (!CacheEntryPath.empty()) {
994 // Cache is enabled, reload from the cache
995 // We do this to lower memory pressuree: the buffer is on the heap
996 // and releasing it frees memory that can be used for the next input
997 // file. The final binary link will read from the VFS cache
998 // (hopefully!) or from disk if the memory pressure wasn't too high.
999 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1000 if (auto EC = ReloadedBufferOrErr.getError()) {
1001 // On error, keeping the preexisting buffer and printing a
1002 // diagnostic is more friendly than just crashing.
1003 errs() << "error: can't reload cached file '" << CacheEntryPath
1004 << "': " << EC.message() << "\n";
1005 } else {
1006 OutputBuffer = std::move(*ReloadedBufferOrErr);
1007 }
1008 }
1009 ProducedBinaries[count] = std::move(OutputBuffer);
1010 return;
1011 }
1012 ProducedBinaryFiles[count] = writeGeneratedObject(
1013 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001014 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001015 }
1016 }
1017
Peter Collingbournecead56f2017-03-15 22:54:18 +00001018 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001019
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001020 // If statistics were requested, print them out now.
1021 if (llvm::AreStatisticsEnabled())
1022 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +00001023 reportAndResetTimings();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001024}