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