blob: f9ff5e29769ca55c717ba16a52e5e19aeacbaf33 [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"
16#include "llvm/Analysis/TargetLibraryInfo.h"
17#include "llvm/Analysis/TargetTransformInfo.h"
18#include "llvm/Bitcode/ReaderWriter.h"
Davide Italiano8eca2822016-04-01 00:35:29 +000019#include "llvm/CodeGen/CommandFlags.h"
Davide Italianobc176632016-04-15 22:38:10 +000020#include "llvm/CodeGen/ParallelCG.h"
Davide Italiano334fce92016-05-11 01:07:22 +000021#include "llvm/IR/AutoUpgrade.h"
Rui Ueyama25992482016-03-22 20:52:10 +000022#include "llvm/IR/LegacyPassManager.h"
23#include "llvm/Linker/IRMover.h"
24#include "llvm/Support/StringSaver.h"
25#include "llvm/Support/TargetRegistry.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Transforms/IPO.h"
28#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Rafael Espindola9fdd0712016-04-27 23:54:04 +000029#include "llvm/Transforms/Utils/ModuleUtils.h"
Rui Ueyama25992482016-03-22 20:52:10 +000030
31using namespace llvm;
32using namespace llvm::object;
33using namespace llvm::ELF;
34
35using namespace lld;
36using namespace lld::elf;
37
38// This is for use when debugging LTO.
Davide Italianobc176632016-04-15 22:38:10 +000039static void saveLtoObjectFile(StringRef Buffer, unsigned I, bool Many) {
40 SmallString<128> Filename = Config->OutputFile;
41 if (Many)
42 Filename += utostr(I);
43 Filename += ".lto.o";
Rui Ueyama25992482016-03-22 20:52:10 +000044 std::error_code EC;
Davide Italianobc176632016-04-15 22:38:10 +000045 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
Rui Ueyama25992482016-03-22 20:52:10 +000046 check(EC);
47 OS << Buffer;
48}
49
50// This is for use when debugging LTO.
51static void saveBCFile(Module &M, StringRef Suffix) {
52 std::error_code EC;
53 raw_fd_ostream OS(Config->OutputFile.str() + Suffix.str(), EC,
54 sys::fs::OpenFlags::F_None);
55 check(EC);
56 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
57}
58
59// Run LTO passes.
Rui Ueyama4e62db42016-03-29 19:19:03 +000060// Note that the gold plugin has a similar piece of code, so
61// it is probably better to move this code to a common place.
Rui Ueyama25992482016-03-22 20:52:10 +000062static void runLTOPasses(Module &M, TargetMachine &TM) {
63 legacy::PassManager LtoPasses;
64 LtoPasses.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
65 PassManagerBuilder PMB;
66 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
67 PMB.Inliner = createFunctionInliningPass();
Davide Italiano842fa532016-04-03 03:39:09 +000068 PMB.VerifyInput = PMB.VerifyOutput = !Config->DisableVerify;
Rui Ueyama25992482016-03-22 20:52:10 +000069 PMB.LoopVectorize = true;
70 PMB.SLPVectorize = true;
Peter Collingbourneed22f9b2016-03-31 21:00:27 +000071 PMB.OptLevel = Config->LtoO;
Rui Ueyama25992482016-03-22 20:52:10 +000072 PMB.populateLTOPassManager(LtoPasses);
73 LtoPasses.run(M);
74
75 if (Config->SaveTemps)
76 saveBCFile(M, ".lto.opt.bc");
77}
78
Rafael Espindolaae605c12016-04-21 20:35:25 +000079static bool shouldInternalize(const SmallPtrSet<GlobalValue *, 8> &Used,
Peter Collingbourne4f952702016-05-01 04:55:03 +000080 Symbol *S, GlobalValue *GV) {
81 if (S->IsUsedInRegularObj)
Rafael Espindolaae605c12016-04-21 20:35:25 +000082 return false;
83
84 if (Used.count(GV))
85 return false;
86
Peter Collingbourne4f952702016-05-01 04:55:03 +000087 return !S->includeInDynsym();
Rafael Espindolaae605c12016-04-21 20:35:25 +000088}
89
Rui Ueyama412c8022016-04-22 21:16:18 +000090BitcodeCompiler::BitcodeCompiler()
Rafael Espindola156f4ee2016-04-28 19:30:41 +000091 : Combined(new llvm::Module("ld-temp.o", Driver->Context)),
92 Mover(*Combined) {}
Rui Ueyama412c8022016-04-22 21:16:18 +000093
Peter Collingbourne0ef38742016-05-12 19:46:14 +000094static void undefine(Symbol *S) {
95 replaceBody<Undefined>(S, S->body()->getName(), STV_DEFAULT, 0);
96}
97
Rui Ueyama25992482016-03-22 20:52:10 +000098void BitcodeCompiler::add(BitcodeFile &F) {
Rafael Espindola156f4ee2016-04-28 19:30:41 +000099 std::unique_ptr<IRObjectFile> Obj = std::move(F.Obj);
Rui Ueyama25992482016-03-22 20:52:10 +0000100 std::vector<GlobalValue *> Keep;
101 unsigned BodyIndex = 0;
Peter Collingbourne4f952702016-05-01 04:55:03 +0000102 ArrayRef<Symbol *> Syms = F.getSymbols();
Rui Ueyama25992482016-03-22 20:52:10 +0000103
Davide Italiano86f2bd52016-03-29 21:46:35 +0000104 Module &M = Obj->getModule();
Davide Italiano493b6832016-04-16 01:33:33 +0000105 if (M.getDataLayoutStr().empty())
106 fatal("invalid bitcode file: " + F.getName() + " has no datalayout");
Davide Italiano49fe4ed2016-03-29 23:57:22 +0000107
Davide Italiano334fce92016-05-11 01:07:22 +0000108 // Discard non-compatible debug infos if necessary.
109 M.materializeMetadata();
110 UpgradeDebugInfo(M);
111
Davide Italiano49fe4ed2016-03-29 23:57:22 +0000112 // If a symbol appears in @llvm.used, the linker is required
113 // to treat the symbol as there is a reference to the symbol
114 // that it cannot see. Therefore, we can't internalize.
Davide Italiano86f2bd52016-03-29 21:46:35 +0000115 SmallPtrSet<GlobalValue *, 8> Used;
116 collectUsedGlobalVariables(M, Used, /* CompilerUsed */ false);
117
Rui Ueyama25992482016-03-22 20:52:10 +0000118 for (const BasicSymbolRef &Sym : Obj->symbols()) {
Peter Collingbourne4f952702016-05-01 04:55:03 +0000119 uint32_t Flags = Sym.getFlags();
Rui Ueyama25992482016-03-22 20:52:10 +0000120 GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
Peter Collingbourne4f952702016-05-01 04:55:03 +0000121 if (GV && GV->hasAppendingLinkage())
Rui Ueyama25992482016-03-22 20:52:10 +0000122 Keep.push_back(GV);
Peter Collingbourne4f952702016-05-01 04:55:03 +0000123 if (BitcodeFile::shouldSkip(Flags))
124 continue;
125 Symbol *S = Syms[BodyIndex++];
126 if (Flags & BasicSymbolRef::SF_Undefined)
127 continue;
Peter Collingbourne4f952702016-05-01 04:55:03 +0000128 auto *B = dyn_cast<DefinedBitcode>(S->body());
129 if (!B || B->File != &F)
Davide Italiano1460e9f2016-03-26 18:33:09 +0000130 continue;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000131
132 // We collect the set of symbols we want to internalize here
133 // and change the linkage after the IRMover executed, i.e. after
134 // we imported the symbols and satisfied undefined references
135 // to it. We can't just change linkage here because otherwise
136 // the IRMover will just rename the symbol.
137 if (GV && shouldInternalize(Used, S, GV))
138 InternalizedSyms.insert(GV->getName());
139
140 // At this point we know that either the combined LTO object will provide a
141 // definition of a symbol, or we will internalize it. In either case, we
142 // need to undefine the symbol. In the former case, the real definition
143 // needs to be able to replace the original definition without conflicting.
144 // In the latter case, we need to allow the combined LTO object to provide a
145 // definition with the same name, for example when doing parallel codegen.
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000146 undefine(S);
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000147
148 if (!GV)
149 // Module asm symbol.
150 continue;
151
Davide Italiano1460e9f2016-03-26 18:33:09 +0000152 switch (GV->getLinkage()) {
153 default:
154 break;
155 case llvm::GlobalValue::LinkOnceAnyLinkage:
156 GV->setLinkage(GlobalValue::WeakAnyLinkage);
157 break;
158 case llvm::GlobalValue::LinkOnceODRLinkage:
159 GV->setLinkage(GlobalValue::WeakODRLinkage);
160 break;
Davide Italianod4c2a032016-03-22 22:31:34 +0000161 }
Davide Italiano828ac5412016-03-28 15:44:21 +0000162
Davide Italiano1460e9f2016-03-26 18:33:09 +0000163 Keep.push_back(GV);
Rui Ueyama25992482016-03-22 20:52:10 +0000164 }
165
166 Mover.move(Obj->takeModule(), Keep,
167 [](GlobalValue &, IRMover::ValueAdder) {});
168}
169
Davide Italiano828ac5412016-03-28 15:44:21 +0000170static void internalize(GlobalValue &GV) {
171 assert(!GV.hasLocalLinkage() &&
Davide Italiano47c33f02016-03-29 21:48:25 +0000172 "Trying to internalize a symbol with local linkage!");
Davide Italiano828ac5412016-03-28 15:44:21 +0000173 GV.setLinkage(GlobalValue::InternalLinkage);
174}
175
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000176std::vector<std::unique_ptr<InputFile>> BitcodeCompiler::runSplitCodegen(
177 const std::function<std::unique_ptr<TargetMachine>()> &TMFactory) {
Davide Italianobc176632016-04-15 22:38:10 +0000178 unsigned NumThreads = Config->LtoJobs;
179 OwningData.resize(NumThreads);
180
181 std::list<raw_svector_ostream> OSs;
182 std::vector<raw_pwrite_stream *> OSPtrs;
183 for (SmallString<0> &Obj : OwningData) {
184 OSs.emplace_back(Obj);
185 OSPtrs.push_back(&OSs.back());
186 }
187
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000188 splitCodeGen(std::move(Combined), OSPtrs, {}, TMFactory);
Davide Italianobc176632016-04-15 22:38:10 +0000189
190 std::vector<std::unique_ptr<InputFile>> ObjFiles;
191 for (SmallString<0> &Obj : OwningData)
192 ObjFiles.push_back(createObjectFile(
193 MemoryBufferRef(Obj, "LLD-INTERNAL-combined-lto-object")));
194
195 if (Config->SaveTemps)
196 for (unsigned I = 0; I < NumThreads; ++I)
197 saveLtoObjectFile(OwningData[I], I, NumThreads > 1);
198
199 return ObjFiles;
200}
201
Rui Ueyama25992482016-03-22 20:52:10 +0000202// Merge all the bitcode files we have seen, codegen the result
203// and return the resulting ObjectFile.
Davide Italianobc176632016-04-15 22:38:10 +0000204std::vector<std::unique_ptr<InputFile>> BitcodeCompiler::compile() {
205 TheTriple = Combined->getTargetTriple();
Davide Italiano828ac5412016-03-28 15:44:21 +0000206 for (const auto &Name : InternalizedSyms) {
Davide Italiano15c41b22016-04-11 22:39:51 +0000207 GlobalValue *GV = Combined->getNamedValue(Name.first());
Davide Italiano828ac5412016-03-28 15:44:21 +0000208 assert(GV);
209 internalize(*GV);
210 }
211
Rui Ueyama25992482016-03-22 20:52:10 +0000212 if (Config->SaveTemps)
Davide Italiano15c41b22016-04-11 22:39:51 +0000213 saveBCFile(*Combined, ".lto.bc");
Rui Ueyama25992482016-03-22 20:52:10 +0000214
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000215 std::string Msg;
Davide Italianobc176632016-04-15 22:38:10 +0000216 const Target *T = TargetRegistry::lookupTarget(TheTriple, Msg);
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000217 if (!T)
218 fatal("target not found: " + Msg);
Davide Italiano8eca2822016-04-01 00:35:29 +0000219 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000220 Reloc::Model R = Config->Pic ? Reloc::PIC_ : Reloc::Static;
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000221
222 auto CreateTargetMachine = [&]() {
223 return std::unique_ptr<TargetMachine>(
224 T->createTargetMachine(TheTriple, "", "", Options, R));
225 };
226
227 std::unique_ptr<TargetMachine> TM = CreateTargetMachine();
228 runLTOPasses(*Combined, *TM);
229
230 return runSplitCodegen(CreateTargetMachine);
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000231}