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