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