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