blob: 8d4f1a48d939ac8886781538e3a26db95d5f7c4f [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
Mehdi Amini9989f802016-08-19 15:35:44 +0000233 // FIXME: move to backend
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000234 Module &M = Input->Obj->getModule();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000235 if (!Conf.OverrideTriple.empty())
236 M.setTargetTriple(Conf.OverrideTriple);
237 else if (M.getTargetTriple().empty())
238 M.setTargetTriple(Conf.DefaultTriple);
239
240 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
241 bool HasThinLTOSummary = hasGlobalValueSummary(MBRef, Conf.DiagHandler);
242
243 if (HasThinLTOSummary)
244 return addThinLTO(std::move(Input), Res);
245 else
246 return addRegularLTO(std::move(Input), Res);
247}
248
249// Add a regular LTO object to the link.
250Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
251 ArrayRef<SymbolResolution> Res) {
252 RegularLTO.HasModule = true;
253
254 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
255 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
256 if (!ObjOrErr)
257 return errorCodeToError(ObjOrErr.getError());
258 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
259
260 Module &M = Obj->getModule();
261 M.materializeMetadata();
262 UpgradeDebugInfo(M);
263
264 SmallPtrSet<GlobalValue *, 8> Used;
265 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
266
267 std::vector<GlobalValue *> Keep;
268
269 for (GlobalVariable &GV : M.globals())
270 if (GV.hasAppendingLinkage())
271 Keep.push_back(&GV);
272
273 auto ResI = Res.begin();
274 for (const InputFile::Symbol &Sym :
275 make_range(InputFile::symbol_iterator(Obj->symbol_begin()),
276 InputFile::symbol_iterator(Obj->symbol_end()))) {
277 assert(ResI != Res.end());
278 SymbolResolution Res = *ResI++;
279 addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
280
281 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
282 if (Res.Prevailing && GV) {
283 Keep.push_back(GV);
284 switch (GV->getLinkage()) {
285 default:
286 break;
287 case GlobalValue::LinkOnceAnyLinkage:
288 GV->setLinkage(GlobalValue::WeakAnyLinkage);
289 break;
290 case GlobalValue::LinkOnceODRLinkage:
291 GV->setLinkage(GlobalValue::WeakODRLinkage);
292 break;
293 }
294 }
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000295 // Common resolution: collect the maximum size/alignment.
296 // FIXME: right now we ignore the prevailing information, it is not clear
297 // what is the "right" behavior here.
298 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
299 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
300 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
301 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
302 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000303
304 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
305 }
306 assert(ResI == Res.end());
307
308 return RegularLTO.Mover.move(Obj->takeModule(), Keep,
309 [](GlobalValue &, IRMover::ValueAdder) {});
310}
311
312// Add a ThinLTO object to the link.
313Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
314 ArrayRef<SymbolResolution> Res) {
315 Module &M = Input->Obj->getModule();
316 SmallPtrSet<GlobalValue *, 8> Used;
317 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
318
319 // We need to initialize the target info for the combined regular LTO module
320 // in case we have no regular LTO objects. In that case we still need to build
321 // it as usual because the client may want to add symbol definitions to it.
322 if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
323 RegularLTO.CombinedModule->setTargetTriple(M.getTargetTriple());
324 RegularLTO.CombinedModule->setDataLayout(M.getDataLayout());
325 }
326
327 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
328 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
329 SummaryObjOrErr =
330 object::ModuleSummaryIndexObjectFile::create(MBRef, Conf.DiagHandler);
331 if (!SummaryObjOrErr)
332 return errorCodeToError(SummaryObjOrErr.getError());
333 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
334 ThinLTO.ModuleMap.size());
335
336 auto ResI = Res.begin();
337 for (const InputFile::Symbol &Sym : Input->symbols()) {
338 assert(ResI != Res.end());
339 SymbolResolution Res = *ResI++;
340 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
341 ThinLTO.ModuleMap.size() + 1);
342
343 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
344 if (Res.Prevailing && GV)
345 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
346 MBRef.getBufferIdentifier();
347 }
348 assert(ResI == Res.end());
349
350 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
351 return Error();
352}
353
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000354unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000355 CalledGetMaxTasks = true;
356 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
357}
358
Mehdi Amini970800e2016-08-17 06:23:09 +0000359Error LTO::run(AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000360 // Invoke regular LTO if there was a regular LTO module to start with,
361 // or if there are any hooks that the linker may have used to add
362 // its own resolved symbols to the combined module.
363 if (RegularLTO.HasModule || Conf.PreOptModuleHook ||
364 Conf.PostInternalizeModuleHook || Conf.PostOptModuleHook ||
365 Conf.PreCodeGenModuleHook)
Mehdi Amini970800e2016-08-17 06:23:09 +0000366 if (auto E = runRegularLTO(AddOutput))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000367 return E;
Mehdi Amini970800e2016-08-17 06:23:09 +0000368 return runThinLTO(AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000369}
370
Mehdi Amini970800e2016-08-17 06:23:09 +0000371Error LTO::runRegularLTO(AddOutputFn AddOutput) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000372 // Make sure commons have the right size/alignment: we kept the largest from
373 // all the prevailing when adding the inputs, and we apply it here.
374 for (auto &I : RegularLTO.Commons) {
375 ArrayType *Ty =
376 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
377 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
378 if (OldGV && OldGV->getType()->getElementType() == Ty) {
379 // Don't create a new global if the type is already correct, just make
380 // sure the alignment is correct.
381 OldGV->setAlignment(I.second.Align);
382 continue;
383 }
384 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
385 GlobalValue::CommonLinkage,
386 ConstantAggregateZero::get(Ty), "");
387 GV->setAlignment(I.second.Align);
388 if (OldGV) {
389 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
390 GV->takeName(OldGV);
391 OldGV->eraseFromParent();
392 } else {
393 GV->setName(I.first);
394 }
395 }
396
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000397 if (Conf.PreOptModuleHook &&
398 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
399 return Error();
400
Mehdi Aminid310b472016-08-22 06:25:41 +0000401 if (!Conf.CodeGenOnly) {
402 for (const auto &R : GlobalResolutions) {
403 if (R.second.IRName.empty())
404 continue;
405 if (R.second.Partition != 0 &&
406 R.second.Partition != GlobalResolution::External)
407 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000408
Mehdi Aminid310b472016-08-22 06:25:41 +0000409 GlobalValue *GV =
410 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
411 // Ignore symbols defined in other partitions.
412 if (!GV || GV->hasLocalLinkage())
413 continue;
414 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
415 : GlobalValue::UnnamedAddr::None);
416 if (R.second.Partition == 0)
417 GV->setLinkage(GlobalValue::InternalLinkage);
418 }
419
420 if (Conf.PostInternalizeModuleHook &&
421 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
422 return Error();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000423 }
Mehdi Amini970800e2016-08-17 06:23:09 +0000424 return backend(Conf, AddOutput, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000425 std::move(RegularLTO.CombinedModule));
426}
427
428/// This class defines the interface to the ThinLTO backend.
429class lto::ThinBackendProc {
430protected:
431 Config &Conf;
432 ModuleSummaryIndex &CombinedIndex;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000433 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
434
435public:
436 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000437 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000438 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000439 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
440
441 virtual ~ThinBackendProc() {}
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000442 virtual Error start(unsigned Task, MemoryBufferRef MBRef,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000443 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000444 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
445 virtual Error wait() = 0;
446};
447
448class InProcessThinBackend : public ThinBackendProc {
449 ThreadPool BackendThreadPool;
Mehdi Amini18b91112016-08-19 06:10:03 +0000450 AddOutputFn AddOutput;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000451
452 Optional<Error> Err;
453 std::mutex ErrMu;
454
455public:
456 InProcessThinBackend(Config &Conf, ModuleSummaryIndex &CombinedIndex,
457 unsigned ThinLTOParallelismLevel,
458 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000459 AddOutputFn AddOutput)
Mehdi Amini18b91112016-08-19 06:10:03 +0000460 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
461 BackendThreadPool(ThinLTOParallelismLevel),
462 AddOutput(std::move(AddOutput)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000463
464 Error
Mehdi Amini970800e2016-08-17 06:23:09 +0000465 runThinLTOBackendThread(AddOutputFn AddOutput, unsigned Task,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000466 MemoryBufferRef MBRef,
467 ModuleSummaryIndex &CombinedIndex,
468 const FunctionImporter::ImportMapTy &ImportList,
469 const GVSummaryMapTy &DefinedGlobals,
470 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000471 LTOLLVMContext BackendContext(Conf);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000472
473 ErrorOr<std::unique_ptr<Module>> MOrErr =
474 parseBitcodeFile(MBRef, BackendContext);
475 assert(MOrErr && "Unable to load module in thread?");
476
Mehdi Amini970800e2016-08-17 06:23:09 +0000477 return thinBackend(Conf, Task, AddOutput, **MOrErr, CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000478 ImportList, DefinedGlobals, ModuleMap);
479 }
480
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000481 Error start(unsigned Task, MemoryBufferRef MBRef,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000482 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000483 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
484 StringRef ModulePath = MBRef.getBufferIdentifier();
485 BackendThreadPool.async(
486 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
487 const FunctionImporter::ImportMapTy &ImportList,
488 GVSummaryMapTy &DefinedGlobals,
489 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
490 Error E =
Mehdi Amini970800e2016-08-17 06:23:09 +0000491 runThinLTOBackendThread(AddOutput, Task, MBRef, CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000492 ImportList, DefinedGlobals, ModuleMap);
493 if (E) {
494 std::unique_lock<std::mutex> L(ErrMu);
495 if (Err)
496 Err = joinErrors(std::move(*Err), std::move(E));
497 else
498 Err = std::move(E);
499 }
500 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000501 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000502 std::ref(ModuleToDefinedGVSummaries[ModulePath]), std::ref(ModuleMap));
503 return Error();
504 }
505
506 Error wait() override {
507 BackendThreadPool.wait();
508 if (Err)
509 return std::move(*Err);
510 else
511 return Error();
512 }
513};
514
515ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
516 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
517 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000518 AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000519 return llvm::make_unique<InProcessThinBackend>(
520 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000521 AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000522 };
523}
524
525class WriteIndexesThinBackend : public ThinBackendProc {
526 std::string OldPrefix, NewPrefix;
527 bool ShouldEmitImportsFiles;
528
529 std::string LinkedObjectsFileName;
530 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
531
532public:
533 WriteIndexesThinBackend(Config &Conf, ModuleSummaryIndex &CombinedIndex,
534 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini18b91112016-08-19 06:10:03 +0000535 std::string OldPrefix, std::string NewPrefix,
536 bool ShouldEmitImportsFiles,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000537 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000538 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000539 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
540 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
541 LinkedObjectsFileName(LinkedObjectsFileName) {}
542
543 /// Given the original \p Path to an output file, replace any path
544 /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
545 /// resulting directory if it does not yet exist.
546 std::string getThinLTOOutputFile(const std::string &Path,
547 const std::string &OldPrefix,
548 const std::string &NewPrefix) {
549 if (OldPrefix.empty() && NewPrefix.empty())
550 return Path;
551 SmallString<128> NewPath(Path);
552 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
553 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
554 if (!ParentPath.empty()) {
555 // Make sure the new directory exists, creating it if necessary.
556 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
557 llvm::errs() << "warning: could not create directory '" << ParentPath
558 << "': " << EC.message() << '\n';
559 }
560 return NewPath.str();
561 }
562
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000563 Error start(unsigned Task, MemoryBufferRef MBRef,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000564 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000565 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
566 StringRef ModulePath = MBRef.getBufferIdentifier();
567 std::string NewModulePath =
568 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
569
570 std::error_code EC;
571 if (!LinkedObjectsFileName.empty()) {
572 if (!LinkedObjectsFile) {
573 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
574 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
575 if (EC)
576 return errorCodeToError(EC);
577 }
578 *LinkedObjectsFile << NewModulePath << '\n';
579 }
580
581 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
582 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000583 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000584
585 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
586 sys::fs::OpenFlags::F_None);
587 if (EC)
588 return errorCodeToError(EC);
589 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
590
591 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000592 return errorCodeToError(
593 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000594 return Error();
595 }
596
597 Error wait() override { return Error(); }
598};
599
600ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
601 std::string NewPrefix,
602 bool ShouldEmitImportsFiles,
603 std::string LinkedObjectsFile) {
604 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
605 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000606 AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000607 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000608 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
609 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000610 };
611}
612
Mehdi Amini970800e2016-08-17 06:23:09 +0000613Error LTO::runThinLTO(AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000614 if (ThinLTO.ModuleMap.empty())
615 return Error();
616
617 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
618 return Error();
619
620 // Collect for each module the list of function it defines (GUID ->
621 // Summary).
622 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
623 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
624 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
625 ModuleToDefinedGVSummaries);
626
627 StringMap<FunctionImporter::ImportMapTy> ImportLists(
628 ThinLTO.ModuleMap.size());
629 StringMap<FunctionImporter::ExportSetTy> ExportLists(
630 ThinLTO.ModuleMap.size());
631 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
632 ImportLists, ExportLists);
633
634 std::set<GlobalValue::GUID> ExportedGUIDs;
635 for (auto &Res : GlobalResolutions) {
636 if (!Res.second.IRName.empty() &&
637 Res.second.Partition == GlobalResolution::External)
638 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
639 }
640
641 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
642 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
643 };
644 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
645 const auto &ExportList = ExportLists.find(ModuleIdentifier);
646 return (ExportList != ExportLists.end() &&
647 ExportList->second.count(GUID)) ||
648 ExportedGUIDs.count(GUID);
649 };
650 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
651 thinLTOResolveWeakForLinkerInIndex(
652 ThinLTO.CombinedIndex, isPrevailing,
653 [](StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes) {});
654
655 std::unique_ptr<ThinBackendProc> BackendProc = ThinLTO.Backend(
Mehdi Amini970800e2016-08-17 06:23:09 +0000656 Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries, AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000657
658 // Partition numbers for ThinLTO jobs start at 1 (see comments for
659 // GlobalResolution in LTO.h). Task numbers, however, start at
660 // ParallelCodeGenParallelismLevel, as tasks 0 through
661 // ParallelCodeGenParallelismLevel-1 are reserved for parallel code generation
662 // partitions.
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000663 unsigned Task = RegularLTO.ParallelCodeGenParallelismLevel;
664 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000665
666 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000667 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000668 ThinLTO.ModuleMap))
669 return E;
670
671 ++Task;
672 ++Partition;
673 }
674
675 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000676}