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, LinkModule;
59 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
60 const CodeGenOptions &CodeGenOpts,
61 const TargetOptions &TargetOpts,
62 const LangOptions &LangOpts, bool TimePasses,
63 const std::string &InFile, llvm::Module *LinkModule,
64 raw_pwrite_stream *OS, LLVMContext &C,
65 CoverageSourceInfo *CoverageInfo = nullptr)
66 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
67 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
68 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
69 Gen(CreateLLVMCodeGen(Diags, InFile, CodeGenOpts, C, CoverageInfo)),
70 LinkModule(LinkModule) {
71 llvm::TimePassesIsEnabled = TimePasses;
74 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
75 llvm::Module *takeLinkModule() { return LinkModule.release(); }
77 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
78 Gen->HandleCXXStaticMemberVarInstantiation(VD);
81 void Initialize(ASTContext &Ctx) override {
83 assert(Context == &Ctx);
89 if (llvm::TimePassesIsEnabled)
90 LLVMIRGeneration.startTimer();
94 TheModule.reset(Gen->GetModule());
96 if (llvm::TimePassesIsEnabled)
97 LLVMIRGeneration.stopTimer();
100 bool HandleTopLevelDecl(DeclGroupRef D) override {
101 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
102 Context->getSourceManager(),
103 "LLVM IR generation of declaration");
105 if (llvm::TimePassesIsEnabled)
106 LLVMIRGeneration.startTimer();
108 Gen->HandleTopLevelDecl(D);
110 if (llvm::TimePassesIsEnabled)
111 LLVMIRGeneration.stopTimer();
116 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
117 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
118 Context->getSourceManager(),
119 "LLVM IR generation of inline method");
120 if (llvm::TimePassesIsEnabled)
121 LLVMIRGeneration.startTimer();
123 Gen->HandleInlineMethodDefinition(D);
125 if (llvm::TimePassesIsEnabled)
126 LLVMIRGeneration.stopTimer();
129 void HandleTranslationUnit(ASTContext &C) override {
131 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
132 if (llvm::TimePassesIsEnabled)
133 LLVMIRGeneration.startTimer();
135 Gen->HandleTranslationUnit(C);
137 if (llvm::TimePassesIsEnabled)
138 LLVMIRGeneration.stopTimer();
141 // Silently ignore if we weren't initialized for some reason.
145 // Make sure IR generation is happy with the module. This is released by
146 // the module provider.
147 llvm::Module *M = Gen->ReleaseModule();
149 // The module has been released by IR gen on failures, do not double
155 assert(TheModule.get() == M &&
156 "Unexpected module change during IR generation");
158 // Link LinkModule into this module if present, preserving its validity.
160 if (Linker::LinkModules(
162 [=](const DiagnosticInfo &DI) { linkerDiagnosticHandler(DI); }))
166 // Install an inline asm handler so that diagnostics get printed through
167 // our diagnostics hooks.
168 LLVMContext &Ctx = TheModule->getContext();
169 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
170 Ctx.getInlineAsmDiagnosticHandler();
171 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
172 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
174 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
175 Ctx.getDiagnosticHandler();
176 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
177 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
179 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
180 C.getTargetInfo().getTargetDescription(),
181 TheModule.get(), Action, 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 HandleVTable(CXXRecordDecl *RD) override {
204 Gen->HandleVTable(RD);
207 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
208 Gen->HandleLinkerOptionPragma(Opts);
211 void HandleDetectMismatch(llvm::StringRef Name,
212 llvm::StringRef Value) override {
213 Gen->HandleDetectMismatch(Name, Value);
216 void HandleDependentLibrary(llvm::StringRef Opts) override {
217 Gen->HandleDependentLibrary(Opts);
220 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
221 unsigned LocCookie) {
222 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
223 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
226 void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI);
228 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
230 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
233 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
234 SourceLocation LocCookie);
236 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
237 /// \brief Specialized handler for InlineAsm diagnostic.
238 /// \return True if the diagnostic has been successfully reported, false
240 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
241 /// \brief Specialized handler for StackSize diagnostic.
242 /// \return True if the diagnostic has been successfully reported, false
244 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
245 /// \brief Specialized handlers for optimization remarks.
246 /// Note that these handlers only accept remarks and they always handle
248 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
251 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
252 void OptimizationRemarkHandler(
253 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
254 void OptimizationRemarkHandler(
255 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
256 void OptimizationFailureHandler(
257 const llvm::DiagnosticInfoOptimizationFailure &D);
260 void BackendConsumer::anchor() {}
263 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
264 /// buffer to be a valid FullSourceLoc.
265 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
266 SourceManager &CSM) {
267 // Get both the clang and llvm source managers. The location is relative to
268 // a memory buffer that the LLVM Source Manager is handling, we need to add
269 // a copy to the Clang source manager.
270 const llvm::SourceMgr &LSM = *D.getSourceMgr();
272 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
273 // already owns its one and clang::SourceManager wants to own its one.
274 const MemoryBuffer *LBuf =
275 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
277 // Create the copy and transfer ownership to clang::SourceManager.
278 // TODO: Avoid copying files into memory.
279 std::unique_ptr<llvm::MemoryBuffer> CBuf =
280 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
281 LBuf->getBufferIdentifier());
282 // FIXME: Keep a file ID map instead of creating new IDs for each location.
283 FileID FID = CSM.createFileID(std::move(CBuf));
285 // Translate the offset into the file.
286 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
287 SourceLocation NewLoc =
288 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
289 return FullSourceLoc(NewLoc, CSM);
293 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
294 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
295 /// the temporary memory buffer that the inline asm parser has set up.
296 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
297 SourceLocation LocCookie) {
298 // There are a couple of different kinds of errors we could get here. First,
299 // we re-format the SMDiagnostic in terms of a clang diagnostic.
301 // Strip "error: " off the start of the message string.
302 StringRef Message = D.getMessage();
303 if (Message.startswith("error: "))
304 Message = Message.substr(7);
306 // If the SMDiagnostic has an inline asm source location, translate it.
308 if (D.getLoc() != SMLoc())
309 Loc = ConvertBackendLocation(D, Context->getSourceManager());
312 switch (D.getKind()) {
313 case llvm::SourceMgr::DK_Error:
314 DiagID = diag::err_fe_inline_asm;
316 case llvm::SourceMgr::DK_Warning:
317 DiagID = diag::warn_fe_inline_asm;
319 case llvm::SourceMgr::DK_Note:
320 DiagID = diag::note_fe_inline_asm;
323 // If this problem has clang-level source location information, report the
324 // issue in the source with a note showing the instantiated
326 if (LocCookie.isValid()) {
327 Diags.Report(LocCookie, DiagID).AddString(Message);
329 if (D.getLoc().isValid()) {
330 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
331 // Convert the SMDiagnostic ranges into SourceRange and attach them
332 // to the diagnostic.
333 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
334 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
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 void BackendConsumer::EmitOptimizationMessage(
428 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
429 // We only support warnings and remarks.
430 assert(D.getSeverity() == llvm::DS_Remark ||
431 D.getSeverity() == llvm::DS_Warning);
433 SourceManager &SourceMgr = Context->getSourceManager();
434 FileManager &FileMgr = SourceMgr.getFileManager();
436 unsigned Line, Column;
437 SourceLocation DILoc;
439 if (D.isLocationAvailable()) {
440 D.getLocation(&Filename, &Line, &Column);
441 const FileEntry *FE = FileMgr.getFile(Filename);
442 if (FE && Line > 0) {
443 // If -gcolumn-info was not used, Column will be 0. This upsets the
444 // source manager, so pass 1 if Column is not set.
445 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
449 // If a location isn't available, try to approximate it using the associated
450 // function definition. We use the definition's right brace to differentiate
451 // from diagnostics that genuinely relate to the function itself.
452 FullSourceLoc Loc(DILoc, SourceMgr);
454 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
455 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
457 Diags.Report(Loc, DiagID)
458 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
461 if (DILoc.isInvalid() && D.isLocationAvailable())
462 // If we were not able to translate the file:line:col information
463 // back to a SourceLocation, at least emit a note stating that
464 // we could not translate this location. This can happen in the
465 // case of #line directives.
466 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
467 << Filename << Line << Column;
470 void BackendConsumer::OptimizationRemarkHandler(
471 const llvm::DiagnosticInfoOptimizationRemark &D) {
472 // Optimization remarks are active only if the -Rpass flag has a regular
473 // expression that matches the name of the pass name in \p D.
474 if (CodeGenOpts.OptimizationRemarkPattern &&
475 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
476 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
479 void BackendConsumer::OptimizationRemarkHandler(
480 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
481 // Missed optimization remarks are active only if the -Rpass-missed
482 // flag has a regular expression that matches the name of the pass
484 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
485 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
486 EmitOptimizationMessage(D,
487 diag::remark_fe_backend_optimization_remark_missed);
490 void BackendConsumer::OptimizationRemarkHandler(
491 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
492 // Optimization analysis remarks are active only if the -Rpass-analysis
493 // flag has a regular expression that matches the name of the pass
495 if (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
496 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))
497 EmitOptimizationMessage(
498 D, diag::remark_fe_backend_optimization_remark_analysis);
501 void BackendConsumer::OptimizationFailureHandler(
502 const llvm::DiagnosticInfoOptimizationFailure &D) {
503 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
506 void BackendConsumer::linkerDiagnosticHandler(const DiagnosticInfo &DI) {
507 if (DI.getSeverity() != DS_Error)
510 std::string MsgStorage;
512 raw_string_ostream Stream(MsgStorage);
513 DiagnosticPrinterRawOStream DP(Stream);
517 Diags.Report(diag::err_fe_cannot_link_module)
518 << LinkModule->getModuleIdentifier() << MsgStorage;
521 /// \brief This function is invoked when the backend needs
522 /// to report something to the user.
523 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
524 unsigned DiagID = diag::err_fe_inline_asm;
525 llvm::DiagnosticSeverity Severity = DI.getSeverity();
526 // Get the diagnostic ID based.
527 switch (DI.getKind()) {
528 case llvm::DK_InlineAsm:
529 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
531 ComputeDiagID(Severity, inline_asm, DiagID);
533 case llvm::DK_StackSize:
534 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
536 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
538 case llvm::DK_OptimizationRemark:
539 // Optimization remarks are always handled completely by this
540 // handler. There is no generic way of emitting them.
541 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
543 case llvm::DK_OptimizationRemarkMissed:
544 // Optimization remarks are always handled completely by this
545 // handler. There is no generic way of emitting them.
546 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
548 case llvm::DK_OptimizationRemarkAnalysis:
549 // Optimization remarks are always handled completely by this
550 // handler. There is no generic way of emitting them.
551 OptimizationRemarkHandler(
552 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
554 case llvm::DK_OptimizationFailure:
555 // Optimization failures are always handled completely by this
557 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
560 // Plugin IDs are not bound to any value as they are set dynamically.
561 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
564 std::string MsgStorage;
566 raw_string_ostream Stream(MsgStorage);
567 DiagnosticPrinterRawOStream DP(Stream);
571 // Report the backend message using the usual diagnostic mechanism.
573 Diags.Report(Loc, DiagID).AddString(MsgStorage);
577 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
578 : Act(_Act), LinkModule(nullptr),
579 VMContext(_VMContext ? _VMContext : new LLVMContext),
580 OwnsVMContext(!_VMContext) {}
582 CodeGenAction::~CodeGenAction() {
588 bool CodeGenAction::hasIRSupport() const { return true; }
590 void CodeGenAction::EndSourceFileAction() {
591 // If the consumer creation failed, do nothing.
592 if (!getCompilerInstance().hasASTConsumer())
595 // If we were given a link module, release consumer's ownership of it.
597 BEConsumer->takeLinkModule();
599 // Steal the module from the consumer.
600 TheModule = BEConsumer->takeModule();
603 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
604 return std::move(TheModule);
607 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
608 OwnsVMContext = false;
612 static raw_pwrite_stream *
613 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
615 case Backend_EmitAssembly:
616 return CI.createDefaultOutputFile(false, InFile, "s");
618 return CI.createDefaultOutputFile(false, InFile, "ll");
620 return CI.createDefaultOutputFile(true, InFile, "bc");
621 case Backend_EmitNothing:
623 case Backend_EmitMCNull:
624 return CI.createNullOutputFile();
625 case Backend_EmitObj:
626 return CI.createDefaultOutputFile(true, InFile, "o");
629 llvm_unreachable("Invalid action!");
632 std::unique_ptr<ASTConsumer>
633 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
634 BackendAction BA = static_cast<BackendAction>(Act);
635 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
636 if (BA != Backend_EmitNothing && !OS)
639 llvm::Module *LinkModuleToUse = LinkModule;
641 // If we were not given a link module, and the user requested that one be
642 // loaded from bitcode, do so now.
643 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
644 if (!LinkModuleToUse && !LinkBCFile.empty()) {
645 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
647 CI.getDiagnostics().Report(diag::err_cannot_open_file)
648 << LinkBCFile << BCBuf.getError().message();
652 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
653 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
654 if (std::error_code EC = ModuleOrErr.getError()) {
655 CI.getDiagnostics().Report(diag::err_cannot_open_file)
656 << LinkBCFile << EC.message();
659 LinkModuleToUse = ModuleOrErr.get().release();
662 CoverageSourceInfo *CoverageInfo = nullptr;
663 // Add the preprocessor callback only when the coverage mapping is generated.
664 if (CI.getCodeGenOpts().CoverageMapping) {
665 CoverageInfo = new CoverageSourceInfo;
666 CI.getPreprocessor().addPPCallbacks(
667 std::unique_ptr<PPCallbacks>(CoverageInfo));
669 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
670 BA, CI.getDiagnostics(), CI.getCodeGenOpts(), CI.getTargetOpts(),
671 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
672 LinkModuleToUse, OS, *VMContext, CoverageInfo));
673 BEConsumer = Result.get();
674 return std::move(Result);
677 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
679 unsigned LocCookie) {
680 SM.print(nullptr, llvm::errs());
683 void CodeGenAction::ExecuteAction() {
684 // If this is an IR file, we have to treat it specially.
685 if (getCurrentFileKind() == IK_LLVM_IR) {
686 BackendAction BA = static_cast<BackendAction>(Act);
687 CompilerInstance &CI = getCompilerInstance();
688 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
689 if (BA != Backend_EmitNothing && !OS)
693 SourceManager &SM = CI.getSourceManager();
694 FileID FID = SM.getMainFileID();
695 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
699 llvm::SMDiagnostic Err;
700 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
702 // Translate from the diagnostic info to the SourceManager location if
704 // TODO: Unify this with ConvertBackendLocation()
706 if (Err.getLineNo() > 0) {
707 assert(Err.getColumnNo() >= 0);
708 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
709 Err.getLineNo(), Err.getColumnNo() + 1);
712 // Strip off a leading diagnostic code if there is one.
713 StringRef Msg = Err.getMessage();
714 if (Msg.startswith("error: "))
718 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
720 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
723 const TargetOptions &TargetOpts = CI.getTargetOpts();
724 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
725 CI.getDiagnostics().Report(SourceLocation(),
726 diag::warn_fe_override_module)
727 << TargetOpts.Triple;
728 TheModule->setTargetTriple(TargetOpts.Triple);
731 LLVMContext &Ctx = TheModule->getContext();
732 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
733 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
734 CI.getLangOpts(), CI.getTarget().getTargetDescription(),
735 TheModule.get(), BA, OS);
739 // Otherwise follow the normal AST path.
740 this->ASTFrontendAction::ExecuteAction();
745 void EmitAssemblyAction::anchor() { }
746 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
747 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
749 void EmitBCAction::anchor() { }
750 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
751 : CodeGenAction(Backend_EmitBC, _VMContext) {}
753 void EmitLLVMAction::anchor() { }
754 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
755 : CodeGenAction(Backend_EmitLL, _VMContext) {}
757 void EmitLLVMOnlyAction::anchor() { }
758 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
759 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
761 void EmitCodeGenOnlyAction::anchor() { }
762 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
763 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
765 void EmitObjAction::anchor() { }
766 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
767 : CodeGenAction(Backend_EmitObj, _VMContext) {}