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)
74CGOPT_EXP(uint64_t, LargeDataThreshold)
75CGOPT(ExceptionHandling, ExceptionModel)
77CGOPT(FramePointerKind, FramePointerUsage)
80CGOPT(FloatABI::ABIType, FloatABIForCalls)
81CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
82CGOPT(bool, DontPlaceZerosInBSS)
83CGOPT(bool, EnableGuaranteedTailCallOpt)
84CGOPT(bool, DisableTailCalls)
85CGOPT(bool, StackSymbolOrdering)
86CGOPT(bool, StackRealign)
87CGOPT(std::string, TrapFuncName)
88CGOPT(bool, UseCtors)
89CGOPT_EXP(bool, DataSections)
90CGOPT_EXP(bool, FunctionSections)
91CGOPT(bool, IgnoreXCOFFVisibility)
92CGOPT(bool, XCOFFTracebackTable)
93CGOPT(bool, EnableBBAddrMap)
94CGOPT(std::string, BBSections)
95CGOPT(unsigned, TLSSize)
96CGOPT_EXP(bool, EmulatedTLS)
97CGOPT_EXP(bool, EnableTLSDESC)
98CGOPT(bool, UniqueSectionNames)
99CGOPT(bool, UniqueBasicBlockSectionNames)
100CGOPT(bool, SeparateNamedSections)
101CGOPT(DebuggerKind, DebuggerTuningOpt)
103CGOPT(bool, EnableStackSizeSection)
104CGOPT(bool, EnableAddrsig)
105CGOPT(bool, EnableCallGraphSection)
106CGOPT(bool, EmitCallSiteInfo)
108CGOPT(bool, EnableStaticDataPartitioning)
109CGOPT(bool, EnableDebugEntryValues)
110CGOPT(bool, ForceDwarfFrameSection)
111CGOPT(bool, XRayFunctionIndex)
112CGOPT(bool, DebugStrictDwarf)
113CGOPT(unsigned, AlignLoops)
114CGOPT(bool, JMCInstrument)
115CGOPT(bool, XCOFFReadOnlyPointers)
117
118#define CGBINDOPT(NAME) \
119 do { \
120 NAME##View = std::addressof(NAME); \
121 } while (0)
122
124 static cl::opt<std::string> MArch(
125 "march", cl::desc("Architecture to generate code for (see --version)"));
126 CGBINDOPT(MArch);
127
128 static cl::opt<std::string> MCPU(
129 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
130 cl::value_desc("cpu-name"), cl::init(""));
131 CGBINDOPT(MCPU);
132
133 static cl::list<std::string> MAttrs(
134 "mattr", cl::CommaSeparated,
135 cl::desc("Target specific attributes (-mattr=help for details)"),
136 cl::value_desc("a1,+a2,-a3,..."));
137 CGBINDOPT(MAttrs);
138
139 static cl::opt<Reloc::Model> RelocModel(
140 "relocation-model", cl::desc("Choose relocation model"),
142 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
143 clEnumValN(Reloc::PIC_, "pic",
144 "Fully relocatable, position independent code"),
145 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
146 "Relocatable external references, non-relocatable code"),
148 Reloc::ROPI, "ropi",
149 "Code and read-only data relocatable, accessed PC-relative"),
151 Reloc::RWPI, "rwpi",
152 "Read-write data relocatable, accessed relative to static base"),
153 clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
154 "Combination of ropi and rwpi")));
155 CGBINDOPT(RelocModel);
156
158 "code-model", cl::desc("Choose code model"),
159 cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
160 clEnumValN(CodeModel::Small, "small", "Small code model"),
161 clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
162 clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
163 clEnumValN(CodeModel::Large, "large", "Large code model")));
165
166 static cl::opt<uint64_t> LargeDataThreshold(
167 "large-data-threshold",
168 cl::desc("Choose large data threshold for x86_64 medium code model"),
169 cl::init(0));
170 CGBINDOPT(LargeDataThreshold);
171
172 static cl::opt<ExceptionHandling> ExceptionModel(
173 "exception-model", cl::desc("exception model"),
177 "default exception handling model"),
178 clEnumValN(ExceptionHandling::None, "none", "no exception handling"),
180 "DWARF-like CFI based exception handling"),
182 "SjLj exception handling"),
183 clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
185 "Windows exception model"),
187 "WebAssembly exception handling"),
189 "Emscripten JavaScript-based exception handling")));
190 CGBINDOPT(ExceptionModel);
191
192 static cl::opt<CodeGenFileType> FileType(
194 cl::desc(
195 "Choose a file type (not all types are supported by all targets):"),
197 "Emit an assembly ('.s') file"),
199 "Emit a native object ('.o') file"),
201 "Emit nothing, for performance testing")));
202 CGBINDOPT(FileType);
203
204 static cl::opt<FramePointerKind> FramePointerUsage(
205 "frame-pointer",
206 cl::desc("Specify frame pointer elimination optimization"),
210 "Disable frame pointer elimination"),
212 "Disable frame pointer elimination for non-leaf frame but "
213 "reserve the register in leaf functions"),
214 clEnumValN(FramePointerKind::NonLeafNoReserve, "non-leaf-no-reserve",
215 "Disable frame pointer elimination for non-leaf frame"),
217 "Enable frame pointer elimination, but reserve the frame "
218 "pointer register"),
220 "Enable frame pointer elimination")));
221 CGBINDOPT(FramePointerUsage);
222
223 static const auto DenormFlagEnumOptions = cl::values(
224 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
225 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
226 "the sign of a flushed-to-zero number is preserved "
227 "in the sign of 0"),
228 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
229 "denormals are flushed to positive zero"),
231 "denormals have unknown treatment"));
232
233 // FIXME: Doesn't have way to specify separate input and output modes.
234 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
235 "denormal-fp-math",
236 cl::desc("Select which denormal numbers the code is permitted to require"),
238 DenormFlagEnumOptions);
239 CGBINDOPT(DenormalFPMath);
240
241 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
242 "denormal-fp-math-f32",
243 cl::desc("Select which denormal numbers the code is permitted to require for float"),
245 DenormFlagEnumOptions);
246 CGBINDOPT(DenormalFP32Math);
247
248 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
249 "float-abi", cl::desc("Choose float ABI type"),
252 "Target default float ABI type"),
254 "Soft float ABI (implied by -soft-float)"),
256 "Hard float ABI (uses FP registers)")));
257 CGBINDOPT(FloatABIForCalls);
258
259 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
260 "swift-async-fp",
261 cl::desc("Determine when the Swift async frame pointer should be set"),
264 "Determine based on deployment target"),
266 "Always set the bit"),
268 "Never set the bit")));
269 CGBINDOPT(SwiftAsyncFramePointer);
270
271 static cl::opt<bool> DontPlaceZerosInBSS(
272 "nozero-initialized-in-bss",
273 cl::desc("Don't place zero-initialized symbols into bss section"),
274 cl::init(false));
275 CGBINDOPT(DontPlaceZerosInBSS);
276
277 static cl::opt<bool> EnableGuaranteedTailCallOpt(
278 "tailcallopt",
279 cl::desc(
280 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
281 cl::init(false));
282 CGBINDOPT(EnableGuaranteedTailCallOpt);
283
284 static cl::opt<bool> DisableTailCalls(
285 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
286 CGBINDOPT(DisableTailCalls);
287
288 static cl::opt<bool> StackSymbolOrdering(
289 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
290 cl::init(true));
291 CGBINDOPT(StackSymbolOrdering);
292
293 static cl::opt<bool> StackRealign(
294 "stackrealign",
295 cl::desc("Force align the stack to the minimum alignment"),
296 cl::init(false));
297 CGBINDOPT(StackRealign);
298
299 static cl::opt<std::string> TrapFuncName(
300 "trap-func", cl::Hidden,
301 cl::desc("Emit a call to trap function rather than a trap instruction"),
302 cl::init(""));
303 CGBINDOPT(TrapFuncName);
304
305 static cl::opt<bool> UseCtors("use-ctors",
306 cl::desc("Use .ctors instead of .init_array."),
307 cl::init(false));
308 CGBINDOPT(UseCtors);
309
310 static cl::opt<bool> DataSections(
311 "data-sections", cl::desc("Emit data into separate sections"),
312 cl::init(false));
313 CGBINDOPT(DataSections);
314
315 static cl::opt<bool> FunctionSections(
316 "function-sections", cl::desc("Emit functions into separate sections"),
317 cl::init(false));
318 CGBINDOPT(FunctionSections);
319
320 static cl::opt<bool> IgnoreXCOFFVisibility(
321 "ignore-xcoff-visibility",
322 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
323 "all symbols 'unspecified' visibility in XCOFF object file"),
324 cl::init(false));
325 CGBINDOPT(IgnoreXCOFFVisibility);
326
327 static cl::opt<bool> XCOFFTracebackTable(
328 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
329 cl::init(true));
330 CGBINDOPT(XCOFFTracebackTable);
331
332 static cl::opt<bool> EnableBBAddrMap(
333 "basic-block-address-map",
334 cl::desc("Emit the basic block address map section"), cl::init(false));
335 CGBINDOPT(EnableBBAddrMap);
336
337 static cl::opt<std::string> BBSections(
338 "basic-block-sections",
339 cl::desc("Emit basic blocks into separate sections"),
340 cl::value_desc("all | <function list (file)> | labels | none"),
341 cl::init("none"));
342 CGBINDOPT(BBSections);
343
344 static cl::opt<unsigned> TLSSize(
345 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
346 CGBINDOPT(TLSSize);
347
348 static cl::opt<bool> EmulatedTLS(
349 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
350 CGBINDOPT(EmulatedTLS);
351
352 static cl::opt<bool> EnableTLSDESC(
353 "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
354 cl::init(false));
355 CGBINDOPT(EnableTLSDESC);
356
357 static cl::opt<bool> UniqueSectionNames(
358 "unique-section-names", cl::desc("Give unique names to every section"),
359 cl::init(true));
360 CGBINDOPT(UniqueSectionNames);
361
362 static cl::opt<bool> UniqueBasicBlockSectionNames(
363 "unique-basic-block-section-names",
364 cl::desc("Give unique names to every basic block section"),
365 cl::init(false));
366 CGBINDOPT(UniqueBasicBlockSectionNames);
367
368 static cl::opt<bool> SeparateNamedSections(
369 "separate-named-sections",
370 cl::desc("Use separate unique sections for named sections"),
371 cl::init(false));
372 CGBINDOPT(SeparateNamedSections);
373
374 static cl::opt<DebuggerKind> DebuggerTuningOpt(
375 "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
378 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
379 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
380 clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
381 clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
382 CGBINDOPT(DebuggerTuningOpt);
383
385 "vector-library", cl::Hidden, cl::desc("Vector functions library"),
389 "No vector functions library"),
391 "Accelerate framework"),
392 clEnumValN(VectorLibrary::DarwinLibSystemM, "Darwin_libsystem_m",
393 "Darwin libsystem_m"),
395 "GLIBC Vector Math library"),
396 clEnumValN(VectorLibrary::MASSV, "MASSV", "IBM MASS vector library"),
397 clEnumValN(VectorLibrary::SVML, "SVML", "Intel SVML library"),
399 "SIMD Library for Evaluating Elementary Functions"),
401 "Arm Performance Libraries"),
403 "AMD vector math library")));
405
406 static cl::opt<bool> EnableStackSizeSection(
407 "stack-size-section",
408 cl::desc("Emit a section containing stack size metadata"),
409 cl::init(false));
410 CGBINDOPT(EnableStackSizeSection);
411
412 static cl::opt<bool> EnableAddrsig(
413 "addrsig", cl::desc("Emit an address-significance table"),
414 cl::init(false));
415 CGBINDOPT(EnableAddrsig);
416
417 static cl::opt<bool> EnableCallGraphSection(
418 "call-graph-section", cl::desc("Emit a call graph section"),
419 cl::init(false));
420 CGBINDOPT(EnableCallGraphSection);
421
422 static cl::opt<bool> EmitCallSiteInfo(
423 "emit-call-site-info",
424 cl::desc(
425 "Emit call site debug information, if debug information is enabled."),
426 cl::init(false));
427 CGBINDOPT(EmitCallSiteInfo);
428
429 static cl::opt<bool> EnableDebugEntryValues(
430 "debug-entry-values",
431 cl::desc("Enable debug info for the debug entry values."),
432 cl::init(false));
433 CGBINDOPT(EnableDebugEntryValues);
434
436 "split-machine-functions",
437 cl::desc("Split out cold basic blocks from machine functions based on "
438 "profile information"),
439 cl::init(false));
441
442 static cl::opt<bool> EnableStaticDataPartitioning(
443 "partition-static-data-sections",
444 cl::desc("Partition data sections using profile information."),
445 cl::init(false));
446 CGBINDOPT(EnableStaticDataPartitioning);
447
448 static cl::opt<bool> ForceDwarfFrameSection(
449 "force-dwarf-frame-section",
450 cl::desc("Always emit a debug frame section."), cl::init(false));
451 CGBINDOPT(ForceDwarfFrameSection);
452
453 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
454 cl::desc("Emit xray_fn_idx section"),
455 cl::init(true));
456 CGBINDOPT(XRayFunctionIndex);
457
458 static cl::opt<bool> DebugStrictDwarf(
459 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
460 CGBINDOPT(DebugStrictDwarf);
461
462 static cl::opt<unsigned> AlignLoops("align-loops",
463 cl::desc("Default alignment for loops"));
464 CGBINDOPT(AlignLoops);
465
466 static cl::opt<bool> JMCInstrument(
467 "enable-jmc-instrument",
468 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
469 cl::init(false));
470 CGBINDOPT(JMCInstrument);
471
472 static cl::opt<bool> XCOFFReadOnlyPointers(
473 "mxcoff-roptr",
474 cl::desc("When set to true, const objects with relocatable address "
475 "values are put into the RO data section."),
476 cl::init(false));
477 CGBINDOPT(XCOFFReadOnlyPointers);
478
480}
481
483 static cl::opt<std::string> MTune(
484 "mtune",
485 cl::desc("Tune for a specific CPU microarchitecture (-mtune=help for "
486 "details)"),
487 cl::value_desc("tune-cpu-name"), cl::init(""));
488 CGBINDOPT(MTune);
489}
490
492 static cl::opt<SaveStatsMode> SaveStats(
493 "save-stats",
494 cl::desc(
495 "Save LLVM statistics to a file in the current directory"
496 "(`-save-stats`/`-save-stats=cwd`) or the directory of the output"
497 "file (`-save-stats=obj`). (default: cwd)"),
499 "Save to the current working directory"),
502 "Save to the output file directory")),
504 CGBINDOPT(SaveStats);
505}
506
509 if (getBBSections() == "all")
511 else if (getBBSections() == "none")
513 else {
516 if (!MBOrErr) {
517 errs() << "Error loading basic block sections function list file: "
518 << MBOrErr.getError().message() << "\n";
519 } else {
520 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
521 }
523 }
524}
525
526// Common utility function tightly tied to the options listed here. Initializes
527// a TargetOptions object with CodeGen flags and returns it.
531 Options.NoZerosInBSS = getDontPlaceZerosInBSS();
532 Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
533 Options.StackSymbolOrdering = getStackSymbolOrdering();
534 Options.UseInitArray = !getUseCtors();
535 Options.DataSections =
536 getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
537 Options.FunctionSections = getFunctionSections();
538 Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
539 Options.XCOFFTracebackTable = getXCOFFTracebackTable();
540 Options.BBAddrMap = getEnableBBAddrMap();
541 Options.BBSections = getBBSectionsMode(Options);
542 Options.UniqueSectionNames = getUniqueSectionNames();
543 Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
544 Options.SeparateNamedSections = getSeparateNamedSections();
545 Options.TLSSize = getTLSSize();
546 Options.EmulatedTLS =
547 getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
548 Options.EnableTLSDESC =
549 getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());
550 Options.ExceptionModel = getExceptionModel();
551 Options.VecLib = getVectorLibrary();
552 Options.EmitStackSizeSection = getEnableStackSizeSection();
553 Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
554 Options.EnableStaticDataPartitioning = getEnableStaticDataPartitioning();
555 Options.EmitAddrsig = getEnableAddrsig();
556 Options.EmitCallGraphSection = getEnableCallGraphSection();
557 Options.EmitCallSiteInfo = getEmitCallSiteInfo();
558 Options.EnableDebugEntryValues = getEnableDebugEntryValues();
559 Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
560 Options.XRayFunctionIndex = getXRayFunctionIndex();
561 Options.DebugStrictDwarf = getDebugStrictDwarf();
562 Options.LoopAlignment = getAlignLoops();
563 Options.JMCInstrument = getJMCInstrument();
564 Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
565
567
568 Options.DebuggerTuning = getDebuggerTuningOpt();
569 Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
570 return Options;
571}
572
573std::string codegen::getCPUStr() {
574 std::string MCPU = getMCPU();
575
576 // If user asked for the 'native' CPU, autodetect here. If auto-detection
577 // fails, this will set the CPU to an empty string which tells the target to
578 // pick a basic default.
579 if (MCPU == "native")
580 return std::string(sys::getHostCPUName());
581
582 return MCPU;
583}
584
586 std::string TuneCPU = getMTune();
587
588 // If user asked for the 'native' tune CPU, autodetect here. If auto-detection
589 // fails, this will set the tune CPU to an empty string which tells the target
590 // to pick a basic default.
591 if (TuneCPU == "native")
592 return std::string(sys::getHostCPUName());
593
594 return TuneCPU;
595}
596
598 SubtargetFeatures Features;
599
600 // If user asked for the 'native' CPU, we need to autodetect features.
601 // This is necessary for x86 where the CPU might not support all the
602 // features the autodetected CPU name lists in the target. For example,
603 // not all Sandybridge processors support AVX.
604 if (getMCPU() == "native")
605 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
606 Features.AddFeature(Feature, IsEnabled);
607
608 for (auto const &MAttr : getMAttrs())
609 Features.AddFeature(MAttr);
610
611 return Features.getString();
612}
613
614std::vector<std::string> codegen::getFeatureList() {
615 SubtargetFeatures Features;
616
617 // If user asked for the 'native' CPU, we need to autodetect features.
618 // This is necessary for x86 where the CPU might not support all the
619 // features the autodetected CPU name lists in the target. For example,
620 // not all Sandybridge processors support AVX.
621 if (getMCPU() == "native")
622 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
623 Features.AddFeature(Feature, IsEnabled);
624
625 for (auto const &MAttr : getMAttrs())
626 Features.AddFeature(MAttr);
627
628 return Features.getFeatures();
629}
630
631void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
632 B.addAttribute(Name, Val ? "true" : "false");
633}
634
635#define HANDLE_BOOL_ATTR(CL, AttrName) \
636 do { \
637 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
638 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
639 } while (0)
640
642 StringRef Features, StringRef TuneCPU) {
643 auto &Ctx = F.getContext();
644 AttributeList Attrs = F.getAttributes();
645 AttrBuilder NewAttrs(Ctx);
646
647 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
648 NewAttrs.addAttribute("target-cpu", CPU);
649 if (!TuneCPU.empty() && !F.hasFnAttribute("tune-cpu"))
650 NewAttrs.addAttribute("tune-cpu", TuneCPU);
651 if (!Features.empty()) {
652 // Append the command line features to any that are already on the function.
653 StringRef OldFeatures =
654 F.getFnAttribute("target-features").getValueAsString();
655 if (OldFeatures.empty())
656 NewAttrs.addAttribute("target-features", Features);
657 else {
658 SmallString<256> Appended(OldFeatures);
659 Appended.push_back(',');
660 Appended.append(Features);
661 NewAttrs.addAttribute("target-features", Appended);
662 }
663 }
664 if (FramePointerUsageView->getNumOccurrences() > 0 &&
665 !F.hasFnAttribute("frame-pointer")) {
667 NewAttrs.addAttribute("frame-pointer", "all");
669 NewAttrs.addAttribute("frame-pointer", "non-leaf");
671 NewAttrs.addAttribute("frame-pointer", "non-leaf-no-reserve");
673 NewAttrs.addAttribute("frame-pointer", "reserved");
675 NewAttrs.addAttribute("frame-pointer", "none");
676 }
677 if (DisableTailCallsView->getNumOccurrences() > 0)
678 NewAttrs.addAttribute("disable-tail-calls",
680 if (getStackRealign())
681 NewAttrs.addAttribute("stackrealign");
682
683 if ((DenormalFPMathView->getNumOccurrences() > 0 ||
684 DenormalFP32MathView->getNumOccurrences() > 0) &&
685 !F.hasFnAttribute(Attribute::DenormalFPEnv)) {
688
689 DenormalFPEnv FPEnv(DenormalMode{DenormKind, DenormKind},
690 DenormalMode{DenormKindF32, DenormKindF32});
691 // FIXME: Command line flag should expose separate input/output modes.
692 NewAttrs.addDenormalFPEnvAttr(FPEnv);
693 }
694
695 if (TrapFuncNameView->getNumOccurrences() > 0)
696 for (auto &B : F)
697 for (auto &I : B)
698 if (auto *Call = dyn_cast<CallInst>(&I))
699 if (const auto *F = Call->getCalledFunction())
700 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
701 F->getIntrinsicID() == Intrinsic::trap)
702 Call->addFnAttr(
703 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
704
705 // Let NewAttrs override Attrs.
706 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
707}
708
710 StringRef Features, StringRef TuneCPU) {
711 // Synthesize the "float-abi" module flag from the -float-abi option.
713 if (ABI != FloatABI::Default) {
714 if (auto *Existing =
715 dyn_cast_or_null<MDString>(M.getModuleFlag("float-abi"))) {
716 // The module already records a float ABI; -float-abi must not contradict
717 // it.
718 if (Existing->getString() != FloatABI::getABITypeName(ABI))
720 "-float-abi=" + FloatABI::getABITypeName(ABI) +
721 " conflicts with the \"float-abi\" module flag \"" +
722 Existing->getString() + "\"");
723 } else {
724 M.addModuleFlag(
725 Module::Error, "float-abi",
726 MDString::get(M.getContext(), FloatABI::getABITypeName(ABI)));
727 }
728 }
729
730 // Synthesize the "exception-model" module flag from the -exception-model
731 // option.
733 if (EH != ExceptionHandling::Default) {
734 if (auto *Existing =
735 dyn_cast_or_null<MDString>(M.getModuleFlag("exception-model"))) {
736 // The module already records an exception model; -exception-model must
737 // not contradict it.
738 if (Existing->getString() != getExceptionModelName(EH)) {
740 "-exception-model=" + getExceptionModelName(EH) +
741 " conflicts with the \"exception-model\" module flag \"" +
742 Existing->getString() + "\"");
743 }
744 } else {
745 M.addModuleFlag(Module::Error, "exception-model",
746 MDString::get(M.getContext(), getExceptionModelName(EH)));
747 }
748 }
749
750 for (Function &F : M)
751 setFunctionAttributes(F, CPU, Features, TuneCPU);
752}
753
756 CodeGenOptLevel OptLevel) {
757 // lookupTarget may mutate the triple, so we need a copy.
758 Triple TheTriple(TargetTriple);
759 std::string Error;
760 const auto *TheTarget =
762 if (!TheTarget)
764 auto *Target = TheTarget->createTargetMachine(
768 OptLevel);
769 if (!Target)
771 Twine("could not allocate target machine for ") +
772 TheTriple.str());
773 return std::unique_ptr<TargetMachine>(Target);
774}
775
778 return;
779
781}
782
784 auto SaveStatsValue = getSaveStats();
785 if (SaveStatsValue == codegen::SaveStatsMode::None)
786 return 0;
787
788 SmallString<128> StatsFilename;
789 if (SaveStatsValue == codegen::SaveStatsMode::Obj) {
790 StatsFilename = OutputFilename;
792 } else {
793 assert(SaveStatsValue == codegen::SaveStatsMode::Cwd &&
794 "Should have been a valid --save-stats value");
795 }
796
798 llvm::sys::path::append(StatsFilename, BaseName);
799 llvm::sys::path::replace_extension(StatsFilename, "stats");
800
801 auto FileFlags = llvm::sys::fs::OF_TextWithCRLF;
802 std::error_code EC;
803 auto StatsOS =
804 std::make_unique<llvm::raw_fd_ostream>(StatsFilename, EC, FileFlags);
805 if (EC) {
806 WithColor::error(errs(), ToolName)
807 << "Unable to open statistics file: " << EC.message() << "\n";
808 return 1;
809 }
810
812 return 0;
813}
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:597
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:177
@ 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 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 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 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:263
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
StringRef getExceptionModelName(ExceptionHandling EH)
Returns the "exception-model" module flag spelling for an ExceptionHandling value.
Definition CodeGen.h:71
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:256
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:227
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
ExceptionHandling
Definition CodeGen.h:54
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:58
@ Emscripten
Emscripten JavaScript-based exception handling.
Definition CodeGen.h:62
@ None
No exception support.
Definition CodeGen.h:56
@ Default
Not specified; resolve to the target's default model.
Definition CodeGen.h:55
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:57
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:60
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:61
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.