1218 lines · cpp
1//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "clang/CodeGen/CodeGenAction.h"10#include "BackendConsumer.h"11#include "CGCall.h"12#include "CodeGenModule.h"13#include "CoverageMappingGen.h"14#include "MacroPPCallbacks.h"15#include "clang/AST/ASTConsumer.h"16#include "clang/AST/ASTContext.h"17#include "clang/AST/DeclCXX.h"18#include "clang/AST/DeclGroup.h"19#include "clang/Basic/DiagnosticFrontend.h"20#include "clang/Basic/FileManager.h"21#include "clang/Basic/LangStandard.h"22#include "clang/Basic/SourceManager.h"23#include "clang/Basic/TargetInfo.h"24#include "clang/CodeGen/BackendUtil.h"25#include "clang/CodeGen/ModuleBuilder.h"26#include "clang/Driver/DriverDiagnostic.h"27#include "clang/Frontend/CompilerInstance.h"28#include "clang/Frontend/MultiplexConsumer.h"29#include "clang/Lex/Preprocessor.h"30#include "clang/Serialization/ASTWriter.h"31#include "llvm/ADT/Hashing.h"32#include "llvm/ADT/ScopeExit.h"33#include "llvm/Bitcode/BitcodeReader.h"34#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"35#include "llvm/Demangle/Demangle.h"36#include "llvm/IR/DebugInfo.h"37#include "llvm/IR/DiagnosticInfo.h"38#include "llvm/IR/DiagnosticPrinter.h"39#include "llvm/IR/GlobalValue.h"40#include "llvm/IR/LLVMContext.h"41#include "llvm/IR/LLVMRemarkStreamer.h"42#include "llvm/IR/Module.h"43#include "llvm/IR/Verifier.h"44#include "llvm/IRReader/IRReader.h"45#include "llvm/LTO/LTOBackend.h"46#include "llvm/Linker/Linker.h"47#include "llvm/Pass.h"48#include "llvm/Support/MemoryBuffer.h"49#include "llvm/Support/SourceMgr.h"50#include "llvm/Support/TimeProfiler.h"51#include "llvm/Support/Timer.h"52#include "llvm/Support/ToolOutputFile.h"53#include "llvm/Transforms/IPO/Internalize.h"54#include "llvm/Transforms/Utils/Cloning.h"55 56#include <optional>57using namespace clang;58using namespace llvm;59 60#define DEBUG_TYPE "codegenaction"61 62namespace clang {63class BackendConsumer;64class ClangDiagnosticHandler final : public DiagnosticHandler {65public:66 ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)67 : CodeGenOpts(CGOpts), BackendCon(BCon) {}68 69 bool handleDiagnostics(const DiagnosticInfo &DI) override;70 71 bool isAnalysisRemarkEnabled(StringRef PassName) const override {72 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);73 }74 bool isMissedOptRemarkEnabled(StringRef PassName) const override {75 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);76 }77 bool isPassedOptRemarkEnabled(StringRef PassName) const override {78 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);79 }80 81 bool isAnyRemarkEnabled() const override {82 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||83 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||84 CodeGenOpts.OptimizationRemark.hasValidPattern();85 }86 87private:88 const CodeGenOptions &CodeGenOpts;89 BackendConsumer *BackendCon;90};91 92static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,93 const CodeGenOptions &CodeGenOpts) {94 handleAllErrors(95 std::move(E),96 [&](const LLVMRemarkSetupFileError &E) {97 Diags.Report(diag::err_cannot_open_file)98 << CodeGenOpts.OptRecordFile << E.message();99 },100 [&](const LLVMRemarkSetupPatternError &E) {101 Diags.Report(diag::err_drv_optimization_remark_pattern)102 << E.message() << CodeGenOpts.OptRecordPasses;103 },104 [&](const LLVMRemarkSetupFormatError &E) {105 Diags.Report(diag::err_drv_optimization_remark_format)106 << CodeGenOpts.OptRecordFormat;107 });108}109 110BackendConsumer::BackendConsumer(CompilerInstance &CI, BackendAction Action,111 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,112 LLVMContext &C,113 SmallVector<LinkModule, 4> LinkModules,114 StringRef InFile,115 std::unique_ptr<raw_pwrite_stream> OS,116 CoverageSourceInfo *CoverageInfo,117 llvm::Module *CurLinkModule)118 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),119 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),120 AsmOutStream(std::move(OS)), FS(VFS), Action(Action),121 Gen(CreateLLVMCodeGen(Diags, InFile, std::move(VFS),122 CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(),123 CI.getCodeGenOpts(), C, CoverageInfo)),124 LinkModules(std::move(LinkModules)), CurLinkModule(CurLinkModule) {125 TimerIsEnabled = CodeGenOpts.TimePasses;126 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;127 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;128 if (CodeGenOpts.TimePasses)129 LLVMIRGeneration.init("irgen", "LLVM IR generation", CI.getTimerGroup());130}131 132llvm::Module* BackendConsumer::getModule() const {133 return Gen->GetModule();134}135 136std::unique_ptr<llvm::Module> BackendConsumer::takeModule() {137 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());138}139 140CodeGenerator* BackendConsumer::getCodeGenerator() {141 return Gen.get();142}143 144void BackendConsumer::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {145 Gen->HandleCXXStaticMemberVarInstantiation(VD);146}147 148void BackendConsumer::Initialize(ASTContext &Ctx) {149 assert(!Context && "initialized multiple times");150 151 Context = &Ctx;152 153 if (TimerIsEnabled)154 LLVMIRGeneration.startTimer();155 156 Gen->Initialize(Ctx);157 158 if (TimerIsEnabled)159 LLVMIRGeneration.stopTimer();160}161 162bool BackendConsumer::HandleTopLevelDecl(DeclGroupRef D) {163 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),164 Context->getSourceManager(),165 "LLVM IR generation of declaration");166 167 // Recurse.168 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)169 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);170 171 Gen->HandleTopLevelDecl(D);172 173 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)174 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());175 176 return true;177}178 179void BackendConsumer::HandleInlineFunctionDefinition(FunctionDecl *D) {180 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),181 Context->getSourceManager(),182 "LLVM IR generation of inline function");183 if (TimerIsEnabled)184 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);185 186 Gen->HandleInlineFunctionDefinition(D);187 188 if (TimerIsEnabled)189 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());190}191 192void BackendConsumer::HandleInterestingDecl(DeclGroupRef D) {193 HandleTopLevelDecl(D);194}195 196// Links each entry in LinkModules into our module. Returns true on error.197bool BackendConsumer::LinkInModules(llvm::Module *M) {198 for (auto &LM : LinkModules) {199 assert(LM.Module && "LinkModule does not actually have a module");200 201 if (LM.PropagateAttrs)202 for (Function &F : *LM.Module) {203 // Skip intrinsics. Keep consistent with how intrinsics are created204 // in LLVM IR.205 if (F.isIntrinsic())206 continue;207 CodeGen::mergeDefaultFunctionDefinitionAttributes(208 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);209 }210 211 CurLinkModule = LM.Module.get();212 bool Err;213 214 if (LM.Internalize) {215 Err = Linker::linkModules(216 *M, std::move(LM.Module), LM.LinkFlags,217 [](llvm::Module &M, const llvm::StringSet<> &GVS) {218 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {219 return !GV.hasName() || (GVS.count(GV.getName()) == 0);220 });221 });222 } else223 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);224 225 if (Err)226 return true;227 }228 229 LinkModules.clear();230 return false; // success231}232 233void BackendConsumer::HandleTranslationUnit(ASTContext &C) {234 {235 llvm::TimeTraceScope TimeScope("Frontend");236 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");237 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)238 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);239 240 Gen->HandleTranslationUnit(C);241 242 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)243 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());244 }245 246 // Silently ignore if we weren't initialized for some reason.247 if (!getModule())248 return;249 250 LLVMContext &Ctx = getModule()->getContext();251 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =252 Ctx.getDiagnosticHandler();253 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(254 CodeGenOpts, this));255 256 Ctx.setDefaultTargetCPU(TargetOpts.CPU);257 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));258 259 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =260 setupLLVMOptimizationRemarks(261 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,262 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,263 CodeGenOpts.DiagnosticsHotnessThreshold);264 265 if (Error E = OptRecordFileOrErr.takeError()) {266 reportOptRecordError(std::move(E), Diags, CodeGenOpts);267 return;268 }269 270 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);271 272 if (OptRecordFile && CodeGenOpts.getProfileUse() !=273 llvm::driver::ProfileInstrKind::ProfileNone)274 Ctx.setDiagnosticsHotnessRequested(true);275 276 if (CodeGenOpts.MisExpect) {277 Ctx.setMisExpectWarningRequested(true);278 }279 280 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {281 Ctx.setDiagnosticsMisExpectTolerance(282 CodeGenOpts.DiagnosticsMisExpectTolerance);283 }284 285 // Link each LinkModule into our module.286 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(getModule()))287 return;288 289 for (auto &F : getModule()->functions()) {290 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {291 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());292 // TODO: use a fast content hash when available.293 auto NameHash = llvm::hash_value(F.getName());294 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));295 }296 }297 298 if (CodeGenOpts.ClearASTBeforeBackend) {299 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");300 // Access to the AST is no longer available after this.301 // Other things that the ASTContext manages are still available, e.g.302 // the SourceManager. It'd be nice if we could separate out all the303 // things in ASTContext used after this point and null out the304 // ASTContext, but too many various parts of the ASTContext are still305 // used in various parts.306 C.cleanup();307 C.getAllocator().Reset();308 }309 310 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());311 312 emitBackendOutput(CI, CI.getCodeGenOpts(),313 C.getTargetInfo().getDataLayoutString(), getModule(),314 Action, FS, std::move(AsmOutStream), this);315 316 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));317 318 if (OptRecordFile)319 OptRecordFile->keep();320}321 322void BackendConsumer::HandleTagDeclDefinition(TagDecl *D) {323 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),324 Context->getSourceManager(),325 "LLVM IR generation of declaration");326 Gen->HandleTagDeclDefinition(D);327}328 329void BackendConsumer::HandleTagDeclRequiredDefinition(const TagDecl *D) {330 Gen->HandleTagDeclRequiredDefinition(D);331}332 333void BackendConsumer::CompleteTentativeDefinition(VarDecl *D) {334 Gen->CompleteTentativeDefinition(D);335}336 337void BackendConsumer::CompleteExternalDeclaration(DeclaratorDecl *D) {338 Gen->CompleteExternalDeclaration(D);339}340 341void BackendConsumer::AssignInheritanceModel(CXXRecordDecl *RD) {342 Gen->AssignInheritanceModel(RD);343}344 345void BackendConsumer::HandleVTable(CXXRecordDecl *RD) {346 Gen->HandleVTable(RD);347}348 349void BackendConsumer::anchor() { }350 351} // namespace clang352 353bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {354 BackendCon->DiagnosticHandlerImpl(DI);355 return true;356}357 358/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr359/// buffer to be a valid FullSourceLoc.360static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,361 SourceManager &CSM) {362 // Get both the clang and llvm source managers. The location is relative to363 // a memory buffer that the LLVM Source Manager is handling, we need to add364 // a copy to the Clang source manager.365 const llvm::SourceMgr &LSM = *D.getSourceMgr();366 367 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr368 // already owns its one and clang::SourceManager wants to own its one.369 const MemoryBuffer *LBuf =370 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));371 372 // Create the copy and transfer ownership to clang::SourceManager.373 // TODO: Avoid copying files into memory.374 std::unique_ptr<llvm::MemoryBuffer> CBuf =375 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),376 LBuf->getBufferIdentifier());377 // FIXME: Keep a file ID map instead of creating new IDs for each location.378 FileID FID = CSM.createFileID(std::move(CBuf));379 380 // Translate the offset into the file.381 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();382 SourceLocation NewLoc =383 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);384 return FullSourceLoc(NewLoc, CSM);385}386 387#define ComputeDiagID(Severity, GroupName, DiagID) \388 do { \389 switch (Severity) { \390 case llvm::DS_Error: \391 DiagID = diag::err_fe_##GroupName; \392 break; \393 case llvm::DS_Warning: \394 DiagID = diag::warn_fe_##GroupName; \395 break; \396 case llvm::DS_Remark: \397 llvm_unreachable("'remark' severity not expected"); \398 break; \399 case llvm::DS_Note: \400 DiagID = diag::note_fe_##GroupName; \401 break; \402 } \403 } while (false)404 405#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \406 do { \407 switch (Severity) { \408 case llvm::DS_Error: \409 DiagID = diag::err_fe_##GroupName; \410 break; \411 case llvm::DS_Warning: \412 DiagID = diag::warn_fe_##GroupName; \413 break; \414 case llvm::DS_Remark: \415 DiagID = diag::remark_fe_##GroupName; \416 break; \417 case llvm::DS_Note: \418 DiagID = diag::note_fe_##GroupName; \419 break; \420 } \421 } while (false)422 423void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {424 const llvm::SMDiagnostic &D = DI.getSMDiag();425 426 unsigned DiagID;427 if (DI.isInlineAsmDiag())428 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);429 else430 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);431 432 // This is for the empty BackendConsumer that uses the clang diagnostic433 // handler for IR input files.434 if (!Context) {435 D.print(nullptr, llvm::errs());436 Diags.Report(DiagID).AddString("cannot compile inline asm");437 return;438 }439 440 // There are a couple of different kinds of errors we could get here.441 // First, we re-format the SMDiagnostic in terms of a clang diagnostic.442 443 // Strip "error: " off the start of the message string.444 StringRef Message = D.getMessage();445 (void)Message.consume_front("error: ");446 447 // If the SMDiagnostic has an inline asm source location, translate it.448 FullSourceLoc Loc;449 if (D.getLoc() != SMLoc())450 Loc = ConvertBackendLocation(D, Context->getSourceManager());451 452 // If this problem has clang-level source location information, report the453 // issue in the source with a note showing the instantiated454 // code.455 if (DI.isInlineAsmDiag()) {456 SourceLocation LocCookie =457 SourceLocation::getFromRawEncoding(DI.getLocCookie());458 if (LocCookie.isValid()) {459 Diags.Report(LocCookie, DiagID).AddString(Message);460 461 if (D.getLoc().isValid()) {462 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);463 // Convert the SMDiagnostic ranges into SourceRange and attach them464 // to the diagnostic.465 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {466 unsigned Column = D.getColumnNo();467 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),468 Loc.getLocWithOffset(Range.second - Column));469 }470 }471 return;472 }473 }474 475 // Otherwise, report the backend issue as occurring in the generated .s file.476 // If Loc is invalid, we still need to report the issue, it just gets no477 // location info.478 Diags.Report(Loc, DiagID).AddString(Message);479}480 481bool482BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {483 unsigned DiagID;484 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);485 std::string Message = D.getMsgStr().str();486 487 // If this problem has clang-level source location information, report the488 // issue as being a problem in the source with a note showing the instantiated489 // code.490 SourceLocation LocCookie =491 SourceLocation::getFromRawEncoding(D.getLocCookie());492 if (LocCookie.isValid())493 Diags.Report(LocCookie, DiagID).AddString(Message);494 else {495 // Otherwise, report the backend diagnostic as occurring in the generated496 // .s file.497 // If Loc is invalid, we still need to report the diagnostic, it just gets498 // no location info.499 FullSourceLoc Loc;500 Diags.Report(Loc, DiagID).AddString(Message);501 }502 // We handled all the possible severities.503 return true;504}505 506bool507BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {508 if (D.getSeverity() != llvm::DS_Warning)509 // For now, the only support we have for StackSize diagnostic is warning.510 // We do not know how to format other severities.511 return false;512 513 auto Loc = getFunctionSourceLocation(D.getFunction());514 if (!Loc)515 return false;516 517 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)518 << D.getStackSize() << D.getStackLimit()519 << llvm::demangle(D.getFunction().getName());520 return true;521}522 523bool BackendConsumer::ResourceLimitDiagHandler(524 const llvm::DiagnosticInfoResourceLimit &D) {525 auto Loc = getFunctionSourceLocation(D.getFunction());526 if (!Loc)527 return false;528 unsigned DiagID = diag::err_fe_backend_resource_limit;529 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);530 531 Diags.Report(*Loc, DiagID)532 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()533 << llvm::demangle(D.getFunction().getName());534 return true;535}536 537const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(538 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,539 StringRef &Filename, unsigned &Line, unsigned &Column) const {540 SourceManager &SourceMgr = Context->getSourceManager();541 FileManager &FileMgr = SourceMgr.getFileManager();542 SourceLocation DILoc;543 544 if (D.isLocationAvailable()) {545 D.getLocation(Filename, Line, Column);546 if (Line > 0) {547 auto FE = FileMgr.getOptionalFileRef(Filename);548 if (!FE)549 FE = FileMgr.getOptionalFileRef(D.getAbsolutePath());550 if (FE) {551 // If -gcolumn-info was not used, Column will be 0. This upsets the552 // source manager, so pass 1 if Column is not set.553 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);554 }555 }556 BadDebugInfo = DILoc.isInvalid();557 }558 559 // If a location isn't available, try to approximate it using the associated560 // function definition. We use the definition's right brace to differentiate561 // from diagnostics that genuinely relate to the function itself.562 FullSourceLoc Loc(DILoc, SourceMgr);563 if (Loc.isInvalid()) {564 if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))565 Loc = *MaybeLoc;566 }567 568 if (DILoc.isInvalid() && D.isLocationAvailable())569 // If we were not able to translate the file:line:col information570 // back to a SourceLocation, at least emit a note stating that571 // we could not translate this location. This can happen in the572 // case of #line directives.573 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)574 << Filename << Line << Column;575 576 return Loc;577}578 579std::optional<FullSourceLoc>580BackendConsumer::getFunctionSourceLocation(const Function &F) const {581 auto Hash = llvm::hash_value(F.getName());582 for (const auto &Pair : ManglingFullSourceLocs) {583 if (Pair.first == Hash)584 return Pair.second;585 }586 return std::nullopt;587}588 589void BackendConsumer::UnsupportedDiagHandler(590 const llvm::DiagnosticInfoUnsupported &D) {591 // We only support warnings or errors.592 assert(D.getSeverity() == llvm::DS_Error ||593 D.getSeverity() == llvm::DS_Warning);594 595 StringRef Filename;596 unsigned Line, Column;597 bool BadDebugInfo = false;598 FullSourceLoc Loc;599 std::string Msg;600 raw_string_ostream MsgStream(Msg);601 602 // Context will be nullptr for IR input files, we will construct the diag603 // message from llvm::DiagnosticInfoUnsupported.604 if (Context != nullptr) {605 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);606 MsgStream << D.getMessage();607 } else {608 DiagnosticPrinterRawOStream DP(MsgStream);609 D.print(DP);610 }611 612 auto DiagType = D.getSeverity() == llvm::DS_Error613 ? diag::err_fe_backend_unsupported614 : diag::warn_fe_backend_unsupported;615 Diags.Report(Loc, DiagType) << Msg;616 617 if (BadDebugInfo)618 // If we were not able to translate the file:line:col information619 // back to a SourceLocation, at least emit a note stating that620 // we could not translate this location. This can happen in the621 // case of #line directives.622 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)623 << Filename << Line << Column;624}625 626void BackendConsumer::EmitOptimizationMessage(627 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {628 // We only support warnings and remarks.629 assert(D.getSeverity() == llvm::DS_Remark ||630 D.getSeverity() == llvm::DS_Warning);631 632 StringRef Filename;633 unsigned Line, Column;634 bool BadDebugInfo = false;635 FullSourceLoc Loc;636 std::string Msg;637 raw_string_ostream MsgStream(Msg);638 639 // Context will be nullptr for IR input files, we will construct the remark640 // message from llvm::DiagnosticInfoOptimizationBase.641 if (Context != nullptr) {642 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);643 MsgStream << D.getMsg();644 } else {645 DiagnosticPrinterRawOStream DP(MsgStream);646 D.print(DP);647 }648 649 if (D.getHotness())650 MsgStream << " (hotness: " << *D.getHotness() << ")";651 652 Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName()) << Msg;653 654 if (BadDebugInfo)655 // If we were not able to translate the file:line:col information656 // back to a SourceLocation, at least emit a note stating that657 // we could not translate this location. This can happen in the658 // case of #line directives.659 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)660 << Filename << Line << Column;661}662 663void BackendConsumer::OptimizationRemarkHandler(664 const llvm::DiagnosticInfoOptimizationBase &D) {665 // Without hotness information, don't show noisy remarks.666 if (D.isVerbose() && !D.getHotness())667 return;668 669 if (D.isPassed()) {670 // Optimization remarks are active only if the -Rpass flag has a regular671 // expression that matches the name of the pass name in \p D.672 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))673 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);674 } else if (D.isMissed()) {675 // Missed optimization remarks are active only if the -Rpass-missed676 // flag has a regular expression that matches the name of the pass677 // name in \p D.678 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))679 EmitOptimizationMessage(680 D, diag::remark_fe_backend_optimization_remark_missed);681 } else {682 assert(D.isAnalysis() && "Unknown remark type");683 684 bool ShouldAlwaysPrint = false;685 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))686 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();687 688 if (ShouldAlwaysPrint ||689 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))690 EmitOptimizationMessage(691 D, diag::remark_fe_backend_optimization_remark_analysis);692 }693}694 695void BackendConsumer::OptimizationRemarkHandler(696 const llvm::OptimizationRemarkAnalysisFPCommute &D) {697 // Optimization analysis remarks are active if the pass name is set to698 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a699 // regular expression that matches the name of the pass name in \p D.700 701 if (D.shouldAlwaysPrint() ||702 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))703 EmitOptimizationMessage(704 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);705}706 707void BackendConsumer::OptimizationRemarkHandler(708 const llvm::OptimizationRemarkAnalysisAliasing &D) {709 // Optimization analysis remarks are active if the pass name is set to710 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a711 // regular expression that matches the name of the pass name in \p D.712 713 if (D.shouldAlwaysPrint() ||714 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))715 EmitOptimizationMessage(716 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);717}718 719void BackendConsumer::OptimizationFailureHandler(720 const llvm::DiagnosticInfoOptimizationFailure &D) {721 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);722}723 724void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {725 SourceLocation LocCookie =726 SourceLocation::getFromRawEncoding(D.getLocCookie());727 728 // FIXME: we can't yet diagnose indirect calls. When/if we can, we729 // should instead assert that LocCookie.isValid().730 if (!LocCookie.isValid())731 return;732 733 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error734 ? diag::err_fe_backend_error_attr735 : diag::warn_fe_backend_warning_attr)736 << llvm::demangle(D.getFunctionName()) << D.getNote();737}738 739void BackendConsumer::MisExpectDiagHandler(740 const llvm::DiagnosticInfoMisExpect &D) {741 StringRef Filename;742 unsigned Line, Column;743 bool BadDebugInfo = false;744 FullSourceLoc Loc =745 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);746 747 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();748 749 if (BadDebugInfo)750 // If we were not able to translate the file:line:col information751 // back to a SourceLocation, at least emit a note stating that752 // we could not translate this location. This can happen in the753 // case of #line directives.754 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)755 << Filename << Line << Column;756}757 758/// This function is invoked when the backend needs759/// to report something to the user.760void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {761 unsigned DiagID = diag::err_fe_inline_asm;762 llvm::DiagnosticSeverity Severity = DI.getSeverity();763 // Get the diagnostic ID based.764 switch (DI.getKind()) {765 case llvm::DK_InlineAsm:766 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))767 return;768 ComputeDiagID(Severity, inline_asm, DiagID);769 break;770 case llvm::DK_SrcMgr:771 SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI));772 return;773 case llvm::DK_StackSize:774 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))775 return;776 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);777 break;778 case llvm::DK_ResourceLimit:779 if (ResourceLimitDiagHandler(cast<DiagnosticInfoResourceLimit>(DI)))780 return;781 ComputeDiagID(Severity, backend_resource_limit, DiagID);782 break;783 case DK_Linker:784 ComputeDiagID(Severity, linking_module, DiagID);785 break;786 case llvm::DK_OptimizationRemark:787 // Optimization remarks are always handled completely by this788 // handler. There is no generic way of emitting them.789 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));790 return;791 case llvm::DK_OptimizationRemarkMissed:792 // Optimization remarks are always handled completely by this793 // handler. There is no generic way of emitting them.794 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));795 return;796 case llvm::DK_OptimizationRemarkAnalysis:797 // Optimization remarks are always handled completely by this798 // handler. There is no generic way of emitting them.799 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));800 return;801 case llvm::DK_OptimizationRemarkAnalysisFPCommute:802 // Optimization remarks are always handled completely by this803 // handler. There is no generic way of emitting them.804 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));805 return;806 case llvm::DK_OptimizationRemarkAnalysisAliasing:807 // Optimization remarks are always handled completely by this808 // handler. There is no generic way of emitting them.809 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));810 return;811 case llvm::DK_MachineOptimizationRemark:812 // Optimization remarks are always handled completely by this813 // handler. There is no generic way of emitting them.814 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));815 return;816 case llvm::DK_MachineOptimizationRemarkMissed:817 // Optimization remarks are always handled completely by this818 // handler. There is no generic way of emitting them.819 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));820 return;821 case llvm::DK_MachineOptimizationRemarkAnalysis:822 // Optimization remarks are always handled completely by this823 // handler. There is no generic way of emitting them.824 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));825 return;826 case llvm::DK_OptimizationFailure:827 // Optimization failures are always handled completely by this828 // handler.829 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));830 return;831 case llvm::DK_Unsupported:832 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));833 return;834 case llvm::DK_DontCall:835 DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI));836 return;837 case llvm::DK_MisExpect:838 MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));839 return;840 default:841 // Plugin IDs are not bound to any value as they are set dynamically.842 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);843 break;844 }845 std::string MsgStorage;846 {847 raw_string_ostream Stream(MsgStorage);848 DiagnosticPrinterRawOStream DP(Stream);849 DI.print(DP);850 }851 852 if (DI.getKind() == DK_Linker) {853 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");854 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;855 return;856 }857 858 // Report the backend message using the usual diagnostic mechanism.859 FullSourceLoc Loc;860 Diags.Report(Loc, DiagID).AddString(MsgStorage);861}862#undef ComputeDiagID863 864CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)865 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),866 OwnsVMContext(!_VMContext) {}867 868CodeGenAction::~CodeGenAction() {869 TheModule.reset();870 if (OwnsVMContext)871 delete VMContext;872}873 874bool CodeGenAction::loadLinkModules(CompilerInstance &CI) {875 if (!LinkModules.empty())876 return false;877 878 for (const CodeGenOptions::BitcodeFileToLink &F :879 CI.getCodeGenOpts().LinkBitcodeFiles) {880 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);881 if (!BCBuf) {882 CI.getDiagnostics().Report(diag::err_cannot_open_file)883 << F.Filename << BCBuf.getError().message();884 LinkModules.clear();885 return true;886 }887 888 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =889 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);890 if (!ModuleOrErr) {891 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {892 CI.getDiagnostics().Report(diag::err_cannot_open_file)893 << F.Filename << EIB.message();894 });895 LinkModules.clear();896 return true;897 }898 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,899 F.Internalize, F.LinkFlags});900 }901 return false;902}903 904bool CodeGenAction::hasIRSupport() const { return true; }905 906void CodeGenAction::EndSourceFileAction() {907 ASTFrontendAction::EndSourceFileAction();908 909 // If the consumer creation failed, do nothing.910 if (!getCompilerInstance().hasASTConsumer())911 return;912 913 // Steal the module from the consumer.914 TheModule = BEConsumer->takeModule();915}916 917std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {918 return std::move(TheModule);919}920 921llvm::LLVMContext *CodeGenAction::takeLLVMContext() {922 OwnsVMContext = false;923 return VMContext;924}925 926CodeGenerator *CodeGenAction::getCodeGenerator() const {927 return BEConsumer->getCodeGenerator();928}929 930bool CodeGenAction::BeginSourceFileAction(CompilerInstance &CI) {931 if (CI.getFrontendOpts().GenReducedBMI)932 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);933 return ASTFrontendAction::BeginSourceFileAction(CI);934}935 936static std::unique_ptr<raw_pwrite_stream>937GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {938 switch (Action) {939 case Backend_EmitAssembly:940 return CI.createDefaultOutputFile(false, InFile, "s");941 case Backend_EmitLL:942 return CI.createDefaultOutputFile(false, InFile, "ll");943 case Backend_EmitBC:944 return CI.createDefaultOutputFile(true, InFile, "bc");945 case Backend_EmitNothing:946 return nullptr;947 case Backend_EmitMCNull:948 return CI.createNullOutputFile();949 case Backend_EmitObj:950 return CI.createDefaultOutputFile(true, InFile, "o");951 }952 953 llvm_unreachable("Invalid action!");954}955 956std::unique_ptr<ASTConsumer>957CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {958 BackendAction BA = static_cast<BackendAction>(Act);959 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();960 if (!OS)961 OS = GetOutputStream(CI, InFile, BA);962 963 if (BA != Backend_EmitNothing && !OS)964 return nullptr;965 966 // Load bitcode modules to link with, if we need to.967 if (loadLinkModules(CI))968 return nullptr;969 970 CoverageSourceInfo *CoverageInfo = nullptr;971 // Add the preprocessor callback only when the coverage mapping is generated.972 if (CI.getCodeGenOpts().CoverageMapping)973 CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(974 CI.getPreprocessor());975 976 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(977 CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules),978 InFile, std::move(OS), CoverageInfo));979 BEConsumer = Result.get();980 981 // Enable generating macro debug info only when debug info is not disabled and982 // also macro debug info is enabled.983 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&984 CI.getCodeGenOpts().MacroDebugInfo) {985 std::unique_ptr<PPCallbacks> Callbacks =986 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),987 CI.getPreprocessor());988 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));989 }990 991 if (CI.getFrontendOpts().GenReducedBMI &&992 !CI.getFrontendOpts().ModuleOutputPath.empty()) {993 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);994 Consumers[0] = std::make_unique<ReducedBMIGenerator>(995 CI.getPreprocessor(), CI.getModuleCache(),996 CI.getFrontendOpts().ModuleOutputPath, CI.getCodeGenOpts());997 Consumers[1] = std::move(Result);998 return std::make_unique<MultiplexConsumer>(std::move(Consumers));999 }1000 1001 return std::move(Result);1002}1003 1004std::unique_ptr<llvm::Module>1005CodeGenAction::loadModule(MemoryBufferRef MBRef) {1006 CompilerInstance &CI = getCompilerInstance();1007 SourceManager &SM = CI.getSourceManager();1008 1009 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {1010 unsigned DiagID =1011 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");1012 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {1013 CI.getDiagnostics().Report(DiagID) << EIB.message();1014 });1015 return {};1016 };1017 1018 // For ThinLTO backend invocations, ensure that the context1019 // merges types based on ODR identifiers. We also need to read1020 // the correct module out of a multi-module bitcode file.1021 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {1022 VMContext->enableDebugTypeODRUniquing();1023 1024 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);1025 if (!BMsOrErr)1026 return DiagErrors(BMsOrErr.takeError());1027 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);1028 // We have nothing to do if the file contains no ThinLTO module. This is1029 // possible if ThinLTO compilation was not able to split module. Content of1030 // the file was already processed by indexing and will be passed to the1031 // linker using merged object file.1032 if (!Bm) {1033 auto M = std::make_unique<llvm::Module>("empty", *VMContext);1034 M->setTargetTriple(Triple(CI.getTargetOpts().Triple));1035 return M;1036 }1037 Expected<std::unique_ptr<llvm::Module>> MOrErr =1038 Bm->parseModule(*VMContext);1039 if (!MOrErr)1040 return DiagErrors(MOrErr.takeError());1041 return std::move(*MOrErr);1042 }1043 1044 // Load bitcode modules to link with, if we need to.1045 if (loadLinkModules(CI))1046 return nullptr;1047 1048 // Handle textual IR and bitcode file with one single module.1049 llvm::SMDiagnostic Err;1050 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) {1051 // For LLVM IR files, always verify the input and report the error in a way1052 // that does not ask people to report an issue for it.1053 std::string VerifierErr;1054 raw_string_ostream VerifierErrStream(VerifierErr);1055 if (llvm::verifyModule(*M, &VerifierErrStream)) {1056 CI.getDiagnostics().Report(diag::err_invalid_llvm_ir) << VerifierErr;1057 return {};1058 }1059 return M;1060 }1061 1062 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit1063 // output), place the extra modules (actually only one, a regular LTO module)1064 // into LinkModules as if we are using -mlink-bitcode-file.1065 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);1066 if (BMsOrErr && BMsOrErr->size()) {1067 std::unique_ptr<llvm::Module> FirstM;1068 for (auto &BM : *BMsOrErr) {1069 Expected<std::unique_ptr<llvm::Module>> MOrErr =1070 BM.parseModule(*VMContext);1071 if (!MOrErr)1072 return DiagErrors(MOrErr.takeError());1073 if (FirstM)1074 LinkModules.push_back({std::move(*MOrErr), /*PropagateAttrs=*/false,1075 /*Internalize=*/false, /*LinkFlags=*/{}});1076 else1077 FirstM = std::move(*MOrErr);1078 }1079 if (FirstM)1080 return FirstM;1081 }1082 // If BMsOrErr fails, consume the error and use the error message from1083 // parseIR.1084 consumeError(BMsOrErr.takeError());1085 1086 // Translate from the diagnostic info to the SourceManager location if1087 // available.1088 // TODO: Unify this with ConvertBackendLocation()1089 SourceLocation Loc;1090 if (Err.getLineNo() > 0) {1091 assert(Err.getColumnNo() >= 0);1092 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),1093 Err.getLineNo(), Err.getColumnNo() + 1);1094 }1095 1096 // Strip off a leading diagnostic code if there is one.1097 StringRef Msg = Err.getMessage();1098 Msg.consume_front("error: ");1099 1100 unsigned DiagID =1101 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");1102 1103 CI.getDiagnostics().Report(Loc, DiagID) << Msg;1104 return {};1105}1106 1107void CodeGenAction::ExecuteAction() {1108 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {1109 this->ASTFrontendAction::ExecuteAction();1110 return;1111 }1112 1113 // If this is an IR file, we have to treat it specially.1114 BackendAction BA = static_cast<BackendAction>(Act);1115 CompilerInstance &CI = getCompilerInstance();1116 auto &CodeGenOpts = CI.getCodeGenOpts();1117 auto &Diagnostics = CI.getDiagnostics();1118 std::unique_ptr<raw_pwrite_stream> OS =1119 GetOutputStream(CI, getCurrentFileOrBufferName(), BA);1120 if (BA != Backend_EmitNothing && !OS)1121 return;1122 1123 SourceManager &SM = CI.getSourceManager();1124 FileID FID = SM.getMainFileID();1125 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);1126 if (!MainFile)1127 return;1128 1129 TheModule = loadModule(*MainFile);1130 if (!TheModule)1131 return;1132 1133 const TargetOptions &TargetOpts = CI.getTargetOpts();1134 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {1135 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)1136 << TargetOpts.Triple;1137 TheModule->setTargetTriple(Triple(TargetOpts.Triple));1138 }1139 1140 EmbedObject(TheModule.get(), CodeGenOpts, CI.getVirtualFileSystem(),1141 Diagnostics);1142 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);1143 1144 LLVMContext &Ctx = TheModule->getContext();1145 1146 // Restore any diagnostic handler previously set before returning from this1147 // function.1148 struct RAII {1149 LLVMContext &Ctx;1150 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();1151 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }1152 } _{Ctx};1153 1154 // Set clang diagnostic handler. To do this we need to create a fake1155 // BackendConsumer.1156 BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext,1157 std::move(LinkModules), "", nullptr, nullptr,1158 TheModule.get());1159 1160 // Link in each pending link module.1161 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))1162 return;1163 1164 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be1165 // true here because the valued names are needed for reading textual IR.1166 Ctx.setDiscardValueNames(false);1167 Ctx.setDiagnosticHandler(1168 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));1169 1170 Ctx.setDefaultTargetCPU(TargetOpts.CPU);1171 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));1172 1173 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =1174 setupLLVMOptimizationRemarks(1175 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,1176 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,1177 CodeGenOpts.DiagnosticsHotnessThreshold);1178 1179 if (Error E = OptRecordFileOrErr.takeError()) {1180 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);1181 return;1182 }1183 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);1184 1185 emitBackendOutput(CI, CI.getCodeGenOpts(),1186 CI.getTarget().getDataLayoutString(), TheModule.get(), BA,1187 CI.getFileManager().getVirtualFileSystemPtr(),1188 std::move(OS));1189 if (OptRecordFile)1190 OptRecordFile->keep();1191}1192 1193//1194 1195void EmitAssemblyAction::anchor() { }1196EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)1197 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}1198 1199void EmitBCAction::anchor() { }1200EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)1201 : CodeGenAction(Backend_EmitBC, _VMContext) {}1202 1203void EmitLLVMAction::anchor() { }1204EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)1205 : CodeGenAction(Backend_EmitLL, _VMContext) {}1206 1207void EmitLLVMOnlyAction::anchor() { }1208EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)1209 : CodeGenAction(Backend_EmitNothing, _VMContext) {}1210 1211void EmitCodeGenOnlyAction::anchor() { }1212EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)1213 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}1214 1215void EmitObjAction::anchor() { }1216EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)1217 : CodeGenAction(Backend_EmitObj, _VMContext) {}1218