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