xref: /llvm-project/llvm/lib/CodeGen/CommandFlags.cpp (revision 0c36da722aa55535d35d1423c70fc04ab8889090)
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 
21 using namespace llvm;
22 
23 #define CGOPT(TY, NAME)                                                        \
24   static cl::opt<TY> *NAME##View;                                              \
25   TY codegen::get##NAME() {                                                    \
26     assert(NAME##View && "RegisterCodeGenFlags not created.");                 \
27     return *NAME##View;                                                        \
28   }
29 
30 #define CGLIST(TY, NAME)                                                       \
31   static cl::list<TY> *NAME##View;                                             \
32   std::vector<TY> codegen::get##NAME() {                                       \
33     assert(NAME##View && "RegisterCodeGenFlags not created.");                 \
34     return *NAME##View;                                                        \
35   }
36 
37 #define CGOPT_EXP(TY, NAME)                                                    \
38   CGOPT(TY, NAME)                                                              \
39   Optional<TY> codegen::getExplicit##NAME() {                                  \
40     if (NAME##View->getNumOccurrences()) {                                     \
41       TY res = *NAME##View;                                                    \
42       return res;                                                              \
43     }                                                                          \
44     return None;                                                               \
45   }
46 
47 CGOPT(std::string, MArch)
48 CGOPT(std::string, MCPU)
49 CGLIST(std::string, MAttrs)
50 CGOPT_EXP(Reloc::Model, RelocModel)
51 CGOPT(ThreadModel::Model, ThreadModel)
52 CGOPT_EXP(CodeModel::Model, CodeModel)
53 CGOPT(ExceptionHandling, ExceptionModel)
54 CGOPT_EXP(CodeGenFileType, FileType)
55 CGOPT(FramePointer::FP, FramePointerUsage)
56 CGOPT(bool, EnableUnsafeFPMath)
57 CGOPT(bool, EnableNoInfsFPMath)
58 CGOPT(bool, EnableNoNaNsFPMath)
59 CGOPT(bool, EnableNoSignedZerosFPMath)
60 CGOPT(bool, EnableNoTrappingFPMath)
61 CGOPT(bool, EnableAIXExtendedAltivecABI)
62 CGOPT(DenormalMode::DenormalModeKind, DenormalFPMath)
63 CGOPT(DenormalMode::DenormalModeKind, DenormalFP32Math)
64 CGOPT(bool, EnableHonorSignDependentRoundingFPMath)
65 CGOPT(FloatABI::ABIType, FloatABIForCalls)
66 CGOPT(FPOpFusion::FPOpFusionMode, FuseFPOps)
67 CGOPT(bool, DontPlaceZerosInBSS)
68 CGOPT(bool, EnableGuaranteedTailCallOpt)
69 CGOPT(bool, DisableTailCalls)
70 CGOPT(bool, StackSymbolOrdering)
71 CGOPT(unsigned, OverrideStackAlignment)
72 CGOPT(bool, StackRealign)
73 CGOPT(std::string, TrapFuncName)
74 CGOPT(bool, UseCtors)
75 CGOPT(bool, RelaxELFRelocations)
76 CGOPT_EXP(bool, DataSections)
77 CGOPT_EXP(bool, FunctionSections)
78 CGOPT(bool, IgnoreXCOFFVisibility)
79 CGOPT(bool, XCOFFTracebackTable)
80 CGOPT(std::string, BBSections)
81 CGOPT(std::string, StackProtectorGuard)
82 CGOPT(unsigned, StackProtectorGuardOffset)
83 CGOPT(std::string, StackProtectorGuardReg)
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, PseudoProbeForProfiling)
96 CGOPT(bool, ValueTrackingVariableLocations)
97 CGOPT(bool, ForceDwarfFrameSection)
98 CGOPT(bool, XRayOmitFunctionIndex)
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<FramePointer::FP> FramePointerUsage(
186       "frame-pointer",
187       cl::desc("Specify frame pointer elimination optimization"),
188       cl::init(FramePointer::None),
189       cl::values(
190           clEnumValN(FramePointer::All, "all",
191                      "Disable frame pointer elimination"),
192           clEnumValN(FramePointer::NonLeaf, "non-leaf",
193                      "Disable frame pointer elimination for non-leaf frame"),
194           clEnumValN(FramePointer::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<bool> DontPlaceZerosInBSS(
283       "nozero-initialized-in-bss",
284       cl::desc("Don't place zero-initialized symbols into bss section"),
285       cl::init(false));
286   CGBINDOPT(DontPlaceZerosInBSS);
287 
288   static cl::opt<bool> EnableAIXExtendedAltivecABI(
289       "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
290       cl::init(false));
291   CGBINDOPT(EnableAIXExtendedAltivecABI);
292 
293   static cl::opt<bool> EnableGuaranteedTailCallOpt(
294       "tailcallopt",
295       cl::desc(
296           "Turn fastcc calls into tail calls by (potentially) changing ABI."),
297       cl::init(false));
298   CGBINDOPT(EnableGuaranteedTailCallOpt);
299 
300   static cl::opt<bool> DisableTailCalls(
301       "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
302   CGBINDOPT(DisableTailCalls);
303 
304   static cl::opt<bool> StackSymbolOrdering(
305       "stack-symbol-ordering", cl::desc("Order local stack symbols."),
306       cl::init(true));
307   CGBINDOPT(StackSymbolOrdering);
308 
309   static cl::opt<unsigned> OverrideStackAlignment(
310       "stack-alignment", cl::desc("Override default stack alignment"),
311       cl::init(0));
312   CGBINDOPT(OverrideStackAlignment);
313 
314   static cl::opt<bool> StackRealign(
315       "stackrealign",
316       cl::desc("Force align the stack to the minimum alignment"),
317       cl::init(false));
318   CGBINDOPT(StackRealign);
319 
320   static cl::opt<std::string> TrapFuncName(
321       "trap-func", cl::Hidden,
322       cl::desc("Emit a call to trap function rather than a trap instruction"),
323       cl::init(""));
324   CGBINDOPT(TrapFuncName);
325 
326   static cl::opt<bool> UseCtors("use-ctors",
327                                 cl::desc("Use .ctors instead of .init_array."),
328                                 cl::init(false));
329   CGBINDOPT(UseCtors);
330 
331   static cl::opt<bool> RelaxELFRelocations(
332       "relax-elf-relocations",
333       cl::desc(
334           "Emit GOTPCRELX/REX_GOTPCRELX instead of GOTPCREL on x86-64 ELF"),
335       cl::init(false));
336   CGBINDOPT(RelaxELFRelocations);
337 
338   static cl::opt<bool> DataSections(
339       "data-sections", cl::desc("Emit data into separate sections"),
340       cl::init(false));
341   CGBINDOPT(DataSections);
342 
343   static cl::opt<bool> FunctionSections(
344       "function-sections", cl::desc("Emit functions into separate sections"),
345       cl::init(false));
346   CGBINDOPT(FunctionSections);
347 
348   static cl::opt<bool> IgnoreXCOFFVisibility(
349       "ignore-xcoff-visibility",
350       cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
351                "all symbols 'unspecified' visibility in XCOFF object file"),
352       cl::init(false));
353   CGBINDOPT(IgnoreXCOFFVisibility);
354 
355   static cl::opt<bool> XCOFFTracebackTable(
356       "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
357       cl::init(true));
358   CGBINDOPT(XCOFFTracebackTable);
359 
360   static cl::opt<std::string> BBSections(
361       "basic-block-sections",
362       cl::desc("Emit basic blocks into separate sections"),
363       cl::value_desc("all | <function list (file)> | labels | none"),
364       cl::init("none"));
365   CGBINDOPT(BBSections);
366 
367   static cl::opt<std::string> StackProtectorGuard(
368       "stack-protector-guard", cl::desc("Stack protector guard mode"),
369       cl::init("none"));
370   CGBINDOPT(StackProtectorGuard);
371 
372   static cl::opt<std::string> StackProtectorGuardReg(
373       "stack-protector-guard-reg", cl::desc("Stack protector guard register"),
374       cl::init("none"));
375   CGBINDOPT(StackProtectorGuardReg);
376 
377   static cl::opt<unsigned> StackProtectorGuardOffset(
378       "stack-protector-guard-offset", cl::desc("Stack protector guard offset"),
379       cl::init((unsigned)-1));
380   CGBINDOPT(StackProtectorGuardOffset);
381 
382   static cl::opt<unsigned> TLSSize(
383       "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
384   CGBINDOPT(TLSSize);
385 
386   static cl::opt<bool> EmulatedTLS(
387       "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
388   CGBINDOPT(EmulatedTLS);
389 
390   static cl::opt<bool> UniqueSectionNames(
391       "unique-section-names", cl::desc("Give unique names to every section"),
392       cl::init(true));
393   CGBINDOPT(UniqueSectionNames);
394 
395   static cl::opt<bool> UniqueBasicBlockSectionNames(
396       "unique-basic-block-section-names",
397       cl::desc("Give unique names to every basic block section"),
398       cl::init(false));
399   CGBINDOPT(UniqueBasicBlockSectionNames);
400 
401   static cl::opt<EABI> EABIVersion(
402       "meabi", cl::desc("Set EABI type (default depends on triple):"),
403       cl::init(EABI::Default),
404       cl::values(
405           clEnumValN(EABI::Default, "default", "Triple default EABI version"),
406           clEnumValN(EABI::EABI4, "4", "EABI version 4"),
407           clEnumValN(EABI::EABI5, "5", "EABI version 5"),
408           clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
409   CGBINDOPT(EABIVersion);
410 
411   static cl::opt<DebuggerKind> DebuggerTuningOpt(
412       "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
413       cl::init(DebuggerKind::Default),
414       cl::values(
415           clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
416           clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
417           clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
418           clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
419   CGBINDOPT(DebuggerTuningOpt);
420 
421   static cl::opt<bool> EnableStackSizeSection(
422       "stack-size-section",
423       cl::desc("Emit a section containing stack size metadata"),
424       cl::init(false));
425   CGBINDOPT(EnableStackSizeSection);
426 
427   static cl::opt<bool> EnableAddrsig(
428       "addrsig", cl::desc("Emit an address-significance table"),
429       cl::init(false));
430   CGBINDOPT(EnableAddrsig);
431 
432   static cl::opt<bool> EmitCallSiteInfo(
433       "emit-call-site-info",
434       cl::desc(
435           "Emit call site debug information, if debug information is enabled."),
436       cl::init(false));
437   CGBINDOPT(EmitCallSiteInfo);
438 
439   static cl::opt<bool> EnableDebugEntryValues(
440       "debug-entry-values",
441       cl::desc("Enable debug info for the debug entry values."),
442       cl::init(false));
443   CGBINDOPT(EnableDebugEntryValues);
444 
445   static cl::opt<bool> PseudoProbeForProfiling(
446       "pseudo-probe-for-profiling", cl::desc("Emit pseudo probes for AutoFDO"),
447       cl::init(false));
448   CGBINDOPT(PseudoProbeForProfiling);
449 
450   static cl::opt<bool> ValueTrackingVariableLocations(
451       "experimental-debug-variable-locations",
452       cl::desc("Use experimental new value-tracking variable locations"),
453       cl::init(false));
454   CGBINDOPT(ValueTrackingVariableLocations);
455 
456   static cl::opt<bool> EnableMachineFunctionSplitter(
457       "split-machine-functions",
458       cl::desc("Split out cold basic blocks from machine functions based on "
459                "profile information"),
460       cl::init(false));
461   CGBINDOPT(EnableMachineFunctionSplitter);
462 
463   static cl::opt<bool> ForceDwarfFrameSection(
464       "force-dwarf-frame-section",
465       cl::desc("Always emit a debug frame section."), cl::init(false));
466   CGBINDOPT(ForceDwarfFrameSection);
467 
468   static cl::opt<bool> XRayOmitFunctionIndex(
469       "no-xray-index", cl::desc("Don't emit xray_fn_idx section"),
470       cl::init(false));
471   CGBINDOPT(XRayOmitFunctionIndex);
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 llvm::StackProtectorGuards
500 codegen::getStackProtectorGuardMode(llvm::TargetOptions &Options) {
501   if (getStackProtectorGuard() == "tls")
502     return StackProtectorGuards::TLS;
503   if (getStackProtectorGuard() == "global")
504     return StackProtectorGuards::Global;
505   if (getStackProtectorGuard() != "none") {
506     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
507         MemoryBuffer::getFile(getStackProtectorGuard());
508     if (!MBOrErr)
509       errs() << "error illegal stack protector guard mode: "
510              << MBOrErr.getError().message() << "\n";
511     else
512       Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
513   }
514   return StackProtectorGuards::None;
515 }
516 
517 // Common utility function tightly tied to the options listed here. Initializes
518 // a TargetOptions object with CodeGen flags and returns it.
519 TargetOptions
520 codegen::InitTargetOptionsFromCodeGenFlags(const Triple &TheTriple) {
521   TargetOptions Options;
522   Options.AllowFPOpFusion = getFuseFPOps();
523   Options.UnsafeFPMath = getEnableUnsafeFPMath();
524   Options.NoInfsFPMath = getEnableNoInfsFPMath();
525   Options.NoNaNsFPMath = getEnableNoNaNsFPMath();
526   Options.NoSignedZerosFPMath = getEnableNoSignedZerosFPMath();
527   Options.NoTrappingFPMath = getEnableNoTrappingFPMath();
528 
529   DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();
530 
531   // FIXME: Should have separate input and output flags
532   Options.setFPDenormalMode(DenormalMode(DenormKind, DenormKind));
533 
534   Options.HonorSignDependentRoundingFPMathOption =
535       getEnableHonorSignDependentRoundingFPMath();
536   if (getFloatABIForCalls() != FloatABI::Default)
537     Options.FloatABIType = getFloatABIForCalls();
538   Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
539   Options.NoZerosInBSS = getDontPlaceZerosInBSS();
540   Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
541   Options.StackAlignmentOverride = getOverrideStackAlignment();
542   Options.StackSymbolOrdering = getStackSymbolOrdering();
543   Options.UseInitArray = !getUseCtors();
544   Options.RelaxELFRelocations = getRelaxELFRelocations();
545   Options.DataSections =
546       getExplicitDataSections().getValueOr(TheTriple.hasDefaultDataSections());
547   Options.FunctionSections = getFunctionSections();
548   Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
549   Options.XCOFFTracebackTable = getXCOFFTracebackTable();
550   Options.BBSections = getBBSectionsMode(Options);
551   Options.UniqueSectionNames = getUniqueSectionNames();
552   Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
553   Options.StackProtectorGuard = getStackProtectorGuardMode(Options);
554   Options.StackProtectorGuardOffset = getStackProtectorGuardOffset();
555   Options.StackProtectorGuardReg = getStackProtectorGuardReg();
556   Options.TLSSize = getTLSSize();
557   Options.EmulatedTLS = getEmulatedTLS();
558   Options.ExplicitEmulatedTLS = EmulatedTLSView->getNumOccurrences() > 0;
559   Options.ExceptionModel = getExceptionModel();
560   Options.EmitStackSizeSection = getEnableStackSizeSection();
561   Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
562   Options.EmitAddrsig = getEnableAddrsig();
563   Options.EmitCallSiteInfo = getEmitCallSiteInfo();
564   Options.EnableDebugEntryValues = getEnableDebugEntryValues();
565   Options.PseudoProbeForProfiling = getPseudoProbeForProfiling();
566   Options.ValueTrackingVariableLocations = getValueTrackingVariableLocations();
567   Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
568   Options.XRayOmitFunctionIndex = getXRayOmitFunctionIndex();
569 
570   Options.MCOptions = mc::InitMCTargetOptionsFromFlags();
571 
572   Options.ThreadModel = getThreadModel();
573   Options.EABIVersion = getEABIVersion();
574   Options.DebuggerTuning = getDebuggerTuningOpt();
575 
576   return Options;
577 }
578 
579 std::string codegen::getCPUStr() {
580   // If user asked for the 'native' CPU, autodetect here. If autodection fails,
581   // this will set the CPU to an empty string which tells the target to
582   // pick a basic default.
583   if (getMCPU() == "native")
584     return std::string(sys::getHostCPUName());
585 
586   return getMCPU();
587 }
588 
589 std::string codegen::getFeaturesStr() {
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.getString();
607 }
608 
609 std::vector<std::string> codegen::getFeatureList() {
610   SubtargetFeatures Features;
611 
612   // If user asked for the 'native' CPU, we need to autodetect features.
613   // This is necessary for x86 where the CPU might not support all the
614   // features the autodetected CPU name lists in the target. For example,
615   // not all Sandybridge processors support AVX.
616   if (getMCPU() == "native") {
617     StringMap<bool> HostFeatures;
618     if (sys::getHostCPUFeatures(HostFeatures))
619       for (auto &F : HostFeatures)
620         Features.AddFeature(F.first(), F.second);
621   }
622 
623   for (auto const &MAttr : getMAttrs())
624     Features.AddFeature(MAttr);
625 
626   return Features.getFeatures();
627 }
628 
629 void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
630   B.addAttribute(Name, Val ? "true" : "false");
631 }
632 
633 #define HANDLE_BOOL_ATTR(CL, AttrName)                                         \
634   do {                                                                         \
635     if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName))            \
636       renderBoolStringAttr(NewAttrs, AttrName, *CL);                           \
637   } while (0)
638 
639 /// Set function attributes of function \p F based on CPU, Features, and command
640 /// line flags.
641 void codegen::setFunctionAttributes(StringRef CPU, StringRef Features,
642                                     Function &F) {
643   auto &Ctx = F.getContext();
644   AttributeList Attrs = F.getAttributes();
645   AttrBuilder NewAttrs;
646 
647   if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
648     NewAttrs.addAttribute("target-cpu", CPU);
649   if (!Features.empty()) {
650     // Append the command line features to any that are already on the function.
651     StringRef OldFeatures =
652         F.getFnAttribute("target-features").getValueAsString();
653     if (OldFeatures.empty())
654       NewAttrs.addAttribute("target-features", Features);
655     else {
656       SmallString<256> Appended(OldFeatures);
657       Appended.push_back(',');
658       Appended.append(Features);
659       NewAttrs.addAttribute("target-features", Appended);
660     }
661   }
662   if (FramePointerUsageView->getNumOccurrences() > 0 &&
663       !F.hasFnAttribute("frame-pointer")) {
664     if (getFramePointerUsage() == FramePointer::All)
665       NewAttrs.addAttribute("frame-pointer", "all");
666     else if (getFramePointerUsage() == FramePointer::NonLeaf)
667       NewAttrs.addAttribute("frame-pointer", "non-leaf");
668     else if (getFramePointerUsage() == FramePointer::None)
669       NewAttrs.addAttribute("frame-pointer", "none");
670   }
671   if (DisableTailCallsView->getNumOccurrences() > 0)
672     NewAttrs.addAttribute("disable-tail-calls",
673                           toStringRef(getDisableTailCalls()));
674   if (getStackRealign())
675     NewAttrs.addAttribute("stackrealign");
676 
677   HANDLE_BOOL_ATTR(EnableUnsafeFPMathView, "unsafe-fp-math");
678   HANDLE_BOOL_ATTR(EnableNoInfsFPMathView, "no-infs-fp-math");
679   HANDLE_BOOL_ATTR(EnableNoNaNsFPMathView, "no-nans-fp-math");
680   HANDLE_BOOL_ATTR(EnableNoSignedZerosFPMathView, "no-signed-zeros-fp-math");
681 
682   if (DenormalFPMathView->getNumOccurrences() > 0 &&
683       !F.hasFnAttribute("denormal-fp-math")) {
684     DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();
685 
686     // FIXME: Command line flag should expose separate input/output modes.
687     NewAttrs.addAttribute("denormal-fp-math",
688                           DenormalMode(DenormKind, DenormKind).str());
689   }
690 
691   if (DenormalFP32MathView->getNumOccurrences() > 0 &&
692       !F.hasFnAttribute("denormal-fp-math-f32")) {
693     // FIXME: Command line flag should expose separate input/output modes.
694     DenormalMode::DenormalModeKind DenormKind = getDenormalFP32Math();
695 
696     NewAttrs.addAttribute(
697       "denormal-fp-math-f32",
698       DenormalMode(DenormKind, DenormKind).str());
699   }
700 
701   if (TrapFuncNameView->getNumOccurrences() > 0)
702     for (auto &B : F)
703       for (auto &I : B)
704         if (auto *Call = dyn_cast<CallInst>(&I))
705           if (const auto *F = Call->getCalledFunction())
706             if (F->getIntrinsicID() == Intrinsic::debugtrap ||
707                 F->getIntrinsicID() == Intrinsic::trap)
708               Call->addAttribute(
709                   AttributeList::FunctionIndex,
710                   Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
711 
712   // Let NewAttrs override Attrs.
713   F.setAttributes(
714       Attrs.addAttributes(Ctx, AttributeList::FunctionIndex, NewAttrs));
715 }
716 
717 /// Set function attributes of functions in Module M based on CPU,
718 /// Features, and command line flags.
719 void codegen::setFunctionAttributes(StringRef CPU, StringRef Features,
720                                     Module &M) {
721   for (Function &F : M)
722     setFunctionAttributes(CPU, Features, F);
723 }
724