xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/CommandFlags.cpp (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
1 //===-- CommandFlags.cpp - Command Line Flags Interface ---------*- C++ -*-===//
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 // This file contains codegen-specific flags that are shared between different
10 // command line tools. The tools "llc" and "opt" both use this file to prevent
11 // flag duplication.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/CommandFlags.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/TargetParser/Host.h"
24 #include "llvm/TargetParser/SubtargetFeature.h"
25 #include "llvm/TargetParser/Triple.h"
26 #include <optional>
27 
28 using namespace llvm;
29 
30 #define CGOPT(TY, NAME)                                                        \
31   static cl::opt<TY> *NAME##View;                                              \
32   TY codegen::get##NAME() {                                                    \
33     assert(NAME##View && "RegisterCodeGenFlags not created.");                 \
34     return *NAME##View;                                                        \
35   }
36 
37 #define CGLIST(TY, NAME)                                                       \
38   static cl::list<TY> *NAME##View;                                             \
39   std::vector<TY> codegen::get##NAME() {                                       \
40     assert(NAME##View && "RegisterCodeGenFlags not created.");                 \
41     return *NAME##View;                                                        \
42   }
43 
44 // Temporary macro for incremental transition to std::optional.
45 #define CGOPT_EXP(TY, NAME)                                                    \
46   CGOPT(TY, NAME)                                                              \
47   std::optional<TY> codegen::getExplicit##NAME() {                             \
48     if (NAME##View->getNumOccurrences()) {                                     \
49       TY res = *NAME##View;                                                    \
50       return res;                                                              \
51     }                                                                          \
52     return std::nullopt;                                                       \
53   }
54 
55 CGOPT(std::string, MArch)
56 CGOPT(std::string, MCPU)
57 CGLIST(std::string, MAttrs)
58 CGOPT_EXP(Reloc::Model, RelocModel)
59 CGOPT(ThreadModel::Model, ThreadModel)
60 CGOPT_EXP(CodeModel::Model, CodeModel)
61 CGOPT(ExceptionHandling, ExceptionModel)
62 CGOPT_EXP(CodeGenFileType, FileType)
63 CGOPT(FramePointerKind, FramePointerUsage)
64 CGOPT(bool, EnableUnsafeFPMath)
65 CGOPT(bool, EnableNoInfsFPMath)
66 CGOPT(bool, EnableNoNaNsFPMath)
67 CGOPT(bool, EnableNoSignedZerosFPMath)
68 CGOPT(bool, EnableApproxFuncFPMath)
69 CGOPT(bool, EnableNoTrappingFPMath)
70 CGOPT(bool, EnableAIXExtendedAltivecABI)
71 CGOPT(DenormalMode::DenormalModeKind, DenormalFPMath)
72 CGOPT(DenormalMode::DenormalModeKind, DenormalFP32Math)
73 CGOPT(bool, EnableHonorSignDependentRoundingFPMath)
74 CGOPT(FloatABI::ABIType, FloatABIForCalls)
75 CGOPT(FPOpFusion::FPOpFusionMode, FuseFPOps)
76 CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
77 CGOPT(bool, DontPlaceZerosInBSS)
78 CGOPT(bool, EnableGuaranteedTailCallOpt)
79 CGOPT(bool, DisableTailCalls)
80 CGOPT(bool, StackSymbolOrdering)
81 CGOPT(bool, StackRealign)
82 CGOPT(std::string, TrapFuncName)
83 CGOPT(bool, UseCtors)
84 CGOPT(bool, DisableIntegratedAS)
85 CGOPT(bool, RelaxELFRelocations)
86 CGOPT_EXP(bool, DataSections)
87 CGOPT_EXP(bool, FunctionSections)
88 CGOPT(bool, IgnoreXCOFFVisibility)
89 CGOPT(bool, XCOFFTracebackTable)
90 CGOPT(std::string, BBSections)
91 CGOPT(unsigned, TLSSize)
92 CGOPT_EXP(bool, EmulatedTLS)
93 CGOPT(bool, UniqueSectionNames)
94 CGOPT(bool, UniqueBasicBlockSectionNames)
95 CGOPT(EABI, EABIVersion)
96 CGOPT(DebuggerKind, DebuggerTuningOpt)
97 CGOPT(bool, EnableStackSizeSection)
98 CGOPT(bool, EnableAddrsig)
99 CGOPT(bool, EmitCallSiteInfo)
100 CGOPT(bool, EnableMachineFunctionSplitter)
101 CGOPT(bool, EnableDebugEntryValues)
102 CGOPT(bool, ForceDwarfFrameSection)
103 CGOPT(bool, XRayFunctionIndex)
104 CGOPT(bool, DebugStrictDwarf)
105 CGOPT(unsigned, AlignLoops)
106 CGOPT(bool, JMCInstrument)
107 CGOPT(bool, XCOFFReadOnlyPointers)
108 
109 codegen::RegisterCodeGenFlags::RegisterCodeGenFlags() {
110 #define CGBINDOPT(NAME)                                                        \
111   do {                                                                         \
112     NAME##View = std::addressof(NAME);                                         \
113   } while (0)
114 
115   static cl::opt<std::string> MArch(
116       "march", cl::desc("Architecture to generate code for (see --version)"));
117   CGBINDOPT(MArch);
118 
119   static cl::opt<std::string> MCPU(
120       "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
121       cl::value_desc("cpu-name"), cl::init(""));
122   CGBINDOPT(MCPU);
123 
124   static cl::list<std::string> MAttrs(
125       "mattr", cl::CommaSeparated,
126       cl::desc("Target specific attributes (-mattr=help for details)"),
127       cl::value_desc("a1,+a2,-a3,..."));
128   CGBINDOPT(MAttrs);
129 
130   static cl::opt<Reloc::Model> RelocModel(
131       "relocation-model", cl::desc("Choose relocation model"),
132       cl::values(
133           clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
134           clEnumValN(Reloc::PIC_, "pic",
135                      "Fully relocatable, position independent code"),
136           clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
137                      "Relocatable external references, non-relocatable code"),
138           clEnumValN(
139               Reloc::ROPI, "ropi",
140               "Code and read-only data relocatable, accessed PC-relative"),
141           clEnumValN(
142               Reloc::RWPI, "rwpi",
143               "Read-write data relocatable, accessed relative to static base"),
144           clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
145                      "Combination of ropi and rwpi")));
146   CGBINDOPT(RelocModel);
147 
148   static cl::opt<ThreadModel::Model> ThreadModel(
149       "thread-model", cl::desc("Choose threading model"),
150       cl::init(ThreadModel::POSIX),
151       cl::values(
152           clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"),
153           clEnumValN(ThreadModel::Single, "single", "Single thread model")));
154   CGBINDOPT(ThreadModel);
155 
156   static cl::opt<CodeModel::Model> CodeModel(
157       "code-model", cl::desc("Choose code model"),
158       cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
159                  clEnumValN(CodeModel::Small, "small", "Small code model"),
160                  clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
161                  clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
162                  clEnumValN(CodeModel::Large, "large", "Large code model")));
163   CGBINDOPT(CodeModel);
164 
165   static cl::opt<ExceptionHandling> ExceptionModel(
166       "exception-model", cl::desc("exception model"),
167       cl::init(ExceptionHandling::None),
168       cl::values(
169           clEnumValN(ExceptionHandling::None, "default",
170                      "default exception handling model"),
171           clEnumValN(ExceptionHandling::DwarfCFI, "dwarf",
172                      "DWARF-like CFI based exception handling"),
173           clEnumValN(ExceptionHandling::SjLj, "sjlj",
174                      "SjLj exception handling"),
175           clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
176           clEnumValN(ExceptionHandling::WinEH, "wineh",
177                      "Windows exception model"),
178           clEnumValN(ExceptionHandling::Wasm, "wasm",
179                      "WebAssembly exception handling")));
180   CGBINDOPT(ExceptionModel);
181 
182   static cl::opt<CodeGenFileType> FileType(
183       "filetype", cl::init(CGFT_AssemblyFile),
184       cl::desc(
185           "Choose a file type (not all types are supported by all targets):"),
186       cl::values(
187           clEnumValN(CGFT_AssemblyFile, "asm", "Emit an assembly ('.s') file"),
188           clEnumValN(CGFT_ObjectFile, "obj",
189                      "Emit a native object ('.o') file"),
190           clEnumValN(CGFT_Null, "null",
191                      "Emit nothing, for performance testing")));
192   CGBINDOPT(FileType);
193 
194   static cl::opt<FramePointerKind> FramePointerUsage(
195       "frame-pointer",
196       cl::desc("Specify frame pointer elimination optimization"),
197       cl::init(FramePointerKind::None),
198       cl::values(
199           clEnumValN(FramePointerKind::All, "all",
200                      "Disable frame pointer elimination"),
201           clEnumValN(FramePointerKind::NonLeaf, "non-leaf",
202                      "Disable frame pointer elimination for non-leaf frame"),
203           clEnumValN(FramePointerKind::None, "none",
204                      "Enable frame pointer elimination")));
205   CGBINDOPT(FramePointerUsage);
206 
207   static cl::opt<bool> EnableUnsafeFPMath(
208       "enable-unsafe-fp-math",
209       cl::desc("Enable optimizations that may decrease FP precision"),
210       cl::init(false));
211   CGBINDOPT(EnableUnsafeFPMath);
212 
213   static cl::opt<bool> EnableNoInfsFPMath(
214       "enable-no-infs-fp-math",
215       cl::desc("Enable FP math optimizations that assume no +-Infs"),
216       cl::init(false));
217   CGBINDOPT(EnableNoInfsFPMath);
218 
219   static cl::opt<bool> EnableNoNaNsFPMath(
220       "enable-no-nans-fp-math",
221       cl::desc("Enable FP math optimizations that assume no NaNs"),
222       cl::init(false));
223   CGBINDOPT(EnableNoNaNsFPMath);
224 
225   static cl::opt<bool> EnableNoSignedZerosFPMath(
226       "enable-no-signed-zeros-fp-math",
227       cl::desc("Enable FP math optimizations that assume "
228                "the sign of 0 is insignificant"),
229       cl::init(false));
230   CGBINDOPT(EnableNoSignedZerosFPMath);
231 
232   static cl::opt<bool> EnableApproxFuncFPMath(
233       "enable-approx-func-fp-math",
234       cl::desc("Enable FP math optimizations that assume approx func"),
235       cl::init(false));
236   CGBINDOPT(EnableApproxFuncFPMath);
237 
238   static cl::opt<bool> EnableNoTrappingFPMath(
239       "enable-no-trapping-fp-math",
240       cl::desc("Enable setting the FP exceptions build "
241                "attribute not to use exceptions"),
242       cl::init(false));
243   CGBINDOPT(EnableNoTrappingFPMath);
244 
245   static const auto DenormFlagEnumOptions = cl::values(
246       clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
247       clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
248                  "the sign of a  flushed-to-zero number is preserved "
249                  "in the sign of 0"),
250       clEnumValN(DenormalMode::PositiveZero, "positive-zero",
251                  "denormals are flushed to positive zero"),
252       clEnumValN(DenormalMode::Dynamic, "dynamic",
253                  "denormals have unknown treatment"));
254 
255   // FIXME: Doesn't have way to specify separate input and output modes.
256   static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
257     "denormal-fp-math",
258     cl::desc("Select which denormal numbers the code is permitted to require"),
259     cl::init(DenormalMode::IEEE),
260     DenormFlagEnumOptions);
261   CGBINDOPT(DenormalFPMath);
262 
263   static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
264     "denormal-fp-math-f32",
265     cl::desc("Select which denormal numbers the code is permitted to require for float"),
266     cl::init(DenormalMode::Invalid),
267     DenormFlagEnumOptions);
268   CGBINDOPT(DenormalFP32Math);
269 
270   static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(
271       "enable-sign-dependent-rounding-fp-math", cl::Hidden,
272       cl::desc("Force codegen to assume rounding mode can change dynamically"),
273       cl::init(false));
274   CGBINDOPT(EnableHonorSignDependentRoundingFPMath);
275 
276   static cl::opt<FloatABI::ABIType> FloatABIForCalls(
277       "float-abi", cl::desc("Choose float ABI type"),
278       cl::init(FloatABI::Default),
279       cl::values(clEnumValN(FloatABI::Default, "default",
280                             "Target default float ABI type"),
281                  clEnumValN(FloatABI::Soft, "soft",
282                             "Soft float ABI (implied by -soft-float)"),
283                  clEnumValN(FloatABI::Hard, "hard",
284                             "Hard float ABI (uses FP registers)")));
285   CGBINDOPT(FloatABIForCalls);
286 
287   static cl::opt<FPOpFusion::FPOpFusionMode> FuseFPOps(
288       "fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),
289       cl::init(FPOpFusion::Standard),
290       cl::values(
291           clEnumValN(FPOpFusion::Fast, "fast",
292                      "Fuse FP ops whenever profitable"),
293           clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),
294           clEnumValN(FPOpFusion::Strict, "off",
295                      "Only fuse FP ops when the result won't be affected.")));
296   CGBINDOPT(FuseFPOps);
297 
298   static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
299       "swift-async-fp",
300       cl::desc("Determine when the Swift async frame pointer should be set"),
301       cl::init(SwiftAsyncFramePointerMode::Always),
302       cl::values(clEnumValN(SwiftAsyncFramePointerMode::DeploymentBased, "auto",
303                             "Determine based on deployment target"),
304                  clEnumValN(SwiftAsyncFramePointerMode::Always, "always",
305                             "Always set the bit"),
306                  clEnumValN(SwiftAsyncFramePointerMode::Never, "never",
307                             "Never set the bit")));
308   CGBINDOPT(SwiftAsyncFramePointer);
309 
310   static cl::opt<bool> DontPlaceZerosInBSS(
311       "nozero-initialized-in-bss",
312       cl::desc("Don't place zero-initialized symbols into bss section"),
313       cl::init(false));
314   CGBINDOPT(DontPlaceZerosInBSS);
315 
316   static cl::opt<bool> EnableAIXExtendedAltivecABI(
317       "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
318       cl::init(false));
319   CGBINDOPT(EnableAIXExtendedAltivecABI);
320 
321   static cl::opt<bool> EnableGuaranteedTailCallOpt(
322       "tailcallopt",
323       cl::desc(
324           "Turn fastcc calls into tail calls by (potentially) changing ABI."),
325       cl::init(false));
326   CGBINDOPT(EnableGuaranteedTailCallOpt);
327 
328   static cl::opt<bool> DisableTailCalls(
329       "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
330   CGBINDOPT(DisableTailCalls);
331 
332   static cl::opt<bool> StackSymbolOrdering(
333       "stack-symbol-ordering", cl::desc("Order local stack symbols."),
334       cl::init(true));
335   CGBINDOPT(StackSymbolOrdering);
336 
337   static cl::opt<bool> StackRealign(
338       "stackrealign",
339       cl::desc("Force align the stack to the minimum alignment"),
340       cl::init(false));
341   CGBINDOPT(StackRealign);
342 
343   static cl::opt<std::string> TrapFuncName(
344       "trap-func", cl::Hidden,
345       cl::desc("Emit a call to trap function rather than a trap instruction"),
346       cl::init(""));
347   CGBINDOPT(TrapFuncName);
348 
349   static cl::opt<bool> UseCtors("use-ctors",
350                                 cl::desc("Use .ctors instead of .init_array."),
351                                 cl::init(false));
352   CGBINDOPT(UseCtors);
353 
354   static cl::opt<bool> RelaxELFRelocations(
355       "relax-elf-relocations",
356       cl::desc(
357           "Emit GOTPCRELX/REX_GOTPCRELX instead of GOTPCREL on x86-64 ELF"),
358       cl::init(true));
359   CGBINDOPT(RelaxELFRelocations);
360 
361   static cl::opt<bool> DataSections(
362       "data-sections", cl::desc("Emit data into separate sections"),
363       cl::init(false));
364   CGBINDOPT(DataSections);
365 
366   static cl::opt<bool> FunctionSections(
367       "function-sections", cl::desc("Emit functions into separate sections"),
368       cl::init(false));
369   CGBINDOPT(FunctionSections);
370 
371   static cl::opt<bool> IgnoreXCOFFVisibility(
372       "ignore-xcoff-visibility",
373       cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
374                "all symbols 'unspecified' visibility in XCOFF object file"),
375       cl::init(false));
376   CGBINDOPT(IgnoreXCOFFVisibility);
377 
378   static cl::opt<bool> XCOFFTracebackTable(
379       "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
380       cl::init(true));
381   CGBINDOPT(XCOFFTracebackTable);
382 
383   static cl::opt<std::string> BBSections(
384       "basic-block-sections",
385       cl::desc("Emit basic blocks into separate sections"),
386       cl::value_desc("all | <function list (file)> | labels | none"),
387       cl::init("none"));
388   CGBINDOPT(BBSections);
389 
390   static cl::opt<unsigned> TLSSize(
391       "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
392   CGBINDOPT(TLSSize);
393 
394   static cl::opt<bool> EmulatedTLS(
395       "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
396   CGBINDOPT(EmulatedTLS);
397 
398   static cl::opt<bool> UniqueSectionNames(
399       "unique-section-names", cl::desc("Give unique names to every section"),
400       cl::init(true));
401   CGBINDOPT(UniqueSectionNames);
402 
403   static cl::opt<bool> UniqueBasicBlockSectionNames(
404       "unique-basic-block-section-names",
405       cl::desc("Give unique names to every basic block section"),
406       cl::init(false));
407   CGBINDOPT(UniqueBasicBlockSectionNames);
408 
409   static cl::opt<EABI> EABIVersion(
410       "meabi", cl::desc("Set EABI type (default depends on triple):"),
411       cl::init(EABI::Default),
412       cl::values(
413           clEnumValN(EABI::Default, "default", "Triple default EABI version"),
414           clEnumValN(EABI::EABI4, "4", "EABI version 4"),
415           clEnumValN(EABI::EABI5, "5", "EABI version 5"),
416           clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
417   CGBINDOPT(EABIVersion);
418 
419   static cl::opt<DebuggerKind> DebuggerTuningOpt(
420       "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
421       cl::init(DebuggerKind::Default),
422       cl::values(
423           clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
424           clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
425           clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
426           clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
427   CGBINDOPT(DebuggerTuningOpt);
428 
429   static cl::opt<bool> EnableStackSizeSection(
430       "stack-size-section",
431       cl::desc("Emit a section containing stack size metadata"),
432       cl::init(false));
433   CGBINDOPT(EnableStackSizeSection);
434 
435   static cl::opt<bool> EnableAddrsig(
436       "addrsig", cl::desc("Emit an address-significance table"),
437       cl::init(false));
438   CGBINDOPT(EnableAddrsig);
439 
440   static cl::opt<bool> EmitCallSiteInfo(
441       "emit-call-site-info",
442       cl::desc(
443           "Emit call site debug information, if debug information is enabled."),
444       cl::init(false));
445   CGBINDOPT(EmitCallSiteInfo);
446 
447   static cl::opt<bool> EnableDebugEntryValues(
448       "debug-entry-values",
449       cl::desc("Enable debug info for the debug entry values."),
450       cl::init(false));
451   CGBINDOPT(EnableDebugEntryValues);
452 
453   static cl::opt<bool> EnableMachineFunctionSplitter(
454       "split-machine-functions",
455       cl::desc("Split out cold basic blocks from machine functions based on "
456                "profile information"),
457       cl::init(false));
458   CGBINDOPT(EnableMachineFunctionSplitter);
459 
460   static cl::opt<bool> ForceDwarfFrameSection(
461       "force-dwarf-frame-section",
462       cl::desc("Always emit a debug frame section."), cl::init(false));
463   CGBINDOPT(ForceDwarfFrameSection);
464 
465   static cl::opt<bool> XRayFunctionIndex("xray-function-index",
466                                          cl::desc("Emit xray_fn_idx section"),
467                                          cl::init(true));
468   CGBINDOPT(XRayFunctionIndex);
469 
470   static cl::opt<bool> DebugStrictDwarf(
471       "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
472   CGBINDOPT(DebugStrictDwarf);
473 
474   static cl::opt<unsigned> AlignLoops("align-loops",
475                                       cl::desc("Default alignment for loops"));
476   CGBINDOPT(AlignLoops);
477 
478   static cl::opt<bool> JMCInstrument(
479       "enable-jmc-instrument",
480       cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
481       cl::init(false));
482   CGBINDOPT(JMCInstrument);
483 
484   static cl::opt<bool> XCOFFReadOnlyPointers(
485       "mxcoff-roptr",
486       cl::desc("When set to true, const objects with relocatable address "
487                "values are put into the RO data section."),
488       cl::init(false));
489   CGBINDOPT(XCOFFReadOnlyPointers);
490 
491   static cl::opt<bool> DisableIntegratedAS(
492       "no-integrated-as", cl::desc("Disable integrated assembler"),
493       cl::init(false));
494   CGBINDOPT(DisableIntegratedAS);
495 
496 #undef CGBINDOPT
497 
498   mc::RegisterMCTargetOptionsFlags();
499 }
500 
501 llvm::BasicBlockSection
502 codegen::getBBSectionsMode(llvm::TargetOptions &Options) {
503   if (getBBSections() == "all")
504     return BasicBlockSection::All;
505   else if (getBBSections() == "labels")
506     return BasicBlockSection::Labels;
507   else if (getBBSections() == "none")
508     return BasicBlockSection::None;
509   else {
510     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
511         MemoryBuffer::getFile(getBBSections());
512     if (!MBOrErr) {
513       errs() << "Error loading basic block sections function list file: "
514              << MBOrErr.getError().message() << "\n";
515     } else {
516       Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
517     }
518     return BasicBlockSection::List;
519   }
520 }
521 
522 // Common utility function tightly tied to the options listed here. Initializes
523 // a TargetOptions object with CodeGen flags and returns it.
524 TargetOptions
525 codegen::InitTargetOptionsFromCodeGenFlags(const Triple &TheTriple) {
526   TargetOptions Options;
527   Options.AllowFPOpFusion = getFuseFPOps();
528   Options.UnsafeFPMath = getEnableUnsafeFPMath();
529   Options.NoInfsFPMath = getEnableNoInfsFPMath();
530   Options.NoNaNsFPMath = getEnableNoNaNsFPMath();
531   Options.NoSignedZerosFPMath = getEnableNoSignedZerosFPMath();
532   Options.ApproxFuncFPMath = getEnableApproxFuncFPMath();
533   Options.NoTrappingFPMath = getEnableNoTrappingFPMath();
534 
535   DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();
536 
537   // FIXME: Should have separate input and output flags
538   Options.setFPDenormalMode(DenormalMode(DenormKind, DenormKind));
539 
540   Options.HonorSignDependentRoundingFPMathOption =
541       getEnableHonorSignDependentRoundingFPMath();
542   if (getFloatABIForCalls() != FloatABI::Default)
543     Options.FloatABIType = getFloatABIForCalls();
544   Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
545   Options.NoZerosInBSS = getDontPlaceZerosInBSS();
546   Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
547   Options.StackSymbolOrdering = getStackSymbolOrdering();
548   Options.UseInitArray = !getUseCtors();
549   Options.DisableIntegratedAS = getDisableIntegratedAS();
550   Options.RelaxELFRelocations = getRelaxELFRelocations();
551   Options.DataSections =
552       getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
553   Options.FunctionSections = getFunctionSections();
554   Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
555   Options.XCOFFTracebackTable = getXCOFFTracebackTable();
556   Options.BBSections = getBBSectionsMode(Options);
557   Options.UniqueSectionNames = getUniqueSectionNames();
558   Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
559   Options.TLSSize = getTLSSize();
560   Options.EmulatedTLS =
561       getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
562   Options.ExceptionModel = getExceptionModel();
563   Options.EmitStackSizeSection = getEnableStackSizeSection();
564   Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
565   Options.EmitAddrsig = getEnableAddrsig();
566   Options.EmitCallSiteInfo = getEmitCallSiteInfo();
567   Options.EnableDebugEntryValues = getEnableDebugEntryValues();
568   Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
569   Options.XRayFunctionIndex = getXRayFunctionIndex();
570   Options.DebugStrictDwarf = getDebugStrictDwarf();
571   Options.LoopAlignment = getAlignLoops();
572   Options.JMCInstrument = getJMCInstrument();
573   Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
574 
575   Options.MCOptions = mc::InitMCTargetOptionsFromFlags();
576 
577   Options.ThreadModel = getThreadModel();
578   Options.EABIVersion = getEABIVersion();
579   Options.DebuggerTuning = getDebuggerTuningOpt();
580   Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
581   return Options;
582 }
583 
584 std::string codegen::getCPUStr() {
585   // If user asked for the 'native' CPU, autodetect here. If autodection fails,
586   // this will set the CPU to an empty string which tells the target to
587   // pick a basic default.
588   if (getMCPU() == "native")
589     return std::string(sys::getHostCPUName());
590 
591   return getMCPU();
592 }
593 
594 std::string codegen::getFeaturesStr() {
595   SubtargetFeatures Features;
596 
597   // If user asked for the 'native' CPU, we need to autodetect features.
598   // This is necessary for x86 where the CPU might not support all the
599   // features the autodetected CPU name lists in the target. For example,
600   // not all Sandybridge processors support AVX.
601   if (getMCPU() == "native") {
602     StringMap<bool> HostFeatures;
603     if (sys::getHostCPUFeatures(HostFeatures))
604       for (const auto &[Feature, IsEnabled] : HostFeatures)
605         Features.AddFeature(Feature, IsEnabled);
606   }
607 
608   for (auto const &MAttr : getMAttrs())
609     Features.AddFeature(MAttr);
610 
611   return Features.getString();
612 }
613 
614 std::vector<std::string> codegen::getFeatureList() {
615   SubtargetFeatures Features;
616 
617   // If user asked for the 'native' CPU, we need to autodetect features.
618   // This is necessary for x86 where the CPU might not support all the
619   // features the autodetected CPU name lists in the target. For example,
620   // not all Sandybridge processors support AVX.
621   if (getMCPU() == "native") {
622     StringMap<bool> HostFeatures;
623     if (sys::getHostCPUFeatures(HostFeatures))
624       for (const auto &[Feature, IsEnabled] : HostFeatures)
625         Features.AddFeature(Feature, IsEnabled);
626   }
627 
628   for (auto const &MAttr : getMAttrs())
629     Features.AddFeature(MAttr);
630 
631   return Features.getFeatures();
632 }
633 
634 void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
635   B.addAttribute(Name, Val ? "true" : "false");
636 }
637 
638 #define HANDLE_BOOL_ATTR(CL, AttrName)                                         \
639   do {                                                                         \
640     if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName))            \
641       renderBoolStringAttr(NewAttrs, AttrName, *CL);                           \
642   } while (0)
643 
644 /// Set function attributes of function \p F based on CPU, Features, and command
645 /// line flags.
646 void codegen::setFunctionAttributes(StringRef CPU, StringRef Features,
647                                     Function &F) {
648   auto &Ctx = F.getContext();
649   AttributeList Attrs = F.getAttributes();
650   AttrBuilder NewAttrs(Ctx);
651 
652   if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
653     NewAttrs.addAttribute("target-cpu", CPU);
654   if (!Features.empty()) {
655     // Append the command line features to any that are already on the function.
656     StringRef OldFeatures =
657         F.getFnAttribute("target-features").getValueAsString();
658     if (OldFeatures.empty())
659       NewAttrs.addAttribute("target-features", Features);
660     else {
661       SmallString<256> Appended(OldFeatures);
662       Appended.push_back(',');
663       Appended.append(Features);
664       NewAttrs.addAttribute("target-features", Appended);
665     }
666   }
667   if (FramePointerUsageView->getNumOccurrences() > 0 &&
668       !F.hasFnAttribute("frame-pointer")) {
669     if (getFramePointerUsage() == FramePointerKind::All)
670       NewAttrs.addAttribute("frame-pointer", "all");
671     else if (getFramePointerUsage() == FramePointerKind::NonLeaf)
672       NewAttrs.addAttribute("frame-pointer", "non-leaf");
673     else if (getFramePointerUsage() == FramePointerKind::None)
674       NewAttrs.addAttribute("frame-pointer", "none");
675   }
676   if (DisableTailCallsView->getNumOccurrences() > 0)
677     NewAttrs.addAttribute("disable-tail-calls",
678                           toStringRef(getDisableTailCalls()));
679   if (getStackRealign())
680     NewAttrs.addAttribute("stackrealign");
681 
682   HANDLE_BOOL_ATTR(EnableUnsafeFPMathView, "unsafe-fp-math");
683   HANDLE_BOOL_ATTR(EnableNoInfsFPMathView, "no-infs-fp-math");
684   HANDLE_BOOL_ATTR(EnableNoNaNsFPMathView, "no-nans-fp-math");
685   HANDLE_BOOL_ATTR(EnableNoSignedZerosFPMathView, "no-signed-zeros-fp-math");
686   HANDLE_BOOL_ATTR(EnableApproxFuncFPMathView, "approx-func-fp-math");
687 
688   if (DenormalFPMathView->getNumOccurrences() > 0 &&
689       !F.hasFnAttribute("denormal-fp-math")) {
690     DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();
691 
692     // FIXME: Command line flag should expose separate input/output modes.
693     NewAttrs.addAttribute("denormal-fp-math",
694                           DenormalMode(DenormKind, DenormKind).str());
695   }
696 
697   if (DenormalFP32MathView->getNumOccurrences() > 0 &&
698       !F.hasFnAttribute("denormal-fp-math-f32")) {
699     // FIXME: Command line flag should expose separate input/output modes.
700     DenormalMode::DenormalModeKind DenormKind = getDenormalFP32Math();
701 
702     NewAttrs.addAttribute(
703       "denormal-fp-math-f32",
704       DenormalMode(DenormKind, DenormKind).str());
705   }
706 
707   if (TrapFuncNameView->getNumOccurrences() > 0)
708     for (auto &B : F)
709       for (auto &I : B)
710         if (auto *Call = dyn_cast<CallInst>(&I))
711           if (const auto *F = Call->getCalledFunction())
712             if (F->getIntrinsicID() == Intrinsic::debugtrap ||
713                 F->getIntrinsicID() == Intrinsic::trap)
714               Call->addFnAttr(
715                   Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
716 
717   // Let NewAttrs override Attrs.
718   F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
719 }
720 
721 /// Set function attributes of functions in Module M based on CPU,
722 /// Features, and command line flags.
723 void codegen::setFunctionAttributes(StringRef CPU, StringRef Features,
724                                     Module &M) {
725   for (Function &F : M)
726     setFunctionAttributes(CPU, Features, F);
727 }
728