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