blob: a4ef9b696905a0b20e96337cab9e94f9ada7c0ac [file] [log] [blame]
Rui Ueyama25992482016-03-22 20:52:10 +00001//===- LTO.cpp ------------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "LTO.h"
11#include "Config.h"
12#include "Error.h"
13#include "InputFiles.h"
14#include "Symbols.h"
15#include "llvm/Analysis/TargetLibraryInfo.h"
16#include "llvm/Analysis/TargetTransformInfo.h"
17#include "llvm/Bitcode/ReaderWriter.h"
Davide Italiano8eca2822016-04-01 00:35:29 +000018#include "llvm/CodeGen/CommandFlags.h"
Davide Italianobc176632016-04-15 22:38:10 +000019#include "llvm/CodeGen/ParallelCG.h"
Rui Ueyama25992482016-03-22 20:52:10 +000020#include "llvm/IR/LegacyPassManager.h"
21#include "llvm/Linker/IRMover.h"
22#include "llvm/Support/StringSaver.h"
23#include "llvm/Support/TargetRegistry.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Transforms/IPO.h"
Davide Italiano86f2bd52016-03-29 21:46:35 +000026#include "llvm/Transforms/Utils/ModuleUtils.h"
Rui Ueyama25992482016-03-22 20:52:10 +000027#include "llvm/Transforms/IPO/PassManagerBuilder.h"
28
29using namespace llvm;
30using namespace llvm::object;
31using namespace llvm::ELF;
32
33using namespace lld;
34using namespace lld::elf;
35
36// This is for use when debugging LTO.
Davide Italianobc176632016-04-15 22:38:10 +000037static void saveLtoObjectFile(StringRef Buffer, unsigned I, bool Many) {
38 SmallString<128> Filename = Config->OutputFile;
39 if (Many)
40 Filename += utostr(I);
41 Filename += ".lto.o";
Rui Ueyama25992482016-03-22 20:52:10 +000042 std::error_code EC;
Davide Italianobc176632016-04-15 22:38:10 +000043 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
Rui Ueyama25992482016-03-22 20:52:10 +000044 check(EC);
45 OS << Buffer;
46}
47
48// This is for use when debugging LTO.
49static void saveBCFile(Module &M, StringRef Suffix) {
50 std::error_code EC;
51 raw_fd_ostream OS(Config->OutputFile.str() + Suffix.str(), EC,
52 sys::fs::OpenFlags::F_None);
53 check(EC);
54 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
55}
56
57// Run LTO passes.
Rui Ueyama4e62db42016-03-29 19:19:03 +000058// Note that the gold plugin has a similar piece of code, so
59// it is probably better to move this code to a common place.
Rui Ueyama25992482016-03-22 20:52:10 +000060static void runLTOPasses(Module &M, TargetMachine &TM) {
61 legacy::PassManager LtoPasses;
62 LtoPasses.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
63 PassManagerBuilder PMB;
64 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
65 PMB.Inliner = createFunctionInliningPass();
Davide Italiano842fa532016-04-03 03:39:09 +000066 PMB.VerifyInput = PMB.VerifyOutput = !Config->DisableVerify;
Rui Ueyama25992482016-03-22 20:52:10 +000067 PMB.LoopVectorize = true;
68 PMB.SLPVectorize = true;
Peter Collingbourneed22f9b2016-03-31 21:00:27 +000069 PMB.OptLevel = Config->LtoO;
Rui Ueyama25992482016-03-22 20:52:10 +000070 PMB.populateLTOPassManager(LtoPasses);
71 LtoPasses.run(M);
72
73 if (Config->SaveTemps)
74 saveBCFile(M, ".lto.opt.bc");
75}
76
77void BitcodeCompiler::add(BitcodeFile &F) {
78 std::unique_ptr<IRObjectFile> Obj =
79 check(IRObjectFile::create(F.MB, Context));
80 std::vector<GlobalValue *> Keep;
81 unsigned BodyIndex = 0;
82 ArrayRef<SymbolBody *> Bodies = F.getSymbols();
83
Davide Italiano86f2bd52016-03-29 21:46:35 +000084 Module &M = Obj->getModule();
Davide Italiano49fe4ed2016-03-29 23:57:22 +000085
86 // If a symbol appears in @llvm.used, the linker is required
87 // to treat the symbol as there is a reference to the symbol
88 // that it cannot see. Therefore, we can't internalize.
Davide Italiano86f2bd52016-03-29 21:46:35 +000089 SmallPtrSet<GlobalValue *, 8> Used;
90 collectUsedGlobalVariables(M, Used, /* CompilerUsed */ false);
91
Rui Ueyama25992482016-03-22 20:52:10 +000092 for (const BasicSymbolRef &Sym : Obj->symbols()) {
93 GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
Peter Collingbourne7cf73ec2016-04-11 16:39:43 +000094 // Ignore module asm symbols.
95 if (!GV)
96 continue;
Rui Ueyama25992482016-03-22 20:52:10 +000097 if (GV->hasAppendingLinkage()) {
98 Keep.push_back(GV);
99 continue;
100 }
Davide Italiano1460e9f2016-03-26 18:33:09 +0000101 if (BitcodeFile::shouldSkip(Sym))
102 continue;
103 SymbolBody *B = Bodies[BodyIndex++];
104 if (!B || &B->repl() != B || !isa<DefinedBitcode>(B))
105 continue;
106 switch (GV->getLinkage()) {
107 default:
108 break;
109 case llvm::GlobalValue::LinkOnceAnyLinkage:
110 GV->setLinkage(GlobalValue::WeakAnyLinkage);
111 break;
112 case llvm::GlobalValue::LinkOnceODRLinkage:
113 GV->setLinkage(GlobalValue::WeakODRLinkage);
114 break;
Davide Italianod4c2a032016-03-22 22:31:34 +0000115 }
Davide Italiano828ac5412016-03-28 15:44:21 +0000116
117 // We collect the set of symbols we want to internalize here
118 // and change the linkage after the IRMover executed, i.e. after
119 // we imported the symbols and satisfied undefined references
120 // to it. We can't just change linkage here because otherwise
121 // the IRMover will just rename the symbol.
122 // Shared libraries need to be handled slightly differently.
123 // For now, let's be conservative and just never internalize
124 // symbols when creating a shared library.
Rafael Espindola8caf33c2016-04-08 18:39:03 +0000125 if (!Config->Shared && !Config->ExportDynamic && !B->isUsedInRegularObj() &&
126 !B->MustBeInDynSym)
Davide Italiano86f2bd52016-03-29 21:46:35 +0000127 if (!Used.count(GV))
128 InternalizedSyms.insert(GV->getName());
Davide Italiano828ac5412016-03-28 15:44:21 +0000129
Davide Italiano1460e9f2016-03-26 18:33:09 +0000130 Keep.push_back(GV);
Rui Ueyama25992482016-03-22 20:52:10 +0000131 }
132
133 Mover.move(Obj->takeModule(), Keep,
134 [](GlobalValue &, IRMover::ValueAdder) {});
135}
136
Davide Italiano828ac5412016-03-28 15:44:21 +0000137static void internalize(GlobalValue &GV) {
138 assert(!GV.hasLocalLinkage() &&
Davide Italiano47c33f02016-03-29 21:48:25 +0000139 "Trying to internalize a symbol with local linkage!");
Davide Italiano828ac5412016-03-28 15:44:21 +0000140 GV.setLinkage(GlobalValue::InternalLinkage);
141}
142
Davide Italianobc176632016-04-15 22:38:10 +0000143std::vector<std::unique_ptr<InputFile>> BitcodeCompiler::runSplitCodegen() {
144 unsigned NumThreads = Config->LtoJobs;
145 OwningData.resize(NumThreads);
146
147 std::list<raw_svector_ostream> OSs;
148 std::vector<raw_pwrite_stream *> OSPtrs;
149 for (SmallString<0> &Obj : OwningData) {
150 OSs.emplace_back(Obj);
151 OSPtrs.push_back(&OSs.back());
152 }
153
154 splitCodeGen(std::move(Combined), OSPtrs, {},
155 [this]() { return getTargetMachine(); });
156
157 std::vector<std::unique_ptr<InputFile>> ObjFiles;
158 for (SmallString<0> &Obj : OwningData)
159 ObjFiles.push_back(createObjectFile(
160 MemoryBufferRef(Obj, "LLD-INTERNAL-combined-lto-object")));
161
162 if (Config->SaveTemps)
163 for (unsigned I = 0; I < NumThreads; ++I)
164 saveLtoObjectFile(OwningData[I], I, NumThreads > 1);
165
166 return ObjFiles;
167}
168
Rui Ueyama25992482016-03-22 20:52:10 +0000169// Merge all the bitcode files we have seen, codegen the result
170// and return the resulting ObjectFile.
Davide Italianobc176632016-04-15 22:38:10 +0000171std::vector<std::unique_ptr<InputFile>> BitcodeCompiler::compile() {
172 TheTriple = Combined->getTargetTriple();
Davide Italiano828ac5412016-03-28 15:44:21 +0000173 for (const auto &Name : InternalizedSyms) {
Davide Italiano15c41b22016-04-11 22:39:51 +0000174 GlobalValue *GV = Combined->getNamedValue(Name.first());
Davide Italiano828ac5412016-03-28 15:44:21 +0000175 assert(GV);
176 internalize(*GV);
177 }
178
Rui Ueyama25992482016-03-22 20:52:10 +0000179 if (Config->SaveTemps)
Davide Italiano15c41b22016-04-11 22:39:51 +0000180 saveBCFile(*Combined, ".lto.bc");
Rui Ueyama25992482016-03-22 20:52:10 +0000181
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000182 std::unique_ptr<TargetMachine> TM(getTargetMachine());
Davide Italiano15c41b22016-04-11 22:39:51 +0000183 runLTOPasses(*Combined, *TM);
Rui Ueyama25992482016-03-22 20:52:10 +0000184
Davide Italianobc176632016-04-15 22:38:10 +0000185 return runSplitCodegen();
Rui Ueyama25992482016-03-22 20:52:10 +0000186}
187
Davide Italianobc176632016-04-15 22:38:10 +0000188std::unique_ptr<TargetMachine> BitcodeCompiler::getTargetMachine() {
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000189 std::string Msg;
Davide Italianobc176632016-04-15 22:38:10 +0000190 const Target *T = TargetRegistry::lookupTarget(TheTriple, Msg);
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000191 if (!T)
192 fatal("target not found: " + Msg);
Davide Italiano8eca2822016-04-01 00:35:29 +0000193 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000194 Reloc::Model R = Config->Pic ? Reloc::PIC_ : Reloc::Static;
Davide Italianobc176632016-04-15 22:38:10 +0000195 return std::unique_ptr<TargetMachine>(
196 T->createTargetMachine(TheTriple, "", "", Options, R));
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000197}