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