LLVM 24.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"
29#include "llvm/Support/Path.h"
36#include <cassert>
37#include <memory>
38#include <optional>
39#include <system_error>
40
41using namespace llvm;
42
43#define CGOPT(TY, NAME) \
44 static cl::opt<TY> *NAME##View; \
45 TY codegen::get##NAME() { \
46 assert(NAME##View && "Flag not registered."); \
47 return *NAME##View; \
48 }
49
50#define CGLIST(TY, NAME) \
51 static cl::list<TY> *NAME##View; \
52 std::vector<TY> codegen::get##NAME() { \
53 assert(NAME##View && "Flag not registered."); \
54 return *NAME##View; \
55 }
56
57// Temporary macro for incremental transition to std::optional.
58#define CGOPT_EXP(TY, NAME) \
59 CGOPT(TY, NAME) \
60 std::optional<TY> codegen::getExplicit##NAME() { \
61 if (NAME##View->getNumOccurrences()) { \
62 TY res = *NAME##View; \
63 return res; \
64 } \
65 return std::nullopt; \
66 }
67
68CGOPT(std::string, MArch)
69CGOPT(std::string, MCPU)
70CGOPT(std::string, MTune)
71CGLIST(std::string, MAttrs)
72CGOPT_EXP(Reloc::Model, RelocModel)
75CGOPT_EXP(uint64_t, LargeDataThreshold)
76CGOPT(ExceptionHandling, ExceptionModel)
78CGOPT(FramePointerKind, FramePointerUsage)
79CGOPT(bool, EnableAIXExtendedAltivecABI)
82CGOPT(FloatABI::ABIType, FloatABIForCalls)
83CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
84CGOPT(bool, DontPlaceZerosInBSS)
85CGOPT(bool, EnableGuaranteedTailCallOpt)
86CGOPT(bool, DisableTailCalls)
87CGOPT(bool, StackSymbolOrdering)
88CGOPT(bool, StackRealign)
89CGOPT(std::string, TrapFuncName)
90CGOPT(bool, UseCtors)
91CGOPT_EXP(bool, DataSections)
92CGOPT_EXP(bool, FunctionSections)
93CGOPT(bool, IgnoreXCOFFVisibility)
94CGOPT(bool, XCOFFTracebackTable)
95CGOPT(bool, EnableBBAddrMap)
96CGOPT(std::string, BBSections)
97CGOPT(unsigned, TLSSize)
98CGOPT_EXP(bool, EmulatedTLS)
99CGOPT_EXP(bool, EnableTLSDESC)
100CGOPT(bool, UniqueSectionNames)
101CGOPT(bool, UniqueBasicBlockSectionNames)
102CGOPT(bool, SeparateNamedSections)
103CGOPT(EABI, EABIVersion)
104CGOPT(DebuggerKind, DebuggerTuningOpt)
106CGOPT(bool, EnableStackSizeSection)
107CGOPT(bool, EnableAddrsig)
108CGOPT(bool, EnableCallGraphSection)
109CGOPT(bool, EmitCallSiteInfo)
111CGOPT(bool, EnableStaticDataPartitioning)
112CGOPT(bool, EnableDebugEntryValues)
113CGOPT(bool, ForceDwarfFrameSection)
114CGOPT(bool, XRayFunctionIndex)
115CGOPT(bool, DebugStrictDwarf)
116CGOPT(unsigned, AlignLoops)
117CGOPT(bool, JMCInstrument)
118CGOPT(bool, XCOFFReadOnlyPointers)
120
121#define CGBINDOPT(NAME) \
122 do { \
123 NAME##View = std::addressof(NAME); \
124 } while (0)
125
127 static cl::opt<std::string> MArch(
128 "march", cl::desc("Architecture to generate code for (see --version)"));
129 CGBINDOPT(MArch);
130
131 static cl::opt<std::string> MCPU(
132 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
133 cl::value_desc("cpu-name"), cl::init(""));
134 CGBINDOPT(MCPU);
135
136 static cl::list<std::string> MAttrs(
137 "mattr", cl::CommaSeparated,
138 cl::desc("Target specific attributes (-mattr=help for details)"),
139 cl::value_desc("a1,+a2,-a3,..."));
140 CGBINDOPT(MAttrs);
141
142 static cl::opt<Reloc::Model> RelocModel(
143 "relocation-model", cl::desc("Choose relocation model"),
145 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
146 clEnumValN(Reloc::PIC_, "pic",
147 "Fully relocatable, position independent code"),
148 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
149 "Relocatable external references, non-relocatable code"),
151 Reloc::ROPI, "ropi",
152 "Code and read-only data relocatable, accessed PC-relative"),
154 Reloc::RWPI, "rwpi",
155 "Read-write data relocatable, accessed relative to static base"),
156 clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
157 "Combination of ropi and rwpi")));
158 CGBINDOPT(RelocModel);
159
161 "thread-model", cl::desc("Choose threading model"),
164 clEnumValN(llvm::ThreadModel::POSIX, "posix", "POSIX thread model"),
166 "Single thread model")));
168
170 "code-model", cl::desc("Choose code model"),
171 cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
172 clEnumValN(CodeModel::Small, "small", "Small code model"),
173 clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
174 clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
175 clEnumValN(CodeModel::Large, "large", "Large code model")));
177
178 static cl::opt<uint64_t> LargeDataThreshold(
179 "large-data-threshold",
180 cl::desc("Choose large data threshold for x86_64 medium code model"),
181 cl::init(0));
182 CGBINDOPT(LargeDataThreshold);
183
184 static cl::opt<ExceptionHandling> ExceptionModel(
185 "exception-model", cl::desc("exception model"),
189 "default exception handling model"),
191 "DWARF-like CFI based exception handling"),
193 "SjLj exception handling"),
194 clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
196 "Windows exception model"),
198 "WebAssembly exception handling")));
199 CGBINDOPT(ExceptionModel);
200
201 static cl::opt<CodeGenFileType> FileType(
203 cl::desc(
204 "Choose a file type (not all types are supported by all targets):"),
206 "Emit an assembly ('.s') file"),
208 "Emit a native object ('.o') file"),
210 "Emit nothing, for performance testing")));
211 CGBINDOPT(FileType);
212
213 static cl::opt<FramePointerKind> FramePointerUsage(
214 "frame-pointer",
215 cl::desc("Specify frame pointer elimination optimization"),
219 "Disable frame pointer elimination"),
221 "Disable frame pointer elimination for non-leaf frame but "
222 "reserve the register in leaf functions"),
223 clEnumValN(FramePointerKind::NonLeafNoReserve, "non-leaf-no-reserve",
224 "Disable frame pointer elimination for non-leaf frame"),
226 "Enable frame pointer elimination, but reserve the frame "
227 "pointer register"),
229 "Enable frame pointer elimination")));
230 CGBINDOPT(FramePointerUsage);
231
232 static const auto DenormFlagEnumOptions = cl::values(
233 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
234 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
235 "the sign of a flushed-to-zero number is preserved "
236 "in the sign of 0"),
237 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
238 "denormals are flushed to positive zero"),
240 "denormals have unknown treatment"));
241
242 // FIXME: Doesn't have way to specify separate input and output modes.
243 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
244 "denormal-fp-math",
245 cl::desc("Select which denormal numbers the code is permitted to require"),
247 DenormFlagEnumOptions);
248 CGBINDOPT(DenormalFPMath);
249
250 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
251 "denormal-fp-math-f32",
252 cl::desc("Select which denormal numbers the code is permitted to require for float"),
254 DenormFlagEnumOptions);
255 CGBINDOPT(DenormalFP32Math);
256
257 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
258 "float-abi", cl::desc("Choose float ABI type"),
261 "Target default float ABI type"),
263 "Soft float ABI (implied by -soft-float)"),
265 "Hard float ABI (uses FP registers)")));
266 CGBINDOPT(FloatABIForCalls);
267
268 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
269 "swift-async-fp",
270 cl::desc("Determine when the Swift async frame pointer should be set"),
273 "Determine based on deployment target"),
275 "Always set the bit"),
277 "Never set the bit")));
278 CGBINDOPT(SwiftAsyncFramePointer);
279
280 static cl::opt<bool> DontPlaceZerosInBSS(
281 "nozero-initialized-in-bss",
282 cl::desc("Don't place zero-initialized symbols into bss section"),
283 cl::init(false));
284 CGBINDOPT(DontPlaceZerosInBSS);
285
286 static cl::opt<bool> EnableAIXExtendedAltivecABI(
287 "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
288 cl::init(false));
289 CGBINDOPT(EnableAIXExtendedAltivecABI);
290
291 static cl::opt<bool> EnableGuaranteedTailCallOpt(
292 "tailcallopt",
293 cl::desc(
294 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
295 cl::init(false));
296 CGBINDOPT(EnableGuaranteedTailCallOpt);
297
298 static cl::opt<bool> DisableTailCalls(
299 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
300 CGBINDOPT(DisableTailCalls);
301
302 static cl::opt<bool> StackSymbolOrdering(
303 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
304 cl::init(true));
305 CGBINDOPT(StackSymbolOrdering);
306
307 static cl::opt<bool> StackRealign(
308 "stackrealign",
309 cl::desc("Force align the stack to the minimum alignment"),
310 cl::init(false));
311 CGBINDOPT(StackRealign);
312
313 static cl::opt<std::string> TrapFuncName(
314 "trap-func", cl::Hidden,
315 cl::desc("Emit a call to trap function rather than a trap instruction"),
316 cl::init(""));
317 CGBINDOPT(TrapFuncName);
318
319 static cl::opt<bool> UseCtors("use-ctors",
320 cl::desc("Use .ctors instead of .init_array."),
321 cl::init(false));
322 CGBINDOPT(UseCtors);
323
324 static cl::opt<bool> DataSections(
325 "data-sections", cl::desc("Emit data into separate sections"),
326 cl::init(false));
327 CGBINDOPT(DataSections);
328
329 static cl::opt<bool> FunctionSections(
330 "function-sections", cl::desc("Emit functions into separate sections"),
331 cl::init(false));
332 CGBINDOPT(FunctionSections);
333
334 static cl::opt<bool> IgnoreXCOFFVisibility(
335 "ignore-xcoff-visibility",
336 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
337 "all symbols 'unspecified' visibility in XCOFF object file"),
338 cl::init(false));
339 CGBINDOPT(IgnoreXCOFFVisibility);
340
341 static cl::opt<bool> XCOFFTracebackTable(
342 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
343 cl::init(true));
344 CGBINDOPT(XCOFFTracebackTable);
345
346 static cl::opt<bool> EnableBBAddrMap(
347 "basic-block-address-map",
348 cl::desc("Emit the basic block address map section"), cl::init(false));
349 CGBINDOPT(EnableBBAddrMap);
350
351 static cl::opt<std::string> BBSections(
352 "basic-block-sections",
353 cl::desc("Emit basic blocks into separate sections"),
354 cl::value_desc("all | <function list (file)> | labels | none"),
355 cl::init("none"));
356 CGBINDOPT(BBSections);
357
358 static cl::opt<unsigned> TLSSize(
359 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
360 CGBINDOPT(TLSSize);
361
362 static cl::opt<bool> EmulatedTLS(
363 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
364 CGBINDOPT(EmulatedTLS);
365
366 static cl::opt<bool> EnableTLSDESC(
367 "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
368 cl::init(false));
369 CGBINDOPT(EnableTLSDESC);
370
371 static cl::opt<bool> UniqueSectionNames(
372 "unique-section-names", cl::desc("Give unique names to every section"),
373 cl::init(true));
374 CGBINDOPT(UniqueSectionNames);
375
376 static cl::opt<bool> UniqueBasicBlockSectionNames(
377 "unique-basic-block-section-names",
378 cl::desc("Give unique names to every basic block section"),
379 cl::init(false));
380 CGBINDOPT(UniqueBasicBlockSectionNames);
381
382 static cl::opt<bool> SeparateNamedSections(
383 "separate-named-sections",
384 cl::desc("Use separate unique sections for named sections"),
385 cl::init(false));
386 CGBINDOPT(SeparateNamedSections);
387
388 static cl::opt<EABI> EABIVersion(
389 "meabi", cl::desc("Set EABI type (default depends on triple):"),
392 clEnumValN(EABI::Default, "default", "Triple default EABI version"),
393 clEnumValN(EABI::EABI4, "4", "EABI version 4"),
394 clEnumValN(EABI::EABI5, "5", "EABI version 5"),
395 clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
396 CGBINDOPT(EABIVersion);
397
398 static cl::opt<DebuggerKind> DebuggerTuningOpt(
399 "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
402 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
403 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
404 clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
405 clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
406 CGBINDOPT(DebuggerTuningOpt);
407
409 "vector-library", cl::Hidden, cl::desc("Vector functions library"),
413 "No vector functions library"),
415 "Accelerate framework"),
416 clEnumValN(VectorLibrary::DarwinLibSystemM, "Darwin_libsystem_m",
417 "Darwin libsystem_m"),
419 "GLIBC Vector Math library"),
420 clEnumValN(VectorLibrary::MASSV, "MASSV", "IBM MASS vector library"),
421 clEnumValN(VectorLibrary::SVML, "SVML", "Intel SVML library"),
423 "SIMD Library for Evaluating Elementary Functions"),
425 "Arm Performance Libraries"),
427 "AMD vector math library")));
429
430 static cl::opt<bool> EnableStackSizeSection(
431 "stack-size-section",
432 cl::desc("Emit a section containing stack size metadata"),
433 cl::init(false));
434 CGBINDOPT(EnableStackSizeSection);
435
436 static cl::opt<bool> EnableAddrsig(
437 "addrsig", cl::desc("Emit an address-significance table"),
438 cl::init(false));
439 CGBINDOPT(EnableAddrsig);
440
441 static cl::opt<bool> EnableCallGraphSection(
442 "call-graph-section", cl::desc("Emit a call graph section"),
443 cl::init(false));
444 CGBINDOPT(EnableCallGraphSection);
445
446 static cl::opt<bool> EmitCallSiteInfo(
447 "emit-call-site-info",
448 cl::desc(
449 "Emit call site debug information, if debug information is enabled."),
450 cl::init(false));
451 CGBINDOPT(EmitCallSiteInfo);
452
453 static cl::opt<bool> EnableDebugEntryValues(
454 "debug-entry-values",
455 cl::desc("Enable debug info for the debug entry values."),
456 cl::init(false));
457 CGBINDOPT(EnableDebugEntryValues);
458
460 "split-machine-functions",
461 cl::desc("Split out cold basic blocks from machine functions based on "
462 "profile information"),
463 cl::init(false));
465
466 static cl::opt<bool> EnableStaticDataPartitioning(
467 "partition-static-data-sections",
468 cl::desc("Partition data sections using profile information."),
469 cl::init(false));
470 CGBINDOPT(EnableStaticDataPartitioning);
471
472 static cl::opt<bool> ForceDwarfFrameSection(
473 "force-dwarf-frame-section",
474 cl::desc("Always emit a debug frame section."), cl::init(false));
475 CGBINDOPT(ForceDwarfFrameSection);
476
477 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
478 cl::desc("Emit xray_fn_idx section"),
479 cl::init(true));
480 CGBINDOPT(XRayFunctionIndex);
481
482 static cl::opt<bool> DebugStrictDwarf(
483 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
484 CGBINDOPT(DebugStrictDwarf);
485
486 static cl::opt<unsigned> AlignLoops("align-loops",
487 cl::desc("Default alignment for loops"));
488 CGBINDOPT(AlignLoops);
489
490 static cl::opt<bool> JMCInstrument(
491 "enable-jmc-instrument",
492 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
493 cl::init(false));
494 CGBINDOPT(JMCInstrument);
495
496 static cl::opt<bool> XCOFFReadOnlyPointers(
497 "mxcoff-roptr",
498 cl::desc("When set to true, const objects with relocatable address "
499 "values are put into the RO data section."),
500 cl::init(false));
501 CGBINDOPT(XCOFFReadOnlyPointers);
502
504}
505
507 static cl::opt<std::string> MTune(
508 "mtune",
509 cl::desc("Tune for a specific CPU microarchitecture (-mtune=help for "
510 "details)"),
511 cl::value_desc("tune-cpu-name"), cl::init(""));
512 CGBINDOPT(MTune);
513}
514
516 static cl::opt<SaveStatsMode> SaveStats(
517 "save-stats",
518 cl::desc(
519 "Save LLVM statistics to a file in the current directory"
520 "(`-save-stats`/`-save-stats=cwd`) or the directory of the output"
521 "file (`-save-stats=obj`). (default: cwd)"),
523 "Save to the current working directory"),
526 "Save to the output file directory")),
528 CGBINDOPT(SaveStats);
529}
530
533 if (getBBSections() == "all")
535 else if (getBBSections() == "none")
537 else {
540 if (!MBOrErr) {
541 errs() << "Error loading basic block sections function list file: "
542 << MBOrErr.getError().message() << "\n";
543 } else {
544 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
545 }
547 }
548}
549
550// Common utility function tightly tied to the options listed here. Initializes
551// a TargetOptions object with CodeGen flags and returns it.
555 Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
556 Options.NoZerosInBSS = getDontPlaceZerosInBSS();
557 Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
558 Options.StackSymbolOrdering = getStackSymbolOrdering();
559 Options.UseInitArray = !getUseCtors();
560 Options.DataSections =
561 getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
562 Options.FunctionSections = getFunctionSections();
563 Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
564 Options.XCOFFTracebackTable = getXCOFFTracebackTable();
565 Options.BBAddrMap = getEnableBBAddrMap();
566 Options.BBSections = getBBSectionsMode(Options);
567 Options.UniqueSectionNames = getUniqueSectionNames();
568 Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
569 Options.SeparateNamedSections = getSeparateNamedSections();
570 Options.TLSSize = getTLSSize();
571 Options.EmulatedTLS =
572 getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
573 Options.EnableTLSDESC =
574 getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());
575 Options.ExceptionModel = getExceptionModel();
576 Options.VecLib = getVectorLibrary();
577 Options.EmitStackSizeSection = getEnableStackSizeSection();
578 Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
579 Options.EnableStaticDataPartitioning = getEnableStaticDataPartitioning();
580 Options.EmitAddrsig = getEnableAddrsig();
581 Options.EmitCallGraphSection = getEnableCallGraphSection();
582 Options.EmitCallSiteInfo = getEmitCallSiteInfo();
583 Options.EnableDebugEntryValues = getEnableDebugEntryValues();
584 Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
585 Options.XRayFunctionIndex = getXRayFunctionIndex();
586 Options.DebugStrictDwarf = getDebugStrictDwarf();
587 Options.LoopAlignment = getAlignLoops();
588 Options.JMCInstrument = getJMCInstrument();
589 Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
590
592
593 Options.ThreadModel = getThreadModel();
594 Options.EABIVersion = getEABIVersion();
595 Options.DebuggerTuning = getDebuggerTuningOpt();
596 Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
597 return Options;
598}
599
600std::string codegen::getCPUStr() {
601 std::string MCPU = getMCPU();
602
603 // If user asked for the 'native' CPU, autodetect here. If auto-detection
604 // fails, this will set the CPU to an empty string which tells the target to
605 // pick a basic default.
606 if (MCPU == "native")
607 return std::string(sys::getHostCPUName());
608
609 return MCPU;
610}
611
613 std::string TuneCPU = getMTune();
614
615 // If user asked for the 'native' tune CPU, autodetect here. If auto-detection
616 // fails, this will set the tune CPU to an empty string which tells the target
617 // to pick a basic default.
618 if (TuneCPU == "native")
619 return std::string(sys::getHostCPUName());
620
621 return TuneCPU;
622}
623
625 SubtargetFeatures Features;
626
627 // If user asked for the 'native' CPU, we need to autodetect features.
628 // This is necessary for x86 where the CPU might not support all the
629 // features the autodetected CPU name lists in the target. For example,
630 // not all Sandybridge processors support AVX.
631 if (getMCPU() == "native")
632 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
633 Features.AddFeature(Feature, IsEnabled);
634
635 for (auto const &MAttr : getMAttrs())
636 Features.AddFeature(MAttr);
637
638 return Features.getString();
639}
640
641std::vector<std::string> codegen::getFeatureList() {
642 SubtargetFeatures Features;
643
644 // If user asked for the 'native' CPU, we need to autodetect features.
645 // This is necessary for x86 where the CPU might not support all the
646 // features the autodetected CPU name lists in the target. For example,
647 // not all Sandybridge processors support AVX.
648 if (getMCPU() == "native")
649 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
650 Features.AddFeature(Feature, IsEnabled);
651
652 for (auto const &MAttr : getMAttrs())
653 Features.AddFeature(MAttr);
654
655 return Features.getFeatures();
656}
657
658void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
659 B.addAttribute(Name, Val ? "true" : "false");
660}
661
662#define HANDLE_BOOL_ATTR(CL, AttrName) \
663 do { \
664 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
665 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
666 } while (0)
667
669 StringRef Features, StringRef TuneCPU) {
670 auto &Ctx = F.getContext();
671 AttributeList Attrs = F.getAttributes();
672 AttrBuilder NewAttrs(Ctx);
673
674 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
675 NewAttrs.addAttribute("target-cpu", CPU);
676 if (!TuneCPU.empty() && !F.hasFnAttribute("tune-cpu"))
677 NewAttrs.addAttribute("tune-cpu", TuneCPU);
678 if (!Features.empty()) {
679 // Append the command line features to any that are already on the function.
680 StringRef OldFeatures =
681 F.getFnAttribute("target-features").getValueAsString();
682 if (OldFeatures.empty())
683 NewAttrs.addAttribute("target-features", Features);
684 else {
685 SmallString<256> Appended(OldFeatures);
686 Appended.push_back(',');
687 Appended.append(Features);
688 NewAttrs.addAttribute("target-features", Appended);
689 }
690 }
691 if (FramePointerUsageView->getNumOccurrences() > 0 &&
692 !F.hasFnAttribute("frame-pointer")) {
694 NewAttrs.addAttribute("frame-pointer", "all");
696 NewAttrs.addAttribute("frame-pointer", "non-leaf");
698 NewAttrs.addAttribute("frame-pointer", "non-leaf-no-reserve");
700 NewAttrs.addAttribute("frame-pointer", "reserved");
702 NewAttrs.addAttribute("frame-pointer", "none");
703 }
704 if (DisableTailCallsView->getNumOccurrences() > 0)
705 NewAttrs.addAttribute("disable-tail-calls",
707 if (getStackRealign())
708 NewAttrs.addAttribute("stackrealign");
709
710 if ((DenormalFPMathView->getNumOccurrences() > 0 ||
711 DenormalFP32MathView->getNumOccurrences() > 0) &&
712 !F.hasFnAttribute(Attribute::DenormalFPEnv)) {
715
716 DenormalFPEnv FPEnv(DenormalMode{DenormKind, DenormKind},
717 DenormalMode{DenormKindF32, DenormKindF32});
718 // FIXME: Command line flag should expose separate input/output modes.
719 NewAttrs.addDenormalFPEnvAttr(FPEnv);
720 }
721
722 if (TrapFuncNameView->getNumOccurrences() > 0)
723 for (auto &B : F)
724 for (auto &I : B)
725 if (auto *Call = dyn_cast<CallInst>(&I))
726 if (const auto *F = Call->getCalledFunction())
727 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
728 F->getIntrinsicID() == Intrinsic::trap)
729 Call->addFnAttr(
730 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
731
732 // Let NewAttrs override Attrs.
733 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
734}
735
737 StringRef Features, StringRef TuneCPU) {
738 // Synthesize the "float-abi" module flag from the -float-abi option.
740 if (ABI != FloatABI::Default) {
741 if (auto *Existing =
742 dyn_cast_or_null<MDString>(M.getModuleFlag("float-abi"))) {
743 // The module already records a float ABI; -float-abi must not contradict
744 // it.
745 if (Existing->getString() != FloatABI::getABITypeName(ABI))
747 "-float-abi=" + FloatABI::getABITypeName(ABI) +
748 " conflicts with the \"float-abi\" module flag \"" +
749 Existing->getString() + "\"");
750 } else {
751 M.addModuleFlag(
752 Module::Error, "float-abi",
753 MDString::get(M.getContext(), FloatABI::getABITypeName(ABI)));
754 }
755 }
756
757 for (Function &F : M)
758 setFunctionAttributes(F, CPU, Features, TuneCPU);
759}
760
763 CodeGenOptLevel OptLevel) {
764 // lookupTarget may mutate the triple, so we need a copy.
765 Triple TheTriple(TargetTriple);
766 std::string Error;
767 const auto *TheTarget =
769 if (!TheTarget)
771 auto *Target = TheTarget->createTargetMachine(
775 OptLevel);
776 if (!Target)
778 Twine("could not allocate target machine for ") +
779 TheTriple.str());
780 return std::unique_ptr<TargetMachine>(Target);
781}
782
785 return;
786
788}
789
791 auto SaveStatsValue = getSaveStats();
792 if (SaveStatsValue == codegen::SaveStatsMode::None)
793 return 0;
794
795 SmallString<128> StatsFilename;
796 if (SaveStatsValue == codegen::SaveStatsMode::Obj) {
797 StatsFilename = OutputFilename;
799 } else {
800 assert(SaveStatsValue == codegen::SaveStatsMode::Cwd &&
801 "Should have been a valid --save-stats value");
802 }
803
805 llvm::sys::path::append(StatsFilename, BaseName);
806 llvm::sys::path::replace_extension(StatsFilename, "stats");
807
808 auto FileFlags = llvm::sys::fs::OF_TextWithCRLF;
809 std::error_code EC;
810 auto StatsOS =
811 std::make_unique<llvm::raw_fd_ostream>(StatsFilename, EC, FileFlags);
812 if (EC) {
813 WithColor::error(errs(), ToolName)
814 << "Unable to open statistics file: " << EC.message() << "\n";
815 return 1;
816 }
817
819 return 0;
820}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
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 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 LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:611
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:68
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
Definition Module.h:121
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)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
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:48
bool hasDefaultTLSDESC() const
True if the target uses TLSDESC by default.
Definition Triple.h:1310
bool hasDefaultDataSections() const
Tests whether the target uses -data-sections as default.
Definition Triple.h:1315
const std::string & str() const
Definition Triple.h:579
bool hasDefaultEmulatedTLS() const
Tests whether the target uses emulated TLS as default.
Definition Triple.h:1304
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:84
CallInst * Call
StringRef getABITypeName(ABIType ABI)
Returns the string spelling used by the "float-abi" IR module flag for a Soft or Hard ABIType.
Definition CodeGen.h:127
@ DynamicNoPIC
Definition CodeGen.h:26
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 std::string getTrapFuncName()
LLVM_ABI bool getEnableDebugEntryValues()
LLVM_ABI unsigned getTLSSize()
LLVM_ABI bool getEnableGuaranteedTailCallOpt()
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 void setFunctionAttributes(Function &F, StringRef CPU, StringRef Features, StringRef TuneCPU="")
Set function attributes of function F based on CPU, TuneCPU, Features, and command line flags.
LLVM_ABI ThreadModel getThreadModel()
LLVM_ABI std::string getTuneCPUStr()
LLVM_ABI std::string getMTune()
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 getEnableStackSizeSection()
LLVM_ABI llvm::EABI getEABIVersion()
LLVM_ABI bool getEnableCallGraphSection()
LLVM_ABI SaveStatsMode getSaveStats()
LLVM_ABI bool getUniqueBasicBlockSectionNames()
LLVM_ABI FramePointerKind getFramePointerUsage()
LLVM_ABI bool getDontPlaceZerosInBSS()
LLVM_ABI bool getSeparateNamedSections()
LLVM_ABI std::optional< bool > getExplicitDataSections()
LLVM_ABI bool getXCOFFTracebackTable()
LLVM_ABI bool getIgnoreXCOFFVisibility()
LLVM_ABI bool getUseCtors()
LLVM_ABI llvm::DebuggerKind getDebuggerTuningOpt()
LLVM_ABI std::vector< std::string > getMAttrs()
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 Expected< std::unique_ptr< TargetMachine > > createTargetMachineForTriple(const Triple &TargetTriple, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default)
Creates a TargetMachine instance with the options defined on the command line.
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:804
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:485
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:491
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
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:467
LLVM_ABI StringMap< bool, MallocAllocator > getHostCPUFeatures()
getHostCPUFeatures - Get the LLVM names for the host CPU features.
Definition Host.cpp:2619
LLVM_ABI StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition Host.cpp:2046
This is an optimization pass for GlobalISel generic memory operations.
FramePointerKind
Definition CodeGen.h:213
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:94
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:206
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:177
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
ThreadModel
The threading model to assume for lowering, e.g. of atomics.
Definition CodeGen.h:141
ExceptionHandling
Definition CodeGen.h:54
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:57
@ None
No exception support.
Definition CodeGen.h:55
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:56
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:59
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:60
BasicBlockSection
VectorLibrary
List of known vector-functions libraries.
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.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Represents the full denormal controls for a function, including the default mode and the f32 specific...
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 LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, 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.