blob: 0d47cd49a172ea9f501ce955352e1444bb7c5e0a [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());
Davide Italiano39ccd242016-09-13 18:45:13 +0000340 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
341 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000342 if (Res.Prevailing && GV) {
343 Keep.push_back(GV);
344 switch (GV->getLinkage()) {
345 default:
346 break;
347 case GlobalValue::LinkOnceAnyLinkage:
348 GV->setLinkage(GlobalValue::WeakAnyLinkage);
349 break;
350 case GlobalValue::LinkOnceODRLinkage:
351 GV->setLinkage(GlobalValue::WeakODRLinkage);
352 break;
353 }
354 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000355 // Common resolution: collect the maximum size/alignment over all commons.
356 // We also record if we see an instance of a common as prevailing, so that
357 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000358 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
359 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
360 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
361 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000362 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000363 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000364
365 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
366 }
367 assert(ResI == Res.end());
368
Mehdi Aminie7494532016-08-23 18:39:12 +0000369 return RegularLTO.Mover->move(Obj->takeModule(), Keep,
370 [](GlobalValue &, IRMover::ValueAdder) {});
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000371}
372
373// Add a ThinLTO object to the link.
374Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
375 ArrayRef<SymbolResolution> Res) {
376 Module &M = Input->Obj->getModule();
377 SmallPtrSet<GlobalValue *, 8> Used;
378 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
379
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000380 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
381 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
382 SummaryObjOrErr =
383 object::ModuleSummaryIndexObjectFile::create(MBRef, Conf.DiagHandler);
384 if (!SummaryObjOrErr)
385 return errorCodeToError(SummaryObjOrErr.getError());
386 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
387 ThinLTO.ModuleMap.size());
388
389 auto ResI = Res.begin();
390 for (const InputFile::Symbol &Sym : Input->symbols()) {
391 assert(ResI != Res.end());
392 SymbolResolution Res = *ResI++;
393 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
394 ThinLTO.ModuleMap.size() + 1);
395
396 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
397 if (Res.Prevailing && GV)
398 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
399 MBRef.getBufferIdentifier();
400 }
401 assert(ResI == Res.end());
402
403 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
404 return Error();
405}
406
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000407unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000408 CalledGetMaxTasks = true;
409 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
410}
411
Mehdi Amini970800e2016-08-17 06:23:09 +0000412Error LTO::run(AddOutputFn AddOutput) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000413 // Save the status of having a regularLTO combined module, as
414 // this is needed for generating the ThinLTO Task ID, and
415 // the CombinedModule will be moved at the end of runRegularLTO.
416 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000417 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000418 if (HasRegularLTO)
Mehdi Amini970800e2016-08-17 06:23:09 +0000419 if (auto E = runRegularLTO(AddOutput))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000420 return E;
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000421 return runThinLTO(AddOutput, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000422}
423
Mehdi Amini970800e2016-08-17 06:23:09 +0000424Error LTO::runRegularLTO(AddOutputFn AddOutput) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000425 // Make sure commons have the right size/alignment: we kept the largest from
426 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000427 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000428 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000429 if (!I.second.Prevailing)
430 // Don't do anything if no instance of this common was prevailing.
431 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000432 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000433 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000434 // Don't create a new global if the type is already correct, just make
435 // sure the alignment is correct.
436 OldGV->setAlignment(I.second.Align);
437 continue;
438 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000439 ArrayType *Ty =
440 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000441 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
442 GlobalValue::CommonLinkage,
443 ConstantAggregateZero::get(Ty), "");
444 GV->setAlignment(I.second.Align);
445 if (OldGV) {
446 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
447 GV->takeName(OldGV);
448 OldGV->eraseFromParent();
449 } else {
450 GV->setName(I.first);
451 }
452 }
453
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000454 if (Conf.PreOptModuleHook &&
455 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
456 return Error();
457
Mehdi Aminid310b472016-08-22 06:25:41 +0000458 if (!Conf.CodeGenOnly) {
459 for (const auto &R : GlobalResolutions) {
460 if (R.second.IRName.empty())
461 continue;
462 if (R.second.Partition != 0 &&
463 R.second.Partition != GlobalResolution::External)
464 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000465
Mehdi Aminid310b472016-08-22 06:25:41 +0000466 GlobalValue *GV =
467 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
468 // Ignore symbols defined in other partitions.
469 if (!GV || GV->hasLocalLinkage())
470 continue;
471 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
472 : GlobalValue::UnnamedAddr::None);
473 if (R.second.Partition == 0)
474 GV->setLinkage(GlobalValue::InternalLinkage);
475 }
476
477 if (Conf.PostInternalizeModuleHook &&
478 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
479 return Error();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000480 }
Mehdi Amini970800e2016-08-17 06:23:09 +0000481 return backend(Conf, AddOutput, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000482 std::move(RegularLTO.CombinedModule));
483}
484
485/// This class defines the interface to the ThinLTO backend.
486class lto::ThinBackendProc {
487protected:
488 Config &Conf;
489 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000490 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000491
492public:
493 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000494 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000495 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000496 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
497
498 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000499 virtual Error start(
500 unsigned Task, MemoryBufferRef MBRef,
501 const FunctionImporter::ImportMapTy &ImportList,
502 const FunctionImporter::ExportSetTy &ExportList,
503 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
504 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000505 virtual Error wait() = 0;
506};
507
508class InProcessThinBackend : public ThinBackendProc {
509 ThreadPool BackendThreadPool;
Mehdi Amini18b91112016-08-19 06:10:03 +0000510 AddOutputFn AddOutput;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000511
512 Optional<Error> Err;
513 std::mutex ErrMu;
514
515public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000516 InProcessThinBackend(
517 Config &Conf, ModuleSummaryIndex &CombinedIndex,
518 unsigned ThinLTOParallelismLevel,
519 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
520 AddOutputFn AddOutput)
Mehdi Amini18b91112016-08-19 06:10:03 +0000521 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
522 BackendThreadPool(ThinLTOParallelismLevel),
523 AddOutput(std::move(AddOutput)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000524
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000525 Error runThinLTOBackendThread(
526 AddOutputFn AddOutput, unsigned Task, MemoryBufferRef MBRef,
527 ModuleSummaryIndex &CombinedIndex,
528 const FunctionImporter::ImportMapTy &ImportList,
529 const FunctionImporter::ExportSetTy &ExportList,
530 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
531 const GVSummaryMapTy &DefinedGlobals,
532 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000533
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000534 auto ModuleIdentifier = MBRef.getBufferIdentifier();
535 auto Output = AddOutput(Task);
536 if (Output->isCachingEnabled()) {
537 SmallString<40> Key;
538 // The module may be cached, this helps handling it.
539 computeCacheKey(Key, CombinedIndex, ModuleIdentifier, ImportList,
540 ExportList, ResolvedODR, DefinedGlobals);
541 if (Output->tryLoadFromCache(Key))
542 return Error();
543 }
544
545 LTOLLVMContext BackendContext(Conf);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000546 ErrorOr<std::unique_ptr<Module>> MOrErr =
547 parseBitcodeFile(MBRef, BackendContext);
548 assert(MOrErr && "Unable to load module in thread?");
549
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000550 auto AddOutputWrapper = [&](unsigned TaskId) {
551 assert(Task == TaskId && "Unexpexted TaskId mismatch");
552 return std::move(Output);
553 };
554 return thinBackend(Conf, Task, AddOutputWrapper, **MOrErr, CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000555 ImportList, DefinedGlobals, ModuleMap);
556 }
557
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000558 Error start(
559 unsigned Task, MemoryBufferRef MBRef,
560 const FunctionImporter::ImportMapTy &ImportList,
561 const FunctionImporter::ExportSetTy &ExportList,
562 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
563 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000564 StringRef ModulePath = MBRef.getBufferIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000565 assert(ModuleToDefinedGVSummaries.count(ModulePath));
566 const GVSummaryMapTy &DefinedGlobals =
567 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000568 BackendThreadPool.async(
569 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
570 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000571 const FunctionImporter::ExportSetTy &ExportList,
572 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
573 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000574 const GVSummaryMapTy &DefinedGlobals,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000575 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000576 Error E = runThinLTOBackendThread(
577 AddOutput, Task, MBRef, CombinedIndex, ImportList, ExportList,
578 ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000579 if (E) {
580 std::unique_lock<std::mutex> L(ErrMu);
581 if (Err)
582 Err = joinErrors(std::move(*Err), std::move(E));
583 else
584 Err = std::move(E);
585 }
586 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000587 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000588 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
589 std::ref(ModuleMap));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000590 return Error();
591 }
592
593 Error wait() override {
594 BackendThreadPool.wait();
595 if (Err)
596 return std::move(*Err);
597 else
598 return Error();
599 }
600};
601
602ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
603 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000604 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000605 AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000606 return llvm::make_unique<InProcessThinBackend>(
607 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000608 AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000609 };
610}
611
612class WriteIndexesThinBackend : public ThinBackendProc {
613 std::string OldPrefix, NewPrefix;
614 bool ShouldEmitImportsFiles;
615
616 std::string LinkedObjectsFileName;
617 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
618
619public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000620 WriteIndexesThinBackend(
621 Config &Conf, ModuleSummaryIndex &CombinedIndex,
622 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
623 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
624 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000625 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000626 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
627 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
628 LinkedObjectsFileName(LinkedObjectsFileName) {}
629
630 /// Given the original \p Path to an output file, replace any path
631 /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
632 /// resulting directory if it does not yet exist.
633 std::string getThinLTOOutputFile(const std::string &Path,
634 const std::string &OldPrefix,
635 const std::string &NewPrefix) {
636 if (OldPrefix.empty() && NewPrefix.empty())
637 return Path;
638 SmallString<128> NewPath(Path);
639 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
640 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
641 if (!ParentPath.empty()) {
642 // Make sure the new directory exists, creating it if necessary.
643 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
644 llvm::errs() << "warning: could not create directory '" << ParentPath
645 << "': " << EC.message() << '\n';
646 }
647 return NewPath.str();
648 }
649
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000650 Error start(
651 unsigned Task, MemoryBufferRef MBRef,
652 const FunctionImporter::ImportMapTy &ImportList,
653 const FunctionImporter::ExportSetTy &ExportList,
654 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
655 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000656 StringRef ModulePath = MBRef.getBufferIdentifier();
657 std::string NewModulePath =
658 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
659
660 std::error_code EC;
661 if (!LinkedObjectsFileName.empty()) {
662 if (!LinkedObjectsFile) {
663 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
664 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
665 if (EC)
666 return errorCodeToError(EC);
667 }
668 *LinkedObjectsFile << NewModulePath << '\n';
669 }
670
671 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
672 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000673 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000674
675 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
676 sys::fs::OpenFlags::F_None);
677 if (EC)
678 return errorCodeToError(EC);
679 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
680
681 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000682 return errorCodeToError(
683 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000684 return Error();
685 }
686
687 Error wait() override { return Error(); }
688};
689
690ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
691 std::string NewPrefix,
692 bool ShouldEmitImportsFiles,
693 std::string LinkedObjectsFile) {
694 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000695 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000696 AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000697 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000698 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
699 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000700 };
701}
702
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000703Error LTO::runThinLTO(AddOutputFn AddOutput, bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000704 if (ThinLTO.ModuleMap.empty())
705 return Error();
706
707 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
708 return Error();
709
710 // Collect for each module the list of function it defines (GUID ->
711 // Summary).
712 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
713 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
714 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
715 ModuleToDefinedGVSummaries);
716
717 StringMap<FunctionImporter::ImportMapTy> ImportLists(
718 ThinLTO.ModuleMap.size());
719 StringMap<FunctionImporter::ExportSetTy> ExportLists(
720 ThinLTO.ModuleMap.size());
721 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
722 ImportLists, ExportLists);
723
724 std::set<GlobalValue::GUID> ExportedGUIDs;
725 for (auto &Res : GlobalResolutions) {
726 if (!Res.second.IRName.empty() &&
727 Res.second.Partition == GlobalResolution::External)
728 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
729 }
730
731 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
732 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
733 };
734 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
735 const auto &ExportList = ExportLists.find(ModuleIdentifier);
736 return (ExportList != ExportLists.end() &&
737 ExportList->second.count(GUID)) ||
738 ExportedGUIDs.count(GUID);
739 };
740 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000741
742 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
743 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
744 GlobalValue::GUID GUID,
745 GlobalValue::LinkageTypes NewLinkage) {
746 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
747 };
748
749 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
750 recordNewLinkage);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000751
752 std::unique_ptr<ThinBackendProc> BackendProc = ThinLTO.Backend(
Mehdi Amini970800e2016-08-17 06:23:09 +0000753 Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries, AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000754
755 // Partition numbers for ThinLTO jobs start at 1 (see comments for
756 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000757 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
758 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
759 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000760 unsigned Task =
761 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000762 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000763
764 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000765 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000766 ExportLists[Mod.first],
767 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000768 return E;
769
770 ++Task;
771 ++Partition;
772 }
773
774 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000775}