1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "CoverageMappingGen.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/DeclGroup.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/CodeGen/BackendUtil.h"
19 #include "clang/CodeGen/CodeGenAction.h"
20 #include "clang/CodeGen/ModuleBuilder.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Frontend/FrontendDiagnostic.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Bitcode/ReaderWriter.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IRReader/IRReader.h"
32 #include "llvm/Linker/Linker.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/Timer.h"
38 using namespace clang;
42 class BackendConsumer : public ASTConsumer {
43 virtual void anchor();
44 DiagnosticsEngine &Diags;
46 const CodeGenOptions &CodeGenOpts;
47 const TargetOptions &TargetOpts;
48 const LangOptions &LangOpts;
49 raw_pwrite_stream *AsmOutStream;
52 Timer LLVMIRGeneration;
54 std::unique_ptr<CodeGenerator> Gen;
56 std::unique_ptr<llvm::Module> TheModule;
57 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
60 // This is here so that the diagnostic printer knows the module a diagnostic
62 llvm::Module *CurLinkModule = nullptr;
66 BackendAction Action, DiagnosticsEngine &Diags,
67 const HeaderSearchOptions &HeaderSearchOpts,
68 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
69 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
70 bool TimePasses, const std::string &InFile,
71 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
72 raw_pwrite_stream *OS, LLVMContext &C,
73 CoverageSourceInfo *CoverageInfo = nullptr)
74 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
75 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
76 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
77 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
78 CodeGenOpts, C, CoverageInfo)) {
79 llvm::TimePassesIsEnabled = TimePasses;
80 for (auto &I : LinkModules)
81 this->LinkModules.push_back(
82 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
84 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
85 void releaseLinkModules() {
86 for (auto &I : LinkModules)
90 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
91 Gen->HandleCXXStaticMemberVarInstantiation(VD);
94 void Initialize(ASTContext &Ctx) override {
95 assert(!Context && "initialized multiple times");
99 if (llvm::TimePassesIsEnabled)
100 LLVMIRGeneration.startTimer();
102 Gen->Initialize(Ctx);
104 TheModule.reset(Gen->GetModule());
106 if (llvm::TimePassesIsEnabled)
107 LLVMIRGeneration.stopTimer();
110 bool HandleTopLevelDecl(DeclGroupRef D) override {
111 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
112 Context->getSourceManager(),
113 "LLVM IR generation of declaration");
115 if (llvm::TimePassesIsEnabled)
116 LLVMIRGeneration.startTimer();
118 Gen->HandleTopLevelDecl(D);
120 if (llvm::TimePassesIsEnabled)
121 LLVMIRGeneration.stopTimer();
126 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
127 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
128 Context->getSourceManager(),
129 "LLVM IR generation of inline method");
130 if (llvm::TimePassesIsEnabled)
131 LLVMIRGeneration.startTimer();
133 Gen->HandleInlineMethodDefinition(D);
135 if (llvm::TimePassesIsEnabled)
136 LLVMIRGeneration.stopTimer();
139 void HandleTranslationUnit(ASTContext &C) override {
141 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
142 if (llvm::TimePassesIsEnabled)
143 LLVMIRGeneration.startTimer();
145 Gen->HandleTranslationUnit(C);
147 if (llvm::TimePassesIsEnabled)
148 LLVMIRGeneration.stopTimer();
151 // Silently ignore if we weren't initialized for some reason.
155 // Make sure IR generation is happy with the module. This is released by
156 // the module provider.
157 llvm::Module *M = Gen->ReleaseModule();
159 // The module has been released by IR gen on failures, do not double
165 assert(TheModule.get() == M &&
166 "Unexpected module change during IR generation");
168 // Install an inline asm handler so that diagnostics get printed through
169 // our diagnostics hooks.
170 LLVMContext &Ctx = TheModule->getContext();
171 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
172 Ctx.getInlineAsmDiagnosticHandler();
173 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
174 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
176 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
177 Ctx.getDiagnosticHandler();
178 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
179 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
181 // Link LinkModule into this module if present, preserving its validity.
182 for (auto &I : LinkModules) {
183 unsigned LinkFlags = I.first;
184 CurLinkModule = I.second.get();
185 if (Linker::linkModules(*M, std::move(I.second), LinkFlags))
189 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
190 C.getTargetInfo().getDataLayoutString(),
191 TheModule.get(), Action, AsmOutStream);
193 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
195 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
198 void HandleTagDeclDefinition(TagDecl *D) override {
199 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
200 Context->getSourceManager(),
201 "LLVM IR generation of declaration");
202 Gen->HandleTagDeclDefinition(D);
205 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
206 Gen->HandleTagDeclRequiredDefinition(D);
209 void CompleteTentativeDefinition(VarDecl *D) override {
210 Gen->CompleteTentativeDefinition(D);
213 void AssignInheritanceModel(CXXRecordDecl *RD) override {
214 Gen->AssignInheritanceModel(RD);
217 void HandleVTable(CXXRecordDecl *RD) override {
218 Gen->HandleVTable(RD);
221 void HandleLinkerOption(llvm::StringRef Opts) override {
222 Gen->HandleLinkerOption(Opts);
225 void HandleDetectMismatch(llvm::StringRef Name,
226 llvm::StringRef Value) override {
227 Gen->HandleDetectMismatch(Name, Value);
230 void HandleDependentLibrary(llvm::StringRef Opts) override {
231 Gen->HandleDependentLibrary(Opts);
234 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
235 unsigned LocCookie) {
236 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
237 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
240 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
242 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
245 /// Get the best possible source location to represent a diagnostic that
246 /// may have associated debug info.
248 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
249 bool &BadDebugInfo, StringRef &Filename,
250 unsigned &Line, unsigned &Column) const;
252 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
253 SourceLocation LocCookie);
255 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
256 /// \brief Specialized handler for InlineAsm diagnostic.
257 /// \return True if the diagnostic has been successfully reported, false
259 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
260 /// \brief Specialized handler for StackSize diagnostic.
261 /// \return True if the diagnostic has been successfully reported, false
263 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
264 /// \brief Specialized handler for unsupported backend feature diagnostic.
265 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
266 /// \brief Specialized handlers for optimization remarks.
267 /// Note that these handlers only accept remarks and they always handle
269 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
272 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
273 void OptimizationRemarkHandler(
274 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
275 void OptimizationRemarkHandler(
276 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
277 void OptimizationRemarkHandler(
278 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
279 void OptimizationRemarkHandler(
280 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
281 void OptimizationFailureHandler(
282 const llvm::DiagnosticInfoOptimizationFailure &D);
285 void BackendConsumer::anchor() {}
288 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
289 /// buffer to be a valid FullSourceLoc.
290 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
291 SourceManager &CSM) {
292 // Get both the clang and llvm source managers. The location is relative to
293 // a memory buffer that the LLVM Source Manager is handling, we need to add
294 // a copy to the Clang source manager.
295 const llvm::SourceMgr &LSM = *D.getSourceMgr();
297 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
298 // already owns its one and clang::SourceManager wants to own its one.
299 const MemoryBuffer *LBuf =
300 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
302 // Create the copy and transfer ownership to clang::SourceManager.
303 // TODO: Avoid copying files into memory.
304 std::unique_ptr<llvm::MemoryBuffer> CBuf =
305 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
306 LBuf->getBufferIdentifier());
307 // FIXME: Keep a file ID map instead of creating new IDs for each location.
308 FileID FID = CSM.createFileID(std::move(CBuf));
310 // Translate the offset into the file.
311 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
312 SourceLocation NewLoc =
313 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
314 return FullSourceLoc(NewLoc, CSM);
318 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
319 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
320 /// the temporary memory buffer that the inline asm parser has set up.
321 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
322 SourceLocation LocCookie) {
323 // There are a couple of different kinds of errors we could get here. First,
324 // we re-format the SMDiagnostic in terms of a clang diagnostic.
326 // Strip "error: " off the start of the message string.
327 StringRef Message = D.getMessage();
328 if (Message.startswith("error: "))
329 Message = Message.substr(7);
331 // If the SMDiagnostic has an inline asm source location, translate it.
333 if (D.getLoc() != SMLoc())
334 Loc = ConvertBackendLocation(D, Context->getSourceManager());
337 switch (D.getKind()) {
338 case llvm::SourceMgr::DK_Error:
339 DiagID = diag::err_fe_inline_asm;
341 case llvm::SourceMgr::DK_Warning:
342 DiagID = diag::warn_fe_inline_asm;
344 case llvm::SourceMgr::DK_Note:
345 DiagID = diag::note_fe_inline_asm;
348 // If this problem has clang-level source location information, report the
349 // issue in the source with a note showing the instantiated
351 if (LocCookie.isValid()) {
352 Diags.Report(LocCookie, DiagID).AddString(Message);
354 if (D.getLoc().isValid()) {
355 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
356 // Convert the SMDiagnostic ranges into SourceRange and attach them
357 // to the diagnostic.
358 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
359 unsigned Column = D.getColumnNo();
360 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
361 Loc.getLocWithOffset(Range.second - Column));
367 // Otherwise, report the backend issue as occurring in the generated .s file.
368 // If Loc is invalid, we still need to report the issue, it just gets no
370 Diags.Report(Loc, DiagID).AddString(Message);
373 #define ComputeDiagID(Severity, GroupName, DiagID) \
375 switch (Severity) { \
376 case llvm::DS_Error: \
377 DiagID = diag::err_fe_##GroupName; \
379 case llvm::DS_Warning: \
380 DiagID = diag::warn_fe_##GroupName; \
382 case llvm::DS_Remark: \
383 llvm_unreachable("'remark' severity not expected"); \
385 case llvm::DS_Note: \
386 DiagID = diag::note_fe_##GroupName; \
391 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
393 switch (Severity) { \
394 case llvm::DS_Error: \
395 DiagID = diag::err_fe_##GroupName; \
397 case llvm::DS_Warning: \
398 DiagID = diag::warn_fe_##GroupName; \
400 case llvm::DS_Remark: \
401 DiagID = diag::remark_fe_##GroupName; \
403 case llvm::DS_Note: \
404 DiagID = diag::note_fe_##GroupName; \
410 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
412 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
413 std::string Message = D.getMsgStr().str();
415 // If this problem has clang-level source location information, report the
416 // issue as being a problem in the source with a note showing the instantiated
418 SourceLocation LocCookie =
419 SourceLocation::getFromRawEncoding(D.getLocCookie());
420 if (LocCookie.isValid())
421 Diags.Report(LocCookie, DiagID).AddString(Message);
423 // Otherwise, report the backend diagnostic as occurring in the generated
425 // If Loc is invalid, we still need to report the diagnostic, it just gets
428 Diags.Report(Loc, DiagID).AddString(Message);
430 // We handled all the possible severities.
435 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
436 if (D.getSeverity() != llvm::DS_Warning)
437 // For now, the only support we have for StackSize diagnostic is warning.
438 // We do not know how to format other severities.
441 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
442 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
443 diag::warn_fe_frame_larger_than)
444 << D.getStackSize() << Decl::castToDeclContext(ND);
451 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
452 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
453 unsigned &Line, unsigned &Column) const {
454 SourceManager &SourceMgr = Context->getSourceManager();
455 FileManager &FileMgr = SourceMgr.getFileManager();
456 SourceLocation DILoc;
458 if (D.isLocationAvailable()) {
459 D.getLocation(&Filename, &Line, &Column);
460 const FileEntry *FE = FileMgr.getFile(Filename);
461 if (FE && Line > 0) {
462 // If -gcolumn-info was not used, Column will be 0. This upsets the
463 // source manager, so pass 1 if Column is not set.
464 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
466 BadDebugInfo = DILoc.isInvalid();
469 // If a location isn't available, try to approximate it using the associated
470 // function definition. We use the definition's right brace to differentiate
471 // from diagnostics that genuinely relate to the function itself.
472 FullSourceLoc Loc(DILoc, SourceMgr);
474 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
475 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
477 if (DILoc.isInvalid() && D.isLocationAvailable())
478 // If we were not able to translate the file:line:col information
479 // back to a SourceLocation, at least emit a note stating that
480 // we could not translate this location. This can happen in the
481 // case of #line directives.
482 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
488 void BackendConsumer::UnsupportedDiagHandler(
489 const llvm::DiagnosticInfoUnsupported &D) {
490 // We only support errors.
491 assert(D.getSeverity() == llvm::DS_Error);
494 unsigned Line, Column;
496 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
499 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
502 // If we were not able to translate the file:line:col information
503 // back to a SourceLocation, at least emit a note stating that
504 // we could not translate this location. This can happen in the
505 // case of #line directives.
506 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
507 << Filename << Line << Column;
510 void BackendConsumer::EmitOptimizationMessage(
511 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
512 // We only support warnings and remarks.
513 assert(D.getSeverity() == llvm::DS_Remark ||
514 D.getSeverity() == llvm::DS_Warning);
517 unsigned Line, Column;
518 bool BadDebugInfo = false;
519 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
522 Diags.Report(Loc, DiagID)
523 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
527 // If we were not able to translate the file:line:col information
528 // back to a SourceLocation, at least emit a note stating that
529 // we could not translate this location. This can happen in the
530 // case of #line directives.
531 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
532 << Filename << Line << Column;
535 void BackendConsumer::OptimizationRemarkHandler(
536 const llvm::DiagnosticInfoOptimizationRemark &D) {
537 // Optimization remarks are active only if the -Rpass flag has a regular
538 // expression that matches the name of the pass name in \p D.
539 if (CodeGenOpts.OptimizationRemarkPattern &&
540 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
541 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
544 void BackendConsumer::OptimizationRemarkHandler(
545 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
546 // Missed optimization remarks are active only if the -Rpass-missed
547 // flag has a regular expression that matches the name of the pass
549 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
550 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
551 EmitOptimizationMessage(D,
552 diag::remark_fe_backend_optimization_remark_missed);
555 void BackendConsumer::OptimizationRemarkHandler(
556 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
557 // Optimization analysis remarks are active if the pass name is set to
558 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
559 // regular expression that matches the name of the pass name in \p D.
561 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
562 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
563 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
564 EmitOptimizationMessage(
565 D, diag::remark_fe_backend_optimization_remark_analysis);
568 void BackendConsumer::OptimizationRemarkHandler(
569 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
570 // Optimization analysis remarks are active if the pass name is set to
571 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
572 // regular expression that matches the name of the pass name in \p D.
574 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
575 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
576 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
577 EmitOptimizationMessage(
578 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
581 void BackendConsumer::OptimizationRemarkHandler(
582 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
583 // Optimization analysis remarks are active if the pass name is set to
584 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
585 // regular expression that matches the name of the pass name in \p D.
587 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
588 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
589 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
590 EmitOptimizationMessage(
591 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
594 void BackendConsumer::OptimizationFailureHandler(
595 const llvm::DiagnosticInfoOptimizationFailure &D) {
596 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
599 /// \brief This function is invoked when the backend needs
600 /// to report something to the user.
601 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
602 unsigned DiagID = diag::err_fe_inline_asm;
603 llvm::DiagnosticSeverity Severity = DI.getSeverity();
604 // Get the diagnostic ID based.
605 switch (DI.getKind()) {
606 case llvm::DK_InlineAsm:
607 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
609 ComputeDiagID(Severity, inline_asm, DiagID);
611 case llvm::DK_StackSize:
612 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
614 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
617 assert(CurLinkModule);
618 // FIXME: stop eating the warnings and notes.
619 if (Severity != DS_Error)
621 DiagID = diag::err_fe_cannot_link_module;
623 case llvm::DK_OptimizationRemark:
624 // Optimization remarks are always handled completely by this
625 // handler. There is no generic way of emitting them.
626 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
628 case llvm::DK_OptimizationRemarkMissed:
629 // Optimization remarks are always handled completely by this
630 // handler. There is no generic way of emitting them.
631 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
633 case llvm::DK_OptimizationRemarkAnalysis:
634 // Optimization remarks are always handled completely by this
635 // handler. There is no generic way of emitting them.
636 OptimizationRemarkHandler(
637 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
639 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
640 // Optimization remarks are always handled completely by this
641 // handler. There is no generic way of emitting them.
642 OptimizationRemarkHandler(
643 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
645 case llvm::DK_OptimizationRemarkAnalysisAliasing:
646 // Optimization remarks are always handled completely by this
647 // handler. There is no generic way of emitting them.
648 OptimizationRemarkHandler(
649 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
651 case llvm::DK_OptimizationFailure:
652 // Optimization failures are always handled completely by this
654 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
656 case llvm::DK_Unsupported:
657 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
660 // Plugin IDs are not bound to any value as they are set dynamically.
661 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
664 std::string MsgStorage;
666 raw_string_ostream Stream(MsgStorage);
667 DiagnosticPrinterRawOStream DP(Stream);
671 if (DiagID == diag::err_fe_cannot_link_module) {
672 Diags.Report(diag::err_fe_cannot_link_module)
673 << CurLinkModule->getModuleIdentifier() << MsgStorage;
677 // Report the backend message using the usual diagnostic mechanism.
679 Diags.Report(Loc, DiagID).AddString(MsgStorage);
683 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
684 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
685 OwnsVMContext(!_VMContext) {}
687 CodeGenAction::~CodeGenAction() {
693 bool CodeGenAction::hasIRSupport() const { return true; }
695 void CodeGenAction::EndSourceFileAction() {
696 // If the consumer creation failed, do nothing.
697 if (!getCompilerInstance().hasASTConsumer())
700 // Take back ownership of link modules we passed to consumer.
701 if (!LinkModules.empty())
702 BEConsumer->releaseLinkModules();
704 // Steal the module from the consumer.
705 TheModule = BEConsumer->takeModule();
708 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
709 return std::move(TheModule);
712 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
713 OwnsVMContext = false;
717 static raw_pwrite_stream *
718 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
720 case Backend_EmitAssembly:
721 return CI.createDefaultOutputFile(false, InFile, "s");
723 return CI.createDefaultOutputFile(false, InFile, "ll");
725 return CI.createDefaultOutputFile(true, InFile, "bc");
726 case Backend_EmitNothing:
728 case Backend_EmitMCNull:
729 return CI.createNullOutputFile();
730 case Backend_EmitObj:
731 return CI.createDefaultOutputFile(true, InFile, "o");
734 llvm_unreachable("Invalid action!");
737 std::unique_ptr<ASTConsumer>
738 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
739 BackendAction BA = static_cast<BackendAction>(Act);
740 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
741 if (BA != Backend_EmitNothing && !OS)
744 // Load bitcode modules to link with, if we need to.
745 if (LinkModules.empty())
746 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
747 const std::string &LinkBCFile = I.second;
749 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
751 CI.getDiagnostics().Report(diag::err_cannot_open_file)
752 << LinkBCFile << BCBuf.getError().message();
757 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
758 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
759 if (std::error_code EC = ModuleOrErr.getError()) {
760 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
765 addLinkModule(ModuleOrErr.get().release(), I.first);
768 CoverageSourceInfo *CoverageInfo = nullptr;
769 // Add the preprocessor callback only when the coverage mapping is generated.
770 if (CI.getCodeGenOpts().CoverageMapping) {
771 CoverageInfo = new CoverageSourceInfo;
772 CI.getPreprocessor().addPPCallbacks(
773 std::unique_ptr<PPCallbacks>(CoverageInfo));
776 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
777 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
778 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
779 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
780 OS, *VMContext, CoverageInfo));
781 BEConsumer = Result.get();
782 return std::move(Result);
785 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
787 unsigned LocCookie) {
788 SM.print(nullptr, llvm::errs());
791 void CodeGenAction::ExecuteAction() {
792 // If this is an IR file, we have to treat it specially.
793 if (getCurrentFileKind() == IK_LLVM_IR) {
794 BackendAction BA = static_cast<BackendAction>(Act);
795 CompilerInstance &CI = getCompilerInstance();
796 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
797 if (BA != Backend_EmitNothing && !OS)
801 SourceManager &SM = CI.getSourceManager();
802 FileID FID = SM.getMainFileID();
803 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
807 llvm::SMDiagnostic Err;
808 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
810 // Translate from the diagnostic info to the SourceManager location if
812 // TODO: Unify this with ConvertBackendLocation()
814 if (Err.getLineNo() > 0) {
815 assert(Err.getColumnNo() >= 0);
816 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
817 Err.getLineNo(), Err.getColumnNo() + 1);
820 // Strip off a leading diagnostic code if there is one.
821 StringRef Msg = Err.getMessage();
822 if (Msg.startswith("error: "))
826 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
828 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
831 const TargetOptions &TargetOpts = CI.getTargetOpts();
832 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
833 CI.getDiagnostics().Report(SourceLocation(),
834 diag::warn_fe_override_module)
835 << TargetOpts.Triple;
836 TheModule->setTargetTriple(TargetOpts.Triple);
839 LLVMContext &Ctx = TheModule->getContext();
840 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
841 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
842 CI.getLangOpts(), CI.getTarget().getDataLayoutString(),
843 TheModule.get(), BA, OS);
847 // Otherwise follow the normal AST path.
848 this->ASTFrontendAction::ExecuteAction();
853 void EmitAssemblyAction::anchor() { }
854 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
855 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
857 void EmitBCAction::anchor() { }
858 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
859 : CodeGenAction(Backend_EmitBC, _VMContext) {}
861 void EmitLLVMAction::anchor() { }
862 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
863 : CodeGenAction(Backend_EmitLL, _VMContext) {}
865 void EmitLLVMOnlyAction::anchor() { }
866 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
867 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
869 void EmitCodeGenOnlyAction::anchor() { }
870 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
871 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
873 void EmitObjAction::anchor() { }
874 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
875 : CodeGenAction(Backend_EmitObj, _VMContext) {}