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