clang  10.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/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/Module.h"
36 #include "llvm/IR/RemarkStreamer.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;
55  public:
57  : CodeGenOpts(CGOpts), BackendCon(BCon) {}
58 
59  bool handleDiagnostics(const DiagnosticInfo &DI) override;
60 
61  bool isAnalysisRemarkEnabled(StringRef PassName) const override {
62  return (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
63  CodeGenOpts.OptimizationRemarkAnalysisPattern->match(PassName));
64  }
65  bool isMissedOptRemarkEnabled(StringRef PassName) const override {
66  return (CodeGenOpts.OptimizationRemarkMissedPattern &&
67  CodeGenOpts.OptimizationRemarkMissedPattern->match(PassName));
68  }
69  bool isPassedOptRemarkEnabled(StringRef PassName) const override {
70  return (CodeGenOpts.OptimizationRemarkPattern &&
71  CodeGenOpts.OptimizationRemarkPattern->match(PassName));
72  }
73 
74  bool isAnyRemarkEnabled() const override {
75  return (CodeGenOpts.OptimizationRemarkAnalysisPattern ||
76  CodeGenOpts.OptimizationRemarkMissedPattern ||
77  CodeGenOpts.OptimizationRemarkPattern);
78  }
79 
80  private:
81  const CodeGenOptions &CodeGenOpts;
82  BackendConsumer *BackendCon;
83  };
84 
86  const CodeGenOptions CodeGenOpts) {
87  handleAllErrors(
88  std::move(E),
89  [&](const RemarkSetupFileError &E) {
90  Diags.Report(diag::err_cannot_open_file)
91  << CodeGenOpts.OptRecordFile << E.message();
92  },
93  [&](const RemarkSetupPatternError &E) {
94  Diags.Report(diag::err_drv_optimization_remark_pattern)
95  << E.message() << CodeGenOpts.OptRecordPasses;
96  },
97  [&](const RemarkSetupFormatError &E) {
98  Diags.Report(diag::err_drv_optimization_remark_format)
99  << CodeGenOpts.OptRecordFormat;
100  });
101  }
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:
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  LinkModules(std::move(LinkModules)) {
151  FrontendTimesIsEnabled = TimePasses;
152  llvm::TimePassesIsEnabled = TimePasses;
153  }
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.
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  LinkModules(std::move(LinkModules)) {
174  FrontendTimesIsEnabled = TimePasses;
175  llvm::TimePassesIsEnabled = TimePasses;
176  }
177  llvm::Module *getModule() const { return Gen->GetModule(); }
178  std::unique_ptr<llvm::Module> takeModule() {
179  return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
180  }
181 
182  CodeGenerator *getCodeGenerator() { return Gen.get(); }
183 
185  Gen->HandleCXXStaticMemberVarInstantiation(VD);
186  }
187 
188  void Initialize(ASTContext &Ctx) override {
189  assert(!Context && "initialized multiple times");
190 
191  Context = &Ctx;
192 
194  LLVMIRGeneration.startTimer();
195 
196  Gen->Initialize(Ctx);
197 
199  LLVMIRGeneration.stopTimer();
200  }
201 
202  bool HandleTopLevelDecl(DeclGroupRef D) override {
203  PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
204  Context->getSourceManager(),
205  "LLVM IR generation of declaration");
206 
207  // Recurse.
209  LLVMIRGenerationRefCount += 1;
210  if (LLVMIRGenerationRefCount == 1)
211  LLVMIRGeneration.startTimer();
212  }
213 
214  Gen->HandleTopLevelDecl(D);
215 
217  LLVMIRGenerationRefCount -= 1;
218  if (LLVMIRGenerationRefCount == 0)
219  LLVMIRGeneration.stopTimer();
220  }
221 
222  return true;
223  }
224 
226  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
227  Context->getSourceManager(),
228  "LLVM IR generation of inline function");
230  LLVMIRGeneration.startTimer();
231 
232  Gen->HandleInlineFunctionDefinition(D);
233 
235  LLVMIRGeneration.stopTimer();
236  }
237 
239  // Ignore interesting decls from the AST reader after IRGen is finished.
240  if (!IRGenFinished)
241  HandleTopLevelDecl(D);
242  }
243 
244  // Links each entry in LinkModules into our module. Returns true on error.
245  bool LinkInModules() {
246  for (auto &LM : LinkModules) {
247  if (LM.PropagateAttrs)
248  for (Function &F : *LM.Module)
249  Gen->CGM().AddDefaultFnAttrs(F);
250 
251  CurLinkModule = LM.Module.get();
252 
253  bool Err;
254  if (LM.Internalize) {
255  Err = Linker::linkModules(
256  *getModule(), std::move(LM.Module), LM.LinkFlags,
257  [](llvm::Module &M, const llvm::StringSet<> &GVS) {
258  internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
259  return !GV.hasName() || (GVS.count(GV.getName()) == 0);
260  });
261  });
262  } else {
263  Err = Linker::linkModules(*getModule(), std::move(LM.Module),
264  LM.LinkFlags);
265  }
266 
267  if (Err)
268  return true;
269  }
270  return false; // success
271  }
272 
274  {
275  llvm::TimeTraceScope TimeScope("Frontend");
276  PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
278  LLVMIRGenerationRefCount += 1;
279  if (LLVMIRGenerationRefCount == 1)
280  LLVMIRGeneration.startTimer();
281  }
282 
283  Gen->HandleTranslationUnit(C);
284 
286  LLVMIRGenerationRefCount -= 1;
287  if (LLVMIRGenerationRefCount == 0)
288  LLVMIRGeneration.stopTimer();
289  }
290 
291  IRGenFinished = true;
292  }
293 
294  // Silently ignore if we weren't initialized for some reason.
295  if (!getModule())
296  return;
297 
298  // Install an inline asm handler so that diagnostics get printed through
299  // our diagnostics hooks.
300  LLVMContext &Ctx = getModule()->getContext();
301  LLVMContext::InlineAsmDiagHandlerTy OldHandler =
302  Ctx.getInlineAsmDiagnosticHandler();
303  void *OldContext = Ctx.getInlineAsmDiagnosticContext();
304  Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
305 
306  std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
307  Ctx.getDiagnosticHandler();
308  Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
309  CodeGenOpts, this));
310 
312  setupOptimizationRemarks(
313  Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
314  CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
315  CodeGenOpts.DiagnosticsHotnessThreshold);
316 
317  if (Error E = OptRecordFileOrErr.takeError()) {
318  reportOptRecordError(std::move(E), Diags, CodeGenOpts);
319  return;
320  }
321 
322  std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
323  std::move(*OptRecordFileOrErr);
324 
325  if (OptRecordFile &&
326  CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
327  Ctx.setDiagnosticsHotnessRequested(true);
328 
329  // Link each LinkModule into our module.
330  if (LinkInModules())
331  return;
332 
333  EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
334 
335  EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
336  LangOpts, C.getTargetInfo().getDataLayout(),
337  getModule(), Action, std::move(AsmOutStream));
338 
339  Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
340 
341  Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
342 
343  if (OptRecordFile)
344  OptRecordFile->keep();
345  }
346 
347  void HandleTagDeclDefinition(TagDecl *D) override {
348  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
349  Context->getSourceManager(),
350  "LLVM IR generation of declaration");
351  Gen->HandleTagDeclDefinition(D);
352  }
353 
354  void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
355  Gen->HandleTagDeclRequiredDefinition(D);
356  }
357 
359  Gen->CompleteTentativeDefinition(D);
360  }
361 
363  Gen->CompleteExternalDeclaration(D);
364  }
365 
367  Gen->AssignInheritanceModel(RD);
368  }
369 
370  void HandleVTable(CXXRecordDecl *RD) override {
371  Gen->HandleVTable(RD);
372  }
373 
374  static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
375  unsigned LocCookie) {
377  ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
378  }
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  void BackendConsumer::anchor() {}
420 }
421 
422 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
423  BackendCon->DiagnosticHandlerImpl(DI);
424  return true;
425 }
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  SourceManager &CSM) {
431  // Get both the clang and llvm source managers. The location is relative to
432  // a memory buffer that the LLVM Source Manager is handling, we need to add
433  // a copy to the Clang source manager.
434  const llvm::SourceMgr &LSM = *D.getSourceMgr();
435 
436  // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
437  // already owns its one and clang::SourceManager wants to own its one.
438  const MemoryBuffer *LBuf =
439  LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
440 
441  // Create the copy and transfer ownership to clang::SourceManager.
442  // TODO: Avoid copying files into memory.
443  std::unique_ptr<llvm::MemoryBuffer> CBuf =
444  llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
445  LBuf->getBufferIdentifier());
446  // FIXME: Keep a file ID map instead of creating new IDs for each location.
447  FileID FID = CSM.createFileID(std::move(CBuf));
448 
449  // Translate the offset into the file.
450  unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
451  SourceLocation NewLoc =
452  CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
453  return FullSourceLoc(NewLoc, CSM);
454 }
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  SourceLocation LocCookie) {
462  // There are a couple of different kinds of errors we could get here. First,
463  // we re-format the SMDiagnostic in terms of a clang diagnostic.
464 
465  // Strip "error: " off the start of the message string.
466  StringRef Message = D.getMessage();
467  if (Message.startswith("error: "))
468  Message = Message.substr(7);
469 
470  // If the SMDiagnostic has an inline asm source location, translate it.
471  FullSourceLoc Loc;
472  if (D.getLoc() != SMLoc())
473  Loc = ConvertBackendLocation(D, Context->getSourceManager());
474 
475  unsigned DiagID;
476  switch (D.getKind()) {
477  case llvm::SourceMgr::DK_Error:
478  DiagID = diag::err_fe_inline_asm;
479  break;
480  case llvm::SourceMgr::DK_Warning:
481  DiagID = diag::warn_fe_inline_asm;
482  break;
483  case llvm::SourceMgr::DK_Note:
484  DiagID = diag::note_fe_inline_asm;
485  break;
486  case llvm::SourceMgr::DK_Remark:
487  llvm_unreachable("remarks unexpected");
488  }
489  // If this problem has clang-level source location information, report the
490  // issue in the source with a note showing the instantiated
491  // code.
492  if (LocCookie.isValid()) {
493  Diags.Report(LocCookie, DiagID).AddString(Message);
494 
495  if (D.getLoc().isValid()) {
496  DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
497  // Convert the SMDiagnostic ranges into SourceRange and attach them
498  // to the diagnostic.
499  for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
500  unsigned Column = D.getColumnNo();
501  B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
502  Loc.getLocWithOffset(Range.second - Column));
503  }
504  }
505  return;
506  }
507 
508  // Otherwise, report the backend issue as occurring in the generated .s file.
509  // If Loc is invalid, we still need to report the issue, it just gets no
510  // location info.
511  Diags.Report(Loc, DiagID).AddString(Message);
512 }
513 
514 #define ComputeDiagID(Severity, GroupName, DiagID) \
515  do { \
516  switch (Severity) { \
517  case llvm::DS_Error: \
518  DiagID = diag::err_fe_##GroupName; \
519  break; \
520  case llvm::DS_Warning: \
521  DiagID = diag::warn_fe_##GroupName; \
522  break; \
523  case llvm::DS_Remark: \
524  llvm_unreachable("'remark' severity not expected"); \
525  break; \
526  case llvm::DS_Note: \
527  DiagID = diag::note_fe_##GroupName; \
528  break; \
529  } \
530  } while (false)
531 
532 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
533  do { \
534  switch (Severity) { \
535  case llvm::DS_Error: \
536  DiagID = diag::err_fe_##GroupName; \
537  break; \
538  case llvm::DS_Warning: \
539  DiagID = diag::warn_fe_##GroupName; \
540  break; \
541  case llvm::DS_Remark: \
542  DiagID = diag::remark_fe_##GroupName; \
543  break; \
544  case llvm::DS_Note: \
545  DiagID = diag::note_fe_##GroupName; \
546  break; \
547  } \
548  } while (false)
549 
550 bool
551 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
552  unsigned DiagID;
553  ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
554  std::string Message = D.getMsgStr().str();
555 
556  // If this problem has clang-level source location information, report the
557  // issue as being a problem in the source with a note showing the instantiated
558  // code.
559  SourceLocation LocCookie =
560  SourceLocation::getFromRawEncoding(D.getLocCookie());
561  if (LocCookie.isValid())
562  Diags.Report(LocCookie, DiagID).AddString(Message);
563  else {
564  // Otherwise, report the backend diagnostic as occurring in the generated
565  // .s file.
566  // If Loc is invalid, we still need to report the diagnostic, it just gets
567  // no location info.
568  FullSourceLoc Loc;
569  Diags.Report(Loc, DiagID).AddString(Message);
570  }
571  // We handled all the possible severities.
572  return true;
573 }
574 
575 bool
576 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
577  if (D.getSeverity() != llvm::DS_Warning)
578  // For now, the only support we have for StackSize diagnostic is warning.
579  // We do not know how to format other severities.
580  return false;
581 
582  if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
583  // FIXME: Shouldn't need to truncate to uint32_t
584  Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
585  diag::warn_fe_frame_larger_than)
586  << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
587  return true;
588  }
589 
590  return false;
591 }
592 
594  const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
595  StringRef &Filename, unsigned &Line, unsigned &Column) const {
596  SourceManager &SourceMgr = Context->getSourceManager();
597  FileManager &FileMgr = SourceMgr.getFileManager();
598  SourceLocation DILoc;
599 
600  if (D.isLocationAvailable()) {
601  D.getLocation(Filename, Line, Column);
602  if (Line > 0) {
603  auto FE = FileMgr.getFile(Filename);
604  if (!FE)
605  FE = FileMgr.getFile(D.getAbsolutePath());
606  if (FE) {
607  // If -gcolumn-info was not used, Column will be 0. This upsets the
608  // source manager, so pass 1 if Column is not set.
609  DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
610  }
611  }
612  BadDebugInfo = DILoc.isInvalid();
613  }
614 
615  // If a location isn't available, try to approximate it using the associated
616  // function definition. We use the definition's right brace to differentiate
617  // from diagnostics that genuinely relate to the function itself.
618  FullSourceLoc Loc(DILoc, SourceMgr);
619  if (Loc.isInvalid())
620  if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
621  Loc = FD->getASTContext().getFullLoc(FD->getLocation());
622 
623  if (DILoc.isInvalid() && D.isLocationAvailable())
624  // If we were not able to translate the file:line:col information
625  // back to a SourceLocation, at least emit a note stating that
626  // we could not translate this location. This can happen in the
627  // case of #line directives.
628  Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
629  << Filename << Line << Column;
630 
631  return Loc;
632 }
633 
635  const llvm::DiagnosticInfoUnsupported &D) {
636  // We only support errors.
637  assert(D.getSeverity() == llvm::DS_Error);
638 
639  StringRef Filename;
640  unsigned Line, Column;
641  bool BadDebugInfo = false;
642  FullSourceLoc Loc;
643  std::string Msg;
644  raw_string_ostream MsgStream(Msg);
645 
646  // Context will be nullptr for IR input files, we will construct the diag
647  // message from llvm::DiagnosticInfoUnsupported.
648  if (Context != nullptr) {
649  Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
650  MsgStream << D.getMessage();
651  } else {
652  DiagnosticPrinterRawOStream DP(MsgStream);
653  D.print(DP);
654  }
655  Diags.Report(Loc, diag::err_fe_backend_unsupported) << MsgStream.str();
656 
657  if (BadDebugInfo)
658  // If we were not able to translate the file:line:col information
659  // back to a SourceLocation, at least emit a note stating that
660  // we could not translate this location. This can happen in the
661  // case of #line directives.
662  Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
663  << Filename << Line << Column;
664 }
665 
667  const llvm::DiagnosticInfoMisExpect &D) {
668  StringRef Filename;
669  unsigned Line, Column;
670  bool BadDebugInfo = false;
671  FullSourceLoc Loc;
672  std::string Msg;
673  raw_string_ostream MsgStream(Msg);
674  DiagnosticPrinterRawOStream DP(MsgStream);
675 
676  // Context will be nullptr for IR input files, we will construct the diag
677  // message from llvm::DiagnosticInfoMisExpect.
678  if (Context != nullptr) {
679  Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
680  MsgStream << D.getMsg();
681  } else {
682  DiagnosticPrinterRawOStream DP(MsgStream);
683  D.print(DP);
684  }
685  Diags.Report(Loc, diag::warn_profile_data_misexpect) << MsgStream.str();
686 
687  if (BadDebugInfo)
688  // If we were not able to translate the file:line:col information
689  // back to a SourceLocation, at least emit a note stating that
690  // we could not translate this location. This can happen in the
691  // case of #line directives.
692  Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
693  << Filename << Line << Column;
694 }
695 
697  const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
698  // We only support warnings and remarks.
699  assert(D.getSeverity() == llvm::DS_Remark ||
700  D.getSeverity() == llvm::DS_Warning);
701 
702  StringRef Filename;
703  unsigned Line, Column;
704  bool BadDebugInfo = false;
705  FullSourceLoc Loc;
706  std::string Msg;
707  raw_string_ostream MsgStream(Msg);
708 
709  // Context will be nullptr for IR input files, we will construct the remark
710  // message from llvm::DiagnosticInfoOptimizationBase.
711  if (Context != nullptr) {
712  Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
713  MsgStream << D.getMsg();
714  } else {
715  DiagnosticPrinterRawOStream DP(MsgStream);
716  D.print(DP);
717  }
718 
719  if (D.getHotness())
720  MsgStream << " (hotness: " << *D.getHotness() << ")";
721 
722  Diags.Report(Loc, DiagID)
723  << AddFlagValue(D.getPassName())
724  << MsgStream.str();
725 
726  if (BadDebugInfo)
727  // If we were not able to translate the file:line:col information
728  // back to a SourceLocation, at least emit a note stating that
729  // we could not translate this location. This can happen in the
730  // case of #line directives.
731  Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
732  << Filename << Line << Column;
733 }
734 
736  const llvm::DiagnosticInfoOptimizationBase &D) {
737  // Without hotness information, don't show noisy remarks.
738  if (D.isVerbose() && !D.getHotness())
739  return;
740 
741  if (D.isPassed()) {
742  // Optimization remarks are active only if the -Rpass flag has a regular
743  // expression that matches the name of the pass name in \p D.
744  if (CodeGenOpts.OptimizationRemarkPattern &&
745  CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
746  EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
747  } else if (D.isMissed()) {
748  // Missed optimization remarks are active only if the -Rpass-missed
749  // flag has a regular expression that matches the name of the pass
750  // name in \p D.
751  if (CodeGenOpts.OptimizationRemarkMissedPattern &&
752  CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
753  EmitOptimizationMessage(
754  D, diag::remark_fe_backend_optimization_remark_missed);
755  } else {
756  assert(D.isAnalysis() && "Unknown remark type");
757 
758  bool ShouldAlwaysPrint = false;
759  if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
760  ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
761 
762  if (ShouldAlwaysPrint ||
763  (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
764  CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
765  EmitOptimizationMessage(
766  D, diag::remark_fe_backend_optimization_remark_analysis);
767  }
768 }
769 
771  const llvm::OptimizationRemarkAnalysisFPCommute &D) {
772  // Optimization analysis remarks are active if the pass name is set to
773  // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
774  // regular expression that matches the name of the pass name in \p D.
775 
776  if (D.shouldAlwaysPrint() ||
777  (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
778  CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
779  EmitOptimizationMessage(
780  D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
781 }
782 
784  const llvm::OptimizationRemarkAnalysisAliasing &D) {
785  // Optimization analysis remarks are active if the pass name is set to
786  // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
787  // regular expression that matches the name of the pass name in \p D.
788 
789  if (D.shouldAlwaysPrint() ||
790  (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
791  CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
792  EmitOptimizationMessage(
793  D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
794 }
795 
797  const llvm::DiagnosticInfoOptimizationFailure &D) {
798  EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
799 }
800 
801 /// This function is invoked when the backend needs
802 /// to report something to the user.
803 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
804  unsigned DiagID = diag::err_fe_inline_asm;
805  llvm::DiagnosticSeverity Severity = DI.getSeverity();
806  // Get the diagnostic ID based.
807  switch (DI.getKind()) {
808  case llvm::DK_InlineAsm:
809  if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
810  return;
811  ComputeDiagID(Severity, inline_asm, DiagID);
812  break;
813  case llvm::DK_StackSize:
814  if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
815  return;
816  ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
817  break;
818  case DK_Linker:
819  assert(CurLinkModule);
820  // FIXME: stop eating the warnings and notes.
821  if (Severity != DS_Error)
822  return;
823  DiagID = diag::err_fe_cannot_link_module;
824  break;
825  case llvm::DK_OptimizationRemark:
826  // Optimization remarks are always handled completely by this
827  // handler. There is no generic way of emitting them.
828  OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
829  return;
830  case llvm::DK_OptimizationRemarkMissed:
831  // Optimization remarks are always handled completely by this
832  // handler. There is no generic way of emitting them.
833  OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
834  return;
835  case llvm::DK_OptimizationRemarkAnalysis:
836  // Optimization remarks are always handled completely by this
837  // handler. There is no generic way of emitting them.
838  OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
839  return;
840  case llvm::DK_OptimizationRemarkAnalysisFPCommute:
841  // Optimization remarks are always handled completely by this
842  // handler. There is no generic way of emitting them.
843  OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
844  return;
845  case llvm::DK_OptimizationRemarkAnalysisAliasing:
846  // Optimization remarks are always handled completely by this
847  // handler. There is no generic way of emitting them.
848  OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
849  return;
850  case llvm::DK_MachineOptimizationRemark:
851  // Optimization remarks are always handled completely by this
852  // handler. There is no generic way of emitting them.
853  OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
854  return;
855  case llvm::DK_MachineOptimizationRemarkMissed:
856  // Optimization remarks are always handled completely by this
857  // handler. There is no generic way of emitting them.
858  OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
859  return;
860  case llvm::DK_MachineOptimizationRemarkAnalysis:
861  // Optimization remarks are always handled completely by this
862  // handler. There is no generic way of emitting them.
863  OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
864  return;
865  case llvm::DK_OptimizationFailure:
866  // Optimization failures are always handled completely by this
867  // handler.
868  OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
869  return;
870  case llvm::DK_Unsupported:
871  UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
872  return;
873  case llvm::DK_MisExpect:
874  MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));
875  return;
876  default:
877  // Plugin IDs are not bound to any value as they are set dynamically.
878  ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
879  break;
880  }
881  std::string MsgStorage;
882  {
883  raw_string_ostream Stream(MsgStorage);
884  DiagnosticPrinterRawOStream DP(Stream);
885  DI.print(DP);
886  }
887 
888  if (DiagID == diag::err_fe_cannot_link_module) {
889  Diags.Report(diag::err_fe_cannot_link_module)
890  << CurLinkModule->getModuleIdentifier() << MsgStorage;
891  return;
892  }
893 
894  // Report the backend message using the usual diagnostic mechanism.
895  FullSourceLoc Loc;
896  Diags.Report(Loc, DiagID).AddString(MsgStorage);
897 }
898 #undef ComputeDiagID
899 
900 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
901  : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
902  OwnsVMContext(!_VMContext) {}
903 
905  TheModule.reset();
906  if (OwnsVMContext)
907  delete VMContext;
908 }
909 
910 bool CodeGenAction::hasIRSupport() const { return true; }
911 
913  // If the consumer creation failed, do nothing.
914  if (!getCompilerInstance().hasASTConsumer())
915  return;
916 
917  // Steal the module from the consumer.
918  TheModule = BEConsumer->takeModule();
919 }
920 
921 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
922  return std::move(TheModule);
923 }
924 
925 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
926  OwnsVMContext = false;
927  return VMContext;
928 }
929 
930 static std::unique_ptr<raw_pwrite_stream>
931 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
932  switch (Action) {
934  return CI.createDefaultOutputFile(false, InFile, "s");
935  case Backend_EmitLL:
936  return CI.createDefaultOutputFile(false, InFile, "ll");
937  case Backend_EmitBC:
938  return CI.createDefaultOutputFile(true, InFile, "bc");
939  case Backend_EmitNothing:
940  return nullptr;
941  case Backend_EmitMCNull:
942  return CI.createNullOutputFile();
943  case Backend_EmitObj:
944  return CI.createDefaultOutputFile(true, InFile, "o");
945  }
946 
947  llvm_unreachable("Invalid action!");
948 }
949 
950 std::unique_ptr<ASTConsumer>
952  BackendAction BA = static_cast<BackendAction>(Act);
953  std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
954  if (!OS)
955  OS = GetOutputStream(CI, InFile, BA);
956 
957  if (BA != Backend_EmitNothing && !OS)
958  return nullptr;
959 
960  // Load bitcode modules to link with, if we need to.
961  if (LinkModules.empty())
962  for (const CodeGenOptions::BitcodeFileToLink &F :
964  auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
965  if (!BCBuf) {
966  CI.getDiagnostics().Report(diag::err_cannot_open_file)
967  << F.Filename << BCBuf.getError().message();
968  LinkModules.clear();
969  return nullptr;
970  }
971 
973  getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
974  if (!ModuleOrErr) {
975  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
976  CI.getDiagnostics().Report(diag::err_cannot_open_file)
977  << F.Filename << EIB.message();
978  });
979  LinkModules.clear();
980  return nullptr;
981  }
982  LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
983  F.Internalize, F.LinkFlags});
984  }
985 
986  CoverageSourceInfo *CoverageInfo = nullptr;
987  // Add the preprocessor callback only when the coverage mapping is generated.
988  if (CI.getCodeGenOpts().CoverageMapping) {
989  CoverageInfo = new CoverageSourceInfo;
991  std::unique_ptr<PPCallbacks>(CoverageInfo));
992  }
993 
994  std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
995  BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
997  CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
998  std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
999  BEConsumer = Result.get();
1000 
1001  // Enable generating macro debug info only when debug info is not disabled and
1002  // also macro debug info is enabled.
1003  if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1004  CI.getCodeGenOpts().MacroDebugInfo) {
1005  std::unique_ptr<PPCallbacks> Callbacks =
1006  std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
1007  CI.getPreprocessor());
1008  CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
1009  }
1010 
1011  return std::move(Result);
1012 }
1013 
1014 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
1015  void *Context,
1016  unsigned LocCookie) {
1017  SM.print(nullptr, llvm::errs());
1018 
1019  auto Diags = static_cast<DiagnosticsEngine *>(Context);
1020  unsigned DiagID;
1021  switch (SM.getKind()) {
1022  case llvm::SourceMgr::DK_Error:
1023  DiagID = diag::err_fe_inline_asm;
1024  break;
1025  case llvm::SourceMgr::DK_Warning:
1026  DiagID = diag::warn_fe_inline_asm;
1027  break;
1028  case llvm::SourceMgr::DK_Note:
1029  DiagID = diag::note_fe_inline_asm;
1030  break;
1031  case llvm::SourceMgr::DK_Remark:
1032  llvm_unreachable("remarks unexpected");
1033  }
1034 
1035  Diags->Report(DiagID).AddString("cannot compile inline asm");
1036 }
1037 
1038 std::unique_ptr<llvm::Module>
1039 CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1042 
1043  // For ThinLTO backend invocations, ensure that the context
1044  // merges types based on ODR identifiers. We also need to read
1045  // the correct module out of a multi-module bitcode file.
1046  if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1047  VMContext->enableDebugTypeODRUniquing();
1048 
1049  auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1050  unsigned DiagID =
1052  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1053  CI.getDiagnostics().Report(DiagID) << EIB.message();
1054  });
1055  return {};
1056  };
1057 
1058  Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1059  if (!BMsOrErr)
1060  return DiagErrors(BMsOrErr.takeError());
1061  BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr);
1062  // We have nothing to do if the file contains no ThinLTO module. This is
1063  // possible if ThinLTO compilation was not able to split module. Content of
1064  // the file was already processed by indexing and will be passed to the
1065  // linker using merged object file.
1066  if (!Bm) {
1067  auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1068  M->setTargetTriple(CI.getTargetOpts().Triple);
1069  return M;
1070  }
1072  Bm->parseModule(*VMContext);
1073  if (!MOrErr)
1074  return DiagErrors(MOrErr.takeError());
1075  return std::move(*MOrErr);
1076  }
1077 
1078  llvm::SMDiagnostic Err;
1079  if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1080  return M;
1081 
1082  // Translate from the diagnostic info to the SourceManager location if
1083  // available.
1084  // TODO: Unify this with ConvertBackendLocation()
1085  SourceLocation Loc;
1086  if (Err.getLineNo() > 0) {
1087  assert(Err.getColumnNo() >= 0);
1089  Err.getLineNo(), Err.getColumnNo() + 1);
1090  }
1091 
1092  // Strip off a leading diagnostic code if there is one.
1093  StringRef Msg = Err.getMessage();
1094  if (Msg.startswith("error: "))
1095  Msg = Msg.substr(7);
1096 
1097  unsigned DiagID =
1099 
1100  CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1101  return {};
1102 }
1103 
1105  // If this is an IR file, we have to treat it specially.
1106  if (getCurrentFileKind().getLanguage() == Language::LLVM_IR) {
1107  BackendAction BA = static_cast<BackendAction>(Act);
1109  auto &CodeGenOpts = CI.getCodeGenOpts();
1110  auto &Diagnostics = CI.getDiagnostics();
1111  std::unique_ptr<raw_pwrite_stream> OS =
1112  GetOutputStream(CI, getCurrentFile(), BA);
1113  if (BA != Backend_EmitNothing && !OS)
1114  return;
1115 
1116  bool Invalid;
1118  FileID FID = SM.getMainFileID();
1119  const llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
1120  if (Invalid)
1121  return;
1122 
1123  TheModule = loadModule(*MainFile);
1124  if (!TheModule)
1125  return;
1126 
1127  const TargetOptions &TargetOpts = CI.getTargetOpts();
1128  if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1129  Diagnostics.Report(SourceLocation(),
1130  diag::warn_fe_override_module)
1131  << TargetOpts.Triple;
1132  TheModule->setTargetTriple(TargetOpts.Triple);
1133  }
1134 
1135  EmbedBitcode(TheModule.get(), CodeGenOpts,
1136  MainFile->getMemBufferRef());
1137 
1138  LLVMContext &Ctx = TheModule->getContext();
1139  Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
1140  &Diagnostics);
1141 
1142  // Set clang diagnostic handler. To do this we need to create a fake
1143  // BackendConsumer.
1146  CI.getTargetOpts(), CI.getLangOpts(),
1148  std::move(LinkModules), *VMContext, nullptr);
1149  Ctx.setDiagnosticHandler(
1150  std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1151 
1153  setupOptimizationRemarks(
1154  Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1155  CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1156  CodeGenOpts.DiagnosticsHotnessThreshold);
1157 
1158  if (Error E = OptRecordFileOrErr.takeError()) {
1159  reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1160  return;
1161  }
1162  std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1163  std::move(*OptRecordFileOrErr);
1164 
1165  EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts,
1166  TargetOpts, CI.getLangOpts(),
1167  CI.getTarget().getDataLayout(), TheModule.get(), BA,
1168  std::move(OS));
1169 
1170  if (OptRecordFile)
1171  OptRecordFile->keep();
1172  return;
1173  }
1174 
1175  // Otherwise follow the normal AST path.
1177 }
1178 
1179 //
1180 
1181 void EmitAssemblyAction::anchor() { }
1182 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1183  : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1184 
1185 void EmitBCAction::anchor() { }
1186 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1187  : CodeGenAction(Backend_EmitBC, _VMContext) {}
1188 
1189 void EmitLLVMAction::anchor() { }
1190 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1191  : CodeGenAction(Backend_EmitLL, _VMContext) {}
1192 
1193 void EmitLLVMOnlyAction::anchor() { }
1194 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1195  : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1196 
1197 void EmitCodeGenOnlyAction::anchor() { }
1198 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1199  : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1200 
1201 void EmitObjAction::anchor() { }
1202 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1203  : CodeGenAction(Backend_EmitObj, _VMContext) {}
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID)
Specialized handlers for optimization remarks.
Defines the clang::ASTContext interface.
LangOptions & getLangOpts()
void HandleInlineFunctionDefinition(FunctionDecl *D) override
This callback is invoked each time an inline (method or friend) function definition in a class is com...
Represents a function declaration or definition.
Definition: Decl.h:1783
PreprocessorOptions & getPreprocessorOpts()
static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM, void *Context, unsigned LocCookie)
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:879
bool isPassedOptRemarkEnabled(StringRef PassName) const override
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:171
bool hasIRSupport() const override
Does this action support use with IR files?
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs...
Definition: ASTConsumer.h:33
Defines the clang::FileManager interface and associated types.
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:33
Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be placed into a PointerUnion...
Definition: Dominators.h:30
Run CodeGen, but don&#39;t emit anything.
Definition: BackendUtil.h:35
void EndSourceFileAction() override
Callback at the end of processing a single input.
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...
Defines the SourceManager interface.
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
bool HandleTopLevelDecl(DeclGroupRef D) override
HandleTopLevelDecl - Handle the specified top-level declaration.
friend class BackendConsumer
Definition: CodeGenAction.h:26
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
Stores additional source code information like skipped ranges which is required by the coverage mappi...
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1300
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions CodeGenOpts)
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:707
void HandleTagDeclRequiredDefinition(const TagDecl *D) override
This callback is invoked the first time each TagDecl is required to be complete.
std::unique_ptr< llvm::Module > takeModule()
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Don&#39;t emit anything (benchmarking mode)
Definition: BackendUtil.h:34
Represents a variable declaration or definition.
Definition: Decl.h:820
Options for controlling the target.
Definition: TargetOptions.h:26
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing)...
Definition: DiagnosticIDs.h:79
void HandleTagDeclDefinition(TagDecl *D) override
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Don&#39;t generate debug info.
bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D)
Specialized handler for StackSize diagnostic.
FileManager & getFileManager() const
bool isAnyRemarkEnabled() const override
#define ComputeDiagRemarkID(Severity, GroupName, DiagID)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:168
Emit LLVM bitcode files.
Definition: BackendUtil.h:32
static SourceLocation getFromRawEncoding(unsigned Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
void OptimizationFailureHandler(const llvm::DiagnosticInfoOptimizationFailure &D)
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
Definition: Format.h:2445
void CompleteTentativeDefinition(VarDecl *D) override
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
CodeGenOptions & getCodeGenOpts()
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:53
BackendAction
Definition: BackendUtil.h:30
CompilerInstance & getCompilerInstance() const
FrontendOptions & getFrontendOpts()
void CompleteExternalDeclaration(VarDecl *D) override
CompleteExternalDeclaration - Callback invoked at the end of a translation unit to notify the consume...
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
iterator begin()
Definition: DeclGroup.h:99
void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI)
This function is invoked when the backend needs to report something to the user.
llvm::Error Error
CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
void HandleInterestingDecl(DeclGroupRef D) override
HandleInterestingDecl - Handle the specified interesting declaration.
bool isMissedOptRemarkEnabled(StringRef PassName) const override
static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM, void *Context, unsigned LocCookie)
The primary public interface to the Clang code generator.
Definition: ModuleBuilder.h:43
HeaderSearchOptions & getHeaderSearchOpts()
bool handleDiagnostics(const DiagnosticInfo &DI) override
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1053
BackendConsumer * BEConsumer
Definition: CodeGenAction.h:80
StringRef Filename
Definition: Format.cpp:1825
EmitLLVMAction(llvm::LLVMContext *_VMContext=nullptr)
unsigned Offset
Definition: Format.cpp:1827
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
const AnnotatedLine * Line
CodeGenAction(unsigned _Act, llvm::LLVMContext *_VMContext=nullptr)
Create a new code generation action.
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, unsigned LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
unsigned ShowTimers
Show timers for individual actions.
Defines the clang::Preprocessor interface.
Emit native object files.
Definition: BackendUtil.h:36
EmitObjAction(llvm::LLVMContext *_VMContext=nullptr)
void OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D)
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
InputKind getCurrentFileKind() const
The result type of a method or function.
static std::unique_ptr< raw_pwrite_stream > GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action)
const SourceManager & SM
Definition: Format.cpp:1685
EmitBCAction(llvm::LLVMContext *_VMContext=nullptr)
llvm::Module * getModule() const
static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, SourceManager &CSM)
ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr buffer to be a valid FullS...
Emit native assembly files.
Definition: BackendUtil.h:31
void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D)
Specialized handler for unsupported backend feature diagnostic.
EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
void AssignInheritanceModel(CXXRecordDecl *RD) override
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3219
BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, const TargetOptions &TargetOpts, const LangOptions &LangOpts, bool TimePasses, SmallVector< LinkModule, 4 > LinkModules, LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D)
Specialized handler for misexpect warnings.
const llvm::DataLayout & getDataLayout() const
Definition: TargetInfo.h:998
#define ComputeDiagID(Severity, GroupName, DiagID)
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:782
std::vector< BitcodeFileToLink > LinkBitcodeFiles
The files specified here are linked in to the module before optimizations.
EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
std::unique_ptr< llvm::Module > takeModule()
Take the generated LLVM module, for use after the action has been run.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
const llvm::MemoryBuffer * getBuffer(FileID FID, SourceLocation Loc, bool *Invalid=nullptr) const
Return the buffer for the specified FileID.
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
FileManager & getFileManager() const
Return the current file manager to the caller.
bool FrontendTimesIsEnabled
If the user specifies the -ftime-report argument on an Clang command line then the value of this bool...
FileID getMainFileID() const
Returns the FileID of the main source file.
StringRef getCurrentFile() const
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, const llvm::DataLayout &TDesc, llvm::Module *M, BackendAction Action, std::unique_ptr< raw_pwrite_stream > OS)
SourceManager & getSourceManager() const
Return the current source manager.
void InlineAsmDiagHandler2(const llvm::SMDiagnostic &, SourceLocation LocCookie)
InlineAsmDiagHandler2 - This function is invoked when the backend hits an error parsing inline asm...
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...
llvm::Expected< llvm::BitcodeModule > FindThinLTOModule(llvm::MemoryBufferRef MBRef)
void HandleVTable(CXXRecordDecl *RD) override
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
void Initialize(ASTContext &Ctx) override
Initialize - This is called to initialize the consumer, providing the ASTContext. ...
TargetInfo & getTarget() const
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="")
Create the default output file (from the invocation&#39;s options) and add it to the list of tracked outp...
SourceManager & getSourceManager()
Definition: ASTContext.h:679
Preprocessor & getPreprocessor() const
Return the current preprocessor.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
EmitAssemblyAction(llvm::LLVMContext *_VMContext=nullptr)
Represents a C++ struct/union/class.
Definition: DeclCXX.h:253
llvm::LLVMContext * takeLLVMContext()
Take the LLVM context used by this action.
CodeGenerator * getCodeGenerator()
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
Defines the clang::TargetInfo interface.
A SourceLocation and its associated SourceManager.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
void HandleTranslationUnit(ASTContext &C) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, const TargetOptions &TargetOpts, const LangOptions &LangOpts, bool TimePasses, const std::string &InFile, SmallVector< LinkModule, 4 > LinkModules, std::unique_ptr< raw_pwrite_stream > OS, LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
A trivial tuple used to represent a source range.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
bool isAnalysisRemarkEnabled(StringRef PassName) const override
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
TargetOptions & getTargetOpts()
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
This class handles loading and caching of source files into memory.
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Definition: DeclBase.h:1178