blob: b793d0c9e3ea63f1bad74109d28e21c6bce64297 [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
Mehdi Aminif95f77a2016-04-21 05:54:23 +000017#ifdef HAVE_LLVM_REVISION
18#include "LLVMLTORevision.h"
19#endif
Mehdi Amini059464f2016-04-24 03:18:01 +000020
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000021#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000022#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000023#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000024#include "llvm/Analysis/ProfileSummaryInfo.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000027#include "llvm/Bitcode/BitcodeReader.h"
28#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000029#include "llvm/Bitcode/BitcodeWriterPass.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000030#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000031#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000032#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/IR/LegacyPassManager.h"
34#include "llvm/IR/Mangler.h"
35#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000036#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000037#include "llvm/Linker/Linker.h"
38#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000039#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000040#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000041#include "llvm/Support/CachePruning.h"
42#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000043#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000046#include "llvm/Support/TargetRegistry.h"
47#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000048#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000049#include "llvm/Support/ToolOutputFile.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000050#include "llvm/Target/TargetMachine.h"
51#include "llvm/Transforms/IPO.h"
52#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000053#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000054#include "llvm/Transforms/IPO/PassManagerBuilder.h"
55#include "llvm/Transforms/ObjCARC.h"
56#include "llvm/Transforms/Utils/FunctionImportUtils.h"
57
Mehdi Amini819e9cd2016-05-16 19:33:07 +000058#include <numeric>
59
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000060using namespace llvm;
61
Mehdi Amini1aafabf2016-04-16 07:02:16 +000062#define DEBUG_TYPE "thinlto"
63
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000064namespace llvm {
65// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
66extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000067extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000068extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000069}
70
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000071namespace {
72
Teresa Johnsonec544c52016-10-19 17:35:01 +000073static cl::opt<int>
74 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000075
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000076// Simple helper to save temporary files for debug.
77static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
78 unsigned count, StringRef Suffix) {
79 if (TempDir.empty())
80 return;
81 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000082 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000083 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000084 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000085 if (EC)
86 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
87 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000088 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000089}
90
Teresa Johnson4d2613f2016-05-24 17:24:25 +000091static const GlobalValueSummary *
92getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
93 // If there is any strong definition anywhere, get it.
94 auto StrongDefForLinker = llvm::find_if(
95 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
96 auto Linkage = Summary->linkage();
97 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
98 !GlobalValue::isWeakForLinker(Linkage);
99 });
100 if (StrongDefForLinker != GVSummaryList.end())
101 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000102 // Get the first *linker visible* definition for this global in the summary
103 // list.
104 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000105 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
106 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000107 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
108 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000109 // Extern templates can be emitted as available_externally.
110 if (FirstDefForLinker == GVSummaryList.end())
111 return nullptr;
112 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000113}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000114
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000115// Populate map of GUID to the prevailing copy for any multiply defined
116// symbols. Currently assume first copy is prevailing, or any strong
117// definition. Can be refined with Linker information in the future.
118static void computePrevailingCopies(
119 const ModuleSummaryIndex &Index,
120 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000121 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
122 return GVSummaryList.size() > 1;
123 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000124
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000125 for (auto &I : Index) {
126 if (HasMultipleCopies(I.second))
127 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000128 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000129}
130
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000131static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000132generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000133 StringMap<MemoryBufferRef> ModuleMap;
134 for (auto &ModuleBuffer : Modules) {
135 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
136 ModuleMap.end() &&
137 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000138 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000139 }
140 return ModuleMap;
141}
142
Teresa Johnson26ab5772016-03-15 00:04:37 +0000143static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000144 if (renameModuleForThinLTO(TheModule, Index))
145 report_fatal_error("renameModuleForThinLTO failed");
146}
147
Peter Collingbournedac43b42016-12-01 05:52:32 +0000148static std::unique_ptr<Module>
149loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000150 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000151 SMDiagnostic Err;
152 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000153 Lazy
154 ? getLazyBitcodeModule(Buffer, Context,
155 /* ShouldLazyLoadMetadata */ true, IsImporting)
156 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000157 if (!ModuleOrErr) {
158 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
159 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
160 SourceMgr::DK_Error, EIB.message());
161 Err.print("ThinLTO", errs());
162 });
163 report_fatal_error("Can't load module, abort.");
164 }
165 return std::move(ModuleOrErr.get());
166}
167
Mehdi Amini01e32132016-03-26 05:40:34 +0000168static void
169crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
170 StringMap<MemoryBufferRef> &ModuleMap,
171 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000172 auto Loader = [&](StringRef Identifier) {
173 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000174 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000175 };
176
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000177 FunctionImporter Importer(Index, Loader);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000178 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
179 if (!Result) {
180 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
181 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
182 SourceMgr::DK_Error, EIB.message());
183 Err.print("ThinLTO", errs());
184 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000185 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000186 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000187}
188
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000189static void optimizeModule(Module &TheModule, TargetMachine &TM,
190 unsigned OptLevel) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000191 // Populate the PassManager
192 PassManagerBuilder PMB;
193 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
194 PMB.Inliner = createFunctionInliningPass();
195 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000196 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000197 PMB.LoopVectorize = true;
198 PMB.SLPVectorize = true;
199 PMB.VerifyInput = true;
200 PMB.VerifyOutput = false;
201
202 legacy::PassManager PM;
203
204 // Add the TTI (required to inform the vectorizer about register size for
205 // instance)
206 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
207
208 // Add optimizations
209 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000210
211 PM.run(TheModule);
212}
213
Mehdi Amini059464f2016-04-24 03:18:01 +0000214// Convert the PreservedSymbols map from "Name" based to "GUID" based.
215static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000216computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
217 const Triple &TheTriple) {
218 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
219 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000220 StringRef Name = Entry.first();
221 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
222 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000223 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000224 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000225 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000226}
227
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000228std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
229 TargetMachine &TM) {
230 SmallVector<char, 128> OutputBuffer;
231
232 // CodeGen
233 {
234 raw_svector_ostream OS(OutputBuffer);
235 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000236
237 // If the bitcode files contain ARC code and were compiled with optimization,
238 // the ObjCARCContractPass must be run, so do it unconditionally here.
239 PM.add(createObjCARCContractPass());
240
241 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000242 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
243 /* DisableVerify */ true))
244 report_fatal_error("Failed to setup codegen");
245
246 // Run codegen now. resulting binary is in OutputBuffer.
247 PM.run(TheModule);
248 }
249 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
250}
251
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000252/// Manage caching for a single Module.
253class ModuleCacheEntry {
254 SmallString<128> EntryPath;
255
256public:
257 // Create a cache entry. This compute a unique hash for the Module considering
258 // the current list of export/import, and offer an interface to query to
259 // access the content in the cache.
260 ModuleCacheEntry(
261 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
262 const FunctionImporter::ImportMapTy &ImportList,
263 const FunctionImporter::ExportSetTy &ExportList,
264 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000265 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000266 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
267 const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000268 if (CachePath.empty())
269 return;
270
Mehdi Amini00fa1402016-10-08 04:44:18 +0000271 if (!Index.modulePaths().count(ModuleID))
272 // The module does not have an entry, it can't have a hash at all
273 return;
274
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000275 // Compute the unique hash for this entry
276 // This is based on the current compiler version, the module itself, the
277 // export list, the hash for every single module in the import list, the
278 // list of ResolvedODR for the module, and the list of preserved symbols.
279
Mehdi Aminif82bda02016-10-08 04:44:23 +0000280 // Include the hash for the current module
281 auto ModHash = Index.getModuleHash(ModuleID);
282
283 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
284 // No hash entry, no caching!
285 return;
286
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000287 SHA1 Hasher;
288
Mehdi Aminic92b6122017-01-10 00:55:47 +0000289 // Include the parts of the LTO configuration that affect code generation.
290 auto AddString = [&](StringRef Str) {
291 Hasher.update(Str);
292 Hasher.update(ArrayRef<uint8_t>{0});
293 };
294 auto AddUnsigned = [&](unsigned I) {
295 uint8_t Data[4];
296 Data[0] = I;
297 Data[1] = I >> 8;
298 Data[2] = I >> 16;
299 Data[3] = I >> 24;
300 Hasher.update(ArrayRef<uint8_t>{Data, 4});
301 };
302
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000303 // Start with the compiler revision
304 Hasher.update(LLVM_VERSION_STRING);
305#ifdef HAVE_LLVM_REVISION
306 Hasher.update(LLVM_REVISION);
307#endif
308
Mehdi Aminic92b6122017-01-10 00:55:47 +0000309 // Hash the optimization level and the target machine settings.
310 AddString(TMBuilder.MCpu);
311 // FIXME: Hash more of Options. For now all clients initialize Options from
312 // command-line flags (which is unsupported in production), but may set
313 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
314 // DataSections and DebuggerTuning via command line flags.
315 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
316 AddUnsigned(TMBuilder.Options.FunctionSections);
317 AddUnsigned(TMBuilder.Options.DataSections);
318 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
319 AddString(TMBuilder.MAttr);
320 if (TMBuilder.RelocModel)
321 AddUnsigned(*TMBuilder.RelocModel);
322 AddUnsigned(TMBuilder.CGOptLevel);
323 AddUnsigned(OptLevel);
324
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
351 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
352 }
353
Mehdi Amini059464f2016-04-24 03:18:01 +0000354 // Access the path to this entry in the cache.
355 StringRef getEntryPath() { return EntryPath; }
356
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000357 // Try loading the buffer for this cache entry.
358 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
359 if (EntryPath.empty())
360 return std::error_code();
361 return MemoryBuffer::getFile(EntryPath);
362 }
363
364 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000365 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000366 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000367 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000368
369 // Write to a temporary to avoid race condition
370 SmallString<128> TempFilename;
371 int TempFD;
372 std::error_code EC =
373 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
374 if (EC) {
375 errs() << "Error: " << EC.message() << "\n";
376 report_fatal_error("ThinLTO: Can't get a temporary file");
377 }
378 {
379 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000380 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000381 }
382 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000383 EC = sys::fs::rename(TempFilename, EntryPath);
384 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000385 sys::fs::remove(TempFilename);
386 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
387 if (EC)
388 report_fatal_error(Twine("Failed to open ") + EntryPath +
389 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000390 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000391 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000392 }
393};
394
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000395static std::unique_ptr<MemoryBuffer>
396ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
397 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
398 const FunctionImporter::ImportMapTy &ImportList,
399 const FunctionImporter::ExportSetTy &ExportList,
400 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
401 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000402 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000403 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000404 unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000405
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000406 // "Benchmark"-like optimization: single-source case
407 bool SingleModule = (ModuleMap.size() == 1);
408
409 if (!SingleModule) {
410 promoteModule(TheModule, Index);
411
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000412 // Apply summary-based LinkOnce/Weak resolution decisions.
413 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000414
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000415 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000416 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000417 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000418
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000419 // Be friendly and don't nuke totally the module when the client didn't
420 // supply anything to preserve.
421 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
422 // Apply summary-based internalization decisions.
423 thinLTOInternalizeModule(TheModule, DefinedGlobals);
424 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000425
426 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000427 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000428
429 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000430 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000431
432 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000433 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000434 }
435
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000436 optimizeModule(TheModule, TM, OptLevel);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000437
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000438 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000439
Mehdi Amini43b657b2016-04-01 06:47:02 +0000440 if (DisableCodeGen) {
441 // Configured to stop before CodeGen, serialize the bitcode and return.
442 SmallVector<char, 128> OutputBuffer;
443 {
444 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000445 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000446 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000447 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000448 }
449 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
450 }
451
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000452 return codegenModule(TheModule, TM);
453}
454
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000455/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
456/// for caching, and in the \p Index for application during the ThinLTO
457/// backends. This is needed for correctness for exported symbols (ensure
458/// at least one copy kept) and a compile-time optimization (to drop duplicate
459/// copies when possible).
460static void resolveWeakForLinkerInIndex(
461 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000462 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
463 &ResolvedODR) {
464
465 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
466 computePrevailingCopies(Index, PrevailingCopy);
467
468 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
469 const auto &Prevailing = PrevailingCopy.find(GUID);
470 // Not in map means that there was only one copy, which must be prevailing.
471 if (Prevailing == PrevailingCopy.end())
472 return true;
473 return Prevailing->second == S;
474 };
475
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000476 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
477 GlobalValue::GUID GUID,
478 GlobalValue::LinkageTypes NewLinkage) {
479 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
480 };
481
Peter Collingbourne73589f32016-07-07 18:31:51 +0000482 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000483}
484
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000485// Initialize the TargetMachine builder for a given Triple
486static void initTMBuilder(TargetMachineBuilder &TMBuilder,
487 const Triple &TheTriple) {
488 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
489 // FIXME this looks pretty terrible...
490 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
491 if (TheTriple.getArch() == llvm::Triple::x86_64)
492 TMBuilder.MCpu = "core2";
493 else if (TheTriple.getArch() == llvm::Triple::x86)
494 TMBuilder.MCpu = "yonah";
495 else if (TheTriple.getArch() == llvm::Triple::aarch64)
496 TMBuilder.MCpu = "cyclone";
497 }
498 TMBuilder.TheTriple = std::move(TheTriple);
499}
500
501} // end anonymous namespace
502
503void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000504 ThinLTOBuffer Buffer(Data, Identifier);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000505 if (Modules.empty()) {
506 // First module added, so initialize the triple and some options
507 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000508 StringRef TripleStr;
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000509 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
510 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
Peter Collingbournecd513a42016-11-11 19:50:24 +0000511 if (TripleOrErr)
512 TripleStr = *TripleOrErr;
513 Triple TheTriple(TripleStr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000514 initTMBuilder(TMBuilder, Triple(TheTriple));
515 }
516#ifndef NDEBUG
517 else {
518 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000519 StringRef TripleStr;
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000520 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
521 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
Peter Collingbournecd513a42016-11-11 19:50:24 +0000522 if (TripleOrErr)
523 TripleStr = *TripleOrErr;
524 assert(TMBuilder.TheTriple.str() == TripleStr &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000525 "ThinLTO modules with different triple not supported");
526 }
527#endif
528 Modules.push_back(Buffer);
529}
530
531void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
532 PreservedSymbols.insert(Name);
533}
534
535void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000536 // FIXME: At the moment, we don't take advantage of this extra information,
537 // we're conservatively considering cross-references as preserved.
538 // CrossReferencedSymbols.insert(Name);
539 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000540}
541
542// TargetMachine factory
543std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
544 std::string ErrMsg;
545 const Target *TheTarget =
546 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
547 if (!TheTarget) {
548 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
549 }
550
551 // Use MAttr as the default set of features.
552 SubtargetFeatures Features(MAttr);
553 Features.getDefaultSubtargetFeatures(TheTriple);
554 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000555
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000556 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
557 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
558 CodeModel::Default, CGOptLevel));
559}
560
561/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000562 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000563 * "thin-link".
564 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000565std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
566 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000567 uint64_t NextModuleId = 0;
568 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000569 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000570 object::ModuleSummaryIndexObjectFile::create(
571 ModuleBuffer.getMemBuffer());
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000572 if (!ObjOrErr) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000573 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000574 logAllUnhandledErrors(
575 ObjOrErr.takeError(), errs(),
576 "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000577 return nullptr;
578 }
579 auto Index = (*ObjOrErr)->takeIndex();
580 if (CombinedIndex) {
581 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
582 } else {
583 CombinedIndex = std::move(Index);
584 }
585 }
586 return CombinedIndex;
587}
588
589/**
590 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000591 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000592 */
593void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000594 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000595 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000596 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000597
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000598 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000599 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000600 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000601
Teresa Johnson6c475a72017-01-05 21:34:18 +0000602 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000603 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000604 PreservedSymbols, Triple(TheModule.getTargetTriple()));
605
606 // Compute "dead" symbols, we don't want to import/export these!
607 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
608
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000609 // Generate import/export list
610 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
611 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
612 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000613 ExportLists, &DeadSymbols);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000614
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000615 // Resolve LinkOnce/Weak symbols.
616 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000617 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000618
619 thinLTOResolveWeakForLinkerModule(
620 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000621
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000622 // Promote the exported values in the index, so that they are promoted
623 // in the module.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000624 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000625 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000626 return (ExportList != ExportLists.end() &&
627 ExportList->second.count(GUID)) ||
628 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000629 };
630 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
631
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000632 promoteModule(TheModule, Index);
633}
634
635/**
636 * Perform cross-module importing for the module identified by ModuleIdentifier.
637 */
638void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000639 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000640 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000641 auto ModuleCount = Index.modulePaths().size();
642
643 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000644 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000645 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000646
Teresa Johnson6c475a72017-01-05 21:34:18 +0000647 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000648 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000649 PreservedSymbols, Triple(TheModule.getTargetTriple()));
650
651 // Compute "dead" symbols, we don't want to import/export these!
652 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
653
Mehdi Amini01e32132016-03-26 05:40:34 +0000654 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000655 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
656 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000657 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000658 ExportLists, &DeadSymbols);
Mehdi Amini01e32132016-03-26 05:40:34 +0000659 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
660
661 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000662}
663
664/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000665 * Compute the list of summaries needed for importing into module.
666 */
667void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
668 StringRef ModulePath, ModuleSummaryIndex &Index,
669 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
670 auto ModuleCount = Index.modulePaths().size();
671
672 // Collect for each module the list of function it defines (GUID -> Summary).
673 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
674 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
675
676 // Generate import/export list
677 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
678 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
679 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
680 ExportLists);
681
682 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000683 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000684 ModuleToSummariesForIndex);
685}
686
687/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000688 * Emit the list of files needed for importing into module.
689 */
690void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
691 StringRef OutputName,
692 ModuleSummaryIndex &Index) {
693 auto ModuleCount = Index.modulePaths().size();
694
695 // Collect for each module the list of function it defines (GUID -> Summary).
696 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
697 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
698
699 // Generate import/export list
700 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
701 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
702 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
703 ExportLists);
704
705 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000706 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000707 report_fatal_error(Twine("Failed to open ") + OutputName +
708 " to save imports lists\n");
709}
710
711/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000712 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000713 */
714void ThinLTOCodeGenerator::internalize(Module &TheModule,
715 ModuleSummaryIndex &Index) {
716 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
717 auto ModuleCount = Index.modulePaths().size();
718 auto ModuleIdentifier = TheModule.getModuleIdentifier();
719
720 // Convert the preserved symbols set from string to GUID
721 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000722 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000723
724 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000725 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000726 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
727
Teresa Johnson6c475a72017-01-05 21:34:18 +0000728 // Compute "dead" symbols, we don't want to import/export these!
729 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
730
Mehdi Amini059464f2016-04-24 03:18:01 +0000731 // Generate import/export list
732 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
733 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
734 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000735 ExportLists, &DeadSymbols);
Mehdi Amini059464f2016-04-24 03:18:01 +0000736 auto &ExportList = ExportLists[ModuleIdentifier];
737
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000738 // Be friendly and don't nuke totally the module when the client didn't
739 // supply anything to preserve.
740 if (ExportList.empty() && GUIDPreservedSymbols.empty())
741 return;
742
Mehdi Amini059464f2016-04-24 03:18:01 +0000743 // Internalization
Mehdi Amini1380edf2017-02-03 07:41:43 +0000744 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000745 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000746 return (ExportList != ExportLists.end() &&
747 ExportList->second.count(GUID)) ||
748 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000749 };
750 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
751 thinLTOInternalizeModule(TheModule,
752 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000753}
754
755/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000756 * Perform post-importing ThinLTO optimizations.
757 */
758void ThinLTOCodeGenerator::optimize(Module &TheModule) {
759 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000760
761 // Optimize now
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000762 optimizeModule(TheModule, *TMBuilder.create(), OptLevel);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000763}
764
765/**
766 * Perform ThinLTO CodeGen.
767 */
768std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
769 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
770 return codegenModule(TheModule, *TMBuilder.create());
771}
772
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000773/// Write out the generated object file, either from CacheEntryPath or from
774/// OutputBuffer, preferring hard-link when possible.
775/// Returns the path to the generated file in SavedObjectsDirectoryPath.
776static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
777 StringRef SavedObjectsDirectoryPath,
778 const MemoryBuffer &OutputBuffer) {
779 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
780 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
781 OutputPath.c_str(); // Ensure the string is null terminated.
782 if (sys::fs::exists(OutputPath))
783 sys::fs::remove(OutputPath);
784
785 // We don't return a memory buffer to the linker, just a list of files.
786 if (!CacheEntryPath.empty()) {
787 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
788 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
789 if (!Err)
790 return OutputPath.str();
791 // Hard linking failed, try to copy.
792 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
793 if (!Err)
794 return OutputPath.str();
795 // Copy failed (could be because the CacheEntry was removed from the cache
796 // in the meantime by another process), fall back and try to write down the
797 // buffer to the output.
798 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
799 << "' to '" << OutputPath << "'\n";
800 }
801 // No cache entry, just write out the buffer.
802 std::error_code Err;
803 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
804 if (Err)
805 report_fatal_error("Can't open output '" + OutputPath + "'\n");
806 OS << OutputBuffer.getBuffer();
807 return OutputPath.str();
808}
809
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000810// Main entry point for the ThinLTO processing
811void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000812 // Prepare the resulting object vector
813 assert(ProducedBinaries.empty() && "The generator should not be reused");
814 if (SavedObjectsDirectoryPath.empty())
815 ProducedBinaries.resize(Modules.size());
816 else {
817 sys::fs::create_directories(SavedObjectsDirectoryPath);
818 bool IsDir;
819 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
820 if (!IsDir)
821 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
822 ProducedBinaryFiles.resize(Modules.size());
823 }
824
Mehdi Amini43b657b2016-04-01 06:47:02 +0000825 if (CodeGenOnly) {
826 // Perform only parallel codegen and return.
827 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000828 int count = 0;
829 for (auto &ModuleBuffer : Modules) {
830 Pool.async([&](int count) {
831 LLVMContext Context;
832 Context.setDiscardValueNames(LTODiscardValueNames);
833
834 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000835 auto TheModule =
836 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
837 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000838
839 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000840 auto OutputBuffer = codegen(*TheModule);
841 if (SavedObjectsDirectoryPath.empty())
842 ProducedBinaries[count] = std::move(OutputBuffer);
843 else
844 ProducedBinaryFiles[count] = writeGeneratedObject(
845 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000846 }, count++);
847 }
848
849 return;
850 }
851
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000852 // Sequential linking phase
853 auto Index = linkCombinedIndex();
854
855 // Save temps: index.
856 if (!SaveTempsDir.empty()) {
857 auto SaveTempPath = SaveTempsDir + "index.bc";
858 std::error_code EC;
859 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
860 if (EC)
861 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
862 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000863 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000864 }
865
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000866
867 // Prepare the module map.
868 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000869 auto ModuleCount = Modules.size();
870
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000871 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000872 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000873 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
874
Teresa Johnson6c475a72017-01-05 21:34:18 +0000875 // Convert the preserved symbols set from string to GUID, this is needed for
876 // computing the caching hash and the internalization.
877 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000878 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000879
880 // Compute "dead" symbols, we don't want to import/export these!
881 auto DeadSymbols = computeDeadSymbols(*Index, GUIDPreservedSymbols);
882
Mehdi Amini01e32132016-03-26 05:40:34 +0000883 // Collect the import/export lists for all modules from the call-graph in the
884 // combined index.
885 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
886 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000887 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000888 ExportLists, &DeadSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000889
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000890 // We use a std::map here to be able to have a defined ordering when
891 // producing a hash for the cache entry.
892 // FIXME: we should be able to compute the caching hash for the entry based
893 // on the index, and nuke this map.
894 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
895
896 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
897 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000898 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000899
Mehdi Amini1380edf2017-02-03 07:41:43 +0000900 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000901 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000902 return (ExportList != ExportLists.end() &&
903 ExportList->second.count(GUID)) ||
904 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000905 };
906
907 // Use global summary-based analysis to identify symbols that can be
908 // internalized (because they aren't exported or preserved as per callback).
909 // Changes are made in the index, consumed in the ThinLTO backends.
910 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
911
Teresa Johnson141149f2016-05-24 18:44:01 +0000912 // Make sure that every module has an entry in the ExportLists and
913 // ResolvedODR maps to enable threaded access to these maps below.
914 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000915 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000916 ResolvedODR[DefinedGVSummaries.first()];
917 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000918
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000919 // Compute the ordering we will process the inputs: the rough heuristic here
920 // is to sort them per size so that the largest module get schedule as soon as
921 // possible. This is purely a compile-time optimization.
922 std::vector<int> ModulesOrdering;
923 ModulesOrdering.resize(Modules.size());
924 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
925 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
926 [&](int LeftIndex, int RightIndex) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000927 auto LSize = Modules[LeftIndex].getBuffer().size();
928 auto RSize = Modules[RightIndex].getBuffer().size();
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000929 return LSize > RSize;
930 });
931
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000932 // Parallel optimizer + codegen
933 {
934 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000935 for (auto IndexCount : ModulesOrdering) {
936 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000937 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000938 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000939 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000940
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000941 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
942
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000943 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000944 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
945 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000946 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000947 DefinedFunctions, GUIDPreservedSymbols,
948 OptLevel, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000949 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000950
951 {
952 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000953 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000954 << CacheEntryPath << "' for buffer " << count << " "
955 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000956
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000957 if (ErrOrBuffer) {
958 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000959 if (SavedObjectsDirectoryPath.empty())
960 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
961 else
962 ProducedBinaryFiles[count] = writeGeneratedObject(
963 count, CacheEntryPath, SavedObjectsDirectoryPath,
964 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000965 return;
966 }
967 }
968
969 LLVMContext Context;
970 Context.setDiscardValueNames(LTODiscardValueNames);
971 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000972 auto DiagFileOrErr = lto::setupOptimizationRemarks(
973 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000974 if (!DiagFileOrErr) {
975 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
976 report_fatal_error("ThinLTO: Can't get an output file for the "
977 "remarks");
978 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000979
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000980 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000981 auto TheModule =
982 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
983 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000984
985 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000986 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000987
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000988 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000989 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000990 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000991 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000992 ExportList, GUIDPreservedSymbols,
993 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000994 DisableCodeGen, SaveTempsDir, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000995
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000996 // Commit to the cache (if enabled)
997 CacheEntry.write(*OutputBuffer);
998
999 if (SavedObjectsDirectoryPath.empty()) {
1000 // We need to generated a memory buffer for the linker.
1001 if (!CacheEntryPath.empty()) {
1002 // Cache is enabled, reload from the cache
1003 // We do this to lower memory pressuree: the buffer is on the heap
1004 // and releasing it frees memory that can be used for the next input
1005 // file. The final binary link will read from the VFS cache
1006 // (hopefully!) or from disk if the memory pressure wasn't too high.
1007 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1008 if (auto EC = ReloadedBufferOrErr.getError()) {
1009 // On error, keeping the preexisting buffer and printing a
1010 // diagnostic is more friendly than just crashing.
1011 errs() << "error: can't reload cached file '" << CacheEntryPath
1012 << "': " << EC.message() << "\n";
1013 } else {
1014 OutputBuffer = std::move(*ReloadedBufferOrErr);
1015 }
1016 }
1017 ProducedBinaries[count] = std::move(OutputBuffer);
1018 return;
1019 }
1020 ProducedBinaryFiles[count] = writeGeneratedObject(
1021 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001022 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001023 }
1024 }
1025
Peter Collingbournecead56f2017-03-15 22:54:18 +00001026 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001027
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001028 // If statistics were requested, print them out now.
1029 if (llvm::AreStatisticsEnabled())
1030 llvm::PrintStatistics();
1031}