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