blob: 1e5ab584bb122e8a42421eccf756486e6bc63fea [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 Johnsondf6edc52016-05-23 22:54:06 +0000102// Simple helper to load a module from bitcode
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000103std::unique_ptr<Module>
104llvm::loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
105 bool Lazy) {
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000106 SMDiagnostic Err;
107 ErrorOr<std::unique_ptr<Module>> ModuleOrErr(nullptr);
108 if (Lazy) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000109 ModuleOrErr = getLazyBitcodeModule(Buffer, Context,
110 /* ShouldLazyLoadMetadata */ Lazy);
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000111 } else {
112 ModuleOrErr = parseBitcodeFile(Buffer, Context);
113 }
114 if (std::error_code EC = ModuleOrErr.getError()) {
115 Err = SMDiagnostic(Buffer.getBufferIdentifier(), SourceMgr::DK_Error,
116 EC.message());
117 Err.print("ThinLTO", errs());
118 report_fatal_error("Can't load module, abort.");
119 }
120 return std::move(ModuleOrErr.get());
121}
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000122
123static void thinLTOResolveWeakForLinkerGUID(
124 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
125 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000126 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000127 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000128 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000129 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000130 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000131 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
132 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
133 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000134 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000135 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000136 // This is both a compile-time optimization and a correctness
137 // transformation. This is necessary for correctness when we have exported
138 // a reference - we need to convert the linkonce to weak to
139 // ensure a copy is kept to satisfy the exported reference.
140 // FIXME: We may want to split the compile time and correctness
141 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000142 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000143 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
144 S->setLinkage(GlobalValue::getWeakLinkage(
145 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000146 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000147 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000148 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000149 !GlobalInvolvedWithAlias.count(S.get()) &&
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000150 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
151 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
152 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
153 if (S->linkage() != OriginalLinkage)
154 recordNewLinkage(S->modulePath(), GUID, S->linkage());
155 }
156}
157
158// Resolve Weak and LinkOnce values in the \p Index.
159//
160// We'd like to drop these functions if they are no longer referenced in the
161// current module. However there is a chance that another module is still
162// referencing them because of the import. We make sure we always emit at least
163// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000164void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000165 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000166 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000167 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000168 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000169 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000170 // We won't optimize the globals that are referenced by an alias for now
171 // Ideally we should turn the alias into a global and duplicate the definition
172 // when needed.
173 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
174 for (auto &I : Index)
175 for (auto &S : I.second)
176 if (auto AS = dyn_cast<AliasSummary>(S.get()))
177 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
178
179 for (auto &I : Index)
180 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000181 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000182}
183
184static void thinLTOInternalizeAndPromoteGUID(
185 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000186 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000187 for (auto &S : GVSummaryList) {
188 if (isExported(S->modulePath(), GUID)) {
189 if (GlobalValue::isLocalLinkage(S->linkage()))
190 S->setLinkage(GlobalValue::ExternalLinkage);
191 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
192 S->setLinkage(GlobalValue::InternalLinkage);
193 }
194}
195
196// Update the linkages in the given \p Index to mark exported values
197// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000198void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000199 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000200 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000201 for (auto &I : Index)
202 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
203}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000204
205Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
206 std::unique_ptr<InputFile> File(new InputFile);
207 std::string Msg;
208 auto DiagHandler = [](const DiagnosticInfo &DI, void *MsgP) {
209 auto *Msg = reinterpret_cast<std::string *>(MsgP);
210 raw_string_ostream OS(*Msg);
211 DiagnosticPrinterRawOStream DP(OS);
212 DI.print(DP);
213 };
214 File->Ctx.setDiagnosticHandler(DiagHandler, static_cast<void *>(&Msg));
215
216 ErrorOr<std::unique_ptr<object::IRObjectFile>> IRObj =
217 IRObjectFile::create(Object, File->Ctx);
218 if (!Msg.empty())
219 return make_error<StringError>(Msg, inconvertibleErrorCode());
220 if (!IRObj)
221 return errorCodeToError(IRObj.getError());
222 File->Obj = std::move(*IRObj);
223
224 File->Ctx.setDiagnosticHandler(nullptr, nullptr);
225
Rafael Espindola79121102016-10-25 12:02:03 +0000226 for (const auto &C : File->Obj->getModule().getComdatSymbolTable()) {
227 auto P =
228 File->ComdatMap.insert(std::make_pair(&C.second, File->Comdats.size()));
229 assert(P.second);
Rafael Espindola20aa1772016-10-25 12:28:26 +0000230 (void)P;
Rafael Espindola79121102016-10-25 12:02:03 +0000231 File->Comdats.push_back(C.first());
232 }
233
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000234 return std::move(File);
235}
236
Rafael Espindola79121102016-10-25 12:02:03 +0000237Expected<int> InputFile::Symbol::getComdatIndex() const {
238 if (!GV)
239 return -1;
240 const GlobalObject *GO;
241 if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
242 GO = GA->getBaseObject();
243 if (!GO)
244 return make_error<StringError>("Unable to determine comdat of alias!",
245 inconvertibleErrorCode());
246 } else {
247 GO = cast<GlobalObject>(GV);
248 }
249 if (const Comdat *C = GO->getComdat()) {
250 auto I = File->ComdatMap.find(C);
251 assert(I != File->ComdatMap.end());
252 return I->second;
253 }
254 return -1;
255}
256
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000257LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
258 Config &Conf)
259 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000260 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000261
262LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
263 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000264 this->Backend =
265 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000266}
267
268LTO::LTO(Config Conf, ThinBackend Backend,
269 unsigned ParallelCodeGenParallelismLevel)
270 : Conf(std::move(Conf)),
271 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000272 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000273
274// Add the given symbol to the GlobalResolutions map, and resolve its partition.
275void LTO::addSymbolToGlobalRes(IRObjectFile *Obj,
276 SmallPtrSet<GlobalValue *, 8> &Used,
277 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000278 SymbolResolution Res, unsigned Partition) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000279 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
280
281 auto &GlobalRes = GlobalResolutions[Sym.getName()];
282 if (GV) {
283 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
284 if (Res.Prevailing)
285 GlobalRes.IRName = GV->getName();
286 }
287 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
288 (GlobalRes.Partition != GlobalResolution::Unknown &&
289 GlobalRes.Partition != Partition))
290 GlobalRes.Partition = GlobalResolution::External;
291 else
292 GlobalRes.Partition = Partition;
293}
294
Rafael Espindola7775c332016-08-26 20:19:35 +0000295static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
296 ArrayRef<SymbolResolution> Res) {
297 StringRef Path = Input->getMemoryBufferRef().getBufferIdentifier();
298 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000299 auto ResI = Res.begin();
300 for (const InputFile::Symbol &Sym : Input->symbols()) {
301 assert(ResI != Res.end());
302 SymbolResolution Res = *ResI++;
303
Rafael Espindola7775c332016-08-26 20:19:35 +0000304 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000305 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000306 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000307 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000308 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000309 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000310 OS << 'x';
311 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000312 }
313 assert(ResI == Res.end());
314}
315
316Error LTO::add(std::unique_ptr<InputFile> Input,
317 ArrayRef<SymbolResolution> Res) {
318 assert(!CalledGetMaxTasks);
319
320 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000321 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000322
Mehdi Amini9989f802016-08-19 15:35:44 +0000323 // FIXME: move to backend
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000324 Module &M = Input->Obj->getModule();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000325 if (!Conf.OverrideTriple.empty())
326 M.setTargetTriple(Conf.OverrideTriple);
327 else if (M.getTargetTriple().empty())
328 M.setTargetTriple(Conf.DefaultTriple);
329
330 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
331 bool HasThinLTOSummary = hasGlobalValueSummary(MBRef, Conf.DiagHandler);
332
333 if (HasThinLTOSummary)
334 return addThinLTO(std::move(Input), Res);
335 else
336 return addRegularLTO(std::move(Input), Res);
337}
338
339// Add a regular LTO object to the link.
340Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
341 ArrayRef<SymbolResolution> Res) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000342 if (!RegularLTO.CombinedModule) {
343 RegularLTO.CombinedModule =
344 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
345 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
346 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000347 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
348 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
349 if (!ObjOrErr)
350 return errorCodeToError(ObjOrErr.getError());
351 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
352
353 Module &M = Obj->getModule();
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000354 if (Error Err = M.materializeMetadata())
355 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000356 UpgradeDebugInfo(M);
357
358 SmallPtrSet<GlobalValue *, 8> Used;
359 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
360
361 std::vector<GlobalValue *> Keep;
362
363 for (GlobalVariable &GV : M.globals())
364 if (GV.hasAppendingLinkage())
365 Keep.push_back(&GV);
366
367 auto ResI = Res.begin();
368 for (const InputFile::Symbol &Sym :
Rafael Espindola79121102016-10-25 12:02:03 +0000369 make_range(InputFile::symbol_iterator(Obj->symbol_begin(), nullptr),
370 InputFile::symbol_iterator(Obj->symbol_end(), nullptr))) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000371 assert(ResI != Res.end());
372 SymbolResolution Res = *ResI++;
373 addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
374
375 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
Davide Italiano39ccd242016-09-13 18:45:13 +0000376 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
377 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000378 if (Res.Prevailing && GV) {
379 Keep.push_back(GV);
380 switch (GV->getLinkage()) {
381 default:
382 break;
383 case GlobalValue::LinkOnceAnyLinkage:
384 GV->setLinkage(GlobalValue::WeakAnyLinkage);
385 break;
386 case GlobalValue::LinkOnceODRLinkage:
387 GV->setLinkage(GlobalValue::WeakODRLinkage);
388 break;
389 }
390 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000391 // Common resolution: collect the maximum size/alignment over all commons.
392 // We also record if we see an instance of a common as prevailing, so that
393 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000394 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
395 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
396 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
397 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000398 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000399 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000400
401 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
402 }
403 assert(ResI == Res.end());
404
Mehdi Aminie7494532016-08-23 18:39:12 +0000405 return RegularLTO.Mover->move(Obj->takeModule(), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000406 [](GlobalValue &, IRMover::ValueAdder) {},
407 /* LinkModuleInlineAsm */ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000408}
409
410// Add a ThinLTO object to the link.
411Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
412 ArrayRef<SymbolResolution> Res) {
413 Module &M = Input->Obj->getModule();
414 SmallPtrSet<GlobalValue *, 8> Used;
415 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
416
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000417 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
418 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
419 SummaryObjOrErr =
420 object::ModuleSummaryIndexObjectFile::create(MBRef, Conf.DiagHandler);
421 if (!SummaryObjOrErr)
422 return errorCodeToError(SummaryObjOrErr.getError());
423 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
424 ThinLTO.ModuleMap.size());
425
426 auto ResI = Res.begin();
427 for (const InputFile::Symbol &Sym : Input->symbols()) {
428 assert(ResI != Res.end());
429 SymbolResolution Res = *ResI++;
430 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
431 ThinLTO.ModuleMap.size() + 1);
432
433 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
434 if (Res.Prevailing && GV)
435 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
436 MBRef.getBufferIdentifier();
437 }
438 assert(ResI == Res.end());
439
440 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
Mehdi Amini41af4302016-11-11 04:28:40 +0000441 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000442}
443
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000444unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000445 CalledGetMaxTasks = true;
446 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
447}
448
Peter Collingbourne80186a52016-09-23 21:33:43 +0000449Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000450 // Save the status of having a regularLTO combined module, as
451 // this is needed for generating the ThinLTO Task ID, and
452 // the CombinedModule will be moved at the end of runRegularLTO.
453 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000454 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000455 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000456 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000457 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000458 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000459}
460
Peter Collingbourne80186a52016-09-23 21:33:43 +0000461Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000462 // Make sure commons have the right size/alignment: we kept the largest from
463 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000464 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000465 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000466 if (!I.second.Prevailing)
467 // Don't do anything if no instance of this common was prevailing.
468 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000469 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000470 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000471 // Don't create a new global if the type is already correct, just make
472 // sure the alignment is correct.
473 OldGV->setAlignment(I.second.Align);
474 continue;
475 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000476 ArrayType *Ty =
477 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000478 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
479 GlobalValue::CommonLinkage,
480 ConstantAggregateZero::get(Ty), "");
481 GV->setAlignment(I.second.Align);
482 if (OldGV) {
483 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
484 GV->takeName(OldGV);
485 OldGV->eraseFromParent();
486 } else {
487 GV->setName(I.first);
488 }
489 }
490
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000491 if (Conf.PreOptModuleHook &&
492 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000493 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000494
Mehdi Aminid310b472016-08-22 06:25:41 +0000495 if (!Conf.CodeGenOnly) {
496 for (const auto &R : GlobalResolutions) {
497 if (R.second.IRName.empty())
498 continue;
499 if (R.second.Partition != 0 &&
500 R.second.Partition != GlobalResolution::External)
501 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000502
Mehdi Aminid310b472016-08-22 06:25:41 +0000503 GlobalValue *GV =
504 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
505 // Ignore symbols defined in other partitions.
506 if (!GV || GV->hasLocalLinkage())
507 continue;
508 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
509 : GlobalValue::UnnamedAddr::None);
510 if (R.second.Partition == 0)
511 GV->setLinkage(GlobalValue::InternalLinkage);
512 }
513
514 if (Conf.PostInternalizeModuleHook &&
515 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000516 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000517 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000518 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000519 std::move(RegularLTO.CombinedModule));
520}
521
522/// This class defines the interface to the ThinLTO backend.
523class lto::ThinBackendProc {
524protected:
525 Config &Conf;
526 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000527 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000528
529public:
530 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000531 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000532 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000533 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
534
535 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000536 virtual Error start(
537 unsigned Task, MemoryBufferRef MBRef,
538 const FunctionImporter::ImportMapTy &ImportList,
539 const FunctionImporter::ExportSetTy &ExportList,
540 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
541 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000542 virtual Error wait() = 0;
543};
544
545class InProcessThinBackend : public ThinBackendProc {
546 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000547 AddStreamFn AddStream;
548 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000549
550 Optional<Error> Err;
551 std::mutex ErrMu;
552
553public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000554 InProcessThinBackend(
555 Config &Conf, ModuleSummaryIndex &CombinedIndex,
556 unsigned ThinLTOParallelismLevel,
557 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000558 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000559 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
560 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000561 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000562
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000563 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000564 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
565 MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000566 const FunctionImporter::ImportMapTy &ImportList,
567 const FunctionImporter::ExportSetTy &ExportList,
568 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
569 const GVSummaryMapTy &DefinedGlobals,
570 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000571 auto RunThinBackend = [&](AddStreamFn AddStream) {
572 LTOLLVMContext BackendContext(Conf);
573 ErrorOr<std::unique_ptr<Module>> MOrErr =
574 parseBitcodeFile(MBRef, BackendContext);
575 assert(MOrErr && "Unable to load module in thread?");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000576
Peter Collingbourne80186a52016-09-23 21:33:43 +0000577 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
578 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000579 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000580
Mehdi Amini00fa1402016-10-08 04:44:18 +0000581 auto ModuleID = MBRef.getBufferIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000582
583 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
584 all_of(CombinedIndex.getModuleHash(ModuleID),
585 [](uint32_t V) { return V == 0; }))
586 // Cache disabled or no entry for this module in the combined index or
587 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000588 return RunThinBackend(AddStream);
589
590 SmallString<40> Key;
591 // The module may be cached, this helps handling it.
Mehdi Amini00fa1402016-10-08 04:44:18 +0000592 computeCacheKey(Key, CombinedIndex, ModuleID, ImportList, ExportList,
593 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000594 if (AddStreamFn CacheAddStream = Cache(Task, Key))
595 return RunThinBackend(CacheAddStream);
596
Mehdi Amini41af4302016-11-11 04:28:40 +0000597 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000598 }
599
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000600 Error start(
601 unsigned Task, MemoryBufferRef MBRef,
602 const FunctionImporter::ImportMapTy &ImportList,
603 const FunctionImporter::ExportSetTy &ExportList,
604 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
605 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000606 StringRef ModulePath = MBRef.getBufferIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000607 assert(ModuleToDefinedGVSummaries.count(ModulePath));
608 const GVSummaryMapTy &DefinedGlobals =
609 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000610 BackendThreadPool.async(
611 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
612 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000613 const FunctionImporter::ExportSetTy &ExportList,
614 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
615 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000616 const GVSummaryMapTy &DefinedGlobals,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000617 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000618 Error E = runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000619 AddStream, Cache, Task, MBRef, CombinedIndex, ImportList,
620 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000621 if (E) {
622 std::unique_lock<std::mutex> L(ErrMu);
623 if (Err)
624 Err = joinErrors(std::move(*Err), std::move(E));
625 else
626 Err = std::move(E);
627 }
628 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000629 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000630 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
631 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000632 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000633 }
634
635 Error wait() override {
636 BackendThreadPool.wait();
637 if (Err)
638 return std::move(*Err);
639 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000640 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000641 }
642};
643
644ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
645 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000646 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000647 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000648 return llvm::make_unique<InProcessThinBackend>(
649 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000650 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000651 };
652}
653
Teresa Johnson3f212b82016-09-21 19:12:05 +0000654// Given the original \p Path to an output file, replace any path
655// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
656// resulting directory if it does not yet exist.
657std::string lto::getThinLTOOutputFile(const std::string &Path,
658 const std::string &OldPrefix,
659 const std::string &NewPrefix) {
660 if (OldPrefix.empty() && NewPrefix.empty())
661 return Path;
662 SmallString<128> NewPath(Path);
663 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
664 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
665 if (!ParentPath.empty()) {
666 // Make sure the new directory exists, creating it if necessary.
667 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
668 llvm::errs() << "warning: could not create directory '" << ParentPath
669 << "': " << EC.message() << '\n';
670 }
671 return NewPath.str();
672}
673
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000674class WriteIndexesThinBackend : public ThinBackendProc {
675 std::string OldPrefix, NewPrefix;
676 bool ShouldEmitImportsFiles;
677
678 std::string LinkedObjectsFileName;
679 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
680
681public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000682 WriteIndexesThinBackend(
683 Config &Conf, ModuleSummaryIndex &CombinedIndex,
684 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
685 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
686 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000687 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000688 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
689 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
690 LinkedObjectsFileName(LinkedObjectsFileName) {}
691
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000692 Error start(
693 unsigned Task, MemoryBufferRef MBRef,
694 const FunctionImporter::ImportMapTy &ImportList,
695 const FunctionImporter::ExportSetTy &ExportList,
696 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
697 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000698 StringRef ModulePath = MBRef.getBufferIdentifier();
699 std::string NewModulePath =
700 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
701
702 std::error_code EC;
703 if (!LinkedObjectsFileName.empty()) {
704 if (!LinkedObjectsFile) {
705 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
706 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
707 if (EC)
708 return errorCodeToError(EC);
709 }
710 *LinkedObjectsFile << NewModulePath << '\n';
711 }
712
713 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
714 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000715 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000716
717 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
718 sys::fs::OpenFlags::F_None);
719 if (EC)
720 return errorCodeToError(EC);
721 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
722
723 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000724 return errorCodeToError(
725 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000726 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000727 }
728
Mehdi Amini41af4302016-11-11 04:28:40 +0000729 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000730};
731
732ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
733 std::string NewPrefix,
734 bool ShouldEmitImportsFiles,
735 std::string LinkedObjectsFile) {
736 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000737 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000738 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000739 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000740 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
741 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000742 };
743}
744
Peter Collingbourne80186a52016-09-23 21:33:43 +0000745Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
746 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000747 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000748 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000749
750 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000751 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000752
753 // Collect for each module the list of function it defines (GUID ->
754 // Summary).
755 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
756 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
757 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
758 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000759 // Create entries for any modules that didn't have any GV summaries
760 // (either they didn't have any GVs to start with, or we suppressed
761 // generation of the summaries because they e.g. had inline assembly
762 // uses that couldn't be promoted/renamed on export). This is so
763 // InProcessThinBackend::start can still launch a backend thread, which
764 // is passed the map of summaries for the module, without any special
765 // handling for this case.
766 for (auto &Mod : ThinLTO.ModuleMap)
767 if (!ModuleToDefinedGVSummaries.count(Mod.first))
768 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000769
770 StringMap<FunctionImporter::ImportMapTy> ImportLists(
771 ThinLTO.ModuleMap.size());
772 StringMap<FunctionImporter::ExportSetTy> ExportLists(
773 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000774 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000775
Teresa Johnson002af9b2016-10-31 22:12:21 +0000776 if (Conf.OptLevel > 0) {
777 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
778 ImportLists, ExportLists);
779
780 std::set<GlobalValue::GUID> ExportedGUIDs;
781 for (auto &Res : GlobalResolutions) {
782 if (!Res.second.IRName.empty() &&
783 Res.second.Partition == GlobalResolution::External)
784 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
785 }
786
787 auto isPrevailing = [&](GlobalValue::GUID GUID,
788 const GlobalValueSummary *S) {
789 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
790 };
791 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
792 const auto &ExportList = ExportLists.find(ModuleIdentifier);
793 return (ExportList != ExportLists.end() &&
794 ExportList->second.count(GUID)) ||
795 ExportedGUIDs.count(GUID);
796 };
797 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
798
799 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
800 GlobalValue::GUID GUID,
801 GlobalValue::LinkageTypes NewLinkage) {
802 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
803 };
804
805 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
806 recordNewLinkage);
807 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000808
Peter Collingbourne80186a52016-09-23 21:33:43 +0000809 std::unique_ptr<ThinBackendProc> BackendProc =
810 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
811 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000812
813 // Partition numbers for ThinLTO jobs start at 1 (see comments for
814 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000815 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
816 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
817 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000818 unsigned Task =
819 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000820 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000821
822 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000823 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000824 ExportLists[Mod.first],
825 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000826 return E;
827
828 ++Task;
829 ++Partition;
830 }
831
832 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000833}