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