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