blob: 5c74d72c25a3e3818a8e38adf0bd189580caf11b [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
15#include "llvm/LTO/ThinLTOCodeGenerator.h"
16
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
21#include "UpdateCompilerUsed.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000022#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000023#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000024#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000027#include "llvm/Bitcode/BitcodeWriterPass.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/Bitcode/ReaderWriter.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000029#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000030#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000031#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000032#include "llvm/IR/LegacyPassManager.h"
33#include "llvm/IR/Mangler.h"
34#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000035#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000036#include "llvm/Linker/Linker.h"
37#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000038#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000039#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000040#include "llvm/Support/CachePruning.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/ThreadPool.h"
46#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;
63}
64
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000065namespace {
66
67static cl::opt<int> ThreadCount("threads",
68 cl::init(std::thread::hardware_concurrency()));
69
70static void diagnosticHandler(const DiagnosticInfo &DI) {
71 DiagnosticPrinterRawOStream DP(errs());
72 DI.print(DP);
73 errs() << '\n';
74}
75
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.
82 auto SaveTempPath = TempDir + llvm::utostr(count) + Suffix;
83 std::error_code EC;
84 raw_fd_ostream OS(SaveTempPath.str(), EC, sys::fs::F_None);
85 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
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000131static void thinLTOResolveWeakForLinkerGUID(
132 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
133 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
134 std::function<bool(GlobalValue::GUID, const GlobalValueSummary *)>
135 isPrevailing,
136 std::function<bool(StringRef, GlobalValue::GUID)> isExported,
137 std::function<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
138 recordNewLinkage) {
139 auto HasMultipleCopies = GVSummaryList.size() > 1;
140
141 for (auto &S : GVSummaryList) {
142 if (GlobalInvolvedWithAlias.count(S.get()))
143 continue;
144 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
145 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
146 continue;
147 // We need to emit only one of these, the first module will keep it,
148 // but turned into a weak, while the others will drop it when possible.
149 if (!HasMultipleCopies) {
150 // Exported Linkonce needs to be promoted to not be discarded.
151 // FIXME: This should handle LinkOnceAny as well, but that should be a
152 // follow-on to the NFC restructuring:
153 // if (GlobalValue::isLinkOnceLinkage(OriginalLinkage) &&
154 // isExported(S->modulePath(), GUID))
155 // S->setLinkage(GlobalValue::getWeakLinkage(
156 // GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
157 if (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) &&
158 isExported(S->modulePath(), GUID))
159 S->setLinkage(GlobalValue::WeakODRLinkage);
160 } else if (isPrevailing(GUID, S.get())) {
161 // FIXME: This should handle LinkOnceAny as well, but that should be a
162 // follow-on to the NFC restructuring:
163 // if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
164 // S->setLinkage(GlobalValue::getWeakLinkage(
165 // GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
166 if (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage))
167 S->setLinkage(GlobalValue::WeakODRLinkage);
168 }
169 // Alias can't be turned into available_externally.
170 else if (!isa<AliasSummary>(S.get()) &&
171 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
172 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
173 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
174 if (S->linkage() != OriginalLinkage)
175 recordNewLinkage(S->modulePath(), GUID, S->linkage());
176 }
177}
178
179// Resolve Weak and LinkOnce values in the \p Index.
180//
181// We'd like to drop these functions if they are no longer referenced in the
182// current module. However there is a chance that another module is still
183// referencing them because of the import. We make sure we always emit at least
184// one copy.
185void thinLTOResolveWeakForLinkerInIndex(
186 ModuleSummaryIndex &Index,
187 std::function<bool(GlobalValue::GUID, const GlobalValueSummary *)>
188 isPrevailing,
189 std::function<bool(StringRef, GlobalValue::GUID)> isExported,
190 std::function<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
191 recordNewLinkage) {
Mehdi Amini8dcc8082016-04-14 08:46:22 +0000192 if (Index.modulePaths().size() == 1)
193 // Nothing to do if we don't have multiple modules
194 return;
195
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000196 // We won't optimize the globals that are referenced by an alias for now
197 // Ideally we should turn the alias into a global and duplicate the definition
198 // when needed.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000199 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000200 for (auto &I : Index)
201 for (auto &S : I.second)
202 if (auto AS = dyn_cast<AliasSummary>(S.get()))
203 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000204
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000205 for (auto &I : Index)
206 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
207 isPrevailing, isExported, recordNewLinkage);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000208}
209
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000210/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
211void thinLTOResolveWeakForLinkerModule(Module &TheModule,
212 const GVSummaryMapTy &DefinedGlobals) {
213 auto updateLinkage = [&](GlobalValue &GV) {
214 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
215 return;
216 // See if the global summary analysis computed a new resolved linkage.
217 const auto &GS = DefinedGlobals.find(GV.getGUID());
218 if (GS == DefinedGlobals.end())
219 return;
220 auto NewLinkage = GS->second->linkage();
221 if (NewLinkage == GV.getLinkage())
222 return;
223 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
224 << GV.getLinkage() << " to " << NewLinkage << "\n");
225 GV.setLinkage(NewLinkage);
226 };
227
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000228 // Process functions and global now
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000229 for (auto &GV : TheModule)
230 updateLinkage(GV);
231 for (auto &GV : TheModule.globals())
232 updateLinkage(GV);
233 for (auto &GV : TheModule.aliases())
234 updateLinkage(GV);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000235}
236
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000237static StringMap<MemoryBufferRef>
238generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
239 StringMap<MemoryBufferRef> ModuleMap;
240 for (auto &ModuleBuffer : Modules) {
241 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
242 ModuleMap.end() &&
243 "Expect unique Buffer Identifier");
244 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
245 }
246 return ModuleMap;
247}
248
Teresa Johnson26ab5772016-03-15 00:04:37 +0000249static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000250 if (renameModuleForThinLTO(TheModule, Index))
251 report_fatal_error("renameModuleForThinLTO failed");
252}
253
Mehdi Amini01e32132016-03-26 05:40:34 +0000254static void
255crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
256 StringMap<MemoryBufferRef> &ModuleMap,
257 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000258 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
259 FunctionImporter Importer(Index, Loader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000260 Importer.importFunctions(TheModule, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000261}
262
263static void optimizeModule(Module &TheModule, TargetMachine &TM) {
264 // Populate the PassManager
265 PassManagerBuilder PMB;
266 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
267 PMB.Inliner = createFunctionInliningPass();
268 // FIXME: should get it from the bitcode?
269 PMB.OptLevel = 3;
270 PMB.LoopVectorize = true;
271 PMB.SLPVectorize = true;
272 PMB.VerifyInput = true;
273 PMB.VerifyOutput = false;
274
275 legacy::PassManager PM;
276
277 // Add the TTI (required to inform the vectorizer about register size for
278 // instance)
279 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
280
281 // Add optimizations
282 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000283
284 PM.run(TheModule);
285}
286
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000287static void thinLTOInternalizeAndPromoteGUID(
288 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
289 std::function<bool(StringRef, GlobalValue::GUID)> isExported) {
290 for (auto &S : GVSummaryList) {
291 if (isExported(S->modulePath(), GUID)) {
292 if (GlobalValue::isLocalLinkage(S->linkage()))
293 S->setLinkage(GlobalValue::ExternalLinkage);
294 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
295 S->setLinkage(GlobalValue::InternalLinkage);
296 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000297}
298
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000299// Update the linkages in the given \p Index to mark exported values
300// as external and non-exported values as internal.
301void thinLTOInternalizeAndPromoteInIndex(
302 ModuleSummaryIndex &Index,
303 std::function<bool(StringRef, GlobalValue::GUID)> isExported) {
304 for (auto &I : Index)
305 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
306}
Mehdi Amini059464f2016-04-24 03:18:01 +0000307
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000308// Run internalization on \p TheModule based on symmary analysis.
309void thinLTOInternalizeModule(Module &TheModule,
310 const GVSummaryMapTy &DefinedGlobals) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000311 // Parse inline ASM and collect the list of symbols that are not defined in
312 // the current module.
313 StringSet<> AsmUndefinedRefs;
314 object::IRObjectFile::CollectAsmUndefinedRefs(
315 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
316 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
317 if (Flags & object::BasicSymbolRef::SF_Undefined)
318 AsmUndefinedRefs.insert(Name);
319 });
320
Mehdi Amini059464f2016-04-24 03:18:01 +0000321 // Declare a callback for the internalize pass that will ask for every
322 // candidate GlobalValue if it can be internalized or not.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000323 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
324 // Can't be internalized if referenced in inline asm.
325 if (AsmUndefinedRefs.count(GV.getName()))
326 return true;
Mehdi Amini059464f2016-04-24 03:18:01 +0000327
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000328 // Lookup the linkage recorded in the summaries during global analysis.
329 const auto &GS = DefinedGlobals.find(GV.getGUID());
330 GlobalValue::LinkageTypes Linkage;
331 if (GS == DefinedGlobals.end()) {
332 // Must have been promoted (possibly conservatively). Find original
333 // name so that we can access the correct summary and see if it can
334 // be internalized again.
335 // FIXME: Eventually we should control promotion instead of promoting
336 // and internalizing again.
337 StringRef OrigName =
338 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
339 std::string OrigId = GlobalValue::getGlobalIdentifier(
340 OrigName, GlobalValue::InternalLinkage,
341 TheModule.getSourceFileName());
342 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
343 assert(GS != DefinedGlobals.end());
344 Linkage = GS->second->linkage();
345 } else
346 Linkage = GS->second->linkage();
347 return !GlobalValue::isLocalLinkage(Linkage);
348 };
349
350 // FIXME: See if we can just internalize directly here via linkage changes
351 // based on the index, rather than invoking internalizeModule.
Mehdi Amini059464f2016-04-24 03:18:01 +0000352 llvm::internalizeModule(TheModule, MustPreserveGV);
353}
354
355// Convert the PreservedSymbols map from "Name" based to "GUID" based.
356static DenseSet<GlobalValue::GUID>
357computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
358 const Triple &TheTriple) {
359 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
360 for (auto &Entry : PreservedSymbols) {
361 StringRef Name = Entry.first();
362 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
363 Name = Name.drop_front();
364 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
365 }
366 return GUIDPreservedSymbols;
367}
368
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000369std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
370 TargetMachine &TM) {
371 SmallVector<char, 128> OutputBuffer;
372
373 // CodeGen
374 {
375 raw_svector_ostream OS(OutputBuffer);
376 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000377
378 // If the bitcode files contain ARC code and were compiled with optimization,
379 // the ObjCARCContractPass must be run, so do it unconditionally here.
380 PM.add(createObjCARCContractPass());
381
382 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000383 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
384 /* DisableVerify */ true))
385 report_fatal_error("Failed to setup codegen");
386
387 // Run codegen now. resulting binary is in OutputBuffer.
388 PM.run(TheModule);
389 }
390 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
391}
392
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000393/// Manage caching for a single Module.
394class ModuleCacheEntry {
395 SmallString<128> EntryPath;
396
397public:
398 // Create a cache entry. This compute a unique hash for the Module considering
399 // the current list of export/import, and offer an interface to query to
400 // access the content in the cache.
401 ModuleCacheEntry(
402 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
403 const FunctionImporter::ImportMapTy &ImportList,
404 const FunctionImporter::ExportSetTy &ExportList,
405 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000406 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000407 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
408 if (CachePath.empty())
409 return;
410
411 // Compute the unique hash for this entry
412 // This is based on the current compiler version, the module itself, the
413 // export list, the hash for every single module in the import list, the
414 // list of ResolvedODR for the module, and the list of preserved symbols.
415
416 SHA1 Hasher;
417
418 // Start with the compiler revision
419 Hasher.update(LLVM_VERSION_STRING);
420#ifdef HAVE_LLVM_REVISION
421 Hasher.update(LLVM_REVISION);
422#endif
423
424 // Include the hash for the current module
425 auto ModHash = Index.getModuleHash(ModuleID);
426 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
427 for (auto F : ExportList)
428 // The export list can impact the internalization, be conservative here
429 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
430
431 // Include the hash for every module we import functions from
432 for (auto &Entry : ImportList) {
433 auto ModHash = Index.getModuleHash(Entry.first());
434 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
435 }
436
437 // Include the hash for the resolved ODR.
438 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000439 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000440 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000441 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000442 sizeof(GlobalValue::LinkageTypes)));
443 }
444
445 // Include the hash for the preserved symbols.
446 for (auto &Entry : PreservedSymbols) {
447 if (DefinedFunctions.count(Entry))
448 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000449 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000450 }
451
452 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
453 }
454
Mehdi Amini059464f2016-04-24 03:18:01 +0000455 // Access the path to this entry in the cache.
456 StringRef getEntryPath() { return EntryPath; }
457
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000458 // Try loading the buffer for this cache entry.
459 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
460 if (EntryPath.empty())
461 return std::error_code();
462 return MemoryBuffer::getFile(EntryPath);
463 }
464
465 // Cache the Produced object file
Mehdi Amini001bb412016-05-16 19:11:59 +0000466 std::unique_ptr<MemoryBuffer>
467 write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000468 if (EntryPath.empty())
Mehdi Amini001bb412016-05-16 19:11:59 +0000469 return OutputBuffer;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000470
471 // Write to a temporary to avoid race condition
472 SmallString<128> TempFilename;
473 int TempFD;
474 std::error_code EC =
475 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
476 if (EC) {
477 errs() << "Error: " << EC.message() << "\n";
478 report_fatal_error("ThinLTO: Can't get a temporary file");
479 }
480 {
481 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini001bb412016-05-16 19:11:59 +0000482 OS << OutputBuffer->getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000483 }
484 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000485 EC = sys::fs::rename(TempFilename, EntryPath);
486 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000487 sys::fs::remove(TempFilename);
488 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
489 if (EC)
490 report_fatal_error(Twine("Failed to open ") + EntryPath +
491 " to save cached entry\n");
Mehdi Amini001bb412016-05-16 19:11:59 +0000492 OS << OutputBuffer->getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000493 }
Mehdi Amini001bb412016-05-16 19:11:59 +0000494 auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
495 if (auto EC = ReloadedBufferOrErr.getError()) {
496 // FIXME diagnose
497 errs() << "error: can't reload cached file '" << EntryPath
498 << "': " << EC.message() << "\n";
499 return OutputBuffer;
500 }
501 return std::move(*ReloadedBufferOrErr);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000502 }
503};
504
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000505static std::unique_ptr<MemoryBuffer>
506ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
507 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
508 const FunctionImporter::ImportMapTy &ImportList,
509 const FunctionImporter::ExportSetTy &ExportList,
510 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
511 const GVSummaryMapTy &DefinedGlobals,
512 ThinLTOCodeGenerator::CachingOptions CacheOptions,
513 bool DisableCodeGen, StringRef SaveTempsDir,
514 unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000515
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000516 // "Benchmark"-like optimization: single-source case
517 bool SingleModule = (ModuleMap.size() == 1);
518
519 if (!SingleModule) {
520 promoteModule(TheModule, Index);
521
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000522 // Apply summary-based LinkOnce/Weak resolution decisions.
523 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000524
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000525 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000526 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000527 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000528
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000529 // Be friendly and don't nuke totally the module when the client didn't
530 // supply anything to preserve.
531 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
532 // Apply summary-based internalization decisions.
533 thinLTOInternalizeModule(TheModule, DefinedGlobals);
534 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000535
536 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000537 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000538
539 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000540 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000541
542 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000543 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000544 }
545
546 optimizeModule(TheModule, TM);
547
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000548 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000549
Mehdi Amini43b657b2016-04-01 06:47:02 +0000550 if (DisableCodeGen) {
551 // Configured to stop before CodeGen, serialize the bitcode and return.
552 SmallVector<char, 128> OutputBuffer;
553 {
554 raw_svector_ostream OS(OutputBuffer);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000555 ModuleSummaryIndexBuilder IndexBuilder(&TheModule);
556 WriteBitcodeToFile(&TheModule, OS, true, &IndexBuilder.getIndex());
Mehdi Amini43b657b2016-04-01 06:47:02 +0000557 }
558 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
559 }
560
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000561 return codegenModule(TheModule, TM);
562}
563
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000564/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
565/// for caching, and in the \p Index for application during the ThinLTO
566/// backends. This is needed for correctness for exported symbols (ensure
567/// at least one copy kept) and a compile-time optimization (to drop duplicate
568/// copies when possible).
569static void resolveWeakForLinkerInIndex(
570 ModuleSummaryIndex &Index,
571 const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
572 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
573 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
574 &ResolvedODR) {
575
576 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
577 computePrevailingCopies(Index, PrevailingCopy);
578
579 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
580 const auto &Prevailing = PrevailingCopy.find(GUID);
581 // Not in map means that there was only one copy, which must be prevailing.
582 if (Prevailing == PrevailingCopy.end())
583 return true;
584 return Prevailing->second == S;
585 };
586
587 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
588 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000589 return (ExportList != ExportLists.end() &&
590 ExportList->second.count(GUID)) ||
591 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000592 };
593
594 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
595 GlobalValue::GUID GUID,
596 GlobalValue::LinkageTypes NewLinkage) {
597 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
598 };
599
600 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, isExported,
601 recordNewLinkage);
602}
603
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000604// Initialize the TargetMachine builder for a given Triple
605static void initTMBuilder(TargetMachineBuilder &TMBuilder,
606 const Triple &TheTriple) {
607 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
608 // FIXME this looks pretty terrible...
609 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
610 if (TheTriple.getArch() == llvm::Triple::x86_64)
611 TMBuilder.MCpu = "core2";
612 else if (TheTriple.getArch() == llvm::Triple::x86)
613 TMBuilder.MCpu = "yonah";
614 else if (TheTriple.getArch() == llvm::Triple::aarch64)
615 TMBuilder.MCpu = "cyclone";
616 }
617 TMBuilder.TheTriple = std::move(TheTriple);
618}
619
620} // end anonymous namespace
621
622void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
623 MemoryBufferRef Buffer(Data, Identifier);
624 if (Modules.empty()) {
625 // First module added, so initialize the triple and some options
626 LLVMContext Context;
627 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
628 initTMBuilder(TMBuilder, Triple(TheTriple));
629 }
630#ifndef NDEBUG
631 else {
632 LLVMContext Context;
633 assert(TMBuilder.TheTriple.str() ==
634 getBitcodeTargetTriple(Buffer, Context) &&
635 "ThinLTO modules with different triple not supported");
636 }
637#endif
638 Modules.push_back(Buffer);
639}
640
641void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
642 PreservedSymbols.insert(Name);
643}
644
645void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000646 // FIXME: At the moment, we don't take advantage of this extra information,
647 // we're conservatively considering cross-references as preserved.
648 // CrossReferencedSymbols.insert(Name);
649 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000650}
651
652// TargetMachine factory
653std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
654 std::string ErrMsg;
655 const Target *TheTarget =
656 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
657 if (!TheTarget) {
658 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
659 }
660
661 // Use MAttr as the default set of features.
662 SubtargetFeatures Features(MAttr);
663 Features.getDefaultSubtargetFeatures(TheTriple);
664 std::string FeatureStr = Features.getString();
665 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
666 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
667 CodeModel::Default, CGOptLevel));
668}
669
670/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000671 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000672 * "thin-link".
673 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000674std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
675 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000676 uint64_t NextModuleId = 0;
677 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000678 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
679 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000680 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000681 if (std::error_code EC = ObjOrErr.getError()) {
682 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000683 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000684 << EC.message() << "\n";
685 return nullptr;
686 }
687 auto Index = (*ObjOrErr)->takeIndex();
688 if (CombinedIndex) {
689 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
690 } else {
691 CombinedIndex = std::move(Index);
692 }
693 }
694 return CombinedIndex;
695}
696
697/**
698 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000699 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000700 */
701void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000702 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000703 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000704 auto ModuleIdentifier = TheModule.getModuleIdentifier();
705 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000706 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000707 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000708
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000709 // Generate import/export list
710 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
711 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
712 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
713 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000714
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000715 // Convert the preserved symbols set from string to GUID
716 auto GUIDPreservedSymbols =
717 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
718
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000719 // Resolve LinkOnce/Weak symbols.
720 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
721 resolveWeakForLinkerInIndex(Index, ExportLists, GUIDPreservedSymbols,
722 ResolvedODR);
723
724 thinLTOResolveWeakForLinkerModule(
725 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000726
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000727 promoteModule(TheModule, Index);
728}
729
730/**
731 * Perform cross-module importing for the module identified by ModuleIdentifier.
732 */
733void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000734 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000735 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000736 auto ModuleCount = Index.modulePaths().size();
737
738 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000739 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000740 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000741
742 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000743 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
744 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000745 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
746 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000747 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
748
749 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000750}
751
752/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000753 * Compute the list of summaries needed for importing into module.
754 */
755void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
756 StringRef ModulePath, ModuleSummaryIndex &Index,
757 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
758 auto ModuleCount = Index.modulePaths().size();
759
760 // Collect for each module the list of function it defines (GUID -> Summary).
761 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
762 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
763
764 // Generate import/export list
765 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
766 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
767 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
768 ExportLists);
769
770 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
771 ImportLists,
772 ModuleToSummariesForIndex);
773}
774
775/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000776 * Emit the list of files needed for importing into module.
777 */
778void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
779 StringRef OutputName,
780 ModuleSummaryIndex &Index) {
781 auto ModuleCount = Index.modulePaths().size();
782
783 // Collect for each module the list of function it defines (GUID -> Summary).
784 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
785 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
786
787 // Generate import/export list
788 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
789 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
790 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
791 ExportLists);
792
793 std::error_code EC;
794 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists)))
795 report_fatal_error(Twine("Failed to open ") + OutputName +
796 " to save imports lists\n");
797}
798
799/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000800 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000801 */
802void ThinLTOCodeGenerator::internalize(Module &TheModule,
803 ModuleSummaryIndex &Index) {
804 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
805 auto ModuleCount = Index.modulePaths().size();
806 auto ModuleIdentifier = TheModule.getModuleIdentifier();
807
808 // Convert the preserved symbols set from string to GUID
809 auto GUIDPreservedSymbols =
810 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
811
812 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000813 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000814 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
815
816 // Generate import/export list
817 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
818 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
819 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
820 ExportLists);
821 auto &ExportList = ExportLists[ModuleIdentifier];
822
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000823 // Be friendly and don't nuke totally the module when the client didn't
824 // supply anything to preserve.
825 if (ExportList.empty() && GUIDPreservedSymbols.empty())
826 return;
827
Mehdi Amini059464f2016-04-24 03:18:01 +0000828 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000829 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
830 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000831 return (ExportList != ExportLists.end() &&
832 ExportList->second.count(GUID)) ||
833 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000834 };
835 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
836 thinLTOInternalizeModule(TheModule,
837 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000838}
839
840/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000841 * Perform post-importing ThinLTO optimizations.
842 */
843void ThinLTOCodeGenerator::optimize(Module &TheModule) {
844 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000845
846 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000847 optimizeModule(TheModule, *TMBuilder.create());
848}
849
850/**
851 * Perform ThinLTO CodeGen.
852 */
853std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
854 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
855 return codegenModule(TheModule, *TMBuilder.create());
856}
857
858// Main entry point for the ThinLTO processing
859void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000860 if (CodeGenOnly) {
861 // Perform only parallel codegen and return.
862 ThreadPool Pool;
863 assert(ProducedBinaries.empty() && "The generator should not be reused");
864 ProducedBinaries.resize(Modules.size());
865 int count = 0;
866 for (auto &ModuleBuffer : Modules) {
867 Pool.async([&](int count) {
868 LLVMContext Context;
869 Context.setDiscardValueNames(LTODiscardValueNames);
870
871 // Parse module now
872 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
873
874 // CodeGen
875 ProducedBinaries[count] = codegen(*TheModule);
876 }, count++);
877 }
878
879 return;
880 }
881
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000882 // Sequential linking phase
883 auto Index = linkCombinedIndex();
884
885 // Save temps: index.
886 if (!SaveTempsDir.empty()) {
887 auto SaveTempPath = SaveTempsDir + "index.bc";
888 std::error_code EC;
889 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
890 if (EC)
891 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
892 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000893 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000894 }
895
896 // Prepare the resulting object vector
897 assert(ProducedBinaries.empty() && "The generator should not be reused");
898 ProducedBinaries.resize(Modules.size());
899
900 // Prepare the module map.
901 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000902 auto ModuleCount = Modules.size();
903
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000904 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000905 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000906 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
907
Mehdi Amini01e32132016-03-26 05:40:34 +0000908 // Collect the import/export lists for all modules from the call-graph in the
909 // combined index.
910 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
911 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000912 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
913 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000914
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000915 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000916 // computing the caching hash and the internalization.
917 auto GUIDPreservedSymbols =
918 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000919
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000920 // We use a std::map here to be able to have a defined ordering when
921 // producing a hash for the cache entry.
922 // FIXME: we should be able to compute the caching hash for the entry based
923 // on the index, and nuke this map.
924 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
925
926 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
927 // impacts the caching.
928 resolveWeakForLinkerInIndex(*Index, ExportLists, GUIDPreservedSymbols,
929 ResolvedODR);
930
931 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
932 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000933 return (ExportList != ExportLists.end() &&
934 ExportList->second.count(GUID)) ||
935 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000936 };
937
938 // Use global summary-based analysis to identify symbols that can be
939 // internalized (because they aren't exported or preserved as per callback).
940 // Changes are made in the index, consumed in the ThinLTO backends.
941 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
942
Teresa Johnson141149f2016-05-24 18:44:01 +0000943 // Make sure that every module has an entry in the ExportLists and
944 // ResolvedODR maps to enable threaded access to these maps below.
945 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000946 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000947 ResolvedODR[DefinedGVSummaries.first()];
948 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000949
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000950 // Compute the ordering we will process the inputs: the rough heuristic here
951 // is to sort them per size so that the largest module get schedule as soon as
952 // possible. This is purely a compile-time optimization.
953 std::vector<int> ModulesOrdering;
954 ModulesOrdering.resize(Modules.size());
955 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
956 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
957 [&](int LeftIndex, int RightIndex) {
958 auto LSize = Modules[LeftIndex].getBufferSize();
959 auto RSize = Modules[RightIndex].getBufferSize();
960 return LSize > RSize;
961 });
962
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000963 // Parallel optimizer + codegen
964 {
965 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000966 for (auto IndexCount : ModulesOrdering) {
967 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000968 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000969 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000970 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000971
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000972 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
973
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000974 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000975 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
976 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000977 ResolvedODR[ModuleIdentifier],
978 DefinedFunctions, GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000979
980 {
981 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000982 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
983 << CacheEntry.getEntryPath() << "' for buffer " << count
984 << " " << ModuleIdentifier << "\n");
985
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000986 if (ErrOrBuffer) {
987 // Cache Hit!
988 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
989 return;
990 }
991 }
992
993 LLVMContext Context;
994 Context.setDiscardValueNames(LTODiscardValueNames);
995 Context.enableDebugTypeODRUniquing();
996
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000997 // Parse module now
998 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
999
1000 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +00001001 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001002
Mehdi Amini1aafabf2016-04-16 07:02:16 +00001003 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +00001004 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001005 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001006 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001007 ExportList, GUIDPreservedSymbols,
1008 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Amini059464f2016-04-24 03:18:01 +00001009 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001010
Mehdi Amini001bb412016-05-16 19:11:59 +00001011 OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001012 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001013 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001014 }
1015 }
1016
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001017 CachePruning(CacheOptions.Path)
1018 .setPruningInterval(CacheOptions.PruningInterval)
1019 .setEntryExpiration(CacheOptions.Expiration)
1020 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
1021 .prune();
1022
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001023 // If statistics were requested, print them out now.
1024 if (llvm::AreStatisticsEnabled())
1025 llvm::PrintStatistics();
1026}