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