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