Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
10
#include "CGDebugInfo.h"
11
#include "CodeGenModule.h"
12
#include "clang/AST/ASTContext.h"
13
#include "clang/AST/DeclObjC.h"
14
#include "clang/AST/Expr.h"
15
#include "clang/AST/RecursiveASTVisitor.h"
16
#include "clang/Basic/CodeGenOptions.h"
17
#include "clang/Basic/Diagnostic.h"
18
#include "clang/Basic/TargetInfo.h"
19
#include "clang/CodeGen/BackendUtil.h"
20
#include "clang/Frontend/CompilerInstance.h"
21
#include "clang/Lex/HeaderSearch.h"
22
#include "clang/Lex/Preprocessor.h"
23
#include "llvm/ADT/StringRef.h"
24
#include "llvm/Bitstream/BitstreamReader.h"
25
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
26
#include "llvm/IR/Constants.h"
27
#include "llvm/IR/DataLayout.h"
28
#include "llvm/IR/LLVMContext.h"
29
#include "llvm/IR/Module.h"
30
#include "llvm/Object/COFF.h"
31
#include "llvm/Object/ObjectFile.h"
32
#include "llvm/Support/Path.h"
33
#include "llvm/Support/TargetRegistry.h"
34
#include <memory>
35
#include <utility>
36
37
using namespace clang;
38
39
#define DEBUG_TYPE "pchcontainer"
40
41
namespace {
42
class PCHContainerGenerator : public ASTConsumer {
43
  DiagnosticsEngine &Diags;
44
  const std::string MainFileName;
45
  const std::string OutputFileName;
46
  ASTContext *Ctx;
47
  ModuleMap &MMap;
48
  const HeaderSearchOptions &HeaderSearchOpts;
49
  const PreprocessorOptions &PreprocessorOpts;
50
  CodeGenOptions CodeGenOpts;
51
  const TargetOptions TargetOpts;
52
  const LangOptions LangOpts;
53
  std::unique_ptr<llvm::LLVMContext> VMContext;
54
  std::unique_ptr<llvm::Module> M;
55
  std::unique_ptr<CodeGen::CodeGenModule> Builder;
56
  std::unique_ptr<raw_pwrite_stream> OS;
57
  std::shared_ptr<PCHBuffer> Buffer;
58
59
  /// Visit every type and emit debug info for it.
60
  struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
61
    clang::CodeGen::CGDebugInfo &DI;
62
    ASTContext &Ctx;
63
    DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
64
288
        : DI(DI), Ctx(Ctx) {}
65
66
    /// Determine whether this type can be represented in DWARF.
67
285
    static bool CanRepresent(const Type *Ty) {
68
285
      return !Ty->isDependentType() && 
!Ty->isUndeducedType()211
;
69
285
    }
70
71
0
    bool VisitImportDecl(ImportDecl *D) {
72
0
      if (!D->getImportedOwningModule())
73
0
        DI.EmitImportDecl(*D);
74
0
      return true;
75
0
    }
76
77
265
    bool VisitTypeDecl(TypeDecl *D) {
78
265
      // TagDecls may be deferred until after all decls have been merged and we
79
265
      // know the complete type. Pure forward declarations will be skipped, but
80
265
      // they don't need to be emitted into the module anyway.
81
265
      if (auto *TD = dyn_cast<TagDecl>(D))
82
200
        if (!TD->isCompleteDefinition())
83
24
          return true;
84
241
85
241
      QualType QualTy = Ctx.getTypeDeclType(D);
86
241
      if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
87
167
        DI.getOrCreateStandaloneType(QualTy, D->getLocation());
88
241
      return true;
89
241
    }
90
91
13
    bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
92
13
      QualType QualTy(D->getTypeForDecl(), 0);
93
13
      if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
94
13
        DI.getOrCreateStandaloneType(QualTy, D->getLocation());
95
13
      return true;
96
13
    }
97
98
37
    bool VisitFunctionDecl(FunctionDecl *D) {
99
37
      if (isa<CXXMethodDecl>(D))
100
26
        // This is not yet supported. Constructing the `this' argument
101
26
        // mandates a CodeGenFunction.
102
26
        return true;
103
11
104
11
      SmallVector<QualType, 16> ArgTypes;
105
11
      for (auto i : D->parameters())
106
2
        ArgTypes.push_back(i->getType());
107
11
      QualType RetTy = D->getReturnType();
108
11
      QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
109
11
                                          FunctionProtoType::ExtProtoInfo());
110
11
      if (CanRepresent(FnTy.getTypePtr()))
111
11
        DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
112
11
      return true;
113
11
    }
114
115
23
    bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
116
23
      if (!D->getClassInterface())
117
3
        return true;
118
20
119
20
      bool selfIsPseudoStrong, selfIsConsumed;
120
20
      SmallVector<QualType, 16> ArgTypes;
121
20
      ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
122
20
                                        selfIsPseudoStrong, selfIsConsumed));
123
20
      ArgTypes.push_back(Ctx.getObjCSelType());
124
20
      for (auto i : D->parameters())
125
3
        ArgTypes.push_back(i->getType());
126
20
      QualType RetTy = D->getReturnType();
127
20
      QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
128
20
                                          FunctionProtoType::ExtProtoInfo());
129
20
      if (CanRepresent(FnTy.getTypePtr()))
130
20
        DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
131
20
      return true;
132
20
    }
133
  };
134
135
public:
136
  PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
137
                        const std::string &OutputFileName,
138
                        std::unique_ptr<raw_pwrite_stream> OS,
139
                        std::shared_ptr<PCHBuffer> Buffer)
140
      : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
141
        OutputFileName(OutputFileName), Ctx(nullptr),
142
        MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
143
        HeaderSearchOpts(CI.getHeaderSearchOpts()),
144
        PreprocessorOpts(CI.getPreprocessorOpts()),
145
        TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
146
23
        OS(std::move(OS)), Buffer(std::move(Buffer)) {
147
23
    // The debug info output isn't affected by CodeModel and
148
23
    // ThreadModel, but the backend expects them to be nonempty.
149
23
    CodeGenOpts.CodeModel = "default";
150
23
    CodeGenOpts.ThreadModel = "single";
151
23
    CodeGenOpts.DebugTypeExtRefs = true;
152
23
    // When building a module MainFileName is the name of the modulemap file.
153
23
    CodeGenOpts.MainFileName =
154
23
        LangOpts.CurrentModule.empty() ? 
MainFileName5
:
LangOpts.CurrentModule18
;
155
23
    CodeGenOpts.setDebugInfo(codegenoptions::FullDebugInfo);
156
23
    CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
157
23
    CodeGenOpts.DebugPrefixMap =
158
23
        CI.getInvocation().getCodeGenOpts().DebugPrefixMap;
159
23
  }
160
161
23
  ~PCHContainerGenerator() override = default;
162
163
23
  void Initialize(ASTContext &Context) override {
164
23
    assert(!Ctx && "initialized multiple times");
165
23
166
23
    Ctx = &Context;
167
23
    VMContext.reset(new llvm::LLVMContext());
168
23
    M.reset(new llvm::Module(MainFileName, *VMContext));
169
23
    M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
170
23
    Builder.reset(new CodeGen::CodeGenModule(
171
23
        *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
172
23
173
23
    // Prepare CGDebugInfo to emit debug info for a clang module.
174
23
    auto *DI = Builder->getModuleDebugInfo();
175
23
    StringRef ModuleName = llvm::sys::path::filename(MainFileName);
176
23
    DI->setPCHDescriptor({ModuleName, "", OutputFileName,
177
23
                          ASTFileSignature{{{~0U, ~0U, ~0U, ~0U, ~1U}}}});
178
23
    DI->setModuleMap(MMap);
179
23
  }
180
181
178
  bool HandleTopLevelDecl(DeclGroupRef D) override {
182
178
    if (Diags.hasErrorOccurred())
183
0
      return true;
184
178
185
178
    // Collect debug info for all decls in this group.
186
178
    for (auto *I : D)
187
223
      if (!I->isFromASTFile()) {
188
219
        DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
189
219
        DTV.TraverseDecl(I);
190
219
      }
191
178
    return true;
192
178
  }
193
194
3
  void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
195
3
    HandleTopLevelDecl(D);
196
3
  }
197
198
111
  void HandleTagDeclDefinition(TagDecl *D) override {
199
111
    if (Diags.hasErrorOccurred())
200
0
      return;
201
111
202
111
    if (D->isFromASTFile())
203
1
      return;
204
110
205
110
    // Anonymous tag decls are deferred until we are building their declcontext.
206
110
    if (D->getName().empty())
207
37
      return;
208
73
209
73
    // Defer tag decls until their declcontext is complete.
210
73
    auto *DeclCtx = D->getDeclContext();
211
168
    while (DeclCtx) {
212
99
      if (auto *D = dyn_cast<TagDecl>(DeclCtx))
213
4
        if (!D->isCompleteDefinition())
214
4
          return;
215
95
      DeclCtx = DeclCtx->getParent();
216
95
    }
217
73
218
73
    DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
219
69
    DTV.TraverseDecl(D);
220
69
    Builder->UpdateCompletedType(D);
221
69
  }
222
223
29
  void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
224
29
    if (Diags.hasErrorOccurred())
225
0
      return;
226
29
227
29
    if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
228
25
      Builder->getModuleDebugInfo()->completeRequiredType(RD);
229
29
  }
230
231
66
  void HandleImplicitImportDecl(ImportDecl *D) override {
232
66
    if (!D->getImportedOwningModule())
233
66
      Builder->getModuleDebugInfo()->EmitImportDecl(*D);
234
66
  }
235
236
  /// Emit a container holding the serialized AST.
237
23
  void HandleTranslationUnit(ASTContext &Ctx) override {
238
23
    assert(M && VMContext && Builder);
239
23
    // Delete these on function exit.
240
23
    std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
241
23
    std::unique_ptr<llvm::Module> M = std::move(this->M);
242
23
    std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
243
23
244
23
    if (Diags.hasErrorOccurred())
245
0
      return;
246
23
247
23
    M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
248
23
    M->setDataLayout(Ctx.getTargetInfo().getDataLayout());
249
23
250
23
    // PCH files don't have a signature field in the control block,
251
23
    // but LLVM detects DWO CUs by looking for a non-zero DWO id.
252
23
    // We use the lower 64 bits for debug info.
253
23
    uint64_t Signature =
254
23
        Buffer->Signature
255
23
            ? 
(uint64_t)Buffer->Signature[1] << 32 | Buffer->Signature[0]18
256
23
            : 
~1ULL5
;
257
23
    Builder->getModuleDebugInfo()->setDwoId(Signature);
258
23
259
23
    // Finalize the Builder.
260
23
    if (Builder)
261
23
      Builder->Release();
262
23
263
23
    // Ensure the target exists.
264
23
    std::string Error;
265
23
    auto Triple = Ctx.getTargetInfo().getTriple();
266
23
    if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
267
0
      llvm::report_fatal_error(Error);
268
23
269
23
    // Emit the serialized Clang AST into its own section.
270
23
    assert(Buffer->IsComplete && "serialization did not complete");
271
23
    auto &SerializedAST = Buffer->Data;
272
23
    auto Size = SerializedAST.size();
273
23
    auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
274
23
    auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
275
23
    auto *Data = llvm::ConstantDataArray::getString(
276
23
        *VMContext, StringRef(SerializedAST.data(), Size),
277
23
        /*AddNull=*/false);
278
23
    auto *ASTSym = new llvm::GlobalVariable(
279
23
        *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
280
23
        "__clang_ast");
281
23
    // The on-disk hashtable needs to be aligned.
282
23
    ASTSym->setAlignment(8);
283
23
284
23
    // Mach-O also needs a segment name.
285
23
    if (Triple.isOSBinFormatMachO())
286
19
      ASTSym->setSection("__CLANG,__clangast");
287
4
    // COFF has an eight character length limit.
288
4
    else if (Triple.isOSBinFormatCOFF())
289
2
      ASTSym->setSection("clangast");
290
2
    else
291
2
      ASTSym->setSection("__clangast");
292
23
293
23
    LLVM_DEBUG({
294
23
      // Print the IR for the PCH container to the debug output.
295
23
      llvm::SmallString<0> Buffer;
296
23
      clang::EmitBackendOutput(
297
23
          Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
298
23
          Ctx.getTargetInfo().getDataLayout(), M.get(),
299
23
          BackendAction::Backend_EmitLL,
300
23
          llvm::make_unique<llvm::raw_svector_ostream>(Buffer));
301
23
      llvm::dbgs() << Buffer;
302
23
    });
303
23
304
23
    // Use the LLVM backend to emit the pch container.
305
23
    clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
306
23
                             LangOpts, Ctx.getTargetInfo().getDataLayout(),
307
23
                             M.get(), BackendAction::Backend_EmitObj,
308
23
                             std::move(OS));
309
23
310
23
    // Free the memory for the temporary buffer.
311
23
    llvm::SmallVector<char, 0> Empty;
312
23
    SerializedAST = std::move(Empty);
313
23
  }
314
};
315
316
} // anonymous namespace
317
318
std::unique_ptr<ASTConsumer>
319
ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
320
    CompilerInstance &CI, const std::string &MainFileName,
321
    const std::string &OutputFileName,
322
    std::unique_ptr<llvm::raw_pwrite_stream> OS,
323
23
    std::shared_ptr<PCHBuffer> Buffer) const {
324
23
  return llvm::make_unique<PCHContainerGenerator>(
325
23
      CI, MainFileName, OutputFileName, std::move(OS), Buffer);
326
23
}
327
328
StringRef
329
116
ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
330
116
  StringRef PCH;
331
116
  auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
332
116
  if (OFOrErr) {
333
55
    auto &OF = OFOrErr.get();
334
55
    bool IsCOFF = isa<llvm::object::COFFObjectFile>(*OF);
335
55
    // Find the clang AST section in the container.
336
118
    for (auto &Section : OF->sections()) {
337
118
      StringRef Name;
338
118
      Section.getName(Name);
339
118
      if ((!IsCOFF && 
Name == "__clangast"110
) ||
(65
IsCOFF65
&&
Name == "clangast"8
)) {
340
55
        if (Expected<StringRef> E = Section.getContents())
341
55
          return *E;
342
0
        else {
343
0
          handleAllErrors(E.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
344
0
            EIB.log(llvm::errs());
345
0
          });
346
0
          return "";
347
0
        }
348
55
      }
349
118
    }
350
55
  }
351
116
  
handleAllErrors(OFOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) 61
{
352
61
    if (EIB.convertToErrorCode() ==
353
61
        llvm::object::object_error::invalid_file_type)
354
61
      // As a fallback, treat the buffer as a raw AST.
355
61
      PCH = Buffer.getBuffer();
356
0
    else
357
0
      EIB.log(llvm::errs());
358
61
  });
359
61
  return PCH;
360
116
}