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