| 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 "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/ScopeExit.h" |
| 32 | #include "llvm/Bitcode/BitcodeReader.h" |
| 33 | #include "llvm/IR/DebugInfo.h" |
| 34 | #include "llvm/IR/DiagnosticInfo.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/IR/PassTimingInfo.h" |
| 40 | #include "llvm/IR/Verifier.h" |
| 41 | #include "llvm/IRReader/IRReader.h" |
| 42 | #include "llvm/LTO/LTOBackend.h" |
| 43 | #include "llvm/Pass.h" |
| 44 | #include "llvm/Support/LibraryOptionsContext.h" |
| 45 | #include "llvm/Support/ManagedStatic.h" |
| 46 | #include "llvm/Support/MemoryBuffer.h" |
| 47 | #include "llvm/Support/Mutex.h" |
| 48 | #include "llvm/Support/SourceMgr.h" |
| 49 | #include "llvm/Support/TimeProfiler.h" |
| 50 | #include "llvm/Support/Timer.h" |
| 51 | #include "llvm/Support/ToolOutputFile.h" |
| 52 | #include "llvm/Transforms/Utils/Cloning.h" |
| 53 | |
| 54 | #include <optional> |
| 55 | using namespace clang; |
| 56 | using namespace llvm; |
| 57 | |
| 58 | #define DEBUG_TYPE "codegenaction" |
| 59 | |
| 60 | namespace { |
| 61 | llvm::ManagedStatic<llvm::sys::SmartMutex<true>> TimePassesMutex; |
| 62 | } |
| 63 | |
| 64 | namespace clang { |
| 65 | |
| 66 | static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, |
| 67 | const CodeGenOptions &CodeGenOpts) { |
| 68 | handleAllErrors( |
| 69 | E: std::move(E), |
| 70 | Handlers: [&](const LLVMRemarkSetupFileError &E) { |
| 71 | Diags.Report(DiagID: diag::err_cannot_open_file) |
| 72 | << CodeGenOpts.OptRecordFile << E.message(); |
| 73 | }, |
| 74 | Handlers: [&](const LLVMRemarkSetupPatternError &E) { |
| 75 | Diags.Report(DiagID: diag::err_drv_optimization_remark_pattern) |
| 76 | << E.message() << CodeGenOpts.OptRecordPasses; |
| 77 | }, |
| 78 | Handlers: [&](const LLVMRemarkSetupFormatError &E) { |
| 79 | Diags.Report(DiagID: diag::err_drv_optimization_remark_format) |
| 80 | << CodeGenOpts.OptRecordFormat; |
| 81 | }); |
| 82 | } |
| 83 | |
| 84 | BackendConsumer::BackendConsumer(CompilerInstance &CI, BackendAction Action, |
| 85 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, |
| 86 | LLVMContext &C, |
| 87 | SmallVector<LinkModule, 4> LinkModules, |
| 88 | StringRef InFile, |
| 89 | std::unique_ptr<raw_pwrite_stream> OS, |
| 90 | CoverageSourceInfo *CoverageInfo, |
| 91 | llvm::Module *CurLinkModule) |
| 92 | : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()), |
| 93 | TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), |
| 94 | AsmOutStream(std::move(OS)), FS(VFS), Action(Action), |
| 95 | Gen(CreateLLVMCodeGen(CI, ModuleName: InFile, C, CoverageInfo)), |
| 96 | LinkModules(std::move(LinkModules)), DiagConsumer(Diags, CodeGenOpts) { |
| 97 | DiagConsumer.setCurLinkModule(CurLinkModule); |
| 98 | TimerIsEnabled = CodeGenOpts.TimePasses; |
| 99 | { |
| 100 | llvm::sys::SmartScopedLock<true> Lock(*TimePassesMutex); |
| 101 | llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses; |
| 102 | llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun; |
| 103 | } |
| 104 | if (CodeGenOpts.TimePasses) |
| 105 | LLVMIRGeneration.init(TimerName: "irgen" , TimerDescription: "LLVM IR generation" , tg&: CI.getTimerGroup()); |
| 106 | } |
| 107 | |
| 108 | llvm::Module* BackendConsumer::getModule() const { |
| 109 | return Gen->GetModule(); |
| 110 | } |
| 111 | |
| 112 | std::unique_ptr<llvm::Module> BackendConsumer::takeModule() { |
| 113 | return std::unique_ptr<llvm::Module>(Gen->ReleaseModule()); |
| 114 | } |
| 115 | |
| 116 | CodeGenerator* BackendConsumer::getCodeGenerator() { |
| 117 | return Gen.get(); |
| 118 | } |
| 119 | |
| 120 | void BackendConsumer::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { |
| 121 | Gen->HandleCXXStaticMemberVarInstantiation(D: VD); |
| 122 | } |
| 123 | |
| 124 | void BackendConsumer::Initialize(ASTContext &Ctx) { |
| 125 | assert(!Context && "initialized multiple times" ); |
| 126 | |
| 127 | Context = &Ctx; |
| 128 | DiagConsumer.setSourceManager(&Ctx.getSourceManager()); |
| 129 | |
| 130 | if (TimerIsEnabled) |
| 131 | LLVMIRGeneration.startTimer(); |
| 132 | |
| 133 | Gen->Initialize(Context&: Ctx); |
| 134 | |
| 135 | if (TimerIsEnabled) |
| 136 | LLVMIRGeneration.stopTimer(); |
| 137 | } |
| 138 | |
| 139 | bool BackendConsumer::HandleTopLevelDecl(DeclGroupRef D) { |
| 140 | PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), |
| 141 | Context->getSourceManager(), |
| 142 | "LLVM IR generation of declaration" ); |
| 143 | |
| 144 | // Recurse. |
| 145 | if (TimerIsEnabled && !LLVMIRGenerationRefCount++) |
| 146 | CI.getFrontendTimer().yieldTo(LLVMIRGeneration); |
| 147 | |
| 148 | Gen->HandleTopLevelDecl(D); |
| 149 | |
| 150 | if (TimerIsEnabled && !--LLVMIRGenerationRefCount) |
| 151 | LLVMIRGeneration.yieldTo(CI.getFrontendTimer()); |
| 152 | |
| 153 | return true; |
| 154 | } |
| 155 | |
| 156 | void BackendConsumer::HandleInlineFunctionDefinition(FunctionDecl *D) { |
| 157 | PrettyStackTraceDecl CrashInfo(D, SourceLocation(), |
| 158 | Context->getSourceManager(), |
| 159 | "LLVM IR generation of inline function" ); |
| 160 | if (TimerIsEnabled) |
| 161 | CI.getFrontendTimer().yieldTo(LLVMIRGeneration); |
| 162 | |
| 163 | Gen->HandleInlineFunctionDefinition(D); |
| 164 | |
| 165 | if (TimerIsEnabled) |
| 166 | LLVMIRGeneration.yieldTo(CI.getFrontendTimer()); |
| 167 | } |
| 168 | |
| 169 | void BackendConsumer::HandleInterestingDecl(DeclGroupRef D) { |
| 170 | HandleTopLevelDecl(D); |
| 171 | } |
| 172 | |
| 173 | // Links each entry in LinkModules into our module. Returns true on error. |
| 174 | bool BackendConsumer::LinkInModules(llvm::Module *M) { |
| 175 | return linkInModules(M&: *M, LinkModules, CodeGenOpts, LangOpts, TargetOpts, |
| 176 | DiagConsumer); |
| 177 | } |
| 178 | |
| 179 | void BackendConsumer::HandleTranslationUnit(ASTContext &C) { |
| 180 | { |
| 181 | llvm::TimeTraceScope TimeScope("Frontend" ); |
| 182 | PrettyStackTraceString CrashInfo("Per-file LLVM IR generation" ); |
| 183 | if (TimerIsEnabled && !LLVMIRGenerationRefCount++) |
| 184 | CI.getFrontendTimer().yieldTo(LLVMIRGeneration); |
| 185 | |
| 186 | Gen->HandleTranslationUnit(Ctx&: C); |
| 187 | |
| 188 | if (TimerIsEnabled && !--LLVMIRGenerationRefCount) |
| 189 | LLVMIRGeneration.yieldTo(CI.getFrontendTimer()); |
| 190 | } |
| 191 | |
| 192 | // Silently ignore if we weren't initialized for some reason. |
| 193 | if (!getModule()) |
| 194 | return; |
| 195 | |
| 196 | LLVMContext &Ctx = getModule()->getContext(); |
| 197 | std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler = |
| 198 | Ctx.getDiagnosticHandler(); |
| 199 | llvm::scope_exit RestoreDiagnosticHandler( |
| 200 | [&]() { Ctx.setDiagnosticHandler(DH: std::move(OldDiagnosticHandler)); }); |
| 201 | Ctx.setDiagnosticHandler(DH: createDiagnosticHandler()); |
| 202 | |
| 203 | Ctx.setDefaultTargetCPU(TargetOpts.CPU); |
| 204 | Ctx.setDefaultTargetFeatures(llvm::join(R: TargetOpts.Features, Separator: "," )); |
| 205 | Ctx.setVirtualFileSystem(CI.getVirtualFileSystemPtr()); |
| 206 | |
| 207 | Expected<LLVMRemarkFileHandle> OptRecordFileOrErr = |
| 208 | setupLLVMOptimizationRemarks( |
| 209 | Context&: Ctx, RemarksFilename: CodeGenOpts.OptRecordFile, RemarksPasses: CodeGenOpts.OptRecordPasses, |
| 210 | RemarksFormat: CodeGenOpts.OptRecordFormat, RemarksWithHotness: CodeGenOpts.DiagnosticsWithHotness, |
| 211 | RemarksHotnessThreshold: CodeGenOpts.DiagnosticsHotnessThreshold); |
| 212 | |
| 213 | if (Error E = OptRecordFileOrErr.takeError()) { |
| 214 | reportOptRecordError(E: std::move(E), Diags, CodeGenOpts); |
| 215 | return; |
| 216 | } |
| 217 | |
| 218 | LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr); |
| 219 | |
| 220 | if (OptRecordFile && CodeGenOpts.getProfileUse() != |
| 221 | llvm::driver::ProfileInstrKind::ProfileNone) |
| 222 | Ctx.setDiagnosticsHotnessRequested(true); |
| 223 | |
| 224 | if (CodeGenOpts.MisExpect) { |
| 225 | Ctx.setMisExpectWarningRequested(true); |
| 226 | } |
| 227 | |
| 228 | if (CodeGenOpts.DiagnosticsMisExpectTolerance) { |
| 229 | Ctx.setDiagnosticsMisExpectTolerance( |
| 230 | CodeGenOpts.DiagnosticsMisExpectTolerance); |
| 231 | } |
| 232 | |
| 233 | // Link each LinkModule into our module. |
| 234 | if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(M: getModule())) |
| 235 | return; |
| 236 | |
| 237 | for (auto &F : getModule()->functions()) { |
| 238 | if (const Decl *FD = Gen->GetDeclForMangledName(MangledName: F.getName())) { |
| 239 | auto Loc = FD->getASTContext().getFullLoc(Loc: FD->getLocation()); |
| 240 | DiagConsumer.addFunctionSourceLocation(MangledName: F.getName(), Loc); |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | if (CodeGenOpts.ClearASTBeforeBackend) { |
| 245 | LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n" ); |
| 246 | // Access to the AST is no longer available after this. |
| 247 | // Other things that the ASTContext manages are still available, e.g. |
| 248 | // the SourceManager. It'd be nice if we could separate out all the |
| 249 | // things in ASTContext used after this point and null out the |
| 250 | // ASTContext, but too many various parts of the ASTContext are still |
| 251 | // used in various parts. |
| 252 | C.cleanup(); |
| 253 | C.getAllocator().Reset(); |
| 254 | } |
| 255 | |
| 256 | EmbedBitcode(M: getModule(), CGOpts: CodeGenOpts, Buf: llvm::MemoryBufferRef()); |
| 257 | |
| 258 | emitBackendOutput(CI, CGOpts&: CI.getCodeGenOpts(), M: getModule(), Action, VFS: FS, |
| 259 | OS: std::move(AsmOutStream), BC: this); |
| 260 | |
| 261 | if (OptRecordFile) |
| 262 | OptRecordFile->keep(); |
| 263 | } |
| 264 | |
| 265 | void BackendConsumer::HandleTagDeclDefinition(TagDecl *D) { |
| 266 | PrettyStackTraceDecl CrashInfo(D, SourceLocation(), |
| 267 | Context->getSourceManager(), |
| 268 | "LLVM IR generation of declaration" ); |
| 269 | Gen->HandleTagDeclDefinition(D); |
| 270 | } |
| 271 | |
| 272 | void BackendConsumer::HandleTagDeclRequiredDefinition(const TagDecl *D) { |
| 273 | Gen->HandleTagDeclRequiredDefinition(D); |
| 274 | } |
| 275 | |
| 276 | void BackendConsumer::CompleteTentativeDefinition(VarDecl *D) { |
| 277 | Gen->CompleteTentativeDefinition(D); |
| 278 | } |
| 279 | |
| 280 | void BackendConsumer::CompleteExternalDeclaration(DeclaratorDecl *D) { |
| 281 | Gen->CompleteExternalDeclaration(D); |
| 282 | } |
| 283 | |
| 284 | void BackendConsumer::AssignInheritanceModel(CXXRecordDecl *RD) { |
| 285 | Gen->AssignInheritanceModel(RD); |
| 286 | } |
| 287 | |
| 288 | void BackendConsumer::HandleVTable(CXXRecordDecl *RD) { |
| 289 | Gen->HandleVTable(RD); |
| 290 | } |
| 291 | |
| 292 | void BackendConsumer::anchor() { } |
| 293 | |
| 294 | } // namespace clang |
| 295 | |
| 296 | std::unique_ptr<llvm::DiagnosticHandler> |
| 297 | BackendConsumer::createDiagnosticHandler() { |
| 298 | return DiagConsumer.createDiagnosticHandler(); |
| 299 | } |
| 300 | |
| 301 | CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) |
| 302 | : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext), |
| 303 | OwnsVMContext(!_VMContext) {} |
| 304 | |
| 305 | CodeGenAction::~CodeGenAction() { |
| 306 | TheModule.reset(); |
| 307 | if (OwnsVMContext) |
| 308 | delete VMContext; |
| 309 | } |
| 310 | |
| 311 | bool CodeGenAction::hasIRSupport() const { return true; } |
| 312 | |
| 313 | void CodeGenAction::EndSourceFileAction() { |
| 314 | ASTFrontendAction::EndSourceFileAction(); |
| 315 | |
| 316 | // If the consumer creation failed, do nothing. |
| 317 | if (!getCompilerInstance().hasASTConsumer()) |
| 318 | return; |
| 319 | |
| 320 | // Steal the module from the consumer. |
| 321 | TheModule = BEConsumer->takeModule(); |
| 322 | } |
| 323 | |
| 324 | std::unique_ptr<llvm::Module> CodeGenAction::takeModule() { |
| 325 | return std::move(TheModule); |
| 326 | } |
| 327 | |
| 328 | llvm::LLVMContext *CodeGenAction::takeLLVMContext() { |
| 329 | OwnsVMContext = false; |
| 330 | return VMContext; |
| 331 | } |
| 332 | |
| 333 | CodeGenerator *CodeGenAction::getCodeGenerator() const { |
| 334 | return BEConsumer->getCodeGenerator(); |
| 335 | } |
| 336 | |
| 337 | bool CodeGenAction::BeginSourceFileAction(CompilerInstance &CI) { |
| 338 | VMContext->getLibraryOptions().assign(Other: CI.getLibraryOptions()); |
| 339 | if (CI.getFrontendOpts().GenReducedBMI) |
| 340 | CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface); |
| 341 | return ASTFrontendAction::BeginSourceFileAction(CI); |
| 342 | } |
| 343 | |
| 344 | static std::unique_ptr<raw_pwrite_stream> |
| 345 | GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) { |
| 346 | switch (Action) { |
| 347 | case Backend_EmitAssembly: |
| 348 | return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "s" ); |
| 349 | case Backend_EmitLL: |
| 350 | return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "ll" ); |
| 351 | case Backend_EmitBC: |
| 352 | return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "bc" ); |
| 353 | case Backend_EmitNothing: |
| 354 | return nullptr; |
| 355 | case Backend_EmitMCNull: |
| 356 | return CI.createNullOutputFile(); |
| 357 | case Backend_EmitObj: |
| 358 | return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "o" ); |
| 359 | } |
| 360 | |
| 361 | llvm_unreachable("Invalid action!" ); |
| 362 | } |
| 363 | |
| 364 | std::unique_ptr<ASTConsumer> |
| 365 | CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 366 | BackendAction BA = static_cast<BackendAction>(Act); |
| 367 | std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream(); |
| 368 | if (!OS) |
| 369 | OS = GetOutputStream(CI, InFile, Action: BA); |
| 370 | |
| 371 | if (BA != Backend_EmitNothing && !OS) |
| 372 | return nullptr; |
| 373 | |
| 374 | // Load bitcode modules to link with, if we need to. |
| 375 | if (clang::loadLinkModules(CI, Ctx&: *VMContext, LinkModules)) |
| 376 | return nullptr; |
| 377 | |
| 378 | CoverageSourceInfo *CoverageInfo = nullptr; |
| 379 | // Add the preprocessor callback only when the coverage mapping is generated. |
| 380 | if (CI.getCodeGenOpts().CoverageMapping) |
| 381 | CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks( |
| 382 | CI.getPreprocessor()); |
| 383 | |
| 384 | std::unique_ptr<BackendConsumer> Result(new BackendConsumer( |
| 385 | CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules), |
| 386 | InFile, std::move(OS), CoverageInfo)); |
| 387 | BEConsumer = Result.get(); |
| 388 | |
| 389 | // Enable generating macro debug info only when debug info is not disabled and |
| 390 | // also macro debug info is enabled. |
| 391 | if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo && |
| 392 | CI.getCodeGenOpts().MacroDebugInfo) { |
| 393 | std::unique_ptr<PPCallbacks> Callbacks = |
| 394 | std::make_unique<MacroPPCallbacks>(args: BEConsumer->getCodeGenerator(), |
| 395 | args&: CI.getPreprocessor()); |
| 396 | CI.getPreprocessor().addPPCallbacks(C: std::move(Callbacks)); |
| 397 | } |
| 398 | |
| 399 | if (CI.getFrontendOpts().GenReducedBMI && |
| 400 | !CI.getFrontendOpts().ModuleOutputPath.empty()) { |
| 401 | std::vector<std::unique_ptr<ASTConsumer>> Consumers(2); |
| 402 | Consumers[0] = std::make_unique<ReducedBMIGenerator>( |
| 403 | args&: CI.getPreprocessor(), args&: CI.getModuleCache(), |
| 404 | args&: CI.getFrontendOpts().ModuleOutputPath, args&: CI.getCodeGenOpts()); |
| 405 | Consumers[1] = std::move(Result); |
| 406 | return std::make_unique<MultiplexConsumer>(args: std::move(Consumers)); |
| 407 | } |
| 408 | |
| 409 | return std::move(Result); |
| 410 | } |
| 411 | |
| 412 | std::unique_ptr<llvm::Module> |
| 413 | CodeGenAction::loadModule(MemoryBufferRef MBRef) { |
| 414 | CompilerInstance &CI = getCompilerInstance(); |
| 415 | SourceManager &SM = CI.getSourceManager(); |
| 416 | |
| 417 | auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> { |
| 418 | unsigned DiagID = |
| 419 | CI.getDiagnostics().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0" ); |
| 420 | handleAllErrors(E: std::move(E), Handlers: [&](ErrorInfoBase &EIB) { |
| 421 | CI.getDiagnostics().Report(DiagID) << EIB.message(); |
| 422 | }); |
| 423 | return {}; |
| 424 | }; |
| 425 | |
| 426 | // For ThinLTO backend invocations, ensure that the context |
| 427 | // merges types based on ODR identifiers. We also need to read |
| 428 | // the correct module out of a multi-module bitcode file. |
| 429 | if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) { |
| 430 | VMContext->enableDebugTypeODRUniquing(); |
| 431 | |
| 432 | Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef); |
| 433 | if (!BMsOrErr) |
| 434 | return DiagErrors(BMsOrErr.takeError()); |
| 435 | BitcodeModule *Bm = llvm::lto::findThinLTOModule(BMs: *BMsOrErr); |
| 436 | // We have nothing to do if the file contains no ThinLTO module. This is |
| 437 | // possible if ThinLTO compilation was not able to split module. Content of |
| 438 | // the file was already processed by indexing and will be passed to the |
| 439 | // linker using merged object file. |
| 440 | if (!Bm) { |
| 441 | auto M = std::make_unique<llvm::Module>(args: "empty" , args&: *VMContext); |
| 442 | M->setTargetTriple(Triple(CI.getTargetOpts().Triple)); |
| 443 | return M; |
| 444 | } |
| 445 | Expected<std::unique_ptr<llvm::Module>> MOrErr = |
| 446 | Bm->parseModule(Context&: *VMContext); |
| 447 | if (!MOrErr) |
| 448 | return DiagErrors(MOrErr.takeError()); |
| 449 | return std::move(*MOrErr); |
| 450 | } |
| 451 | |
| 452 | // Load bitcode modules to link with, if we need to. |
| 453 | if (clang::loadLinkModules(CI, Ctx&: *VMContext, LinkModules)) |
| 454 | return nullptr; |
| 455 | |
| 456 | // Handle textual IR and bitcode file with one single module. |
| 457 | llvm::SMDiagnostic Err; |
| 458 | if (std::unique_ptr<llvm::Module> M = parseIR(Buffer: MBRef, Err, Context&: *VMContext)) { |
| 459 | // For LLVM IR files, always verify the input and report the error in a way |
| 460 | // that does not ask people to report an issue for it. |
| 461 | std::string VerifierErr; |
| 462 | raw_string_ostream VerifierErrStream(VerifierErr); |
| 463 | if (llvm::verifyModule(M: *M, OS: &VerifierErrStream)) { |
| 464 | CI.getDiagnostics().Report(DiagID: diag::err_invalid_llvm_ir) << VerifierErr; |
| 465 | return {}; |
| 466 | } |
| 467 | return M; |
| 468 | } |
| 469 | |
| 470 | // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit |
| 471 | // output), place the extra modules (actually only one, a regular LTO module) |
| 472 | // into LinkModules as if we are using -mlink-bitcode-file. |
| 473 | Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef); |
| 474 | if (BMsOrErr && BMsOrErr->size()) { |
| 475 | std::unique_ptr<llvm::Module> FirstM; |
| 476 | for (auto &BM : *BMsOrErr) { |
| 477 | Expected<std::unique_ptr<llvm::Module>> MOrErr = |
| 478 | BM.parseModule(Context&: *VMContext); |
| 479 | if (!MOrErr) |
| 480 | return DiagErrors(MOrErr.takeError()); |
| 481 | if (FirstM) |
| 482 | LinkModules.push_back(Elt: {.Module: std::move(*MOrErr), /*PropagateAttrs=*/false, |
| 483 | /*Internalize=*/false, /*LinkFlags=*/{}}); |
| 484 | else |
| 485 | FirstM = std::move(*MOrErr); |
| 486 | } |
| 487 | if (FirstM) |
| 488 | return FirstM; |
| 489 | } |
| 490 | // If BMsOrErr fails, consume the error and use the error message from |
| 491 | // parseIR. |
| 492 | consumeError(Err: BMsOrErr.takeError()); |
| 493 | |
| 494 | // Translate from the diagnostic info to the SourceManager location if |
| 495 | // available. |
| 496 | // TODO: Unify this with ConvertBackendLocation() |
| 497 | SourceLocation Loc; |
| 498 | if (Err.getLineNo() > 0) { |
| 499 | assert(Err.getColumnNo() >= 0); |
| 500 | Loc = SM.translateFileLineCol(SourceFile: SM.getFileEntryForID(FID: SM.getMainFileID()), |
| 501 | Line: Err.getLineNo(), Col: Err.getColumnNo() + 1); |
| 502 | } |
| 503 | |
| 504 | // Strip off a leading diagnostic code if there is one. |
| 505 | StringRef Msg = Err.getMessage(); |
| 506 | Msg.consume_front(Prefix: "error: " ); |
| 507 | |
| 508 | unsigned DiagID = |
| 509 | CI.getDiagnostics().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0" ); |
| 510 | |
| 511 | CI.getDiagnostics().Report(Loc, DiagID) << Msg; |
| 512 | return {}; |
| 513 | } |
| 514 | |
| 515 | void CodeGenAction::ExecuteAction() { |
| 516 | if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) { |
| 517 | this->ASTFrontendAction::ExecuteAction(); |
| 518 | return; |
| 519 | } |
| 520 | |
| 521 | // If this is an IR file, we have to treat it specially. |
| 522 | BackendAction BA = static_cast<BackendAction>(Act); |
| 523 | CompilerInstance &CI = getCompilerInstance(); |
| 524 | auto &CodeGenOpts = CI.getCodeGenOpts(); |
| 525 | auto &Diagnostics = CI.getDiagnostics(); |
| 526 | std::unique_ptr<raw_pwrite_stream> OS = |
| 527 | GetOutputStream(CI, InFile: getCurrentFileOrBufferName(), Action: BA); |
| 528 | if (BA != Backend_EmitNothing && !OS) |
| 529 | return; |
| 530 | |
| 531 | SourceManager &SM = CI.getSourceManager(); |
| 532 | FileID FID = SM.getMainFileID(); |
| 533 | std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID); |
| 534 | if (!MainFile) |
| 535 | return; |
| 536 | |
| 537 | TheModule = loadModule(MBRef: *MainFile); |
| 538 | if (!TheModule) |
| 539 | return; |
| 540 | |
| 541 | const TargetOptions &TargetOpts = CI.getTargetOpts(); |
| 542 | if (TheModule->getTargetTriple().str() != TargetOpts.Triple) { |
| 543 | Diagnostics.Report(Loc: SourceLocation(), DiagID: diag::warn_fe_override_module) |
| 544 | << TargetOpts.Triple; |
| 545 | TheModule->setTargetTriple(Triple(TargetOpts.Triple)); |
| 546 | } |
| 547 | |
| 548 | llvm::ExceptionHandling ExceptionModel = |
| 549 | CodeGenOptions::toExceptionHandling(Kind: CodeGenOpts.getExceptionHandling()); |
| 550 | if (ExceptionModel != llvm::ExceptionHandling::Default) { |
| 551 | StringRef ModelName = llvm::getExceptionModelName(EH: ExceptionModel); |
| 552 | if (auto *Existing = cast_or_null<llvm::MDString>( |
| 553 | Val: TheModule->getModuleFlag(Key: "exception-model" ))) { |
| 554 | if (Existing->getString() != ModelName) { |
| 555 | Diagnostics.Report(DiagID: diag::err_fe_exception_model_mismatch) |
| 556 | << ModelName << Existing->getString(); |
| 557 | return; |
| 558 | } |
| 559 | } else { |
| 560 | TheModule->addModuleFlag( |
| 561 | Behavior: llvm::Module::Error, Key: "exception-model" , |
| 562 | Val: llvm::MDString::get(Context&: TheModule->getContext(), Str: ModelName)); |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | EmbedObject(M: TheModule.get(), CGOpts: CodeGenOpts, VFS&: CI.getVirtualFileSystem(), |
| 567 | Diags&: Diagnostics); |
| 568 | EmbedBitcode(M: TheModule.get(), CGOpts: CodeGenOpts, Buf: *MainFile); |
| 569 | |
| 570 | LLVMContext &Ctx = TheModule->getContext(); |
| 571 | |
| 572 | // Restore any diagnostic handler previously set before returning from this |
| 573 | // function. |
| 574 | struct RAII { |
| 575 | LLVMContext &Ctx; |
| 576 | std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler(); |
| 577 | ~RAII() { Ctx.setDiagnosticHandler(DH: std::move(PrevHandler)); } |
| 578 | } _{.Ctx: Ctx}; |
| 579 | |
| 580 | // Set clang diagnostic handler. To do this we need to create a fake |
| 581 | // BackendConsumer. |
| 582 | BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, |
| 583 | std::move(LinkModules), "" , nullptr, nullptr, |
| 584 | TheModule.get()); |
| 585 | |
| 586 | // Link in each pending link module. |
| 587 | if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(M: &*TheModule)) |
| 588 | return; |
| 589 | |
| 590 | // Textual IR needs value names while parsing; discard new names afterwards. |
| 591 | Ctx.setDiscardValueNames(CodeGenOpts.DiscardValueNames); |
| 592 | Ctx.setDiagnosticHandler(DH: Result.createDiagnosticHandler()); |
| 593 | |
| 594 | Ctx.setDefaultTargetCPU(TargetOpts.CPU); |
| 595 | Ctx.setDefaultTargetFeatures(llvm::join(R: TargetOpts.Features, Separator: "," )); |
| 596 | Ctx.setVirtualFileSystem(CI.getVirtualFileSystemPtr()); |
| 597 | |
| 598 | Expected<LLVMRemarkFileHandle> OptRecordFileOrErr = |
| 599 | setupLLVMOptimizationRemarks( |
| 600 | Context&: Ctx, RemarksFilename: CodeGenOpts.OptRecordFile, RemarksPasses: CodeGenOpts.OptRecordPasses, |
| 601 | RemarksFormat: CodeGenOpts.OptRecordFormat, RemarksWithHotness: CodeGenOpts.DiagnosticsWithHotness, |
| 602 | RemarksHotnessThreshold: CodeGenOpts.DiagnosticsHotnessThreshold); |
| 603 | |
| 604 | if (Error E = OptRecordFileOrErr.takeError()) { |
| 605 | reportOptRecordError(E: std::move(E), Diags&: Diagnostics, CodeGenOpts); |
| 606 | return; |
| 607 | } |
| 608 | LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr); |
| 609 | |
| 610 | emitBackendOutput(CI, CGOpts&: CI.getCodeGenOpts(), M: TheModule.get(), Action: BA, |
| 611 | VFS: CI.getFileManager().getVirtualFileSystemPtr(), |
| 612 | OS: std::move(OS)); |
| 613 | if (OptRecordFile) |
| 614 | OptRecordFile->keep(); |
| 615 | } |
| 616 | |
| 617 | // |
| 618 | |
| 619 | void EmitAssemblyAction::anchor() { } |
| 620 | EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) |
| 621 | : CodeGenAction(Backend_EmitAssembly, _VMContext) {} |
| 622 | |
| 623 | void EmitBCAction::anchor() { } |
| 624 | EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) |
| 625 | : CodeGenAction(Backend_EmitBC, _VMContext) {} |
| 626 | |
| 627 | void EmitLLVMAction::anchor() { } |
| 628 | EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) |
| 629 | : CodeGenAction(Backend_EmitLL, _VMContext) {} |
| 630 | |
| 631 | void EmitLLVMOnlyAction::anchor() { } |
| 632 | EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) |
| 633 | : CodeGenAction(Backend_EmitNothing, _VMContext) {} |
| 634 | |
| 635 | void EmitCodeGenOnlyAction::anchor() { } |
| 636 | EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) |
| 637 | : CodeGenAction(Backend_EmitMCNull, _VMContext) {} |
| 638 | |
| 639 | void EmitObjAction::anchor() { } |
| 640 | EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) |
| 641 | : CodeGenAction(Backend_EmitObj, _VMContext) {} |
| 642 | |