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.SanitizeCoverageIgnorelistFiles)); 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.getSanitizeAddressDtor(); 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 case CodeGenOptions::Darwin_libsystem_m: 406 TLII->addVectorizableFunctionsFromVecLib( 407 TargetLibraryInfoImpl::DarwinLibSystemM); 408 break; 409 default: 410 break; 411 } 412 return TLII; 413 } 414 415 static void addSymbolRewriterPass(const CodeGenOptions &Opts, 416 legacy::PassManager *MPM) { 417 llvm::SymbolRewriter::RewriteDescriptorList DL; 418 419 llvm::SymbolRewriter::RewriteMapParser MapParser; 420 for (const auto &MapFile : Opts.RewriteMapFiles) 421 MapParser.parse(MapFile, &DL); 422 423 MPM->add(createRewriteSymbolsPass(DL)); 424 } 425 426 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) { 427 switch (CodeGenOpts.OptimizationLevel) { 428 default: 429 llvm_unreachable("Invalid optimization level!"); 430 case 0: 431 return CodeGenOpt::None; 432 case 1: 433 return CodeGenOpt::Less; 434 case 2: 435 return CodeGenOpt::Default; // O2/Os/Oz 436 case 3: 437 return CodeGenOpt::Aggressive; 438 } 439 } 440 441 static Optional<llvm::CodeModel::Model> 442 getCodeModel(const CodeGenOptions &CodeGenOpts) { 443 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 444 .Case("tiny", llvm::CodeModel::Tiny) 445 .Case("small", llvm::CodeModel::Small) 446 .Case("kernel", llvm::CodeModel::Kernel) 447 .Case("medium", llvm::CodeModel::Medium) 448 .Case("large", llvm::CodeModel::Large) 449 .Case("default", ~1u) 450 .Default(~0u); 451 assert(CodeModel != ~0u && "invalid code model!"); 452 if (CodeModel == ~1u) 453 return None; 454 return static_cast<llvm::CodeModel::Model>(CodeModel); 455 } 456 457 static CodeGenFileType getCodeGenFileType(BackendAction Action) { 458 if (Action == Backend_EmitObj) 459 return CGFT_ObjectFile; 460 else if (Action == Backend_EmitMCNull) 461 return CGFT_Null; 462 else { 463 assert(Action == Backend_EmitAssembly && "Invalid action!"); 464 return CGFT_AssemblyFile; 465 } 466 } 467 468 static bool initTargetOptions(DiagnosticsEngine &Diags, 469 llvm::TargetOptions &Options, 470 const CodeGenOptions &CodeGenOpts, 471 const clang::TargetOptions &TargetOpts, 472 const LangOptions &LangOpts, 473 const HeaderSearchOptions &HSOpts) { 474 switch (LangOpts.getThreadModel()) { 475 case LangOptions::ThreadModelKind::POSIX: 476 Options.ThreadModel = llvm::ThreadModel::POSIX; 477 break; 478 case LangOptions::ThreadModelKind::Single: 479 Options.ThreadModel = llvm::ThreadModel::Single; 480 break; 481 } 482 483 // Set float ABI type. 484 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 485 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 486 "Invalid Floating Point ABI!"); 487 Options.FloatABIType = 488 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 489 .Case("soft", llvm::FloatABI::Soft) 490 .Case("softfp", llvm::FloatABI::Soft) 491 .Case("hard", llvm::FloatABI::Hard) 492 .Default(llvm::FloatABI::Default); 493 494 // Set FP fusion mode. 495 switch (LangOpts.getDefaultFPContractMode()) { 496 case LangOptions::FPM_Off: 497 // Preserve any contraction performed by the front-end. (Strict performs 498 // splitting of the muladd intrinsic in the backend.) 499 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 500 break; 501 case LangOptions::FPM_On: 502 case LangOptions::FPM_FastHonorPragmas: 503 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 504 break; 505 case LangOptions::FPM_Fast: 506 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 507 break; 508 } 509 510 Options.BinutilsVersion = 511 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion); 512 Options.UseInitArray = CodeGenOpts.UseInitArray; 513 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 514 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections(); 515 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; 516 517 // Set EABI version. 518 Options.EABIVersion = TargetOpts.EABIVersion; 519 520 if (LangOpts.hasSjLjExceptions()) 521 Options.ExceptionModel = llvm::ExceptionHandling::SjLj; 522 if (LangOpts.hasSEHExceptions()) 523 Options.ExceptionModel = llvm::ExceptionHandling::WinEH; 524 if (LangOpts.hasDWARFExceptions()) 525 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI; 526 if (LangOpts.hasWasmExceptions()) 527 Options.ExceptionModel = llvm::ExceptionHandling::Wasm; 528 529 Options.NoInfsFPMath = LangOpts.NoHonorInfs; 530 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs; 531 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 532 Options.UnsafeFPMath = LangOpts.UnsafeFPMath; 533 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 534 535 Options.BBSections = 536 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections) 537 .Case("all", llvm::BasicBlockSection::All) 538 .Case("labels", llvm::BasicBlockSection::Labels) 539 .StartsWith("list=", llvm::BasicBlockSection::List) 540 .Case("none", llvm::BasicBlockSection::None) 541 .Default(llvm::BasicBlockSection::None); 542 543 if (Options.BBSections == llvm::BasicBlockSection::List) { 544 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 545 MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5)); 546 if (!MBOrErr) { 547 Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file) 548 << MBOrErr.getError().message(); 549 return false; 550 } 551 Options.BBSectionsFuncListBuf = std::move(*MBOrErr); 552 } 553 554 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions; 555 Options.FunctionSections = CodeGenOpts.FunctionSections; 556 Options.DataSections = CodeGenOpts.DataSections; 557 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility; 558 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 559 Options.UniqueBasicBlockSectionNames = 560 CodeGenOpts.UniqueBasicBlockSectionNames; 561 Options.TLSSize = CodeGenOpts.TLSSize; 562 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 563 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS; 564 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 565 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection; 566 Options.StackUsageOutput = CodeGenOpts.StackUsageOutput; 567 Options.EmitAddrsig = CodeGenOpts.Addrsig; 568 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection; 569 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo; 570 Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI; 571 Options.PseudoProbeForProfiling = CodeGenOpts.PseudoProbeForProfiling; 572 Options.ValueTrackingVariableLocations = 573 CodeGenOpts.ValueTrackingVariableLocations; 574 Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex; 575 576 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile; 577 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 578 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 579 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; 580 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 581 Options.MCOptions.MCIncrementalLinkerCompatible = 582 CodeGenOpts.IncrementalLinkerCompatible; 583 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 584 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn; 585 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 586 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64; 587 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments; 588 Options.MCOptions.ABIName = TargetOpts.ABI; 589 for (const auto &Entry : HSOpts.UserEntries) 590 if (!Entry.IsFramework && 591 (Entry.Group == frontend::IncludeDirGroup::Quoted || 592 Entry.Group == frontend::IncludeDirGroup::Angled || 593 Entry.Group == frontend::IncludeDirGroup::System)) 594 Options.MCOptions.IASSearchPaths.push_back( 595 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path); 596 Options.MCOptions.Argv0 = CodeGenOpts.Argv0; 597 Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs; 598 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf; 599 600 return true; 601 } 602 603 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts, 604 const LangOptions &LangOpts) { 605 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes) 606 return None; 607 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 608 // LLVM's -default-gcov-version flag is set to something invalid. 609 GCOVOptions Options; 610 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 611 Options.EmitData = CodeGenOpts.EmitGcovArcs; 612 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version)); 613 Options.NoRedZone = CodeGenOpts.DisableRedZone; 614 Options.Filter = CodeGenOpts.ProfileFilterFiles; 615 Options.Exclude = CodeGenOpts.ProfileExcludeFiles; 616 Options.Atomic = CodeGenOpts.AtomicProfileUpdate; 617 return Options; 618 } 619 620 static Optional<InstrProfOptions> 621 getInstrProfOptions(const CodeGenOptions &CodeGenOpts, 622 const LangOptions &LangOpts) { 623 if (!CodeGenOpts.hasProfileClangInstr()) 624 return None; 625 InstrProfOptions Options; 626 Options.NoRedZone = CodeGenOpts.DisableRedZone; 627 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 628 Options.Atomic = CodeGenOpts.AtomicProfileUpdate; 629 return Options; 630 } 631 632 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM, 633 legacy::FunctionPassManager &FPM) { 634 // Handle disabling of all LLVM passes, where we want to preserve the 635 // internal module before any optimization. 636 if (CodeGenOpts.DisableLLVMPasses) 637 return; 638 639 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM 640 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling) 641 // are inserted before PMBuilder ones - they'd get the default-constructed 642 // TLI with an unknown target otherwise. 643 Triple TargetTriple(TheModule->getTargetTriple()); 644 std::unique_ptr<TargetLibraryInfoImpl> TLII( 645 createTLII(TargetTriple, CodeGenOpts)); 646 647 // If we reached here with a non-empty index file name, then the index file 648 // was empty and we are not performing ThinLTO backend compilation (used in 649 // testing in a distributed build environment). Drop any the type test 650 // assume sequences inserted for whole program vtables so that codegen doesn't 651 // complain. 652 if (!CodeGenOpts.ThinLTOIndexFile.empty()) 653 MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr, 654 /*ImportSummary=*/nullptr, 655 /*DropTypeTests=*/true)); 656 657 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts); 658 659 // At O0 and O1 we only run the always inliner which is more efficient. At 660 // higher optimization levels we run the normal inliner. 661 if (CodeGenOpts.OptimizationLevel <= 1) { 662 bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 && 663 !CodeGenOpts.DisableLifetimeMarkers) || 664 LangOpts.Coroutines); 665 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics); 666 } else { 667 // We do not want to inline hot callsites for SamplePGO module-summary build 668 // because profile annotation will happen again in ThinLTO backend, and we 669 // want the IR of the hot path to match the profile. 670 PMBuilder.Inliner = createFunctionInliningPass( 671 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize, 672 (!CodeGenOpts.SampleProfileFile.empty() && 673 CodeGenOpts.PrepareForThinLTO)); 674 } 675 676 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel; 677 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 678 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 679 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 680 // Only enable CGProfilePass when using integrated assembler, since 681 // non-integrated assemblers don't recognize .cgprofile section. 682 PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS; 683 684 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 685 // Loop interleaving in the loop vectorizer has historically been set to be 686 // enabled when loop unrolling is enabled. 687 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops; 688 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; 689 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO; 690 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO; 691 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 692 693 MPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 694 695 if (TM) 696 TM->adjustPassManager(PMBuilder); 697 698 if (CodeGenOpts.DebugInfoForProfiling || 699 !CodeGenOpts.SampleProfileFile.empty()) 700 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 701 addAddDiscriminatorsPass); 702 703 // In ObjC ARC mode, add the main ARC optimization passes. 704 if (LangOpts.ObjCAutoRefCount) { 705 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 706 addObjCARCExpandPass); 707 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 708 addObjCARCAPElimPass); 709 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 710 addObjCARCOptPass); 711 } 712 713 if (LangOpts.Coroutines) 714 addCoroutinePassesToExtensionPoints(PMBuilder); 715 716 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 717 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 718 addMemProfilerPasses); 719 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 720 addMemProfilerPasses); 721 } 722 723 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { 724 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 725 addBoundsCheckingPass); 726 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 727 addBoundsCheckingPass); 728 } 729 730 if (CodeGenOpts.hasSanitizeCoverage()) { 731 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 732 addSanitizerCoveragePass); 733 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 734 addSanitizerCoveragePass); 735 } 736 737 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 738 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 739 addAddressSanitizerPasses); 740 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 741 addAddressSanitizerPasses); 742 } 743 744 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 745 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 746 addKernelAddressSanitizerPasses); 747 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 748 addKernelAddressSanitizerPasses); 749 } 750 751 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { 752 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 753 addHWAddressSanitizerPasses); 754 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 755 addHWAddressSanitizerPasses); 756 } 757 758 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { 759 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 760 addKernelHWAddressSanitizerPasses); 761 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 762 addKernelHWAddressSanitizerPasses); 763 } 764 765 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 766 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 767 addMemorySanitizerPass); 768 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 769 addMemorySanitizerPass); 770 } 771 772 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) { 773 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 774 addKernelMemorySanitizerPass); 775 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 776 addKernelMemorySanitizerPass); 777 } 778 779 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 780 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 781 addThreadSanitizerPass); 782 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 783 addThreadSanitizerPass); 784 } 785 786 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 787 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 788 addDataFlowSanitizerPass); 789 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 790 addDataFlowSanitizerPass); 791 } 792 793 if (CodeGenOpts.InstrumentFunctions || 794 CodeGenOpts.InstrumentFunctionEntryBare || 795 CodeGenOpts.InstrumentFunctionsAfterInlining || 796 CodeGenOpts.InstrumentForProfiling) { 797 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 798 addEntryExitInstrumentationPass); 799 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 800 addEntryExitInstrumentationPass); 801 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 802 addPostInlineEntryExitInstrumentationPass); 803 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 804 addPostInlineEntryExitInstrumentationPass); 805 } 806 807 // Set up the per-function pass manager. 808 FPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 809 if (CodeGenOpts.VerifyModule) 810 FPM.add(createVerifierPass()); 811 812 // Set up the per-module pass manager. 813 if (!CodeGenOpts.RewriteMapFiles.empty()) 814 addSymbolRewriterPass(CodeGenOpts, &MPM); 815 816 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) { 817 MPM.add(createGCOVProfilerPass(*Options)); 818 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo) 819 MPM.add(createStripSymbolsPass(true)); 820 } 821 822 if (Optional<InstrProfOptions> Options = 823 getInstrProfOptions(CodeGenOpts, LangOpts)) 824 MPM.add(createInstrProfilingLegacyPass(*Options, false)); 825 826 bool hasIRInstr = false; 827 if (CodeGenOpts.hasProfileIRInstr()) { 828 PMBuilder.EnablePGOInstrGen = true; 829 hasIRInstr = true; 830 } 831 if (CodeGenOpts.hasProfileCSIRInstr()) { 832 assert(!CodeGenOpts.hasProfileCSIRUse() && 833 "Cannot have both CSProfileUse pass and CSProfileGen pass at the " 834 "same time"); 835 assert(!hasIRInstr && 836 "Cannot have both ProfileGen pass and CSProfileGen pass at the " 837 "same time"); 838 PMBuilder.EnablePGOCSInstrGen = true; 839 hasIRInstr = true; 840 } 841 if (hasIRInstr) { 842 if (!CodeGenOpts.InstrProfileOutput.empty()) 843 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput; 844 else 845 PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName); 846 } 847 if (CodeGenOpts.hasProfileIRUse()) { 848 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath; 849 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse(); 850 } 851 852 if (!CodeGenOpts.SampleProfileFile.empty()) 853 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile; 854 855 PMBuilder.populateFunctionPassManager(FPM); 856 PMBuilder.populateModulePassManager(MPM); 857 } 858 859 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) { 860 SmallVector<const char *, 16> BackendArgs; 861 BackendArgs.push_back("clang"); // Fake program name. 862 if (!CodeGenOpts.DebugPass.empty()) { 863 BackendArgs.push_back("-debug-pass"); 864 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 865 } 866 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 867 BackendArgs.push_back("-limit-float-precision"); 868 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 869 } 870 // Check for the default "clang" invocation that won't set any cl::opt values. 871 // Skip trying to parse the command line invocation to avoid the issues 872 // described below. 873 if (BackendArgs.size() == 1) 874 return; 875 BackendArgs.push_back(nullptr); 876 // FIXME: The command line parser below is not thread-safe and shares a global 877 // state, so this call might crash or overwrite the options of another Clang 878 // instance in the same process. 879 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 880 BackendArgs.data()); 881 } 882 883 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 884 // Create the TargetMachine for generating code. 885 std::string Error; 886 std::string Triple = TheModule->getTargetTriple(); 887 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 888 if (!TheTarget) { 889 if (MustCreateTM) 890 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 891 return; 892 } 893 894 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts); 895 std::string FeaturesStr = 896 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 897 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel; 898 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts); 899 900 llvm::TargetOptions Options; 901 if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts, 902 HSOpts)) 903 return; 904 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr, 905 Options, RM, CM, OptLevel)); 906 } 907 908 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses, 909 BackendAction Action, 910 raw_pwrite_stream &OS, 911 raw_pwrite_stream *DwoOS) { 912 // Add LibraryInfo. 913 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 914 std::unique_ptr<TargetLibraryInfoImpl> TLII( 915 createTLII(TargetTriple, CodeGenOpts)); 916 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII)); 917 918 // Normal mode, emit a .s or .o file by running the code generator. Note, 919 // this also adds codegenerator level optimization passes. 920 CodeGenFileType CGFT = getCodeGenFileType(Action); 921 922 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 923 // "codegen" passes so that it isn't run multiple times when there is 924 // inlining happening. 925 if (CodeGenOpts.OptimizationLevel > 0) 926 CodeGenPasses.add(createObjCARCContractPass()); 927 928 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT, 929 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 930 Diags.Report(diag::err_fe_unable_to_interface_with_target); 931 return false; 932 } 933 934 return true; 935 } 936 937 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 938 std::unique_ptr<raw_pwrite_stream> OS) { 939 TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr); 940 941 setCommandLineOpts(CodeGenOpts); 942 943 bool UsesCodeGen = (Action != Backend_EmitNothing && 944 Action != Backend_EmitBC && 945 Action != Backend_EmitLL); 946 CreateTargetMachine(UsesCodeGen); 947 948 if (UsesCodeGen && !TM) 949 return; 950 if (TM) 951 TheModule->setDataLayout(TM->createDataLayout()); 952 953 DebugifyCustomPassManager PerModulePasses; 954 DebugInfoPerPassMap DIPreservationMap; 955 if (CodeGenOpts.EnableDIPreservationVerify) { 956 PerModulePasses.setDebugifyMode(DebugifyMode::OriginalDebugInfo); 957 PerModulePasses.setDIPreservationMap(DIPreservationMap); 958 959 if (!CodeGenOpts.DIBugsReportFilePath.empty()) 960 PerModulePasses.setOrigDIVerifyBugsReportFilePath( 961 CodeGenOpts.DIBugsReportFilePath); 962 } 963 PerModulePasses.add( 964 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 965 966 legacy::FunctionPassManager PerFunctionPasses(TheModule); 967 PerFunctionPasses.add( 968 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 969 970 CreatePasses(PerModulePasses, PerFunctionPasses); 971 972 legacy::PassManager CodeGenPasses; 973 CodeGenPasses.add( 974 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 975 976 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 977 978 switch (Action) { 979 case Backend_EmitNothing: 980 break; 981 982 case Backend_EmitBC: 983 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 984 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 985 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 986 if (!ThinLinkOS) 987 return; 988 } 989 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 990 CodeGenOpts.EnableSplitLTOUnit); 991 PerModulePasses.add(createWriteThinLTOBitcodePass( 992 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr)); 993 } else { 994 // Emit a module summary by default for Regular LTO except for ld64 995 // targets 996 bool EmitLTOSummary = 997 (CodeGenOpts.PrepareForLTO && 998 !CodeGenOpts.DisableLLVMPasses && 999 llvm::Triple(TheModule->getTargetTriple()).getVendor() != 1000 llvm::Triple::Apple); 1001 if (EmitLTOSummary) { 1002 if (!TheModule->getModuleFlag("ThinLTO")) 1003 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 1004 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1005 uint32_t(1)); 1006 } 1007 1008 PerModulePasses.add(createBitcodeWriterPass( 1009 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); 1010 } 1011 break; 1012 1013 case Backend_EmitLL: 1014 PerModulePasses.add( 1015 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 1016 break; 1017 1018 default: 1019 if (!CodeGenOpts.SplitDwarfOutput.empty()) { 1020 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); 1021 if (!DwoOS) 1022 return; 1023 } 1024 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 1025 DwoOS ? &DwoOS->os() : nullptr)) 1026 return; 1027 } 1028 1029 // Before executing passes, print the final values of the LLVM options. 1030 cl::PrintOptionValues(); 1031 1032 // Run passes. For now we do all passes at once, but eventually we 1033 // would like to have the option of streaming code generation. 1034 1035 { 1036 PrettyStackTraceString CrashInfo("Per-function optimization"); 1037 llvm::TimeTraceScope TimeScope("PerFunctionPasses"); 1038 1039 PerFunctionPasses.doInitialization(); 1040 for (Function &F : *TheModule) 1041 if (!F.isDeclaration()) 1042 PerFunctionPasses.run(F); 1043 PerFunctionPasses.doFinalization(); 1044 } 1045 1046 { 1047 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 1048 llvm::TimeTraceScope TimeScope("PerModulePasses"); 1049 PerModulePasses.run(*TheModule); 1050 } 1051 1052 { 1053 PrettyStackTraceString CrashInfo("Code generation"); 1054 llvm::TimeTraceScope TimeScope("CodeGenPasses"); 1055 CodeGenPasses.run(*TheModule); 1056 } 1057 1058 if (ThinLinkOS) 1059 ThinLinkOS->keep(); 1060 if (DwoOS) 1061 DwoOS->keep(); 1062 } 1063 1064 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) { 1065 switch (Opts.OptimizationLevel) { 1066 default: 1067 llvm_unreachable("Invalid optimization level!"); 1068 1069 case 0: 1070 return PassBuilder::OptimizationLevel::O0; 1071 1072 case 1: 1073 return PassBuilder::OptimizationLevel::O1; 1074 1075 case 2: 1076 switch (Opts.OptimizeSize) { 1077 default: 1078 llvm_unreachable("Invalid optimization level for size!"); 1079 1080 case 0: 1081 return PassBuilder::OptimizationLevel::O2; 1082 1083 case 1: 1084 return PassBuilder::OptimizationLevel::Os; 1085 1086 case 2: 1087 return PassBuilder::OptimizationLevel::Oz; 1088 } 1089 1090 case 3: 1091 return PassBuilder::OptimizationLevel::O3; 1092 } 1093 } 1094 1095 static void addSanitizers(const Triple &TargetTriple, 1096 const CodeGenOptions &CodeGenOpts, 1097 const LangOptions &LangOpts, PassBuilder &PB) { 1098 PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM, 1099 PassBuilder::OptimizationLevel Level) { 1100 if (CodeGenOpts.hasSanitizeCoverage()) { 1101 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts); 1102 MPM.addPass(ModuleSanitizerCoveragePass( 1103 SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles, 1104 CodeGenOpts.SanitizeCoverageIgnorelistFiles)); 1105 } 1106 1107 auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) { 1108 if (LangOpts.Sanitize.has(Mask)) { 1109 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins; 1110 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 1111 1112 MPM.addPass( 1113 MemorySanitizerPass({TrackOrigins, Recover, CompileKernel})); 1114 FunctionPassManager FPM; 1115 FPM.addPass( 1116 MemorySanitizerPass({TrackOrigins, Recover, CompileKernel})); 1117 if (Level != PassBuilder::OptimizationLevel::O0) { 1118 // MemorySanitizer inserts complex instrumentation that mostly 1119 // follows the logic of the original code, but operates on 1120 // "shadow" values. It can benefit from re-running some 1121 // general purpose optimization passes. 1122 FPM.addPass(EarlyCSEPass()); 1123 // TODO: Consider add more passes like in 1124 // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible 1125 // difference on size. It's not clear if the rest is still 1126 // usefull. InstCombinePass breakes 1127 // compiler-rt/test/msan/select_origin.cpp. 1128 } 1129 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1130 } 1131 }; 1132 MSanPass(SanitizerKind::Memory, false); 1133 MSanPass(SanitizerKind::KernelMemory, true); 1134 1135 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 1136 MPM.addPass(ThreadSanitizerPass()); 1137 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); 1138 } 1139 1140 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 1141 if (LangOpts.Sanitize.has(Mask)) { 1142 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 1143 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope; 1144 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts); 1145 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator; 1146 llvm::AsanDtorKind DestructorKind = 1147 CodeGenOpts.getSanitizeAddressDtor(); 1148 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 1149 MPM.addPass(ModuleAddressSanitizerPass( 1150 CompileKernel, Recover, ModuleUseAfterScope, UseOdrIndicator, 1151 DestructorKind)); 1152 MPM.addPass(createModuleToFunctionPassAdaptor( 1153 AddressSanitizerPass(CompileKernel, Recover, UseAfterScope))); 1154 } 1155 }; 1156 ASanPass(SanitizerKind::Address, false); 1157 ASanPass(SanitizerKind::KernelAddress, true); 1158 1159 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 1160 if (LangOpts.Sanitize.has(Mask)) { 1161 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 1162 MPM.addPass(HWAddressSanitizerPass(CompileKernel, Recover)); 1163 } 1164 }; 1165 HWASanPass(SanitizerKind::HWAddress, false); 1166 HWASanPass(SanitizerKind::KernelHWAddress, true); 1167 1168 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 1169 MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles)); 1170 } 1171 }); 1172 } 1173 1174 /// A clean version of `EmitAssembly` that uses the new pass manager. 1175 /// 1176 /// Not all features are currently supported in this system, but where 1177 /// necessary it falls back to the legacy pass manager to at least provide 1178 /// basic functionality. 1179 /// 1180 /// This API is planned to have its functionality finished and then to replace 1181 /// `EmitAssembly` at some point in the future when the default switches. 1182 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager( 1183 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) { 1184 TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr); 1185 setCommandLineOpts(CodeGenOpts); 1186 1187 bool RequiresCodeGen = (Action != Backend_EmitNothing && 1188 Action != Backend_EmitBC && 1189 Action != Backend_EmitLL); 1190 CreateTargetMachine(RequiresCodeGen); 1191 1192 if (RequiresCodeGen && !TM) 1193 return; 1194 if (TM) 1195 TheModule->setDataLayout(TM->createDataLayout()); 1196 1197 Optional<PGOOptions> PGOOpt; 1198 1199 if (CodeGenOpts.hasProfileIRInstr()) 1200 // -fprofile-generate. 1201 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty() 1202 ? std::string(DefaultProfileGenName) 1203 : CodeGenOpts.InstrProfileOutput, 1204 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction, 1205 CodeGenOpts.DebugInfoForProfiling); 1206 else if (CodeGenOpts.hasProfileIRUse()) { 1207 // -fprofile-use. 1208 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse 1209 : PGOOptions::NoCSAction; 1210 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "", 1211 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse, 1212 CSAction, CodeGenOpts.DebugInfoForProfiling); 1213 } else if (!CodeGenOpts.SampleProfileFile.empty()) 1214 // -fprofile-sample-use 1215 PGOOpt = PGOOptions( 1216 CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile, 1217 PGOOptions::SampleUse, PGOOptions::NoCSAction, 1218 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling); 1219 else if (CodeGenOpts.PseudoProbeForProfiling) 1220 // -fpseudo-probe-for-profiling 1221 PGOOpt = 1222 PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction, 1223 CodeGenOpts.DebugInfoForProfiling, true); 1224 else if (CodeGenOpts.DebugInfoForProfiling) 1225 // -fdebug-info-for-profiling 1226 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction, 1227 PGOOptions::NoCSAction, true); 1228 1229 // Check to see if we want to generate a CS profile. 1230 if (CodeGenOpts.hasProfileCSIRInstr()) { 1231 assert(!CodeGenOpts.hasProfileCSIRUse() && 1232 "Cannot have both CSProfileUse pass and CSProfileGen pass at " 1233 "the same time"); 1234 if (PGOOpt.hasValue()) { 1235 assert(PGOOpt->Action != PGOOptions::IRInstr && 1236 PGOOpt->Action != PGOOptions::SampleUse && 1237 "Cannot run CSProfileGen pass with ProfileGen or SampleUse " 1238 " pass"); 1239 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() 1240 ? std::string(DefaultProfileGenName) 1241 : CodeGenOpts.InstrProfileOutput; 1242 PGOOpt->CSAction = PGOOptions::CSIRInstr; 1243 } else 1244 PGOOpt = PGOOptions("", 1245 CodeGenOpts.InstrProfileOutput.empty() 1246 ? std::string(DefaultProfileGenName) 1247 : CodeGenOpts.InstrProfileOutput, 1248 "", PGOOptions::NoAction, PGOOptions::CSIRInstr, 1249 CodeGenOpts.DebugInfoForProfiling); 1250 } 1251 1252 PipelineTuningOptions PTO; 1253 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops; 1254 // For historical reasons, loop interleaving is set to mirror setting for loop 1255 // unrolling. 1256 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops; 1257 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop; 1258 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP; 1259 PTO.MergeFunctions = CodeGenOpts.MergeFunctions; 1260 // Only enable CGProfilePass when using integrated assembler, since 1261 // non-integrated assemblers don't recognize .cgprofile section. 1262 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS; 1263 PTO.Coroutines = LangOpts.Coroutines; 1264 1265 LoopAnalysisManager LAM; 1266 FunctionAnalysisManager FAM; 1267 CGSCCAnalysisManager CGAM; 1268 ModuleAnalysisManager MAM; 1269 1270 bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure"; 1271 PassInstrumentationCallbacks PIC; 1272 PrintPassOptions PrintPassOpts; 1273 PrintPassOpts.Indent = DebugPassStructure; 1274 PrintPassOpts.SkipAnalyses = DebugPassStructure; 1275 StandardInstrumentations SI(CodeGenOpts.DebugPassManager || 1276 DebugPassStructure, 1277 /*VerifyEach*/ false, PrintPassOpts); 1278 SI.registerCallbacks(PIC, &FAM); 1279 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC); 1280 1281 // Attempt to load pass plugins and register their callbacks with PB. 1282 for (auto &PluginFN : CodeGenOpts.PassPlugins) { 1283 auto PassPlugin = PassPlugin::Load(PluginFN); 1284 if (PassPlugin) { 1285 PassPlugin->registerPassBuilderCallbacks(PB); 1286 } else { 1287 Diags.Report(diag::err_fe_unable_to_load_plugin) 1288 << PluginFN << toString(PassPlugin.takeError()); 1289 } 1290 } 1291 #define HANDLE_EXTENSION(Ext) \ 1292 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB); 1293 #include "llvm/Support/Extension.def" 1294 1295 // Register the AA manager first so that our version is the one used. 1296 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); }); 1297 1298 // Register the target library analysis directly and give it a customized 1299 // preset TLI. 1300 Triple TargetTriple(TheModule->getTargetTriple()); 1301 std::unique_ptr<TargetLibraryInfoImpl> TLII( 1302 createTLII(TargetTriple, CodeGenOpts)); 1303 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); 1304 1305 // Register all the basic analyses with the managers. 1306 PB.registerModuleAnalyses(MAM); 1307 PB.registerCGSCCAnalyses(CGAM); 1308 PB.registerFunctionAnalyses(FAM); 1309 PB.registerLoopAnalyses(LAM); 1310 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 1311 1312 ModulePassManager MPM; 1313 1314 if (!CodeGenOpts.DisableLLVMPasses) { 1315 // Map our optimization levels into one of the distinct levels used to 1316 // configure the pipeline. 1317 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts); 1318 1319 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO; 1320 bool IsLTO = CodeGenOpts.PrepareForLTO; 1321 1322 if (LangOpts.ObjCAutoRefCount) { 1323 PB.registerPipelineStartEPCallback( 1324 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1325 if (Level != PassBuilder::OptimizationLevel::O0) 1326 MPM.addPass( 1327 createModuleToFunctionPassAdaptor(ObjCARCExpandPass())); 1328 }); 1329 PB.registerPipelineEarlySimplificationEPCallback( 1330 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1331 if (Level != PassBuilder::OptimizationLevel::O0) 1332 MPM.addPass(ObjCARCAPElimPass()); 1333 }); 1334 PB.registerScalarOptimizerLateEPCallback( 1335 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 1336 if (Level != PassBuilder::OptimizationLevel::O0) 1337 FPM.addPass(ObjCARCOptPass()); 1338 }); 1339 } 1340 1341 // If we reached here with a non-empty index file name, then the index 1342 // file was empty and we are not performing ThinLTO backend compilation 1343 // (used in testing in a distributed build environment). 1344 bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty(); 1345 // If so drop any the type test assume sequences inserted for whole program 1346 // vtables so that codegen doesn't complain. 1347 if (IsThinLTOPostLink) 1348 PB.registerPipelineStartEPCallback( 1349 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1350 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, 1351 /*ImportSummary=*/nullptr, 1352 /*DropTypeTests=*/true)); 1353 }); 1354 1355 if (CodeGenOpts.InstrumentFunctions || 1356 CodeGenOpts.InstrumentFunctionEntryBare || 1357 CodeGenOpts.InstrumentFunctionsAfterInlining || 1358 CodeGenOpts.InstrumentForProfiling) { 1359 PB.registerPipelineStartEPCallback( 1360 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1361 MPM.addPass(createModuleToFunctionPassAdaptor( 1362 EntryExitInstrumenterPass(/*PostInlining=*/false))); 1363 }); 1364 PB.registerOptimizerLastEPCallback( 1365 [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) { 1366 MPM.addPass(createModuleToFunctionPassAdaptor( 1367 EntryExitInstrumenterPass(/*PostInlining=*/true))); 1368 }); 1369 } 1370 1371 // Register callbacks to schedule sanitizer passes at the appropriate part 1372 // of the pipeline. 1373 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) 1374 PB.registerScalarOptimizerLateEPCallback( 1375 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 1376 FPM.addPass(BoundsCheckingPass()); 1377 }); 1378 1379 // Don't add sanitizers if we are here from ThinLTO PostLink. That already 1380 // done on PreLink stage. 1381 if (!IsThinLTOPostLink) 1382 addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB); 1383 1384 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) 1385 PB.registerPipelineStartEPCallback( 1386 [Options](ModulePassManager &MPM, 1387 PassBuilder::OptimizationLevel Level) { 1388 MPM.addPass(GCOVProfilerPass(*Options)); 1389 }); 1390 if (Optional<InstrProfOptions> Options = 1391 getInstrProfOptions(CodeGenOpts, LangOpts)) 1392 PB.registerPipelineStartEPCallback( 1393 [Options](ModulePassManager &MPM, 1394 PassBuilder::OptimizationLevel Level) { 1395 MPM.addPass(InstrProfiling(*Options, false)); 1396 }); 1397 1398 if (CodeGenOpts.OptimizationLevel == 0) { 1399 MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO); 1400 } else if (IsThinLTO) { 1401 MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level); 1402 } else if (IsLTO) { 1403 MPM = PB.buildLTOPreLinkDefaultPipeline(Level); 1404 } else { 1405 MPM = PB.buildPerModuleDefaultPipeline(Level); 1406 } 1407 1408 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 1409 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass())); 1410 MPM.addPass(ModuleMemProfilerPass()); 1411 } 1412 } 1413 1414 // FIXME: We still use the legacy pass manager to do code generation. We 1415 // create that pass manager here and use it as needed below. 1416 legacy::PassManager CodeGenPasses; 1417 bool NeedCodeGen = false; 1418 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 1419 1420 // Append any output we need to the pass manager. 1421 switch (Action) { 1422 case Backend_EmitNothing: 1423 break; 1424 1425 case Backend_EmitBC: 1426 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 1427 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 1428 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 1429 if (!ThinLinkOS) 1430 return; 1431 } 1432 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1433 CodeGenOpts.EnableSplitLTOUnit); 1434 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os() 1435 : nullptr)); 1436 } else { 1437 // Emit a module summary by default for Regular LTO except for ld64 1438 // targets 1439 bool EmitLTOSummary = 1440 (CodeGenOpts.PrepareForLTO && 1441 !CodeGenOpts.DisableLLVMPasses && 1442 llvm::Triple(TheModule->getTargetTriple()).getVendor() != 1443 llvm::Triple::Apple); 1444 if (EmitLTOSummary) { 1445 if (!TheModule->getModuleFlag("ThinLTO")) 1446 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 1447 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1448 uint32_t(1)); 1449 } 1450 MPM.addPass( 1451 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); 1452 } 1453 break; 1454 1455 case Backend_EmitLL: 1456 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 1457 break; 1458 1459 case Backend_EmitAssembly: 1460 case Backend_EmitMCNull: 1461 case Backend_EmitObj: 1462 NeedCodeGen = true; 1463 CodeGenPasses.add( 1464 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 1465 if (!CodeGenOpts.SplitDwarfOutput.empty()) { 1466 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); 1467 if (!DwoOS) 1468 return; 1469 } 1470 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 1471 DwoOS ? &DwoOS->os() : nullptr)) 1472 // FIXME: Should we handle this error differently? 1473 return; 1474 break; 1475 } 1476 1477 // Before executing passes, print the final values of the LLVM options. 1478 cl::PrintOptionValues(); 1479 1480 // Now that we have all of the passes ready, run them. 1481 { 1482 PrettyStackTraceString CrashInfo("Optimizer"); 1483 MPM.run(*TheModule, MAM); 1484 } 1485 1486 // Now if needed, run the legacy PM for codegen. 1487 if (NeedCodeGen) { 1488 PrettyStackTraceString CrashInfo("Code generation"); 1489 CodeGenPasses.run(*TheModule); 1490 } 1491 1492 if (ThinLinkOS) 1493 ThinLinkOS->keep(); 1494 if (DwoOS) 1495 DwoOS->keep(); 1496 } 1497 1498 static void runThinLTOBackend( 1499 DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M, 1500 const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts, 1501 const clang::TargetOptions &TOpts, const LangOptions &LOpts, 1502 std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile, 1503 std::string ProfileRemapping, BackendAction Action) { 1504 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>> 1505 ModuleToDefinedGVSummaries; 1506 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 1507 1508 setCommandLineOpts(CGOpts); 1509 1510 // We can simply import the values mentioned in the combined index, since 1511 // we should only invoke this using the individual indexes written out 1512 // via a WriteIndexesThinBackend. 1513 FunctionImporter::ImportMapTy ImportList; 1514 if (!lto::initImportList(*M, *CombinedIndex, ImportList)) 1515 return; 1516 1517 auto AddStream = [&](size_t Task) { 1518 return std::make_unique<lto::NativeObjectStream>(std::move(OS)); 1519 }; 1520 lto::Config Conf; 1521 if (CGOpts.SaveTempsFilePrefix != "") { 1522 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".", 1523 /* UseInputModulePath */ false)) { 1524 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1525 errs() << "Error setting up ThinLTO save-temps: " << EIB.message() 1526 << '\n'; 1527 }); 1528 } 1529 } 1530 Conf.CPU = TOpts.CPU; 1531 Conf.CodeModel = getCodeModel(CGOpts); 1532 Conf.MAttrs = TOpts.Features; 1533 Conf.RelocModel = CGOpts.RelocationModel; 1534 Conf.CGOptLevel = getCGOptLevel(CGOpts); 1535 Conf.OptLevel = CGOpts.OptimizationLevel; 1536 initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts); 1537 Conf.SampleProfile = std::move(SampleProfile); 1538 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops; 1539 // For historical reasons, loop interleaving is set to mirror setting for loop 1540 // unrolling. 1541 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops; 1542 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop; 1543 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP; 1544 // Only enable CGProfilePass when using integrated assembler, since 1545 // non-integrated assemblers don't recognize .cgprofile section. 1546 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS; 1547 1548 // Context sensitive profile. 1549 if (CGOpts.hasProfileCSIRInstr()) { 1550 Conf.RunCSIRInstr = true; 1551 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput); 1552 } else if (CGOpts.hasProfileCSIRUse()) { 1553 Conf.RunCSIRInstr = false; 1554 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath); 1555 } 1556 1557 Conf.ProfileRemapping = std::move(ProfileRemapping); 1558 Conf.UseNewPM = !CGOpts.LegacyPassManager; 1559 Conf.DebugPassManager = CGOpts.DebugPassManager; 1560 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness; 1561 Conf.RemarksFilename = CGOpts.OptRecordFile; 1562 Conf.RemarksPasses = CGOpts.OptRecordPasses; 1563 Conf.RemarksFormat = CGOpts.OptRecordFormat; 1564 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile; 1565 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput; 1566 switch (Action) { 1567 case Backend_EmitNothing: 1568 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) { 1569 return false; 1570 }; 1571 break; 1572 case Backend_EmitLL: 1573 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1574 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists); 1575 return false; 1576 }; 1577 break; 1578 case Backend_EmitBC: 1579 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1580 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists); 1581 return false; 1582 }; 1583 break; 1584 default: 1585 Conf.CGFileType = getCodeGenFileType(Action); 1586 break; 1587 } 1588 if (Error E = 1589 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList, 1590 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], 1591 /* ModuleMap */ nullptr, CGOpts.CmdArgs)) { 1592 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1593 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; 1594 }); 1595 } 1596 } 1597 1598 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 1599 const HeaderSearchOptions &HeaderOpts, 1600 const CodeGenOptions &CGOpts, 1601 const clang::TargetOptions &TOpts, 1602 const LangOptions &LOpts, 1603 StringRef TDesc, Module *M, 1604 BackendAction Action, 1605 std::unique_ptr<raw_pwrite_stream> OS) { 1606 1607 llvm::TimeTraceScope TimeScope("Backend"); 1608 1609 std::unique_ptr<llvm::Module> EmptyModule; 1610 if (!CGOpts.ThinLTOIndexFile.empty()) { 1611 // If we are performing a ThinLTO importing compile, load the function index 1612 // into memory and pass it into runThinLTOBackend, which will run the 1613 // function importer and invoke LTO passes. 1614 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = 1615 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile, 1616 /*IgnoreEmptyThinLTOIndexFile*/true); 1617 if (!IndexOrErr) { 1618 logAllUnhandledErrors(IndexOrErr.takeError(), errs(), 1619 "Error loading index file '" + 1620 CGOpts.ThinLTOIndexFile + "': "); 1621 return; 1622 } 1623 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr); 1624 // A null CombinedIndex means we should skip ThinLTO compilation 1625 // (LLVM will optionally ignore empty index files, returning null instead 1626 // of an error). 1627 if (CombinedIndex) { 1628 if (!CombinedIndex->skipModuleByDistributedBackend()) { 1629 runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts, 1630 TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile, 1631 CGOpts.ProfileRemappingFile, Action); 1632 return; 1633 } 1634 // Distributed indexing detected that nothing from the module is needed 1635 // for the final linking. So we can skip the compilation. We sill need to 1636 // output an empty object file to make sure that a linker does not fail 1637 // trying to read it. Also for some features, like CFI, we must skip 1638 // the compilation as CombinedIndex does not contain all required 1639 // information. 1640 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext()); 1641 EmptyModule->setTargetTriple(M->getTargetTriple()); 1642 M = EmptyModule.get(); 1643 } 1644 } 1645 1646 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M); 1647 1648 if (!CGOpts.LegacyPassManager) 1649 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS)); 1650 else 1651 AsmHelper.EmitAssembly(Action, std::move(OS)); 1652 1653 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 1654 // DataLayout. 1655 if (AsmHelper.TM) { 1656 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 1657 if (DLDesc != TDesc) { 1658 unsigned DiagID = Diags.getCustomDiagID( 1659 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 1660 "expected target description '%1'"); 1661 Diags.Report(DiagID) << DLDesc << TDesc; 1662 } 1663 } 1664 } 1665 1666 // With -fembed-bitcode, save a copy of the llvm IR as data in the 1667 // __LLVM,__bitcode section. 1668 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 1669 llvm::MemoryBufferRef Buf) { 1670 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 1671 return; 1672 llvm::EmbedBitcodeInModule( 1673 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker, 1674 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode, 1675 CGOpts.CmdArgs); 1676 } 1677