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 std::unique_ptr<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 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
72 CoverageSourceInfo *CoverageInfo = nullptr)
73 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
74 TargetOpts(TargetOpts), LangOpts(LangOpts),
75 AsmOutStream(std::move(OS)), Context(nullptr),
76 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 llvm::Module *getModule() const { return Gen->GetModule(); }
85 std::unique_ptr<llvm::Module> takeModule() {
86 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
88 void releaseLinkModules() {
89 for (auto &I : LinkModules)
93 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
94 Gen->HandleCXXStaticMemberVarInstantiation(VD);
97 void Initialize(ASTContext &Ctx) override {
98 assert(!Context && "initialized multiple times");
102 if (llvm::TimePassesIsEnabled)
103 LLVMIRGeneration.startTimer();
105 Gen->Initialize(Ctx);
107 if (llvm::TimePassesIsEnabled)
108 LLVMIRGeneration.stopTimer();
111 bool HandleTopLevelDecl(DeclGroupRef D) override {
112 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
113 Context->getSourceManager(),
114 "LLVM IR generation of declaration");
116 if (llvm::TimePassesIsEnabled)
117 LLVMIRGeneration.startTimer();
119 Gen->HandleTopLevelDecl(D);
121 if (llvm::TimePassesIsEnabled)
122 LLVMIRGeneration.stopTimer();
127 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
128 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
129 Context->getSourceManager(),
130 "LLVM IR generation of inline function");
131 if (llvm::TimePassesIsEnabled)
132 LLVMIRGeneration.startTimer();
134 Gen->HandleInlineFunctionDefinition(D);
136 if (llvm::TimePassesIsEnabled)
137 LLVMIRGeneration.stopTimer();
140 void HandleTranslationUnit(ASTContext &C) override {
142 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
143 if (llvm::TimePassesIsEnabled)
144 LLVMIRGeneration.startTimer();
146 Gen->HandleTranslationUnit(C);
148 if (llvm::TimePassesIsEnabled)
149 LLVMIRGeneration.stopTimer();
152 // Silently ignore if we weren't initialized for some reason.
156 // Install an inline asm handler so that diagnostics get printed through
157 // our diagnostics hooks.
158 LLVMContext &Ctx = getModule()->getContext();
159 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
160 Ctx.getInlineAsmDiagnosticHandler();
161 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
162 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
164 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
165 Ctx.getDiagnosticHandler();
166 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
167 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
169 // Link LinkModule into this module if present, preserving its validity.
170 for (auto &I : LinkModules) {
171 unsigned LinkFlags = I.first;
172 CurLinkModule = I.second.get();
173 if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
177 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
179 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
180 C.getTargetInfo().getDataLayout(),
181 getModule(), Action, std::move(AsmOutStream));
183 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
185 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
188 void HandleTagDeclDefinition(TagDecl *D) override {
189 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
190 Context->getSourceManager(),
191 "LLVM IR generation of declaration");
192 Gen->HandleTagDeclDefinition(D);
195 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
196 Gen->HandleTagDeclRequiredDefinition(D);
199 void CompleteTentativeDefinition(VarDecl *D) override {
200 Gen->CompleteTentativeDefinition(D);
203 void AssignInheritanceModel(CXXRecordDecl *RD) override {
204 Gen->AssignInheritanceModel(RD);
207 void HandleVTable(CXXRecordDecl *RD) override {
208 Gen->HandleVTable(RD);
211 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
212 unsigned LocCookie) {
213 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
214 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
217 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
219 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
222 /// Get the best possible source location to represent a diagnostic that
223 /// may have associated debug info.
225 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
226 bool &BadDebugInfo, StringRef &Filename,
227 unsigned &Line, unsigned &Column) const;
229 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
230 SourceLocation LocCookie);
232 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
233 /// \brief Specialized handler for InlineAsm diagnostic.
234 /// \return True if the diagnostic has been successfully reported, false
236 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
237 /// \brief Specialized handler for StackSize diagnostic.
238 /// \return True if the diagnostic has been successfully reported, false
240 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
241 /// \brief Specialized handler for unsupported backend feature diagnostic.
242 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
243 /// \brief Specialized handlers for optimization remarks.
244 /// Note that these handlers only accept remarks and they always handle
246 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
249 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
250 void OptimizationRemarkHandler(
251 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
252 void OptimizationRemarkHandler(
253 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
254 void OptimizationRemarkHandler(
255 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
256 void OptimizationRemarkHandler(
257 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
258 void OptimizationFailureHandler(
259 const llvm::DiagnosticInfoOptimizationFailure &D);
262 void BackendConsumer::anchor() {}
265 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
266 /// buffer to be a valid FullSourceLoc.
267 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
268 SourceManager &CSM) {
269 // Get both the clang and llvm source managers. The location is relative to
270 // a memory buffer that the LLVM Source Manager is handling, we need to add
271 // a copy to the Clang source manager.
272 const llvm::SourceMgr &LSM = *D.getSourceMgr();
274 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
275 // already owns its one and clang::SourceManager wants to own its one.
276 const MemoryBuffer *LBuf =
277 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
279 // Create the copy and transfer ownership to clang::SourceManager.
280 // TODO: Avoid copying files into memory.
281 std::unique_ptr<llvm::MemoryBuffer> CBuf =
282 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
283 LBuf->getBufferIdentifier());
284 // FIXME: Keep a file ID map instead of creating new IDs for each location.
285 FileID FID = CSM.createFileID(std::move(CBuf));
287 // Translate the offset into the file.
288 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
289 SourceLocation NewLoc =
290 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
291 return FullSourceLoc(NewLoc, CSM);
295 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
296 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
297 /// the temporary memory buffer that the inline asm parser has set up.
298 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
299 SourceLocation LocCookie) {
300 // There are a couple of different kinds of errors we could get here. First,
301 // we re-format the SMDiagnostic in terms of a clang diagnostic.
303 // Strip "error: " off the start of the message string.
304 StringRef Message = D.getMessage();
305 if (Message.startswith("error: "))
306 Message = Message.substr(7);
308 // If the SMDiagnostic has an inline asm source location, translate it.
310 if (D.getLoc() != SMLoc())
311 Loc = ConvertBackendLocation(D, Context->getSourceManager());
314 switch (D.getKind()) {
315 case llvm::SourceMgr::DK_Error:
316 DiagID = diag::err_fe_inline_asm;
318 case llvm::SourceMgr::DK_Warning:
319 DiagID = diag::warn_fe_inline_asm;
321 case llvm::SourceMgr::DK_Note:
322 DiagID = diag::note_fe_inline_asm;
325 // If this problem has clang-level source location information, report the
326 // issue in the source with a note showing the instantiated
328 if (LocCookie.isValid()) {
329 Diags.Report(LocCookie, DiagID).AddString(Message);
331 if (D.getLoc().isValid()) {
332 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
333 // Convert the SMDiagnostic ranges into SourceRange and attach them
334 // to the diagnostic.
335 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
336 unsigned Column = D.getColumnNo();
337 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
338 Loc.getLocWithOffset(Range.second - Column));
344 // Otherwise, report the backend issue as occurring in the generated .s file.
345 // If Loc is invalid, we still need to report the issue, it just gets no
347 Diags.Report(Loc, DiagID).AddString(Message);
350 #define ComputeDiagID(Severity, GroupName, DiagID) \
352 switch (Severity) { \
353 case llvm::DS_Error: \
354 DiagID = diag::err_fe_##GroupName; \
356 case llvm::DS_Warning: \
357 DiagID = diag::warn_fe_##GroupName; \
359 case llvm::DS_Remark: \
360 llvm_unreachable("'remark' severity not expected"); \
362 case llvm::DS_Note: \
363 DiagID = diag::note_fe_##GroupName; \
368 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
370 switch (Severity) { \
371 case llvm::DS_Error: \
372 DiagID = diag::err_fe_##GroupName; \
374 case llvm::DS_Warning: \
375 DiagID = diag::warn_fe_##GroupName; \
377 case llvm::DS_Remark: \
378 DiagID = diag::remark_fe_##GroupName; \
380 case llvm::DS_Note: \
381 DiagID = diag::note_fe_##GroupName; \
387 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
389 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
390 std::string Message = D.getMsgStr().str();
392 // If this problem has clang-level source location information, report the
393 // issue as being a problem in the source with a note showing the instantiated
395 SourceLocation LocCookie =
396 SourceLocation::getFromRawEncoding(D.getLocCookie());
397 if (LocCookie.isValid())
398 Diags.Report(LocCookie, DiagID).AddString(Message);
400 // Otherwise, report the backend diagnostic as occurring in the generated
402 // If Loc is invalid, we still need to report the diagnostic, it just gets
405 Diags.Report(Loc, DiagID).AddString(Message);
407 // We handled all the possible severities.
412 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
413 if (D.getSeverity() != llvm::DS_Warning)
414 // For now, the only support we have for StackSize diagnostic is warning.
415 // We do not know how to format other severities.
418 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
419 // FIXME: Shouldn't need to truncate to uint32_t
420 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
421 diag::warn_fe_frame_larger_than)
422 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
429 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
430 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
431 unsigned &Line, unsigned &Column) const {
432 SourceManager &SourceMgr = Context->getSourceManager();
433 FileManager &FileMgr = SourceMgr.getFileManager();
434 SourceLocation DILoc;
436 if (D.isLocationAvailable()) {
437 D.getLocation(&Filename, &Line, &Column);
438 const FileEntry *FE = FileMgr.getFile(Filename);
439 if (FE && Line > 0) {
440 // If -gcolumn-info was not used, Column will be 0. This upsets the
441 // source manager, so pass 1 if Column is not set.
442 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
444 BadDebugInfo = DILoc.isInvalid();
447 // If a location isn't available, try to approximate it using the associated
448 // function definition. We use the definition's right brace to differentiate
449 // from diagnostics that genuinely relate to the function itself.
450 FullSourceLoc Loc(DILoc, SourceMgr);
452 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
453 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
455 if (DILoc.isInvalid() && D.isLocationAvailable())
456 // If we were not able to translate the file:line:col information
457 // back to a SourceLocation, at least emit a note stating that
458 // we could not translate this location. This can happen in the
459 // case of #line directives.
460 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
461 << Filename << Line << Column;
466 void BackendConsumer::UnsupportedDiagHandler(
467 const llvm::DiagnosticInfoUnsupported &D) {
468 // We only support errors.
469 assert(D.getSeverity() == llvm::DS_Error);
472 unsigned Line, Column;
474 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
477 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
480 // If we were not able to translate the file:line:col information
481 // back to a SourceLocation, at least emit a note stating that
482 // we could not translate this location. This can happen in the
483 // case of #line directives.
484 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
485 << Filename << Line << Column;
488 void BackendConsumer::EmitOptimizationMessage(
489 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
490 // We only support warnings and remarks.
491 assert(D.getSeverity() == llvm::DS_Remark ||
492 D.getSeverity() == llvm::DS_Warning);
495 unsigned Line, Column;
496 bool BadDebugInfo = false;
497 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
500 Diags.Report(Loc, DiagID)
501 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
505 // If we were not able to translate the file:line:col information
506 // back to a SourceLocation, at least emit a note stating that
507 // we could not translate this location. This can happen in the
508 // case of #line directives.
509 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
510 << Filename << Line << Column;
513 void BackendConsumer::OptimizationRemarkHandler(
514 const llvm::DiagnosticInfoOptimizationRemark &D) {
515 // Optimization remarks are active only if the -Rpass flag has a regular
516 // expression that matches the name of the pass name in \p D.
517 if (CodeGenOpts.OptimizationRemarkPattern &&
518 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
519 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
522 void BackendConsumer::OptimizationRemarkHandler(
523 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
524 // Missed optimization remarks are active only if the -Rpass-missed
525 // flag has a regular expression that matches the name of the pass
527 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
528 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
529 EmitOptimizationMessage(D,
530 diag::remark_fe_backend_optimization_remark_missed);
533 void BackendConsumer::OptimizationRemarkHandler(
534 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
535 // Optimization analysis remarks are active if the pass name is set to
536 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
537 // regular expression that matches the name of the pass name in \p D.
539 if (D.shouldAlwaysPrint() ||
540 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
541 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
542 EmitOptimizationMessage(
543 D, diag::remark_fe_backend_optimization_remark_analysis);
546 void BackendConsumer::OptimizationRemarkHandler(
547 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
548 // Optimization analysis remarks are active if the pass name is set to
549 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
550 // regular expression that matches the name of the pass name in \p D.
552 if (D.shouldAlwaysPrint() ||
553 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
554 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
555 EmitOptimizationMessage(
556 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
559 void BackendConsumer::OptimizationRemarkHandler(
560 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
561 // Optimization analysis remarks are active if the pass name is set to
562 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
563 // regular expression that matches the name of the pass name in \p D.
565 if (D.shouldAlwaysPrint() ||
566 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
567 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
568 EmitOptimizationMessage(
569 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
572 void BackendConsumer::OptimizationFailureHandler(
573 const llvm::DiagnosticInfoOptimizationFailure &D) {
574 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
577 /// \brief This function is invoked when the backend needs
578 /// to report something to the user.
579 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
580 unsigned DiagID = diag::err_fe_inline_asm;
581 llvm::DiagnosticSeverity Severity = DI.getSeverity();
582 // Get the diagnostic ID based.
583 switch (DI.getKind()) {
584 case llvm::DK_InlineAsm:
585 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
587 ComputeDiagID(Severity, inline_asm, DiagID);
589 case llvm::DK_StackSize:
590 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
592 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
595 assert(CurLinkModule);
596 // FIXME: stop eating the warnings and notes.
597 if (Severity != DS_Error)
599 DiagID = diag::err_fe_cannot_link_module;
601 case llvm::DK_OptimizationRemark:
602 // Optimization remarks are always handled completely by this
603 // handler. There is no generic way of emitting them.
604 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
606 case llvm::DK_OptimizationRemarkMissed:
607 // Optimization remarks are always handled completely by this
608 // handler. There is no generic way of emitting them.
609 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
611 case llvm::DK_OptimizationRemarkAnalysis:
612 // Optimization remarks are always handled completely by this
613 // handler. There is no generic way of emitting them.
614 OptimizationRemarkHandler(
615 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
617 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
618 // Optimization remarks are always handled completely by this
619 // handler. There is no generic way of emitting them.
620 OptimizationRemarkHandler(
621 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
623 case llvm::DK_OptimizationRemarkAnalysisAliasing:
624 // Optimization remarks are always handled completely by this
625 // handler. There is no generic way of emitting them.
626 OptimizationRemarkHandler(
627 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
629 case llvm::DK_OptimizationFailure:
630 // Optimization failures are always handled completely by this
632 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
634 case llvm::DK_Unsupported:
635 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
638 // Plugin IDs are not bound to any value as they are set dynamically.
639 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
642 std::string MsgStorage;
644 raw_string_ostream Stream(MsgStorage);
645 DiagnosticPrinterRawOStream DP(Stream);
649 if (DiagID == diag::err_fe_cannot_link_module) {
650 Diags.Report(diag::err_fe_cannot_link_module)
651 << CurLinkModule->getModuleIdentifier() << MsgStorage;
655 // Report the backend message using the usual diagnostic mechanism.
657 Diags.Report(Loc, DiagID).AddString(MsgStorage);
661 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
662 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
663 OwnsVMContext(!_VMContext) {}
665 CodeGenAction::~CodeGenAction() {
671 bool CodeGenAction::hasIRSupport() const { return true; }
673 void CodeGenAction::EndSourceFileAction() {
674 // If the consumer creation failed, do nothing.
675 if (!getCompilerInstance().hasASTConsumer())
678 // Take back ownership of link modules we passed to consumer.
679 if (!LinkModules.empty())
680 BEConsumer->releaseLinkModules();
682 // Steal the module from the consumer.
683 TheModule = BEConsumer->takeModule();
686 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
687 return std::move(TheModule);
690 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
691 OwnsVMContext = false;
695 static std::unique_ptr<raw_pwrite_stream>
696 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
698 case Backend_EmitAssembly:
699 return CI.createDefaultOutputFile(false, InFile, "s");
701 return CI.createDefaultOutputFile(false, InFile, "ll");
703 return CI.createDefaultOutputFile(true, InFile, "bc");
704 case Backend_EmitNothing:
706 case Backend_EmitMCNull:
707 return CI.createNullOutputFile();
708 case Backend_EmitObj:
709 return CI.createDefaultOutputFile(true, InFile, "o");
712 llvm_unreachable("Invalid action!");
715 std::unique_ptr<ASTConsumer>
716 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
717 BackendAction BA = static_cast<BackendAction>(Act);
718 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
719 if (BA != Backend_EmitNothing && !OS)
722 // Load bitcode modules to link with, if we need to.
723 if (LinkModules.empty())
724 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
725 const std::string &LinkBCFile = I.second;
727 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
729 CI.getDiagnostics().Report(diag::err_cannot_open_file)
730 << LinkBCFile << BCBuf.getError().message();
735 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
736 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
737 if (std::error_code EC = ModuleOrErr.getError()) {
738 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
743 addLinkModule(ModuleOrErr.get().release(), I.first);
746 CoverageSourceInfo *CoverageInfo = nullptr;
747 // Add the preprocessor callback only when the coverage mapping is generated.
748 if (CI.getCodeGenOpts().CoverageMapping) {
749 CoverageInfo = new CoverageSourceInfo;
750 CI.getPreprocessor().addPPCallbacks(
751 std::unique_ptr<PPCallbacks>(CoverageInfo));
754 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
755 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
756 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
757 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
758 std::move(OS), *VMContext, CoverageInfo));
759 BEConsumer = Result.get();
760 return std::move(Result);
763 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
765 unsigned LocCookie) {
766 SM.print(nullptr, llvm::errs());
768 auto Diags = static_cast<DiagnosticsEngine *>(Context);
770 switch (SM.getKind()) {
771 case llvm::SourceMgr::DK_Error:
772 DiagID = diag::err_fe_inline_asm;
774 case llvm::SourceMgr::DK_Warning:
775 DiagID = diag::warn_fe_inline_asm;
777 case llvm::SourceMgr::DK_Note:
778 DiagID = diag::note_fe_inline_asm;
782 Diags->Report(DiagID).AddString("cannot compile inline asm");
785 void CodeGenAction::ExecuteAction() {
786 // If this is an IR file, we have to treat it specially.
787 if (getCurrentFileKind() == IK_LLVM_IR) {
788 BackendAction BA = static_cast<BackendAction>(Act);
789 CompilerInstance &CI = getCompilerInstance();
790 std::unique_ptr<raw_pwrite_stream> OS =
791 GetOutputStream(CI, getCurrentFile(), BA);
792 if (BA != Backend_EmitNothing && !OS)
796 SourceManager &SM = CI.getSourceManager();
797 FileID FID = SM.getMainFileID();
798 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
802 // For ThinLTO backend invocations, ensure that the context
803 // merges types based on ODR identifiers.
804 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
805 VMContext->enableDebugTypeODRUniquing();
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 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
840 MainFile->getMemBufferRef());
842 LLVMContext &Ctx = TheModule->getContext();
843 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
844 &CI.getDiagnostics());
846 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
847 CI.getLangOpts(), CI.getTarget().getDataLayout(),
848 TheModule.get(), BA, std::move(OS));
852 // Otherwise follow the normal AST path.
853 this->ASTFrontendAction::ExecuteAction();
858 void EmitAssemblyAction::anchor() { }
859 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
860 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
862 void EmitBCAction::anchor() { }
863 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
864 : CodeGenAction(Backend_EmitBC, _VMContext) {}
866 void EmitLLVMAction::anchor() { }
867 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
868 : CodeGenAction(Backend_EmitLL, _VMContext) {}
870 void EmitLLVMOnlyAction::anchor() { }
871 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
872 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
874 void EmitCodeGenOnlyAction::anchor() { }
875 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
876 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
878 void EmitObjAction::anchor() { }
879 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
880 : CodeGenAction(Backend_EmitObj, _VMContext) {}