blob: 5a1b8872bee9964f111c9c4c7508f883f3dc0d60 [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"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000028#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000029#include "llvm/Support/TargetRegistry.h"
30#include "llvm/Support/ThreadPool.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000031#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000032#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetOptions.h"
34#include "llvm/Transforms/IPO.h"
35#include "llvm/Transforms/IPO/PassManagerBuilder.h"
36#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000037
Teresa Johnson9ba95f92016-08-11 14:58:12 +000038#include <set>
39
40using namespace llvm;
41using namespace lto;
42using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000043
44// Simple helper to load a module from bitcode
Teresa Johnson9ba95f92016-08-11 14:58:12 +000045std::unique_ptr<Module>
46llvm::loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
47 bool Lazy) {
Teresa Johnsondf6edc52016-05-23 22:54:06 +000048 SMDiagnostic Err;
49 ErrorOr<std::unique_ptr<Module>> ModuleOrErr(nullptr);
50 if (Lazy) {
51 ModuleOrErr =
52 getLazyBitcodeModule(MemoryBuffer::getMemBuffer(Buffer, false), Context,
53 /* ShouldLazyLoadMetadata */ Lazy);
54 } else {
55 ModuleOrErr = parseBitcodeFile(Buffer, Context);
56 }
57 if (std::error_code EC = ModuleOrErr.getError()) {
58 Err = SMDiagnostic(Buffer.getBufferIdentifier(), SourceMgr::DK_Error,
59 EC.message());
60 Err.print("ThinLTO", errs());
61 report_fatal_error("Can't load module, abort.");
62 }
63 return std::move(ModuleOrErr.get());
64}
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000065
66static void thinLTOResolveWeakForLinkerGUID(
67 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
68 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +000069 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000070 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +000071 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000072 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000073 for (auto &S : GVSummaryList) {
74 if (GlobalInvolvedWithAlias.count(S.get()))
75 continue;
76 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
77 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
78 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +000079 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000080 // but turned into a weak, while the others will drop it when possible.
Peter Collingbourne73589f32016-07-07 18:31:51 +000081 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +000082 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
83 S->setLinkage(GlobalValue::getWeakLinkage(
84 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000085 }
86 // Alias can't be turned into available_externally.
87 else if (!isa<AliasSummary>(S.get()) &&
88 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
89 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
90 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
91 if (S->linkage() != OriginalLinkage)
92 recordNewLinkage(S->modulePath(), GUID, S->linkage());
93 }
94}
95
96// Resolve Weak and LinkOnce values in the \p Index.
97//
98// We'd like to drop these functions if they are no longer referenced in the
99// current module. However there is a chance that another module is still
100// referencing them because of the import. We make sure we always emit at least
101// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000102void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000103 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000104 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000105 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000106 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000107 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000108 // We won't optimize the globals that are referenced by an alias for now
109 // Ideally we should turn the alias into a global and duplicate the definition
110 // when needed.
111 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
112 for (auto &I : Index)
113 for (auto &S : I.second)
114 if (auto AS = dyn_cast<AliasSummary>(S.get()))
115 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
116
117 for (auto &I : Index)
118 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000119 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000120}
121
122static void thinLTOInternalizeAndPromoteGUID(
123 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000124 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000125 for (auto &S : GVSummaryList) {
126 if (isExported(S->modulePath(), GUID)) {
127 if (GlobalValue::isLocalLinkage(S->linkage()))
128 S->setLinkage(GlobalValue::ExternalLinkage);
129 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
130 S->setLinkage(GlobalValue::InternalLinkage);
131 }
132}
133
134// Update the linkages in the given \p Index to mark exported values
135// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000136void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000137 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000138 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000139 for (auto &I : Index)
140 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
141}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000142
143Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
144 std::unique_ptr<InputFile> File(new InputFile);
145 std::string Msg;
146 auto DiagHandler = [](const DiagnosticInfo &DI, void *MsgP) {
147 auto *Msg = reinterpret_cast<std::string *>(MsgP);
148 raw_string_ostream OS(*Msg);
149 DiagnosticPrinterRawOStream DP(OS);
150 DI.print(DP);
151 };
152 File->Ctx.setDiagnosticHandler(DiagHandler, static_cast<void *>(&Msg));
153
154 ErrorOr<std::unique_ptr<object::IRObjectFile>> IRObj =
155 IRObjectFile::create(Object, File->Ctx);
156 if (!Msg.empty())
157 return make_error<StringError>(Msg, inconvertibleErrorCode());
158 if (!IRObj)
159 return errorCodeToError(IRObj.getError());
160 File->Obj = std::move(*IRObj);
161
162 File->Ctx.setDiagnosticHandler(nullptr, nullptr);
163
164 return std::move(File);
165}
166
167LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
168 Config &Conf)
169 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
170 Ctx(Conf), CombinedModule(llvm::make_unique<Module>("ld-temp.o", Ctx)),
171 Mover(*CombinedModule) {}
172
173LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
174 if (!Backend)
175 this->Backend = createInProcessThinBackend(thread::hardware_concurrency());
176}
177
178LTO::LTO(Config Conf, ThinBackend Backend,
179 unsigned ParallelCodeGenParallelismLevel)
180 : Conf(std::move(Conf)),
181 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000182 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000183
184// Add the given symbol to the GlobalResolutions map, and resolve its partition.
185void LTO::addSymbolToGlobalRes(IRObjectFile *Obj,
186 SmallPtrSet<GlobalValue *, 8> &Used,
187 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000188 SymbolResolution Res, unsigned Partition) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000189 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
190
191 auto &GlobalRes = GlobalResolutions[Sym.getName()];
192 if (GV) {
193 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
194 if (Res.Prevailing)
195 GlobalRes.IRName = GV->getName();
196 }
197 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
198 (GlobalRes.Partition != GlobalResolution::Unknown &&
199 GlobalRes.Partition != Partition))
200 GlobalRes.Partition = GlobalResolution::External;
201 else
202 GlobalRes.Partition = Partition;
203}
204
205void LTO::writeToResolutionFile(InputFile *Input,
206 ArrayRef<SymbolResolution> Res) {
207 StringRef Path = Input->Obj->getMemoryBufferRef().getBufferIdentifier();
208 *Conf.ResolutionFile << Path << '\n';
209 auto ResI = Res.begin();
210 for (const InputFile::Symbol &Sym : Input->symbols()) {
211 assert(ResI != Res.end());
212 SymbolResolution Res = *ResI++;
213
214 *Conf.ResolutionFile << "-r=" << Path << ',' << Sym.getName() << ',';
215 if (Res.Prevailing)
216 *Conf.ResolutionFile << 'p';
217 if (Res.FinalDefinitionInLinkageUnit)
218 *Conf.ResolutionFile << 'l';
219 if (Res.VisibleToRegularObj)
220 *Conf.ResolutionFile << 'x';
221 *Conf.ResolutionFile << '\n';
222 }
223 assert(ResI == Res.end());
224}
225
226Error LTO::add(std::unique_ptr<InputFile> Input,
227 ArrayRef<SymbolResolution> Res) {
228 assert(!CalledGetMaxTasks);
229
230 if (Conf.ResolutionFile)
231 writeToResolutionFile(Input.get(), Res);
232
233 Module &M = Input->Obj->getModule();
234 SmallPtrSet<GlobalValue *, 8> Used;
235 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
236
237 if (!Conf.OverrideTriple.empty())
238 M.setTargetTriple(Conf.OverrideTriple);
239 else if (M.getTargetTriple().empty())
240 M.setTargetTriple(Conf.DefaultTriple);
241
242 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
243 bool HasThinLTOSummary = hasGlobalValueSummary(MBRef, Conf.DiagHandler);
244
245 if (HasThinLTOSummary)
246 return addThinLTO(std::move(Input), Res);
247 else
248 return addRegularLTO(std::move(Input), Res);
249}
250
251// Add a regular LTO object to the link.
252Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
253 ArrayRef<SymbolResolution> Res) {
254 RegularLTO.HasModule = true;
255
256 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
257 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
258 if (!ObjOrErr)
259 return errorCodeToError(ObjOrErr.getError());
260 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
261
262 Module &M = Obj->getModule();
263 M.materializeMetadata();
264 UpgradeDebugInfo(M);
265
266 SmallPtrSet<GlobalValue *, 8> Used;
267 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
268
269 std::vector<GlobalValue *> Keep;
270
271 for (GlobalVariable &GV : M.globals())
272 if (GV.hasAppendingLinkage())
273 Keep.push_back(&GV);
274
275 auto ResI = Res.begin();
276 for (const InputFile::Symbol &Sym :
277 make_range(InputFile::symbol_iterator(Obj->symbol_begin()),
278 InputFile::symbol_iterator(Obj->symbol_end()))) {
279 assert(ResI != Res.end());
280 SymbolResolution Res = *ResI++;
281 addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
282
283 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
284 if (Res.Prevailing && GV) {
285 Keep.push_back(GV);
286 switch (GV->getLinkage()) {
287 default:
288 break;
289 case GlobalValue::LinkOnceAnyLinkage:
290 GV->setLinkage(GlobalValue::WeakAnyLinkage);
291 break;
292 case GlobalValue::LinkOnceODRLinkage:
293 GV->setLinkage(GlobalValue::WeakODRLinkage);
294 break;
295 }
296 }
297
298 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
299 }
300 assert(ResI == Res.end());
301
302 return RegularLTO.Mover.move(Obj->takeModule(), Keep,
303 [](GlobalValue &, IRMover::ValueAdder) {});
304}
305
306// Add a ThinLTO object to the link.
307Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
308 ArrayRef<SymbolResolution> Res) {
309 Module &M = Input->Obj->getModule();
310 SmallPtrSet<GlobalValue *, 8> Used;
311 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
312
313 // We need to initialize the target info for the combined regular LTO module
314 // in case we have no regular LTO objects. In that case we still need to build
315 // it as usual because the client may want to add symbol definitions to it.
316 if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
317 RegularLTO.CombinedModule->setTargetTriple(M.getTargetTriple());
318 RegularLTO.CombinedModule->setDataLayout(M.getDataLayout());
319 }
320
321 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
322 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
323 SummaryObjOrErr =
324 object::ModuleSummaryIndexObjectFile::create(MBRef, Conf.DiagHandler);
325 if (!SummaryObjOrErr)
326 return errorCodeToError(SummaryObjOrErr.getError());
327 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
328 ThinLTO.ModuleMap.size());
329
330 auto ResI = Res.begin();
331 for (const InputFile::Symbol &Sym : Input->symbols()) {
332 assert(ResI != Res.end());
333 SymbolResolution Res = *ResI++;
334 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
335 ThinLTO.ModuleMap.size() + 1);
336
337 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
338 if (Res.Prevailing && GV)
339 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
340 MBRef.getBufferIdentifier();
341 }
342 assert(ResI == Res.end());
343
344 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
345 return Error();
346}
347
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000348unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000349 CalledGetMaxTasks = true;
350 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
351}
352
Mehdi Amini970800e2016-08-17 06:23:09 +0000353Error LTO::run(AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000354 // Invoke regular LTO if there was a regular LTO module to start with,
355 // or if there are any hooks that the linker may have used to add
356 // its own resolved symbols to the combined module.
357 if (RegularLTO.HasModule || Conf.PreOptModuleHook ||
358 Conf.PostInternalizeModuleHook || Conf.PostOptModuleHook ||
359 Conf.PreCodeGenModuleHook)
Mehdi Amini970800e2016-08-17 06:23:09 +0000360 if (auto E = runRegularLTO(AddOutput))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000361 return E;
Mehdi Amini970800e2016-08-17 06:23:09 +0000362 return runThinLTO(AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000363}
364
Mehdi Amini970800e2016-08-17 06:23:09 +0000365Error LTO::runRegularLTO(AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000366 if (Conf.PreOptModuleHook &&
367 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
368 return Error();
369
370 for (const auto &R : GlobalResolutions) {
371 if (R.second.IRName.empty())
372 continue;
373 if (R.second.Partition != 0 &&
374 R.second.Partition != GlobalResolution::External)
375 continue;
376
377 GlobalValue *GV = RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
378 // Ignore symbols defined in other partitions.
379 if (!GV || GV->hasLocalLinkage())
380 continue;
381 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
382 : GlobalValue::UnnamedAddr::None);
383 if (R.second.Partition == 0)
384 GV->setLinkage(GlobalValue::InternalLinkage);
385 }
386
387 if (Conf.PostInternalizeModuleHook &&
388 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
389 return Error();
390
Mehdi Amini970800e2016-08-17 06:23:09 +0000391 return backend(Conf, AddOutput, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000392 std::move(RegularLTO.CombinedModule));
393}
394
395/// This class defines the interface to the ThinLTO backend.
396class lto::ThinBackendProc {
397protected:
398 Config &Conf;
399 ModuleSummaryIndex &CombinedIndex;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000400 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
401
402public:
403 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000404 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000405 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000406 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
407
408 virtual ~ThinBackendProc() {}
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000409 virtual Error start(unsigned Task, MemoryBufferRef MBRef,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000410 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000411 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
412 virtual Error wait() = 0;
413};
414
415class InProcessThinBackend : public ThinBackendProc {
416 ThreadPool BackendThreadPool;
Mehdi Amini18b91112016-08-19 06:10:03 +0000417 AddOutputFn AddOutput;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000418
419 Optional<Error> Err;
420 std::mutex ErrMu;
421
422public:
423 InProcessThinBackend(Config &Conf, ModuleSummaryIndex &CombinedIndex,
424 unsigned ThinLTOParallelismLevel,
425 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000426 AddOutputFn AddOutput)
Mehdi Amini18b91112016-08-19 06:10:03 +0000427 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
428 BackendThreadPool(ThinLTOParallelismLevel),
429 AddOutput(std::move(AddOutput)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000430
431 Error
Mehdi Amini970800e2016-08-17 06:23:09 +0000432 runThinLTOBackendThread(AddOutputFn AddOutput, unsigned Task,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000433 MemoryBufferRef MBRef,
434 ModuleSummaryIndex &CombinedIndex,
435 const FunctionImporter::ImportMapTy &ImportList,
436 const GVSummaryMapTy &DefinedGlobals,
437 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
438 LLVMContext BackendContext;
439
440 ErrorOr<std::unique_ptr<Module>> MOrErr =
441 parseBitcodeFile(MBRef, BackendContext);
442 assert(MOrErr && "Unable to load module in thread?");
443
Mehdi Amini970800e2016-08-17 06:23:09 +0000444 return thinBackend(Conf, Task, AddOutput, **MOrErr, CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000445 ImportList, DefinedGlobals, ModuleMap);
446 }
447
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000448 Error start(unsigned Task, MemoryBufferRef MBRef,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000449 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000450 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
451 StringRef ModulePath = MBRef.getBufferIdentifier();
452 BackendThreadPool.async(
453 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
454 const FunctionImporter::ImportMapTy &ImportList,
455 GVSummaryMapTy &DefinedGlobals,
456 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
457 Error E =
Mehdi Amini970800e2016-08-17 06:23:09 +0000458 runThinLTOBackendThread(AddOutput, Task, MBRef, CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000459 ImportList, DefinedGlobals, ModuleMap);
460 if (E) {
461 std::unique_lock<std::mutex> L(ErrMu);
462 if (Err)
463 Err = joinErrors(std::move(*Err), std::move(E));
464 else
465 Err = std::move(E);
466 }
467 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000468 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000469 std::ref(ModuleToDefinedGVSummaries[ModulePath]), std::ref(ModuleMap));
470 return Error();
471 }
472
473 Error wait() override {
474 BackendThreadPool.wait();
475 if (Err)
476 return std::move(*Err);
477 else
478 return Error();
479 }
480};
481
482ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
483 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
484 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000485 AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000486 return llvm::make_unique<InProcessThinBackend>(
487 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000488 AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000489 };
490}
491
492class WriteIndexesThinBackend : public ThinBackendProc {
493 std::string OldPrefix, NewPrefix;
494 bool ShouldEmitImportsFiles;
495
496 std::string LinkedObjectsFileName;
497 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
498
499public:
500 WriteIndexesThinBackend(Config &Conf, ModuleSummaryIndex &CombinedIndex,
501 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini18b91112016-08-19 06:10:03 +0000502 std::string OldPrefix, std::string NewPrefix,
503 bool ShouldEmitImportsFiles,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000504 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000505 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000506 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
507 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
508 LinkedObjectsFileName(LinkedObjectsFileName) {}
509
510 /// Given the original \p Path to an output file, replace any path
511 /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
512 /// resulting directory if it does not yet exist.
513 std::string getThinLTOOutputFile(const std::string &Path,
514 const std::string &OldPrefix,
515 const std::string &NewPrefix) {
516 if (OldPrefix.empty() && NewPrefix.empty())
517 return Path;
518 SmallString<128> NewPath(Path);
519 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
520 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
521 if (!ParentPath.empty()) {
522 // Make sure the new directory exists, creating it if necessary.
523 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
524 llvm::errs() << "warning: could not create directory '" << ParentPath
525 << "': " << EC.message() << '\n';
526 }
527 return NewPath.str();
528 }
529
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000530 Error start(unsigned Task, MemoryBufferRef MBRef,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000531 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000532 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
533 StringRef ModulePath = MBRef.getBufferIdentifier();
534 std::string NewModulePath =
535 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
536
537 std::error_code EC;
538 if (!LinkedObjectsFileName.empty()) {
539 if (!LinkedObjectsFile) {
540 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
541 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
542 if (EC)
543 return errorCodeToError(EC);
544 }
545 *LinkedObjectsFile << NewModulePath << '\n';
546 }
547
548 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
549 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000550 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000551
552 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
553 sys::fs::OpenFlags::F_None);
554 if (EC)
555 return errorCodeToError(EC);
556 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
557
558 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000559 return errorCodeToError(
560 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000561 return Error();
562 }
563
564 Error wait() override { return Error(); }
565};
566
567ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
568 std::string NewPrefix,
569 bool ShouldEmitImportsFiles,
570 std::string LinkedObjectsFile) {
571 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
572 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000573 AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000574 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000575 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
576 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000577 };
578}
579
Mehdi Amini970800e2016-08-17 06:23:09 +0000580Error LTO::runThinLTO(AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000581 if (ThinLTO.ModuleMap.empty())
582 return Error();
583
584 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
585 return Error();
586
587 // Collect for each module the list of function it defines (GUID ->
588 // Summary).
589 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
590 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
591 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
592 ModuleToDefinedGVSummaries);
593
594 StringMap<FunctionImporter::ImportMapTy> ImportLists(
595 ThinLTO.ModuleMap.size());
596 StringMap<FunctionImporter::ExportSetTy> ExportLists(
597 ThinLTO.ModuleMap.size());
598 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
599 ImportLists, ExportLists);
600
601 std::set<GlobalValue::GUID> ExportedGUIDs;
602 for (auto &Res : GlobalResolutions) {
603 if (!Res.second.IRName.empty() &&
604 Res.second.Partition == GlobalResolution::External)
605 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
606 }
607
608 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
609 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
610 };
611 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
612 const auto &ExportList = ExportLists.find(ModuleIdentifier);
613 return (ExportList != ExportLists.end() &&
614 ExportList->second.count(GUID)) ||
615 ExportedGUIDs.count(GUID);
616 };
617 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
618 thinLTOResolveWeakForLinkerInIndex(
619 ThinLTO.CombinedIndex, isPrevailing,
620 [](StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes) {});
621
622 std::unique_ptr<ThinBackendProc> BackendProc = ThinLTO.Backend(
Mehdi Amini970800e2016-08-17 06:23:09 +0000623 Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries, AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000624
625 // Partition numbers for ThinLTO jobs start at 1 (see comments for
626 // GlobalResolution in LTO.h). Task numbers, however, start at
627 // ParallelCodeGenParallelismLevel, as tasks 0 through
628 // ParallelCodeGenParallelismLevel-1 are reserved for parallel code generation
629 // partitions.
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000630 unsigned Task = RegularLTO.ParallelCodeGenParallelismLevel;
631 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000632
633 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000634 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000635 ThinLTO.ModuleMap))
636 return E;
637
638 ++Task;
639 ++Partition;
640 }
641
642 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000643}