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