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