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