blob: 4ff1bfb14711771b6ed5dcc35cd4a7d1e2b27605 [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();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000331 Expected<bool> HasThinLTOSummary = hasGlobalValueSummary(MBRef);
332 if (!HasThinLTOSummary)
333 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000334
Peter Collingbournecd513a42016-11-11 19:50:24 +0000335 if (*HasThinLTOSummary)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000336 return addThinLTO(std::move(Input), Res);
337 else
338 return addRegularLTO(std::move(Input), Res);
339}
340
341// Add a regular LTO object to the link.
342Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
343 ArrayRef<SymbolResolution> Res) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000344 if (!RegularLTO.CombinedModule) {
345 RegularLTO.CombinedModule =
346 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
347 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
348 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000349 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
350 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
351 if (!ObjOrErr)
352 return errorCodeToError(ObjOrErr.getError());
353 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
354
355 Module &M = Obj->getModule();
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000356 if (Error Err = M.materializeMetadata())
357 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000358 UpgradeDebugInfo(M);
359
360 SmallPtrSet<GlobalValue *, 8> Used;
361 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
362
363 std::vector<GlobalValue *> Keep;
364
365 for (GlobalVariable &GV : M.globals())
366 if (GV.hasAppendingLinkage())
367 Keep.push_back(&GV);
368
369 auto ResI = Res.begin();
370 for (const InputFile::Symbol &Sym :
Rafael Espindola79121102016-10-25 12:02:03 +0000371 make_range(InputFile::symbol_iterator(Obj->symbol_begin(), nullptr),
372 InputFile::symbol_iterator(Obj->symbol_end(), nullptr))) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000373 assert(ResI != Res.end());
374 SymbolResolution Res = *ResI++;
375 addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
376
377 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
Davide Italiano39ccd242016-09-13 18:45:13 +0000378 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
379 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000380 if (Res.Prevailing && GV) {
381 Keep.push_back(GV);
382 switch (GV->getLinkage()) {
383 default:
384 break;
385 case GlobalValue::LinkOnceAnyLinkage:
386 GV->setLinkage(GlobalValue::WeakAnyLinkage);
387 break;
388 case GlobalValue::LinkOnceODRLinkage:
389 GV->setLinkage(GlobalValue::WeakODRLinkage);
390 break;
391 }
392 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000393 // Common resolution: collect the maximum size/alignment over all commons.
394 // We also record if we see an instance of a common as prevailing, so that
395 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000396 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
397 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
398 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
399 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000400 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000401 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000402
403 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
404 }
405 assert(ResI == Res.end());
406
Mehdi Aminie7494532016-08-23 18:39:12 +0000407 return RegularLTO.Mover->move(Obj->takeModule(), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000408 [](GlobalValue &, IRMover::ValueAdder) {},
409 /* LinkModuleInlineAsm */ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000410}
411
412// Add a ThinLTO object to the link.
413Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
414 ArrayRef<SymbolResolution> Res) {
415 Module &M = Input->Obj->getModule();
416 SmallPtrSet<GlobalValue *, 8> Used;
417 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
418
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000419 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
420 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
421 SummaryObjOrErr =
422 object::ModuleSummaryIndexObjectFile::create(MBRef, Conf.DiagHandler);
423 if (!SummaryObjOrErr)
424 return errorCodeToError(SummaryObjOrErr.getError());
425 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
426 ThinLTO.ModuleMap.size());
427
428 auto ResI = Res.begin();
429 for (const InputFile::Symbol &Sym : Input->symbols()) {
430 assert(ResI != Res.end());
431 SymbolResolution Res = *ResI++;
432 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
433 ThinLTO.ModuleMap.size() + 1);
434
435 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
436 if (Res.Prevailing && GV)
437 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
438 MBRef.getBufferIdentifier();
439 }
440 assert(ResI == Res.end());
441
442 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
Mehdi Amini41af4302016-11-11 04:28:40 +0000443 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000444}
445
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000446unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000447 CalledGetMaxTasks = true;
448 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
449}
450
Peter Collingbourne80186a52016-09-23 21:33:43 +0000451Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000452 // Save the status of having a regularLTO combined module, as
453 // this is needed for generating the ThinLTO Task ID, and
454 // the CombinedModule will be moved at the end of runRegularLTO.
455 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000456 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000457 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000458 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000459 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000460 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000461}
462
Peter Collingbourne80186a52016-09-23 21:33:43 +0000463Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000464 // Make sure commons have the right size/alignment: we kept the largest from
465 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000466 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000467 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000468 if (!I.second.Prevailing)
469 // Don't do anything if no instance of this common was prevailing.
470 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000471 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000472 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000473 // Don't create a new global if the type is already correct, just make
474 // sure the alignment is correct.
475 OldGV->setAlignment(I.second.Align);
476 continue;
477 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000478 ArrayType *Ty =
479 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000480 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
481 GlobalValue::CommonLinkage,
482 ConstantAggregateZero::get(Ty), "");
483 GV->setAlignment(I.second.Align);
484 if (OldGV) {
485 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
486 GV->takeName(OldGV);
487 OldGV->eraseFromParent();
488 } else {
489 GV->setName(I.first);
490 }
491 }
492
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000493 if (Conf.PreOptModuleHook &&
494 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000495 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000496
Mehdi Aminid310b472016-08-22 06:25:41 +0000497 if (!Conf.CodeGenOnly) {
498 for (const auto &R : GlobalResolutions) {
499 if (R.second.IRName.empty())
500 continue;
501 if (R.second.Partition != 0 &&
502 R.second.Partition != GlobalResolution::External)
503 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000504
Mehdi Aminid310b472016-08-22 06:25:41 +0000505 GlobalValue *GV =
506 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
507 // Ignore symbols defined in other partitions.
508 if (!GV || GV->hasLocalLinkage())
509 continue;
510 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
511 : GlobalValue::UnnamedAddr::None);
512 if (R.second.Partition == 0)
513 GV->setLinkage(GlobalValue::InternalLinkage);
514 }
515
516 if (Conf.PostInternalizeModuleHook &&
517 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000518 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000519 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000520 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000521 std::move(RegularLTO.CombinedModule));
522}
523
524/// This class defines the interface to the ThinLTO backend.
525class lto::ThinBackendProc {
526protected:
527 Config &Conf;
528 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000529 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000530
531public:
532 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000533 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000534 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000535 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
536
537 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000538 virtual Error start(
539 unsigned Task, MemoryBufferRef MBRef,
540 const FunctionImporter::ImportMapTy &ImportList,
541 const FunctionImporter::ExportSetTy &ExportList,
542 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
543 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000544 virtual Error wait() = 0;
545};
546
547class InProcessThinBackend : public ThinBackendProc {
548 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000549 AddStreamFn AddStream;
550 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000551
552 Optional<Error> Err;
553 std::mutex ErrMu;
554
555public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000556 InProcessThinBackend(
557 Config &Conf, ModuleSummaryIndex &CombinedIndex,
558 unsigned ThinLTOParallelismLevel,
559 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000560 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000561 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
562 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000563 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000564
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000565 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000566 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
567 MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000568 const FunctionImporter::ImportMapTy &ImportList,
569 const FunctionImporter::ExportSetTy &ExportList,
570 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
571 const GVSummaryMapTy &DefinedGlobals,
572 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000573 auto RunThinBackend = [&](AddStreamFn AddStream) {
574 LTOLLVMContext BackendContext(Conf);
575 ErrorOr<std::unique_ptr<Module>> MOrErr =
576 parseBitcodeFile(MBRef, BackendContext);
577 assert(MOrErr && "Unable to load module in thread?");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000578
Peter Collingbourne80186a52016-09-23 21:33:43 +0000579 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
580 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000581 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000582
Mehdi Amini00fa1402016-10-08 04:44:18 +0000583 auto ModuleID = MBRef.getBufferIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000584
585 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
586 all_of(CombinedIndex.getModuleHash(ModuleID),
587 [](uint32_t V) { return V == 0; }))
588 // Cache disabled or no entry for this module in the combined index or
589 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000590 return RunThinBackend(AddStream);
591
592 SmallString<40> Key;
593 // The module may be cached, this helps handling it.
Mehdi Amini00fa1402016-10-08 04:44:18 +0000594 computeCacheKey(Key, CombinedIndex, ModuleID, ImportList, ExportList,
595 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000596 if (AddStreamFn CacheAddStream = Cache(Task, Key))
597 return RunThinBackend(CacheAddStream);
598
Mehdi Amini41af4302016-11-11 04:28:40 +0000599 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000600 }
601
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000602 Error start(
603 unsigned Task, MemoryBufferRef MBRef,
604 const FunctionImporter::ImportMapTy &ImportList,
605 const FunctionImporter::ExportSetTy &ExportList,
606 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
607 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000608 StringRef ModulePath = MBRef.getBufferIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000609 assert(ModuleToDefinedGVSummaries.count(ModulePath));
610 const GVSummaryMapTy &DefinedGlobals =
611 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000612 BackendThreadPool.async(
613 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
614 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000615 const FunctionImporter::ExportSetTy &ExportList,
616 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
617 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000618 const GVSummaryMapTy &DefinedGlobals,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000619 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000620 Error E = runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000621 AddStream, Cache, Task, MBRef, CombinedIndex, ImportList,
622 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000623 if (E) {
624 std::unique_lock<std::mutex> L(ErrMu);
625 if (Err)
626 Err = joinErrors(std::move(*Err), std::move(E));
627 else
628 Err = std::move(E);
629 }
630 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000631 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000632 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
633 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000634 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000635 }
636
637 Error wait() override {
638 BackendThreadPool.wait();
639 if (Err)
640 return std::move(*Err);
641 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000642 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000643 }
644};
645
646ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
647 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000648 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000649 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000650 return llvm::make_unique<InProcessThinBackend>(
651 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000652 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000653 };
654}
655
Teresa Johnson3f212b82016-09-21 19:12:05 +0000656// Given the original \p Path to an output file, replace any path
657// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
658// resulting directory if it does not yet exist.
659std::string lto::getThinLTOOutputFile(const std::string &Path,
660 const std::string &OldPrefix,
661 const std::string &NewPrefix) {
662 if (OldPrefix.empty() && NewPrefix.empty())
663 return Path;
664 SmallString<128> NewPath(Path);
665 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
666 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
667 if (!ParentPath.empty()) {
668 // Make sure the new directory exists, creating it if necessary.
669 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
670 llvm::errs() << "warning: could not create directory '" << ParentPath
671 << "': " << EC.message() << '\n';
672 }
673 return NewPath.str();
674}
675
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000676class WriteIndexesThinBackend : public ThinBackendProc {
677 std::string OldPrefix, NewPrefix;
678 bool ShouldEmitImportsFiles;
679
680 std::string LinkedObjectsFileName;
681 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
682
683public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000684 WriteIndexesThinBackend(
685 Config &Conf, ModuleSummaryIndex &CombinedIndex,
686 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
687 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
688 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000689 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000690 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
691 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
692 LinkedObjectsFileName(LinkedObjectsFileName) {}
693
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000694 Error start(
695 unsigned Task, MemoryBufferRef MBRef,
696 const FunctionImporter::ImportMapTy &ImportList,
697 const FunctionImporter::ExportSetTy &ExportList,
698 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
699 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000700 StringRef ModulePath = MBRef.getBufferIdentifier();
701 std::string NewModulePath =
702 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
703
704 std::error_code EC;
705 if (!LinkedObjectsFileName.empty()) {
706 if (!LinkedObjectsFile) {
707 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
708 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
709 if (EC)
710 return errorCodeToError(EC);
711 }
712 *LinkedObjectsFile << NewModulePath << '\n';
713 }
714
715 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
716 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000717 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000718
719 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
720 sys::fs::OpenFlags::F_None);
721 if (EC)
722 return errorCodeToError(EC);
723 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
724
725 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000726 return errorCodeToError(
727 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000728 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000729 }
730
Mehdi Amini41af4302016-11-11 04:28:40 +0000731 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000732};
733
734ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
735 std::string NewPrefix,
736 bool ShouldEmitImportsFiles,
737 std::string LinkedObjectsFile) {
738 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000739 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000740 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000741 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000742 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
743 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000744 };
745}
746
Peter Collingbourne80186a52016-09-23 21:33:43 +0000747Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
748 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000749 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000750 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000751
752 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000753 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000754
755 // Collect for each module the list of function it defines (GUID ->
756 // Summary).
757 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
758 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
759 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
760 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000761 // Create entries for any modules that didn't have any GV summaries
762 // (either they didn't have any GVs to start with, or we suppressed
763 // generation of the summaries because they e.g. had inline assembly
764 // uses that couldn't be promoted/renamed on export). This is so
765 // InProcessThinBackend::start can still launch a backend thread, which
766 // is passed the map of summaries for the module, without any special
767 // handling for this case.
768 for (auto &Mod : ThinLTO.ModuleMap)
769 if (!ModuleToDefinedGVSummaries.count(Mod.first))
770 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000771
772 StringMap<FunctionImporter::ImportMapTy> ImportLists(
773 ThinLTO.ModuleMap.size());
774 StringMap<FunctionImporter::ExportSetTy> ExportLists(
775 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000776 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000777
Teresa Johnson002af9b2016-10-31 22:12:21 +0000778 if (Conf.OptLevel > 0) {
779 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
780 ImportLists, ExportLists);
781
782 std::set<GlobalValue::GUID> ExportedGUIDs;
783 for (auto &Res : GlobalResolutions) {
784 if (!Res.second.IRName.empty() &&
785 Res.second.Partition == GlobalResolution::External)
786 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
787 }
788
789 auto isPrevailing = [&](GlobalValue::GUID GUID,
790 const GlobalValueSummary *S) {
791 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
792 };
793 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
794 const auto &ExportList = ExportLists.find(ModuleIdentifier);
795 return (ExportList != ExportLists.end() &&
796 ExportList->second.count(GUID)) ||
797 ExportedGUIDs.count(GUID);
798 };
799 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
800
801 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
802 GlobalValue::GUID GUID,
803 GlobalValue::LinkageTypes NewLinkage) {
804 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
805 };
806
807 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
808 recordNewLinkage);
809 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000810
Peter Collingbourne80186a52016-09-23 21:33:43 +0000811 std::unique_ptr<ThinBackendProc> BackendProc =
812 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
813 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000814
815 // Partition numbers for ThinLTO jobs start at 1 (see comments for
816 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000817 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
818 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
819 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000820 unsigned Task =
821 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000822 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000823
824 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000825 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000826 ExportLists[Mod.first],
827 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000828 return E;
829
830 ++Task;
831 ++Partition;
832 }
833
834 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000835}