Coverage Report

Created: 2017-10-03 07:32

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/lld/ELF/LTO.cpp
Line
Count
Source
1
//===- 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 "LinkerScript.h"
14
#include "InputFiles.h"
15
#include "SymbolTable.h"
16
#include "Symbols.h"
17
#include "lld/Core/TargetOptionsCommandFlags.h"
18
#include "llvm/ADT/STLExtras.h"
19
#include "llvm/ADT/SmallString.h"
20
#include "llvm/ADT/StringRef.h"
21
#include "llvm/ADT/Twine.h"
22
#include "llvm/BinaryFormat/ELF.h"
23
#include "llvm/IR/DiagnosticPrinter.h"
24
#include "llvm/LTO/Caching.h"
25
#include "llvm/LTO/Config.h"
26
#include "llvm/LTO/LTO.h"
27
#include "llvm/Object/SymbolicFile.h"
28
#include "llvm/Support/CodeGen.h"
29
#include "llvm/Support/Error.h"
30
#include "llvm/Support/FileSystem.h"
31
#include "llvm/Support/MemoryBuffer.h"
32
#include "llvm/Support/raw_ostream.h"
33
#include <algorithm>
34
#include <cstddef>
35
#include <memory>
36
#include <string>
37
#include <system_error>
38
#include <vector>
39
40
using namespace llvm;
41
using namespace llvm::object;
42
using namespace llvm::ELF;
43
44
using namespace lld;
45
using namespace lld::elf;
46
47
// This is for use when debugging LTO.
48
static void saveBuffer(StringRef Buffer, const Twine &Path) {
49
  std::error_code EC;
50
  raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
51
  if (EC)
52
    error("cannot create " + Path + ": " + EC.message());
53
  OS << Buffer;
54
}
55
56
static void diagnosticHandler(const DiagnosticInfo &DI) {
57
  SmallString<128> ErrStorage;
58
  raw_svector_ostream OS(ErrStorage);
59
  DiagnosticPrinterRawOStream DP(OS);
60
  DI.print(DP);
61
  warn(ErrStorage);
62
}
63
64
static void checkError(Error E) {
65
  handleAllErrors(std::move(E),
66
                  [&](ErrorInfoBase &EIB) { error(EIB.message()); });
67
}
68
69
static std::unique_ptr<lto::LTO> createLTO() {
70
  lto::Config Conf;
71
72
  // LLD supports the new relocations.
73
  Conf.Options = InitTargetOptionsFromCodeGenFlags();
74
  Conf.Options.RelaxELFRelocations = true;
75
76
  // Always emit a section per function/datum with LTO.
77
  Conf.Options.FunctionSections = true;
78
  Conf.Options.DataSections = true;
79
80
  if (Config->Relocatable)
81
    Conf.RelocModel = None;
82
  else if (Config->Pic)
83
    Conf.RelocModel = Reloc::PIC_;
84
  else
85
    Conf.RelocModel = Reloc::Static;
86
  Conf.CodeModel = GetCodeModelFromCMModel();
87
  Conf.DisableVerify = Config->DisableVerify;
88
  Conf.DiagHandler = diagnosticHandler;
89
  Conf.OptLevel = Config->LTOO;
90
91
  // Set up a custom pipeline if we've been asked to.
92
  Conf.OptPipeline = Config->LTONewPmPasses;
93
  Conf.AAPipeline = Config->LTOAAPipeline;
94
95
  // Set up optimization remarks if we've been asked to.
96
  Conf.RemarksFilename = Config->OptRemarksFilename;
97
  Conf.RemarksWithHotness = Config->OptRemarksWithHotness;
98
99
  if (Config->SaveTemps)
100
    checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".",
101
                                 /*UseInputModulePath*/ true));
102
103
  lto::ThinBackend Backend;
104
  if (Config->ThinLTOJobs != -1u)
105
    Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
106
  return llvm::make_unique<lto::LTO>(std::move(Conf), Backend,
107
                                     Config->LTOPartitions);
108
}
109
110
114
BitcodeCompiler::BitcodeCompiler() : LTOObj(createLTO()) {
111
246
  for (Symbol *Sym : Symtab->getSymbols()) {
112
246
    StringRef Name = Sym->body()->getName();
113
246
    for (StringRef Prefix : {"__start_", "__stop_"})
114
492
      
if (492
Name.startswith(Prefix)492
)
115
4
        UsedStartStop.insert(Name.substr(Prefix.size()));
116
246
  }
117
114
}
118
119
114
BitcodeCompiler::~BitcodeCompiler() = default;
120
121
200
static void undefine(Symbol *S) {
122
200
  replaceBody<Undefined>(S, nullptr, S->body()->getName(), /*IsLocal=*/false,
123
200
                         STV_DEFAULT, S->body()->Type);
124
200
}
125
126
159
void BitcodeCompiler::add(BitcodeFile &F) {
127
159
  lto::InputFile &Obj = *F.Obj;
128
159
  unsigned SymNum = 0;
129
159
  std::vector<SymbolBody *> Syms = F.getSymbols();
130
159
  std::vector<lto::SymbolResolution> Resols(Syms.size());
131
159
132
159
  DenseSet<StringRef> ScriptSymbols;
133
159
  for (BaseCommand *Base : Script->Opt.Commands)
134
5
    
if (auto *5
Cmd5
= dyn_cast<SymbolAssignment>(Base))
135
5
      ScriptSymbols.insert(Cmd->Name);
136
159
137
159
  // Provide a resolution to the LTO API for each symbol.
138
283
  for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
139
283
    SymbolBody *B = Syms[SymNum];
140
283
    Symbol *Sym = B->symbol();
141
283
    lto::SymbolResolution &R = Resols[SymNum];
142
283
    ++SymNum;
143
283
144
283
    // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
145
283
    // reports two symbols for module ASM defined. Without this check, lld
146
283
    // flags an undefined in IR with a definition in ASM as prevailing.
147
283
    // Once IRObjectFile is fixed to report only one symbol this hack can
148
283
    // be removed.
149
212
    R.Prevailing = !ObjSym.isUndefined() && B->getFile() == &F;
150
283
151
283
    // We ask LTO to preserve following global symbols:
152
283
    // 1) All symbols when doing relocatable link, so that them can be used
153
283
    //    for doing final link.
154
283
    // 2) Symbols that are used in regular objects.
155
283
    // 3) C named sections if we have corresponding __start_/__stop_ symbol.
156
283
    // 4) Symbols that are defined in bitcode files and used for dynamic linking.
157
278
    R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
158
196
                            
(R.Prevailing && 196
Sym->includeInDynsym()131
) ||
159
114
                            UsedStartStop.count(ObjSym.getSectionName());
160
283
    if (R.Prevailing)
161
200
      undefine(Sym);
162
283
163
283
    // We tell LTO to not apply interprocedural optimization for following
164
283
    // symbols because otherwise LTO would inline them while their values are
165
283
    // still not final:
166
283
    // 1) Aliased (with --defsym) or wrapped (with --wrap) symbols.
167
283
    // 2) Symbols redefined in linker script.
168
267
    R.LinkerRedefined = !Sym->CanInline || ScriptSymbols.count(B->getName());
169
283
  }
170
159
  checkError(LTOObj->add(std::move(F.Obj), Resols));
171
159
}
172
173
// Merge all the bitcode files we have seen, codegen the result
174
// and return the resulting ObjectFile(s).
175
114
std::vector<InputFile *> BitcodeCompiler::compile() {
176
114
  std::vector<InputFile *> Ret;
177
114
  unsigned MaxTasks = LTOObj->getMaxTasks();
178
114
  Buff.resize(MaxTasks);
179
114
  Files.resize(MaxTasks);
180
114
181
114
  // The --thinlto-cache-dir option specifies the path to a directory in which
182
114
  // to cache native object files for ThinLTO incremental builds. If a path was
183
114
  // specified, configure LTO to use it as the cache directory.
184
114
  lto::NativeObjectCache Cache;
185
114
  if (!Config->ThinLTOCacheDir.empty())
186
3
    Cache = check(
187
3
        lto::localCache(Config->ThinLTOCacheDir,
188
3
                        [&](size_t Task, std::unique_ptr<MemoryBuffer> MB,
189
6
                            StringRef Path) { Files[Task] = std::move(MB); }));
190
114
191
114
  checkError(LTOObj->run(
192
123
      [&](size_t Task) {
193
123
        return llvm::make_unique<lto::NativeObjectStream>(
194
123
            llvm::make_unique<raw_svector_ostream>(Buff[Task]));
195
123
      },
196
114
      Cache));
197
114
198
114
  if (!Config->ThinLTOCacheDir.empty())
199
3
    pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
200
114
201
256
  for (unsigned I = 0; 
I != MaxTasks256
;
++I142
) {
202
142
    if (Buff[I].empty())
203
19
      continue;
204
123
    
if (123
Config->SaveTemps123
) {
205
51
      if (I == 0)
206
47
        saveBuffer(Buff[I], Config->OutputFile + ".lto.o");
207
51
      else
208
4
        saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o");
209
51
    }
210
142
    InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp"));
211
142
    Ret.push_back(Obj);
212
142
  }
213
114
214
114
  for (std::unique_ptr<MemoryBuffer> &File : Files)
215
142
    
if (142
File142
)
216
6
      Ret.push_back(createObjectFile(*File));
217
114
218
114
  return Ret;
219
114
}