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