Coverage Report

Created: 2020-02-25 14:32

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