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 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
178 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
179 C.getTargetInfo().getDataLayout(),
180 getModule(), Action, AsmOutStream);
182 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
184 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
187 void HandleTagDeclDefinition(TagDecl *D) override {
188 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
189 Context->getSourceManager(),
190 "LLVM IR generation of declaration");
191 Gen->HandleTagDeclDefinition(D);
194 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
195 Gen->HandleTagDeclRequiredDefinition(D);
198 void CompleteTentativeDefinition(VarDecl *D) override {
199 Gen->CompleteTentativeDefinition(D);
202 void AssignInheritanceModel(CXXRecordDecl *RD) override {
203 Gen->AssignInheritanceModel(RD);
206 void HandleVTable(CXXRecordDecl *RD) override {
207 Gen->HandleVTable(RD);
210 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
211 unsigned LocCookie) {
212 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
213 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
216 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
218 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
221 /// Get the best possible source location to represent a diagnostic that
222 /// may have associated debug info.
224 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
225 bool &BadDebugInfo, StringRef &Filename,
226 unsigned &Line, unsigned &Column) const;
228 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
229 SourceLocation LocCookie);
231 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
232 /// \brief Specialized handler for InlineAsm diagnostic.
233 /// \return True if the diagnostic has been successfully reported, false
235 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
236 /// \brief Specialized handler for StackSize diagnostic.
237 /// \return True if the diagnostic has been successfully reported, false
239 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
240 /// \brief Specialized handler for unsupported backend feature diagnostic.
241 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
242 /// \brief Specialized handlers for optimization remarks.
243 /// Note that these handlers only accept remarks and they always handle
245 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
248 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
249 void OptimizationRemarkHandler(
250 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
251 void OptimizationRemarkHandler(
252 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
253 void OptimizationRemarkHandler(
254 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
255 void OptimizationRemarkHandler(
256 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
257 void OptimizationFailureHandler(
258 const llvm::DiagnosticInfoOptimizationFailure &D);
261 void BackendConsumer::anchor() {}
264 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
265 /// buffer to be a valid FullSourceLoc.
266 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
267 SourceManager &CSM) {
268 // Get both the clang and llvm source managers. The location is relative to
269 // a memory buffer that the LLVM Source Manager is handling, we need to add
270 // a copy to the Clang source manager.
271 const llvm::SourceMgr &LSM = *D.getSourceMgr();
273 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
274 // already owns its one and clang::SourceManager wants to own its one.
275 const MemoryBuffer *LBuf =
276 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
278 // Create the copy and transfer ownership to clang::SourceManager.
279 // TODO: Avoid copying files into memory.
280 std::unique_ptr<llvm::MemoryBuffer> CBuf =
281 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
282 LBuf->getBufferIdentifier());
283 // FIXME: Keep a file ID map instead of creating new IDs for each location.
284 FileID FID = CSM.createFileID(std::move(CBuf));
286 // Translate the offset into the file.
287 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
288 SourceLocation NewLoc =
289 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
290 return FullSourceLoc(NewLoc, CSM);
294 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
295 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
296 /// the temporary memory buffer that the inline asm parser has set up.
297 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
298 SourceLocation LocCookie) {
299 // There are a couple of different kinds of errors we could get here. First,
300 // we re-format the SMDiagnostic in terms of a clang diagnostic.
302 // Strip "error: " off the start of the message string.
303 StringRef Message = D.getMessage();
304 if (Message.startswith("error: "))
305 Message = Message.substr(7);
307 // If the SMDiagnostic has an inline asm source location, translate it.
309 if (D.getLoc() != SMLoc())
310 Loc = ConvertBackendLocation(D, Context->getSourceManager());
313 switch (D.getKind()) {
314 case llvm::SourceMgr::DK_Error:
315 DiagID = diag::err_fe_inline_asm;
317 case llvm::SourceMgr::DK_Warning:
318 DiagID = diag::warn_fe_inline_asm;
320 case llvm::SourceMgr::DK_Note:
321 DiagID = diag::note_fe_inline_asm;
324 // If this problem has clang-level source location information, report the
325 // issue in the source with a note showing the instantiated
327 if (LocCookie.isValid()) {
328 Diags.Report(LocCookie, DiagID).AddString(Message);
330 if (D.getLoc().isValid()) {
331 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
332 // Convert the SMDiagnostic ranges into SourceRange and attach them
333 // to the diagnostic.
334 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
335 unsigned Column = D.getColumnNo();
336 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
337 Loc.getLocWithOffset(Range.second - Column));
343 // Otherwise, report the backend issue as occurring in the generated .s file.
344 // If Loc is invalid, we still need to report the issue, it just gets no
346 Diags.Report(Loc, DiagID).AddString(Message);
349 #define ComputeDiagID(Severity, GroupName, DiagID) \
351 switch (Severity) { \
352 case llvm::DS_Error: \
353 DiagID = diag::err_fe_##GroupName; \
355 case llvm::DS_Warning: \
356 DiagID = diag::warn_fe_##GroupName; \
358 case llvm::DS_Remark: \
359 llvm_unreachable("'remark' severity not expected"); \
361 case llvm::DS_Note: \
362 DiagID = diag::note_fe_##GroupName; \
367 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
369 switch (Severity) { \
370 case llvm::DS_Error: \
371 DiagID = diag::err_fe_##GroupName; \
373 case llvm::DS_Warning: \
374 DiagID = diag::warn_fe_##GroupName; \
376 case llvm::DS_Remark: \
377 DiagID = diag::remark_fe_##GroupName; \
379 case llvm::DS_Note: \
380 DiagID = diag::note_fe_##GroupName; \
386 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
388 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
389 std::string Message = D.getMsgStr().str();
391 // If this problem has clang-level source location information, report the
392 // issue as being a problem in the source with a note showing the instantiated
394 SourceLocation LocCookie =
395 SourceLocation::getFromRawEncoding(D.getLocCookie());
396 if (LocCookie.isValid())
397 Diags.Report(LocCookie, DiagID).AddString(Message);
399 // Otherwise, report the backend diagnostic as occurring in the generated
401 // If Loc is invalid, we still need to report the diagnostic, it just gets
404 Diags.Report(Loc, DiagID).AddString(Message);
406 // We handled all the possible severities.
411 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
412 if (D.getSeverity() != llvm::DS_Warning)
413 // For now, the only support we have for StackSize diagnostic is warning.
414 // We do not know how to format other severities.
417 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
418 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
419 diag::warn_fe_frame_larger_than)
420 << D.getStackSize() << Decl::castToDeclContext(ND);
427 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
428 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
429 unsigned &Line, unsigned &Column) const {
430 SourceManager &SourceMgr = Context->getSourceManager();
431 FileManager &FileMgr = SourceMgr.getFileManager();
432 SourceLocation DILoc;
434 if (D.isLocationAvailable()) {
435 D.getLocation(&Filename, &Line, &Column);
436 const FileEntry *FE = FileMgr.getFile(Filename);
437 if (FE && Line > 0) {
438 // If -gcolumn-info was not used, Column will be 0. This upsets the
439 // source manager, so pass 1 if Column is not set.
440 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
442 BadDebugInfo = DILoc.isInvalid();
445 // If a location isn't available, try to approximate it using the associated
446 // function definition. We use the definition's right brace to differentiate
447 // from diagnostics that genuinely relate to the function itself.
448 FullSourceLoc Loc(DILoc, SourceMgr);
450 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
451 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
453 if (DILoc.isInvalid() && D.isLocationAvailable())
454 // If we were not able to translate the file:line:col information
455 // back to a SourceLocation, at least emit a note stating that
456 // we could not translate this location. This can happen in the
457 // case of #line directives.
458 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
459 << Filename << Line << Column;
464 void BackendConsumer::UnsupportedDiagHandler(
465 const llvm::DiagnosticInfoUnsupported &D) {
466 // We only support errors.
467 assert(D.getSeverity() == llvm::DS_Error);
470 unsigned Line, Column;
472 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
475 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
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)
483 << Filename << Line << Column;
486 void BackendConsumer::EmitOptimizationMessage(
487 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
488 // We only support warnings and remarks.
489 assert(D.getSeverity() == llvm::DS_Remark ||
490 D.getSeverity() == llvm::DS_Warning);
493 unsigned Line, Column;
494 bool BadDebugInfo = false;
495 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
498 Diags.Report(Loc, DiagID)
499 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
503 // If we were not able to translate the file:line:col information
504 // back to a SourceLocation, at least emit a note stating that
505 // we could not translate this location. This can happen in the
506 // case of #line directives.
507 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
508 << Filename << Line << Column;
511 void BackendConsumer::OptimizationRemarkHandler(
512 const llvm::DiagnosticInfoOptimizationRemark &D) {
513 // Optimization remarks are active only if the -Rpass flag has a regular
514 // expression that matches the name of the pass name in \p D.
515 if (CodeGenOpts.OptimizationRemarkPattern &&
516 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
517 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
520 void BackendConsumer::OptimizationRemarkHandler(
521 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
522 // Missed optimization remarks are active only if the -Rpass-missed
523 // flag has a regular expression that matches the name of the pass
525 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
526 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
527 EmitOptimizationMessage(D,
528 diag::remark_fe_backend_optimization_remark_missed);
531 void BackendConsumer::OptimizationRemarkHandler(
532 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
533 // Optimization analysis remarks are active if the pass name is set to
534 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
535 // regular expression that matches the name of the pass name in \p D.
537 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
538 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
539 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
540 EmitOptimizationMessage(
541 D, diag::remark_fe_backend_optimization_remark_analysis);
544 void BackendConsumer::OptimizationRemarkHandler(
545 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
546 // Optimization analysis remarks are active if the pass name is set to
547 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
548 // regular expression that matches the name of the pass name in \p D.
550 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
551 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
552 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
553 EmitOptimizationMessage(
554 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
557 void BackendConsumer::OptimizationRemarkHandler(
558 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
559 // Optimization analysis remarks are active if the pass name is set to
560 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
561 // regular expression that matches the name of the pass name in \p D.
563 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
564 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
565 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
566 EmitOptimizationMessage(
567 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
570 void BackendConsumer::OptimizationFailureHandler(
571 const llvm::DiagnosticInfoOptimizationFailure &D) {
572 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
575 /// \brief This function is invoked when the backend needs
576 /// to report something to the user.
577 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
578 unsigned DiagID = diag::err_fe_inline_asm;
579 llvm::DiagnosticSeverity Severity = DI.getSeverity();
580 // Get the diagnostic ID based.
581 switch (DI.getKind()) {
582 case llvm::DK_InlineAsm:
583 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
585 ComputeDiagID(Severity, inline_asm, DiagID);
587 case llvm::DK_StackSize:
588 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
590 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
593 assert(CurLinkModule);
594 // FIXME: stop eating the warnings and notes.
595 if (Severity != DS_Error)
597 DiagID = diag::err_fe_cannot_link_module;
599 case llvm::DK_OptimizationRemark:
600 // Optimization remarks are always handled completely by this
601 // handler. There is no generic way of emitting them.
602 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
604 case llvm::DK_OptimizationRemarkMissed:
605 // Optimization remarks are always handled completely by this
606 // handler. There is no generic way of emitting them.
607 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
609 case llvm::DK_OptimizationRemarkAnalysis:
610 // Optimization remarks are always handled completely by this
611 // handler. There is no generic way of emitting them.
612 OptimizationRemarkHandler(
613 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
615 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
616 // Optimization remarks are always handled completely by this
617 // handler. There is no generic way of emitting them.
618 OptimizationRemarkHandler(
619 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
621 case llvm::DK_OptimizationRemarkAnalysisAliasing:
622 // Optimization remarks are always handled completely by this
623 // handler. There is no generic way of emitting them.
624 OptimizationRemarkHandler(
625 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
627 case llvm::DK_OptimizationFailure:
628 // Optimization failures are always handled completely by this
630 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
632 case llvm::DK_Unsupported:
633 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
636 // Plugin IDs are not bound to any value as they are set dynamically.
637 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
640 std::string MsgStorage;
642 raw_string_ostream Stream(MsgStorage);
643 DiagnosticPrinterRawOStream DP(Stream);
647 if (DiagID == diag::err_fe_cannot_link_module) {
648 Diags.Report(diag::err_fe_cannot_link_module)
649 << CurLinkModule->getModuleIdentifier() << MsgStorage;
653 // Report the backend message using the usual diagnostic mechanism.
655 Diags.Report(Loc, DiagID).AddString(MsgStorage);
659 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
660 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
661 OwnsVMContext(!_VMContext) {}
663 CodeGenAction::~CodeGenAction() {
669 bool CodeGenAction::hasIRSupport() const { return true; }
671 void CodeGenAction::EndSourceFileAction() {
672 // If the consumer creation failed, do nothing.
673 if (!getCompilerInstance().hasASTConsumer())
676 // Take back ownership of link modules we passed to consumer.
677 if (!LinkModules.empty())
678 BEConsumer->releaseLinkModules();
680 // Steal the module from the consumer.
681 TheModule = BEConsumer->takeModule();
684 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
685 return std::move(TheModule);
688 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
689 OwnsVMContext = false;
693 static raw_pwrite_stream *
694 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
696 case Backend_EmitAssembly:
697 return CI.createDefaultOutputFile(false, InFile, "s");
699 return CI.createDefaultOutputFile(false, InFile, "ll");
701 return CI.createDefaultOutputFile(true, InFile, "bc");
702 case Backend_EmitNothing:
704 case Backend_EmitMCNull:
705 return CI.createNullOutputFile();
706 case Backend_EmitObj:
707 return CI.createDefaultOutputFile(true, InFile, "o");
710 llvm_unreachable("Invalid action!");
713 std::unique_ptr<ASTConsumer>
714 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
715 BackendAction BA = static_cast<BackendAction>(Act);
716 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
717 if (BA != Backend_EmitNothing && !OS)
720 // Load bitcode modules to link with, if we need to.
721 if (LinkModules.empty())
722 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
723 const std::string &LinkBCFile = I.second;
725 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
727 CI.getDiagnostics().Report(diag::err_cannot_open_file)
728 << LinkBCFile << BCBuf.getError().message();
733 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
734 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
735 if (std::error_code EC = ModuleOrErr.getError()) {
736 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
741 addLinkModule(ModuleOrErr.get().release(), I.first);
744 CoverageSourceInfo *CoverageInfo = nullptr;
745 // Add the preprocessor callback only when the coverage mapping is generated.
746 if (CI.getCodeGenOpts().CoverageMapping) {
747 CoverageInfo = new CoverageSourceInfo;
748 CI.getPreprocessor().addPPCallbacks(
749 std::unique_ptr<PPCallbacks>(CoverageInfo));
752 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
753 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
754 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
755 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
756 OS, *VMContext, CoverageInfo));
757 BEConsumer = Result.get();
758 return std::move(Result);
761 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
763 unsigned LocCookie) {
764 SM.print(nullptr, llvm::errs());
766 auto Diags = static_cast<DiagnosticsEngine *>(Context);
768 switch (SM.getKind()) {
769 case llvm::SourceMgr::DK_Error:
770 DiagID = diag::err_fe_inline_asm;
772 case llvm::SourceMgr::DK_Warning:
773 DiagID = diag::warn_fe_inline_asm;
775 case llvm::SourceMgr::DK_Note:
776 DiagID = diag::note_fe_inline_asm;
780 Diags->Report(DiagID).AddString("cannot compile inline asm");
783 void CodeGenAction::ExecuteAction() {
784 // If this is an IR file, we have to treat it specially.
785 if (getCurrentFileKind() == IK_LLVM_IR) {
786 BackendAction BA = static_cast<BackendAction>(Act);
787 CompilerInstance &CI = getCompilerInstance();
788 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
789 if (BA != Backend_EmitNothing && !OS)
793 SourceManager &SM = CI.getSourceManager();
794 FileID FID = SM.getMainFileID();
795 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
799 // For ThinLTO backend invocations, ensure that the context
800 // merges types based on ODR identifiers.
801 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
802 VMContext->enableDebugTypeODRUniquing();
804 llvm::SMDiagnostic Err;
805 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
807 // Translate from the diagnostic info to the SourceManager location if
809 // TODO: Unify this with ConvertBackendLocation()
811 if (Err.getLineNo() > 0) {
812 assert(Err.getColumnNo() >= 0);
813 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
814 Err.getLineNo(), Err.getColumnNo() + 1);
817 // Strip off a leading diagnostic code if there is one.
818 StringRef Msg = Err.getMessage();
819 if (Msg.startswith("error: "))
823 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
825 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
828 const TargetOptions &TargetOpts = CI.getTargetOpts();
829 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
830 CI.getDiagnostics().Report(SourceLocation(),
831 diag::warn_fe_override_module)
832 << TargetOpts.Triple;
833 TheModule->setTargetTriple(TargetOpts.Triple);
836 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
837 MainFile->getMemBufferRef());
839 LLVMContext &Ctx = TheModule->getContext();
840 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
841 &CI.getDiagnostics());
843 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
844 CI.getLangOpts(), CI.getTarget().getDataLayout(),
845 TheModule.get(), BA, OS);
849 // Otherwise follow the normal AST path.
850 this->ASTFrontendAction::ExecuteAction();
855 void EmitAssemblyAction::anchor() { }
856 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
857 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
859 void EmitBCAction::anchor() { }
860 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
861 : CodeGenAction(Backend_EmitBC, _VMContext) {}
863 void EmitLLVMAction::anchor() { }
864 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
865 : CodeGenAction(Backend_EmitLL, _VMContext) {}
867 void EmitLLVMOnlyAction::anchor() { }
868 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
869 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
871 void EmitCodeGenOnlyAction::anchor() { }
872 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
873 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
875 void EmitObjAction::anchor() { }
876 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
877 : CodeGenAction(Backend_EmitObj, _VMContext) {}