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/AliasAnalysis.h" 22 #include "llvm/Analysis/StackSafetyAnalysis.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/Analysis/TargetTransformInfo.h" 25 #include "llvm/Bitcode/BitcodeReader.h" 26 #include "llvm/Bitcode/BitcodeWriter.h" 27 #include "llvm/Bitcode/BitcodeWriterPass.h" 28 #include "llvm/CodeGen/RegAllocRegistry.h" 29 #include "llvm/CodeGen/SchedulerRegistry.h" 30 #include "llvm/CodeGen/TargetSubtargetInfo.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/IRPrintingPasses.h" 33 #include "llvm/IR/LegacyPassManager.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/IR/ModuleSummaryIndex.h" 36 #include "llvm/IR/PassManager.h" 37 #include "llvm/IR/Verifier.h" 38 #include "llvm/LTO/LTOBackend.h" 39 #include "llvm/MC/MCAsmInfo.h" 40 #include "llvm/MC/SubtargetFeature.h" 41 #include "llvm/MC/TargetRegistry.h" 42 #include "llvm/Object/OffloadBinary.h" 43 #include "llvm/Passes/PassBuilder.h" 44 #include "llvm/Passes/PassPlugin.h" 45 #include "llvm/Passes/StandardInstrumentations.h" 46 #include "llvm/Support/BuryPointer.h" 47 #include "llvm/Support/CommandLine.h" 48 #include "llvm/Support/MemoryBuffer.h" 49 #include "llvm/Support/PrettyStackTrace.h" 50 #include "llvm/Support/TimeProfiler.h" 51 #include "llvm/Support/Timer.h" 52 #include "llvm/Support/ToolOutputFile.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include "llvm/Target/TargetMachine.h" 55 #include "llvm/Target/TargetOptions.h" 56 #include "llvm/Transforms/Coroutines/CoroCleanup.h" 57 #include "llvm/Transforms/Coroutines/CoroEarly.h" 58 #include "llvm/Transforms/Coroutines/CoroElide.h" 59 #include "llvm/Transforms/Coroutines/CoroSplit.h" 60 #include "llvm/Transforms/IPO.h" 61 #include "llvm/Transforms/IPO/AlwaysInliner.h" 62 #include "llvm/Transforms/IPO/LowerTypeTests.h" 63 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h" 64 #include "llvm/Transforms/InstCombine/InstCombine.h" 65 #include "llvm/Transforms/Instrumentation.h" 66 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h" 67 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h" 68 #include "llvm/Transforms/Instrumentation/BoundsChecking.h" 69 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h" 70 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" 71 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h" 72 #include "llvm/Transforms/Instrumentation/InstrProfiling.h" 73 #include "llvm/Transforms/Instrumentation/MemProfiler.h" 74 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" 75 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h" 76 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" 77 #include "llvm/Transforms/ObjCARC.h" 78 #include "llvm/Transforms/Scalar.h" 79 #include "llvm/Transforms/Scalar/EarlyCSE.h" 80 #include "llvm/Transforms/Scalar/GVN.h" 81 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h" 82 #include "llvm/Transforms/Utils.h" 83 #include "llvm/Transforms/Utils/CanonicalizeAliases.h" 84 #include "llvm/Transforms/Utils/Debugify.h" 85 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h" 86 #include "llvm/Transforms/Utils/ModuleUtils.h" 87 #include "llvm/Transforms/Utils/NameAnonGlobals.h" 88 #include "llvm/Transforms/Utils/SymbolRewriter.h" 89 #include <memory> 90 using namespace clang; 91 using namespace llvm; 92 93 #define HANDLE_EXTENSION(Ext) \ 94 llvm::PassPluginLibraryInfo get##Ext##PluginInfo(); 95 #include "llvm/Support/Extension.def" 96 97 namespace llvm { 98 extern cl::opt<bool> DebugInfoCorrelate; 99 } 100 101 namespace { 102 103 // Default filename used for profile generation. 104 std::string getDefaultProfileGenName() { 105 return DebugInfoCorrelate ? "default_%p.proflite" : "default_%m.profraw"; 106 } 107 108 class EmitAssemblyHelper { 109 DiagnosticsEngine &Diags; 110 const HeaderSearchOptions &HSOpts; 111 const CodeGenOptions &CodeGenOpts; 112 const clang::TargetOptions &TargetOpts; 113 const LangOptions &LangOpts; 114 Module *TheModule; 115 116 Timer CodeGenerationTime; 117 118 std::unique_ptr<raw_pwrite_stream> OS; 119 120 Triple TargetTriple; 121 122 TargetIRAnalysis getTargetIRAnalysis() const { 123 if (TM) 124 return TM->getTargetIRAnalysis(); 125 126 return TargetIRAnalysis(); 127 } 128 129 /// Generates the TargetMachine. 130 /// Leaves TM unchanged if it is unable to create the target machine. 131 /// Some of our clang tests specify triples which are not built 132 /// into clang. This is okay because these tests check the generated 133 /// IR, and they require DataLayout which depends on the triple. 134 /// In this case, we allow this method to fail and not report an error. 135 /// When MustCreateTM is used, we print an error if we are unable to load 136 /// the requested target. 137 void CreateTargetMachine(bool MustCreateTM); 138 139 /// Add passes necessary to emit assembly or LLVM IR. 140 /// 141 /// \return True on success. 142 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action, 143 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS); 144 145 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) { 146 std::error_code EC; 147 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC, 148 llvm::sys::fs::OF_None); 149 if (EC) { 150 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message(); 151 F.reset(); 152 } 153 return F; 154 } 155 156 void 157 RunOptimizationPipeline(BackendAction Action, 158 std::unique_ptr<raw_pwrite_stream> &OS, 159 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS); 160 void RunCodegenPipeline(BackendAction Action, 161 std::unique_ptr<raw_pwrite_stream> &OS, 162 std::unique_ptr<llvm::ToolOutputFile> &DwoOS); 163 164 /// Check whether we should emit a module summary for regular LTO. 165 /// The module summary should be emitted by default for regular LTO 166 /// except for ld64 targets. 167 /// 168 /// \return True if the module summary should be emitted. 169 bool shouldEmitRegularLTOSummary() const { 170 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses && 171 TargetTriple.getVendor() != llvm::Triple::Apple; 172 } 173 174 public: 175 EmitAssemblyHelper(DiagnosticsEngine &_Diags, 176 const HeaderSearchOptions &HeaderSearchOpts, 177 const CodeGenOptions &CGOpts, 178 const clang::TargetOptions &TOpts, 179 const LangOptions &LOpts, Module *M) 180 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts), 181 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), 182 CodeGenerationTime("codegen", "Code Generation Time"), 183 TargetTriple(TheModule->getTargetTriple()) {} 184 185 ~EmitAssemblyHelper() { 186 if (CodeGenOpts.DisableFree) 187 BuryPointer(std::move(TM)); 188 } 189 190 std::unique_ptr<TargetMachine> TM; 191 192 // Emit output using the new pass manager for the optimization pipeline. 193 void EmitAssembly(BackendAction Action, 194 std::unique_ptr<raw_pwrite_stream> OS); 195 }; 196 } 197 198 static SanitizerCoverageOptions 199 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) { 200 SanitizerCoverageOptions Opts; 201 Opts.CoverageType = 202 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType); 203 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; 204 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; 205 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; 206 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv; 207 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep; 208 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; 209 Opts.TracePC = CGOpts.SanitizeCoverageTracePC; 210 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard; 211 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune; 212 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters; 213 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag; 214 Opts.PCTable = CGOpts.SanitizeCoveragePCTable; 215 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth; 216 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads; 217 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores; 218 return Opts; 219 } 220 221 // Check if ASan should use GC-friendly instrumentation for globals. 222 // First of all, there is no point if -fdata-sections is off (expect for MachO, 223 // where this is not a factor). Also, on ELF this feature requires an assembler 224 // extension that only works with -integrated-as at the moment. 225 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) { 226 if (!CGOpts.SanitizeAddressGlobalsDeadStripping) 227 return false; 228 switch (T.getObjectFormat()) { 229 case Triple::MachO: 230 case Triple::COFF: 231 return true; 232 case Triple::ELF: 233 return !CGOpts.DisableIntegratedAS; 234 case Triple::GOFF: 235 llvm::report_fatal_error("ASan not implemented for GOFF"); 236 case Triple::XCOFF: 237 llvm::report_fatal_error("ASan not implemented for XCOFF."); 238 case Triple::Wasm: 239 case Triple::DXContainer: 240 case Triple::SPIRV: 241 case Triple::UnknownObjectFormat: 242 break; 243 } 244 return false; 245 } 246 247 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple, 248 const CodeGenOptions &CodeGenOpts) { 249 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple); 250 251 switch (CodeGenOpts.getVecLib()) { 252 case CodeGenOptions::Accelerate: 253 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); 254 break; 255 case CodeGenOptions::LIBMVEC: 256 switch(TargetTriple.getArch()) { 257 default: 258 break; 259 case llvm::Triple::x86_64: 260 TLII->addVectorizableFunctionsFromVecLib 261 (TargetLibraryInfoImpl::LIBMVEC_X86); 262 break; 263 } 264 break; 265 case CodeGenOptions::MASSV: 266 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV); 267 break; 268 case CodeGenOptions::SVML: 269 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML); 270 break; 271 case CodeGenOptions::Darwin_libsystem_m: 272 TLII->addVectorizableFunctionsFromVecLib( 273 TargetLibraryInfoImpl::DarwinLibSystemM); 274 break; 275 default: 276 break; 277 } 278 return TLII; 279 } 280 281 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) { 282 switch (CodeGenOpts.OptimizationLevel) { 283 default: 284 llvm_unreachable("Invalid optimization level!"); 285 case 0: 286 return CodeGenOpt::None; 287 case 1: 288 return CodeGenOpt::Less; 289 case 2: 290 return CodeGenOpt::Default; // O2/Os/Oz 291 case 3: 292 return CodeGenOpt::Aggressive; 293 } 294 } 295 296 static Optional<llvm::CodeModel::Model> 297 getCodeModel(const CodeGenOptions &CodeGenOpts) { 298 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 299 .Case("tiny", llvm::CodeModel::Tiny) 300 .Case("small", llvm::CodeModel::Small) 301 .Case("kernel", llvm::CodeModel::Kernel) 302 .Case("medium", llvm::CodeModel::Medium) 303 .Case("large", llvm::CodeModel::Large) 304 .Case("default", ~1u) 305 .Default(~0u); 306 assert(CodeModel != ~0u && "invalid code model!"); 307 if (CodeModel == ~1u) 308 return None; 309 return static_cast<llvm::CodeModel::Model>(CodeModel); 310 } 311 312 static CodeGenFileType getCodeGenFileType(BackendAction Action) { 313 if (Action == Backend_EmitObj) 314 return CGFT_ObjectFile; 315 else if (Action == Backend_EmitMCNull) 316 return CGFT_Null; 317 else { 318 assert(Action == Backend_EmitAssembly && "Invalid action!"); 319 return CGFT_AssemblyFile; 320 } 321 } 322 323 static bool actionRequiresCodeGen(BackendAction Action) { 324 return Action != Backend_EmitNothing && Action != Backend_EmitBC && 325 Action != Backend_EmitLL; 326 } 327 328 static bool initTargetOptions(DiagnosticsEngine &Diags, 329 llvm::TargetOptions &Options, 330 const CodeGenOptions &CodeGenOpts, 331 const clang::TargetOptions &TargetOpts, 332 const LangOptions &LangOpts, 333 const HeaderSearchOptions &HSOpts) { 334 switch (LangOpts.getThreadModel()) { 335 case LangOptions::ThreadModelKind::POSIX: 336 Options.ThreadModel = llvm::ThreadModel::POSIX; 337 break; 338 case LangOptions::ThreadModelKind::Single: 339 Options.ThreadModel = llvm::ThreadModel::Single; 340 break; 341 } 342 343 // Set float ABI type. 344 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 345 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 346 "Invalid Floating Point ABI!"); 347 Options.FloatABIType = 348 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 349 .Case("soft", llvm::FloatABI::Soft) 350 .Case("softfp", llvm::FloatABI::Soft) 351 .Case("hard", llvm::FloatABI::Hard) 352 .Default(llvm::FloatABI::Default); 353 354 // Set FP fusion mode. 355 switch (LangOpts.getDefaultFPContractMode()) { 356 case LangOptions::FPM_Off: 357 // Preserve any contraction performed by the front-end. (Strict performs 358 // splitting of the muladd intrinsic in the backend.) 359 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 360 break; 361 case LangOptions::FPM_On: 362 case LangOptions::FPM_FastHonorPragmas: 363 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 364 break; 365 case LangOptions::FPM_Fast: 366 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 367 break; 368 } 369 370 Options.BinutilsVersion = 371 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion); 372 Options.UseInitArray = CodeGenOpts.UseInitArray; 373 Options.LowerGlobalDtorsViaCxaAtExit = 374 CodeGenOpts.RegisterGlobalDtorsWithAtExit; 375 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 376 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections(); 377 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; 378 379 // Set EABI version. 380 Options.EABIVersion = TargetOpts.EABIVersion; 381 382 if (LangOpts.hasSjLjExceptions()) 383 Options.ExceptionModel = llvm::ExceptionHandling::SjLj; 384 if (LangOpts.hasSEHExceptions()) 385 Options.ExceptionModel = llvm::ExceptionHandling::WinEH; 386 if (LangOpts.hasDWARFExceptions()) 387 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI; 388 if (LangOpts.hasWasmExceptions()) 389 Options.ExceptionModel = llvm::ExceptionHandling::Wasm; 390 391 Options.NoInfsFPMath = LangOpts.NoHonorInfs; 392 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs; 393 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 394 Options.UnsafeFPMath = LangOpts.UnsafeFPMath; 395 Options.ApproxFuncFPMath = LangOpts.ApproxFunc; 396 397 Options.BBSections = 398 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections) 399 .Case("all", llvm::BasicBlockSection::All) 400 .Case("labels", llvm::BasicBlockSection::Labels) 401 .StartsWith("list=", llvm::BasicBlockSection::List) 402 .Case("none", llvm::BasicBlockSection::None) 403 .Default(llvm::BasicBlockSection::None); 404 405 if (Options.BBSections == llvm::BasicBlockSection::List) { 406 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 407 MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5)); 408 if (!MBOrErr) { 409 Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file) 410 << MBOrErr.getError().message(); 411 return false; 412 } 413 Options.BBSectionsFuncListBuf = std::move(*MBOrErr); 414 } 415 416 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions; 417 Options.FunctionSections = CodeGenOpts.FunctionSections; 418 Options.DataSections = CodeGenOpts.DataSections; 419 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility; 420 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 421 Options.UniqueBasicBlockSectionNames = 422 CodeGenOpts.UniqueBasicBlockSectionNames; 423 Options.TLSSize = CodeGenOpts.TLSSize; 424 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 425 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS; 426 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 427 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection; 428 Options.StackUsageOutput = CodeGenOpts.StackUsageOutput; 429 Options.EmitAddrsig = CodeGenOpts.Addrsig; 430 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection; 431 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo; 432 Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI; 433 Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex; 434 Options.LoopAlignment = CodeGenOpts.LoopAlignment; 435 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf; 436 Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug; 437 Options.Hotpatch = CodeGenOpts.HotPatch; 438 Options.JMCInstrument = CodeGenOpts.JMCInstrument; 439 440 switch (CodeGenOpts.getSwiftAsyncFramePointer()) { 441 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto: 442 Options.SwiftAsyncFramePointer = 443 SwiftAsyncFramePointerMode::DeploymentBased; 444 break; 445 446 case CodeGenOptions::SwiftAsyncFramePointerKind::Always: 447 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always; 448 break; 449 450 case CodeGenOptions::SwiftAsyncFramePointerKind::Never: 451 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never; 452 break; 453 } 454 455 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile; 456 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind(); 457 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 458 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 459 Options.MCOptions.MCUseDwarfDirectory = 460 CodeGenOpts.NoDwarfDirectoryAsm 461 ? llvm::MCTargetOptions::DisableDwarfDirectory 462 : llvm::MCTargetOptions::EnableDwarfDirectory; 463 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 464 Options.MCOptions.MCIncrementalLinkerCompatible = 465 CodeGenOpts.IncrementalLinkerCompatible; 466 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 467 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn; 468 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 469 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64; 470 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments; 471 Options.MCOptions.ABIName = TargetOpts.ABI; 472 for (const auto &Entry : HSOpts.UserEntries) 473 if (!Entry.IsFramework && 474 (Entry.Group == frontend::IncludeDirGroup::Quoted || 475 Entry.Group == frontend::IncludeDirGroup::Angled || 476 Entry.Group == frontend::IncludeDirGroup::System)) 477 Options.MCOptions.IASSearchPaths.push_back( 478 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path); 479 Options.MCOptions.Argv0 = CodeGenOpts.Argv0; 480 Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs; 481 Options.MisExpect = CodeGenOpts.MisExpect; 482 483 return true; 484 } 485 486 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts, 487 const LangOptions &LangOpts) { 488 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes) 489 return None; 490 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 491 // LLVM's -default-gcov-version flag is set to something invalid. 492 GCOVOptions Options; 493 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 494 Options.EmitData = CodeGenOpts.EmitGcovArcs; 495 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version)); 496 Options.NoRedZone = CodeGenOpts.DisableRedZone; 497 Options.Filter = CodeGenOpts.ProfileFilterFiles; 498 Options.Exclude = CodeGenOpts.ProfileExcludeFiles; 499 Options.Atomic = CodeGenOpts.AtomicProfileUpdate; 500 return Options; 501 } 502 503 static Optional<InstrProfOptions> 504 getInstrProfOptions(const CodeGenOptions &CodeGenOpts, 505 const LangOptions &LangOpts) { 506 if (!CodeGenOpts.hasProfileClangInstr()) 507 return None; 508 InstrProfOptions Options; 509 Options.NoRedZone = CodeGenOpts.DisableRedZone; 510 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 511 Options.Atomic = CodeGenOpts.AtomicProfileUpdate; 512 return Options; 513 } 514 515 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) { 516 SmallVector<const char *, 16> BackendArgs; 517 BackendArgs.push_back("clang"); // Fake program name. 518 if (!CodeGenOpts.DebugPass.empty()) { 519 BackendArgs.push_back("-debug-pass"); 520 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 521 } 522 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 523 BackendArgs.push_back("-limit-float-precision"); 524 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 525 } 526 // Check for the default "clang" invocation that won't set any cl::opt values. 527 // Skip trying to parse the command line invocation to avoid the issues 528 // described below. 529 if (BackendArgs.size() == 1) 530 return; 531 BackendArgs.push_back(nullptr); 532 // FIXME: The command line parser below is not thread-safe and shares a global 533 // state, so this call might crash or overwrite the options of another Clang 534 // instance in the same process. 535 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 536 BackendArgs.data()); 537 } 538 539 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 540 // Create the TargetMachine for generating code. 541 std::string Error; 542 std::string Triple = TheModule->getTargetTriple(); 543 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 544 if (!TheTarget) { 545 if (MustCreateTM) 546 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 547 return; 548 } 549 550 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts); 551 std::string FeaturesStr = 552 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 553 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel; 554 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts); 555 556 llvm::TargetOptions Options; 557 if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts, 558 HSOpts)) 559 return; 560 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr, 561 Options, RM, CM, OptLevel)); 562 } 563 564 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses, 565 BackendAction Action, 566 raw_pwrite_stream &OS, 567 raw_pwrite_stream *DwoOS) { 568 // Add LibraryInfo. 569 std::unique_ptr<TargetLibraryInfoImpl> TLII( 570 createTLII(TargetTriple, CodeGenOpts)); 571 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII)); 572 573 // Normal mode, emit a .s or .o file by running the code generator. Note, 574 // this also adds codegenerator level optimization passes. 575 CodeGenFileType CGFT = getCodeGenFileType(Action); 576 577 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 578 // "codegen" passes so that it isn't run multiple times when there is 579 // inlining happening. 580 if (CodeGenOpts.OptimizationLevel > 0) 581 CodeGenPasses.add(createObjCARCContractPass()); 582 583 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT, 584 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 585 Diags.Report(diag::err_fe_unable_to_interface_with_target); 586 return false; 587 } 588 589 return true; 590 } 591 592 static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) { 593 switch (Opts.OptimizationLevel) { 594 default: 595 llvm_unreachable("Invalid optimization level!"); 596 597 case 0: 598 return OptimizationLevel::O0; 599 600 case 1: 601 return OptimizationLevel::O1; 602 603 case 2: 604 switch (Opts.OptimizeSize) { 605 default: 606 llvm_unreachable("Invalid optimization level for size!"); 607 608 case 0: 609 return OptimizationLevel::O2; 610 611 case 1: 612 return OptimizationLevel::Os; 613 614 case 2: 615 return OptimizationLevel::Oz; 616 } 617 618 case 3: 619 return OptimizationLevel::O3; 620 } 621 } 622 623 static void addSanitizers(const Triple &TargetTriple, 624 const CodeGenOptions &CodeGenOpts, 625 const LangOptions &LangOpts, PassBuilder &PB) { 626 PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM, 627 OptimizationLevel Level) { 628 if (CodeGenOpts.hasSanitizeCoverage()) { 629 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts); 630 MPM.addPass(ModuleSanitizerCoveragePass( 631 SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles, 632 CodeGenOpts.SanitizeCoverageIgnorelistFiles)); 633 } 634 635 auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) { 636 if (LangOpts.Sanitize.has(Mask)) { 637 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins; 638 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 639 640 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel, 641 CodeGenOpts.SanitizeMemoryParamRetval); 642 MPM.addPass(ModuleMemorySanitizerPass(options)); 643 FunctionPassManager FPM; 644 FPM.addPass(MemorySanitizerPass(options)); 645 if (Level != OptimizationLevel::O0) { 646 // MemorySanitizer inserts complex instrumentation that mostly 647 // follows the logic of the original code, but operates on 648 // "shadow" values. It can benefit from re-running some 649 // general purpose optimization passes. 650 FPM.addPass(EarlyCSEPass()); 651 // TODO: Consider add more passes like in 652 // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible 653 // difference on size. It's not clear if the rest is still 654 // usefull. InstCombinePass breakes 655 // compiler-rt/test/msan/select_origin.cpp. 656 } 657 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 658 } 659 }; 660 MSanPass(SanitizerKind::Memory, false); 661 MSanPass(SanitizerKind::KernelMemory, true); 662 663 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 664 MPM.addPass(ModuleThreadSanitizerPass()); 665 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); 666 } 667 668 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 669 if (LangOpts.Sanitize.has(Mask)) { 670 bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts); 671 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator; 672 llvm::AsanDtorKind DestructorKind = 673 CodeGenOpts.getSanitizeAddressDtor(); 674 AddressSanitizerOptions Opts; 675 Opts.CompileKernel = CompileKernel; 676 Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask); 677 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope; 678 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn(); 679 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 680 MPM.addPass(ModuleAddressSanitizerPass( 681 Opts, UseGlobalGC, UseOdrIndicator, DestructorKind)); 682 } 683 }; 684 ASanPass(SanitizerKind::Address, false); 685 ASanPass(SanitizerKind::KernelAddress, true); 686 687 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 688 if (LangOpts.Sanitize.has(Mask)) { 689 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 690 MPM.addPass(HWAddressSanitizerPass( 691 {CompileKernel, Recover, 692 /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0})); 693 } 694 }; 695 HWASanPass(SanitizerKind::HWAddress, false); 696 HWASanPass(SanitizerKind::KernelHWAddress, true); 697 698 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 699 MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles)); 700 } 701 }); 702 } 703 704 void EmitAssemblyHelper::RunOptimizationPipeline( 705 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS, 706 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS) { 707 Optional<PGOOptions> PGOOpt; 708 709 if (CodeGenOpts.hasProfileIRInstr()) 710 // -fprofile-generate. 711 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty() 712 ? getDefaultProfileGenName() 713 : CodeGenOpts.InstrProfileOutput, 714 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction, 715 CodeGenOpts.DebugInfoForProfiling); 716 else if (CodeGenOpts.hasProfileIRUse()) { 717 // -fprofile-use. 718 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse 719 : PGOOptions::NoCSAction; 720 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "", 721 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse, 722 CSAction, CodeGenOpts.DebugInfoForProfiling); 723 } else if (!CodeGenOpts.SampleProfileFile.empty()) 724 // -fprofile-sample-use 725 PGOOpt = PGOOptions( 726 CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile, 727 PGOOptions::SampleUse, PGOOptions::NoCSAction, 728 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling); 729 else if (CodeGenOpts.PseudoProbeForProfiling) 730 // -fpseudo-probe-for-profiling 731 PGOOpt = 732 PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction, 733 CodeGenOpts.DebugInfoForProfiling, true); 734 else if (CodeGenOpts.DebugInfoForProfiling) 735 // -fdebug-info-for-profiling 736 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction, 737 PGOOptions::NoCSAction, true); 738 739 // Check to see if we want to generate a CS profile. 740 if (CodeGenOpts.hasProfileCSIRInstr()) { 741 assert(!CodeGenOpts.hasProfileCSIRUse() && 742 "Cannot have both CSProfileUse pass and CSProfileGen pass at " 743 "the same time"); 744 if (PGOOpt.hasValue()) { 745 assert(PGOOpt->Action != PGOOptions::IRInstr && 746 PGOOpt->Action != PGOOptions::SampleUse && 747 "Cannot run CSProfileGen pass with ProfileGen or SampleUse " 748 " pass"); 749 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() 750 ? getDefaultProfileGenName() 751 : CodeGenOpts.InstrProfileOutput; 752 PGOOpt->CSAction = PGOOptions::CSIRInstr; 753 } else 754 PGOOpt = PGOOptions("", 755 CodeGenOpts.InstrProfileOutput.empty() 756 ? getDefaultProfileGenName() 757 : CodeGenOpts.InstrProfileOutput, 758 "", PGOOptions::NoAction, PGOOptions::CSIRInstr, 759 CodeGenOpts.DebugInfoForProfiling); 760 } 761 if (TM) 762 TM->setPGOOption(PGOOpt); 763 764 PipelineTuningOptions PTO; 765 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops; 766 // For historical reasons, loop interleaving is set to mirror setting for loop 767 // unrolling. 768 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops; 769 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop; 770 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP; 771 PTO.MergeFunctions = CodeGenOpts.MergeFunctions; 772 // Only enable CGProfilePass when using integrated assembler, since 773 // non-integrated assemblers don't recognize .cgprofile section. 774 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS; 775 776 LoopAnalysisManager LAM; 777 FunctionAnalysisManager FAM; 778 CGSCCAnalysisManager CGAM; 779 ModuleAnalysisManager MAM; 780 781 bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure"; 782 PassInstrumentationCallbacks PIC; 783 PrintPassOptions PrintPassOpts; 784 PrintPassOpts.Indent = DebugPassStructure; 785 PrintPassOpts.SkipAnalyses = DebugPassStructure; 786 StandardInstrumentations SI(CodeGenOpts.DebugPassManager || 787 DebugPassStructure, 788 /*VerifyEach*/ false, PrintPassOpts); 789 SI.registerCallbacks(PIC, &FAM); 790 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC); 791 792 // Attempt to load pass plugins and register their callbacks with PB. 793 for (auto &PluginFN : CodeGenOpts.PassPlugins) { 794 auto PassPlugin = PassPlugin::Load(PluginFN); 795 if (PassPlugin) { 796 PassPlugin->registerPassBuilderCallbacks(PB); 797 } else { 798 Diags.Report(diag::err_fe_unable_to_load_plugin) 799 << PluginFN << toString(PassPlugin.takeError()); 800 } 801 } 802 #define HANDLE_EXTENSION(Ext) \ 803 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB); 804 #include "llvm/Support/Extension.def" 805 806 // Register the target library analysis directly and give it a customized 807 // preset TLI. 808 std::unique_ptr<TargetLibraryInfoImpl> TLII( 809 createTLII(TargetTriple, CodeGenOpts)); 810 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); 811 812 // Register all the basic analyses with the managers. 813 PB.registerModuleAnalyses(MAM); 814 PB.registerCGSCCAnalyses(CGAM); 815 PB.registerFunctionAnalyses(FAM); 816 PB.registerLoopAnalyses(LAM); 817 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 818 819 ModulePassManager MPM; 820 821 if (!CodeGenOpts.DisableLLVMPasses) { 822 // Map our optimization levels into one of the distinct levels used to 823 // configure the pipeline. 824 OptimizationLevel Level = mapToLevel(CodeGenOpts); 825 826 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO; 827 bool IsLTO = CodeGenOpts.PrepareForLTO; 828 829 if (LangOpts.ObjCAutoRefCount) { 830 PB.registerPipelineStartEPCallback( 831 [](ModulePassManager &MPM, OptimizationLevel Level) { 832 if (Level != OptimizationLevel::O0) 833 MPM.addPass( 834 createModuleToFunctionPassAdaptor(ObjCARCExpandPass())); 835 }); 836 PB.registerPipelineEarlySimplificationEPCallback( 837 [](ModulePassManager &MPM, OptimizationLevel Level) { 838 if (Level != OptimizationLevel::O0) 839 MPM.addPass(ObjCARCAPElimPass()); 840 }); 841 PB.registerScalarOptimizerLateEPCallback( 842 [](FunctionPassManager &FPM, OptimizationLevel Level) { 843 if (Level != OptimizationLevel::O0) 844 FPM.addPass(ObjCARCOptPass()); 845 }); 846 } 847 848 // If we reached here with a non-empty index file name, then the index 849 // file was empty and we are not performing ThinLTO backend compilation 850 // (used in testing in a distributed build environment). 851 bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty(); 852 // If so drop any the type test assume sequences inserted for whole program 853 // vtables so that codegen doesn't complain. 854 if (IsThinLTOPostLink) 855 PB.registerPipelineStartEPCallback( 856 [](ModulePassManager &MPM, OptimizationLevel Level) { 857 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, 858 /*ImportSummary=*/nullptr, 859 /*DropTypeTests=*/true)); 860 }); 861 862 if (CodeGenOpts.InstrumentFunctions || 863 CodeGenOpts.InstrumentFunctionEntryBare || 864 CodeGenOpts.InstrumentFunctionsAfterInlining || 865 CodeGenOpts.InstrumentForProfiling) { 866 PB.registerPipelineStartEPCallback( 867 [](ModulePassManager &MPM, OptimizationLevel Level) { 868 MPM.addPass(createModuleToFunctionPassAdaptor( 869 EntryExitInstrumenterPass(/*PostInlining=*/false))); 870 }); 871 PB.registerOptimizerLastEPCallback( 872 [](ModulePassManager &MPM, OptimizationLevel Level) { 873 MPM.addPass(createModuleToFunctionPassAdaptor( 874 EntryExitInstrumenterPass(/*PostInlining=*/true))); 875 }); 876 } 877 878 // Register callbacks to schedule sanitizer passes at the appropriate part 879 // of the pipeline. 880 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) 881 PB.registerScalarOptimizerLateEPCallback( 882 [](FunctionPassManager &FPM, OptimizationLevel Level) { 883 FPM.addPass(BoundsCheckingPass()); 884 }); 885 886 // Don't add sanitizers if we are here from ThinLTO PostLink. That already 887 // done on PreLink stage. 888 if (!IsThinLTOPostLink) 889 addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB); 890 891 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) 892 PB.registerPipelineStartEPCallback( 893 [Options](ModulePassManager &MPM, OptimizationLevel Level) { 894 MPM.addPass(GCOVProfilerPass(*Options)); 895 }); 896 if (Optional<InstrProfOptions> Options = 897 getInstrProfOptions(CodeGenOpts, LangOpts)) 898 PB.registerPipelineStartEPCallback( 899 [Options](ModulePassManager &MPM, OptimizationLevel Level) { 900 MPM.addPass(InstrProfiling(*Options, false)); 901 }); 902 903 if (CodeGenOpts.OptimizationLevel == 0) { 904 MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO); 905 } else if (IsThinLTO) { 906 MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level); 907 } else if (IsLTO) { 908 MPM = PB.buildLTOPreLinkDefaultPipeline(Level); 909 } else { 910 MPM = PB.buildPerModuleDefaultPipeline(Level); 911 } 912 913 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 914 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass())); 915 MPM.addPass(ModuleMemProfilerPass()); 916 } 917 } 918 919 // Add a verifier pass if requested. We don't have to do this if the action 920 // requires code generation because there will already be a verifier pass in 921 // the code-generation pipeline. 922 if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule) 923 MPM.addPass(VerifierPass()); 924 925 switch (Action) { 926 case Backend_EmitBC: 927 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 928 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 929 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 930 if (!ThinLinkOS) 931 return; 932 } 933 if (!TheModule->getModuleFlag("EnableSplitLTOUnit")) 934 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 935 CodeGenOpts.EnableSplitLTOUnit); 936 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os() 937 : nullptr)); 938 } else { 939 // Emit a module summary by default for Regular LTO except for ld64 940 // targets 941 bool EmitLTOSummary = shouldEmitRegularLTOSummary(); 942 if (EmitLTOSummary) { 943 if (!TheModule->getModuleFlag("ThinLTO")) 944 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 945 if (!TheModule->getModuleFlag("EnableSplitLTOUnit")) 946 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 947 uint32_t(1)); 948 } 949 MPM.addPass( 950 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); 951 } 952 break; 953 954 case Backend_EmitLL: 955 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 956 break; 957 958 default: 959 break; 960 } 961 962 // Now that we have all of the passes ready, run them. 963 { 964 PrettyStackTraceString CrashInfo("Optimizer"); 965 llvm::TimeTraceScope TimeScope("Optimizer"); 966 MPM.run(*TheModule, MAM); 967 } 968 } 969 970 void EmitAssemblyHelper::RunCodegenPipeline( 971 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS, 972 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) { 973 // We still use the legacy PM to run the codegen pipeline since the new PM 974 // does not work with the codegen pipeline. 975 // FIXME: make the new PM work with the codegen pipeline. 976 legacy::PassManager CodeGenPasses; 977 978 // Append any output we need to the pass manager. 979 switch (Action) { 980 case Backend_EmitAssembly: 981 case Backend_EmitMCNull: 982 case Backend_EmitObj: 983 CodeGenPasses.add( 984 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 985 if (!CodeGenOpts.SplitDwarfOutput.empty()) { 986 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); 987 if (!DwoOS) 988 return; 989 } 990 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 991 DwoOS ? &DwoOS->os() : nullptr)) 992 // FIXME: Should we handle this error differently? 993 return; 994 break; 995 default: 996 return; 997 } 998 999 { 1000 PrettyStackTraceString CrashInfo("Code generation"); 1001 llvm::TimeTraceScope TimeScope("CodeGenPasses"); 1002 CodeGenPasses.run(*TheModule); 1003 } 1004 } 1005 1006 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 1007 std::unique_ptr<raw_pwrite_stream> OS) { 1008 TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr); 1009 setCommandLineOpts(CodeGenOpts); 1010 1011 bool RequiresCodeGen = actionRequiresCodeGen(Action); 1012 CreateTargetMachine(RequiresCodeGen); 1013 1014 if (RequiresCodeGen && !TM) 1015 return; 1016 if (TM) 1017 TheModule->setDataLayout(TM->createDataLayout()); 1018 1019 // Before executing passes, print the final values of the LLVM options. 1020 cl::PrintOptionValues(); 1021 1022 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 1023 RunOptimizationPipeline(Action, OS, ThinLinkOS); 1024 RunCodegenPipeline(Action, OS, DwoOS); 1025 1026 if (ThinLinkOS) 1027 ThinLinkOS->keep(); 1028 if (DwoOS) 1029 DwoOS->keep(); 1030 } 1031 1032 static void runThinLTOBackend( 1033 DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M, 1034 const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts, 1035 const clang::TargetOptions &TOpts, const LangOptions &LOpts, 1036 std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile, 1037 std::string ProfileRemapping, BackendAction Action) { 1038 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>> 1039 ModuleToDefinedGVSummaries; 1040 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 1041 1042 setCommandLineOpts(CGOpts); 1043 1044 // We can simply import the values mentioned in the combined index, since 1045 // we should only invoke this using the individual indexes written out 1046 // via a WriteIndexesThinBackend. 1047 FunctionImporter::ImportMapTy ImportList; 1048 if (!lto::initImportList(*M, *CombinedIndex, ImportList)) 1049 return; 1050 1051 auto AddStream = [&](size_t Task) { 1052 return std::make_unique<CachedFileStream>(std::move(OS), 1053 CGOpts.ObjectFilenameForDebug); 1054 }; 1055 lto::Config Conf; 1056 if (CGOpts.SaveTempsFilePrefix != "") { 1057 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".", 1058 /* UseInputModulePath */ false)) { 1059 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1060 errs() << "Error setting up ThinLTO save-temps: " << EIB.message() 1061 << '\n'; 1062 }); 1063 } 1064 } 1065 Conf.CPU = TOpts.CPU; 1066 Conf.CodeModel = getCodeModel(CGOpts); 1067 Conf.MAttrs = TOpts.Features; 1068 Conf.RelocModel = CGOpts.RelocationModel; 1069 Conf.CGOptLevel = getCGOptLevel(CGOpts); 1070 Conf.OptLevel = CGOpts.OptimizationLevel; 1071 initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts); 1072 Conf.SampleProfile = std::move(SampleProfile); 1073 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops; 1074 // For historical reasons, loop interleaving is set to mirror setting for loop 1075 // unrolling. 1076 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops; 1077 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop; 1078 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP; 1079 // Only enable CGProfilePass when using integrated assembler, since 1080 // non-integrated assemblers don't recognize .cgprofile section. 1081 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS; 1082 1083 // Context sensitive profile. 1084 if (CGOpts.hasProfileCSIRInstr()) { 1085 Conf.RunCSIRInstr = true; 1086 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput); 1087 } else if (CGOpts.hasProfileCSIRUse()) { 1088 Conf.RunCSIRInstr = false; 1089 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath); 1090 } 1091 1092 Conf.ProfileRemapping = std::move(ProfileRemapping); 1093 Conf.DebugPassManager = CGOpts.DebugPassManager; 1094 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness; 1095 Conf.RemarksFilename = CGOpts.OptRecordFile; 1096 Conf.RemarksPasses = CGOpts.OptRecordPasses; 1097 Conf.RemarksFormat = CGOpts.OptRecordFormat; 1098 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile; 1099 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput; 1100 switch (Action) { 1101 case Backend_EmitNothing: 1102 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) { 1103 return false; 1104 }; 1105 break; 1106 case Backend_EmitLL: 1107 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1108 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists); 1109 return false; 1110 }; 1111 break; 1112 case Backend_EmitBC: 1113 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1114 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists); 1115 return false; 1116 }; 1117 break; 1118 default: 1119 Conf.CGFileType = getCodeGenFileType(Action); 1120 break; 1121 } 1122 if (Error E = 1123 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList, 1124 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], 1125 /* ModuleMap */ nullptr, CGOpts.CmdArgs)) { 1126 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1127 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; 1128 }); 1129 } 1130 } 1131 1132 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 1133 const HeaderSearchOptions &HeaderOpts, 1134 const CodeGenOptions &CGOpts, 1135 const clang::TargetOptions &TOpts, 1136 const LangOptions &LOpts, 1137 StringRef TDesc, Module *M, 1138 BackendAction Action, 1139 std::unique_ptr<raw_pwrite_stream> OS) { 1140 1141 llvm::TimeTraceScope TimeScope("Backend"); 1142 1143 std::unique_ptr<llvm::Module> EmptyModule; 1144 if (!CGOpts.ThinLTOIndexFile.empty()) { 1145 // If we are performing a ThinLTO importing compile, load the function index 1146 // into memory and pass it into runThinLTOBackend, which will run the 1147 // function importer and invoke LTO passes. 1148 std::unique_ptr<ModuleSummaryIndex> CombinedIndex; 1149 if (Error E = llvm::getModuleSummaryIndexForFile( 1150 CGOpts.ThinLTOIndexFile, 1151 /*IgnoreEmptyThinLTOIndexFile*/ true) 1152 .moveInto(CombinedIndex)) { 1153 logAllUnhandledErrors(std::move(E), errs(), 1154 "Error loading index file '" + 1155 CGOpts.ThinLTOIndexFile + "': "); 1156 return; 1157 } 1158 1159 // A null CombinedIndex means we should skip ThinLTO compilation 1160 // (LLVM will optionally ignore empty index files, returning null instead 1161 // of an error). 1162 if (CombinedIndex) { 1163 if (!CombinedIndex->skipModuleByDistributedBackend()) { 1164 runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts, 1165 TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile, 1166 CGOpts.ProfileRemappingFile, Action); 1167 return; 1168 } 1169 // Distributed indexing detected that nothing from the module is needed 1170 // for the final linking. So we can skip the compilation. We sill need to 1171 // output an empty object file to make sure that a linker does not fail 1172 // trying to read it. Also for some features, like CFI, we must skip 1173 // the compilation as CombinedIndex does not contain all required 1174 // information. 1175 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext()); 1176 EmptyModule->setTargetTriple(M->getTargetTriple()); 1177 M = EmptyModule.get(); 1178 } 1179 } 1180 1181 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M); 1182 AsmHelper.EmitAssembly(Action, std::move(OS)); 1183 1184 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 1185 // DataLayout. 1186 if (AsmHelper.TM) { 1187 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 1188 if (DLDesc != TDesc) { 1189 unsigned DiagID = Diags.getCustomDiagID( 1190 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 1191 "expected target description '%1'"); 1192 Diags.Report(DiagID) << DLDesc << TDesc; 1193 } 1194 } 1195 } 1196 1197 // With -fembed-bitcode, save a copy of the llvm IR as data in the 1198 // __LLVM,__bitcode section. 1199 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 1200 llvm::MemoryBufferRef Buf) { 1201 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 1202 return; 1203 llvm::embedBitcodeInModule( 1204 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker, 1205 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode, 1206 CGOpts.CmdArgs); 1207 } 1208 1209 void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, 1210 DiagnosticsEngine &Diags) { 1211 if (CGOpts.OffloadObjects.empty()) 1212 return; 1213 1214 for (StringRef OffloadObject : CGOpts.OffloadObjects) { 1215 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr = 1216 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject); 1217 if (std::error_code EC = ObjectOrErr.getError()) { 1218 auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1219 "could not open '%0' for embedding"); 1220 Diags.Report(DiagID) << OffloadObject; 1221 return; 1222 } 1223 1224 llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading", 1225 Align(object::OffloadBinary::getAlignment())); 1226 } 1227 } 1228