blob: c8587465e4b759bc8f66a5ec52d7a0ddc909a5d4 [file] [log] [blame]
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001//===-LTO.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 functions and classes used to support LTO.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000015#include "llvm/Analysis/TargetLibraryInfo.h"
16#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000017#include "llvm/Bitcode/BitcodeReader.h"
18#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000019#include "llvm/CodeGen/Analysis.h"
20#include "llvm/IR/AutoUpgrade.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/LegacyPassManager.h"
23#include "llvm/LTO/LTOBackend.h"
24#include "llvm/Linker/IRMover.h"
25#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
26#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000027#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000028#include "llvm/Support/Path.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000029#include "llvm/Support/SHA1.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000030#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031#include "llvm/Support/TargetRegistry.h"
32#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000033#include "llvm/Support/Threading.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000034#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000035#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
37#include "llvm/Transforms/IPO.h"
38#include "llvm/Transforms/IPO/PassManagerBuilder.h"
39#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000040
Teresa Johnson9ba95f92016-08-11 14:58:12 +000041#include <set>
42
43using namespace llvm;
44using namespace lto;
45using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000046
Mehdi Aminiadc0e262016-08-23 21:30:12 +000047#define DEBUG_TYPE "lto"
48
49// Returns a unique hash for the Module considering the current list of
50// export/import and other global analysis results.
51// The hash is produced in \p Key.
52static void computeCacheKey(
53 SmallString<40> &Key, const ModuleSummaryIndex &Index, StringRef ModuleID,
54 const FunctionImporter::ImportMapTy &ImportList,
55 const FunctionImporter::ExportSetTy &ExportList,
56 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
57 const GVSummaryMapTy &DefinedGlobals) {
58 // Compute the unique hash for this entry.
59 // This is based on the current compiler version, the module itself, the
60 // export list, the hash for every single module in the import list, the
61 // list of ResolvedODR for the module, and the list of preserved symbols.
62 SHA1 Hasher;
63
64 // Start with the compiler revision
65 Hasher.update(LLVM_VERSION_STRING);
66#ifdef HAVE_LLVM_REVISION
67 Hasher.update(LLVM_REVISION);
68#endif
69
70 // Include the hash for the current module
71 auto ModHash = Index.getModuleHash(ModuleID);
72 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
73 for (auto F : ExportList)
74 // The export list can impact the internalization, be conservative here
75 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
76
77 // Include the hash for every module we import functions from
78 for (auto &Entry : ImportList) {
79 auto ModHash = Index.getModuleHash(Entry.first());
80 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
81 }
82
83 // Include the hash for the resolved ODR.
84 for (auto &Entry : ResolvedODR) {
85 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
86 sizeof(GlobalValue::GUID)));
87 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
88 sizeof(GlobalValue::LinkageTypes)));
89 }
90
91 // Include the hash for the linkage type to reflect internalization and weak
92 // resolution.
93 for (auto &GS : DefinedGlobals) {
94 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
95 Hasher.update(
96 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
97 }
98
99 Key = toHex(Hasher.result());
100}
101
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000102static void thinLTOResolveWeakForLinkerGUID(
103 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
104 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000105 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000106 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000107 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000108 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000109 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000110 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
111 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
112 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000113 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000114 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000115 // This is both a compile-time optimization and a correctness
116 // transformation. This is necessary for correctness when we have exported
117 // a reference - we need to convert the linkonce to weak to
118 // ensure a copy is kept to satisfy the exported reference.
119 // FIXME: We may want to split the compile time and correctness
120 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000121 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000122 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
123 S->setLinkage(GlobalValue::getWeakLinkage(
124 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000125 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000126 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000127 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000128 !GlobalInvolvedWithAlias.count(S.get()) &&
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000129 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
130 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
131 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
132 if (S->linkage() != OriginalLinkage)
133 recordNewLinkage(S->modulePath(), GUID, S->linkage());
134 }
135}
136
137// Resolve Weak and LinkOnce values in the \p Index.
138//
139// We'd like to drop these functions if they are no longer referenced in the
140// current module. However there is a chance that another module is still
141// referencing them because of the import. We make sure we always emit at least
142// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000143void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000144 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000145 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000146 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000147 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000148 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000149 // We won't optimize the globals that are referenced by an alias for now
150 // Ideally we should turn the alias into a global and duplicate the definition
151 // when needed.
152 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
153 for (auto &I : Index)
154 for (auto &S : I.second)
155 if (auto AS = dyn_cast<AliasSummary>(S.get()))
156 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
157
158 for (auto &I : Index)
159 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000160 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000161}
162
163static void thinLTOInternalizeAndPromoteGUID(
164 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000165 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000166 for (auto &S : GVSummaryList) {
167 if (isExported(S->modulePath(), GUID)) {
168 if (GlobalValue::isLocalLinkage(S->linkage()))
169 S->setLinkage(GlobalValue::ExternalLinkage);
170 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
171 S->setLinkage(GlobalValue::InternalLinkage);
172 }
173}
174
175// Update the linkages in the given \p Index to mark exported values
176// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000177void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000178 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000179 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000180 for (auto &I : Index)
181 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
182}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000183
184Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
185 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000186
Peter Collingbourned9445c42016-11-13 07:00:17 +0000187 Expected<std::unique_ptr<object::IRObjectFile>> IRObj =
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000188 IRObjectFile::create(Object, File->Ctx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000189 if (!IRObj)
Peter Collingbourned9445c42016-11-13 07:00:17 +0000190 return IRObj.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000191 File->Obj = std::move(*IRObj);
192
Rafael Espindola79121102016-10-25 12:02:03 +0000193 for (const auto &C : File->Obj->getModule().getComdatSymbolTable()) {
194 auto P =
195 File->ComdatMap.insert(std::make_pair(&C.second, File->Comdats.size()));
196 assert(P.second);
Rafael Espindola20aa1772016-10-25 12:28:26 +0000197 (void)P;
Rafael Espindola79121102016-10-25 12:02:03 +0000198 File->Comdats.push_back(C.first());
199 }
200
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000201 return std::move(File);
202}
203
Rafael Espindola79121102016-10-25 12:02:03 +0000204Expected<int> InputFile::Symbol::getComdatIndex() const {
205 if (!GV)
206 return -1;
207 const GlobalObject *GO;
208 if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
209 GO = GA->getBaseObject();
210 if (!GO)
211 return make_error<StringError>("Unable to determine comdat of alias!",
212 inconvertibleErrorCode());
213 } else {
214 GO = cast<GlobalObject>(GV);
215 }
216 if (const Comdat *C = GO->getComdat()) {
217 auto I = File->ComdatMap.find(C);
218 assert(I != File->ComdatMap.end());
219 return I->second;
220 }
221 return -1;
222}
223
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000224LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
225 Config &Conf)
226 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000227 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000228
229LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
230 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000231 this->Backend =
232 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000233}
234
235LTO::LTO(Config Conf, ThinBackend Backend,
236 unsigned ParallelCodeGenParallelismLevel)
237 : Conf(std::move(Conf)),
238 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000239 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000240
241// Add the given symbol to the GlobalResolutions map, and resolve its partition.
242void LTO::addSymbolToGlobalRes(IRObjectFile *Obj,
243 SmallPtrSet<GlobalValue *, 8> &Used,
244 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000245 SymbolResolution Res, unsigned Partition) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000246 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
247
248 auto &GlobalRes = GlobalResolutions[Sym.getName()];
249 if (GV) {
250 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
251 if (Res.Prevailing)
252 GlobalRes.IRName = GV->getName();
253 }
254 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
255 (GlobalRes.Partition != GlobalResolution::Unknown &&
256 GlobalRes.Partition != Partition))
257 GlobalRes.Partition = GlobalResolution::External;
258 else
259 GlobalRes.Partition = Partition;
260}
261
Rafael Espindola7775c332016-08-26 20:19:35 +0000262static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
263 ArrayRef<SymbolResolution> Res) {
264 StringRef Path = Input->getMemoryBufferRef().getBufferIdentifier();
265 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000266 auto ResI = Res.begin();
267 for (const InputFile::Symbol &Sym : Input->symbols()) {
268 assert(ResI != Res.end());
269 SymbolResolution Res = *ResI++;
270
Rafael Espindola7775c332016-08-26 20:19:35 +0000271 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000272 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000273 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000274 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000275 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000276 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000277 OS << 'x';
278 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000279 }
280 assert(ResI == Res.end());
281}
282
283Error LTO::add(std::unique_ptr<InputFile> Input,
284 ArrayRef<SymbolResolution> Res) {
285 assert(!CalledGetMaxTasks);
286
287 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000288 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000289
Mehdi Amini9989f802016-08-19 15:35:44 +0000290 // FIXME: move to backend
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000291 Module &M = Input->Obj->getModule();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000292 if (!Conf.OverrideTriple.empty())
293 M.setTargetTriple(Conf.OverrideTriple);
294 else if (M.getTargetTriple().empty())
295 M.setTargetTriple(Conf.DefaultTriple);
296
297 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000298 Expected<bool> HasThinLTOSummary = hasGlobalValueSummary(MBRef);
299 if (!HasThinLTOSummary)
300 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000301
Peter Collingbournecd513a42016-11-11 19:50:24 +0000302 if (*HasThinLTOSummary)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000303 return addThinLTO(std::move(Input), Res);
304 else
305 return addRegularLTO(std::move(Input), Res);
306}
307
308// Add a regular LTO object to the link.
309Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
310 ArrayRef<SymbolResolution> Res) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000311 if (!RegularLTO.CombinedModule) {
312 RegularLTO.CombinedModule =
313 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
314 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
315 }
Peter Collingbourned9445c42016-11-13 07:00:17 +0000316 Expected<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000317 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
318 if (!ObjOrErr)
Peter Collingbourned9445c42016-11-13 07:00:17 +0000319 return ObjOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000320 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
321
322 Module &M = Obj->getModule();
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000323 if (Error Err = M.materializeMetadata())
324 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000325 UpgradeDebugInfo(M);
326
327 SmallPtrSet<GlobalValue *, 8> Used;
328 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
329
330 std::vector<GlobalValue *> Keep;
331
332 for (GlobalVariable &GV : M.globals())
333 if (GV.hasAppendingLinkage())
334 Keep.push_back(&GV);
335
336 auto ResI = Res.begin();
337 for (const InputFile::Symbol &Sym :
Rafael Espindola79121102016-10-25 12:02:03 +0000338 make_range(InputFile::symbol_iterator(Obj->symbol_begin(), nullptr),
339 InputFile::symbol_iterator(Obj->symbol_end(), nullptr))) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000340 assert(ResI != Res.end());
341 SymbolResolution Res = *ResI++;
342 addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
343
344 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
Davide Italiano39ccd242016-09-13 18:45:13 +0000345 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
346 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000347 if (Res.Prevailing && GV) {
348 Keep.push_back(GV);
349 switch (GV->getLinkage()) {
350 default:
351 break;
352 case GlobalValue::LinkOnceAnyLinkage:
353 GV->setLinkage(GlobalValue::WeakAnyLinkage);
354 break;
355 case GlobalValue::LinkOnceODRLinkage:
356 GV->setLinkage(GlobalValue::WeakODRLinkage);
357 break;
358 }
359 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000360 // Common resolution: collect the maximum size/alignment over all commons.
361 // We also record if we see an instance of a common as prevailing, so that
362 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000363 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000364 // FIXME: We should figure out what to do about commons defined by asm.
365 // For now they aren't reported correctly by ModuleSymbolTable.
366 assert(GV);
367 auto &CommonRes = RegularLTO.Commons[GV->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000368 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
369 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000370 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000371 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000372
373 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
374 }
375 assert(ResI == Res.end());
376
Mehdi Aminie7494532016-08-23 18:39:12 +0000377 return RegularLTO.Mover->move(Obj->takeModule(), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000378 [](GlobalValue &, IRMover::ValueAdder) {},
379 /* LinkModuleInlineAsm */ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000380}
381
382// Add a ThinLTO object to the link.
383Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
384 ArrayRef<SymbolResolution> Res) {
385 Module &M = Input->Obj->getModule();
386 SmallPtrSet<GlobalValue *, 8> Used;
387 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
388
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000389 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000390 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
391 SummaryObjOrErr = object::ModuleSummaryIndexObjectFile::create(MBRef);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000392 if (!SummaryObjOrErr)
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000393 return SummaryObjOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000394 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
395 ThinLTO.ModuleMap.size());
396
397 auto ResI = Res.begin();
398 for (const InputFile::Symbol &Sym : Input->symbols()) {
399 assert(ResI != Res.end());
400 SymbolResolution Res = *ResI++;
401 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
402 ThinLTO.ModuleMap.size() + 1);
403
404 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
405 if (Res.Prevailing && GV)
406 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
407 MBRef.getBufferIdentifier();
408 }
409 assert(ResI == Res.end());
410
411 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
Mehdi Amini41af4302016-11-11 04:28:40 +0000412 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000413}
414
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000415unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000416 CalledGetMaxTasks = true;
417 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
418}
419
Peter Collingbourne80186a52016-09-23 21:33:43 +0000420Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000421 // Save the status of having a regularLTO combined module, as
422 // this is needed for generating the ThinLTO Task ID, and
423 // the CombinedModule will be moved at the end of runRegularLTO.
424 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000425 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000426 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000427 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000428 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000429 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000430}
431
Peter Collingbourne80186a52016-09-23 21:33:43 +0000432Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000433 // Make sure commons have the right size/alignment: we kept the largest from
434 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000435 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000436 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000437 if (!I.second.Prevailing)
438 // Don't do anything if no instance of this common was prevailing.
439 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000440 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000441 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000442 // Don't create a new global if the type is already correct, just make
443 // sure the alignment is correct.
444 OldGV->setAlignment(I.second.Align);
445 continue;
446 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000447 ArrayType *Ty =
448 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000449 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
450 GlobalValue::CommonLinkage,
451 ConstantAggregateZero::get(Ty), "");
452 GV->setAlignment(I.second.Align);
453 if (OldGV) {
454 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
455 GV->takeName(OldGV);
456 OldGV->eraseFromParent();
457 } else {
458 GV->setName(I.first);
459 }
460 }
461
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000462 if (Conf.PreOptModuleHook &&
463 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000464 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000465
Mehdi Aminid310b472016-08-22 06:25:41 +0000466 if (!Conf.CodeGenOnly) {
467 for (const auto &R : GlobalResolutions) {
468 if (R.second.IRName.empty())
469 continue;
470 if (R.second.Partition != 0 &&
471 R.second.Partition != GlobalResolution::External)
472 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000473
Mehdi Aminid310b472016-08-22 06:25:41 +0000474 GlobalValue *GV =
475 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
476 // Ignore symbols defined in other partitions.
477 if (!GV || GV->hasLocalLinkage())
478 continue;
479 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
480 : GlobalValue::UnnamedAddr::None);
481 if (R.second.Partition == 0)
482 GV->setLinkage(GlobalValue::InternalLinkage);
483 }
484
485 if (Conf.PostInternalizeModuleHook &&
486 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000487 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000488 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000489 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000490 std::move(RegularLTO.CombinedModule));
491}
492
493/// This class defines the interface to the ThinLTO backend.
494class lto::ThinBackendProc {
495protected:
496 Config &Conf;
497 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000498 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000499
500public:
501 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000502 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000503 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000504 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
505
506 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000507 virtual Error start(
508 unsigned Task, MemoryBufferRef MBRef,
509 const FunctionImporter::ImportMapTy &ImportList,
510 const FunctionImporter::ExportSetTy &ExportList,
511 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
512 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000513 virtual Error wait() = 0;
514};
515
Benjamin Kramerffd37152016-11-19 20:44:26 +0000516namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000517class InProcessThinBackend : public ThinBackendProc {
518 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000519 AddStreamFn AddStream;
520 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000521
522 Optional<Error> Err;
523 std::mutex ErrMu;
524
525public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000526 InProcessThinBackend(
527 Config &Conf, ModuleSummaryIndex &CombinedIndex,
528 unsigned ThinLTOParallelismLevel,
529 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000530 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000531 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
532 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000533 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000534
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000535 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000536 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
537 MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000538 const FunctionImporter::ImportMapTy &ImportList,
539 const FunctionImporter::ExportSetTy &ExportList,
540 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
541 const GVSummaryMapTy &DefinedGlobals,
542 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000543 auto RunThinBackend = [&](AddStreamFn AddStream) {
544 LTOLLVMContext BackendContext(Conf);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000545 Expected<std::unique_ptr<Module>> MOrErr =
Peter Collingbourne80186a52016-09-23 21:33:43 +0000546 parseBitcodeFile(MBRef, BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000547 if (!MOrErr)
548 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000549
Peter Collingbourne80186a52016-09-23 21:33:43 +0000550 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
551 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000552 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000553
Mehdi Amini00fa1402016-10-08 04:44:18 +0000554 auto ModuleID = MBRef.getBufferIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000555
556 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
557 all_of(CombinedIndex.getModuleHash(ModuleID),
558 [](uint32_t V) { return V == 0; }))
559 // Cache disabled or no entry for this module in the combined index or
560 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000561 return RunThinBackend(AddStream);
562
563 SmallString<40> Key;
564 // The module may be cached, this helps handling it.
Mehdi Amini00fa1402016-10-08 04:44:18 +0000565 computeCacheKey(Key, CombinedIndex, ModuleID, ImportList, ExportList,
566 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000567 if (AddStreamFn CacheAddStream = Cache(Task, Key))
568 return RunThinBackend(CacheAddStream);
569
Mehdi Amini41af4302016-11-11 04:28:40 +0000570 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000571 }
572
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000573 Error start(
574 unsigned Task, MemoryBufferRef MBRef,
575 const FunctionImporter::ImportMapTy &ImportList,
576 const FunctionImporter::ExportSetTy &ExportList,
577 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
578 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000579 StringRef ModulePath = MBRef.getBufferIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000580 assert(ModuleToDefinedGVSummaries.count(ModulePath));
581 const GVSummaryMapTy &DefinedGlobals =
582 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000583 BackendThreadPool.async(
584 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
585 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000586 const FunctionImporter::ExportSetTy &ExportList,
587 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
588 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000589 const GVSummaryMapTy &DefinedGlobals,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000590 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000591 Error E = runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000592 AddStream, Cache, Task, MBRef, CombinedIndex, ImportList,
593 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000594 if (E) {
595 std::unique_lock<std::mutex> L(ErrMu);
596 if (Err)
597 Err = joinErrors(std::move(*Err), std::move(E));
598 else
599 Err = std::move(E);
600 }
601 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000602 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000603 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
604 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000605 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000606 }
607
608 Error wait() override {
609 BackendThreadPool.wait();
610 if (Err)
611 return std::move(*Err);
612 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000613 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000614 }
615};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000616} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000617
618ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
619 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000620 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000621 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000622 return llvm::make_unique<InProcessThinBackend>(
623 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000624 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000625 };
626}
627
Teresa Johnson3f212b82016-09-21 19:12:05 +0000628// Given the original \p Path to an output file, replace any path
629// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
630// resulting directory if it does not yet exist.
631std::string lto::getThinLTOOutputFile(const std::string &Path,
632 const std::string &OldPrefix,
633 const std::string &NewPrefix) {
634 if (OldPrefix.empty() && NewPrefix.empty())
635 return Path;
636 SmallString<128> NewPath(Path);
637 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
638 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
639 if (!ParentPath.empty()) {
640 // Make sure the new directory exists, creating it if necessary.
641 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
642 llvm::errs() << "warning: could not create directory '" << ParentPath
643 << "': " << EC.message() << '\n';
644 }
645 return NewPath.str();
646}
647
Benjamin Kramerffd37152016-11-19 20:44:26 +0000648namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000649class WriteIndexesThinBackend : public ThinBackendProc {
650 std::string OldPrefix, NewPrefix;
651 bool ShouldEmitImportsFiles;
652
653 std::string LinkedObjectsFileName;
654 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
655
656public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000657 WriteIndexesThinBackend(
658 Config &Conf, ModuleSummaryIndex &CombinedIndex,
659 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
660 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
661 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000662 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000663 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
664 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
665 LinkedObjectsFileName(LinkedObjectsFileName) {}
666
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000667 Error start(
668 unsigned Task, MemoryBufferRef MBRef,
669 const FunctionImporter::ImportMapTy &ImportList,
670 const FunctionImporter::ExportSetTy &ExportList,
671 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
672 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000673 StringRef ModulePath = MBRef.getBufferIdentifier();
674 std::string NewModulePath =
675 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
676
677 std::error_code EC;
678 if (!LinkedObjectsFileName.empty()) {
679 if (!LinkedObjectsFile) {
680 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
681 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
682 if (EC)
683 return errorCodeToError(EC);
684 }
685 *LinkedObjectsFile << NewModulePath << '\n';
686 }
687
688 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
689 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000690 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000691
692 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
693 sys::fs::OpenFlags::F_None);
694 if (EC)
695 return errorCodeToError(EC);
696 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
697
698 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000699 return errorCodeToError(
700 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000701 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000702 }
703
Mehdi Amini41af4302016-11-11 04:28:40 +0000704 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000705};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000706} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000707
708ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
709 std::string NewPrefix,
710 bool ShouldEmitImportsFiles,
711 std::string LinkedObjectsFile) {
712 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000713 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000714 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000715 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000716 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
717 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000718 };
719}
720
Peter Collingbourne80186a52016-09-23 21:33:43 +0000721Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
722 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000723 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000724 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000725
726 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000727 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000728
729 // Collect for each module the list of function it defines (GUID ->
730 // Summary).
731 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
732 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
733 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
734 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000735 // Create entries for any modules that didn't have any GV summaries
736 // (either they didn't have any GVs to start with, or we suppressed
737 // generation of the summaries because they e.g. had inline assembly
738 // uses that couldn't be promoted/renamed on export). This is so
739 // InProcessThinBackend::start can still launch a backend thread, which
740 // is passed the map of summaries for the module, without any special
741 // handling for this case.
742 for (auto &Mod : ThinLTO.ModuleMap)
743 if (!ModuleToDefinedGVSummaries.count(Mod.first))
744 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000745
746 StringMap<FunctionImporter::ImportMapTy> ImportLists(
747 ThinLTO.ModuleMap.size());
748 StringMap<FunctionImporter::ExportSetTy> ExportLists(
749 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000750 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000751
Teresa Johnson002af9b2016-10-31 22:12:21 +0000752 if (Conf.OptLevel > 0) {
753 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
754 ImportLists, ExportLists);
755
756 std::set<GlobalValue::GUID> ExportedGUIDs;
757 for (auto &Res : GlobalResolutions) {
758 if (!Res.second.IRName.empty() &&
759 Res.second.Partition == GlobalResolution::External)
760 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
761 }
762
763 auto isPrevailing = [&](GlobalValue::GUID GUID,
764 const GlobalValueSummary *S) {
765 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
766 };
767 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
768 const auto &ExportList = ExportLists.find(ModuleIdentifier);
769 return (ExportList != ExportLists.end() &&
770 ExportList->second.count(GUID)) ||
771 ExportedGUIDs.count(GUID);
772 };
773 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
774
775 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
776 GlobalValue::GUID GUID,
777 GlobalValue::LinkageTypes NewLinkage) {
778 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
779 };
780
781 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
782 recordNewLinkage);
783 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000784
Peter Collingbourne80186a52016-09-23 21:33:43 +0000785 std::unique_ptr<ThinBackendProc> BackendProc =
786 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
787 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000788
789 // Partition numbers for ThinLTO jobs start at 1 (see comments for
790 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000791 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
792 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
793 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000794 unsigned Task =
795 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000796 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000797
798 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000799 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000800 ExportLists[Mod.first],
801 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000802 return E;
803
804 ++Task;
805 ++Partition;
806 }
807
808 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000809}