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
17#include "llvm/ADT/Statistic.h"
19#include "llvm/ADT/StringRef.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/Module.h"
28#include "llvm/Support/Path.h"
35#include <cassert>
36#include <memory>
37#include <optional>
38#include <system_error>
39
40using namespace llvm;
41
42#define CGOPT(TY, NAME) \
43 static cl::opt<TY> *NAME##View; \
44 TY codegen::get##NAME() { \
45 assert(NAME##View && "Flag not registered."); \
46 return *NAME##View; \
47 }
48
49#define CGLIST(TY, NAME) \
50 static cl::list<TY> *NAME##View; \
51 std::vector<TY> codegen::get##NAME() { \
52 assert(NAME##View && "Flag not registered."); \
53 return *NAME##View; \
54 }
55
56// Temporary macro for incremental transition to std::optional.
57#define CGOPT_EXP(TY, NAME) \
58 CGOPT(TY, NAME) \
59 std::optional<TY> codegen::getExplicit##NAME() { \
60 if (NAME##View->getNumOccurrences()) { \
61 TY res = *NAME##View; \
62 return res; \
63 } \
64 return std::nullopt; \
65 }
66
67CGOPT(std::string, MArch)
68CGOPT(std::string, MCPU)
69CGLIST(std::string, MAttrs)
70CGOPT_EXP(Reloc::Model, RelocModel)
73CGOPT_EXP(uint64_t, LargeDataThreshold)
74CGOPT(ExceptionHandling, ExceptionModel)
76CGOPT(FramePointerKind, FramePointerUsage)
77CGOPT(bool, EnableNoInfsFPMath)
78CGOPT(bool, EnableNoNaNsFPMath)
79CGOPT(bool, EnableNoSignedZerosFPMath)
80CGOPT(bool, EnableNoTrappingFPMath)
81CGOPT(bool, EnableAIXExtendedAltivecABI)
84CGOPT(bool, EnableHonorSignDependentRoundingFPMath)
85CGOPT(FloatABI::ABIType, FloatABIForCalls)
87CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
88CGOPT(bool, DontPlaceZerosInBSS)
89CGOPT(bool, EnableGuaranteedTailCallOpt)
90CGOPT(bool, DisableTailCalls)
91CGOPT(bool, StackSymbolOrdering)
92CGOPT(bool, StackRealign)
93CGOPT(std::string, TrapFuncName)
94CGOPT(bool, UseCtors)
95CGOPT(bool, DisableIntegratedAS)
96CGOPT_EXP(bool, DataSections)
97CGOPT_EXP(bool, FunctionSections)
98CGOPT(bool, IgnoreXCOFFVisibility)
99CGOPT(bool, XCOFFTracebackTable)
100CGOPT(bool, EnableBBAddrMap)
101CGOPT(std::string, BBSections)
102CGOPT(unsigned, TLSSize)
103CGOPT_EXP(bool, EmulatedTLS)
104CGOPT_EXP(bool, EnableTLSDESC)
105CGOPT(bool, UniqueSectionNames)
106CGOPT(bool, UniqueBasicBlockSectionNames)
107CGOPT(bool, SeparateNamedSections)
108CGOPT(EABI, EABIVersion)
109CGOPT(DebuggerKind, DebuggerTuningOpt)
111CGOPT(bool, EnableStackSizeSection)
112CGOPT(bool, EnableAddrsig)
113CGOPT(bool, EnableCallGraphSection)
114CGOPT(bool, EmitCallSiteInfo)
116CGOPT(bool, EnableStaticDataPartitioning)
117CGOPT(bool, EnableDebugEntryValues)
118CGOPT(bool, ForceDwarfFrameSection)
119CGOPT(bool, XRayFunctionIndex)
120CGOPT(bool, DebugStrictDwarf)
121CGOPT(unsigned, AlignLoops)
122CGOPT(bool, JMCInstrument)
123CGOPT(bool, XCOFFReadOnlyPointers)
125
126#define CGBINDOPT(NAME) \
127 do { \
128 NAME##View = std::addressof(NAME); \
129 } while (0)
130
132 static cl::opt<std::string> MArch(
133 "march", cl::desc("Architecture to generate code for (see --version)"));
134 CGBINDOPT(MArch);
135
136 static cl::opt<std::string> MCPU(
137 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
138 cl::value_desc("cpu-name"), cl::init(""));
139 CGBINDOPT(MCPU);
140
141 static cl::list<std::string> MAttrs(
142 "mattr", cl::CommaSeparated,
143 cl::desc("Target specific attributes (-mattr=help for details)"),
144 cl::value_desc("a1,+a2,-a3,..."));
145 CGBINDOPT(MAttrs);
146
147 static cl::opt<Reloc::Model> RelocModel(
148 "relocation-model", cl::desc("Choose relocation model"),
150 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
151 clEnumValN(Reloc::PIC_, "pic",
152 "Fully relocatable, position independent code"),
153 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
154 "Relocatable external references, non-relocatable code"),
156 Reloc::ROPI, "ropi",
157 "Code and read-only data relocatable, accessed PC-relative"),
159 Reloc::RWPI, "rwpi",
160 "Read-write data relocatable, accessed relative to static base"),
161 clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
162 "Combination of ropi and rwpi")));
163 CGBINDOPT(RelocModel);
164
166 "thread-model", cl::desc("Choose threading model"),
169 clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"),
170 clEnumValN(ThreadModel::Single, "single", "Single thread model")));
172
174 "code-model", cl::desc("Choose code model"),
175 cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
176 clEnumValN(CodeModel::Small, "small", "Small code model"),
177 clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
178 clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
179 clEnumValN(CodeModel::Large, "large", "Large code model")));
181
182 static cl::opt<uint64_t> LargeDataThreshold(
183 "large-data-threshold",
184 cl::desc("Choose large data threshold for x86_64 medium code model"),
185 cl::init(0));
186 CGBINDOPT(LargeDataThreshold);
187
188 static cl::opt<ExceptionHandling> ExceptionModel(
189 "exception-model", cl::desc("exception model"),
193 "default exception handling model"),
195 "DWARF-like CFI based exception handling"),
197 "SjLj exception handling"),
198 clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
200 "Windows exception model"),
202 "WebAssembly exception handling")));
203 CGBINDOPT(ExceptionModel);
204
205 static cl::opt<CodeGenFileType> FileType(
207 cl::desc(
208 "Choose a file type (not all types are supported by all targets):"),
210 "Emit an assembly ('.s') file"),
212 "Emit a native object ('.o') file"),
214 "Emit nothing, for performance testing")));
215 CGBINDOPT(FileType);
216
217 static cl::opt<FramePointerKind> FramePointerUsage(
218 "frame-pointer",
219 cl::desc("Specify frame pointer elimination optimization"),
223 "Disable frame pointer elimination"),
225 "Disable frame pointer elimination for non-leaf frame but "
226 "reserve the register in leaf functions"),
227 clEnumValN(FramePointerKind::NonLeafNoReserve, "non-leaf-no-reserve",
228 "Disable frame pointer elimination for non-leaf frame"),
230 "Enable frame pointer elimination, but reserve the frame "
231 "pointer register"),
233 "Enable frame pointer elimination")));
234 CGBINDOPT(FramePointerUsage);
235
236 static cl::opt<bool> EnableNoInfsFPMath(
237 "enable-no-infs-fp-math",
238 cl::desc("Enable FP math optimizations that assume no +-Infs"),
239 cl::init(false));
240 CGBINDOPT(EnableNoInfsFPMath);
241
242 static cl::opt<bool> EnableNoNaNsFPMath(
243 "enable-no-nans-fp-math",
244 cl::desc("Enable FP math optimizations that assume no NaNs"),
245 cl::init(false));
246 CGBINDOPT(EnableNoNaNsFPMath);
247
248 static cl::opt<bool> EnableNoSignedZerosFPMath(
249 "enable-no-signed-zeros-fp-math",
250 cl::desc("Enable FP math optimizations that assume "
251 "the sign of 0 is insignificant"),
252 cl::init(false));
253 CGBINDOPT(EnableNoSignedZerosFPMath);
254
255 static cl::opt<bool> EnableNoTrappingFPMath(
256 "enable-no-trapping-fp-math",
257 cl::desc("Enable setting the FP exceptions build "
258 "attribute not to use exceptions"),
259 cl::init(false));
260 CGBINDOPT(EnableNoTrappingFPMath);
261
262 static const auto DenormFlagEnumOptions = cl::values(
263 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
264 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
265 "the sign of a flushed-to-zero number is preserved "
266 "in the sign of 0"),
267 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
268 "denormals are flushed to positive zero"),
270 "denormals have unknown treatment"));
271
272 // FIXME: Doesn't have way to specify separate input and output modes.
273 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
274 "denormal-fp-math",
275 cl::desc("Select which denormal numbers the code is permitted to require"),
277 DenormFlagEnumOptions);
278 CGBINDOPT(DenormalFPMath);
279
280 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
281 "denormal-fp-math-f32",
282 cl::desc("Select which denormal numbers the code is permitted to require for float"),
284 DenormFlagEnumOptions);
285 CGBINDOPT(DenormalFP32Math);
286
287 static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(
288 "enable-sign-dependent-rounding-fp-math", cl::Hidden,
289 cl::desc("Force codegen to assume rounding mode can change dynamically"),
290 cl::init(false));
291 CGBINDOPT(EnableHonorSignDependentRoundingFPMath);
292
293 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
294 "float-abi", cl::desc("Choose float ABI type"),
297 "Target default float ABI type"),
299 "Soft float ABI (implied by -soft-float)"),
301 "Hard float ABI (uses FP registers)")));
302 CGBINDOPT(FloatABIForCalls);
303
305 "fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),
309 "Fuse FP ops whenever profitable"),
310 clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),
312 "Only fuse FP ops when the result won't be affected.")));
313 CGBINDOPT(FuseFPOps);
314
315 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
316 "swift-async-fp",
317 cl::desc("Determine when the Swift async frame pointer should be set"),
320 "Determine based on deployment target"),
322 "Always set the bit"),
324 "Never set the bit")));
325 CGBINDOPT(SwiftAsyncFramePointer);
326
327 static cl::opt<bool> DontPlaceZerosInBSS(
328 "nozero-initialized-in-bss",
329 cl::desc("Don't place zero-initialized symbols into bss section"),
330 cl::init(false));
331 CGBINDOPT(DontPlaceZerosInBSS);
332
333 static cl::opt<bool> EnableAIXExtendedAltivecABI(
334 "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
335 cl::init(false));
336 CGBINDOPT(EnableAIXExtendedAltivecABI);
337
338 static cl::opt<bool> EnableGuaranteedTailCallOpt(
339 "tailcallopt",
340 cl::desc(
341 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
342 cl::init(false));
343 CGBINDOPT(EnableGuaranteedTailCallOpt);
344
345 static cl::opt<bool> DisableTailCalls(
346 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
347 CGBINDOPT(DisableTailCalls);
348
349 static cl::opt<bool> StackSymbolOrdering(
350 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
351 cl::init(true));
352 CGBINDOPT(StackSymbolOrdering);
353
354 static cl::opt<bool> StackRealign(
355 "stackrealign",
356 cl::desc("Force align the stack to the minimum alignment"),
357 cl::init(false));
358 CGBINDOPT(StackRealign);
359
360 static cl::opt<std::string> TrapFuncName(
361 "trap-func", cl::Hidden,
362 cl::desc("Emit a call to trap function rather than a trap instruction"),
363 cl::init(""));
364 CGBINDOPT(TrapFuncName);
365
366 static cl::opt<bool> UseCtors("use-ctors",
367 cl::desc("Use .ctors instead of .init_array."),
368 cl::init(false));
369 CGBINDOPT(UseCtors);
370
371 static cl::opt<bool> DataSections(
372 "data-sections", cl::desc("Emit data into separate sections"),
373 cl::init(false));
374 CGBINDOPT(DataSections);
375
376 static cl::opt<bool> FunctionSections(
377 "function-sections", cl::desc("Emit functions into separate sections"),
378 cl::init(false));
379 CGBINDOPT(FunctionSections);
380
381 static cl::opt<bool> IgnoreXCOFFVisibility(
382 "ignore-xcoff-visibility",
383 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
384 "all symbols 'unspecified' visibility in XCOFF object file"),
385 cl::init(false));
386 CGBINDOPT(IgnoreXCOFFVisibility);
387
388 static cl::opt<bool> XCOFFTracebackTable(
389 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
390 cl::init(true));
391 CGBINDOPT(XCOFFTracebackTable);
392
393 static cl::opt<bool> EnableBBAddrMap(
394 "basic-block-address-map",
395 cl::desc("Emit the basic block address map section"), cl::init(false));
396 CGBINDOPT(EnableBBAddrMap);
397
398 static cl::opt<std::string> BBSections(
399 "basic-block-sections",
400 cl::desc("Emit basic blocks into separate sections"),
401 cl::value_desc("all | <function list (file)> | labels | none"),
402 cl::init("none"));
403 CGBINDOPT(BBSections);
404
405 static cl::opt<unsigned> TLSSize(
406 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
407 CGBINDOPT(TLSSize);
408
409 static cl::opt<bool> EmulatedTLS(
410 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
411 CGBINDOPT(EmulatedTLS);
412
413 static cl::opt<bool> EnableTLSDESC(
414 "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
415 cl::init(false));
416 CGBINDOPT(EnableTLSDESC);
417
418 static cl::opt<bool> UniqueSectionNames(
419 "unique-section-names", cl::desc("Give unique names to every section"),
420 cl::init(true));
421 CGBINDOPT(UniqueSectionNames);
422
423 static cl::opt<bool> UniqueBasicBlockSectionNames(
424 "unique-basic-block-section-names",
425 cl::desc("Give unique names to every basic block section"),
426 cl::init(false));
427 CGBINDOPT(UniqueBasicBlockSectionNames);
428
429 static cl::opt<bool> SeparateNamedSections(
430 "separate-named-sections",
431 cl::desc("Use separate unique sections for named sections"),
432 cl::init(false));
433 CGBINDOPT(SeparateNamedSections);
434
435 static cl::opt<EABI> EABIVersion(
436 "meabi", cl::desc("Set EABI type (default depends on triple):"),
439 clEnumValN(EABI::Default, "default", "Triple default EABI version"),
440 clEnumValN(EABI::EABI4, "4", "EABI version 4"),
441 clEnumValN(EABI::EABI5, "5", "EABI version 5"),
442 clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
443 CGBINDOPT(EABIVersion);
444
445 static cl::opt<DebuggerKind> DebuggerTuningOpt(
446 "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
449 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
450 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
451 clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
452 clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
453 CGBINDOPT(DebuggerTuningOpt);
454
456 "vector-library", cl::Hidden, cl::desc("Vector functions library"),
460 "No vector functions library"),
462 "Accelerate framework"),
463 clEnumValN(VectorLibrary::DarwinLibSystemM, "Darwin_libsystem_m",
464 "Darwin libsystem_m"),
466 "GLIBC Vector Math library"),
467 clEnumValN(VectorLibrary::MASSV, "MASSV", "IBM MASS vector library"),
468 clEnumValN(VectorLibrary::SVML, "SVML", "Intel SVML library"),
470 "SIMD Library for Evaluating Elementary Functions"),
472 "Arm Performance Libraries"),
474 "AMD vector math library")));
476
477 static cl::opt<bool> EnableStackSizeSection(
478 "stack-size-section",
479 cl::desc("Emit a section containing stack size metadata"),
480 cl::init(false));
481 CGBINDOPT(EnableStackSizeSection);
482
483 static cl::opt<bool> EnableAddrsig(
484 "addrsig", cl::desc("Emit an address-significance table"),
485 cl::init(false));
486 CGBINDOPT(EnableAddrsig);
487
488 static cl::opt<bool> EnableCallGraphSection(
489 "call-graph-section", cl::desc("Emit a call graph section"),
490 cl::init(false));
491 CGBINDOPT(EnableCallGraphSection);
492
493 static cl::opt<bool> EmitCallSiteInfo(
494 "emit-call-site-info",
495 cl::desc(
496 "Emit call site debug information, if debug information is enabled."),
497 cl::init(false));
498 CGBINDOPT(EmitCallSiteInfo);
499
500 static cl::opt<bool> EnableDebugEntryValues(
501 "debug-entry-values",
502 cl::desc("Enable debug info for the debug entry values."),
503 cl::init(false));
504 CGBINDOPT(EnableDebugEntryValues);
505
507 "split-machine-functions",
508 cl::desc("Split out cold basic blocks from machine functions based on "
509 "profile information"),
510 cl::init(false));
512
513 static cl::opt<bool> EnableStaticDataPartitioning(
514 "partition-static-data-sections",
515 cl::desc("Partition data sections using profile information."),
516 cl::init(false));
517 CGBINDOPT(EnableStaticDataPartitioning);
518
519 static cl::opt<bool> ForceDwarfFrameSection(
520 "force-dwarf-frame-section",
521 cl::desc("Always emit a debug frame section."), cl::init(false));
522 CGBINDOPT(ForceDwarfFrameSection);
523
524 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
525 cl::desc("Emit xray_fn_idx section"),
526 cl::init(true));
527 CGBINDOPT(XRayFunctionIndex);
528
529 static cl::opt<bool> DebugStrictDwarf(
530 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
531 CGBINDOPT(DebugStrictDwarf);
532
533 static cl::opt<unsigned> AlignLoops("align-loops",
534 cl::desc("Default alignment for loops"));
535 CGBINDOPT(AlignLoops);
536
537 static cl::opt<bool> JMCInstrument(
538 "enable-jmc-instrument",
539 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
540 cl::init(false));
541 CGBINDOPT(JMCInstrument);
542
543 static cl::opt<bool> XCOFFReadOnlyPointers(
544 "mxcoff-roptr",
545 cl::desc("When set to true, const objects with relocatable address "
546 "values are put into the RO data section."),
547 cl::init(false));
548 CGBINDOPT(XCOFFReadOnlyPointers);
549
550 static cl::opt<bool> DisableIntegratedAS(
551 "no-integrated-as", cl::desc("Disable integrated assembler"),
552 cl::init(false));
553 CGBINDOPT(DisableIntegratedAS);
554
556}
557
559 static cl::opt<SaveStatsMode> SaveStats(
560 "save-stats",
561 cl::desc(
562 "Save LLVM statistics to a file in the current directory"
563 "(`-save-stats`/`-save-stats=cwd`) or the directory of the output"
564 "file (`-save-stats=obj`). (default: cwd)"),
566 "Save to the current working directory"),
569 "Save to the output file directory")),
571 CGBINDOPT(SaveStats);
572}
573
576 if (getBBSections() == "all")
578 else if (getBBSections() == "none")
580 else {
583 if (!MBOrErr) {
584 errs() << "Error loading basic block sections function list file: "
585 << MBOrErr.getError().message() << "\n";
586 } else {
587 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
588 }
590 }
591}
592
593// Common utility function tightly tied to the options listed here. Initializes
594// a TargetOptions object with CodeGen flags and returns it.
598 Options.AllowFPOpFusion = getFuseFPOps();
599 Options.NoInfsFPMath = getEnableNoInfsFPMath();
600 Options.NoNaNsFPMath = getEnableNoNaNsFPMath();
601 Options.NoSignedZerosFPMath = getEnableNoSignedZerosFPMath();
602 Options.NoTrappingFPMath = getEnableNoTrappingFPMath();
603
604 Options.HonorSignDependentRoundingFPMathOption =
607 Options.FloatABIType = getFloatABIForCalls();
608 Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
609 Options.NoZerosInBSS = getDontPlaceZerosInBSS();
610 Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
611 Options.StackSymbolOrdering = getStackSymbolOrdering();
612 Options.UseInitArray = !getUseCtors();
613 Options.DisableIntegratedAS = getDisableIntegratedAS();
614 Options.DataSections =
615 getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
616 Options.FunctionSections = getFunctionSections();
617 Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
618 Options.XCOFFTracebackTable = getXCOFFTracebackTable();
619 Options.BBAddrMap = getEnableBBAddrMap();
620 Options.BBSections = getBBSectionsMode(Options);
621 Options.UniqueSectionNames = getUniqueSectionNames();
622 Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
623 Options.SeparateNamedSections = getSeparateNamedSections();
624 Options.TLSSize = getTLSSize();
625 Options.EmulatedTLS =
626 getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
627 Options.EnableTLSDESC =
628 getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());
629 Options.ExceptionModel = getExceptionModel();
630 Options.VecLib = getVectorLibrary();
631 Options.EmitStackSizeSection = getEnableStackSizeSection();
632 Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
633 Options.EnableStaticDataPartitioning = getEnableStaticDataPartitioning();
634 Options.EmitAddrsig = getEnableAddrsig();
635 Options.EmitCallGraphSection = getEnableCallGraphSection();
636 Options.EmitCallSiteInfo = getEmitCallSiteInfo();
637 Options.EnableDebugEntryValues = getEnableDebugEntryValues();
638 Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
639 Options.XRayFunctionIndex = getXRayFunctionIndex();
640 Options.DebugStrictDwarf = getDebugStrictDwarf();
641 Options.LoopAlignment = getAlignLoops();
642 Options.JMCInstrument = getJMCInstrument();
643 Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
644
646
647 Options.ThreadModel = getThreadModel();
648 Options.EABIVersion = getEABIVersion();
649 Options.DebuggerTuning = getDebuggerTuningOpt();
650 Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
651 return Options;
652}
653
654std::string codegen::getCPUStr() {
655 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
656 // this will set the CPU to an empty string which tells the target to
657 // pick a basic default.
658 if (getMCPU() == "native")
659 return std::string(sys::getHostCPUName());
660
661 return getMCPU();
662}
663
665 SubtargetFeatures Features;
666
667 // If user asked for the 'native' CPU, we need to autodetect features.
668 // This is necessary for x86 where the CPU might not support all the
669 // features the autodetected CPU name lists in the target. For example,
670 // not all Sandybridge processors support AVX.
671 if (getMCPU() == "native")
672 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
673 Features.AddFeature(Feature, IsEnabled);
674
675 for (auto const &MAttr : getMAttrs())
676 Features.AddFeature(MAttr);
677
678 return Features.getString();
679}
680
681std::vector<std::string> codegen::getFeatureList() {
682 SubtargetFeatures Features;
683
684 // If user asked for the 'native' CPU, we need to autodetect features.
685 // This is necessary for x86 where the CPU might not support all the
686 // features the autodetected CPU name lists in the target. For example,
687 // not all Sandybridge processors support AVX.
688 if (getMCPU() == "native")
689 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
690 Features.AddFeature(Feature, IsEnabled);
691
692 for (auto const &MAttr : getMAttrs())
693 Features.AddFeature(MAttr);
694
695 return Features.getFeatures();
696}
697
698void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
699 B.addAttribute(Name, Val ? "true" : "false");
700}
701
702#define HANDLE_BOOL_ATTR(CL, AttrName) \
703 do { \
704 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
705 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
706 } while (0)
707
708/// Set function attributes of function \p F based on CPU, Features, and command
709/// line flags.
711 Function &F) {
712 auto &Ctx = F.getContext();
713 AttributeList Attrs = F.getAttributes();
714 AttrBuilder NewAttrs(Ctx);
715
716 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
717 NewAttrs.addAttribute("target-cpu", CPU);
718 if (!Features.empty()) {
719 // Append the command line features to any that are already on the function.
720 StringRef OldFeatures =
721 F.getFnAttribute("target-features").getValueAsString();
722 if (OldFeatures.empty())
723 NewAttrs.addAttribute("target-features", Features);
724 else {
725 SmallString<256> Appended(OldFeatures);
726 Appended.push_back(',');
727 Appended.append(Features);
728 NewAttrs.addAttribute("target-features", Appended);
729 }
730 }
731 if (FramePointerUsageView->getNumOccurrences() > 0 &&
732 !F.hasFnAttribute("frame-pointer")) {
734 NewAttrs.addAttribute("frame-pointer", "all");
736 NewAttrs.addAttribute("frame-pointer", "non-leaf");
738 NewAttrs.addAttribute("frame-pointer", "non-leaf-no-reserve");
740 NewAttrs.addAttribute("frame-pointer", "reserved");
742 NewAttrs.addAttribute("frame-pointer", "none");
743 }
744 if (DisableTailCallsView->getNumOccurrences() > 0)
745 NewAttrs.addAttribute("disable-tail-calls",
747 if (getStackRealign())
748 NewAttrs.addAttribute("stackrealign");
749
750 HANDLE_BOOL_ATTR(EnableNoInfsFPMathView, "no-infs-fp-math");
751 HANDLE_BOOL_ATTR(EnableNoNaNsFPMathView, "no-nans-fp-math");
752 HANDLE_BOOL_ATTR(EnableNoSignedZerosFPMathView, "no-signed-zeros-fp-math");
753
754 if (DenormalFPMathView->getNumOccurrences() > 0 &&
755 !F.hasFnAttribute("denormal-fp-math")) {
757
758 // FIXME: Command line flag should expose separate input/output modes.
759 NewAttrs.addAttribute("denormal-fp-math",
760 DenormalMode(DenormKind, DenormKind).str());
761 }
762
763 if (DenormalFP32MathView->getNumOccurrences() > 0 &&
764 !F.hasFnAttribute("denormal-fp-math-f32")) {
765 // FIXME: Command line flag should expose separate input/output modes.
767
768 NewAttrs.addAttribute(
769 "denormal-fp-math-f32",
770 DenormalMode(DenormKind, DenormKind).str());
771 }
772
773 if (TrapFuncNameView->getNumOccurrences() > 0)
774 for (auto &B : F)
775 for (auto &I : B)
776 if (auto *Call = dyn_cast<CallInst>(&I))
777 if (const auto *F = Call->getCalledFunction())
778 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
779 F->getIntrinsicID() == Intrinsic::trap)
780 Call->addFnAttr(
781 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
782
783 // Let NewAttrs override Attrs.
784 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
785}
786
787/// Set function attributes of functions in Module M based on CPU,
788/// Features, and command line flags.
790 Module &M) {
791 for (Function &F : M)
792 setFunctionAttributes(CPU, Features, F);
793}
794
797 CodeGenOptLevel OptLevel) {
798 Triple TheTriple(TargetTriple);
799 std::string Error;
800 const auto *TheTarget =
802 if (!TheTarget)
804 auto *Target = TheTarget->createTargetMachine(
808 OptLevel);
809 if (!Target)
811 Twine("could not allocate target machine for ") +
812 TargetTriple);
813 return std::unique_ptr<TargetMachine>(Target);
814}
815
818 return;
819
821}
822
824 auto SaveStatsValue = getSaveStats();
825 if (SaveStatsValue == codegen::SaveStatsMode::None)
826 return 0;
827
828 SmallString<128> StatsFilename;
829 if (SaveStatsValue == codegen::SaveStatsMode::Obj) {
830 StatsFilename = OutputFilename;
832 } else {
833 assert(SaveStatsValue == codegen::SaveStatsMode::Cwd &&
834 "Should have been a valid --save-stats value");
835 }
836
838 llvm::sys::path::append(StatsFilename, BaseName);
839 llvm::sys::path::replace_extension(StatsFilename, "stats");
840
841 auto FileFlags = llvm::sys::fs::OF_TextWithCRLF;
842 std::error_code EC;
843 auto StatsOS =
844 std::make_unique<llvm::raw_fd_ostream>(StatsFilename, EC, FileFlags);
845 if (EC) {
846 WithColor::error(errs(), ToolName)
847 << "Unable to open statistics file: " << EC.message() << "\n";
848 return 1;
849 }
850
852 return 0;
853}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:54
#define I(x, y, z)
Definition MD5.cpp:57
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
This file defines the SmallString class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
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:1212
bool hasDefaultDataSections() const
Tests whether the target uses -data-sections as default.
Definition Triple.h:1217
bool hasDefaultEmulatedTLS() const
Tests whether the target uses emulated TLS as default.
Definition Triple.h:1206
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI raw_ostream & error()
Convenience method for printing "error: " to stderr.
Definition WithColor.cpp:83
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 llvm::VectorLibrary getVectorLibrary()
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 void MaybeEnableStatistics()
Conditionally enables the collection of LLVM statistics during the tool run, based on the value of th...
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 SaveStatsMode getSaveStats()
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 int MaybeSaveStatistics(StringRef OutputFilename, StringRef ToolName)
Conditionally saves the collected LLVM statistics to the received output file, based on the value of ...
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()
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:764
LLVM_ABI void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
Definition Path.cpp:475
LLVM_ABI void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition Path.cpp:481
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:578
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:457
LLVM_ABI StringMap< bool, MallocAllocator > getHostCPUFeatures()
getHostCPUFeatures - Get the LLVM names for the host CPU features.
Definition Host.cpp:2525
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.
Definition Types.h:26
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
LLVM_ABI void EnableStatistics(bool DoPrintOnExit=true)
Enable the collection and printing of statistics.
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
VectorLibrary
List of known vector-functions libraries.
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.
LLVM_ABI void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
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.