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