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