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 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
59 // This is here so that the diagnostic printer knows the module a diagnostic
61 llvm::Module *CurLinkModule = nullptr;
65 BackendAction Action, DiagnosticsEngine &Diags,
66 const HeaderSearchOptions &HeaderSearchOpts,
67 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
68 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
69 bool TimePasses, const std::string &InFile,
70 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
71 raw_pwrite_stream *OS, LLVMContext &C,
72 CoverageSourceInfo *CoverageInfo = nullptr)
73 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
74 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
75 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
76 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
77 CodeGenOpts, C, CoverageInfo)) {
78 llvm::TimePassesIsEnabled = TimePasses;
79 for (auto &I : LinkModules)
80 this->LinkModules.push_back(
81 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
83 llvm::Module *getModule() const { return Gen->GetModule(); }
84 std::unique_ptr<llvm::Module> takeModule() {
85 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
87 void releaseLinkModules() {
88 for (auto &I : LinkModules)
92 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
93 Gen->HandleCXXStaticMemberVarInstantiation(VD);
96 void Initialize(ASTContext &Ctx) override {
97 assert(!Context && "initialized multiple times");
101 if (llvm::TimePassesIsEnabled)
102 LLVMIRGeneration.startTimer();
104 Gen->Initialize(Ctx);
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 HandleInlineFunctionDefinition(FunctionDecl *D) override {
127 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
128 Context->getSourceManager(),
129 "LLVM IR generation of inline function");
130 if (llvm::TimePassesIsEnabled)
131 LLVMIRGeneration.startTimer();
133 Gen->HandleInlineFunctionDefinition(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 // Install an inline asm handler so that diagnostics get printed through
156 // our diagnostics hooks.
157 LLVMContext &Ctx = getModule()->getContext();
158 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
159 Ctx.getInlineAsmDiagnosticHandler();
160 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
161 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
163 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
164 Ctx.getDiagnosticHandler();
165 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
166 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
168 // Link LinkModule into this module if present, preserving its validity.
169 for (auto &I : LinkModules) {
170 unsigned LinkFlags = I.first;
171 CurLinkModule = I.second.get();
172 if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
176 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
177 C.getTargetInfo().getDataLayout(),
178 getModule(), Action, AsmOutStream);
180 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
182 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
185 void HandleTagDeclDefinition(TagDecl *D) override {
186 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
187 Context->getSourceManager(),
188 "LLVM IR generation of declaration");
189 Gen->HandleTagDeclDefinition(D);
192 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
193 Gen->HandleTagDeclRequiredDefinition(D);
196 void CompleteTentativeDefinition(VarDecl *D) override {
197 Gen->CompleteTentativeDefinition(D);
200 void AssignInheritanceModel(CXXRecordDecl *RD) override {
201 Gen->AssignInheritanceModel(RD);
204 void HandleVTable(CXXRecordDecl *RD) override {
205 Gen->HandleVTable(RD);
208 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
209 unsigned LocCookie) {
210 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
211 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
214 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
216 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
219 /// Get the best possible source location to represent a diagnostic that
220 /// may have associated debug info.
222 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
223 bool &BadDebugInfo, StringRef &Filename,
224 unsigned &Line, unsigned &Column) const;
226 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
227 SourceLocation LocCookie);
229 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
230 /// \brief Specialized handler for InlineAsm diagnostic.
231 /// \return True if the diagnostic has been successfully reported, false
233 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
234 /// \brief Specialized handler for StackSize diagnostic.
235 /// \return True if the diagnostic has been successfully reported, false
237 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
238 /// \brief Specialized handler for unsupported backend feature diagnostic.
239 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
240 /// \brief Specialized handlers for optimization remarks.
241 /// Note that these handlers only accept remarks and they always handle
243 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
246 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
247 void OptimizationRemarkHandler(
248 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
249 void OptimizationRemarkHandler(
250 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
251 void OptimizationRemarkHandler(
252 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
253 void OptimizationRemarkHandler(
254 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
255 void OptimizationFailureHandler(
256 const llvm::DiagnosticInfoOptimizationFailure &D);
259 void BackendConsumer::anchor() {}
262 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
263 /// buffer to be a valid FullSourceLoc.
264 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
265 SourceManager &CSM) {
266 // Get both the clang and llvm source managers. The location is relative to
267 // a memory buffer that the LLVM Source Manager is handling, we need to add
268 // a copy to the Clang source manager.
269 const llvm::SourceMgr &LSM = *D.getSourceMgr();
271 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
272 // already owns its one and clang::SourceManager wants to own its one.
273 const MemoryBuffer *LBuf =
274 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
276 // Create the copy and transfer ownership to clang::SourceManager.
277 // TODO: Avoid copying files into memory.
278 std::unique_ptr<llvm::MemoryBuffer> CBuf =
279 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
280 LBuf->getBufferIdentifier());
281 // FIXME: Keep a file ID map instead of creating new IDs for each location.
282 FileID FID = CSM.createFileID(std::move(CBuf));
284 // Translate the offset into the file.
285 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
286 SourceLocation NewLoc =
287 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
288 return FullSourceLoc(NewLoc, CSM);
292 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
293 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
294 /// the temporary memory buffer that the inline asm parser has set up.
295 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
296 SourceLocation LocCookie) {
297 // There are a couple of different kinds of errors we could get here. First,
298 // we re-format the SMDiagnostic in terms of a clang diagnostic.
300 // Strip "error: " off the start of the message string.
301 StringRef Message = D.getMessage();
302 if (Message.startswith("error: "))
303 Message = Message.substr(7);
305 // If the SMDiagnostic has an inline asm source location, translate it.
307 if (D.getLoc() != SMLoc())
308 Loc = ConvertBackendLocation(D, Context->getSourceManager());
311 switch (D.getKind()) {
312 case llvm::SourceMgr::DK_Error:
313 DiagID = diag::err_fe_inline_asm;
315 case llvm::SourceMgr::DK_Warning:
316 DiagID = diag::warn_fe_inline_asm;
318 case llvm::SourceMgr::DK_Note:
319 DiagID = diag::note_fe_inline_asm;
322 // If this problem has clang-level source location information, report the
323 // issue in the source with a note showing the instantiated
325 if (LocCookie.isValid()) {
326 Diags.Report(LocCookie, DiagID).AddString(Message);
328 if (D.getLoc().isValid()) {
329 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
330 // Convert the SMDiagnostic ranges into SourceRange and attach them
331 // to the diagnostic.
332 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
333 unsigned Column = D.getColumnNo();
334 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
335 Loc.getLocWithOffset(Range.second - Column));
341 // Otherwise, report the backend issue as occurring in the generated .s file.
342 // If Loc is invalid, we still need to report the issue, it just gets no
344 Diags.Report(Loc, DiagID).AddString(Message);
347 #define ComputeDiagID(Severity, GroupName, DiagID) \
349 switch (Severity) { \
350 case llvm::DS_Error: \
351 DiagID = diag::err_fe_##GroupName; \
353 case llvm::DS_Warning: \
354 DiagID = diag::warn_fe_##GroupName; \
356 case llvm::DS_Remark: \
357 llvm_unreachable("'remark' severity not expected"); \
359 case llvm::DS_Note: \
360 DiagID = diag::note_fe_##GroupName; \
365 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
367 switch (Severity) { \
368 case llvm::DS_Error: \
369 DiagID = diag::err_fe_##GroupName; \
371 case llvm::DS_Warning: \
372 DiagID = diag::warn_fe_##GroupName; \
374 case llvm::DS_Remark: \
375 DiagID = diag::remark_fe_##GroupName; \
377 case llvm::DS_Note: \
378 DiagID = diag::note_fe_##GroupName; \
384 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
386 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
387 std::string Message = D.getMsgStr().str();
389 // If this problem has clang-level source location information, report the
390 // issue as being a problem in the source with a note showing the instantiated
392 SourceLocation LocCookie =
393 SourceLocation::getFromRawEncoding(D.getLocCookie());
394 if (LocCookie.isValid())
395 Diags.Report(LocCookie, DiagID).AddString(Message);
397 // Otherwise, report the backend diagnostic as occurring in the generated
399 // If Loc is invalid, we still need to report the diagnostic, it just gets
402 Diags.Report(Loc, DiagID).AddString(Message);
404 // We handled all the possible severities.
409 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
410 if (D.getSeverity() != llvm::DS_Warning)
411 // For now, the only support we have for StackSize diagnostic is warning.
412 // We do not know how to format other severities.
415 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
416 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
417 diag::warn_fe_frame_larger_than)
418 << D.getStackSize() << Decl::castToDeclContext(ND);
425 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
426 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
427 unsigned &Line, unsigned &Column) const {
428 SourceManager &SourceMgr = Context->getSourceManager();
429 FileManager &FileMgr = SourceMgr.getFileManager();
430 SourceLocation DILoc;
432 if (D.isLocationAvailable()) {
433 D.getLocation(&Filename, &Line, &Column);
434 const FileEntry *FE = FileMgr.getFile(Filename);
435 if (FE && Line > 0) {
436 // If -gcolumn-info was not used, Column will be 0. This upsets the
437 // source manager, so pass 1 if Column is not set.
438 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
440 BadDebugInfo = DILoc.isInvalid();
443 // If a location isn't available, try to approximate it using the associated
444 // function definition. We use the definition's right brace to differentiate
445 // from diagnostics that genuinely relate to the function itself.
446 FullSourceLoc Loc(DILoc, SourceMgr);
448 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
449 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
451 if (DILoc.isInvalid() && D.isLocationAvailable())
452 // If we were not able to translate the file:line:col information
453 // back to a SourceLocation, at least emit a note stating that
454 // we could not translate this location. This can happen in the
455 // case of #line directives.
456 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
462 void BackendConsumer::UnsupportedDiagHandler(
463 const llvm::DiagnosticInfoUnsupported &D) {
464 // We only support errors.
465 assert(D.getSeverity() == llvm::DS_Error);
468 unsigned Line, Column;
470 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
473 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
476 // If we were not able to translate the file:line:col information
477 // back to a SourceLocation, at least emit a note stating that
478 // we could not translate this location. This can happen in the
479 // case of #line directives.
480 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
481 << Filename << Line << Column;
484 void BackendConsumer::EmitOptimizationMessage(
485 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
486 // We only support warnings and remarks.
487 assert(D.getSeverity() == llvm::DS_Remark ||
488 D.getSeverity() == llvm::DS_Warning);
491 unsigned Line, Column;
492 bool BadDebugInfo = false;
493 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
496 Diags.Report(Loc, DiagID)
497 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
501 // If we were not able to translate the file:line:col information
502 // back to a SourceLocation, at least emit a note stating that
503 // we could not translate this location. This can happen in the
504 // case of #line directives.
505 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
506 << Filename << Line << Column;
509 void BackendConsumer::OptimizationRemarkHandler(
510 const llvm::DiagnosticInfoOptimizationRemark &D) {
511 // Optimization remarks are active only if the -Rpass flag has a regular
512 // expression that matches the name of the pass name in \p D.
513 if (CodeGenOpts.OptimizationRemarkPattern &&
514 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
515 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
518 void BackendConsumer::OptimizationRemarkHandler(
519 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
520 // Missed optimization remarks are active only if the -Rpass-missed
521 // flag has a regular expression that matches the name of the pass
523 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
524 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
525 EmitOptimizationMessage(D,
526 diag::remark_fe_backend_optimization_remark_missed);
529 void BackendConsumer::OptimizationRemarkHandler(
530 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
531 // Optimization analysis remarks are active if the pass name is set to
532 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
533 // regular expression that matches the name of the pass name in \p D.
535 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
536 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
537 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
538 EmitOptimizationMessage(
539 D, diag::remark_fe_backend_optimization_remark_analysis);
542 void BackendConsumer::OptimizationRemarkHandler(
543 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
544 // Optimization analysis remarks are active if the pass name is set to
545 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
546 // regular expression that matches the name of the pass name in \p D.
548 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
549 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
550 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
551 EmitOptimizationMessage(
552 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
555 void BackendConsumer::OptimizationRemarkHandler(
556 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &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_aliasing);
568 void BackendConsumer::OptimizationFailureHandler(
569 const llvm::DiagnosticInfoOptimizationFailure &D) {
570 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
573 /// \brief This function is invoked when the backend needs
574 /// to report something to the user.
575 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
576 unsigned DiagID = diag::err_fe_inline_asm;
577 llvm::DiagnosticSeverity Severity = DI.getSeverity();
578 // Get the diagnostic ID based.
579 switch (DI.getKind()) {
580 case llvm::DK_InlineAsm:
581 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
583 ComputeDiagID(Severity, inline_asm, DiagID);
585 case llvm::DK_StackSize:
586 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
588 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
591 assert(CurLinkModule);
592 // FIXME: stop eating the warnings and notes.
593 if (Severity != DS_Error)
595 DiagID = diag::err_fe_cannot_link_module;
597 case llvm::DK_OptimizationRemark:
598 // Optimization remarks are always handled completely by this
599 // handler. There is no generic way of emitting them.
600 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
602 case llvm::DK_OptimizationRemarkMissed:
603 // Optimization remarks are always handled completely by this
604 // handler. There is no generic way of emitting them.
605 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
607 case llvm::DK_OptimizationRemarkAnalysis:
608 // Optimization remarks are always handled completely by this
609 // handler. There is no generic way of emitting them.
610 OptimizationRemarkHandler(
611 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
613 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
614 // Optimization remarks are always handled completely by this
615 // handler. There is no generic way of emitting them.
616 OptimizationRemarkHandler(
617 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
619 case llvm::DK_OptimizationRemarkAnalysisAliasing:
620 // Optimization remarks are always handled completely by this
621 // handler. There is no generic way of emitting them.
622 OptimizationRemarkHandler(
623 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
625 case llvm::DK_OptimizationFailure:
626 // Optimization failures are always handled completely by this
628 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
630 case llvm::DK_Unsupported:
631 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
634 // Plugin IDs are not bound to any value as they are set dynamically.
635 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
638 std::string MsgStorage;
640 raw_string_ostream Stream(MsgStorage);
641 DiagnosticPrinterRawOStream DP(Stream);
645 if (DiagID == diag::err_fe_cannot_link_module) {
646 Diags.Report(diag::err_fe_cannot_link_module)
647 << CurLinkModule->getModuleIdentifier() << MsgStorage;
651 // Report the backend message using the usual diagnostic mechanism.
653 Diags.Report(Loc, DiagID).AddString(MsgStorage);
657 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
658 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
659 OwnsVMContext(!_VMContext) {}
661 CodeGenAction::~CodeGenAction() {
667 bool CodeGenAction::hasIRSupport() const { return true; }
669 void CodeGenAction::EndSourceFileAction() {
670 // If the consumer creation failed, do nothing.
671 if (!getCompilerInstance().hasASTConsumer())
674 // Take back ownership of link modules we passed to consumer.
675 if (!LinkModules.empty())
676 BEConsumer->releaseLinkModules();
678 // Steal the module from the consumer.
679 TheModule = BEConsumer->takeModule();
682 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
683 return std::move(TheModule);
686 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
687 OwnsVMContext = false;
691 static raw_pwrite_stream *
692 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
694 case Backend_EmitAssembly:
695 return CI.createDefaultOutputFile(false, InFile, "s");
697 return CI.createDefaultOutputFile(false, InFile, "ll");
699 return CI.createDefaultOutputFile(true, InFile, "bc");
700 case Backend_EmitNothing:
702 case Backend_EmitMCNull:
703 return CI.createNullOutputFile();
704 case Backend_EmitObj:
705 return CI.createDefaultOutputFile(true, InFile, "o");
708 llvm_unreachable("Invalid action!");
711 std::unique_ptr<ASTConsumer>
712 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
713 BackendAction BA = static_cast<BackendAction>(Act);
714 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
715 if (BA != Backend_EmitNothing && !OS)
718 // Load bitcode modules to link with, if we need to.
719 if (LinkModules.empty())
720 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
721 const std::string &LinkBCFile = I.second;
723 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
725 CI.getDiagnostics().Report(diag::err_cannot_open_file)
726 << LinkBCFile << BCBuf.getError().message();
731 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
732 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
733 if (std::error_code EC = ModuleOrErr.getError()) {
734 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
739 addLinkModule(ModuleOrErr.get().release(), I.first);
742 CoverageSourceInfo *CoverageInfo = nullptr;
743 // Add the preprocessor callback only when the coverage mapping is generated.
744 if (CI.getCodeGenOpts().CoverageMapping) {
745 CoverageInfo = new CoverageSourceInfo;
746 CI.getPreprocessor().addPPCallbacks(
747 std::unique_ptr<PPCallbacks>(CoverageInfo));
750 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
751 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
752 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
753 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
754 OS, *VMContext, CoverageInfo));
755 BEConsumer = Result.get();
756 return std::move(Result);
759 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
761 unsigned LocCookie) {
762 SM.print(nullptr, llvm::errs());
765 void CodeGenAction::ExecuteAction() {
766 // If this is an IR file, we have to treat it specially.
767 if (getCurrentFileKind() == IK_LLVM_IR) {
768 BackendAction BA = static_cast<BackendAction>(Act);
769 CompilerInstance &CI = getCompilerInstance();
770 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
771 if (BA != Backend_EmitNothing && !OS)
775 SourceManager &SM = CI.getSourceManager();
776 FileID FID = SM.getMainFileID();
777 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
781 llvm::SMDiagnostic Err;
782 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
784 // Translate from the diagnostic info to the SourceManager location if
786 // TODO: Unify this with ConvertBackendLocation()
788 if (Err.getLineNo() > 0) {
789 assert(Err.getColumnNo() >= 0);
790 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
791 Err.getLineNo(), Err.getColumnNo() + 1);
794 // Strip off a leading diagnostic code if there is one.
795 StringRef Msg = Err.getMessage();
796 if (Msg.startswith("error: "))
800 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
802 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
805 const TargetOptions &TargetOpts = CI.getTargetOpts();
806 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
807 CI.getDiagnostics().Report(SourceLocation(),
808 diag::warn_fe_override_module)
809 << TargetOpts.Triple;
810 TheModule->setTargetTriple(TargetOpts.Triple);
813 LLVMContext &Ctx = TheModule->getContext();
814 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
815 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
816 CI.getLangOpts(), CI.getTarget().getDataLayout(),
817 TheModule.get(), BA, OS);
821 // Otherwise follow the normal AST path.
822 this->ASTFrontendAction::ExecuteAction();
827 void EmitAssemblyAction::anchor() { }
828 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
829 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
831 void EmitBCAction::anchor() { }
832 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
833 : CodeGenAction(Backend_EmitBC, _VMContext) {}
835 void EmitLLVMAction::anchor() { }
836 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
837 : CodeGenAction(Backend_EmitLL, _VMContext) {}
839 void EmitLLVMOnlyAction::anchor() { }
840 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
841 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
843 void EmitCodeGenOnlyAction::anchor() { }
844 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
845 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
847 void EmitObjAction::anchor() { }
848 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
849 : CodeGenAction(Backend_EmitObj, _VMContext) {}