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