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