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