blob: 32bddbc8f1adc8f59aa4b7b35d128c7b31e37bd6 [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 Johnsondf6edc52016-05-23 22:54:06 +000017#include "llvm/Bitcode/ReaderWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000018#include "llvm/CodeGen/Analysis.h"
19#include "llvm/IR/AutoUpgrade.h"
20#include "llvm/IR/DiagnosticPrinter.h"
21#include "llvm/IR/LegacyPassManager.h"
22#include "llvm/LTO/LTOBackend.h"
23#include "llvm/Linker/IRMover.h"
24#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
25#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000026#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000027#include "llvm/Support/Path.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000028#include "llvm/Support/SHA1.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000029#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000030#include "llvm/Support/TargetRegistry.h"
31#include "llvm/Support/ThreadPool.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000032#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000033#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetOptions.h"
35#include "llvm/Transforms/IPO.h"
36#include "llvm/Transforms/IPO/PassManagerBuilder.h"
37#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000038
Teresa Johnson9ba95f92016-08-11 14:58:12 +000039#include <set>
40
41using namespace llvm;
42using namespace lto;
43using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000044
Mehdi Aminiadc0e262016-08-23 21:30:12 +000045#define DEBUG_TYPE "lto"
46
47// Returns a unique hash for the Module considering the current list of
48// export/import and other global analysis results.
49// The hash is produced in \p Key.
50static void computeCacheKey(
51 SmallString<40> &Key, const ModuleSummaryIndex &Index, StringRef ModuleID,
52 const FunctionImporter::ImportMapTy &ImportList,
53 const FunctionImporter::ExportSetTy &ExportList,
54 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
55 const GVSummaryMapTy &DefinedGlobals) {
56 // Compute the unique hash for this entry.
57 // This is based on the current compiler version, the module itself, the
58 // export list, the hash for every single module in the import list, the
59 // list of ResolvedODR for the module, and the list of preserved symbols.
60 SHA1 Hasher;
61
62 // Start with the compiler revision
63 Hasher.update(LLVM_VERSION_STRING);
64#ifdef HAVE_LLVM_REVISION
65 Hasher.update(LLVM_REVISION);
66#endif
67
68 // Include the hash for the current module
69 auto ModHash = Index.getModuleHash(ModuleID);
70 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
71 for (auto F : ExportList)
72 // The export list can impact the internalization, be conservative here
73 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
74
75 // Include the hash for every module we import functions from
76 for (auto &Entry : ImportList) {
77 auto ModHash = Index.getModuleHash(Entry.first());
78 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
79 }
80
81 // Include the hash for the resolved ODR.
82 for (auto &Entry : ResolvedODR) {
83 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
84 sizeof(GlobalValue::GUID)));
85 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
86 sizeof(GlobalValue::LinkageTypes)));
87 }
88
89 // Include the hash for the linkage type to reflect internalization and weak
90 // resolution.
91 for (auto &GS : DefinedGlobals) {
92 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
93 Hasher.update(
94 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
95 }
96
97 Key = toHex(Hasher.result());
98}
99
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000100// Simple helper to load a module from bitcode
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000101std::unique_ptr<Module>
102llvm::loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
103 bool Lazy) {
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000104 SMDiagnostic Err;
105 ErrorOr<std::unique_ptr<Module>> ModuleOrErr(nullptr);
106 if (Lazy) {
107 ModuleOrErr =
108 getLazyBitcodeModule(MemoryBuffer::getMemBuffer(Buffer, false), Context,
109 /* ShouldLazyLoadMetadata */ Lazy);
110 } else {
111 ModuleOrErr = parseBitcodeFile(Buffer, Context);
112 }
113 if (std::error_code EC = ModuleOrErr.getError()) {
114 Err = SMDiagnostic(Buffer.getBufferIdentifier(), SourceMgr::DK_Error,
115 EC.message());
116 Err.print("ThinLTO", errs());
117 report_fatal_error("Can't load module, abort.");
118 }
119 return std::move(ModuleOrErr.get());
120}
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000121
122static void thinLTOResolveWeakForLinkerGUID(
123 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
124 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000125 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000126 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000127 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000128 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000129 for (auto &S : GVSummaryList) {
130 if (GlobalInvolvedWithAlias.count(S.get()))
131 continue;
132 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
133 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
134 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000135 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000136 // but turned into a weak, while the others will drop it when possible.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000137 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000138 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
139 S->setLinkage(GlobalValue::getWeakLinkage(
140 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000141 }
142 // Alias can't be turned into available_externally.
143 else if (!isa<AliasSummary>(S.get()) &&
144 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
145 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
146 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
147 if (S->linkage() != OriginalLinkage)
148 recordNewLinkage(S->modulePath(), GUID, S->linkage());
149 }
150}
151
152// Resolve Weak and LinkOnce values in the \p Index.
153//
154// We'd like to drop these functions if they are no longer referenced in the
155// current module. However there is a chance that another module is still
156// referencing them because of the import. We make sure we always emit at least
157// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000158void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000159 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000160 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000161 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000162 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000163 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000164 // We won't optimize the globals that are referenced by an alias for now
165 // Ideally we should turn the alias into a global and duplicate the definition
166 // when needed.
167 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
168 for (auto &I : Index)
169 for (auto &S : I.second)
170 if (auto AS = dyn_cast<AliasSummary>(S.get()))
171 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
172
173 for (auto &I : Index)
174 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000175 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000176}
177
178static void thinLTOInternalizeAndPromoteGUID(
179 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000180 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000181 for (auto &S : GVSummaryList) {
182 if (isExported(S->modulePath(), GUID)) {
183 if (GlobalValue::isLocalLinkage(S->linkage()))
184 S->setLinkage(GlobalValue::ExternalLinkage);
185 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
186 S->setLinkage(GlobalValue::InternalLinkage);
187 }
188}
189
190// Update the linkages in the given \p Index to mark exported values
191// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000192void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000193 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000194 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000195 for (auto &I : Index)
196 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
197}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000198
199Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
200 std::unique_ptr<InputFile> File(new InputFile);
201 std::string Msg;
202 auto DiagHandler = [](const DiagnosticInfo &DI, void *MsgP) {
203 auto *Msg = reinterpret_cast<std::string *>(MsgP);
204 raw_string_ostream OS(*Msg);
205 DiagnosticPrinterRawOStream DP(OS);
206 DI.print(DP);
207 };
208 File->Ctx.setDiagnosticHandler(DiagHandler, static_cast<void *>(&Msg));
209
210 ErrorOr<std::unique_ptr<object::IRObjectFile>> IRObj =
211 IRObjectFile::create(Object, File->Ctx);
212 if (!Msg.empty())
213 return make_error<StringError>(Msg, inconvertibleErrorCode());
214 if (!IRObj)
215 return errorCodeToError(IRObj.getError());
216 File->Obj = std::move(*IRObj);
217
218 File->Ctx.setDiagnosticHandler(nullptr, nullptr);
219
220 return std::move(File);
221}
222
223LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
224 Config &Conf)
225 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000226 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000227
228LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
229 if (!Backend)
230 this->Backend = createInProcessThinBackend(thread::hardware_concurrency());
231}
232
233LTO::LTO(Config Conf, ThinBackend Backend,
234 unsigned ParallelCodeGenParallelismLevel)
235 : Conf(std::move(Conf)),
236 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000237 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000238
239// Add the given symbol to the GlobalResolutions map, and resolve its partition.
240void LTO::addSymbolToGlobalRes(IRObjectFile *Obj,
241 SmallPtrSet<GlobalValue *, 8> &Used,
242 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000243 SymbolResolution Res, unsigned Partition) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000244 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
245
246 auto &GlobalRes = GlobalResolutions[Sym.getName()];
247 if (GV) {
248 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
249 if (Res.Prevailing)
250 GlobalRes.IRName = GV->getName();
251 }
252 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
253 (GlobalRes.Partition != GlobalResolution::Unknown &&
254 GlobalRes.Partition != Partition))
255 GlobalRes.Partition = GlobalResolution::External;
256 else
257 GlobalRes.Partition = Partition;
258}
259
Rafael Espindola7775c332016-08-26 20:19:35 +0000260static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
261 ArrayRef<SymbolResolution> Res) {
262 StringRef Path = Input->getMemoryBufferRef().getBufferIdentifier();
263 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000264 auto ResI = Res.begin();
265 for (const InputFile::Symbol &Sym : Input->symbols()) {
266 assert(ResI != Res.end());
267 SymbolResolution Res = *ResI++;
268
Rafael Espindola7775c332016-08-26 20:19:35 +0000269 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000270 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000271 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000272 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000273 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000274 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000275 OS << 'x';
276 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000277 }
278 assert(ResI == Res.end());
279}
280
281Error LTO::add(std::unique_ptr<InputFile> Input,
282 ArrayRef<SymbolResolution> Res) {
283 assert(!CalledGetMaxTasks);
284
285 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000286 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000287
Mehdi Amini9989f802016-08-19 15:35:44 +0000288 // FIXME: move to backend
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000289 Module &M = Input->Obj->getModule();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000290 if (!Conf.OverrideTriple.empty())
291 M.setTargetTriple(Conf.OverrideTriple);
292 else if (M.getTargetTriple().empty())
293 M.setTargetTriple(Conf.DefaultTriple);
294
295 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
296 bool HasThinLTOSummary = hasGlobalValueSummary(MBRef, Conf.DiagHandler);
297
298 if (HasThinLTOSummary)
299 return addThinLTO(std::move(Input), Res);
300 else
301 return addRegularLTO(std::move(Input), Res);
302}
303
304// Add a regular LTO object to the link.
305Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
306 ArrayRef<SymbolResolution> Res) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000307 if (!RegularLTO.CombinedModule) {
308 RegularLTO.CombinedModule =
309 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
310 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
311 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000312 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
313 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
314 if (!ObjOrErr)
315 return errorCodeToError(ObjOrErr.getError());
316 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
317
318 Module &M = Obj->getModule();
319 M.materializeMetadata();
320 UpgradeDebugInfo(M);
321
322 SmallPtrSet<GlobalValue *, 8> Used;
323 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
324
325 std::vector<GlobalValue *> Keep;
326
327 for (GlobalVariable &GV : M.globals())
328 if (GV.hasAppendingLinkage())
329 Keep.push_back(&GV);
330
331 auto ResI = Res.begin();
332 for (const InputFile::Symbol &Sym :
333 make_range(InputFile::symbol_iterator(Obj->symbol_begin()),
334 InputFile::symbol_iterator(Obj->symbol_end()))) {
335 assert(ResI != Res.end());
336 SymbolResolution Res = *ResI++;
337 addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
338
339 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
340 if (Res.Prevailing && GV) {
341 Keep.push_back(GV);
342 switch (GV->getLinkage()) {
343 default:
344 break;
345 case GlobalValue::LinkOnceAnyLinkage:
346 GV->setLinkage(GlobalValue::WeakAnyLinkage);
347 break;
348 case GlobalValue::LinkOnceODRLinkage:
349 GV->setLinkage(GlobalValue::WeakODRLinkage);
350 break;
351 }
352 }
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000353 // Common resolution: collect the maximum size/alignment.
354 // FIXME: right now we ignore the prevailing information, it is not clear
355 // what is the "right" behavior here.
356 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
357 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
358 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
359 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
360 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000361
362 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
363 }
364 assert(ResI == Res.end());
365
Mehdi Aminie7494532016-08-23 18:39:12 +0000366 return RegularLTO.Mover->move(Obj->takeModule(), Keep,
367 [](GlobalValue &, IRMover::ValueAdder) {});
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000368}
369
370// Add a ThinLTO object to the link.
371Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
372 ArrayRef<SymbolResolution> Res) {
373 Module &M = Input->Obj->getModule();
374 SmallPtrSet<GlobalValue *, 8> Used;
375 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
376
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000377 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
378 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
379 SummaryObjOrErr =
380 object::ModuleSummaryIndexObjectFile::create(MBRef, Conf.DiagHandler);
381 if (!SummaryObjOrErr)
382 return errorCodeToError(SummaryObjOrErr.getError());
383 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
384 ThinLTO.ModuleMap.size());
385
386 auto ResI = Res.begin();
387 for (const InputFile::Symbol &Sym : Input->symbols()) {
388 assert(ResI != Res.end());
389 SymbolResolution Res = *ResI++;
390 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
391 ThinLTO.ModuleMap.size() + 1);
392
393 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
394 if (Res.Prevailing && GV)
395 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
396 MBRef.getBufferIdentifier();
397 }
398 assert(ResI == Res.end());
399
400 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
401 return Error();
402}
403
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000404unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000405 CalledGetMaxTasks = true;
406 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
407}
408
Mehdi Amini970800e2016-08-17 06:23:09 +0000409Error LTO::run(AddOutputFn AddOutput) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000410 // Invoke regular LTO if there was a regular LTO module to start with.
411 if (RegularLTO.CombinedModule)
Mehdi Amini970800e2016-08-17 06:23:09 +0000412 if (auto E = runRegularLTO(AddOutput))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000413 return E;
Mehdi Amini970800e2016-08-17 06:23:09 +0000414 return runThinLTO(AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000415}
416
Mehdi Amini970800e2016-08-17 06:23:09 +0000417Error LTO::runRegularLTO(AddOutputFn AddOutput) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000418 // Make sure commons have the right size/alignment: we kept the largest from
419 // all the prevailing when adding the inputs, and we apply it here.
420 for (auto &I : RegularLTO.Commons) {
421 ArrayType *Ty =
422 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
423 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
424 if (OldGV && OldGV->getType()->getElementType() == Ty) {
425 // Don't create a new global if the type is already correct, just make
426 // sure the alignment is correct.
427 OldGV->setAlignment(I.second.Align);
428 continue;
429 }
430 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
431 GlobalValue::CommonLinkage,
432 ConstantAggregateZero::get(Ty), "");
433 GV->setAlignment(I.second.Align);
434 if (OldGV) {
435 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
436 GV->takeName(OldGV);
437 OldGV->eraseFromParent();
438 } else {
439 GV->setName(I.first);
440 }
441 }
442
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000443 if (Conf.PreOptModuleHook &&
444 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
445 return Error();
446
Mehdi Aminid310b472016-08-22 06:25:41 +0000447 if (!Conf.CodeGenOnly) {
448 for (const auto &R : GlobalResolutions) {
449 if (R.second.IRName.empty())
450 continue;
451 if (R.second.Partition != 0 &&
452 R.second.Partition != GlobalResolution::External)
453 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000454
Mehdi Aminid310b472016-08-22 06:25:41 +0000455 GlobalValue *GV =
456 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
457 // Ignore symbols defined in other partitions.
458 if (!GV || GV->hasLocalLinkage())
459 continue;
460 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
461 : GlobalValue::UnnamedAddr::None);
462 if (R.second.Partition == 0)
463 GV->setLinkage(GlobalValue::InternalLinkage);
464 }
465
466 if (Conf.PostInternalizeModuleHook &&
467 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
468 return Error();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000469 }
Mehdi Amini970800e2016-08-17 06:23:09 +0000470 return backend(Conf, AddOutput, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000471 std::move(RegularLTO.CombinedModule));
472}
473
474/// This class defines the interface to the ThinLTO backend.
475class lto::ThinBackendProc {
476protected:
477 Config &Conf;
478 ModuleSummaryIndex &CombinedIndex;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000479 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
480
481public:
482 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000483 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000484 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000485 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
486
487 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000488 virtual Error start(
489 unsigned Task, MemoryBufferRef MBRef,
490 const FunctionImporter::ImportMapTy &ImportList,
491 const FunctionImporter::ExportSetTy &ExportList,
492 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
493 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000494 virtual Error wait() = 0;
495};
496
497class InProcessThinBackend : public ThinBackendProc {
498 ThreadPool BackendThreadPool;
Mehdi Amini18b91112016-08-19 06:10:03 +0000499 AddOutputFn AddOutput;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000500
501 Optional<Error> Err;
502 std::mutex ErrMu;
503
504public:
505 InProcessThinBackend(Config &Conf, ModuleSummaryIndex &CombinedIndex,
506 unsigned ThinLTOParallelismLevel,
507 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000508 AddOutputFn AddOutput)
Mehdi Amini18b91112016-08-19 06:10:03 +0000509 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
510 BackendThreadPool(ThinLTOParallelismLevel),
511 AddOutput(std::move(AddOutput)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000512
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000513 Error runThinLTOBackendThread(
514 AddOutputFn AddOutput, unsigned Task, MemoryBufferRef MBRef,
515 ModuleSummaryIndex &CombinedIndex,
516 const FunctionImporter::ImportMapTy &ImportList,
517 const FunctionImporter::ExportSetTy &ExportList,
518 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
519 const GVSummaryMapTy &DefinedGlobals,
520 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000521
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000522 auto ModuleIdentifier = MBRef.getBufferIdentifier();
523 auto Output = AddOutput(Task);
524 if (Output->isCachingEnabled()) {
525 SmallString<40> Key;
526 // The module may be cached, this helps handling it.
527 computeCacheKey(Key, CombinedIndex, ModuleIdentifier, ImportList,
528 ExportList, ResolvedODR, DefinedGlobals);
529 if (Output->tryLoadFromCache(Key))
530 return Error();
531 }
532
533 LTOLLVMContext BackendContext(Conf);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000534 ErrorOr<std::unique_ptr<Module>> MOrErr =
535 parseBitcodeFile(MBRef, BackendContext);
536 assert(MOrErr && "Unable to load module in thread?");
537
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000538 auto AddOutputWrapper = [&](unsigned TaskId) {
539 assert(Task == TaskId && "Unexpexted TaskId mismatch");
540 return std::move(Output);
541 };
542 return thinBackend(Conf, Task, AddOutputWrapper, **MOrErr, CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000543 ImportList, DefinedGlobals, ModuleMap);
544 }
545
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000546 Error start(
547 unsigned Task, MemoryBufferRef MBRef,
548 const FunctionImporter::ImportMapTy &ImportList,
549 const FunctionImporter::ExportSetTy &ExportList,
550 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
551 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000552 StringRef ModulePath = MBRef.getBufferIdentifier();
553 BackendThreadPool.async(
554 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
555 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000556 const FunctionImporter::ExportSetTy &ExportList,
557 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
558 &ResolvedODR,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000559 GVSummaryMapTy &DefinedGlobals,
560 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000561 Error E = runThinLTOBackendThread(
562 AddOutput, Task, MBRef, CombinedIndex, ImportList, ExportList,
563 ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000564 if (E) {
565 std::unique_lock<std::mutex> L(ErrMu);
566 if (Err)
567 Err = joinErrors(std::move(*Err), std::move(E));
568 else
569 Err = std::move(E);
570 }
571 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000572 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000573 std::ref(ExportList), std::ref(ResolvedODR),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000574 std::ref(ModuleToDefinedGVSummaries[ModulePath]), std::ref(ModuleMap));
575 return Error();
576 }
577
578 Error wait() override {
579 BackendThreadPool.wait();
580 if (Err)
581 return std::move(*Err);
582 else
583 return Error();
584 }
585};
586
587ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
588 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
589 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000590 AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000591 return llvm::make_unique<InProcessThinBackend>(
592 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000593 AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000594 };
595}
596
597class WriteIndexesThinBackend : public ThinBackendProc {
598 std::string OldPrefix, NewPrefix;
599 bool ShouldEmitImportsFiles;
600
601 std::string LinkedObjectsFileName;
602 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
603
604public:
605 WriteIndexesThinBackend(Config &Conf, ModuleSummaryIndex &CombinedIndex,
606 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini18b91112016-08-19 06:10:03 +0000607 std::string OldPrefix, std::string NewPrefix,
608 bool ShouldEmitImportsFiles,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000609 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000610 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000611 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
612 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
613 LinkedObjectsFileName(LinkedObjectsFileName) {}
614
615 /// Given the original \p Path to an output file, replace any path
616 /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
617 /// resulting directory if it does not yet exist.
618 std::string getThinLTOOutputFile(const std::string &Path,
619 const std::string &OldPrefix,
620 const std::string &NewPrefix) {
621 if (OldPrefix.empty() && NewPrefix.empty())
622 return Path;
623 SmallString<128> NewPath(Path);
624 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
625 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
626 if (!ParentPath.empty()) {
627 // Make sure the new directory exists, creating it if necessary.
628 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
629 llvm::errs() << "warning: could not create directory '" << ParentPath
630 << "': " << EC.message() << '\n';
631 }
632 return NewPath.str();
633 }
634
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000635 Error start(
636 unsigned Task, MemoryBufferRef MBRef,
637 const FunctionImporter::ImportMapTy &ImportList,
638 const FunctionImporter::ExportSetTy &ExportList,
639 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
640 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000641 StringRef ModulePath = MBRef.getBufferIdentifier();
642 std::string NewModulePath =
643 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
644
645 std::error_code EC;
646 if (!LinkedObjectsFileName.empty()) {
647 if (!LinkedObjectsFile) {
648 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
649 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
650 if (EC)
651 return errorCodeToError(EC);
652 }
653 *LinkedObjectsFile << NewModulePath << '\n';
654 }
655
656 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
657 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000658 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000659
660 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
661 sys::fs::OpenFlags::F_None);
662 if (EC)
663 return errorCodeToError(EC);
664 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
665
666 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000667 return errorCodeToError(
668 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000669 return Error();
670 }
671
672 Error wait() override { return Error(); }
673};
674
675ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
676 std::string NewPrefix,
677 bool ShouldEmitImportsFiles,
678 std::string LinkedObjectsFile) {
679 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
680 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000681 AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000682 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000683 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
684 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000685 };
686}
687
Mehdi Amini970800e2016-08-17 06:23:09 +0000688Error LTO::runThinLTO(AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000689 if (ThinLTO.ModuleMap.empty())
690 return Error();
691
692 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
693 return Error();
694
695 // Collect for each module the list of function it defines (GUID ->
696 // Summary).
697 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
698 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
699 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
700 ModuleToDefinedGVSummaries);
701
702 StringMap<FunctionImporter::ImportMapTy> ImportLists(
703 ThinLTO.ModuleMap.size());
704 StringMap<FunctionImporter::ExportSetTy> ExportLists(
705 ThinLTO.ModuleMap.size());
706 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
707 ImportLists, ExportLists);
708
709 std::set<GlobalValue::GUID> ExportedGUIDs;
710 for (auto &Res : GlobalResolutions) {
711 if (!Res.second.IRName.empty() &&
712 Res.second.Partition == GlobalResolution::External)
713 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
714 }
715
716 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
717 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
718 };
719 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
720 const auto &ExportList = ExportLists.find(ModuleIdentifier);
721 return (ExportList != ExportLists.end() &&
722 ExportList->second.count(GUID)) ||
723 ExportedGUIDs.count(GUID);
724 };
725 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000726
727 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
728 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
729 GlobalValue::GUID GUID,
730 GlobalValue::LinkageTypes NewLinkage) {
731 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
732 };
733
734 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
735 recordNewLinkage);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000736
737 std::unique_ptr<ThinBackendProc> BackendProc = ThinLTO.Backend(
Mehdi Amini970800e2016-08-17 06:23:09 +0000738 Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries, AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000739
740 // Partition numbers for ThinLTO jobs start at 1 (see comments for
741 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000742 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
743 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
744 // generation partitions.
Mehdi Aminie7494532016-08-23 18:39:12 +0000745 unsigned Task = RegularLTO.CombinedModule
746 ? RegularLTO.ParallelCodeGenParallelismLevel
747 : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000748 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000749
750 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000751 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000752 ExportLists[Mod.first],
753 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000754 return E;
755
756 ++Task;
757 ++Partition;
758 }
759
760 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000761}