LLVM 22.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"
28#include <optional>
29
30using namespace llvm;
31
32#define CGOPT(TY, NAME) \
33 static cl::opt<TY> *NAME##View; \
34 TY codegen::get##NAME() { \
35 assert(NAME##View && "RegisterCodeGenFlags not created."); \
36 return *NAME##View; \
37 }
38
39#define CGLIST(TY, NAME) \
40 static cl::list<TY> *NAME##View; \
41 std::vector<TY> codegen::get##NAME() { \
42 assert(NAME##View && "RegisterCodeGenFlags not created."); \
43 return *NAME##View; \
44 }
45
46// Temporary macro for incremental transition to std::optional.
47#define CGOPT_EXP(TY, NAME) \
48 CGOPT(TY, NAME) \
49 std::optional<TY> codegen::getExplicit##NAME() { \
50 if (NAME##View->getNumOccurrences()) { \
51 TY res = *NAME##View; \
52 return res; \
53 } \
54 return std::nullopt; \
55 }
56
57CGOPT(std::string, MArch)
58CGOPT(std::string, MCPU)
59CGLIST(std::string, MAttrs)
60CGOPT_EXP(Reloc::Model, RelocModel)
63CGOPT_EXP(uint64_t, LargeDataThreshold)
64CGOPT(ExceptionHandling, ExceptionModel)
66CGOPT(FramePointerKind, FramePointerUsage)
67CGOPT(bool, EnableNoInfsFPMath)
68CGOPT(bool, EnableNoNaNsFPMath)
69CGOPT(bool, EnableNoSignedZerosFPMath)
70CGOPT(bool, EnableNoTrappingFPMath)
71CGOPT(bool, EnableAIXExtendedAltivecABI)
74CGOPT(bool, EnableHonorSignDependentRoundingFPMath)
75CGOPT(FloatABI::ABIType, FloatABIForCalls)
77CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
78CGOPT(bool, DontPlaceZerosInBSS)
79CGOPT(bool, EnableGuaranteedTailCallOpt)
80CGOPT(bool, DisableTailCalls)
81CGOPT(bool, StackSymbolOrdering)
82CGOPT(bool, StackRealign)
83CGOPT(std::string, TrapFuncName)
84CGOPT(bool, UseCtors)
85CGOPT(bool, DisableIntegratedAS)
86CGOPT_EXP(bool, DataSections)
87CGOPT_EXP(bool, FunctionSections)
88CGOPT(bool, IgnoreXCOFFVisibility)
89CGOPT(bool, XCOFFTracebackTable)
90CGOPT(bool, EnableBBAddrMap)
91CGOPT(std::string, BBSections)
92CGOPT(unsigned, TLSSize)
93CGOPT_EXP(bool, EmulatedTLS)
94CGOPT_EXP(bool, EnableTLSDESC)
95CGOPT(bool, UniqueSectionNames)
96CGOPT(bool, UniqueBasicBlockSectionNames)
97CGOPT(bool, SeparateNamedSections)
98CGOPT(EABI, EABIVersion)
99CGOPT(DebuggerKind, DebuggerTuningOpt)
100CGOPT(bool, EnableStackSizeSection)
101CGOPT(bool, EnableAddrsig)
102CGOPT(bool, EnableCallGraphSection)
103CGOPT(bool, EmitCallSiteInfo)
105CGOPT(bool, EnableStaticDataPartitioning)
106CGOPT(bool, EnableDebugEntryValues)
107CGOPT(bool, ForceDwarfFrameSection)
108CGOPT(bool, XRayFunctionIndex)
109CGOPT(bool, DebugStrictDwarf)
110CGOPT(unsigned, AlignLoops)
111CGOPT(bool, JMCInstrument)
112CGOPT(bool, XCOFFReadOnlyPointers)
113
115#define CGBINDOPT(NAME) \
116 do { \
117 NAME##View = std::addressof(NAME); \
118 } while (0)
119
120 static cl::opt<std::string> MArch(
121 "march", cl::desc("Architecture to generate code for (see --version)"));
122 CGBINDOPT(MArch);
123
124 static cl::opt<std::string> MCPU(
125 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
126 cl::value_desc("cpu-name"), cl::init(""));
127 CGBINDOPT(MCPU);
128
129 static cl::list<std::string> MAttrs(
130 "mattr", cl::CommaSeparated,
131 cl::desc("Target specific attributes (-mattr=help for details)"),
132 cl::value_desc("a1,+a2,-a3,..."));
133 CGBINDOPT(MAttrs);
134
135 static cl::opt<Reloc::Model> RelocModel(
136 "relocation-model", cl::desc("Choose relocation model"),
138 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
139 clEnumValN(Reloc::PIC_, "pic",
140 "Fully relocatable, position independent code"),
141 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
142 "Relocatable external references, non-relocatable code"),
144 Reloc::ROPI, "ropi",
145 "Code and read-only data relocatable, accessed PC-relative"),
147 Reloc::RWPI, "rwpi",
148 "Read-write data relocatable, accessed relative to static base"),
149 clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
150 "Combination of ropi and rwpi")));
151 CGBINDOPT(RelocModel);
152
154 "thread-model", cl::desc("Choose threading model"),
157 clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"),
158 clEnumValN(ThreadModel::Single, "single", "Single thread model")));
160
162 "code-model", cl::desc("Choose code model"),
163 cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
164 clEnumValN(CodeModel::Small, "small", "Small code model"),
165 clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
166 clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
167 clEnumValN(CodeModel::Large, "large", "Large code model")));
169
170 static cl::opt<uint64_t> LargeDataThreshold(
171 "large-data-threshold",
172 cl::desc("Choose large data threshold for x86_64 medium code model"),
173 cl::init(0));
174 CGBINDOPT(LargeDataThreshold);
175
176 static cl::opt<ExceptionHandling> ExceptionModel(
177 "exception-model", cl::desc("exception model"),
181 "default exception handling model"),
183 "DWARF-like CFI based exception handling"),
185 "SjLj exception handling"),
186 clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
188 "Windows exception model"),
190 "WebAssembly exception handling")));
191 CGBINDOPT(ExceptionModel);
192
193 static cl::opt<CodeGenFileType> FileType(
195 cl::desc(
196 "Choose a file type (not all types are supported by all targets):"),
198 "Emit an assembly ('.s') file"),
200 "Emit a native object ('.o') file"),
202 "Emit nothing, for performance testing")));
203 CGBINDOPT(FileType);
204
205 static cl::opt<FramePointerKind> FramePointerUsage(
206 "frame-pointer",
207 cl::desc("Specify frame pointer elimination optimization"),
211 "Disable frame pointer elimination"),
213 "Disable frame pointer elimination for non-leaf frame"),
215 "Enable frame pointer elimination, but reserve the frame "
216 "pointer register"),
218 "Enable frame pointer elimination")));
219 CGBINDOPT(FramePointerUsage);
220
221 static cl::opt<bool> EnableNoInfsFPMath(
222 "enable-no-infs-fp-math",
223 cl::desc("Enable FP math optimizations that assume no +-Infs"),
224 cl::init(false));
225 CGBINDOPT(EnableNoInfsFPMath);
226
227 static cl::opt<bool> EnableNoNaNsFPMath(
228 "enable-no-nans-fp-math",
229 cl::desc("Enable FP math optimizations that assume no NaNs"),
230 cl::init(false));
231 CGBINDOPT(EnableNoNaNsFPMath);
232
233 static cl::opt<bool> EnableNoSignedZerosFPMath(
234 "enable-no-signed-zeros-fp-math",
235 cl::desc("Enable FP math optimizations that assume "
236 "the sign of 0 is insignificant"),
237 cl::init(false));
238 CGBINDOPT(EnableNoSignedZerosFPMath);
239
240 static cl::opt<bool> EnableNoTrappingFPMath(
241 "enable-no-trapping-fp-math",
242 cl::desc("Enable setting the FP exceptions build "
243 "attribute not to use exceptions"),
244 cl::init(false));
245 CGBINDOPT(EnableNoTrappingFPMath);
246
247 static const auto DenormFlagEnumOptions = cl::values(
248 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
249 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
250 "the sign of a flushed-to-zero number is preserved "
251 "in the sign of 0"),
252 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
253 "denormals are flushed to positive zero"),
255 "denormals have unknown treatment"));
256
257 // FIXME: Doesn't have way to specify separate input and output modes.
258 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
259 "denormal-fp-math",
260 cl::desc("Select which denormal numbers the code is permitted to require"),
262 DenormFlagEnumOptions);
263 CGBINDOPT(DenormalFPMath);
264
265 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
266 "denormal-fp-math-f32",
267 cl::desc("Select which denormal numbers the code is permitted to require for float"),
269 DenormFlagEnumOptions);
270 CGBINDOPT(DenormalFP32Math);
271
272 static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(
273 "enable-sign-dependent-rounding-fp-math", cl::Hidden,
274 cl::desc("Force codegen to assume rounding mode can change dynamically"),
275 cl::init(false));
276 CGBINDOPT(EnableHonorSignDependentRoundingFPMath);
277
278 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
279 "float-abi", cl::desc("Choose float ABI type"),
282 "Target default float ABI type"),
284 "Soft float ABI (implied by -soft-float)"),
286 "Hard float ABI (uses FP registers)")));
287 CGBINDOPT(FloatABIForCalls);
288
290 "fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),
294 "Fuse FP ops whenever profitable"),
295 clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),
297 "Only fuse FP ops when the result won't be affected.")));
298 CGBINDOPT(FuseFPOps);
299
300 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
301 "swift-async-fp",
302 cl::desc("Determine when the Swift async frame pointer should be set"),
305 "Determine based on deployment target"),
307 "Always set the bit"),
309 "Never set the bit")));
310 CGBINDOPT(SwiftAsyncFramePointer);
311
312 static cl::opt<bool> DontPlaceZerosInBSS(
313 "nozero-initialized-in-bss",
314 cl::desc("Don't place zero-initialized symbols into bss section"),
315 cl::init(false));
316 CGBINDOPT(DontPlaceZerosInBSS);
317
318 static cl::opt<bool> EnableAIXExtendedAltivecABI(
319 "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
320 cl::init(false));
321 CGBINDOPT(EnableAIXExtendedAltivecABI);
322
323 static cl::opt<bool> EnableGuaranteedTailCallOpt(
324 "tailcallopt",
325 cl::desc(
326 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
327 cl::init(false));
328 CGBINDOPT(EnableGuaranteedTailCallOpt);
329
330 static cl::opt<bool> DisableTailCalls(
331 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
332 CGBINDOPT(DisableTailCalls);
333
334 static cl::opt<bool> StackSymbolOrdering(
335 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
336 cl::init(true));
337 CGBINDOPT(StackSymbolOrdering);
338
339 static cl::opt<bool> StackRealign(
340 "stackrealign",
341 cl::desc("Force align the stack to the minimum alignment"),
342 cl::init(false));
343 CGBINDOPT(StackRealign);
344
345 static cl::opt<std::string> TrapFuncName(
346 "trap-func", cl::Hidden,
347 cl::desc("Emit a call to trap function rather than a trap instruction"),
348 cl::init(""));
349 CGBINDOPT(TrapFuncName);
350
351 static cl::opt<bool> UseCtors("use-ctors",
352 cl::desc("Use .ctors instead of .init_array."),
353 cl::init(false));
354 CGBINDOPT(UseCtors);
355
356 static cl::opt<bool> DataSections(
357 "data-sections", cl::desc("Emit data into separate sections"),
358 cl::init(false));
359 CGBINDOPT(DataSections);
360
361 static cl::opt<bool> FunctionSections(
362 "function-sections", cl::desc("Emit functions into separate sections"),
363 cl::init(false));
364 CGBINDOPT(FunctionSections);
365
366 static cl::opt<bool> IgnoreXCOFFVisibility(
367 "ignore-xcoff-visibility",
368 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
369 "all symbols 'unspecified' visibility in XCOFF object file"),
370 cl::init(false));
371 CGBINDOPT(IgnoreXCOFFVisibility);
372
373 static cl::opt<bool> XCOFFTracebackTable(
374 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
375 cl::init(true));
376 CGBINDOPT(XCOFFTracebackTable);
377
378 static cl::opt<bool> EnableBBAddrMap(
379 "basic-block-address-map",
380 cl::desc("Emit the basic block address map section"), cl::init(false));
381 CGBINDOPT(EnableBBAddrMap);
382
383 static cl::opt<std::string> BBSections(
384 "basic-block-sections",
385 cl::desc("Emit basic blocks into separate sections"),
386 cl::value_desc("all | <function list (file)> | labels | none"),
387 cl::init("none"));
388 CGBINDOPT(BBSections);
389
390 static cl::opt<unsigned> TLSSize(
391 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
392 CGBINDOPT(TLSSize);
393
394 static cl::opt<bool> EmulatedTLS(
395 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
396 CGBINDOPT(EmulatedTLS);
397
398 static cl::opt<bool> EnableTLSDESC(
399 "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
400 cl::init(false));
401 CGBINDOPT(EnableTLSDESC);
402
403 static cl::opt<bool> UniqueSectionNames(
404 "unique-section-names", cl::desc("Give unique names to every section"),
405 cl::init(true));
406 CGBINDOPT(UniqueSectionNames);
407
408 static cl::opt<bool> UniqueBasicBlockSectionNames(
409 "unique-basic-block-section-names",
410 cl::desc("Give unique names to every basic block section"),
411 cl::init(false));
412 CGBINDOPT(UniqueBasicBlockSectionNames);
413
414 static cl::opt<bool> SeparateNamedSections(
415 "separate-named-sections",
416 cl::desc("Use separate unique sections for named sections"),
417 cl::init(false));
418 CGBINDOPT(SeparateNamedSections);
419
420 static cl::opt<EABI> EABIVersion(
421 "meabi", cl::desc("Set EABI type (default depends on triple):"),
424 clEnumValN(EABI::Default, "default", "Triple default EABI version"),
425 clEnumValN(EABI::EABI4, "4", "EABI version 4"),
426 clEnumValN(EABI::EABI5, "5", "EABI version 5"),
427 clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
428 CGBINDOPT(EABIVersion);
429
430 static cl::opt<DebuggerKind> DebuggerTuningOpt(
431 "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
434 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
435 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
436 clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
437 clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
438 CGBINDOPT(DebuggerTuningOpt);
439
440 static cl::opt<bool> EnableStackSizeSection(
441 "stack-size-section",
442 cl::desc("Emit a section containing stack size metadata"),
443 cl::init(false));
444 CGBINDOPT(EnableStackSizeSection);
445
446 static cl::opt<bool> EnableAddrsig(
447 "addrsig", cl::desc("Emit an address-significance table"),
448 cl::init(false));
449 CGBINDOPT(EnableAddrsig);
450
451 static cl::opt<bool> EnableCallGraphSection(
452 "call-graph-section", cl::desc("Emit a call graph section"),
453 cl::init(false));
454 CGBINDOPT(EnableCallGraphSection);
455
456 static cl::opt<bool> EmitCallSiteInfo(
457 "emit-call-site-info",
458 cl::desc(
459 "Emit call site debug information, if debug information is enabled."),
460 cl::init(false));
461 CGBINDOPT(EmitCallSiteInfo);
462
463 static cl::opt<bool> EnableDebugEntryValues(
464 "debug-entry-values",
465 cl::desc("Enable debug info for the debug entry values."),
466 cl::init(false));
467 CGBINDOPT(EnableDebugEntryValues);
468
470 "split-machine-functions",
471 cl::desc("Split out cold basic blocks from machine functions based on "
472 "profile information"),
473 cl::init(false));
475
476 static cl::opt<bool> EnableStaticDataPartitioning(
477 "partition-static-data-sections",
478 cl::desc("Partition data sections using profile information."),
479 cl::init(false));
480 CGBINDOPT(EnableStaticDataPartitioning);
481
482 static cl::opt<bool> ForceDwarfFrameSection(
483 "force-dwarf-frame-section",
484 cl::desc("Always emit a debug frame section."), cl::init(false));
485 CGBINDOPT(ForceDwarfFrameSection);
486
487 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
488 cl::desc("Emit xray_fn_idx section"),
489 cl::init(true));
490 CGBINDOPT(XRayFunctionIndex);
491
492 static cl::opt<bool> DebugStrictDwarf(
493 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
494 CGBINDOPT(DebugStrictDwarf);
495
496 static cl::opt<unsigned> AlignLoops("align-loops",
497 cl::desc("Default alignment for loops"));
498 CGBINDOPT(AlignLoops);
499
500 static cl::opt<bool> JMCInstrument(
501 "enable-jmc-instrument",
502 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
503 cl::init(false));
504 CGBINDOPT(JMCInstrument);
505
506 static cl::opt<bool> XCOFFReadOnlyPointers(
507 "mxcoff-roptr",
508 cl::desc("When set to true, const objects with relocatable address "
509 "values are put into the RO data section."),
510 cl::init(false));
511 CGBINDOPT(XCOFFReadOnlyPointers);
512
513 static cl::opt<bool> DisableIntegratedAS(
514 "no-integrated-as", cl::desc("Disable integrated assembler"),
515 cl::init(false));
516 CGBINDOPT(DisableIntegratedAS);
517
518#undef CGBINDOPT
519
521}
522
525 if (getBBSections() == "all")
527 else if (getBBSections() == "none")
529 else {
532 if (!MBOrErr) {
533 errs() << "Error loading basic block sections function list file: "
534 << MBOrErr.getError().message() << "\n";
535 } else {
536 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
537 }
539 }
540}
541
542// Common utility function tightly tied to the options listed here. Initializes
543// a TargetOptions object with CodeGen flags and returns it.
547 Options.AllowFPOpFusion = getFuseFPOps();
548 Options.NoInfsFPMath = getEnableNoInfsFPMath();
549 Options.NoNaNsFPMath = getEnableNoNaNsFPMath();
550 Options.NoSignedZerosFPMath = getEnableNoSignedZerosFPMath();
551 Options.NoTrappingFPMath = getEnableNoTrappingFPMath();
552
554
555 // FIXME: Should have separate input and output flags
556 Options.setFPDenormalMode(DenormalMode(DenormKind, DenormKind));
557
558 Options.HonorSignDependentRoundingFPMathOption =
561 Options.FloatABIType = getFloatABIForCalls();
562 Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
563 Options.NoZerosInBSS = getDontPlaceZerosInBSS();
564 Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
565 Options.StackSymbolOrdering = getStackSymbolOrdering();
566 Options.UseInitArray = !getUseCtors();
567 Options.DisableIntegratedAS = getDisableIntegratedAS();
568 Options.DataSections =
569 getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
570 Options.FunctionSections = getFunctionSections();
571 Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
572 Options.XCOFFTracebackTable = getXCOFFTracebackTable();
573 Options.BBAddrMap = getEnableBBAddrMap();
574 Options.BBSections = getBBSectionsMode(Options);
575 Options.UniqueSectionNames = getUniqueSectionNames();
576 Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
577 Options.SeparateNamedSections = getSeparateNamedSections();
578 Options.TLSSize = getTLSSize();
579 Options.EmulatedTLS =
580 getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
581 Options.EnableTLSDESC =
582 getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());
583 Options.ExceptionModel = getExceptionModel();
584 Options.EmitStackSizeSection = getEnableStackSizeSection();
585 Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
586 Options.EnableStaticDataPartitioning = getEnableStaticDataPartitioning();
587 Options.EmitAddrsig = getEnableAddrsig();
588 Options.EmitCallGraphSection = getEnableCallGraphSection();
589 Options.EmitCallSiteInfo = getEmitCallSiteInfo();
590 Options.EnableDebugEntryValues = getEnableDebugEntryValues();
591 Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
592 Options.XRayFunctionIndex = getXRayFunctionIndex();
593 Options.DebugStrictDwarf = getDebugStrictDwarf();
594 Options.LoopAlignment = getAlignLoops();
595 Options.JMCInstrument = getJMCInstrument();
596 Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
597
599
600 Options.ThreadModel = getThreadModel();
601 Options.EABIVersion = getEABIVersion();
602 Options.DebuggerTuning = getDebuggerTuningOpt();
603 Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
604 return Options;
605}
606
607std::string codegen::getCPUStr() {
608 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
609 // this will set the CPU to an empty string which tells the target to
610 // pick a basic default.
611 if (getMCPU() == "native")
612 return std::string(sys::getHostCPUName());
613
614 return getMCPU();
615}
616
618 SubtargetFeatures Features;
619
620 // If user asked for the 'native' CPU, we need to autodetect features.
621 // This is necessary for x86 where the CPU might not support all the
622 // features the autodetected CPU name lists in the target. For example,
623 // not all Sandybridge processors support AVX.
624 if (getMCPU() == "native")
625 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
626 Features.AddFeature(Feature, IsEnabled);
627
628 for (auto const &MAttr : getMAttrs())
629 Features.AddFeature(MAttr);
630
631 return Features.getString();
632}
633
634std::vector<std::string> codegen::getFeatureList() {
635 SubtargetFeatures Features;
636
637 // If user asked for the 'native' CPU, we need to autodetect features.
638 // This is necessary for x86 where the CPU might not support all the
639 // features the autodetected CPU name lists in the target. For example,
640 // not all Sandybridge processors support AVX.
641 if (getMCPU() == "native")
642 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
643 Features.AddFeature(Feature, IsEnabled);
644
645 for (auto const &MAttr : getMAttrs())
646 Features.AddFeature(MAttr);
647
648 return Features.getFeatures();
649}
650
651void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
652 B.addAttribute(Name, Val ? "true" : "false");
653}
654
655#define HANDLE_BOOL_ATTR(CL, AttrName) \
656 do { \
657 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
658 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
659 } while (0)
660
661/// Set function attributes of function \p F based on CPU, Features, and command
662/// line flags.
664 Function &F) {
665 auto &Ctx = F.getContext();
666 AttributeList Attrs = F.getAttributes();
667 AttrBuilder NewAttrs(Ctx);
668
669 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
670 NewAttrs.addAttribute("target-cpu", CPU);
671 if (!Features.empty()) {
672 // Append the command line features to any that are already on the function.
673 StringRef OldFeatures =
674 F.getFnAttribute("target-features").getValueAsString();
675 if (OldFeatures.empty())
676 NewAttrs.addAttribute("target-features", Features);
677 else {
678 SmallString<256> Appended(OldFeatures);
679 Appended.push_back(',');
680 Appended.append(Features);
681 NewAttrs.addAttribute("target-features", Appended);
682 }
683 }
684 if (FramePointerUsageView->getNumOccurrences() > 0 &&
685 !F.hasFnAttribute("frame-pointer")) {
687 NewAttrs.addAttribute("frame-pointer", "all");
689 NewAttrs.addAttribute("frame-pointer", "non-leaf");
691 NewAttrs.addAttribute("frame-pointer", "reserved");
693 NewAttrs.addAttribute("frame-pointer", "none");
694 }
695 if (DisableTailCallsView->getNumOccurrences() > 0)
696 NewAttrs.addAttribute("disable-tail-calls",
698 if (getStackRealign())
699 NewAttrs.addAttribute("stackrealign");
700
701 HANDLE_BOOL_ATTR(EnableNoInfsFPMathView, "no-infs-fp-math");
702 HANDLE_BOOL_ATTR(EnableNoNaNsFPMathView, "no-nans-fp-math");
703 HANDLE_BOOL_ATTR(EnableNoSignedZerosFPMathView, "no-signed-zeros-fp-math");
704
705 if (DenormalFPMathView->getNumOccurrences() > 0 &&
706 !F.hasFnAttribute("denormal-fp-math")) {
708
709 // FIXME: Command line flag should expose separate input/output modes.
710 NewAttrs.addAttribute("denormal-fp-math",
711 DenormalMode(DenormKind, DenormKind).str());
712 }
713
714 if (DenormalFP32MathView->getNumOccurrences() > 0 &&
715 !F.hasFnAttribute("denormal-fp-math-f32")) {
716 // FIXME: Command line flag should expose separate input/output modes.
718
719 NewAttrs.addAttribute(
720 "denormal-fp-math-f32",
721 DenormalMode(DenormKind, DenormKind).str());
722 }
723
724 if (TrapFuncNameView->getNumOccurrences() > 0)
725 for (auto &B : F)
726 for (auto &I : B)
727 if (auto *Call = dyn_cast<CallInst>(&I))
728 if (const auto *F = Call->getCalledFunction())
729 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
730 F->getIntrinsicID() == Intrinsic::trap)
731 Call->addFnAttr(
732 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
733
734 // Let NewAttrs override Attrs.
735 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
736}
737
738/// Set function attributes of functions in Module M based on CPU,
739/// Features, and command line flags.
741 Module &M) {
742 for (Function &F : M)
743 setFunctionAttributes(CPU, Features, F);
744}
745
748 CodeGenOptLevel OptLevel) {
749 Triple TheTriple(TargetTriple);
750 std::string Error;
751 const auto *TheTarget =
753 if (!TheTarget)
755 auto *Target = TheTarget->createTargetMachine(
759 OptLevel);
760 if (!Target)
762 Twine("could not allocate target machine for ") +
763 TargetTriple);
764 return std::unique_ptr<TargetMachine>(Target);
765}
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)
Module.h This file contains the declarations for the Module class.
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
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.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
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:67
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)
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
Manages the enabling and disabling of subtarget specific features.
const std::vector< std::string > & getFeatures() const
Returns the vector of individual subtarget features.
LLVM_ABI std::string getString() const
Returns features as a string.
LLVM_ABI void AddFeature(StringRef String, bool Enable=true)
Adds Features.
Target - Wrapper for Target specific information.
TargetMachine * createTargetMachine(const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
bool hasDefaultTLSDESC() const
True if the target uses TLSDESC by default.
Definition Triple.h:1191
bool hasDefaultDataSections() const
Tests whether the target uses -data-sections as default.
Definition Triple.h:1196
bool hasDefaultEmulatedTLS() const
Tests whether the target uses emulated TLS as default.
Definition Triple.h:1185
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
CallInst * Call
@ DynamicNoPIC
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 ...
initializer< Ty > init(const Ty &Val)
LLVM_ABI bool getEnableMachineFunctionSplitter()
LLVM_ABI bool getEnableHonorSignDependentRoundingFPMath()
LLVM_ABI std::string getTrapFuncName()
LLVM_ABI bool getEnableDebugEntryValues()
LLVM_ABI unsigned getTLSSize()
LLVM_ABI bool getEnableGuaranteedTailCallOpt()
LLVM_ABI llvm::FPOpFusion::FPOpFusionMode getFuseFPOps()
LLVM_ABI std::optional< CodeModel::Model > getExplicitCodeModel()
LLVM_ABI bool getFunctionSections()
LLVM_ABI bool getDisableTailCalls()
LLVM_ABI std::string getCPUStr()
LLVM_ABI bool getXCOFFReadOnlyPointers()
LLVM_ABI std::string getFeaturesStr()
LLVM_ABI bool getUniqueSectionNames()
LLVM_ABI DenormalMode::DenormalModeKind getDenormalFPMath()
LLVM_ABI llvm::FloatABI::ABIType getFloatABIForCalls()
LLVM_ABI void renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val)
LLVM_ABI bool getDebugStrictDwarf()
LLVM_ABI bool getForceDwarfFrameSection()
LLVM_ABI bool getStackRealign()
LLVM_ABI std::string getMCPU()
LLVM_ABI bool getJMCInstrument()
LLVM_ABI bool getEnableAddrsig()
LLVM_ABI bool getStackSymbolOrdering()
LLVM_ABI SwiftAsyncFramePointerMode getSwiftAsyncFramePointer()
LLVM_ABI bool getEnableBBAddrMap()
LLVM_ABI std::vector< std::string > getFeatureList()
LLVM_ABI bool getEnableStaticDataPartitioning()
LLVM_ABI std::string getMArch()
LLVM_ABI DenormalMode::DenormalModeKind getDenormalFP32Math()
LLVM_ABI bool getEnableNoSignedZerosFPMath()
LLVM_ABI bool getEnableStackSizeSection()
LLVM_ABI llvm::EABI getEABIVersion()
LLVM_ABI bool getEnableCallGraphSection()
LLVM_ABI bool getEnableNoTrappingFPMath()
LLVM_ABI Expected< std::unique_ptr< TargetMachine > > createTargetMachineForTriple(StringRef TargetTriple, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default)
Creates a TargetMachine instance with the options defined on the command line.
LLVM_ABI bool getUniqueBasicBlockSectionNames()
LLVM_ABI FramePointerKind getFramePointerUsage()
LLVM_ABI bool getDontPlaceZerosInBSS()
LLVM_ABI bool getSeparateNamedSections()
LLVM_ABI bool getEnableNoInfsFPMath()
LLVM_ABI bool getEnableNoNaNsFPMath()
LLVM_ABI std::optional< bool > getExplicitDataSections()
LLVM_ABI ThreadModel::Model getThreadModel()
LLVM_ABI bool getXCOFFTracebackTable()
LLVM_ABI bool getIgnoreXCOFFVisibility()
LLVM_ABI bool getDisableIntegratedAS()
LLVM_ABI bool getUseCtors()
LLVM_ABI llvm::DebuggerKind getDebuggerTuningOpt()
LLVM_ABI std::vector< std::string > getMAttrs()
LLVM_ABI void setFunctionAttributes(StringRef CPU, StringRef Features, Function &F)
Set function attributes of function F based on CPU, Features, and command line flags.
LLVM_ABI llvm::BasicBlockSection getBBSectionsMode(llvm::TargetOptions &Options)
LLVM_ABI TargetOptions InitTargetOptionsFromCodeGenFlags(const llvm::Triple &TheTriple)
Common utility function tightly tied to the options listed here.
LLVM_ABI std::string getBBSections()
LLVM_ABI std::optional< bool > getExplicitEnableTLSDESC()
LLVM_ABI unsigned getAlignLoops()
LLVM_ABI std::optional< Reloc::Model > getExplicitRelocModel()
LLVM_ABI bool getEnableAIXExtendedAltivecABI()
LLVM_ABI bool getXRayFunctionIndex()
LLVM_ABI llvm::ExceptionHandling getExceptionModel()
LLVM_ABI bool getEmitCallSiteInfo()
LLVM_ABI std::optional< bool > getExplicitEmulatedTLS()
LLVM_ABI MCTargetOptions InitMCTargetOptionsFromFlags()
LLVM_ABI StringMap< bool, MallocAllocator > getHostCPUFeatures()
getHostCPUFeatures - Get the LLVM names for the host CPU features.
Definition Host.cpp:2422
LLVM_ABI StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition Host.cpp:1978
This is an optimization pass for GlobalISel generic memory operations.
FramePointerKind
Definition CodeGen.h:118
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:98
ExceptionHandling
Definition CodeGen.h:53
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:56
@ None
No exception support.
Definition CodeGen.h:54
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:55
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:58
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:59
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1305
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:111
SwiftAsyncFramePointerMode
Indicates when and how the Swift async frame pointer bit should be set.
@ DeploymentBased
Determine whether to set the bit statically or dynamically based on the deployment target.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
BasicBlockSection
EABI
Definition CodeGen.h:73
DebuggerKind
Identify a debugger for "tuning" the debug info.
@ SCE
Tune debug info for SCE targets (e.g. PS4).
@ DBX
Tune debug info for dbx.
@ Default
No specific tuning requested.
@ GDB
Tune debug info for gdb.
@ LLDB
Tune debug info for lldb.
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
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.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Create this object with static storage to register mc-related command line options.