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