Coverage Report

Created: 2020-09-19 12:23

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CodeGenAction.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
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/CodeGenAction.h"
10
#include "CodeGenModule.h"
11
#include "CoverageMappingGen.h"
12
#include "MacroPPCallbacks.h"
13
#include "clang/AST/ASTConsumer.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/DeclCXX.h"
16
#include "clang/AST/DeclGroup.h"
17
#include "clang/Basic/DiagnosticFrontend.h"
18
#include "clang/Basic/FileManager.h"
19
#include "clang/Basic/LangStandard.h"
20
#include "clang/Basic/SourceManager.h"
21
#include "clang/Basic/TargetInfo.h"
22
#include "clang/CodeGen/BackendUtil.h"
23
#include "clang/CodeGen/ModuleBuilder.h"
24
#include "clang/Driver/DriverDiagnostic.h"
25
#include "clang/Frontend/CompilerInstance.h"
26
#include "clang/Frontend/FrontendDiagnostic.h"
27
#include "clang/Lex/Preprocessor.h"
28
#include "llvm/Bitcode/BitcodeReader.h"
29
#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
30
#include "llvm/IR/DebugInfo.h"
31
#include "llvm/IR/DiagnosticInfo.h"
32
#include "llvm/IR/DiagnosticPrinter.h"
33
#include "llvm/IR/GlobalValue.h"
34
#include "llvm/IR/LLVMContext.h"
35
#include "llvm/IR/LLVMRemarkStreamer.h"
36
#include "llvm/IR/Module.h"
37
#include "llvm/IRReader/IRReader.h"
38
#include "llvm/Linker/Linker.h"
39
#include "llvm/Pass.h"
40
#include "llvm/Support/MemoryBuffer.h"
41
#include "llvm/Support/SourceMgr.h"
42
#include "llvm/Support/TimeProfiler.h"
43
#include "llvm/Support/Timer.h"
44
#include "llvm/Support/ToolOutputFile.h"
45
#include "llvm/Support/YAMLTraits.h"
46
#include "llvm/Transforms/IPO/Internalize.h"
47
48
#include <memory>
49
using namespace clang;
50
using namespace llvm;
51
52
namespace clang {
53
  class BackendConsumer;
54
  class ClangDiagnosticHandler final : public DiagnosticHandler {
55
  public:
56
    ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
57
17.1k
        : CodeGenOpts(CGOpts), BackendCon(BCon) {}
58
59
    bool handleDiagnostics(const DiagnosticInfo &DI) override;
60
61
4.84M
    bool isAnalysisRemarkEnabled(StringRef PassName) const override {
62
4.84M
      return (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
63
400
              CodeGenOpts.OptimizationRemarkAnalysisPattern->match(PassName));
64
4.84M
    }
65
44.7k
    bool isMissedOptRemarkEnabled(StringRef PassName) const override {
66
44.7k
      return (CodeGenOpts.OptimizationRemarkMissedPattern &&
67
14
              CodeGenOpts.OptimizationRemarkMissedPattern->match(PassName));
68
44.7k
    }
69
6.48k
    bool isPassedOptRemarkEnabled(StringRef PassName) const override {
70
6.48k
      return (CodeGenOpts.OptimizationRemarkPattern &&
71
176
              CodeGenOpts.OptimizationRemarkPattern->match(PassName));
72
6.48k
    }
73
74
429k
    bool isAnyRemarkEnabled() const override {
75
429k
      return (CodeGenOpts.OptimizationRemarkAnalysisPattern ||
76
429k
              CodeGenOpts.OptimizationRemarkMissedPattern ||
77
429k
              CodeGenOpts.OptimizationRemarkPattern);
78
429k
    }
79
80
  private:
81
    const CodeGenOptions &CodeGenOpts;
82
    BackendConsumer *BackendCon;
83
  };
84
85
  static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
86
2
                                   const CodeGenOptions CodeGenOpts) {
87
2
    handleAllErrors(
88
2
        std::move(E),
89
0
      [&](const LLVMRemarkSetupFileError &E) {
90
0
          Diags.Report(diag::err_cannot_open_file)
91
0
              << CodeGenOpts.OptRecordFile << E.message();
92
0
        },
93
1
      [&](const LLVMRemarkSetupPatternError &E) {
94
1
          Diags.Report(diag::err_drv_optimization_remark_pattern)
95
1
              << E.message() << CodeGenOpts.OptRecordPasses;
96
1
        },
97
1
      [&](const LLVMRemarkSetupFormatError &E) {
98
1
          Diags.Report(diag::err_drv_optimization_remark_format)
99
1
              << CodeGenOpts.OptRecordFormat;
100
1
        });
101
2
    }
102
103
  class BackendConsumer : public ASTConsumer {
104
    using LinkModule = CodeGenAction::LinkModule;
105
106
    virtual void anchor();
107
    DiagnosticsEngine &Diags;
108
    BackendAction Action;
109
    const HeaderSearchOptions &HeaderSearchOpts;
110
    const CodeGenOptions &CodeGenOpts;
111
    const TargetOptions &TargetOpts;
112
    const LangOptions &LangOpts;
113
    std::unique_ptr<raw_pwrite_stream> AsmOutStream;
114
    ASTContext *Context;
115
116
    Timer LLVMIRGeneration;
117
    unsigned LLVMIRGenerationRefCount;
118
119
    /// True if we've finished generating IR. This prevents us from generating
120
    /// additional LLVM IR after emitting output in HandleTranslationUnit. This
121
    /// can happen when Clang plugins trigger additional AST deserialization.
122
    bool IRGenFinished = false;
123
124
    std::unique_ptr<CodeGenerator> Gen;
125
126
    SmallVector<LinkModule, 4> LinkModules;
127
128
    // This is here so that the diagnostic printer knows the module a diagnostic
129
    // refers to.
130
    llvm::Module *CurLinkModule = nullptr;
131
132
  public:
133
    BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
134
                    const HeaderSearchOptions &HeaderSearchOpts,
135
                    const PreprocessorOptions &PPOpts,
136
                    const CodeGenOptions &CodeGenOpts,
137
                    const TargetOptions &TargetOpts,
138
                    const LangOptions &LangOpts, bool TimePasses,
139
                    const std::string &InFile,
140
                    SmallVector<LinkModule, 4> LinkModules,
141
                    std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
142
                    CoverageSourceInfo *CoverageInfo = nullptr)
143
        : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
144
          CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
145
          AsmOutStream(std::move(OS)), Context(nullptr),
146
          LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
147
          LLVMIRGenerationRefCount(0),
148
          Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
149
                                CodeGenOpts, C, CoverageInfo)),
150
17.2k
          LinkModules(std::move(LinkModules)) {
151
17.2k
      FrontendTimesIsEnabled = TimePasses;
152
17.2k
      llvm::TimePassesIsEnabled = TimePasses;
153
17.2k
    }
154
155
    // This constructor is used in installing an empty BackendConsumer
156
    // to use the clang diagnostic handler for IR input files. It avoids
157
    // initializing the OS field.
158
    BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
159
                    const HeaderSearchOptions &HeaderSearchOpts,
160
                    const PreprocessorOptions &PPOpts,
161
                    const CodeGenOptions &CodeGenOpts,
162
                    const TargetOptions &TargetOpts,
163
                    const LangOptions &LangOpts, bool TimePasses,
164
                    SmallVector<LinkModule, 4> LinkModules, LLVMContext &C,
165
                    CoverageSourceInfo *CoverageInfo = nullptr)
166
        : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
167
          CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
168
          Context(nullptr),
169
          LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
170
          LLVMIRGenerationRefCount(0),
171
          Gen(CreateLLVMCodeGen(Diags, "", HeaderSearchOpts, PPOpts,
172
                                CodeGenOpts, C, CoverageInfo)),
173
114
          LinkModules(std::move(LinkModules)) {
174
114
      FrontendTimesIsEnabled = TimePasses;
175
114
      llvm::TimePassesIsEnabled = TimePasses;
176
114
    }
177
68.4k
    llvm::Module *getModule() const { return Gen->GetModule(); }
178
17.2k
    std::unique_ptr<llvm::Module> takeModule() {
179
17.2k
      return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
180
17.2k
    }
181
182
5
    CodeGenerator *getCodeGenerator() { return Gen.get(); }
183
184
536k
    void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
185
536k
      Gen->HandleCXXStaticMemberVarInstantiation(VD);
186
536k
    }
187
188
17.2k
    void Initialize(ASTContext &Ctx) override {
189
17.2k
      assert(!Context && "initialized multiple times");
190
17.2k
191
17.2k
      Context = &Ctx;
192
17.2k
193
17.2k
      if (FrontendTimesIsEnabled)
194
10
        LLVMIRGeneration.startTimer();
195
17.2k
196
17.2k
      Gen->Initialize(Ctx);
197
17.2k
198
17.2k
      if (FrontendTimesIsEnabled)
199
10
        LLVMIRGeneration.stopTimer();
200
17.2k
    }
201
202
12.7M
    bool HandleTopLevelDecl(DeclGroupRef D) override {
203
12.7M
      PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
204
12.7M
                                     Context->getSourceManager(),
205
12.7M
                                     "LLVM IR generation of declaration");
206
12.7M
207
      // Recurse.
208
12.7M
      if (FrontendTimesIsEnabled) {
209
82
        LLVMIRGenerationRefCount += 1;
210
82
        if (LLVMIRGenerationRefCount == 1)
211
82
          LLVMIRGeneration.startTimer();
212
82
      }
213
12.7M
214
12.7M
      Gen->HandleTopLevelDecl(D);
215
12.7M
216
12.7M
      if (FrontendTimesIsEnabled) {
217
82
        LLVMIRGenerationRefCount -= 1;
218
82
        if (LLVMIRGenerationRefCount == 0)
219
82
          LLVMIRGeneration.stopTimer();
220
82
      }
221
12.7M
222
12.7M
      return true;
223
12.7M
    }
224
225
413k
    void HandleInlineFunctionDefinition(FunctionDecl *D) override {
226
413k
      PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
227
413k
                                     Context->getSourceManager(),
228
413k
                                     "LLVM IR generation of inline function");
229
413k
      if (FrontendTimesIsEnabled)
230
0
        LLVMIRGeneration.startTimer();
231
413k
232
413k
      Gen->HandleInlineFunctionDefinition(D);
233
413k
234
413k
      if (FrontendTimesIsEnabled)
235
0
        LLVMIRGeneration.stopTimer();
236
413k
    }
237
238
72.6k
    void HandleInterestingDecl(DeclGroupRef D) override {
239
      // Ignore interesting decls from the AST reader after IRGen is finished.
240
72.6k
      if (!IRGenFinished)
241
72.6k
        HandleTopLevelDecl(D);
242
72.6k
    }
243
244
    // Links each entry in LinkModules into our module.  Returns true on error.
245
17.0k
    bool LinkInModules() {
246
13
      for (auto &LM : LinkModules) {
247
13
        if (LM.PropagateAttrs)
248
22
          
for (Function &F : *LM.Module)8
{
249
            // Skip intrinsics. Keep consistent with how intrinsics are created
250
            // in LLVM IR.
251
22
            if (F.isIntrinsic())
252
0
              continue;
253
22
            Gen->CGM().addDefaultFunctionDefinitionAttributes(F);
254
22
          }
255
13
256
13
        CurLinkModule = LM.Module.get();
257
13
258
13
        bool Err;
259
13
        if (LM.Internalize) {
260
8
          Err = Linker::linkModules(
261
8
              *getModule(), std::move(LM.Module), LM.LinkFlags,
262
8
              [](llvm::Module &M, const llvm::StringSet<> &GVS) {
263
21
                internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
264
21
                  return !GV.hasName() || (GVS.count(GV.getName()) == 0);
265
21
                });
266
8
              });
267
5
        } else {
268
5
          Err = Linker::linkModules(*getModule(), std::move(LM.Module),
269
5
                                    LM.LinkFlags);
270
5
        }
271
13
272
13
        if (Err)
273
1
          return true;
274
13
      }
275
17.0k
      return false; // success
276
17.0k
    }
277
278
17.2k
    void HandleTranslationUnit(ASTContext &C) override {
279
17.2k
      {
280
17.2k
        llvm::TimeTraceScope TimeScope("Frontend");
281
17.2k
        PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
282
17.2k
        if (FrontendTimesIsEnabled) {
283
10
          LLVMIRGenerationRefCount += 1;
284
10
          if (LLVMIRGenerationRefCount == 1)
285
10
            LLVMIRGeneration.startTimer();
286
10
        }
287
17.2k
288
17.2k
        Gen->HandleTranslationUnit(C);
289
17.2k
290
17.2k
        if (FrontendTimesIsEnabled) {
291
10
          LLVMIRGenerationRefCount -= 1;
292
10
          if (LLVMIRGenerationRefCount == 0)
293
10
            LLVMIRGeneration.stopTimer();
294
10
        }
295
17.2k
296
17.2k
        IRGenFinished = true;
297
17.2k
      }
298
17.2k
299
      // Silently ignore if we weren't initialized for some reason.
300
17.2k
      if (!getModule())
301
194
        return;
302
17.0k
303
      // Install an inline asm handler so that diagnostics get printed through
304
      // our diagnostics hooks.
305
17.0k
      LLVMContext &Ctx = getModule()->getContext();
306
17.0k
      LLVMContext::InlineAsmDiagHandlerTy OldHandler =
307
17.0k
        Ctx.getInlineAsmDiagnosticHandler();
308
17.0k
      void *OldContext = Ctx.getInlineAsmDiagnosticContext();
309
17.0k
      Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
310
17.0k
311
17.0k
      std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
312
17.0k
          Ctx.getDiagnosticHandler();
313
17.0k
      Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
314
17.0k
        CodeGenOpts, this));
315
17.0k
316
17.0k
      Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
317
17.0k
          setupLLVMOptimizationRemarks(
318
17.0k
              Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
319
17.0k
              CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
320
17.0k
              CodeGenOpts.DiagnosticsHotnessThreshold);
321
17.0k
322
17.0k
      if (Error E = OptRecordFileOrErr.takeError()) {
323
2
        reportOptRecordError(std::move(E), Diags, CodeGenOpts);
324
2
        return;
325
2
      }
326
17.0k
327
17.0k
      std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
328
17.0k
          std::move(*OptRecordFileOrErr);
329
17.0k
330
17.0k
      if (OptRecordFile &&
331
7
          CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
332
1
        Ctx.setDiagnosticsHotnessRequested(true);
333
17.0k
334
      // Link each LinkModule into our module.
335
17.0k
      if (LinkInModules())
336
1
        return;
337
17.0k
338
17.0k
      EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
339
17.0k
340
17.0k
      EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
341
17.0k
                        LangOpts, C.getTargetInfo().getDataLayout(),
342
17.0k
                        getModule(), Action, std::move(AsmOutStream));
343
17.0k
344
17.0k
      Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
345
17.0k
346
17.0k
      Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
347
17.0k
348
17.0k
      if (OptRecordFile)
349
7
        OptRecordFile->keep();
350
17.0k
    }
351
352
2.17M
    void HandleTagDeclDefinition(TagDecl *D) override {
353
2.17M
      PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
354
2.17M
                                     Context->getSourceManager(),
355
2.17M
                                     "LLVM IR generation of declaration");
356
2.17M
      Gen->HandleTagDeclDefinition(D);
357
2.17M
    }
358
359
986k
    void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
360
986k
      Gen->HandleTagDeclRequiredDefinition(D);
361
986k
    }
362
363
4.38k
    void CompleteTentativeDefinition(VarDecl *D) override {
364
4.38k
      Gen->CompleteTentativeDefinition(D);
365
4.38k
    }
366
367
7
    void CompleteExternalDeclaration(VarDecl *D) override {
368
7
      Gen->CompleteExternalDeclaration(D);
369
7
    }
370
371
478
    void AssignInheritanceModel(CXXRecordDecl *RD) override {
372
478
      Gen->AssignInheritanceModel(RD);
373
478
    }
374
375
777
    void HandleVTable(CXXRecordDecl *RD) override {
376
777
      Gen->HandleVTable(RD);
377
777
    }
378
379
    static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
380
10
                                     unsigned LocCookie) {
381
10
      SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
382
10
      ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
383
10
    }
384
385
    /// Get the best possible source location to represent a diagnostic that
386
    /// may have associated debug info.
387
    const FullSourceLoc
388
    getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
389
                                bool &BadDebugInfo, StringRef &Filename,
390
                                unsigned &Line, unsigned &Column) const;
391
392
    void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
393
                               SourceLocation LocCookie);
394
395
    void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
396
    /// Specialized handler for InlineAsm diagnostic.
397
    /// \return True if the diagnostic has been successfully reported, false
398
    /// otherwise.
399
    bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
400
    /// Specialized handler for StackSize diagnostic.
401
    /// \return True if the diagnostic has been successfully reported, false
402
    /// otherwise.
403
    bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
404
    /// Specialized handler for unsupported backend feature diagnostic.
405
    void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
406
    /// Specialized handler for misexpect warnings.
407
    /// Note that misexpect remarks are emitted through ORE
408
    void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D);
409
    /// Specialized handlers for optimization remarks.
410
    /// Note that these handlers only accept remarks and they always handle
411
    /// them.
412
    void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
413
                                 unsigned DiagID);
414
    void
415
    OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
416
    void OptimizationRemarkHandler(
417
        const llvm::OptimizationRemarkAnalysisFPCommute &D);
418
    void OptimizationRemarkHandler(
419
        const llvm::OptimizationRemarkAnalysisAliasing &D);
420
    void OptimizationFailureHandler(
421
        const llvm::DiagnosticInfoOptimizationFailure &D);
422
  };
423
424
0
  void BackendConsumer::anchor() {}
425
}
426
427
135k
bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
428
135k
  BackendCon->DiagnosticHandlerImpl(DI);
429
135k
  return true;
430
135k
}
431
432
/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
433
/// buffer to be a valid FullSourceLoc.
434
static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
435
10
                                            SourceManager &CSM) {
436
  // Get both the clang and llvm source managers.  The location is relative to
437
  // a memory buffer that the LLVM Source Manager is handling, we need to add
438
  // a copy to the Clang source manager.
439
10
  const llvm::SourceMgr &LSM = *D.getSourceMgr();
440
10
441
  // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
442
  // already owns its one and clang::SourceManager wants to own its one.
443
10
  const MemoryBuffer *LBuf =
444
10
  LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
445
10
446
  // Create the copy and transfer ownership to clang::SourceManager.
447
  // TODO: Avoid copying files into memory.
448
10
  std::unique_ptr<llvm::MemoryBuffer> CBuf =
449
10
      llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
450
10
                                           LBuf->getBufferIdentifier());
451
  // FIXME: Keep a file ID map instead of creating new IDs for each location.
452
10
  FileID FID = CSM.createFileID(std::move(CBuf));
453
10
454
  // Translate the offset into the file.
455
10
  unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
456
10
  SourceLocation NewLoc =
457
10
  CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
458
10
  return FullSourceLoc(NewLoc, CSM);
459
10
}
460
461
462
/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
463
/// error parsing inline asm.  The SMDiagnostic indicates the error relative to
464
/// the temporary memory buffer that the inline asm parser has set up.
465
void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
466
10
                                            SourceLocation LocCookie) {
467
  // There are a couple of different kinds of errors we could get here.  First,
468
  // we re-format the SMDiagnostic in terms of a clang diagnostic.
469
10
470
  // Strip "error: " off the start of the message string.
471
10
  StringRef Message = D.getMessage();
472
10
  if (Message.startswith("error: "))
473
0
    Message = Message.substr(7);
474
10
475
  // If the SMDiagnostic has an inline asm source location, translate it.
476
10
  FullSourceLoc Loc;
477
10
  if (D.getLoc() != SMLoc())
478
10
    Loc = ConvertBackendLocation(D, Context->getSourceManager());
479
10
480
10
  unsigned DiagID;
481
10
  switch (D.getKind()) {
482
5
  case llvm::SourceMgr::DK_Error:
483
5
    DiagID = diag::err_fe_inline_asm;
484
5
    break;
485
5
  case llvm::SourceMgr::DK_Warning:
486
5
    DiagID = diag::warn_fe_inline_asm;
487
5
    break;
488
0
  case llvm::SourceMgr::DK_Note:
489
0
    DiagID = diag::note_fe_inline_asm;
490
0
    break;
491
0
  case llvm::SourceMgr::DK_Remark:
492
0
    llvm_unreachable("remarks unexpected");
493
10
  }
494
  // If this problem has clang-level source location information, report the
495
  // issue in the source with a note showing the instantiated
496
  // code.
497
10
  if (LocCookie.isValid()) {
498
9
    Diags.Report(LocCookie, DiagID).AddString(Message);
499
9
500
9
    if (D.getLoc().isValid()) {
501
9
      DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
502
      // Convert the SMDiagnostic ranges into SourceRange and attach them
503
      // to the diagnostic.
504
2
      for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
505
2
        unsigned Column = D.getColumnNo();
506
2
        B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
507
2
                         Loc.getLocWithOffset(Range.second - Column));
508
2
      }
509
9
    }
510
9
    return;
511
9
  }
512
1
513
  // Otherwise, report the backend issue as occurring in the generated .s file.
514
  // If Loc is invalid, we still need to report the issue, it just gets no
515
  // location info.
516
1
  Diags.Report(Loc, DiagID).AddString(Message);
517
1
}
518
519
#define ComputeDiagID(Severity, GroupName, DiagID)                             \
520
18
  do {                                                                         \
521
17
    switch (Severity) {                                                        \
522
16
    case llvm::DS_Error:                                                       \
523
16
      DiagID = diag::err_fe_##GroupName;                                       \
524
16
      break;                                                                   \
525
1
    case llvm::DS_Warning:                                                     \
526
1
      DiagID = diag::warn_fe_##GroupName;                                      \
527
1
      break;                                                                   \
528
0
    case llvm::DS_Remark:                                                      \
529
0
      llvm_unreachable("'remark' severity not expected");                      \
530
0
      break;                                                                   \
531
0
    case llvm::DS_Note:                                                        \
532
0
      DiagID = diag::note_fe_##GroupName;                                      \
533
0
      break;                                                                   \
534
17
    }                                                                          \
535
17
  } while (false)
536
537
#define ComputeDiagRemarkID(Severity, GroupName, DiagID)                       \
538
4
  do {                                                                         \
539
4
    switch (Severity) {                                                        \
540
4
    case llvm::DS_Error:                                                       \
541
4
      DiagID = diag::err_fe_##GroupName;                                       \
542
4
      break;                                                                   \
543
0
    case llvm::DS_Warning:                                                     \
544
0
      DiagID = diag::warn_fe_##GroupName;                                      \
545
0
      break;                                                                   \
546
0
    case llvm::DS_Remark:                                                      \
547
0
      DiagID = diag::remark_fe_##GroupName;                                    \
548
0
      break;                                                                   \
549
0
    case llvm::DS_Note:                                                        \
550
0
      DiagID = diag::note_fe_##GroupName;                                      \
551
0
      break;                                                                   \
552
4
    }                                                                          \
553
4
  } while (false)
554
555
bool
556
16
BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
557
16
  unsigned DiagID;
558
16
  ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
559
16
  std::string Message = D.getMsgStr().str();
560
16
561
  // If this problem has clang-level source location information, report the
562
  // issue as being a problem in the source with a note showing the instantiated
563
  // code.
564
16
  SourceLocation LocCookie =
565
16
      SourceLocation::getFromRawEncoding(D.getLocCookie());
566
16
  if (LocCookie.isValid())
567
16
    Diags.Report(LocCookie, DiagID).AddString(Message);
568
0
  else {
569
    // Otherwise, report the backend diagnostic as occurring in the generated
570
    // .s file.
571
    // If Loc is invalid, we still need to report the diagnostic, it just gets
572
    // no location info.
573
0
    FullSourceLoc Loc;
574
0
    Diags.Report(Loc, DiagID).AddString(Message);
575
0
  }
576
  // We handled all the possible severities.
577
16
  return true;
578
16
}
579
580
bool
581
18
BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
582
18
  if (D.getSeverity() != llvm::DS_Warning)
583
    // For now, the only support we have for StackSize diagnostic is warning.
584
    // We do not know how to format other severities.
585
0
    return false;
586
18
587
18
  if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
588
    // FIXME: Shouldn't need to truncate to uint32_t
589
17
    Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
590
17
                 diag::warn_fe_frame_larger_than)
591
17
      << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
592
17
    return true;
593
17
  }
594
1
595
1
  return false;
596
1
}
597
598
const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
599
    const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
600
142
    StringRef &Filename, unsigned &Line, unsigned &Column) const {
601
142
  SourceManager &SourceMgr = Context->getSourceManager();
602
142
  FileManager &FileMgr = SourceMgr.getFileManager();
603
142
  SourceLocation DILoc;
604
142
605
142
  if (D.isLocationAvailable()) {
606
113
    D.getLocation(Filename, Line, Column);
607
113
    if (Line > 0) {
608
113
      auto FE = FileMgr.getFile(Filename);
609
113
      if (!FE)
610
113
        FE = FileMgr.getFile(D.getAbsolutePath());
611
113
      if (FE) {
612
        // If -gcolumn-info was not used, Column will be 0. This upsets the
613
        // source manager, so pass 1 if Column is not set.
614
60
        DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? 
Column51
: 1);
615
111
      }
616
113
    }
617
113
    BadDebugInfo = DILoc.isInvalid();
618
113
  }
619
142
620
  // If a location isn't available, try to approximate it using the associated
621
  // function definition. We use the definition's right brace to differentiate
622
  // from diagnostics that genuinely relate to the function itself.
623
142
  FullSourceLoc Loc(DILoc, SourceMgr);
624
142
  if (Loc.isInvalid())
625
31
    if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
626
15
      Loc = FD->getASTContext().getFullLoc(FD->getLocation());
627
142
628
142
  if (DILoc.isInvalid() && 
D.isLocationAvailable()31
)
629
    // If we were not able to translate the file:line:col information
630
    // back to a SourceLocation, at least emit a note stating that
631
    // we could not translate this location. This can happen in the
632
    // case of #line directives.
633
2
    Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
634
2
        << Filename << Line << Column;
635
142
636
142
  return Loc;
637
142
}
638
639
void BackendConsumer::UnsupportedDiagHandler(
640
9
    const llvm::DiagnosticInfoUnsupported &D) {
641
  // We only support warnings or errors.
642
9
  assert(D.getSeverity() == llvm::DS_Error ||
643
9
         D.getSeverity() == llvm::DS_Warning);
644
9
645
9
  StringRef Filename;
646
9
  unsigned Line, Column;
647
9
  bool BadDebugInfo = false;
648
9
  FullSourceLoc Loc;
649
9
  std::string Msg;
650
9
  raw_string_ostream MsgStream(Msg);
651
9
652
  // Context will be nullptr for IR input files, we will construct the diag
653
  // message from llvm::DiagnosticInfoUnsupported.
654
9
  if (Context != nullptr) {
655
6
    Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
656
6
    MsgStream << D.getMessage();
657
3
  } else {
658
3
    DiagnosticPrinterRawOStream DP(MsgStream);
659
3
    D.print(DP);
660
3
  }
661
9
662
9
  auto DiagType = D.getSeverity() == llvm::DS_Error
663
8
                      ? diag::err_fe_backend_unsupported
664
1
                      : diag::warn_fe_backend_unsupported;
665
9
  Diags.Report(Loc, DiagType) << MsgStream.str();
666
9
667
9
  if (BadDebugInfo)
668
    // If we were not able to translate the file:line:col information
669
    // back to a SourceLocation, at least emit a note stating that
670
    // we could not translate this location. This can happen in the
671
    // case of #line directives.
672
0
    Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
673
0
        << Filename << Line << Column;
674
9
}
675
676
void BackendConsumer::MisExpectDiagHandler(
677
7
    const llvm::DiagnosticInfoMisExpect &D) {
678
7
  StringRef Filename;
679
7
  unsigned Line, Column;
680
7
  bool BadDebugInfo = false;
681
7
  FullSourceLoc Loc;
682
7
  std::string Msg;
683
7
  raw_string_ostream MsgStream(Msg);
684
7
  DiagnosticPrinterRawOStream DP(MsgStream);
685
7
686
  // Context will be nullptr for IR input files, we will construct the diag
687
  // message from llvm::DiagnosticInfoMisExpect.
688
7
  if (Context != nullptr) {
689
5
    Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
690
5
    MsgStream << D.getMsg();
691
2
  } else {
692
2
    DiagnosticPrinterRawOStream DP(MsgStream);
693
2
    D.print(DP);
694
2
  }
695
7
  Diags.Report(Loc, diag::warn_profile_data_misexpect) << MsgStream.str();
696
7
697
7
  if (BadDebugInfo)
698
    // If we were not able to translate the file:line:col information
699
    // back to a SourceLocation, at least emit a note stating that
700
    // we could not translate this location. This can happen in the
701
    // case of #line directives.
702
0
    Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
703
0
        << Filename << Line << Column;
704
7
}
705
706
void BackendConsumer::EmitOptimizationMessage(
707
140
    const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
708
  // We only support warnings and remarks.
709
140
  assert(D.getSeverity() == llvm::DS_Remark ||
710
140
         D.getSeverity() == llvm::DS_Warning);
711
140
712
140
  StringRef Filename;
713
140
  unsigned Line, Column;
714
140
  bool BadDebugInfo = false;
715
140
  FullSourceLoc Loc;
716
140
  std::string Msg;
717
140
  raw_string_ostream MsgStream(Msg);
718
140
719
  // Context will be nullptr for IR input files, we will construct the remark
720
  // message from llvm::DiagnosticInfoOptimizationBase.
721
140
  if (Context != nullptr) {
722
131
    Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
723
131
    MsgStream << D.getMsg();
724
9
  } else {
725
9
    DiagnosticPrinterRawOStream DP(MsgStream);
726
9
    D.print(DP);
727
9
  }
728
140
729
140
  if (D.getHotness())
730
17
    MsgStream << " (hotness: " << *D.getHotness() << ")";
731
140
732
140
  Diags.Report(Loc, DiagID)
733
140
      << AddFlagValue(D.getPassName())
734
140
      << MsgStream.str();
735
140
736
140
  if (BadDebugInfo)
737
    // If we were not able to translate the file:line:col information
738
    // back to a SourceLocation, at least emit a note stating that
739
    // we could not translate this location. This can happen in the
740
    // case of #line directives.
741
2
    Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
742
2
        << Filename << Line << Column;
743
140
}
744
745
void BackendConsumer::OptimizationRemarkHandler(
746
135k
    const llvm::DiagnosticInfoOptimizationBase &D) {
747
  // Without hotness information, don't show noisy remarks.
748
135k
  if (D.isVerbose() && 
!D.getHotness()268
)
749
267
    return;
750
135k
751
135k
  if (D.isPassed()) {
752
    // Optimization remarks are active only if the -Rpass flag has a regular
753
    // expression that matches the name of the pass name in \p D.
754
517
    if (CodeGenOpts.OptimizationRemarkPattern &&
755
393
        CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
756
110
      EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
757
134k
  } else if (D.isMissed()) {
758
    // Missed optimization remarks are active only if the -Rpass-missed
759
    // flag has a regular expression that matches the name of the pass
760
    // name in \p D.
761
45.8k
    if (CodeGenOpts.OptimizationRemarkMissedPattern &&
762
20
        CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
763
12
      EmitOptimizationMessage(
764
12
          D, diag::remark_fe_backend_optimization_remark_missed);
765
88.9k
  } else {
766
88.9k
    assert(D.isAnalysis() && "Unknown remark type");
767
88.9k
768
88.9k
    bool ShouldAlwaysPrint = false;
769
88.9k
    if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
770
18
      ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
771
88.9k
772
88.9k
    if (ShouldAlwaysPrint ||
773
88.9k
        (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
774
12
         CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
775
12
      EmitOptimizationMessage(
776
12
          D, diag::remark_fe_backend_optimization_remark_analysis);
777
88.9k
  }
778
135k
}
779
780
void BackendConsumer::OptimizationRemarkHandler(
781
1
    const llvm::OptimizationRemarkAnalysisFPCommute &D) {
782
  // Optimization analysis remarks are active if the pass name is set to
783
  // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
784
  // regular expression that matches the name of the pass name in \p D.
785
1
786
1
  if (D.shouldAlwaysPrint() ||
787
1
      (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
788
1
       CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
789
1
    EmitOptimizationMessage(
790
1
        D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
791
1
}
792
793
void BackendConsumer::OptimizationRemarkHandler(
794
1
    const llvm::OptimizationRemarkAnalysisAliasing &D) {
795
  // Optimization analysis remarks are active if the pass name is set to
796
  // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
797
  // regular expression that matches the name of the pass name in \p D.
798
1
799
1
  if (D.shouldAlwaysPrint() ||
800
1
      (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
801
1
       CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
802
1
    EmitOptimizationMessage(
803
1
        D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
804
1
}
805
806
void BackendConsumer::OptimizationFailureHandler(
807
4
    const llvm::DiagnosticInfoOptimizationFailure &D) {
808
4
  EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
809
4
}
810
811
/// This function is invoked when the backend needs
812
/// to report something to the user.
813
135k
void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
814
135k
  unsigned DiagID = diag::err_fe_inline_asm;
815
135k
  llvm::DiagnosticSeverity Severity = DI.getSeverity();
816
  // Get the diagnostic ID based.
817
135k
  switch (DI.getKind()) {
818
16
  case llvm::DK_InlineAsm:
819
16
    if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
820
16
      return;
821
0
    ComputeDiagID(Severity, inline_asm, DiagID);
822
0
    break;
823
18
  case llvm::DK_StackSize:
824
18
    if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
825
17
      return;
826
1
    ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
827
1
    break;
828
1
  case DK_Linker:
829
1
    assert(CurLinkModule);
830
    // FIXME: stop eating the warnings and notes.
831
1
    if (Severity != DS_Error)
832
0
      return;
833
1
    DiagID = diag::err_fe_cannot_link_module;
834
1
    break;
835
517
  case llvm::DK_OptimizationRemark:
836
    // Optimization remarks are always handled completely by this
837
    // handler. There is no generic way of emitting them.
838
517
    OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
839
517
    return;
840
46.0k
  case llvm::DK_OptimizationRemarkMissed:
841
    // Optimization remarks are always handled completely by this
842
    // handler. There is no generic way of emitting them.
843
46.0k
    OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
844
46.0k
    return;
845
18
  case llvm::DK_OptimizationRemarkAnalysis:
846
    // Optimization remarks are always handled completely by this
847
    // handler. There is no generic way of emitting them.
848
18
    OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
849
18
    return;
850
1
  case llvm::DK_OptimizationRemarkAnalysisFPCommute:
851
    // Optimization remarks are always handled completely by this
852
    // handler. There is no generic way of emitting them.
853
1
    OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
854
1
    return;
855
1
  case llvm::DK_OptimizationRemarkAnalysisAliasing:
856
    // Optimization remarks are always handled completely by this
857
    // handler. There is no generic way of emitting them.
858
1
    OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
859
1
    return;
860
0
  case llvm::DK_MachineOptimizationRemark:
861
    // Optimization remarks are always handled completely by this
862
    // handler. There is no generic way of emitting them.
863
0
    OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
864
0
    return;
865
16
  case llvm::DK_MachineOptimizationRemarkMissed:
866
    // Optimization remarks are always handled completely by this
867
    // handler. There is no generic way of emitting them.
868
16
    OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
869
16
    return;
870
88.9k
  case llvm::DK_MachineOptimizationRemarkAnalysis:
871
    // Optimization remarks are always handled completely by this
872
    // handler. There is no generic way of emitting them.
873
88.9k
    OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
874
88.9k
    return;
875
4
  case llvm::DK_OptimizationFailure:
876
    // Optimization failures are always handled completely by this
877
    // handler.
878
4
    OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
879
4
    return;
880
9
  case llvm::DK_Unsupported:
881
9
    UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
882
9
    return;
883
7
  case llvm::DK_MisExpect:
884
7
    MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));
885
7
    return;
886
4
  default:
887
    // Plugin IDs are not bound to any value as they are set dynamically.
888
4
    ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
889
4
    break;
890
6
  }
891
6
  std::string MsgStorage;
892
6
  {
893
6
    raw_string_ostream Stream(MsgStorage);
894
6
    DiagnosticPrinterRawOStream DP(Stream);
895
6
    DI.print(DP);
896
6
  }
897
6
898
6
  if (DiagID == diag::err_fe_cannot_link_module) {
899
1
    Diags.Report(diag::err_fe_cannot_link_module)
900
1
        << CurLinkModule->getModuleIdentifier() << MsgStorage;
901
1
    return;
902
1
  }
903
5
904
  // Report the backend message using the usual diagnostic mechanism.
905
5
  FullSourceLoc Loc;
906
5
  Diags.Report(Loc, DiagID).AddString(MsgStorage);
907
5
}
908
#undef ComputeDiagID
909
910
CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
911
    : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
912
17.4k
      OwnsVMContext(!_VMContext) {}
913
914
13.5k
CodeGenAction::~CodeGenAction() {
915
13.5k
  TheModule.reset();
916
13.5k
  if (OwnsVMContext)
917
13.5k
    delete VMContext;
918
13.5k
}
919
920
115
bool CodeGenAction::hasIRSupport() const { return true; }
921
922
17.3k
void CodeGenAction::EndSourceFileAction() {
923
  // If the consumer creation failed, do nothing.
924
17.3k
  if (!getCompilerInstance().hasASTConsumer())
925
115
    return;
926
17.2k
927
  // Steal the module from the consumer.
928
17.2k
  TheModule = BEConsumer->takeModule();
929
17.2k
}
930
931
0
std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
932
0
  return std::move(TheModule);
933
0
}
934
935
0
llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
936
0
  OwnsVMContext = false;
937
0
  return VMContext;
938
0
}
939
940
static std::unique_ptr<raw_pwrite_stream>
941
17.3k
GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
942
17.3k
  switch (Action) {
943
551
  case Backend_EmitAssembly:
944
551
    return CI.createDefaultOutputFile(false, InFile, "s");
945
12.7k
  case Backend_EmitLL:
946
12.7k
    return CI.createDefaultOutputFile(false, InFile, "ll");
947
560
  case Backend_EmitBC:
948
560
    return CI.createDefaultOutputFile(true, InFile, "bc");
949
232
  case Backend_EmitNothing:
950
232
    return nullptr;
951
4
  case Backend_EmitMCNull:
952
4
    return CI.createNullOutputFile();
953
3.32k
  case Backend_EmitObj:
954
3.32k
    return CI.createDefaultOutputFile(true, InFile, "o");
955
0
  }
956
0
957
0
  llvm_unreachable("Invalid action!");
958
0
}
959
960
std::unique_ptr<ASTConsumer>
961
17.2k
CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
962
17.2k
  BackendAction BA = static_cast<BackendAction>(Act);
963
17.2k
  std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
964
17.2k
  if (!OS)
965
17.2k
    OS = GetOutputStream(CI, InFile, BA);
966
17.2k
967
17.2k
  if (BA != Backend_EmitNothing && 
!OS17.0k
)
968
2
    return nullptr;
969
17.2k
970
  // Load bitcode modules to link with, if we need to.
971
17.2k
  if (LinkModules.empty())
972
17.2k
    for (const CodeGenOptions::BitcodeFileToLink &F :
973
14
         CI.getCodeGenOpts().LinkBitcodeFiles) {
974
14
      auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
975
14
      if (!BCBuf) {
976
1
        CI.getDiagnostics().Report(diag::err_cannot_open_file)
977
1
            << F.Filename << BCBuf.getError().message();
978
1
        LinkModules.clear();
979
1
        return nullptr;
980
1
      }
981
13
982
13
      Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
983
13
          getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
984
13
      if (!ModuleOrErr) {
985
0
        handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
986
0
          CI.getDiagnostics().Report(diag::err_cannot_open_file)
987
0
              << F.Filename << EIB.message();
988
0
        });
989
0
        LinkModules.clear();
990
0
        return nullptr;
991
0
      }
992
13
      LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
993
13
                             F.Internalize, F.LinkFlags});
994
13
    }
995
17.2k
996
17.2k
  CoverageSourceInfo *CoverageInfo = nullptr;
997
  // Add the preprocessor callback only when the coverage mapping is generated.
998
17.2k
  if (CI.getCodeGenOpts().CoverageMapping)
999
64
    CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
1000
64
        CI.getPreprocessor());
1001
17.2k
1002
17.2k
  std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
1003
17.2k
      BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1004
17.2k
      CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
1005
17.2k
      CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, std::string(InFile),
1006
17.2k
      std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
1007
17.2k
  BEConsumer = Result.get();
1008
17.2k
1009
  // Enable generating macro debug info only when debug info is not disabled and
1010
  // also macro debug info is enabled.
1011
17.2k
  if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1012
3.81k
      CI.getCodeGenOpts().MacroDebugInfo) {
1013
5
    std::unique_ptr<PPCallbacks> Callbacks =
1014
5
        std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
1015
5
                                            CI.getPreprocessor());
1016
5
    CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
1017
5
  }
1018
17.2k
1019
17.2k
  return std::move(Result);
1020
17.2k
}
1021
1022
static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
1023
                                         void *Context,
1024
1
                                         unsigned LocCookie) {
1025
1
  SM.print(nullptr, llvm::errs());
1026
1
1027
1
  auto Diags = static_cast<DiagnosticsEngine *>(Context);
1028
1
  unsigned DiagID;
1029
1
  switch (SM.getKind()) {
1030
1
  case llvm::SourceMgr::DK_Error:
1031
1
    DiagID = diag::err_fe_inline_asm;
1032
1
    break;
1033
0
  case llvm::SourceMgr::DK_Warning:
1034
0
    DiagID = diag::warn_fe_inline_asm;
1035
0
    break;
1036
0
  case llvm::SourceMgr::DK_Note:
1037
0
    DiagID = diag::note_fe_inline_asm;
1038
0
    break;
1039
0
  case llvm::SourceMgr::DK_Remark:
1040
0
    llvm_unreachable("remarks unexpected");
1041
1
  }
1042
1
1043
1
  Diags->Report(DiagID).AddString("cannot compile inline asm");
1044
1
}
1045
1046
std::unique_ptr<llvm::Module>
1047
115
CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1048
115
  CompilerInstance &CI = getCompilerInstance();
1049
115
  SourceManager &SM = CI.getSourceManager();
1050
115
1051
  // For ThinLTO backend invocations, ensure that the context
1052
  // merges types based on ODR identifiers. We also need to read
1053
  // the correct module out of a multi-module bitcode file.
1054
115
  if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1055
59
    VMContext->enableDebugTypeODRUniquing();
1056
59
1057
0
    auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1058
0
      unsigned DiagID =
1059
0
          CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1060
0
      handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1061
0
        CI.getDiagnostics().Report(DiagID) << EIB.message();
1062
0
      });
1063
0
      return {};
1064
0
    };
1065
59
1066
59
    Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1067
59
    if (!BMsOrErr)
1068
0
      return DiagErrors(BMsOrErr.takeError());
1069
59
    BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr);
1070
    // We have nothing to do if the file contains no ThinLTO module. This is
1071
    // possible if ThinLTO compilation was not able to split module. Content of
1072
    // the file was already processed by indexing and will be passed to the
1073
    // linker using merged object file.
1074
59
    if (!Bm) {
1075
1
      auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1076
1
      M->setTargetTriple(CI.getTargetOpts().Triple);
1077
1
      return M;
1078
1
    }
1079
58
    Expected<std::unique_ptr<llvm::Module>> MOrErr =
1080
58
        Bm->parseModule(*VMContext);
1081
58
    if (!MOrErr)
1082
0
      return DiagErrors(MOrErr.takeError());
1083
58
    return std::move(*MOrErr);
1084
58
  }
1085
56
1086
56
  llvm::SMDiagnostic Err;
1087
56
  if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1088
55
    return M;
1089
1
1090
  // Translate from the diagnostic info to the SourceManager location if
1091
  // available.
1092
  // TODO: Unify this with ConvertBackendLocation()
1093
1
  SourceLocation Loc;
1094
1
  if (Err.getLineNo() > 0) {
1095
1
    assert(Err.getColumnNo() >= 0);
1096
1
    Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1097
1
                                  Err.getLineNo(), Err.getColumnNo() + 1);
1098
1
  }
1099
1
1100
  // Strip off a leading diagnostic code if there is one.
1101
1
  StringRef Msg = Err.getMessage();
1102
1
  if (Msg.startswith("error: "))
1103
0
    Msg = Msg.substr(7);
1104
1
1105
1
  unsigned DiagID =
1106
1
      CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1107
1
1108
1
  CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1109
1
  return {};
1110
1
}
1111
1112
17.3k
void CodeGenAction::ExecuteAction() {
1113
  // If this is an IR file, we have to treat it specially.
1114
17.3k
  if (getCurrentFileKind().getLanguage() == Language::LLVM_IR) {
1115
115
    BackendAction BA = static_cast<BackendAction>(Act);
1116
115
    CompilerInstance &CI = getCompilerInstance();
1117
115
    auto &CodeGenOpts = CI.getCodeGenOpts();
1118
115
    auto &Diagnostics = CI.getDiagnostics();
1119
115
    std::unique_ptr<raw_pwrite_stream> OS =
1120
115
        GetOutputStream(CI, getCurrentFile(), BA);
1121
115
    if (BA != Backend_EmitNothing && !OS)
1122
0
      return;
1123
115
1124
115
    bool Invalid;
1125
115
    SourceManager &SM = CI.getSourceManager();
1126
115
    FileID FID = SM.getMainFileID();
1127
115
    const llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
1128
115
    if (Invalid)
1129
0
      return;
1130
115
1131
115
    TheModule = loadModule(*MainFile);
1132
115
    if (!TheModule)
1133
1
      return;
1134
114
1135
114
    const TargetOptions &TargetOpts = CI.getTargetOpts();
1136
114
    if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1137
35
      Diagnostics.Report(SourceLocation(),
1138
35
                         diag::warn_fe_override_module)
1139
35
          << TargetOpts.Triple;
1140
35
      TheModule->setTargetTriple(TargetOpts.Triple);
1141
35
    }
1142
114
1143
114
    EmbedBitcode(TheModule.get(), CodeGenOpts,
1144
114
                 MainFile->getMemBufferRef());
1145
114
1146
114
    LLVMContext &Ctx = TheModule->getContext();
1147
114
    Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
1148
114
                                      &Diagnostics);
1149
114
1150
    // Set clang diagnostic handler. To do this we need to create a fake
1151
    // BackendConsumer.
1152
114
    BackendConsumer Result(BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1153
114
                           CI.getPreprocessorOpts(), CI.getCodeGenOpts(),
1154
114
                           CI.getTargetOpts(), CI.getLangOpts(),
1155
114
                           CI.getFrontendOpts().ShowTimers,
1156
114
                           std::move(LinkModules), *VMContext, nullptr);
1157
    // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1158
    // true here because the valued names are needed for reading textual IR.
1159
114
    Ctx.setDiscardValueNames(false);
1160
114
    Ctx.setDiagnosticHandler(
1161
114
        std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1162
114
1163
114
    Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
1164
114
        setupLLVMOptimizationRemarks(
1165
114
            Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1166
114
            CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1167
114
            CodeGenOpts.DiagnosticsHotnessThreshold);
1168
114
1169
114
    if (Error E = OptRecordFileOrErr.takeError()) {
1170
0
      reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1171
0
      return;
1172
0
    }
1173
114
    std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1174
114
        std::move(*OptRecordFileOrErr);
1175
114
1176
114
    EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts,
1177
114
                      TargetOpts, CI.getLangOpts(),
1178
114
                      CI.getTarget().getDataLayout(), TheModule.get(), BA,
1179
114
                      std::move(OS));
1180
114
1181
114
    if (OptRecordFile)
1182
2
      OptRecordFile->keep();
1183
114
    return;
1184
114
  }
1185
17.2k
1186
  // Otherwise follow the normal AST path.
1187
17.2k
  this->ASTFrontendAction::ExecuteAction();
1188
17.2k
}
1189
1190
//
1191
1192
0
void EmitAssemblyAction::anchor() { }
1193
EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1194
560
  : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1195
1196
0
void EmitBCAction::anchor() { }
1197
EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1198
563
  : CodeGenAction(Backend_EmitBC, _VMContext) {}
1199
1200
0
void EmitLLVMAction::anchor() { }
1201
EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1202
12.7k
  : CodeGenAction(Backend_EmitLL, _VMContext) {}
1203
1204
0
void EmitLLVMOnlyAction::anchor() { }
1205
EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1206
232
  : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1207
1208
0
void EmitCodeGenOnlyAction::anchor() { }
1209
EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1210
3
  : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1211
1212
0
void EmitObjAction::anchor() { }
1213
EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1214
3.33k
  : CodeGenAction(Backend_EmitObj, _VMContext) {}