clang  16.0.0git
CodeGenAction.cpp
Go to the documentation of this file.
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 
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"
21 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "llvm/ADT/Hashing.h"
29 #include "llvm/Bitcode/BitcodeReader.h"
30 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
31 #include "llvm/Demangle/Demangle.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/DiagnosticPrinter.h"
35 #include "llvm/IR/GlobalValue.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/LLVMRemarkStreamer.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IRReader/IRReader.h"
40 #include "llvm/LTO/LTOBackend.h"
41 #include "llvm/Linker/Linker.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/SourceMgr.h"
45 #include "llvm/Support/TimeProfiler.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Support/YAMLTraits.h"
49 #include "llvm/Transforms/IPO/Internalize.h"
50 
51 #include <memory>
52 using namespace clang;
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "codegenaction"
56 
57 namespace clang {
58  class BackendConsumer;
60  public:
62  : CodeGenOpts(CGOpts), BackendCon(BCon) {}
63 
64  bool handleDiagnostics(const DiagnosticInfo &DI) override;
65 
66  bool isAnalysisRemarkEnabled(StringRef PassName) const override {
67  return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
68  }
69  bool isMissedOptRemarkEnabled(StringRef PassName) const override {
70  return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
71  }
72  bool isPassedOptRemarkEnabled(StringRef PassName) const override {
73  return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
74  }
75 
76  bool isAnyRemarkEnabled() const override {
77  return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
78  CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
79  CodeGenOpts.OptimizationRemark.hasValidPattern();
80  }
81 
82  private:
83  const CodeGenOptions &CodeGenOpts;
84  BackendConsumer *BackendCon;
85  };
86 
87  static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
88  const CodeGenOptions CodeGenOpts) {
89  handleAllErrors(
90  std::move(E),
91  [&](const LLVMRemarkSetupFileError &E) {
92  Diags.Report(diag::err_cannot_open_file)
93  << CodeGenOpts.OptRecordFile << E.message();
94  },
95  [&](const LLVMRemarkSetupPatternError &E) {
96  Diags.Report(diag::err_drv_optimization_remark_pattern)
97  << E.message() << CodeGenOpts.OptRecordPasses;
98  },
99  [&](const LLVMRemarkSetupFormatError &E) {
100  Diags.Report(diag::err_drv_optimization_remark_format)
101  << CodeGenOpts.OptRecordFormat;
102  });
103  }
104 
105  class BackendConsumer : public ASTConsumer {
106  using LinkModule = CodeGenAction::LinkModule;
107 
108  virtual void anchor();
109  DiagnosticsEngine &Diags;
110  BackendAction Action;
111  const HeaderSearchOptions &HeaderSearchOpts;
112  const CodeGenOptions &CodeGenOpts;
113  const TargetOptions &TargetOpts;
114  const LangOptions &LangOpts;
115  std::unique_ptr<raw_pwrite_stream> AsmOutStream;
116  ASTContext *Context;
117 
118  Timer LLVMIRGeneration;
119  unsigned LLVMIRGenerationRefCount;
120 
121  /// True if we've finished generating IR. This prevents us from generating
122  /// additional LLVM IR after emitting output in HandleTranslationUnit. This
123  /// can happen when Clang plugins trigger additional AST deserialization.
124  bool IRGenFinished = false;
125 
126  bool TimerIsEnabled = false;
127 
128  std::unique_ptr<CodeGenerator> Gen;
129 
130  SmallVector<LinkModule, 4> LinkModules;
131 
132  // A map from mangled names to their function's source location, used for
133  // backend diagnostics as the Clang AST may be unavailable. We actually use
134  // the mangled name's hash as the key because mangled names can be very
135  // long and take up lots of space. Using a hash can cause name collision,
136  // but that is rare and the consequences are pointing to a wrong source
137  // location which is not severe. This is a vector instead of an actual map
138  // because we optimize for time building this map rather than time
139  // retrieving an entry, as backend diagnostics are uncommon.
140  std::vector<std::pair<llvm::hash_code, FullSourceLoc>>
141  ManglingFullSourceLocs;
142 
143  // This is here so that the diagnostic printer knows the module a diagnostic
144  // refers to.
145  llvm::Module *CurLinkModule = nullptr;
146 
147  public:
150  const HeaderSearchOptions &HeaderSearchOpts,
151  const PreprocessorOptions &PPOpts,
152  const CodeGenOptions &CodeGenOpts,
153  const TargetOptions &TargetOpts,
154  const LangOptions &LangOpts, const std::string &InFile,
155  SmallVector<LinkModule, 4> LinkModules,
156  std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
157  CoverageSourceInfo *CoverageInfo = nullptr)
158  : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
159  CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
160  AsmOutStream(std::move(OS)), Context(nullptr),
161  LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
162  LLVMIRGenerationRefCount(0),
163  Gen(CreateLLVMCodeGen(Diags, InFile, std::move(FS), HeaderSearchOpts,
164  PPOpts, CodeGenOpts, C, CoverageInfo)),
165  LinkModules(std::move(LinkModules)) {
166  TimerIsEnabled = CodeGenOpts.TimePasses;
167  llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
168  llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
169  }
170 
171  // This constructor is used in installing an empty BackendConsumer
172  // to use the clang diagnostic handler for IR input files. It avoids
173  // initializing the OS field.
176  const HeaderSearchOptions &HeaderSearchOpts,
177  const PreprocessorOptions &PPOpts,
178  const CodeGenOptions &CodeGenOpts,
179  const TargetOptions &TargetOpts,
180  const LangOptions &LangOpts, llvm::Module *Module,
181  SmallVector<LinkModule, 4> LinkModules, LLVMContext &C,
182  CoverageSourceInfo *CoverageInfo = nullptr)
183  : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
184  CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
185  Context(nullptr),
186  LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
187  LLVMIRGenerationRefCount(0),
188  Gen(CreateLLVMCodeGen(Diags, "", std::move(FS), HeaderSearchOpts,
189  PPOpts, CodeGenOpts, C, CoverageInfo)),
190  LinkModules(std::move(LinkModules)), CurLinkModule(Module) {
191  TimerIsEnabled = CodeGenOpts.TimePasses;
192  llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
193  llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
194  }
195  llvm::Module *getModule() const { return Gen->GetModule(); }
196  std::unique_ptr<llvm::Module> takeModule() {
197  return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
198  }
199 
200  CodeGenerator *getCodeGenerator() { return Gen.get(); }
201 
203  Gen->HandleCXXStaticMemberVarInstantiation(VD);
204  }
205 
206  void Initialize(ASTContext &Ctx) override {
207  assert(!Context && "initialized multiple times");
208 
209  Context = &Ctx;
210 
211  if (TimerIsEnabled)
212  LLVMIRGeneration.startTimer();
213 
214  Gen->Initialize(Ctx);
215 
216  if (TimerIsEnabled)
217  LLVMIRGeneration.stopTimer();
218  }
219 
220  bool HandleTopLevelDecl(DeclGroupRef D) override {
221  PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
222  Context->getSourceManager(),
223  "LLVM IR generation of declaration");
224 
225  // Recurse.
226  if (TimerIsEnabled) {
227  LLVMIRGenerationRefCount += 1;
228  if (LLVMIRGenerationRefCount == 1)
229  LLVMIRGeneration.startTimer();
230  }
231 
232  Gen->HandleTopLevelDecl(D);
233 
234  if (TimerIsEnabled) {
235  LLVMIRGenerationRefCount -= 1;
236  if (LLVMIRGenerationRefCount == 0)
237  LLVMIRGeneration.stopTimer();
238  }
239 
240  return true;
241  }
242 
244  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
245  Context->getSourceManager(),
246  "LLVM IR generation of inline function");
247  if (TimerIsEnabled)
248  LLVMIRGeneration.startTimer();
249 
250  Gen->HandleInlineFunctionDefinition(D);
251 
252  if (TimerIsEnabled)
253  LLVMIRGeneration.stopTimer();
254  }
255 
257  // Ignore interesting decls from the AST reader after IRGen is finished.
258  if (!IRGenFinished)
259  HandleTopLevelDecl(D);
260  }
261 
262  // Links each entry in LinkModules into our module. Returns true on error.
263  bool LinkInModules() {
264  for (auto &LM : LinkModules) {
265  if (LM.PropagateAttrs)
266  for (Function &F : *LM.Module) {
267  // Skip intrinsics. Keep consistent with how intrinsics are created
268  // in LLVM IR.
269  if (F.isIntrinsic())
270  continue;
271  Gen->CGM().addDefaultFunctionDefinitionAttributes(F);
272  }
273 
274  CurLinkModule = LM.Module.get();
275 
276  bool Err;
277  if (LM.Internalize) {
278  Err = Linker::linkModules(
279  *getModule(), std::move(LM.Module), LM.LinkFlags,
280  [](llvm::Module &M, const llvm::StringSet<> &GVS) {
281  internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
282  return !GV.hasName() || (GVS.count(GV.getName()) == 0);
283  });
284  });
285  } else {
286  Err = Linker::linkModules(*getModule(), std::move(LM.Module),
287  LM.LinkFlags);
288  }
289 
290  if (Err)
291  return true;
292  }
293  return false; // success
294  }
295 
296  void HandleTranslationUnit(ASTContext &C) override {
297  {
298  llvm::TimeTraceScope TimeScope("Frontend");
299  PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
300  if (TimerIsEnabled) {
301  LLVMIRGenerationRefCount += 1;
302  if (LLVMIRGenerationRefCount == 1)
303  LLVMIRGeneration.startTimer();
304  }
305 
306  Gen->HandleTranslationUnit(C);
307 
308  if (TimerIsEnabled) {
309  LLVMIRGenerationRefCount -= 1;
310  if (LLVMIRGenerationRefCount == 0)
311  LLVMIRGeneration.stopTimer();
312  }
313 
314  IRGenFinished = true;
315  }
316 
317  // Silently ignore if we weren't initialized for some reason.
318  if (!getModule())
319  return;
320 
321  LLVMContext &Ctx = getModule()->getContext();
322  std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
323  Ctx.getDiagnosticHandler();
324  Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
325  CodeGenOpts, this));
326 
328  setupLLVMOptimizationRemarks(
329  Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
330  CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
331  CodeGenOpts.DiagnosticsHotnessThreshold);
332 
333  if (Error E = OptRecordFileOrErr.takeError()) {
334  reportOptRecordError(std::move(E), Diags, CodeGenOpts);
335  return;
336  }
337 
338  std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
339  std::move(*OptRecordFileOrErr);
340 
341  if (OptRecordFile &&
342  CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
343  Ctx.setDiagnosticsHotnessRequested(true);
344 
345  if (CodeGenOpts.MisExpect) {
346  Ctx.setMisExpectWarningRequested(true);
347  }
348 
349  if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
350  Ctx.setDiagnosticsMisExpectTolerance(
351  CodeGenOpts.DiagnosticsMisExpectTolerance);
352  }
353 
354  // Link each LinkModule into our module.
355  if (LinkInModules())
356  return;
357 
358  for (auto &F : getModule()->functions()) {
359  if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
360  auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
361  // TODO: use a fast content hash when available.
362  auto NameHash = llvm::hash_value(F.getName());
363  ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
364  }
365  }
366 
367  if (CodeGenOpts.ClearASTBeforeBackend) {
368  LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
369  // Access to the AST is no longer available after this.
370  // Other things that the ASTContext manages are still available, e.g.
371  // the SourceManager. It'd be nice if we could separate out all the
372  // things in ASTContext used after this point and null out the
373  // ASTContext, but too many various parts of the ASTContext are still
374  // used in various parts.
375  C.cleanup();
376  C.getAllocator().Reset();
377  }
378 
379  EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
380 
381  EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
382  LangOpts, C.getTargetInfo().getDataLayoutString(),
383  getModule(), Action, std::move(AsmOutStream));
384 
385  Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
386 
387  if (OptRecordFile)
388  OptRecordFile->keep();
389  }
390 
391  void HandleTagDeclDefinition(TagDecl *D) override {
392  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
393  Context->getSourceManager(),
394  "LLVM IR generation of declaration");
395  Gen->HandleTagDeclDefinition(D);
396  }
397 
398  void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
399  Gen->HandleTagDeclRequiredDefinition(D);
400  }
401 
403  Gen->CompleteTentativeDefinition(D);
404  }
405 
407  Gen->CompleteExternalDeclaration(D);
408  }
409 
411  Gen->AssignInheritanceModel(RD);
412  }
413 
414  void HandleVTable(CXXRecordDecl *RD) override {
415  Gen->HandleVTable(RD);
416  }
417 
418  /// Get the best possible source location to represent a diagnostic that
419  /// may have associated debug info.
420  const FullSourceLoc
421  getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
422  bool &BadDebugInfo, StringRef &Filename,
423  unsigned &Line, unsigned &Column) const;
424 
425  Optional<FullSourceLoc> getFunctionSourceLocation(const Function &F) const;
426 
427  void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
428  /// Specialized handler for InlineAsm diagnostic.
429  /// \return True if the diagnostic has been successfully reported, false
430  /// otherwise.
431  bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
432  /// Specialized handler for diagnostics reported using SMDiagnostic.
433  void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D);
434  /// Specialized handler for StackSize diagnostic.
435  /// \return True if the diagnostic has been successfully reported, false
436  /// otherwise.
437  bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
438  /// Specialized handler for ResourceLimit diagnostic.
439  /// \return True if the diagnostic has been successfully reported, false
440  /// otherwise.
441  bool ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit &D);
442 
443  /// Specialized handler for unsupported backend feature diagnostic.
444  void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
445  /// Specialized handlers for optimization remarks.
446  /// Note that these handlers only accept remarks and they always handle
447  /// them.
448  void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
449  unsigned DiagID);
450  void
451  OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
452  void OptimizationRemarkHandler(
453  const llvm::OptimizationRemarkAnalysisFPCommute &D);
454  void OptimizationRemarkHandler(
455  const llvm::OptimizationRemarkAnalysisAliasing &D);
456  void OptimizationFailureHandler(
457  const llvm::DiagnosticInfoOptimizationFailure &D);
458  void DontCallDiagHandler(const DiagnosticInfoDontCall &D);
459  /// Specialized handler for misexpect warnings.
460  /// Note that misexpect remarks are emitted through ORE
461  void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D);
462  };
463 
464  void BackendConsumer::anchor() {}
465 }
466 
467 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
468  BackendCon->DiagnosticHandlerImpl(DI);
469  return true;
470 }
471 
472 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
473 /// buffer to be a valid FullSourceLoc.
474 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
475  SourceManager &CSM) {
476  // Get both the clang and llvm source managers. The location is relative to
477  // a memory buffer that the LLVM Source Manager is handling, we need to add
478  // a copy to the Clang source manager.
479  const llvm::SourceMgr &LSM = *D.getSourceMgr();
480 
481  // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
482  // already owns its one and clang::SourceManager wants to own its one.
483  const MemoryBuffer *LBuf =
484  LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
485 
486  // Create the copy and transfer ownership to clang::SourceManager.
487  // TODO: Avoid copying files into memory.
488  std::unique_ptr<llvm::MemoryBuffer> CBuf =
489  llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
490  LBuf->getBufferIdentifier());
491  // FIXME: Keep a file ID map instead of creating new IDs for each location.
492  FileID FID = CSM.createFileID(std::move(CBuf));
493 
494  // Translate the offset into the file.
495  unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
496  SourceLocation NewLoc =
498  return FullSourceLoc(NewLoc, CSM);
499 }
500 
501 #define ComputeDiagID(Severity, GroupName, DiagID) \
502  do { \
503  switch (Severity) { \
504  case llvm::DS_Error: \
505  DiagID = diag::err_fe_##GroupName; \
506  break; \
507  case llvm::DS_Warning: \
508  DiagID = diag::warn_fe_##GroupName; \
509  break; \
510  case llvm::DS_Remark: \
511  llvm_unreachable("'remark' severity not expected"); \
512  break; \
513  case llvm::DS_Note: \
514  DiagID = diag::note_fe_##GroupName; \
515  break; \
516  } \
517  } while (false)
518 
519 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
520  do { \
521  switch (Severity) { \
522  case llvm::DS_Error: \
523  DiagID = diag::err_fe_##GroupName; \
524  break; \
525  case llvm::DS_Warning: \
526  DiagID = diag::warn_fe_##GroupName; \
527  break; \
528  case llvm::DS_Remark: \
529  DiagID = diag::remark_fe_##GroupName; \
530  break; \
531  case llvm::DS_Note: \
532  DiagID = diag::note_fe_##GroupName; \
533  break; \
534  } \
535  } while (false)
536 
537 void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
538  const llvm::SMDiagnostic &D = DI.getSMDiag();
539 
540  unsigned DiagID;
541  if (DI.isInlineAsmDiag())
542  ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
543  else
544  ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
545 
546  // This is for the empty BackendConsumer that uses the clang diagnostic
547  // handler for IR input files.
548  if (!Context) {
549  D.print(nullptr, llvm::errs());
550  Diags.Report(DiagID).AddString("cannot compile inline asm");
551  return;
552  }
553 
554  // There are a couple of different kinds of errors we could get here.
555  // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
556 
557  // Strip "error: " off the start of the message string.
558  StringRef Message = D.getMessage();
559  (void)Message.consume_front("error: ");
560 
561  // If the SMDiagnostic has an inline asm source location, translate it.
562  FullSourceLoc Loc;
563  if (D.getLoc() != SMLoc())
564  Loc = ConvertBackendLocation(D, Context->getSourceManager());
565 
566  // If this problem has clang-level source location information, report the
567  // issue in the source with a note showing the instantiated
568  // code.
569  if (DI.isInlineAsmDiag()) {
570  SourceLocation LocCookie =
571  SourceLocation::getFromRawEncoding(DI.getLocCookie());
572  if (LocCookie.isValid()) {
573  Diags.Report(LocCookie, DiagID).AddString(Message);
574 
575  if (D.getLoc().isValid()) {
576  DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
577  // Convert the SMDiagnostic ranges into SourceRange and attach them
578  // to the diagnostic.
579  for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
580  unsigned Column = D.getColumnNo();
581  B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
582  Loc.getLocWithOffset(Range.second - Column));
583  }
584  }
585  return;
586  }
587  }
588 
589  // Otherwise, report the backend issue as occurring in the generated .s file.
590  // If Loc is invalid, we still need to report the issue, it just gets no
591  // location info.
592  Diags.Report(Loc, DiagID).AddString(Message);
593 }
594 
595 bool
596 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
597  unsigned DiagID;
598  ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
599  std::string Message = D.getMsgStr().str();
600 
601  // If this problem has clang-level source location information, report the
602  // issue as being a problem in the source with a note showing the instantiated
603  // code.
604  SourceLocation LocCookie =
605  SourceLocation::getFromRawEncoding(D.getLocCookie());
606  if (LocCookie.isValid())
607  Diags.Report(LocCookie, DiagID).AddString(Message);
608  else {
609  // Otherwise, report the backend diagnostic as occurring in the generated
610  // .s file.
611  // If Loc is invalid, we still need to report the diagnostic, it just gets
612  // no location info.
613  FullSourceLoc Loc;
614  Diags.Report(Loc, DiagID).AddString(Message);
615  }
616  // We handled all the possible severities.
617  return true;
618 }
619 
620 bool
621 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
622  if (D.getSeverity() != llvm::DS_Warning)
623  // For now, the only support we have for StackSize diagnostic is warning.
624  // We do not know how to format other severities.
625  return false;
626 
627  auto Loc = getFunctionSourceLocation(D.getFunction());
628  if (!Loc)
629  return false;
630 
631  Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
632  << D.getStackSize()
633  << D.getStackLimit()
634  << llvm::demangle(D.getFunction().getName().str());
635  return true;
636 }
637 
639  const llvm::DiagnosticInfoResourceLimit &D) {
640  auto Loc = getFunctionSourceLocation(D.getFunction());
641  if (!Loc)
642  return false;
643  unsigned DiagID = diag::err_fe_backend_resource_limit;
644  ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
645 
646  Diags.Report(*Loc, DiagID)
647  << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
648  << llvm::demangle(D.getFunction().getName().str());
649  return true;
650 }
651 
653  const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
654  StringRef &Filename, unsigned &Line, unsigned &Column) const {
655  SourceManager &SourceMgr = Context->getSourceManager();
656  FileManager &FileMgr = SourceMgr.getFileManager();
657  SourceLocation DILoc;
658 
659  if (D.isLocationAvailable()) {
660  D.getLocation(Filename, Line, Column);
661  if (Line > 0) {
662  auto FE = FileMgr.getFile(Filename);
663  if (!FE)
664  FE = FileMgr.getFile(D.getAbsolutePath());
665  if (FE) {
666  // If -gcolumn-info was not used, Column will be 0. This upsets the
667  // source manager, so pass 1 if Column is not set.
668  DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
669  }
670  }
671  BadDebugInfo = DILoc.isInvalid();
672  }
673 
674  // If a location isn't available, try to approximate it using the associated
675  // function definition. We use the definition's right brace to differentiate
676  // from diagnostics that genuinely relate to the function itself.
677  FullSourceLoc Loc(DILoc, SourceMgr);
678  if (Loc.isInvalid()) {
679  if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))
680  Loc = *MaybeLoc;
681  }
682 
683  if (DILoc.isInvalid() && D.isLocationAvailable())
684  // If we were not able to translate the file:line:col information
685  // back to a SourceLocation, at least emit a note stating that
686  // we could not translate this location. This can happen in the
687  // case of #line directives.
688  Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
689  << Filename << Line << Column;
690 
691  return Loc;
692 }
693 
696  auto Hash = llvm::hash_value(F.getName());
697  for (const auto &Pair : ManglingFullSourceLocs) {
698  if (Pair.first == Hash)
699  return Pair.second;
700  }
701  return None;
702 }
703 
705  const llvm::DiagnosticInfoUnsupported &D) {
706  // We only support warnings or errors.
707  assert(D.getSeverity() == llvm::DS_Error ||
708  D.getSeverity() == llvm::DS_Warning);
709 
710  StringRef Filename;
711  unsigned Line, Column;
712  bool BadDebugInfo = false;
713  FullSourceLoc Loc;
714  std::string Msg;
715  raw_string_ostream MsgStream(Msg);
716 
717  // Context will be nullptr for IR input files, we will construct the diag
718  // message from llvm::DiagnosticInfoUnsupported.
719  if (Context != nullptr) {
720  Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
721  MsgStream << D.getMessage();
722  } else {
723  DiagnosticPrinterRawOStream DP(MsgStream);
724  D.print(DP);
725  }
726 
727  auto DiagType = D.getSeverity() == llvm::DS_Error
728  ? diag::err_fe_backend_unsupported
729  : diag::warn_fe_backend_unsupported;
730  Diags.Report(Loc, DiagType) << MsgStream.str();
731 
732  if (BadDebugInfo)
733  // If we were not able to translate the file:line:col information
734  // back to a SourceLocation, at least emit a note stating that
735  // we could not translate this location. This can happen in the
736  // case of #line directives.
737  Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
738  << Filename << Line << Column;
739 }
740 
742  const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
743  // We only support warnings and remarks.
744  assert(D.getSeverity() == llvm::DS_Remark ||
745  D.getSeverity() == llvm::DS_Warning);
746 
747  StringRef Filename;
748  unsigned Line, Column;
749  bool BadDebugInfo = false;
750  FullSourceLoc Loc;
751  std::string Msg;
752  raw_string_ostream MsgStream(Msg);
753 
754  // Context will be nullptr for IR input files, we will construct the remark
755  // message from llvm::DiagnosticInfoOptimizationBase.
756  if (Context != nullptr) {
757  Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
758  MsgStream << D.getMsg();
759  } else {
760  DiagnosticPrinterRawOStream DP(MsgStream);
761  D.print(DP);
762  }
763 
764  if (D.getHotness())
765  MsgStream << " (hotness: " << *D.getHotness() << ")";
766 
767  Diags.Report(Loc, DiagID)
768  << AddFlagValue(D.getPassName())
769  << MsgStream.str();
770 
771  if (BadDebugInfo)
772  // If we were not able to translate the file:line:col information
773  // back to a SourceLocation, at least emit a note stating that
774  // we could not translate this location. This can happen in the
775  // case of #line directives.
776  Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
777  << Filename << Line << Column;
778 }
779 
781  const llvm::DiagnosticInfoOptimizationBase &D) {
782  // Without hotness information, don't show noisy remarks.
783  if (D.isVerbose() && !D.getHotness())
784  return;
785 
786  if (D.isPassed()) {
787  // Optimization remarks are active only if the -Rpass flag has a regular
788  // expression that matches the name of the pass name in \p D.
789  if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
790  EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
791  } else if (D.isMissed()) {
792  // Missed optimization remarks are active only if the -Rpass-missed
793  // flag has a regular expression that matches the name of the pass
794  // name in \p D.
795  if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
797  D, diag::remark_fe_backend_optimization_remark_missed);
798  } else {
799  assert(D.isAnalysis() && "Unknown remark type");
800 
801  bool ShouldAlwaysPrint = false;
802  if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
803  ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
804 
805  if (ShouldAlwaysPrint ||
806  CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
808  D, diag::remark_fe_backend_optimization_remark_analysis);
809  }
810 }
811 
813  const llvm::OptimizationRemarkAnalysisFPCommute &D) {
814  // Optimization analysis remarks are active if the pass name is set to
815  // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
816  // regular expression that matches the name of the pass name in \p D.
817 
818  if (D.shouldAlwaysPrint() ||
819  CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
821  D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
822 }
823 
825  const llvm::OptimizationRemarkAnalysisAliasing &D) {
826  // Optimization analysis remarks are active if the pass name is set to
827  // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
828  // regular expression that matches the name of the pass name in \p D.
829 
830  if (D.shouldAlwaysPrint() ||
831  CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
833  D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
834 }
835 
837  const llvm::DiagnosticInfoOptimizationFailure &D) {
838  EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
839 }
840 
841 void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
842  SourceLocation LocCookie =
843  SourceLocation::getFromRawEncoding(D.getLocCookie());
844 
845  // FIXME: we can't yet diagnose indirect calls. When/if we can, we
846  // should instead assert that LocCookie.isValid().
847  if (!LocCookie.isValid())
848  return;
849 
850  Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
851  ? diag::err_fe_backend_error_attr
852  : diag::warn_fe_backend_warning_attr)
853  << llvm::demangle(D.getFunctionName().str()) << D.getNote();
854 }
855 
857  const llvm::DiagnosticInfoMisExpect &D) {
858  StringRef Filename;
859  unsigned Line, Column;
860  bool BadDebugInfo = false;
861  FullSourceLoc Loc =
862  getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
863 
864  Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
865 
866  if (BadDebugInfo)
867  // If we were not able to translate the file:line:col information
868  // back to a SourceLocation, at least emit a note stating that
869  // we could not translate this location. This can happen in the
870  // case of #line directives.
871  Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
872  << Filename << Line << Column;
873 }
874 
875 /// This function is invoked when the backend needs
876 /// to report something to the user.
877 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
878  unsigned DiagID = diag::err_fe_inline_asm;
879  llvm::DiagnosticSeverity Severity = DI.getSeverity();
880  // Get the diagnostic ID based.
881  switch (DI.getKind()) {
882  case llvm::DK_InlineAsm:
883  if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
884  return;
885  ComputeDiagID(Severity, inline_asm, DiagID);
886  break;
887  case llvm::DK_SrcMgr:
888  SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI));
889  return;
890  case llvm::DK_StackSize:
891  if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
892  return;
893  ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
894  break;
895  case llvm::DK_ResourceLimit:
896  if (ResourceLimitDiagHandler(cast<DiagnosticInfoResourceLimit>(DI)))
897  return;
898  ComputeDiagID(Severity, backend_resource_limit, DiagID);
899  break;
900  case DK_Linker:
901  ComputeDiagID(Severity, linking_module, DiagID);
902  break;
903  case llvm::DK_OptimizationRemark:
904  // Optimization remarks are always handled completely by this
905  // handler. There is no generic way of emitting them.
906  OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
907  return;
908  case llvm::DK_OptimizationRemarkMissed:
909  // Optimization remarks are always handled completely by this
910  // handler. There is no generic way of emitting them.
911  OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
912  return;
913  case llvm::DK_OptimizationRemarkAnalysis:
914  // Optimization remarks are always handled completely by this
915  // handler. There is no generic way of emitting them.
916  OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
917  return;
918  case llvm::DK_OptimizationRemarkAnalysisFPCommute:
919  // Optimization remarks are always handled completely by this
920  // handler. There is no generic way of emitting them.
921  OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
922  return;
923  case llvm::DK_OptimizationRemarkAnalysisAliasing:
924  // Optimization remarks are always handled completely by this
925  // handler. There is no generic way of emitting them.
926  OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
927  return;
928  case llvm::DK_MachineOptimizationRemark:
929  // Optimization remarks are always handled completely by this
930  // handler. There is no generic way of emitting them.
931  OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
932  return;
933  case llvm::DK_MachineOptimizationRemarkMissed:
934  // Optimization remarks are always handled completely by this
935  // handler. There is no generic way of emitting them.
936  OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
937  return;
938  case llvm::DK_MachineOptimizationRemarkAnalysis:
939  // Optimization remarks are always handled completely by this
940  // handler. There is no generic way of emitting them.
941  OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
942  return;
943  case llvm::DK_OptimizationFailure:
944  // Optimization failures are always handled completely by this
945  // handler.
946  OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
947  return;
948  case llvm::DK_Unsupported:
949  UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
950  return;
951  case llvm::DK_DontCall:
952  DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI));
953  return;
954  case llvm::DK_MisExpect:
955  MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));
956  return;
957  default:
958  // Plugin IDs are not bound to any value as they are set dynamically.
959  ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
960  break;
961  }
962  std::string MsgStorage;
963  {
964  raw_string_ostream Stream(MsgStorage);
965  DiagnosticPrinterRawOStream DP(Stream);
966  DI.print(DP);
967  }
968 
969  if (DI.getKind() == DK_Linker) {
970  assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
971  Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
972  return;
973  }
974 
975  // Report the backend message using the usual diagnostic mechanism.
976  FullSourceLoc Loc;
977  Diags.Report(Loc, DiagID).AddString(MsgStorage);
978 }
979 #undef ComputeDiagID
980 
981 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
982  : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
983  OwnsVMContext(!_VMContext) {}
984 
986  TheModule.reset();
987  if (OwnsVMContext)
988  delete VMContext;
989 }
990 
991 bool CodeGenAction::hasIRSupport() const { return true; }
992 
994  // If the consumer creation failed, do nothing.
995  if (!getCompilerInstance().hasASTConsumer())
996  return;
997 
998  // Steal the module from the consumer.
999  TheModule = BEConsumer->takeModule();
1000 }
1001 
1002 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
1003  return std::move(TheModule);
1004 }
1005 
1006 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
1007  OwnsVMContext = false;
1008  return VMContext;
1009 }
1010 
1012  return BEConsumer->getCodeGenerator();
1013 }
1014 
1015 static std::unique_ptr<raw_pwrite_stream>
1016 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
1017  switch (Action) {
1018  case Backend_EmitAssembly:
1019  return CI.createDefaultOutputFile(false, InFile, "s");
1020  case Backend_EmitLL:
1021  return CI.createDefaultOutputFile(false, InFile, "ll");
1022  case Backend_EmitBC:
1023  return CI.createDefaultOutputFile(true, InFile, "bc");
1024  case Backend_EmitNothing:
1025  return nullptr;
1026  case Backend_EmitMCNull:
1027  return CI.createNullOutputFile();
1028  case Backend_EmitObj:
1029  return CI.createDefaultOutputFile(true, InFile, "o");
1030  }
1031 
1032  llvm_unreachable("Invalid action!");
1033 }
1034 
1035 std::unique_ptr<ASTConsumer>
1037  BackendAction BA = static_cast<BackendAction>(Act);
1038  std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
1039  if (!OS)
1040  OS = GetOutputStream(CI, InFile, BA);
1041 
1042  if (BA != Backend_EmitNothing && !OS)
1043  return nullptr;
1044 
1045  VMContext->setOpaquePointers(CI.getCodeGenOpts().OpaquePointers);
1046 
1047  // Load bitcode modules to link with, if we need to.
1048  if (LinkModules.empty())
1049  for (const CodeGenOptions::BitcodeFileToLink &F :
1051  auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
1052  if (!BCBuf) {
1053  CI.getDiagnostics().Report(diag::err_cannot_open_file)
1054  << F.Filename << BCBuf.getError().message();
1055  LinkModules.clear();
1056  return nullptr;
1057  }
1058 
1060  getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
1061  if (!ModuleOrErr) {
1062  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1063  CI.getDiagnostics().Report(diag::err_cannot_open_file)
1064  << F.Filename << EIB.message();
1065  });
1066  LinkModules.clear();
1067  return nullptr;
1068  }
1069  LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
1070  F.Internalize, F.LinkFlags});
1071  }
1072 
1073  CoverageSourceInfo *CoverageInfo = nullptr;
1074  // Add the preprocessor callback only when the coverage mapping is generated.
1075  if (CI.getCodeGenOpts().CoverageMapping)
1077  CI.getPreprocessor());
1078 
1079  std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
1080  BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(),
1082  CI.getTargetOpts(), CI.getLangOpts(), std::string(InFile),
1083  std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
1084  BEConsumer = Result.get();
1085 
1086  // Enable generating macro debug info only when debug info is not disabled and
1087  // also macro debug info is enabled.
1088  if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1089  CI.getCodeGenOpts().MacroDebugInfo) {
1090  std::unique_ptr<PPCallbacks> Callbacks =
1091  std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
1092  CI.getPreprocessor());
1093  CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
1094  }
1095 
1096  return std::move(Result);
1097 }
1098 
1099 std::unique_ptr<llvm::Module>
1100 CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1103 
1104  VMContext->setOpaquePointers(CI.getCodeGenOpts().OpaquePointers);
1105 
1106  // For ThinLTO backend invocations, ensure that the context
1107  // merges types based on ODR identifiers. We also need to read
1108  // the correct module out of a multi-module bitcode file.
1109  if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1110  VMContext->enableDebugTypeODRUniquing();
1111 
1112  auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1113  unsigned DiagID =
1115  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1116  CI.getDiagnostics().Report(DiagID) << EIB.message();
1117  });
1118  return {};
1119  };
1120 
1121  Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1122  if (!BMsOrErr)
1123  return DiagErrors(BMsOrErr.takeError());
1124  BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1125  // We have nothing to do if the file contains no ThinLTO module. This is
1126  // possible if ThinLTO compilation was not able to split module. Content of
1127  // the file was already processed by indexing and will be passed to the
1128  // linker using merged object file.
1129  if (!Bm) {
1130  auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1131  M->setTargetTriple(CI.getTargetOpts().Triple);
1132  return M;
1133  }
1135  Bm->parseModule(*VMContext);
1136  if (!MOrErr)
1137  return DiagErrors(MOrErr.takeError());
1138  return std::move(*MOrErr);
1139  }
1140 
1141  llvm::SMDiagnostic Err;
1142  if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1143  return M;
1144 
1145  // Translate from the diagnostic info to the SourceManager location if
1146  // available.
1147  // TODO: Unify this with ConvertBackendLocation()
1148  SourceLocation Loc;
1149  if (Err.getLineNo() > 0) {
1150  assert(Err.getColumnNo() >= 0);
1151  Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1152  Err.getLineNo(), Err.getColumnNo() + 1);
1153  }
1154 
1155  // Strip off a leading diagnostic code if there is one.
1156  StringRef Msg = Err.getMessage();
1157  if (Msg.startswith("error: "))
1158  Msg = Msg.substr(7);
1159 
1160  unsigned DiagID =
1162 
1163  CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1164  return {};
1165 }
1166 
1168  if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1170  return;
1171  }
1172 
1173  // If this is an IR file, we have to treat it specially.
1174  BackendAction BA = static_cast<BackendAction>(Act);
1176  auto &CodeGenOpts = CI.getCodeGenOpts();
1177  auto &Diagnostics = CI.getDiagnostics();
1178  std::unique_ptr<raw_pwrite_stream> OS =
1180  if (BA != Backend_EmitNothing && !OS)
1181  return;
1182 
1184  FileID FID = SM.getMainFileID();
1185  Optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1186  if (!MainFile)
1187  return;
1188 
1189  TheModule = loadModule(*MainFile);
1190  if (!TheModule)
1191  return;
1192 
1193  const TargetOptions &TargetOpts = CI.getTargetOpts();
1194  if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1195  Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1196  << TargetOpts.Triple;
1197  TheModule->setTargetTriple(TargetOpts.Triple);
1198  }
1199 
1200  EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1201  EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1202 
1203  LLVMContext &Ctx = TheModule->getContext();
1204 
1205  // Restore any diagnostic handler previously set before returning from this
1206  // function.
1207  struct RAII {
1208  LLVMContext &Ctx;
1209  std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1210  ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1211  } _{Ctx};
1212 
1213  // Set clang diagnostic handler. To do this we need to create a fake
1214  // BackendConsumer.
1215  BackendConsumer Result(BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(),
1217  CI.getCodeGenOpts(), CI.getTargetOpts(),
1218  CI.getLangOpts(), TheModule.get(),
1219  std::move(LinkModules), *VMContext, nullptr);
1220  // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1221  // true here because the valued names are needed for reading textual IR.
1222  Ctx.setDiscardValueNames(false);
1223  Ctx.setDiagnosticHandler(
1224  std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1225 
1227  setupLLVMOptimizationRemarks(
1228  Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1229  CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1230  CodeGenOpts.DiagnosticsHotnessThreshold);
1231 
1232  if (Error E = OptRecordFileOrErr.takeError()) {
1233  reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1234  return;
1235  }
1236  std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1237  std::move(*OptRecordFileOrErr);
1238 
1239  EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts,
1240  TargetOpts, CI.getLangOpts(),
1241  CI.getTarget().getDataLayoutString(), TheModule.get(), BA,
1242  std::move(OS));
1243  if (OptRecordFile)
1244  OptRecordFile->keep();
1245 }
1246 
1247 //
1248 
1249 void EmitAssemblyAction::anchor() { }
1250 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1251  : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1252 
1253 void EmitBCAction::anchor() { }
1254 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1255  : CodeGenAction(Backend_EmitBC, _VMContext) {}
1256 
1257 void EmitLLVMAction::anchor() { }
1258 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1259  : CodeGenAction(Backend_EmitLL, _VMContext) {}
1260 
1261 void EmitLLVMOnlyAction::anchor() { }
1262 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1263  : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1264 
1265 void EmitCodeGenOnlyAction::anchor() { }
1266 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1267  : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1268 
1269 void EmitObjAction::anchor() { }
1270 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1271  : CodeGenAction(Backend_EmitObj, _VMContext) {}
clang::TargetInfo::getDataLayoutString
const char * getDataLayoutString() const
Definition: TargetInfo.h:1208
clang::CodeGenAction::ExecuteAction
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Definition: CodeGenAction.cpp:1167
clang::BackendConsumer::EmitOptimizationMessage
void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID)
Specialized handlers for optimization remarks.
Definition: CodeGenAction.cpp:741
clang::diag::Severity
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
Definition: DiagnosticIDs.h:82
getFunctionSourceLocation
static SourceLocation getFunctionSourceLocation(RewriteModernObjC &R, FunctionDecl *FD)
getFunctionSourceLocation - returns start location of a function definition.
Definition: RewriteModernObjC.cpp:3043
clang::CodeGenAction::EndSourceFileAction
void EndSourceFileAction() override
Callback at the end of processing a single input.
Definition: CodeGenAction.cpp:993
clang::BackendConsumer::Initialize
void Initialize(ASTContext &Ctx) override
Initialize - This is called to initialize the consumer, providing the ASTContext.
Definition: CodeGenAction.cpp:206
clang::CodeGenerator
The primary public interface to the Clang code generator.
Definition: ModuleBuilder.h:48
llvm
YAML serialization mapping.
Definition: Dominators.h:30
clang::DiagnosticBuilder
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1266
clang::BackendConsumer::OptimizationRemarkHandler
void OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D)
Definition: CodeGenAction.cpp:780
clang::FullSourceLoc
A SourceLocation and its associated SourceManager.
Definition: SourceLocation.h:368
DiagnosticHandler
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:20
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::PreprocessorOptions
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Definition: PreprocessorOptions.h:65
clang::CodeGenOptions::OptimizationRemarkAnalysis
OptRemark OptimizationRemarkAnalysis
Selected optimizations for which we should enable optimization analyses.
Definition: CodeGenOptions.h:349
llvm::SmallVector< LinkModule, 4 >
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:134
TargetInfo.h
clang::EmitAssemblyAction::EmitAssemblyAction
EmitAssemblyAction(llvm::LLVMContext *_VMContext=nullptr)
Definition: CodeGenAction.cpp:1250
clang::CompilerInstance::getLangOpts
LangOptions & getLangOpts()
Definition: CompilerInstance.h:299
clang::ClangDiagnosticHandler::isMissedOptRemarkEnabled
bool isMissedOptRemarkEnabled(StringRef PassName) const override
Definition: CodeGenAction.cpp:69
Filename
StringRef Filename
Definition: Format.cpp:2715
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::CreateLLVMCodeGen
CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
Definition: ModuleBuilder.cpp:363
DeclCXX.h
clang::BackendConsumer::takeModule
std::unique_ptr< llvm::Module > takeModule()
Definition: CodeGenAction.cpp:196
clang::CodeGenOptions::OptRemark::patternMatches
bool patternMatches(StringRef String) const
Matches the given string against the regex, if there is some.
Definition: CodeGenOptions.h:327
clang::CodeGenAction::~CodeGenAction
~CodeGenAction() override
Definition: CodeGenAction.cpp:985
clang::codegenoptions::NoDebugInfo
@ NoDebugInfo
Don't generate debug info.
Definition: DebugInfoOptions.h:22
clang::BackendConsumer::StackSizeDiagHandler
bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D)
Specialized handler for StackSize diagnostic.
Definition: CodeGenAction.cpp:621
ModuleBuilder.h
clang::DeclGroupRef::begin
iterator begin()
Definition: DeclGroup.h:99
llvm::Optional
Definition: LLVM.h:40
clang::BackendConsumer::HandleInlineFunctionDefinition
void HandleInlineFunctionDefinition(FunctionDecl *D) override
This callback is invoked each time an inline (method or friend) function definition in a class is com...
Definition: CodeGenAction.cpp:243
SourceManager.h
clang::Backend_EmitLL
@ Backend_EmitLL
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:33
clang::CodeGenAction::hasIRSupport
bool hasIRSupport() const override
Does this action support use with IR files?
Definition: CodeGenAction.cpp:991
clang::ClangDiagnosticHandler::ClangDiagnosticHandler
ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
Definition: CodeGenAction.cpp:61
llvm::Expected
Definition: LLVM.h:41
clang::BackendConsumer::ResourceLimitDiagHandler
bool ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit &D)
Specialized handler for ResourceLimit diagnostic.
Definition: CodeGenAction.cpp:638
clang::CoverageSourceInfo
Stores additional source code information like skipped ranges which is required by the coverage mappi...
Definition: CoverageMappingGen.h:62
clang::CompilerInstance::getCodeGenOpts
CodeGenOptions & getCodeGenOpts()
Definition: CompilerInstance.h:254
clang::ASTContext::getSourceManager
SourceManager & getSourceManager()
Definition: ASTContext.h:721
clang::CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks
static CoverageSourceInfo * setUpCoverageCallbacks(Preprocessor &PP)
Definition: CoverageMappingGen.cpp:45
CodeGenAction.h
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:636
clang::BackendConsumer::getFunctionSourceLocation
Optional< FullSourceLoc > getFunctionSourceLocation(const Function &F) const
Definition: CodeGenAction.cpp:695
Preprocessor.h
Offset
unsigned Offset
Definition: Format.cpp:2717
clang::BackendConsumer::HandleTagDeclRequiredDefinition
void HandleTagDeclRequiredDefinition(const TagDecl *D) override
This callback is invoked the first time each TagDecl is required to be complete.
Definition: CodeGenAction.cpp:398
clang::ClangDiagnosticHandler::isAnalysisRemarkEnabled
bool isAnalysisRemarkEnabled(StringRef PassName) const override
Definition: CodeGenAction.cpp:66
clang::EmitCodeGenOnlyAction::EmitCodeGenOnlyAction
EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
Definition: CodeGenAction.cpp:1266
clang::hash_value
llvm::hash_code hash_value(const clang::SanitizerMask &Arg)
Definition: Sanitizers.cpp:68
clang::CompilerInstance::getFileManager
FileManager & getFileManager() const
Return the current file manager to the caller.
Definition: CompilerInstance.h:402
clang::BackendConsumer::getBestLocationFromDebugLoc
const FullSourceLoc getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, StringRef &Filename, unsigned &Line, unsigned &Column) const
Get the best possible source location to represent a diagnostic that may have associated debug info.
Definition: CodeGenAction.cpp:652
BackendUtil.h
clang::BackendConsumer::CompleteTentativeDefinition
void CompleteTentativeDefinition(VarDecl *D) override
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
Definition: CodeGenAction.cpp:402
clang::Module
Describes a module or submodule.
Definition: Module.h:98
clang::EmitLLVMAction::EmitLLVMAction
EmitLLVMAction(llvm::LLVMContext *_VMContext=nullptr)
Definition: CodeGenAction.cpp:1258
clang::CodeGenAction
Definition: CodeGenAction.h:24
clang::AddFlagValue
Definition: Diagnostic.h:1372
clang::FrontendAction::getCurrentFileOrBufferName
StringRef getCurrentFileOrBufferName() const
Definition: FrontendAction.h:144
clang::CodeGenOptions::ProfileNone
@ ProfileNone
Definition: CodeGenOptions.h:86
clang::CompilerInstance::createNullOutputFile
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
Definition: CompilerInstance.cpp:823
clang::BackendConsumer::MisExpectDiagHandler
void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D)
Specialized handler for misexpect warnings.
Definition: CodeGenAction.cpp:856
clang::BackendAction
BackendAction
Definition: BackendUtil.h:30
clang::BackendConsumer::LinkInModules
bool LinkInModules()
Definition: CodeGenAction.cpp:263
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:209
clang::PrettyStackTraceDecl
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Definition: DeclBase.h:1252
DriverDiagnostic.h
clang::BackendConsumer::HandleTagDeclDefinition
void HandleTagDeclDefinition(TagDecl *D) override
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: CodeGenAction.cpp:391
clang::DiagnosticsEngine::Error
@ Error
Definition: Diagnostic.h:200
clang::ASTConsumer
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:33
clang::CodeGenOptions::OptimizationRemarkMissed
OptRemark OptimizationRemarkMissed
Selected optimizations for which we should enable missed optimization remarks.
Definition: CodeGenOptions.h:342
clang::BackendConsumer::AssignInheritanceModel
void AssignInheritanceModel(CXXRecordDecl *RD) override
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: CodeGenAction.cpp:410
clang::EmitLLVMOnlyAction::EmitLLVMOnlyAction
EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
Definition: CodeGenAction.cpp:1262
clang::BackendConsumer::HandleInterestingDecl
void HandleInterestingDecl(DeclGroupRef D) override
HandleInterestingDecl - Handle the specified interesting declaration.
Definition: CodeGenAction.cpp:256
clang::BackendConsumer::BackendConsumer
BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, const TargetOptions &TargetOpts, const LangOptions &LangOpts, llvm::Module *Module, SmallVector< LinkModule, 4 > LinkModules, LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
Definition: CodeGenAction.cpp:174
clang::CodeGenAction::BEConsumer
BackendConsumer * BEConsumer
Definition: CodeGenAction.h:83
clang::ClangDiagnosticHandler
Definition: CodeGenAction.cpp:59
clang::FrontendAction::getCompilerInstance
CompilerInstance & getCompilerInstance() const
Definition: FrontendAction.h:119
clang::CodeGenOptions::OptRecordFormat
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
Definition: CodeGenOptions.h:298
ASTContext.h
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:906
clang::TagDecl
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3423
clang::CompilerInstance::getPreprocessor
Preprocessor & getPreprocessor() const
Return the current preprocessor.
Definition: CompilerInstance.h:442
clang::Backend_EmitBC
@ Backend_EmitBC
Emit LLVM bitcode files.
Definition: BackendUtil.h:32
MacroPPCallbacks.h
clang::Backend_EmitMCNull
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
Definition: BackendUtil.h:35
CodeGenModule.h
Line
const AnnotatedLine * Line
Definition: UsingDeclarationsSorter.cpp:68
clang::EmbedBitcode
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
Definition: BackendUtil.cpp:1290
DeclGroup.h
clang::CompilerInstance
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Definition: CompilerInstance.h:72
clang::CodeGenOptions
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Definition: CodeGenOptions.h:49
clang::CodeGenAction::getCodeGenerator
CodeGenerator * getCodeGenerator() const
Definition: CodeGenAction.cpp:1011
clang::CompilerInstance::getPreprocessorOpts
PreprocessorOptions & getPreprocessorOpts()
Definition: CompilerInstance.h:306
clang::FrontendAction::getCurrentFileKind
InputKind getCurrentFileKind() const
Definition: FrontendAction.h:151
clang::BackendConsumer::CompleteExternalDeclaration
void CompleteExternalDeclaration(VarDecl *D) override
CompleteExternalDeclaration - Callback invoked at the end of a translation unit to notify the consume...
Definition: CodeGenAction.cpp:406
clang::CompilerInstance::takeOutputStream
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
Definition: CompilerInstance.h:767
clang::SourceManager::getLocForStartOfFile
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
Definition: SourceManager.h:1125
clang::ClangDiagnosticHandler::isPassedOptRemarkEnabled
bool isPassedOptRemarkEnabled(StringRef PassName) const override
Definition: CodeGenAction.cpp:72
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
clang::CompilerInstance::getTargetOpts
TargetOptions & getTargetOpts()
Definition: CompilerInstance.h:320
clang::BackendConsumer::UnsupportedDiagHandler
void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D)
Specialized handler for unsupported backend feature diagnostic.
Definition: CodeGenAction.cpp:704
clang::BackendConsumer::SrcMgrDiagHandler
void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D)
Specialized handler for diagnostics reported using SMDiagnostic.
Definition: CodeGenAction.cpp:537
clang::BackendConsumer::HandleVTable
void HandleVTable(CXXRecordDecl *RD) override
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition: CodeGenAction.cpp:414
LangStandard.h
clang::CompilerInstance::getVirtualFileSystem
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: CompilerInstance.cpp:161
clang::EmbedObject
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
Definition: BackendUtil.cpp:1300
clang::reportOptRecordError
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions CodeGenOpts)
Definition: CodeGenAction.cpp:87
clang::Language::LLVM_IR
@ LLVM_IR
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
clang::StreamingDiagnostic::AddString
void AddString(StringRef V) const
Definition: Diagnostic.h:1194
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::DeclGroupRef
Definition: DeclGroup.h:51
clang::FileManager::getBufferForFile
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Definition: FileManager.cpp:539
clang::CodeGenAction::takeModule
std::unique_ptr< llvm::Module > takeModule()
Take the generated LLVM module, for use after the action has been run.
Definition: CodeGenAction.cpp:1002
clang::EmitBackendOutput
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, std::unique_ptr< raw_pwrite_stream > OS)
ASTConsumer.h
clang::CodeGenAction::takeLLVMContext
llvm::LLVMContext * takeLLVMContext()
Take the LLVM context used by this action.
Definition: CodeGenAction.cpp:1006
clang::Backend_EmitAssembly
@ Backend_EmitAssembly
Emit native assembly files.
Definition: BackendUtil.h:31
clang::SourceLocation::getFromRawEncoding
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
Definition: SourceLocation.h:152
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:81
clang::CodeGenAction::CodeGenAction
CodeGenAction(unsigned _Act, llvm::LLVMContext *_VMContext=nullptr)
Create a new code generation action.
Definition: CodeGenAction.cpp:981
std
Definition: Format.h:4477
clang::CompilerInstance::getTarget
TargetInfo & getTarget() const
Definition: CompilerInstance.h:369
clang::CodeGenAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: CodeGenAction.cpp:1036
clang::DiagnosticsEngine::getCustomDiagID
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:868
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang::BackendConsumer::getModule
llvm::Module * getModule() const
Definition: CodeGenAction.cpp:195
clang
Definition: CalledOnceCheck.h:17
clang::FileManager
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
clang::BackendConsumer::InlineAsmDiagHandler
bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D)
Specialized handler for InlineAsm diagnostic.
Definition: CodeGenAction.cpp:596
clang::Preprocessor::addPPCallbacks
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
Definition: Preprocessor.h:1163
clang::SourceManager::createFileID
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
Definition: SourceManager.cpp:534
clang::EmitObjAction::EmitObjAction
EmitObjAction(llvm::LLVMContext *_VMContext=nullptr)
Definition: CodeGenAction.cpp:1270
clang::BackendConsumer::OptimizationFailureHandler
void OptimizationFailureHandler(const llvm::DiagnosticInfoOptimizationFailure &D)
Definition: CodeGenAction.cpp:836
clang::BackendConsumer::DiagnosticHandlerImpl
void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI)
This function is invoked when the backend needs to report something to the user.
Definition: CodeGenAction.cpp:877
clang::BackendConsumer::HandleCXXStaticMemberVarInstantiation
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
Definition: CodeGenAction.cpp:202
clang::BackendConsumer::HandleTopLevelDecl
bool HandleTopLevelDecl(DeclGroupRef D) override
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: CodeGenAction.cpp:220
ConvertBackendLocation
static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, SourceManager &CSM)
ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr buffer to be a valid FullS...
Definition: CodeGenAction.cpp:474
clang::CompilerInstance::createDefaultOutputFile
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
Definition: CompilerInstance.cpp:803
FrontendDiagnostic.h
clang::CodeGenOptions::OptRecordFile
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
Definition: CodeGenOptions.h:291
clang::CodeGenOptions::LinkBitcodeFiles
std::vector< BitcodeFileToLink > LinkBitcodeFiles
The files specified here are linked in to the module before optimizations.
Definition: CodeGenOptions.h:222
clang::EmitBCAction::EmitBCAction
EmitBCAction(llvm::LLVMContext *_VMContext=nullptr)
Definition: CodeGenAction.cpp:1254
clang::TargetOptions::Triple
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:38
ComputeDiagRemarkID
#define ComputeDiagRemarkID(Severity, GroupName, DiagID)
Definition: CodeGenAction.cpp:519
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
clang::BackendConsumer::HandleTranslationUnit
void HandleTranslationUnit(ASTContext &C) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
Definition: CodeGenAction.cpp:296
clang::CodeGenOptions::ThinLTOIndexFile
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
Definition: CodeGenOptions.h:271
clang::Backend_EmitNothing
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Definition: BackendUtil.h:34
clang::SourceManager::getFileManager
FileManager & getFileManager() const
Definition: SourceManager.h:816
clang::FileManager::getFile
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
Definition: FileManager.cpp:197
clang::ASTFrontendAction::ExecuteAction
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
Definition: FrontendAction.cpp:1143
CompilerInstance.h
clang::BackendConsumer::BackendConsumer
BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, const TargetOptions &TargetOpts, const LangOptions &LangOpts, const std::string &InFile, SmallVector< LinkModule, 4 > LinkModules, std::unique_ptr< raw_pwrite_stream > OS, LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
Definition: CodeGenAction.cpp:148
clang::Backend_EmitObj
@ Backend_EmitObj
Emit native object files.
Definition: BackendUtil.h:36
clang::TargetOptions
Options for controlling the target.
Definition: TargetOptions.h:26
clang::CompilerInstance::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
Definition: CompilerInstance.h:334
clang::CompilerInstance::getSourceManager
SourceManager & getSourceManager() const
Return the current source manager.
Definition: CompilerInstance.h:422
clang::SourceManager::translateFileLineCol
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
Definition: SourceManager.cpp:1648
clang::BackendConsumer::getCodeGenerator
CodeGenerator * getCodeGenerator()
Definition: CodeGenAction.cpp:200
FileManager.h
DiagnosticFrontend.h
clang::BackendConsumer
Definition: CodeGenAction.cpp:105
clang::BackendConsumer::DontCallDiagHandler
void DontCallDiagHandler(const DiagnosticInfoDontCall &D)
Definition: CodeGenAction.cpp:841
SM
#define SM(sm)
Definition: Cuda.cpp:79
CoverageMappingGen.h
clang::ClangDiagnosticHandler::isAnyRemarkEnabled
bool isAnyRemarkEnabled() const override
Definition: CodeGenAction.cpp:76
clang::CodeGenAction::BackendConsumer
friend class BackendConsumer
Definition: CodeGenAction.h:27
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1904
clang::CodeGenOptions::OptRecordPasses
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
Definition: CodeGenOptions.h:295
GetOutputStream
static std::unique_ptr< raw_pwrite_stream > GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action)
Definition: CodeGenAction.cpp:1016
clang::CompilerInstance::getHeaderSearchOpts
HeaderSearchOptions & getHeaderSearchOpts()
Definition: CompilerInstance.h:289
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem >
clang::ClangDiagnosticHandler::handleDiagnostics
bool handleDiagnostics(const DiagnosticInfo &DI) override
Definition: CodeGenAction.cpp:467
clang::HeaderSearchOptions
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
Definition: HeaderSearchOptions.h:68
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1537
clang::CodeGenOptions::OptimizationRemark
OptRemark OptimizationRemark
Selected optimizations for which we should enable optimization remarks.
Definition: CodeGenOptions.h:336
ComputeDiagID
#define ComputeDiagID(Severity, GroupName, DiagID)
Definition: CodeGenAction.cpp:501