1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===// 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/BackendUtil.h" 10 #include "clang/Basic/CodeGenOptions.h" 11 #include "clang/Basic/Diagnostic.h" 12 #include "clang/Basic/LangOptions.h" 13 #include "clang/Basic/TargetOptions.h" 14 #include "clang/Frontend/FrontendDiagnostic.h" 15 #include "clang/Frontend/Utils.h" 16 #include "clang/Lex/HeaderSearchOptions.h" 17 #include "llvm/ADT/SmallSet.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/StringSwitch.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/Analysis/StackSafetyAnalysis.h" 22 #include "llvm/Analysis/TargetLibraryInfo.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/Bitcode/BitcodeReader.h" 25 #include "llvm/Bitcode/BitcodeWriter.h" 26 #include "llvm/Bitcode/BitcodeWriterPass.h" 27 #include "llvm/CodeGen/RegAllocRegistry.h" 28 #include "llvm/CodeGen/SchedulerRegistry.h" 29 #include "llvm/CodeGen/TargetSubtargetInfo.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/IRPrintingPasses.h" 32 #include "llvm/IR/LegacyPassManager.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/ModuleSummaryIndex.h" 35 #include "llvm/IR/PassManager.h" 36 #include "llvm/IR/Verifier.h" 37 #include "llvm/LTO/LTOBackend.h" 38 #include "llvm/MC/MCAsmInfo.h" 39 #include "llvm/MC/SubtargetFeature.h" 40 #include "llvm/Passes/PassBuilder.h" 41 #include "llvm/Passes/PassPlugin.h" 42 #include "llvm/Passes/StandardInstrumentations.h" 43 #include "llvm/Support/BuryPointer.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/MemoryBuffer.h" 46 #include "llvm/Support/PrettyStackTrace.h" 47 #include "llvm/Support/TargetRegistry.h" 48 #include "llvm/Support/TimeProfiler.h" 49 #include "llvm/Support/Timer.h" 50 #include "llvm/Support/ToolOutputFile.h" 51 #include "llvm/Support/raw_ostream.h" 52 #include "llvm/Target/TargetMachine.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include "llvm/Transforms/Coroutines.h" 55 #include "llvm/Transforms/Coroutines/CoroCleanup.h" 56 #include "llvm/Transforms/Coroutines/CoroEarly.h" 57 #include "llvm/Transforms/Coroutines/CoroElide.h" 58 #include "llvm/Transforms/Coroutines/CoroSplit.h" 59 #include "llvm/Transforms/IPO.h" 60 #include "llvm/Transforms/IPO/AlwaysInliner.h" 61 #include "llvm/Transforms/IPO/LowerTypeTests.h" 62 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 63 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h" 64 #include "llvm/Transforms/InstCombine/InstCombine.h" 65 #include "llvm/Transforms/Instrumentation.h" 66 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h" 67 #include "llvm/Transforms/Instrumentation/BoundsChecking.h" 68 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" 69 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h" 70 #include "llvm/Transforms/Instrumentation/InstrProfiling.h" 71 #include "llvm/Transforms/Instrumentation/MemProfiler.h" 72 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" 73 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h" 74 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" 75 #include "llvm/Transforms/ObjCARC.h" 76 #include "llvm/Transforms/Scalar.h" 77 #include "llvm/Transforms/Scalar/GVN.h" 78 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h" 79 #include "llvm/Transforms/Utils.h" 80 #include "llvm/Transforms/Utils/CanonicalizeAliases.h" 81 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h" 82 #include "llvm/Transforms/Utils/NameAnonGlobals.h" 83 #include "llvm/Transforms/Utils/SymbolRewriter.h" 84 #include "llvm/Transforms/Utils/UniqueInternalLinkageNames.h" 85 #include <memory> 86 using namespace clang; 87 using namespace llvm; 88 89 #define HANDLE_EXTENSION(Ext) \ 90 llvm::PassPluginLibraryInfo get##Ext##PluginInfo(); 91 #include "llvm/Support/Extension.def" 92 93 namespace { 94 95 // Default filename used for profile generation. 96 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw"; 97 98 class EmitAssemblyHelper { 99 DiagnosticsEngine &Diags; 100 const HeaderSearchOptions &HSOpts; 101 const CodeGenOptions &CodeGenOpts; 102 const clang::TargetOptions &TargetOpts; 103 const LangOptions &LangOpts; 104 Module *TheModule; 105 106 Timer CodeGenerationTime; 107 108 std::unique_ptr<raw_pwrite_stream> OS; 109 110 TargetIRAnalysis getTargetIRAnalysis() const { 111 if (TM) 112 return TM->getTargetIRAnalysis(); 113 114 return TargetIRAnalysis(); 115 } 116 117 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM); 118 119 /// Generates the TargetMachine. 120 /// Leaves TM unchanged if it is unable to create the target machine. 121 /// Some of our clang tests specify triples which are not built 122 /// into clang. This is okay because these tests check the generated 123 /// IR, and they require DataLayout which depends on the triple. 124 /// In this case, we allow this method to fail and not report an error. 125 /// When MustCreateTM is used, we print an error if we are unable to load 126 /// the requested target. 127 void CreateTargetMachine(bool MustCreateTM); 128 129 /// Add passes necessary to emit assembly or LLVM IR. 130 /// 131 /// \return True on success. 132 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action, 133 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS); 134 135 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) { 136 std::error_code EC; 137 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC, 138 llvm::sys::fs::OF_None); 139 if (EC) { 140 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message(); 141 F.reset(); 142 } 143 return F; 144 } 145 146 public: 147 EmitAssemblyHelper(DiagnosticsEngine &_Diags, 148 const HeaderSearchOptions &HeaderSearchOpts, 149 const CodeGenOptions &CGOpts, 150 const clang::TargetOptions &TOpts, 151 const LangOptions &LOpts, Module *M) 152 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts), 153 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), 154 CodeGenerationTime("codegen", "Code Generation Time") {} 155 156 ~EmitAssemblyHelper() { 157 if (CodeGenOpts.DisableFree) 158 BuryPointer(std::move(TM)); 159 } 160 161 std::unique_ptr<TargetMachine> TM; 162 163 void EmitAssembly(BackendAction Action, 164 std::unique_ptr<raw_pwrite_stream> OS); 165 166 void EmitAssemblyWithNewPassManager(BackendAction Action, 167 std::unique_ptr<raw_pwrite_stream> OS); 168 }; 169 170 // We need this wrapper to access LangOpts and CGOpts from extension functions 171 // that we add to the PassManagerBuilder. 172 class PassManagerBuilderWrapper : public PassManagerBuilder { 173 public: 174 PassManagerBuilderWrapper(const Triple &TargetTriple, 175 const CodeGenOptions &CGOpts, 176 const LangOptions &LangOpts) 177 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts), 178 LangOpts(LangOpts) {} 179 const Triple &getTargetTriple() const { return TargetTriple; } 180 const CodeGenOptions &getCGOpts() const { return CGOpts; } 181 const LangOptions &getLangOpts() const { return LangOpts; } 182 183 private: 184 const Triple &TargetTriple; 185 const CodeGenOptions &CGOpts; 186 const LangOptions &LangOpts; 187 }; 188 } 189 190 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 191 if (Builder.OptLevel > 0) 192 PM.add(createObjCARCAPElimPass()); 193 } 194 195 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 196 if (Builder.OptLevel > 0) 197 PM.add(createObjCARCExpandPass()); 198 } 199 200 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 201 if (Builder.OptLevel > 0) 202 PM.add(createObjCARCOptPass()); 203 } 204 205 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, 206 legacy::PassManagerBase &PM) { 207 PM.add(createAddDiscriminatorsPass()); 208 } 209 210 static void addBoundsCheckingPass(const PassManagerBuilder &Builder, 211 legacy::PassManagerBase &PM) { 212 PM.add(createBoundsCheckingLegacyPass()); 213 } 214 215 static SanitizerCoverageOptions 216 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) { 217 SanitizerCoverageOptions Opts; 218 Opts.CoverageType = 219 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType); 220 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; 221 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; 222 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; 223 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv; 224 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep; 225 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; 226 Opts.TracePC = CGOpts.SanitizeCoverageTracePC; 227 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard; 228 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune; 229 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters; 230 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag; 231 Opts.PCTable = CGOpts.SanitizeCoveragePCTable; 232 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth; 233 return Opts; 234 } 235 236 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, 237 legacy::PassManagerBase &PM) { 238 const PassManagerBuilderWrapper &BuilderWrapper = 239 static_cast<const PassManagerBuilderWrapper &>(Builder); 240 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 241 auto Opts = getSancovOptsFromCGOpts(CGOpts); 242 PM.add(createModuleSanitizerCoverageLegacyPassPass( 243 Opts, CGOpts.SanitizeCoverageAllowlistFiles, 244 CGOpts.SanitizeCoverageBlocklistFiles)); 245 } 246 247 // Check if ASan should use GC-friendly instrumentation for globals. 248 // First of all, there is no point if -fdata-sections is off (expect for MachO, 249 // where this is not a factor). Also, on ELF this feature requires an assembler 250 // extension that only works with -integrated-as at the moment. 251 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) { 252 if (!CGOpts.SanitizeAddressGlobalsDeadStripping) 253 return false; 254 switch (T.getObjectFormat()) { 255 case Triple::MachO: 256 case Triple::COFF: 257 return true; 258 case Triple::ELF: 259 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS; 260 case Triple::GOFF: 261 llvm::report_fatal_error("ASan not implemented for GOFF"); 262 case Triple::XCOFF: 263 llvm::report_fatal_error("ASan not implemented for XCOFF."); 264 case Triple::Wasm: 265 case Triple::UnknownObjectFormat: 266 break; 267 } 268 return false; 269 } 270 271 static void addMemProfilerPasses(const PassManagerBuilder &Builder, 272 legacy::PassManagerBase &PM) { 273 PM.add(createMemProfilerFunctionPass()); 274 PM.add(createModuleMemProfilerLegacyPassPass()); 275 } 276 277 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 278 legacy::PassManagerBase &PM) { 279 const PassManagerBuilderWrapper &BuilderWrapper = 280 static_cast<const PassManagerBuilderWrapper&>(Builder); 281 const Triple &T = BuilderWrapper.getTargetTriple(); 282 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 283 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address); 284 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope; 285 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator; 286 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts); 287 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover, 288 UseAfterScope)); 289 PM.add(createModuleAddressSanitizerLegacyPassPass( 290 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator)); 291 } 292 293 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, 294 legacy::PassManagerBase &PM) { 295 PM.add(createAddressSanitizerFunctionPass( 296 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false)); 297 PM.add(createModuleAddressSanitizerLegacyPassPass( 298 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true, 299 /*UseOdrIndicator*/ false)); 300 } 301 302 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder, 303 legacy::PassManagerBase &PM) { 304 const PassManagerBuilderWrapper &BuilderWrapper = 305 static_cast<const PassManagerBuilderWrapper &>(Builder); 306 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 307 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress); 308 PM.add( 309 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover)); 310 } 311 312 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder, 313 legacy::PassManagerBase &PM) { 314 PM.add(createHWAddressSanitizerLegacyPassPass( 315 /*CompileKernel*/ true, /*Recover*/ true)); 316 } 317 318 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder, 319 legacy::PassManagerBase &PM, 320 bool CompileKernel) { 321 const PassManagerBuilderWrapper &BuilderWrapper = 322 static_cast<const PassManagerBuilderWrapper&>(Builder); 323 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 324 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins; 325 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory); 326 PM.add(createMemorySanitizerLegacyPassPass( 327 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel})); 328 329 // MemorySanitizer inserts complex instrumentation that mostly follows 330 // the logic of the original code, but operates on "shadow" values. 331 // It can benefit from re-running some general purpose optimization passes. 332 if (Builder.OptLevel > 0) { 333 PM.add(createEarlyCSEPass()); 334 PM.add(createReassociatePass()); 335 PM.add(createLICMPass()); 336 PM.add(createGVNPass()); 337 PM.add(createInstructionCombiningPass()); 338 PM.add(createDeadStoreEliminationPass()); 339 } 340 } 341 342 static void addMemorySanitizerPass(const PassManagerBuilder &Builder, 343 legacy::PassManagerBase &PM) { 344 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false); 345 } 346 347 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder, 348 legacy::PassManagerBase &PM) { 349 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true); 350 } 351 352 static void addThreadSanitizerPass(const PassManagerBuilder &Builder, 353 legacy::PassManagerBase &PM) { 354 PM.add(createThreadSanitizerLegacyPassPass()); 355 } 356 357 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, 358 legacy::PassManagerBase &PM) { 359 const PassManagerBuilderWrapper &BuilderWrapper = 360 static_cast<const PassManagerBuilderWrapper&>(Builder); 361 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 362 PM.add( 363 createDataFlowSanitizerLegacyPassPass(LangOpts.SanitizerBlacklistFiles)); 364 } 365 366 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple, 367 const CodeGenOptions &CodeGenOpts) { 368 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple); 369 370 switch (CodeGenOpts.getVecLib()) { 371 case CodeGenOptions::Accelerate: 372 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); 373 break; 374 case CodeGenOptions::LIBMVEC: 375 switch(TargetTriple.getArch()) { 376 default: 377 break; 378 case llvm::Triple::x86_64: 379 TLII->addVectorizableFunctionsFromVecLib 380 (TargetLibraryInfoImpl::LIBMVEC_X86); 381 break; 382 } 383 break; 384 case CodeGenOptions::MASSV: 385 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV); 386 break; 387 case CodeGenOptions::SVML: 388 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML); 389 break; 390 default: 391 break; 392 } 393 return TLII; 394 } 395 396 static void addSymbolRewriterPass(const CodeGenOptions &Opts, 397 legacy::PassManager *MPM) { 398 llvm::SymbolRewriter::RewriteDescriptorList DL; 399 400 llvm::SymbolRewriter::RewriteMapParser MapParser; 401 for (const auto &MapFile : Opts.RewriteMapFiles) 402 MapParser.parse(MapFile, &DL); 403 404 MPM->add(createRewriteSymbolsPass(DL)); 405 } 406 407 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) { 408 switch (CodeGenOpts.OptimizationLevel) { 409 default: 410 llvm_unreachable("Invalid optimization level!"); 411 case 0: 412 return CodeGenOpt::None; 413 case 1: 414 return CodeGenOpt::Less; 415 case 2: 416 return CodeGenOpt::Default; // O2/Os/Oz 417 case 3: 418 return CodeGenOpt::Aggressive; 419 } 420 } 421 422 static Optional<llvm::CodeModel::Model> 423 getCodeModel(const CodeGenOptions &CodeGenOpts) { 424 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 425 .Case("tiny", llvm::CodeModel::Tiny) 426 .Case("small", llvm::CodeModel::Small) 427 .Case("kernel", llvm::CodeModel::Kernel) 428 .Case("medium", llvm::CodeModel::Medium) 429 .Case("large", llvm::CodeModel::Large) 430 .Case("default", ~1u) 431 .Default(~0u); 432 assert(CodeModel != ~0u && "invalid code model!"); 433 if (CodeModel == ~1u) 434 return None; 435 return static_cast<llvm::CodeModel::Model>(CodeModel); 436 } 437 438 static CodeGenFileType getCodeGenFileType(BackendAction Action) { 439 if (Action == Backend_EmitObj) 440 return CGFT_ObjectFile; 441 else if (Action == Backend_EmitMCNull) 442 return CGFT_Null; 443 else { 444 assert(Action == Backend_EmitAssembly && "Invalid action!"); 445 return CGFT_AssemblyFile; 446 } 447 } 448 449 static void initTargetOptions(DiagnosticsEngine &Diags, 450 llvm::TargetOptions &Options, 451 const CodeGenOptions &CodeGenOpts, 452 const clang::TargetOptions &TargetOpts, 453 const LangOptions &LangOpts, 454 const HeaderSearchOptions &HSOpts) { 455 Options.ThreadModel = 456 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel) 457 .Case("posix", llvm::ThreadModel::POSIX) 458 .Case("single", llvm::ThreadModel::Single); 459 460 // Set float ABI type. 461 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 462 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 463 "Invalid Floating Point ABI!"); 464 Options.FloatABIType = 465 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 466 .Case("soft", llvm::FloatABI::Soft) 467 .Case("softfp", llvm::FloatABI::Soft) 468 .Case("hard", llvm::FloatABI::Hard) 469 .Default(llvm::FloatABI::Default); 470 471 // Set FP fusion mode. 472 switch (LangOpts.getDefaultFPContractMode()) { 473 case LangOptions::FPM_Off: 474 // Preserve any contraction performed by the front-end. (Strict performs 475 // splitting of the muladd intrinsic in the backend.) 476 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 477 break; 478 case LangOptions::FPM_On: 479 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 480 break; 481 case LangOptions::FPM_Fast: 482 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 483 break; 484 } 485 486 Options.UseInitArray = CodeGenOpts.UseInitArray; 487 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 488 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections(); 489 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; 490 491 // Set EABI version. 492 Options.EABIVersion = TargetOpts.EABIVersion; 493 494 if (LangOpts.SjLjExceptions) 495 Options.ExceptionModel = llvm::ExceptionHandling::SjLj; 496 if (LangOpts.SEHExceptions) 497 Options.ExceptionModel = llvm::ExceptionHandling::WinEH; 498 if (LangOpts.DWARFExceptions) 499 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI; 500 if (LangOpts.WasmExceptions) 501 Options.ExceptionModel = llvm::ExceptionHandling::Wasm; 502 503 Options.NoInfsFPMath = LangOpts.NoHonorInfs; 504 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs; 505 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 506 Options.UnsafeFPMath = LangOpts.UnsafeFPMath; 507 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 508 509 Options.BBSections = 510 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections) 511 .Case("all", llvm::BasicBlockSection::All) 512 .Case("labels", llvm::BasicBlockSection::Labels) 513 .StartsWith("list=", llvm::BasicBlockSection::List) 514 .Case("none", llvm::BasicBlockSection::None) 515 .Default(llvm::BasicBlockSection::None); 516 517 if (Options.BBSections == llvm::BasicBlockSection::List) { 518 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 519 MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5)); 520 if (!MBOrErr) 521 Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file) 522 << MBOrErr.getError().message(); 523 else 524 Options.BBSectionsFuncListBuf = std::move(*MBOrErr); 525 } 526 527 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions; 528 Options.FunctionSections = CodeGenOpts.FunctionSections; 529 Options.DataSections = CodeGenOpts.DataSections; 530 Options.IgnoreXCOFFVisibility = CodeGenOpts.IgnoreXCOFFVisibility; 531 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 532 Options.UniqueBasicBlockSectionNames = 533 CodeGenOpts.UniqueBasicBlockSectionNames; 534 Options.StackProtectorGuard = 535 llvm::StringSwitch<llvm::StackProtectorGuards>(CodeGenOpts 536 .StackProtectorGuard) 537 .Case("tls", llvm::StackProtectorGuards::TLS) 538 .Case("global", llvm::StackProtectorGuards::Global) 539 .Default(llvm::StackProtectorGuards::None); 540 Options.StackProtectorGuardOffset = CodeGenOpts.StackProtectorGuardOffset; 541 Options.StackProtectorGuardReg = CodeGenOpts.StackProtectorGuardReg; 542 Options.TLSSize = CodeGenOpts.TLSSize; 543 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 544 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS; 545 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 546 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection; 547 Options.EmitAddrsig = CodeGenOpts.Addrsig; 548 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection; 549 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo; 550 Options.ValueTrackingVariableLocations = 551 CodeGenOpts.ValueTrackingVariableLocations; 552 Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex; 553 554 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile; 555 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 556 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 557 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; 558 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 559 Options.MCOptions.MCIncrementalLinkerCompatible = 560 CodeGenOpts.IncrementalLinkerCompatible; 561 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 562 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn; 563 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 564 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments; 565 Options.MCOptions.ABIName = TargetOpts.ABI; 566 for (const auto &Entry : HSOpts.UserEntries) 567 if (!Entry.IsFramework && 568 (Entry.Group == frontend::IncludeDirGroup::Quoted || 569 Entry.Group == frontend::IncludeDirGroup::Angled || 570 Entry.Group == frontend::IncludeDirGroup::System)) 571 Options.MCOptions.IASSearchPaths.push_back( 572 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path); 573 Options.MCOptions.Argv0 = CodeGenOpts.Argv0; 574 Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs; 575 } 576 577 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts, 578 const LangOptions &LangOpts) { 579 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes) 580 return None; 581 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 582 // LLVM's -default-gcov-version flag is set to something invalid. 583 GCOVOptions Options; 584 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 585 Options.EmitData = CodeGenOpts.EmitGcovArcs; 586 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version)); 587 Options.NoRedZone = CodeGenOpts.DisableRedZone; 588 Options.Filter = CodeGenOpts.ProfileFilterFiles; 589 Options.Exclude = CodeGenOpts.ProfileExcludeFiles; 590 Options.Atomic = CodeGenOpts.AtomicProfileUpdate; 591 return Options; 592 } 593 594 static Optional<InstrProfOptions> 595 getInstrProfOptions(const CodeGenOptions &CodeGenOpts, 596 const LangOptions &LangOpts) { 597 if (!CodeGenOpts.hasProfileClangInstr()) 598 return None; 599 InstrProfOptions Options; 600 Options.NoRedZone = CodeGenOpts.DisableRedZone; 601 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 602 Options.Atomic = CodeGenOpts.AtomicProfileUpdate; 603 return Options; 604 } 605 606 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM, 607 legacy::FunctionPassManager &FPM) { 608 // Handle disabling of all LLVM passes, where we want to preserve the 609 // internal module before any optimization. 610 if (CodeGenOpts.DisableLLVMPasses) 611 return; 612 613 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM 614 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling) 615 // are inserted before PMBuilder ones - they'd get the default-constructed 616 // TLI with an unknown target otherwise. 617 Triple TargetTriple(TheModule->getTargetTriple()); 618 std::unique_ptr<TargetLibraryInfoImpl> TLII( 619 createTLII(TargetTriple, CodeGenOpts)); 620 621 // If we reached here with a non-empty index file name, then the index file 622 // was empty and we are not performing ThinLTO backend compilation (used in 623 // testing in a distributed build environment). Drop any the type test 624 // assume sequences inserted for whole program vtables so that codegen doesn't 625 // complain. 626 if (!CodeGenOpts.ThinLTOIndexFile.empty()) 627 MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr, 628 /*ImportSummary=*/nullptr, 629 /*DropTypeTests=*/true)); 630 631 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts); 632 633 // At O0 and O1 we only run the always inliner which is more efficient. At 634 // higher optimization levels we run the normal inliner. 635 if (CodeGenOpts.OptimizationLevel <= 1) { 636 bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 && 637 !CodeGenOpts.DisableLifetimeMarkers) || 638 LangOpts.Coroutines); 639 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics); 640 } else { 641 // We do not want to inline hot callsites for SamplePGO module-summary build 642 // because profile annotation will happen again in ThinLTO backend, and we 643 // want the IR of the hot path to match the profile. 644 PMBuilder.Inliner = createFunctionInliningPass( 645 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize, 646 (!CodeGenOpts.SampleProfileFile.empty() && 647 CodeGenOpts.PrepareForThinLTO)); 648 } 649 650 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel; 651 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 652 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 653 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 654 // Only enable CGProfilePass when using integrated assembler, since 655 // non-integrated assemblers don't recognize .cgprofile section. 656 PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS; 657 658 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 659 // Loop interleaving in the loop vectorizer has historically been set to be 660 // enabled when loop unrolling is enabled. 661 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops; 662 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; 663 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO; 664 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO; 665 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 666 667 MPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 668 669 if (TM) 670 TM->adjustPassManager(PMBuilder); 671 672 if (CodeGenOpts.DebugInfoForProfiling || 673 !CodeGenOpts.SampleProfileFile.empty()) 674 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 675 addAddDiscriminatorsPass); 676 677 // In ObjC ARC mode, add the main ARC optimization passes. 678 if (LangOpts.ObjCAutoRefCount) { 679 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 680 addObjCARCExpandPass); 681 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 682 addObjCARCAPElimPass); 683 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 684 addObjCARCOptPass); 685 } 686 687 if (LangOpts.Coroutines) 688 addCoroutinePassesToExtensionPoints(PMBuilder); 689 690 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 691 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 692 addMemProfilerPasses); 693 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 694 addMemProfilerPasses); 695 } 696 697 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { 698 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 699 addBoundsCheckingPass); 700 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 701 addBoundsCheckingPass); 702 } 703 704 if (CodeGenOpts.SanitizeCoverageType || 705 CodeGenOpts.SanitizeCoverageIndirectCalls || 706 CodeGenOpts.SanitizeCoverageTraceCmp) { 707 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 708 addSanitizerCoveragePass); 709 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 710 addSanitizerCoveragePass); 711 } 712 713 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 714 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 715 addAddressSanitizerPasses); 716 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 717 addAddressSanitizerPasses); 718 } 719 720 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 721 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 722 addKernelAddressSanitizerPasses); 723 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 724 addKernelAddressSanitizerPasses); 725 } 726 727 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { 728 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 729 addHWAddressSanitizerPasses); 730 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 731 addHWAddressSanitizerPasses); 732 } 733 734 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { 735 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 736 addKernelHWAddressSanitizerPasses); 737 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 738 addKernelHWAddressSanitizerPasses); 739 } 740 741 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 742 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 743 addMemorySanitizerPass); 744 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 745 addMemorySanitizerPass); 746 } 747 748 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) { 749 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 750 addKernelMemorySanitizerPass); 751 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 752 addKernelMemorySanitizerPass); 753 } 754 755 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 756 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 757 addThreadSanitizerPass); 758 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 759 addThreadSanitizerPass); 760 } 761 762 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 763 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 764 addDataFlowSanitizerPass); 765 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 766 addDataFlowSanitizerPass); 767 } 768 769 // Set up the per-function pass manager. 770 FPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 771 if (CodeGenOpts.VerifyModule) 772 FPM.add(createVerifierPass()); 773 774 // Set up the per-module pass manager. 775 if (!CodeGenOpts.RewriteMapFiles.empty()) 776 addSymbolRewriterPass(CodeGenOpts, &MPM); 777 778 // Add UniqueInternalLinkageNames Pass which renames internal linkage symbols 779 // with unique names. 780 if (CodeGenOpts.UniqueInternalLinkageNames) { 781 MPM.add(createUniqueInternalLinkageNamesPass()); 782 } 783 784 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) { 785 MPM.add(createGCOVProfilerPass(*Options)); 786 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo) 787 MPM.add(createStripSymbolsPass(true)); 788 } 789 790 if (Optional<InstrProfOptions> Options = 791 getInstrProfOptions(CodeGenOpts, LangOpts)) 792 MPM.add(createInstrProfilingLegacyPass(*Options, false)); 793 794 bool hasIRInstr = false; 795 if (CodeGenOpts.hasProfileIRInstr()) { 796 PMBuilder.EnablePGOInstrGen = true; 797 hasIRInstr = true; 798 } 799 if (CodeGenOpts.hasProfileCSIRInstr()) { 800 assert(!CodeGenOpts.hasProfileCSIRUse() && 801 "Cannot have both CSProfileUse pass and CSProfileGen pass at the " 802 "same time"); 803 assert(!hasIRInstr && 804 "Cannot have both ProfileGen pass and CSProfileGen pass at the " 805 "same time"); 806 PMBuilder.EnablePGOCSInstrGen = true; 807 hasIRInstr = true; 808 } 809 if (hasIRInstr) { 810 if (!CodeGenOpts.InstrProfileOutput.empty()) 811 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput; 812 else 813 PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName); 814 } 815 if (CodeGenOpts.hasProfileIRUse()) { 816 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath; 817 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse(); 818 } 819 820 if (!CodeGenOpts.SampleProfileFile.empty()) 821 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile; 822 823 PMBuilder.populateFunctionPassManager(FPM); 824 PMBuilder.populateModulePassManager(MPM); 825 } 826 827 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) { 828 SmallVector<const char *, 16> BackendArgs; 829 BackendArgs.push_back("clang"); // Fake program name. 830 if (!CodeGenOpts.DebugPass.empty()) { 831 BackendArgs.push_back("-debug-pass"); 832 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 833 } 834 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 835 BackendArgs.push_back("-limit-float-precision"); 836 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 837 } 838 BackendArgs.push_back(nullptr); 839 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 840 BackendArgs.data()); 841 } 842 843 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 844 // Create the TargetMachine for generating code. 845 std::string Error; 846 std::string Triple = TheModule->getTargetTriple(); 847 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 848 if (!TheTarget) { 849 if (MustCreateTM) 850 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 851 return; 852 } 853 854 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts); 855 std::string FeaturesStr = 856 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 857 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel; 858 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts); 859 860 llvm::TargetOptions Options; 861 initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts); 862 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr, 863 Options, RM, CM, OptLevel)); 864 } 865 866 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses, 867 BackendAction Action, 868 raw_pwrite_stream &OS, 869 raw_pwrite_stream *DwoOS) { 870 // Add LibraryInfo. 871 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 872 std::unique_ptr<TargetLibraryInfoImpl> TLII( 873 createTLII(TargetTriple, CodeGenOpts)); 874 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII)); 875 876 // Normal mode, emit a .s or .o file by running the code generator. Note, 877 // this also adds codegenerator level optimization passes. 878 CodeGenFileType CGFT = getCodeGenFileType(Action); 879 880 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 881 // "codegen" passes so that it isn't run multiple times when there is 882 // inlining happening. 883 if (CodeGenOpts.OptimizationLevel > 0) 884 CodeGenPasses.add(createObjCARCContractPass()); 885 886 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT, 887 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 888 Diags.Report(diag::err_fe_unable_to_interface_with_target); 889 return false; 890 } 891 892 return true; 893 } 894 895 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 896 std::unique_ptr<raw_pwrite_stream> OS) { 897 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr); 898 899 setCommandLineOpts(CodeGenOpts); 900 901 bool UsesCodeGen = (Action != Backend_EmitNothing && 902 Action != Backend_EmitBC && 903 Action != Backend_EmitLL); 904 CreateTargetMachine(UsesCodeGen); 905 906 if (UsesCodeGen && !TM) 907 return; 908 if (TM) 909 TheModule->setDataLayout(TM->createDataLayout()); 910 911 legacy::PassManager PerModulePasses; 912 PerModulePasses.add( 913 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 914 915 legacy::FunctionPassManager PerFunctionPasses(TheModule); 916 PerFunctionPasses.add( 917 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 918 919 CreatePasses(PerModulePasses, PerFunctionPasses); 920 921 legacy::PassManager CodeGenPasses; 922 CodeGenPasses.add( 923 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 924 925 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 926 927 switch (Action) { 928 case Backend_EmitNothing: 929 break; 930 931 case Backend_EmitBC: 932 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 933 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 934 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 935 if (!ThinLinkOS) 936 return; 937 } 938 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 939 CodeGenOpts.EnableSplitLTOUnit); 940 PerModulePasses.add(createWriteThinLTOBitcodePass( 941 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr)); 942 } else { 943 // Emit a module summary by default for Regular LTO except for ld64 944 // targets 945 bool EmitLTOSummary = 946 (CodeGenOpts.PrepareForLTO && 947 !CodeGenOpts.DisableLLVMPasses && 948 llvm::Triple(TheModule->getTargetTriple()).getVendor() != 949 llvm::Triple::Apple); 950 if (EmitLTOSummary) { 951 if (!TheModule->getModuleFlag("ThinLTO")) 952 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 953 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 954 uint32_t(1)); 955 } 956 957 PerModulePasses.add(createBitcodeWriterPass( 958 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); 959 } 960 break; 961 962 case Backend_EmitLL: 963 PerModulePasses.add( 964 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 965 break; 966 967 default: 968 if (!CodeGenOpts.SplitDwarfOutput.empty()) { 969 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); 970 if (!DwoOS) 971 return; 972 } 973 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 974 DwoOS ? &DwoOS->os() : nullptr)) 975 return; 976 } 977 978 // Before executing passes, print the final values of the LLVM options. 979 cl::PrintOptionValues(); 980 981 // Run passes. For now we do all passes at once, but eventually we 982 // would like to have the option of streaming code generation. 983 984 { 985 PrettyStackTraceString CrashInfo("Per-function optimization"); 986 llvm::TimeTraceScope TimeScope("PerFunctionPasses"); 987 988 PerFunctionPasses.doInitialization(); 989 for (Function &F : *TheModule) 990 if (!F.isDeclaration()) 991 PerFunctionPasses.run(F); 992 PerFunctionPasses.doFinalization(); 993 } 994 995 { 996 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 997 llvm::TimeTraceScope TimeScope("PerModulePasses"); 998 PerModulePasses.run(*TheModule); 999 } 1000 1001 { 1002 PrettyStackTraceString CrashInfo("Code generation"); 1003 llvm::TimeTraceScope TimeScope("CodeGenPasses"); 1004 CodeGenPasses.run(*TheModule); 1005 } 1006 1007 if (ThinLinkOS) 1008 ThinLinkOS->keep(); 1009 if (DwoOS) 1010 DwoOS->keep(); 1011 } 1012 1013 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) { 1014 switch (Opts.OptimizationLevel) { 1015 default: 1016 llvm_unreachable("Invalid optimization level!"); 1017 1018 case 0: 1019 return PassBuilder::OptimizationLevel::O0; 1020 1021 case 1: 1022 return PassBuilder::OptimizationLevel::O1; 1023 1024 case 2: 1025 switch (Opts.OptimizeSize) { 1026 default: 1027 llvm_unreachable("Invalid optimization level for size!"); 1028 1029 case 0: 1030 return PassBuilder::OptimizationLevel::O2; 1031 1032 case 1: 1033 return PassBuilder::OptimizationLevel::Os; 1034 1035 case 2: 1036 return PassBuilder::OptimizationLevel::Oz; 1037 } 1038 1039 case 3: 1040 return PassBuilder::OptimizationLevel::O3; 1041 } 1042 } 1043 1044 static void addCoroutinePassesAtO0(ModulePassManager &MPM, 1045 const LangOptions &LangOpts, 1046 const CodeGenOptions &CodeGenOpts) { 1047 if (!LangOpts.Coroutines) 1048 return; 1049 1050 MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass())); 1051 1052 CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager); 1053 CGPM.addPass(CoroSplitPass()); 1054 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass())); 1055 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1056 1057 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); 1058 } 1059 1060 static void addSanitizersAtO0(ModulePassManager &MPM, 1061 const Triple &TargetTriple, 1062 const LangOptions &LangOpts, 1063 const CodeGenOptions &CodeGenOpts) { 1064 if (CodeGenOpts.SanitizeCoverageType || 1065 CodeGenOpts.SanitizeCoverageIndirectCalls || 1066 CodeGenOpts.SanitizeCoverageTraceCmp) { 1067 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts); 1068 MPM.addPass(ModuleSanitizerCoveragePass( 1069 SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles, 1070 CodeGenOpts.SanitizeCoverageBlocklistFiles)); 1071 } 1072 1073 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 1074 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 1075 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 1076 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass( 1077 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope))); 1078 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts); 1079 MPM.addPass( 1080 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope, 1081 CodeGenOpts.SanitizeAddressUseOdrIndicator)); 1082 }; 1083 1084 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 1085 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false); 1086 } 1087 1088 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 1089 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true); 1090 } 1091 1092 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { 1093 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress); 1094 MPM.addPass(HWAddressSanitizerPass( 1095 /*CompileKernel=*/false, Recover)); 1096 } 1097 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { 1098 MPM.addPass(HWAddressSanitizerPass( 1099 /*CompileKernel=*/true, /*Recover=*/true)); 1100 } 1101 1102 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 1103 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory); 1104 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins; 1105 MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false})); 1106 MPM.addPass(createModuleToFunctionPassAdaptor( 1107 MemorySanitizerPass({TrackOrigins, Recover, false}))); 1108 } 1109 1110 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) { 1111 MPM.addPass(createModuleToFunctionPassAdaptor( 1112 MemorySanitizerPass({0, false, /*Kernel=*/true}))); 1113 } 1114 1115 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 1116 MPM.addPass(ThreadSanitizerPass()); 1117 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); 1118 } 1119 } 1120 1121 /// A clean version of `EmitAssembly` that uses the new pass manager. 1122 /// 1123 /// Not all features are currently supported in this system, but where 1124 /// necessary it falls back to the legacy pass manager to at least provide 1125 /// basic functionality. 1126 /// 1127 /// This API is planned to have its functionality finished and then to replace 1128 /// `EmitAssembly` at some point in the future when the default switches. 1129 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager( 1130 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) { 1131 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr); 1132 setCommandLineOpts(CodeGenOpts); 1133 1134 bool RequiresCodeGen = (Action != Backend_EmitNothing && 1135 Action != Backend_EmitBC && 1136 Action != Backend_EmitLL); 1137 CreateTargetMachine(RequiresCodeGen); 1138 1139 if (RequiresCodeGen && !TM) 1140 return; 1141 if (TM) 1142 TheModule->setDataLayout(TM->createDataLayout()); 1143 1144 Optional<PGOOptions> PGOOpt; 1145 1146 if (CodeGenOpts.hasProfileIRInstr()) 1147 // -fprofile-generate. 1148 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty() 1149 ? std::string(DefaultProfileGenName) 1150 : CodeGenOpts.InstrProfileOutput, 1151 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction, 1152 CodeGenOpts.DebugInfoForProfiling); 1153 else if (CodeGenOpts.hasProfileIRUse()) { 1154 // -fprofile-use. 1155 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse 1156 : PGOOptions::NoCSAction; 1157 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "", 1158 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse, 1159 CSAction, CodeGenOpts.DebugInfoForProfiling); 1160 } else if (!CodeGenOpts.SampleProfileFile.empty()) 1161 // -fprofile-sample-use 1162 PGOOpt = 1163 PGOOptions(CodeGenOpts.SampleProfileFile, "", 1164 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse, 1165 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling); 1166 else if (CodeGenOpts.DebugInfoForProfiling) 1167 // -fdebug-info-for-profiling 1168 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction, 1169 PGOOptions::NoCSAction, true); 1170 1171 // Check to see if we want to generate a CS profile. 1172 if (CodeGenOpts.hasProfileCSIRInstr()) { 1173 assert(!CodeGenOpts.hasProfileCSIRUse() && 1174 "Cannot have both CSProfileUse pass and CSProfileGen pass at " 1175 "the same time"); 1176 if (PGOOpt.hasValue()) { 1177 assert(PGOOpt->Action != PGOOptions::IRInstr && 1178 PGOOpt->Action != PGOOptions::SampleUse && 1179 "Cannot run CSProfileGen pass with ProfileGen or SampleUse " 1180 " pass"); 1181 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() 1182 ? std::string(DefaultProfileGenName) 1183 : CodeGenOpts.InstrProfileOutput; 1184 PGOOpt->CSAction = PGOOptions::CSIRInstr; 1185 } else 1186 PGOOpt = PGOOptions("", 1187 CodeGenOpts.InstrProfileOutput.empty() 1188 ? std::string(DefaultProfileGenName) 1189 : CodeGenOpts.InstrProfileOutput, 1190 "", PGOOptions::NoAction, PGOOptions::CSIRInstr, 1191 CodeGenOpts.DebugInfoForProfiling); 1192 } 1193 1194 PipelineTuningOptions PTO; 1195 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops; 1196 // For historical reasons, loop interleaving is set to mirror setting for loop 1197 // unrolling. 1198 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops; 1199 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop; 1200 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP; 1201 // Only enable CGProfilePass when using integrated assembler, since 1202 // non-integrated assemblers don't recognize .cgprofile section. 1203 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS; 1204 PTO.Coroutines = LangOpts.Coroutines; 1205 1206 PassInstrumentationCallbacks PIC; 1207 StandardInstrumentations SI(CodeGenOpts.DebugPassManager); 1208 SI.registerCallbacks(PIC); 1209 PassBuilder PB(CodeGenOpts.DebugPassManager, TM.get(), PTO, PGOOpt, &PIC); 1210 1211 // Attempt to load pass plugins and register their callbacks with PB. 1212 for (auto &PluginFN : CodeGenOpts.PassPlugins) { 1213 auto PassPlugin = PassPlugin::Load(PluginFN); 1214 if (PassPlugin) { 1215 PassPlugin->registerPassBuilderCallbacks(PB); 1216 } else { 1217 Diags.Report(diag::err_fe_unable_to_load_plugin) 1218 << PluginFN << toString(PassPlugin.takeError()); 1219 } 1220 } 1221 #define HANDLE_EXTENSION(Ext) \ 1222 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB); 1223 #include "llvm/Support/Extension.def" 1224 1225 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager); 1226 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager); 1227 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager); 1228 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager); 1229 1230 // Register the AA manager first so that our version is the one used. 1231 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); }); 1232 1233 // Register the target library analysis directly and give it a customized 1234 // preset TLI. 1235 Triple TargetTriple(TheModule->getTargetTriple()); 1236 std::unique_ptr<TargetLibraryInfoImpl> TLII( 1237 createTLII(TargetTriple, CodeGenOpts)); 1238 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); 1239 1240 // Register all the basic analyses with the managers. 1241 PB.registerModuleAnalyses(MAM); 1242 PB.registerCGSCCAnalyses(CGAM); 1243 PB.registerFunctionAnalyses(FAM); 1244 PB.registerLoopAnalyses(LAM); 1245 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 1246 1247 ModulePassManager MPM(CodeGenOpts.DebugPassManager); 1248 1249 if (!CodeGenOpts.DisableLLVMPasses) { 1250 // Map our optimization levels into one of the distinct levels used to 1251 // configure the pipeline. 1252 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts); 1253 1254 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO; 1255 bool IsLTO = CodeGenOpts.PrepareForLTO; 1256 1257 if (CodeGenOpts.OptimizationLevel == 0) { 1258 // If we reached here with a non-empty index file name, then the index 1259 // file was empty and we are not performing ThinLTO backend compilation 1260 // (used in testing in a distributed build environment). Drop any the type 1261 // test assume sequences inserted for whole program vtables so that 1262 // codegen doesn't complain. 1263 if (!CodeGenOpts.ThinLTOIndexFile.empty()) 1264 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, 1265 /*ImportSummary=*/nullptr, 1266 /*DropTypeTests=*/true)); 1267 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) 1268 MPM.addPass(GCOVProfilerPass(*Options)); 1269 if (Optional<InstrProfOptions> Options = 1270 getInstrProfOptions(CodeGenOpts, LangOpts)) 1271 MPM.addPass(InstrProfiling(*Options, false)); 1272 1273 // Build a minimal pipeline based on the semantics required by Clang, 1274 // which is just that always inlining occurs. Further, disable generating 1275 // lifetime intrinsics to avoid enabling further optimizations during 1276 // code generation. 1277 // However, we need to insert lifetime intrinsics to avoid invalid access 1278 // caused by multithreaded coroutines. 1279 MPM.addPass( 1280 AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines)); 1281 1282 // At -O0, we can still do PGO. Add all the requested passes for 1283 // instrumentation PGO, if requested. 1284 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr || 1285 PGOOpt->Action == PGOOptions::IRUse)) 1286 PB.addPGOInstrPassesForO0( 1287 MPM, 1288 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr), 1289 /* IsCS */ false, PGOOpt->ProfileFile, 1290 PGOOpt->ProfileRemappingFile); 1291 1292 // At -O0 we directly run necessary sanitizer passes. 1293 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) 1294 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass())); 1295 1296 // Lastly, add semantically necessary passes for LTO. 1297 if (IsLTO || IsThinLTO) { 1298 MPM.addPass(CanonicalizeAliasesPass()); 1299 MPM.addPass(NameAnonGlobalPass()); 1300 } 1301 } else { 1302 // If we reached here with a non-empty index file name, then the index 1303 // file was empty and we are not performing ThinLTO backend compilation 1304 // (used in testing in a distributed build environment). Drop any the type 1305 // test assume sequences inserted for whole program vtables so that 1306 // codegen doesn't complain. 1307 if (!CodeGenOpts.ThinLTOIndexFile.empty()) 1308 PB.registerPipelineStartEPCallback( 1309 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1310 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, 1311 /*ImportSummary=*/nullptr, 1312 /*DropTypeTests=*/true)); 1313 }); 1314 1315 PB.registerPipelineStartEPCallback( 1316 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1317 MPM.addPass(createModuleToFunctionPassAdaptor( 1318 EntryExitInstrumenterPass(/*PostInlining=*/false))); 1319 }); 1320 1321 // Register callbacks to schedule sanitizer passes at the appropriate part of 1322 // the pipeline. 1323 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) 1324 PB.registerScalarOptimizerLateEPCallback( 1325 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 1326 FPM.addPass(BoundsCheckingPass()); 1327 }); 1328 1329 if (CodeGenOpts.SanitizeCoverageType || 1330 CodeGenOpts.SanitizeCoverageIndirectCalls || 1331 CodeGenOpts.SanitizeCoverageTraceCmp) { 1332 PB.registerOptimizerLastEPCallback( 1333 [this](ModulePassManager &MPM, 1334 PassBuilder::OptimizationLevel Level) { 1335 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts); 1336 MPM.addPass(ModuleSanitizerCoveragePass( 1337 SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles, 1338 CodeGenOpts.SanitizeCoverageBlocklistFiles)); 1339 }); 1340 } 1341 1342 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 1343 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins; 1344 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory); 1345 PB.registerOptimizerLastEPCallback( 1346 [TrackOrigins, Recover](ModulePassManager &MPM, 1347 PassBuilder::OptimizationLevel Level) { 1348 MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false})); 1349 MPM.addPass(createModuleToFunctionPassAdaptor( 1350 MemorySanitizerPass({TrackOrigins, Recover, false}))); 1351 }); 1352 } 1353 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 1354 PB.registerOptimizerLastEPCallback( 1355 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1356 MPM.addPass(ThreadSanitizerPass()); 1357 MPM.addPass( 1358 createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); 1359 }); 1360 } 1361 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 1362 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address); 1363 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope; 1364 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts); 1365 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator; 1366 PB.registerOptimizerLastEPCallback( 1367 [Recover, UseAfterScope, ModuleUseAfterScope, UseOdrIndicator]( 1368 ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1369 MPM.addPass( 1370 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 1371 MPM.addPass(ModuleAddressSanitizerPass( 1372 /*CompileKernel=*/false, Recover, ModuleUseAfterScope, 1373 UseOdrIndicator)); 1374 MPM.addPass( 1375 createModuleToFunctionPassAdaptor(AddressSanitizerPass( 1376 /*CompileKernel=*/false, Recover, UseAfterScope))); 1377 }); 1378 } 1379 1380 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { 1381 bool Recover = 1382 CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress); 1383 PB.registerOptimizerLastEPCallback( 1384 [Recover](ModulePassManager &MPM, 1385 PassBuilder::OptimizationLevel Level) { 1386 MPM.addPass(HWAddressSanitizerPass( 1387 /*CompileKernel=*/false, Recover)); 1388 }); 1389 } 1390 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { 1391 bool Recover = 1392 CodeGenOpts.SanitizeRecover.has(SanitizerKind::KernelHWAddress); 1393 PB.registerOptimizerLastEPCallback( 1394 [Recover](ModulePassManager &MPM, 1395 PassBuilder::OptimizationLevel Level) { 1396 MPM.addPass(HWAddressSanitizerPass( 1397 /*CompileKernel=*/true, Recover)); 1398 }); 1399 } 1400 1401 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) 1402 PB.registerPipelineStartEPCallback( 1403 [Options](ModulePassManager &MPM, 1404 PassBuilder::OptimizationLevel Level) { 1405 MPM.addPass(GCOVProfilerPass(*Options)); 1406 }); 1407 if (Optional<InstrProfOptions> Options = 1408 getInstrProfOptions(CodeGenOpts, LangOpts)) 1409 PB.registerPipelineStartEPCallback( 1410 [Options](ModulePassManager &MPM, 1411 PassBuilder::OptimizationLevel Level) { 1412 MPM.addPass(InstrProfiling(*Options, false)); 1413 }); 1414 1415 if (IsThinLTO) { 1416 MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level); 1417 MPM.addPass(CanonicalizeAliasesPass()); 1418 MPM.addPass(NameAnonGlobalPass()); 1419 } else if (IsLTO) { 1420 MPM = PB.buildLTOPreLinkDefaultPipeline(Level); 1421 MPM.addPass(CanonicalizeAliasesPass()); 1422 MPM.addPass(NameAnonGlobalPass()); 1423 } else { 1424 MPM = PB.buildPerModuleDefaultPipeline(Level); 1425 } 1426 } 1427 1428 // Add UniqueInternalLinkageNames Pass which renames internal linkage 1429 // symbols with unique names. 1430 if (CodeGenOpts.UniqueInternalLinkageNames) 1431 MPM.addPass(UniqueInternalLinkageNamesPass()); 1432 1433 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 1434 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass())); 1435 MPM.addPass(ModuleMemProfilerPass()); 1436 } 1437 1438 if (CodeGenOpts.OptimizationLevel == 0) { 1439 PB.runRegisteredEPCallbacks(MPM, Level, CodeGenOpts.DebugPassManager); 1440 1441 // FIXME: the backends do not handle matrix intrinsics currently. Make 1442 // sure they are also lowered in O0. A lightweight version of the pass 1443 // should run in the backend pipeline on demand. 1444 if (LangOpts.MatrixTypes) 1445 MPM.addPass( 1446 createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass())); 1447 1448 addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts); 1449 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts); 1450 } 1451 } 1452 1453 // FIXME: We still use the legacy pass manager to do code generation. We 1454 // create that pass manager here and use it as needed below. 1455 legacy::PassManager CodeGenPasses; 1456 bool NeedCodeGen = false; 1457 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 1458 1459 // Append any output we need to the pass manager. 1460 switch (Action) { 1461 case Backend_EmitNothing: 1462 break; 1463 1464 case Backend_EmitBC: 1465 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 1466 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 1467 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 1468 if (!ThinLinkOS) 1469 return; 1470 } 1471 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1472 CodeGenOpts.EnableSplitLTOUnit); 1473 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os() 1474 : nullptr)); 1475 } else { 1476 // Emit a module summary by default for Regular LTO except for ld64 1477 // targets 1478 bool EmitLTOSummary = 1479 (CodeGenOpts.PrepareForLTO && 1480 !CodeGenOpts.DisableLLVMPasses && 1481 llvm::Triple(TheModule->getTargetTriple()).getVendor() != 1482 llvm::Triple::Apple); 1483 if (EmitLTOSummary) { 1484 if (!TheModule->getModuleFlag("ThinLTO")) 1485 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 1486 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1487 uint32_t(1)); 1488 } 1489 MPM.addPass( 1490 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); 1491 } 1492 break; 1493 1494 case Backend_EmitLL: 1495 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 1496 break; 1497 1498 case Backend_EmitAssembly: 1499 case Backend_EmitMCNull: 1500 case Backend_EmitObj: 1501 NeedCodeGen = true; 1502 CodeGenPasses.add( 1503 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 1504 if (!CodeGenOpts.SplitDwarfOutput.empty()) { 1505 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); 1506 if (!DwoOS) 1507 return; 1508 } 1509 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 1510 DwoOS ? &DwoOS->os() : nullptr)) 1511 // FIXME: Should we handle this error differently? 1512 return; 1513 break; 1514 } 1515 1516 // Before executing passes, print the final values of the LLVM options. 1517 cl::PrintOptionValues(); 1518 1519 // Now that we have all of the passes ready, run them. 1520 { 1521 PrettyStackTraceString CrashInfo("Optimizer"); 1522 MPM.run(*TheModule, MAM); 1523 } 1524 1525 // Now if needed, run the legacy PM for codegen. 1526 if (NeedCodeGen) { 1527 PrettyStackTraceString CrashInfo("Code generation"); 1528 CodeGenPasses.run(*TheModule); 1529 } 1530 1531 if (ThinLinkOS) 1532 ThinLinkOS->keep(); 1533 if (DwoOS) 1534 DwoOS->keep(); 1535 } 1536 1537 static void runThinLTOBackend( 1538 DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M, 1539 const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts, 1540 const clang::TargetOptions &TOpts, const LangOptions &LOpts, 1541 std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile, 1542 std::string ProfileRemapping, BackendAction Action) { 1543 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>> 1544 ModuleToDefinedGVSummaries; 1545 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 1546 1547 setCommandLineOpts(CGOpts); 1548 1549 // We can simply import the values mentioned in the combined index, since 1550 // we should only invoke this using the individual indexes written out 1551 // via a WriteIndexesThinBackend. 1552 FunctionImporter::ImportMapTy ImportList; 1553 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports; 1554 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap; 1555 if (!lto::loadReferencedModules(*M, *CombinedIndex, ImportList, ModuleMap, 1556 OwnedImports)) 1557 return; 1558 1559 auto AddStream = [&](size_t Task) { 1560 return std::make_unique<lto::NativeObjectStream>(std::move(OS)); 1561 }; 1562 lto::Config Conf; 1563 if (CGOpts.SaveTempsFilePrefix != "") { 1564 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".", 1565 /* UseInputModulePath */ false)) { 1566 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1567 errs() << "Error setting up ThinLTO save-temps: " << EIB.message() 1568 << '\n'; 1569 }); 1570 } 1571 } 1572 Conf.CPU = TOpts.CPU; 1573 Conf.CodeModel = getCodeModel(CGOpts); 1574 Conf.MAttrs = TOpts.Features; 1575 Conf.RelocModel = CGOpts.RelocationModel; 1576 Conf.CGOptLevel = getCGOptLevel(CGOpts); 1577 Conf.OptLevel = CGOpts.OptimizationLevel; 1578 initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts); 1579 Conf.SampleProfile = std::move(SampleProfile); 1580 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops; 1581 // For historical reasons, loop interleaving is set to mirror setting for loop 1582 // unrolling. 1583 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops; 1584 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop; 1585 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP; 1586 // Only enable CGProfilePass when using integrated assembler, since 1587 // non-integrated assemblers don't recognize .cgprofile section. 1588 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS; 1589 1590 // Context sensitive profile. 1591 if (CGOpts.hasProfileCSIRInstr()) { 1592 Conf.RunCSIRInstr = true; 1593 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput); 1594 } else if (CGOpts.hasProfileCSIRUse()) { 1595 Conf.RunCSIRInstr = false; 1596 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath); 1597 } 1598 1599 Conf.ProfileRemapping = std::move(ProfileRemapping); 1600 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager; 1601 Conf.DebugPassManager = CGOpts.DebugPassManager; 1602 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness; 1603 Conf.RemarksFilename = CGOpts.OptRecordFile; 1604 Conf.RemarksPasses = CGOpts.OptRecordPasses; 1605 Conf.RemarksFormat = CGOpts.OptRecordFormat; 1606 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile; 1607 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput; 1608 switch (Action) { 1609 case Backend_EmitNothing: 1610 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) { 1611 return false; 1612 }; 1613 break; 1614 case Backend_EmitLL: 1615 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1616 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists); 1617 return false; 1618 }; 1619 break; 1620 case Backend_EmitBC: 1621 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1622 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists); 1623 return false; 1624 }; 1625 break; 1626 default: 1627 Conf.CGFileType = getCodeGenFileType(Action); 1628 break; 1629 } 1630 if (Error E = 1631 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList, 1632 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], 1633 ModuleMap, CGOpts.CmdArgs)) { 1634 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1635 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; 1636 }); 1637 } 1638 } 1639 1640 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 1641 const HeaderSearchOptions &HeaderOpts, 1642 const CodeGenOptions &CGOpts, 1643 const clang::TargetOptions &TOpts, 1644 const LangOptions &LOpts, 1645 const llvm::DataLayout &TDesc, Module *M, 1646 BackendAction Action, 1647 std::unique_ptr<raw_pwrite_stream> OS) { 1648 1649 llvm::TimeTraceScope TimeScope("Backend"); 1650 1651 std::unique_ptr<llvm::Module> EmptyModule; 1652 if (!CGOpts.ThinLTOIndexFile.empty()) { 1653 // If we are performing a ThinLTO importing compile, load the function index 1654 // into memory and pass it into runThinLTOBackend, which will run the 1655 // function importer and invoke LTO passes. 1656 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = 1657 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile, 1658 /*IgnoreEmptyThinLTOIndexFile*/true); 1659 if (!IndexOrErr) { 1660 logAllUnhandledErrors(IndexOrErr.takeError(), errs(), 1661 "Error loading index file '" + 1662 CGOpts.ThinLTOIndexFile + "': "); 1663 return; 1664 } 1665 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr); 1666 // A null CombinedIndex means we should skip ThinLTO compilation 1667 // (LLVM will optionally ignore empty index files, returning null instead 1668 // of an error). 1669 if (CombinedIndex) { 1670 if (!CombinedIndex->skipModuleByDistributedBackend()) { 1671 runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts, 1672 TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile, 1673 CGOpts.ProfileRemappingFile, Action); 1674 return; 1675 } 1676 // Distributed indexing detected that nothing from the module is needed 1677 // for the final linking. So we can skip the compilation. We sill need to 1678 // output an empty object file to make sure that a linker does not fail 1679 // trying to read it. Also for some features, like CFI, we must skip 1680 // the compilation as CombinedIndex does not contain all required 1681 // information. 1682 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext()); 1683 EmptyModule->setTargetTriple(M->getTargetTriple()); 1684 M = EmptyModule.get(); 1685 } 1686 } 1687 1688 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M); 1689 1690 if (CGOpts.ExperimentalNewPassManager) 1691 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS)); 1692 else 1693 AsmHelper.EmitAssembly(Action, std::move(OS)); 1694 1695 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 1696 // DataLayout. 1697 if (AsmHelper.TM) { 1698 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 1699 if (DLDesc != TDesc.getStringRepresentation()) { 1700 unsigned DiagID = Diags.getCustomDiagID( 1701 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 1702 "expected target description '%1'"); 1703 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation(); 1704 } 1705 } 1706 } 1707 1708 // With -fembed-bitcode, save a copy of the llvm IR as data in the 1709 // __LLVM,__bitcode section. 1710 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 1711 llvm::MemoryBufferRef Buf) { 1712 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 1713 return; 1714 llvm::EmbedBitcodeInModule( 1715 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker, 1716 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode, 1717 CGOpts.CmdArgs); 1718 } 1719