blob: 3c2c212b640a9c1a4500d612724ed6bf41a7b72e [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"
Rafael Espindola156f4ee2016-04-28 19:30:41 +000012#include "Driver.h"
Rui Ueyama25992482016-03-22 20:52:10 +000013#include "Error.h"
14#include "InputFiles.h"
15#include "Symbols.h"
Davide Italianod26c4a12016-05-15 19:29:38 +000016#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/Analysis/CGSCCPassManager.h"
18#include "llvm/Analysis/LoopPassManager.h"
Rui Ueyama25992482016-03-22 20:52:10 +000019#include "llvm/Analysis/TargetLibraryInfo.h"
20#include "llvm/Analysis/TargetTransformInfo.h"
21#include "llvm/Bitcode/ReaderWriter.h"
Davide Italiano8eca2822016-04-01 00:35:29 +000022#include "llvm/CodeGen/CommandFlags.h"
Davide Italianobc176632016-04-15 22:38:10 +000023#include "llvm/CodeGen/ParallelCG.h"
Davide Italiano334fce92016-05-11 01:07:22 +000024#include "llvm/IR/AutoUpgrade.h"
Rui Ueyama25992482016-03-22 20:52:10 +000025#include "llvm/IR/LegacyPassManager.h"
Davide Italianod26c4a12016-05-15 19:29:38 +000026#include "llvm/IR/PassManager.h"
Davide Italiano5020d2a2016-05-15 19:43:02 +000027#include "llvm/IR/Verifier.h"
Peter Collingbourne6ccb2572016-07-14 21:21:20 +000028#include "llvm/LTO/legacy/UpdateCompilerUsed.h"
Rui Ueyama25992482016-03-22 20:52:10 +000029#include "llvm/Linker/IRMover.h"
Davide Italianod26c4a12016-05-15 19:29:38 +000030#include "llvm/Passes/PassBuilder.h"
Rui Ueyama25992482016-03-22 20:52:10 +000031#include "llvm/Support/StringSaver.h"
32#include "llvm/Support/TargetRegistry.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Transforms/IPO.h"
35#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Rafael Espindola9fdd0712016-04-27 23:54:04 +000036#include "llvm/Transforms/Utils/ModuleUtils.h"
Rui Ueyama25992482016-03-22 20:52:10 +000037
38using namespace llvm;
39using namespace llvm::object;
40using namespace llvm::ELF;
41
42using namespace lld;
43using namespace lld::elf;
44
45// This is for use when debugging LTO.
Davide Italianobc176632016-04-15 22:38:10 +000046static void saveLtoObjectFile(StringRef Buffer, unsigned I, bool Many) {
Rui Ueyamaf8292e92016-07-15 02:01:03 +000047 SmallString<128> Path = Config->OutputFile;
Davide Italianobc176632016-04-15 22:38:10 +000048 if (Many)
Rui Ueyamaf8292e92016-07-15 02:01:03 +000049 Path += utostr(I);
50 Path += ".lto.o";
Rui Ueyama25992482016-03-22 20:52:10 +000051 std::error_code EC;
Rui Ueyamaf8292e92016-07-15 02:01:03 +000052 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
53 if (EC)
54 error(EC, "cannot create " + Path);
Rui Ueyama25992482016-03-22 20:52:10 +000055 OS << Buffer;
56}
57
58// This is for use when debugging LTO.
59static void saveBCFile(Module &M, StringRef Suffix) {
Rui Ueyamaf8292e92016-07-15 02:01:03 +000060 std::string Path = (Config->OutputFile + Suffix).str();
Rui Ueyama25992482016-03-22 20:52:10 +000061 std::error_code EC;
Rui Ueyamaf8292e92016-07-15 02:01:03 +000062 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
63 if (EC)
64 error(EC, "cannot create " + Path);
Rui Ueyama25992482016-03-22 20:52:10 +000065 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
66}
67
Davide Italianod26c4a12016-05-15 19:29:38 +000068static void runNewCustomLtoPasses(Module &M, TargetMachine &TM) {
69 PassBuilder PB(&TM);
70
71 AAManager AA;
Davide Italianodf24d5b2016-06-02 22:58:11 +000072
73 // Parse a custom AA pipeline if asked to.
74 if (!PB.parseAAPipeline(AA, Config->LtoAAPipeline)) {
75 error("Unable to parse AA pipeline description: " + Config->LtoAAPipeline);
76 return;
77 }
78
Davide Italianod26c4a12016-05-15 19:29:38 +000079 LoopAnalysisManager LAM;
80 FunctionAnalysisManager FAM;
81 CGSCCAnalysisManager CGAM;
82 ModuleAnalysisManager MAM;
83
84 // Register the AA manager first so that our version is the one used.
85 FAM.registerPass([&] { return std::move(AA); });
86
87 // Register all the basic analyses with the managers.
88 PB.registerModuleAnalyses(MAM);
89 PB.registerCGSCCAnalyses(CGAM);
90 PB.registerFunctionAnalyses(FAM);
91 PB.registerLoopAnalyses(LAM);
92 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
93
94 ModulePassManager MPM;
95 if (!Config->DisableVerify)
96 MPM.addPass(VerifierPass());
97
98 // Now, add all the passes we've been requested to.
99 if (!PB.parsePassPipeline(MPM, Config->LtoNewPmPasses)) {
100 error("unable to parse pass pipeline description: " +
101 Config->LtoNewPmPasses);
102 return;
103 }
104
105 if (!Config->DisableVerify)
106 MPM.addPass(VerifierPass());
107 MPM.run(M, MAM);
108}
109
110static void runOldLtoPasses(Module &M, TargetMachine &TM) {
111 // Note that the gold plugin has a similar piece of code, so
112 // it is probably better to move this code to a common place.
Rui Ueyama25992482016-03-22 20:52:10 +0000113 legacy::PassManager LtoPasses;
114 LtoPasses.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
115 PassManagerBuilder PMB;
116 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
117 PMB.Inliner = createFunctionInliningPass();
Davide Italiano842fa532016-04-03 03:39:09 +0000118 PMB.VerifyInput = PMB.VerifyOutput = !Config->DisableVerify;
Rui Ueyama25992482016-03-22 20:52:10 +0000119 PMB.LoopVectorize = true;
120 PMB.SLPVectorize = true;
Peter Collingbourneed22f9b2016-03-31 21:00:27 +0000121 PMB.OptLevel = Config->LtoO;
Rui Ueyama25992482016-03-22 20:52:10 +0000122 PMB.populateLTOPassManager(LtoPasses);
123 LtoPasses.run(M);
Davide Italianod26c4a12016-05-15 19:29:38 +0000124}
125
126static void runLTOPasses(Module &M, TargetMachine &TM) {
127 if (!Config->LtoNewPmPasses.empty()) {
128 // The user explicitly asked for a set of passes to be run.
129 // This needs the new PM to work as there's no clean way to
130 // pass a set of passes to run in the legacy PM.
131 runNewCustomLtoPasses(M, TM);
132 if (HasError)
133 return;
134 } else {
135 // Run the 'default' set of LTO passes. This code still uses
136 // the legacy PM as the new one is not the default.
137 runOldLtoPasses(M, TM);
138 }
Rui Ueyama25992482016-03-22 20:52:10 +0000139
140 if (Config->SaveTemps)
141 saveBCFile(M, ".lto.opt.bc");
142}
143
Rafael Espindolaae605c12016-04-21 20:35:25 +0000144static bool shouldInternalize(const SmallPtrSet<GlobalValue *, 8> &Used,
Peter Collingbourne4f952702016-05-01 04:55:03 +0000145 Symbol *S, GlobalValue *GV) {
Davide Italiano39356902016-06-11 14:21:38 +0000146 if (S->IsUsedInRegularObj || Used.count(GV))
Rafael Espindolaae605c12016-04-21 20:35:25 +0000147 return false;
Peter Collingbourne4f952702016-05-01 04:55:03 +0000148 return !S->includeInDynsym();
Rafael Espindolaae605c12016-04-21 20:35:25 +0000149}
150
Rui Ueyama412c8022016-04-22 21:16:18 +0000151BitcodeCompiler::BitcodeCompiler()
Rafael Espindola156f4ee2016-04-28 19:30:41 +0000152 : Combined(new llvm::Module("ld-temp.o", Driver->Context)),
153 Mover(*Combined) {}
Rui Ueyama412c8022016-04-22 21:16:18 +0000154
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000155static void undefine(Symbol *S) {
Davide Italiano64ebf322016-06-01 16:38:13 +0000156 replaceBody<Undefined>(S, S->body()->getName(), STV_DEFAULT, S->body()->Type);
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000157}
158
Davide Italiano595ee8c2016-06-22 18:09:23 +0000159static void handleUndefinedAsmRefs(const BasicSymbolRef &Sym, GlobalValue *GV,
160 StringSet<> &AsmUndefinedRefs) {
161 // GV associated => not an assembly symbol, bail out.
162 if (GV)
163 return;
164
165 // This is an undefined reference to a symbol in asm. We put that in
166 // compiler.used, so that we can preserve it from being dropped from
167 // the output, without necessarily preventing its internalization.
168 SmallString<64> Name;
169 raw_svector_ostream OS(Name);
170 Sym.printName(OS);
171 AsmUndefinedRefs.insert(Name.str());
172}
173
Rui Ueyama25992482016-03-22 20:52:10 +0000174void BitcodeCompiler::add(BitcodeFile &F) {
Rafael Espindola156f4ee2016-04-28 19:30:41 +0000175 std::unique_ptr<IRObjectFile> Obj = std::move(F.Obj);
Rui Ueyama25992482016-03-22 20:52:10 +0000176 std::vector<GlobalValue *> Keep;
177 unsigned BodyIndex = 0;
Peter Collingbourne4f952702016-05-01 04:55:03 +0000178 ArrayRef<Symbol *> Syms = F.getSymbols();
Rui Ueyama25992482016-03-22 20:52:10 +0000179
Davide Italiano86f2bd52016-03-29 21:46:35 +0000180 Module &M = Obj->getModule();
Davide Italiano493b6832016-04-16 01:33:33 +0000181 if (M.getDataLayoutStr().empty())
182 fatal("invalid bitcode file: " + F.getName() + " has no datalayout");
Davide Italiano49fe4ed2016-03-29 23:57:22 +0000183
Davide Italiano334fce92016-05-11 01:07:22 +0000184 // Discard non-compatible debug infos if necessary.
185 M.materializeMetadata();
186 UpgradeDebugInfo(M);
187
Davide Italiano49fe4ed2016-03-29 23:57:22 +0000188 // If a symbol appears in @llvm.used, the linker is required
189 // to treat the symbol as there is a reference to the symbol
190 // that it cannot see. Therefore, we can't internalize.
Davide Italiano86f2bd52016-03-29 21:46:35 +0000191 SmallPtrSet<GlobalValue *, 8> Used;
192 collectUsedGlobalVariables(M, Used, /* CompilerUsed */ false);
193
Rui Ueyama25992482016-03-22 20:52:10 +0000194 for (const BasicSymbolRef &Sym : Obj->symbols()) {
Peter Collingbourne4f952702016-05-01 04:55:03 +0000195 uint32_t Flags = Sym.getFlags();
Rui Ueyama25992482016-03-22 20:52:10 +0000196 GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
Peter Collingbourne4f952702016-05-01 04:55:03 +0000197 if (GV && GV->hasAppendingLinkage())
Rui Ueyama25992482016-03-22 20:52:10 +0000198 Keep.push_back(GV);
Peter Collingbourne4f952702016-05-01 04:55:03 +0000199 if (BitcodeFile::shouldSkip(Flags))
200 continue;
201 Symbol *S = Syms[BodyIndex++];
Davide Italiano595ee8c2016-06-22 18:09:23 +0000202 if (Flags & BasicSymbolRef::SF_Undefined) {
203 handleUndefinedAsmRefs(Sym, GV, AsmUndefinedRefs);
Peter Collingbourne4f952702016-05-01 04:55:03 +0000204 continue;
Davide Italiano595ee8c2016-06-22 18:09:23 +0000205 }
Peter Collingbourne4f952702016-05-01 04:55:03 +0000206 auto *B = dyn_cast<DefinedBitcode>(S->body());
207 if (!B || B->File != &F)
Davide Italiano1460e9f2016-03-26 18:33:09 +0000208 continue;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000209
210 // We collect the set of symbols we want to internalize here
211 // and change the linkage after the IRMover executed, i.e. after
212 // we imported the symbols and satisfied undefined references
213 // to it. We can't just change linkage here because otherwise
214 // the IRMover will just rename the symbol.
215 if (GV && shouldInternalize(Used, S, GV))
216 InternalizedSyms.insert(GV->getName());
217
218 // At this point we know that either the combined LTO object will provide a
219 // definition of a symbol, or we will internalize it. In either case, we
220 // need to undefine the symbol. In the former case, the real definition
221 // needs to be able to replace the original definition without conflicting.
222 // In the latter case, we need to allow the combined LTO object to provide a
223 // definition with the same name, for example when doing parallel codegen.
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000224 undefine(S);
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000225
226 if (!GV)
227 // Module asm symbol.
228 continue;
229
Davide Italiano1460e9f2016-03-26 18:33:09 +0000230 switch (GV->getLinkage()) {
231 default:
232 break;
233 case llvm::GlobalValue::LinkOnceAnyLinkage:
234 GV->setLinkage(GlobalValue::WeakAnyLinkage);
235 break;
236 case llvm::GlobalValue::LinkOnceODRLinkage:
237 GV->setLinkage(GlobalValue::WeakODRLinkage);
238 break;
Davide Italianod4c2a032016-03-22 22:31:34 +0000239 }
Davide Italiano828ac5412016-03-28 15:44:21 +0000240
Davide Italiano1460e9f2016-03-26 18:33:09 +0000241 Keep.push_back(GV);
Rui Ueyama25992482016-03-22 20:52:10 +0000242 }
243
Peter Collingbourne5079f3b2016-05-27 05:21:45 +0000244 if (Error E = Mover.move(Obj->takeModule(), Keep,
245 [](GlobalValue &, IRMover::ValueAdder) {})) {
246 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
247 fatal("failed to link module " + F.getName() + ": " + EIB.message());
248 });
249 }
Rui Ueyama25992482016-03-22 20:52:10 +0000250}
251
Davide Italiano828ac5412016-03-28 15:44:21 +0000252static void internalize(GlobalValue &GV) {
253 assert(!GV.hasLocalLinkage() &&
Davide Italiano47c33f02016-03-29 21:48:25 +0000254 "Trying to internalize a symbol with local linkage!");
Davide Italiano828ac5412016-03-28 15:44:21 +0000255 GV.setLinkage(GlobalValue::InternalLinkage);
256}
257
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000258std::vector<std::unique_ptr<InputFile>> BitcodeCompiler::runSplitCodegen(
259 const std::function<std::unique_ptr<TargetMachine>()> &TMFactory) {
Davide Italianobc176632016-04-15 22:38:10 +0000260 unsigned NumThreads = Config->LtoJobs;
261 OwningData.resize(NumThreads);
262
263 std::list<raw_svector_ostream> OSs;
264 std::vector<raw_pwrite_stream *> OSPtrs;
265 for (SmallString<0> &Obj : OwningData) {
266 OSs.emplace_back(Obj);
267 OSPtrs.push_back(&OSs.back());
268 }
269
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000270 splitCodeGen(std::move(Combined), OSPtrs, {}, TMFactory);
Davide Italianobc176632016-04-15 22:38:10 +0000271
272 std::vector<std::unique_ptr<InputFile>> ObjFiles;
273 for (SmallString<0> &Obj : OwningData)
274 ObjFiles.push_back(createObjectFile(
275 MemoryBufferRef(Obj, "LLD-INTERNAL-combined-lto-object")));
276
277 if (Config->SaveTemps)
278 for (unsigned I = 0; I < NumThreads; ++I)
279 saveLtoObjectFile(OwningData[I], I, NumThreads > 1);
280
281 return ObjFiles;
282}
283
Rui Ueyama25992482016-03-22 20:52:10 +0000284// Merge all the bitcode files we have seen, codegen the result
285// and return the resulting ObjectFile.
Davide Italianobc176632016-04-15 22:38:10 +0000286std::vector<std::unique_ptr<InputFile>> BitcodeCompiler::compile() {
287 TheTriple = Combined->getTargetTriple();
Davide Italiano828ac5412016-03-28 15:44:21 +0000288 for (const auto &Name : InternalizedSyms) {
Davide Italiano15c41b22016-04-11 22:39:51 +0000289 GlobalValue *GV = Combined->getNamedValue(Name.first());
Davide Italiano828ac5412016-03-28 15:44:21 +0000290 assert(GV);
291 internalize(*GV);
292 }
293
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000294 std::string Msg;
Davide Italianobc176632016-04-15 22:38:10 +0000295 const Target *T = TargetRegistry::lookupTarget(TheTriple, Msg);
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000296 if (!T)
297 fatal("target not found: " + Msg);
Davide Italiano8eca2822016-04-01 00:35:29 +0000298 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola254b58d2016-06-21 14:47:43 +0000299
300 // lld supports the new relocations.
301 Options.RelaxELFRelocations = true;
302
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000303 Reloc::Model R = Config->Pic ? Reloc::PIC_ : Reloc::Static;
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000304
305 auto CreateTargetMachine = [&]() {
306 return std::unique_ptr<TargetMachine>(
307 T->createTargetMachine(TheTriple, "", "", Options, R));
308 };
309
310 std::unique_ptr<TargetMachine> TM = CreateTargetMachine();
Davide Italiano595ee8c2016-06-22 18:09:23 +0000311
312 // Update llvm.compiler.used so that optimizations won't strip
313 // off AsmUndefinedReferences.
Davide Italiano30afae12016-06-22 19:51:05 +0000314 updateCompilerUsed(*Combined, *TM, AsmUndefinedRefs);
Davide Italiano595ee8c2016-06-22 18:09:23 +0000315
316 if (Config->SaveTemps)
317 saveBCFile(*Combined, ".lto.bc");
318
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000319 runLTOPasses(*Combined, *TM);
Davide Italianod26c4a12016-05-15 19:29:38 +0000320 if (HasError)
321 return {};
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000322
323 return runSplitCodegen(CreateTargetMachine);
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000324}