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