Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/CodeGen/ModuleBuilder.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
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
// This builds an AST and converts it to LLVM Code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/CodeGen/ModuleBuilder.h"
14
#include "CGDebugInfo.h"
15
#include "CodeGenModule.h"
16
#include "clang/AST/ASTContext.h"
17
#include "clang/AST/DeclObjC.h"
18
#include "clang/AST/Expr.h"
19
#include "clang/Basic/CodeGenOptions.h"
20
#include "clang/Basic/Diagnostic.h"
21
#include "clang/Basic/TargetInfo.h"
22
#include "llvm/ADT/StringRef.h"
23
#include "llvm/IR/DataLayout.h"
24
#include "llvm/IR/LLVMContext.h"
25
#include "llvm/IR/Module.h"
26
#include <memory>
27
28
using namespace clang;
29
using namespace CodeGen;
30
31
namespace {
32
  class CodeGeneratorImpl : public CodeGenerator {
33
    DiagnosticsEngine &Diags;
34
    ASTContext *Ctx;
35
    const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
36
    const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
37
    const CodeGenOptions CodeGenOpts;  // Intentionally copied in.
38
39
    unsigned HandlingTopLevelDecls;
40
41
    /// Use this when emitting decls to block re-entrant decl emission. It will
42
    /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
43
    /// emission must be deferred longer, like at the end of a tag definition.
44
    struct HandlingTopLevelDeclRAII {
45
      CodeGeneratorImpl &Self;
46
      bool EmitDeferred;
47
      HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
48
                               bool EmitDeferred = true)
49
7.11M
          : Self(Self), EmitDeferred(EmitDeferred) {
50
7.11M
        ++Self.HandlingTopLevelDecls;
51
7.11M
      }
52
7.11M
      ~HandlingTopLevelDeclRAII() {
53
7.11M
        unsigned Level = --Self.HandlingTopLevelDecls;
54
7.11M
        if (Level == 0 && 
EmitDeferred7.11M
)
55
3.67M
          Self.EmitDeferredDecls();
56
7.11M
      }
57
    };
58
59
    CoverageSourceInfo *CoverageInfo;
60
61
  protected:
62
    std::unique_ptr<llvm::Module> M;
63
    std::unique_ptr<CodeGen::CodeGenModule> Builder;
64
65
  private:
66
    SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
67
68
  public:
69
    CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
70
                      const HeaderSearchOptions &HSO,
71
                      const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
72
                      llvm::LLVMContext &C,
73
                      CoverageSourceInfo *CoverageInfo = nullptr)
74
        : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
75
          PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
76
17.6k
          CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
77
17.6k
      C.setDiscardValueNames(CGO.DiscardValueNames);
78
17.6k
    }
79
80
17.6k
    ~CodeGeneratorImpl() override {
81
17.6k
      // There should normally not be any leftover inline method definitions.
82
17.6k
      assert(DeferredInlineMemberFuncDefs.empty() ||
83
17.6k
             Diags.hasErrorOccurred());
84
17.6k
    }
85
86
23
    CodeGenModule &CGM() {
87
23
      return *Builder;
88
23
    }
89
90
69.4k
    llvm::Module *GetModule() {
91
69.4k
      return M.get();
92
69.4k
    }
93
94
1.43k
    CGDebugInfo *getCGDebugInfo() {
95
1.43k
      return Builder->getModuleDebugInfo();
96
1.43k
    }
97
98
17.4k
    llvm::Module *ReleaseModule() {
99
17.4k
      return M.release();
100
17.4k
    }
101
102
28
    const Decl *GetDeclForMangledName(StringRef MangledName) {
103
28
      GlobalDecl Result;
104
28
      if (!Builder->lookupRepresentativeDecl(MangledName, Result))
105
1
        return nullptr;
106
27
      const Decl *D = Result.getCanonicalDecl().getDecl();
107
27
      if (auto FD = dyn_cast<FunctionDecl>(D)) {
108
25
        if (FD->hasBody(FD))
109
25
          return FD;
110
2
      } else if (auto TD = dyn_cast<TagDecl>(D)) {
111
0
        if (auto Def = TD->getDefinition())
112
0
          return Def;
113
2
      }
114
2
      return D;
115
2
    }
116
117
1
    llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
118
1
      return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
119
1
    }
120
121
    llvm::Module *StartModule(llvm::StringRef ModuleName,
122
3
                              llvm::LLVMContext &C) {
123
3
      assert(!M && "Replacing existing Module?");
124
3
      M.reset(new llvm::Module(ModuleName, C));
125
3
      Initialize(*Ctx);
126
3
      return M.get();
127
3
    }
128
129
17.6k
    void Initialize(ASTContext &Context) override {
130
17.6k
      Ctx = &Context;
131
17.6k
132
17.6k
      M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
133
17.6k
      M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
134
17.6k
      const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
135
17.6k
      if (!SDKVersion.empty())
136
5.44k
        M->setSDKVersion(SDKVersion);
137
17.6k
      Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
138
17.6k
                                               PreprocessorOpts, CodeGenOpts,
139
17.6k
                                               *M, Diags, CoverageInfo));
140
17.6k
141
17.6k
      for (auto &&Lib : CodeGenOpts.DependentLibraries)
142
54
        Builder->AddDependentLib(Lib);
143
17.6k
      for (auto &&Opt : CodeGenOpts.LinkerOptions)
144
1
        Builder->AppendLinkerOptions(Opt);
145
17.6k
    }
146
147
831k
    void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
148
831k
      if (Diags.hasErrorOccurred())
149
47
        return;
150
831k
151
831k
      Builder->HandleCXXStaticMemberVarInstantiation(VD);
152
831k
    }
153
154
3.64M
    bool HandleTopLevelDecl(DeclGroupRef DG) override {
155
3.64M
      if (Diags.hasErrorOccurred())
156
12.1k
        return true;
157
3.63M
158
3.63M
      HandlingTopLevelDeclRAII HandlingDecl(*this);
159
3.63M
160
3.63M
      // Make sure to emit all elements of a Decl.
161
7.39M
      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; 
++I3.76M
)
162
3.76M
        Builder->EmitTopLevelDecl(*I);
163
3.63M
164
3.63M
      return true;
165
3.63M
    }
166
167
3.67M
    void EmitDeferredDecls() {
168
3.67M
      if (DeferredInlineMemberFuncDefs.empty())
169
3.63M
        return;
170
38.8k
171
38.8k
      // Emit any deferred inline method definitions. Note that more deferred
172
38.8k
      // methods may be added during this loop, since ASTConsumer callbacks
173
38.8k
      // can be invoked if AST inspection results in declarations being added.
174
38.8k
      HandlingTopLevelDeclRAII HandlingDecl(*this);
175
964k
      for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); 
++I926k
)
176
926k
        Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
177
38.8k
      DeferredInlineMemberFuncDefs.clear();
178
38.8k
    }
179
180
927k
    void HandleInlineFunctionDefinition(FunctionDecl *D) override {
181
927k
      if (Diags.hasErrorOccurred())
182
1.05k
        return;
183
926k
184
926k
      assert(D->doesThisDeclarationHaveABody());
185
926k
186
926k
      // We may want to emit this definition. However, that decision might be
187
926k
      // based on computing the linkage, and we have to defer that in case we
188
926k
      // are inside of something that will change the method's final linkage,
189
926k
      // e.g.
190
926k
      //   typedef struct {
191
926k
      //     void bar();
192
926k
      //     void foo() { bar(); }
193
926k
      //   } A;
194
926k
      DeferredInlineMemberFuncDefs.push_back(D);
195
926k
196
926k
      // Provide some coverage mapping even for methods that aren't emitted.
197
926k
      // Don't do this for templated classes though, as they may not be
198
926k
      // instantiable.
199
926k
      if (!D->getLexicalDeclContext()->isDependentContext())
200
297k
        Builder->AddDeferredUnusedCoverageMapping(D);
201
926k
    }
202
203
    /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
204
    /// to (e.g. struct, union, enum, class) is completed. This allows the
205
    /// client hack on the type, which can occur at any point in the file
206
    /// (because these can be defined in declspecs).
207
2.08M
    void HandleTagDeclDefinition(TagDecl *D) override {
208
2.08M
      if (Diags.hasErrorOccurred())
209
1.34k
        return;
210
2.08M
211
2.08M
      // Don't allow re-entrant calls to CodeGen triggered by PCH
212
2.08M
      // deserialization to emit deferred decls.
213
2.08M
      HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
214
2.08M
215
2.08M
      Builder->UpdateCompletedType(D);
216
2.08M
217
2.08M
      // For MSVC compatibility, treat declarations of static data members with
218
2.08M
      // inline initializers as definitions.
219
2.08M
      if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
220
21.0k
        for (Decl *Member : D->decls()) {
221
21.0k
          if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
222
308
            if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
223
308
                
Ctx->DeclMustBeEmitted(VD)87
) {
224
43
              Builder->EmitGlobal(VD);
225
43
            }
226
308
          }
227
21.0k
        }
228
5.29k
      }
229
2.08M
      // For OpenMP emit declare reduction functions, if required.
230
2.08M
      if (Ctx->getLangOpts().OpenMP) {
231
20.7k
        for (Decl *Member : D->decls()) {
232
20.7k
          if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
233
8
            if (Ctx->DeclMustBeEmitted(DRD))
234
6
              Builder->EmitGlobal(DRD);
235
8
          }
236
20.7k
        }
237
4.13k
      }
238
2.08M
    }
239
240
1.35M
    void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
241
1.35M
      if (Diags.hasErrorOccurred())
242
1.00k
        return;
243
1.35M
244
1.35M
      // Don't allow re-entrant calls to CodeGen triggered by PCH
245
1.35M
      // deserialization to emit deferred decls.
246
1.35M
      HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
247
1.35M
248
1.35M
      if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
249
536k
        if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
250
523k
          DI->completeRequiredType(RD);
251
1.35M
    }
252
253
17.6k
    void HandleTranslationUnit(ASTContext &Ctx) override {
254
17.6k
      // Release the Builder when there is no error.
255
17.6k
      if (!Diags.hasErrorOccurred() && 
Builder17.4k
)
256
17.4k
        Builder->Release();
257
17.6k
258
17.6k
      // If there are errors before or when releasing the Builder, reset
259
17.6k
      // the module to stop here before invoking the backend.
260
17.6k
      if (Diags.hasErrorOccurred()) {
261
171
        if (Builder)
262
171
          Builder->clear();
263
171
        M.reset();
264
171
        return;
265
171
      }
266
17.6k
    }
267
268
466
    void AssignInheritanceModel(CXXRecordDecl *RD) override {
269
466
      if (Diags.hasErrorOccurred())
270
18
        return;
271
448
272
448
      Builder->RefreshTypeCacheForClass(RD);
273
448
    }
274
275
14.7k
    void CompleteTentativeDefinition(VarDecl *D) override {
276
14.7k
      if (Diags.hasErrorOccurred())
277
55
        return;
278
14.6k
279
14.6k
      Builder->EmitTentativeDefinition(D);
280
14.6k
    }
281
282
1.70k
    void HandleVTable(CXXRecordDecl *RD) override {
283
1.70k
      if (Diags.hasErrorOccurred())
284
0
        return;
285
1.70k
286
1.70k
      Builder->EmitVTable(RD);
287
1.70k
    }
288
  };
289
}
290
291
0
void CodeGenerator::anchor() { }
292
293
23
CodeGenModule &CodeGenerator::CGM() {
294
23
  return static_cast<CodeGeneratorImpl*>(this)->CGM();
295
23
}
296
297
69.4k
llvm::Module *CodeGenerator::GetModule() {
298
69.4k
  return static_cast<CodeGeneratorImpl*>(this)->GetModule();
299
69.4k
}
300
301
17.4k
llvm::Module *CodeGenerator::ReleaseModule() {
302
17.4k
  return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
303
17.4k
}
304
305
1.43k
CGDebugInfo *CodeGenerator::getCGDebugInfo() {
306
1.43k
  return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
307
1.43k
}
308
309
28
const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
310
28
  return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
311
28
}
312
313
llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
314
1
                                               bool isForDefinition) {
315
1
  return static_cast<CodeGeneratorImpl*>(this)
316
1
           ->GetAddrOfGlobal(global, isForDefinition);
317
1
}
318
319
llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
320
3
                                         llvm::LLVMContext &C) {
321
3
  return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
322
3
}
323
324
CodeGenerator *clang::CreateLLVMCodeGen(
325
    DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
326
    const HeaderSearchOptions &HeaderSearchOpts,
327
    const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
328
17.6k
    llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
329
17.6k
  return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
330
17.6k
                               PreprocessorOpts, CGO, C, CoverageInfo);
331
17.6k
}