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