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/FloatingPointMode.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/Module.h"
24#include "llvm/MC/MCTargetOptionsCommandFlags.h"
25#include "llvm/MC/TargetRegistry.h"
26#include "llvm/Option/LibraryOptions.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/FileSystem.h"
30#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/Path.h"
32#include "llvm/Support/WithColor.h"
33#include "llvm/Support/raw_ostream.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/TargetParser/Host.h"
36#include "llvm/TargetParser/SubtargetFeature.h"
37#include "llvm/TargetParser/Triple.h"
38#include <cassert>
39#include <memory>
40#include <optional>
41#include <system_error>
42
43using namespace llvm;
44
45#define OPTIONS_STRUCT_DECL
46#include "CodeGenToolOptions.inc"
47
48#define OPTIONS_STRUCT_DEFS
49#include "CodeGenToolOptions.inc"
50
51static const CodeGenToolOptions &getCodeGenToolOptions(const LLVMContext &C) {
52 return C.getLibraryOptions().get<CodeGenToolOptions>();
53}
54
55std::string codegen::getMArch(const cl::LibraryOptionsContext &C) {
56 return C.get<CodeGenToolOptions>().march.str();
57}
58
59std::string codegen::getMCPU(const cl::LibraryOptionsContext &C) {
60 return C.get<CodeGenToolOptions>().mcpu.str();
61}
62
63std::vector<std::string>
64codegen::getMAttrs(const cl::LibraryOptionsContext &C) {
65 ArrayRef<StringRef> MAttrs = C.get<CodeGenToolOptions>().mattr;
66 return std::vector<std::string>(MAttrs.begin(), MAttrs.end());
67}
68
69std::optional<Reloc::Model>
70codegen::getExplicitRelocModel(const cl::LibraryOptionsContext &C) {
71 return C.get<CodeGenToolOptions>().relocation_model;
72}
73
74std::optional<CodeModel::Model>
75codegen::getExplicitCodeModel(const cl::LibraryOptionsContext &C) {
76 return C.get<CodeGenToolOptions>().code_model;
77}
78
79std::optional<uint64_t>
80codegen::getExplicitLargeDataThreshold(const cl::LibraryOptionsContext &C) {
81 return C.get<CodeGenToolOptions>().large_data_threshold;
82}
83
84std::optional<CodeGenFileType>
85codegen::getExplicitFileType(const cl::LibraryOptionsContext &C) {
86 return C.get<CodeGenToolOptions>().filetype;
87}
88
89CodeGenFileType codegen::getFileType(const cl::LibraryOptionsContext &C) {
90 return getExplicitFileType(C).value_or(u: CodeGenFileType::AssemblyFile);
91}
92
93FloatABI::ABIType
94codegen::getFloatABIForCalls(const cl::LibraryOptionsContext &C) {
95 return C.get<CodeGenToolOptions>().float_abi;
96}
97
98std::optional<bool>
99codegen::getExplicitDataSections(const cl::LibraryOptionsContext &C) {
100 return toOptional(X: C.get<CodeGenToolOptions>().data_sections);
101}
102
103std::optional<bool>
104codegen::getExplicitFunctionSections(const cl::LibraryOptionsContext &C) {
105 return toOptional(X: C.get<CodeGenToolOptions>().function_sections);
106}
107
108std::optional<bool>
109codegen::getExplicitEmulatedTLS(const cl::LibraryOptionsContext &C) {
110 return toOptional(X: C.get<CodeGenToolOptions>().emulated_tls);
111}
112
113std::string codegen::getMTune(const cl::LibraryOptionsContext &C) {
114 return C.get<CodeGenToolOptions>().mtune.str();
115}
116
117codegen::SaveStatsMode
118codegen::getSaveStats(const cl::LibraryOptionsContext &C) {
119 return C.get<CodeGenToolOptions>().save_stats;
120}
121
122ArrayRef<const cl::LibraryOptions *> codegen::getToolOptions() {
123 static constexpr opt::LibraryOptionsParser Parser(
124 std::in_place_type<CodeGenToolOptions>);
125 assert(mc::getToolOptions().size() == 1);
126 static const cl::LibraryOptions *const Libraries[] = {mc::getToolOptions()[0],
127 &Parser};
128 return Libraries;
129}
130
131static BasicBlockSection getBBSectionsMode(const CodeGenToolOptions &Opts,
132 TargetOptions &Options) {
133 if (Opts.basic_block_sections == "all")
134 return BasicBlockSection::All;
135 else if (Opts.basic_block_sections == "none")
136 return BasicBlockSection::None;
137 else {
138 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
139 MemoryBuffer::getFile(Filename: Opts.basic_block_sections);
140 if (!MBOrErr) {
141 errs() << "Error loading basic block sections function list file: "
142 << MBOrErr.getError().message() << "\n";
143 } else {
144 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
145 }
146 return BasicBlockSection::List;
147 }
148}
149
150// Common utility function tightly tied to the options listed here. Initializes
151// a TargetOptions object with CodeGen options and returns it.
152TargetOptions
153codegen::getTargetOptions(const cl::LibraryOptionsContext &LibraryOptions,
154 const Triple &TheTriple) {
155 const CodeGenToolOptions &Opts = LibraryOptions.get<CodeGenToolOptions>();
156 TargetOptions Options;
157 Options.NoZerosInBSS = Opts.nozero_initialized_in_bss;
158 Options.GuaranteedTailCallOpt = Opts.tailcallopt;
159 Options.StackSymbolOrdering = Opts.stack_symbol_ordering;
160 Options.UseInitArray = !Opts.use_ctors;
161 Options.DataSections =
162 valueOr(X: Opts.data_sections, Default: TheTriple.hasDefaultDataSections());
163 Options.FunctionSections = valueOr(X: Opts.function_sections, Default: false);
164 Options.IgnoreXCOFFVisibility = Opts.ignore_xcoff_visibility;
165 Options.XCOFFTracebackTable = Opts.xcoff_traceback_table;
166 Options.BBAddrMap = Opts.basic_block_address_map;
167 Options.BBSections = getBBSectionsMode(Opts, Options);
168 Options.UniqueSectionNames = Opts.unique_section_names;
169 Options.UniqueBasicBlockSectionNames = Opts.unique_basic_block_section_names;
170 Options.SeparateNamedSections = Opts.separate_named_sections;
171 Options.TLSSize = Opts.tls_size;
172 Options.EmulatedTLS =
173 valueOr(X: Opts.emulated_tls, Default: TheTriple.hasDefaultEmulatedTLS());
174 Options.EnableTLSDESC =
175 valueOr(X: Opts.enable_tlsdesc, Default: TheTriple.hasDefaultTLSDESC());
176 Options.VecLib = Opts.vector_library;
177 Options.EmitStackSizeSection = Opts.stack_size_section;
178 Options.EnableStaticDataPartitioning = Opts.partition_static_data_sections;
179 Options.EmitAddrsig = Opts.addrsig;
180 Options.EmitCallGraphSection = Opts.call_graph_section;
181 Options.EmitCallSiteInfo = Opts.emit_call_site_info;
182 Options.EnableDebugEntryValues = Opts.debug_entry_values;
183 Options.ForceDwarfFrameSection = Opts.force_dwarf_frame_section;
184 Options.XRayFunctionIndex = Opts.xray_function_index;
185 Options.DebugStrictDwarf = Opts.strict_dwarf;
186 Options.LoopAlignment = Opts.align_loops;
187 Options.JMCInstrument = Opts.enable_jmc_instrument;
188 Options.XCOFFReadOnlyPointers = Opts.mxcoff_roptr;
189
190 Options.MCOptions = mc::getMCTargetOptions(C: LibraryOptions);
191
192 Options.SwiftAsyncFramePointer = Opts.swift_async_fp;
193 return Options;
194}
195
196std::string codegen::getCPUStr(const cl::LibraryOptionsContext &C) {
197 std::string MCPU = getMCPU(C);
198
199 // If user asked for the 'native' CPU, autodetect here. If auto-detection
200 // fails, this will set the CPU to an empty string which tells the target to
201 // pick a basic default.
202 if (MCPU == "native")
203 return std::string(sys::getHostCPUName());
204
205 return MCPU;
206}
207
208std::string codegen::getTuneCPUStr(const cl::LibraryOptionsContext &C) {
209 std::string TuneCPU = getMTune(C);
210
211 // If user asked for the 'native' tune CPU, autodetect here. If auto-detection
212 // fails, this will set the tune CPU to an empty string which tells the target
213 // to pick a basic default.
214 if (TuneCPU == "native")
215 return std::string(sys::getHostCPUName());
216
217 return TuneCPU;
218}
219
220std::string codegen::getFeaturesStr(const cl::LibraryOptionsContext &C) {
221 SubtargetFeatures Features;
222
223 // If user asked for the 'native' CPU, we need to autodetect features.
224 // This is necessary for x86 where the CPU might not support all the
225 // features the autodetected CPU name lists in the target. For example,
226 // not all Sandybridge processors support AVX.
227 if (getMCPU(C) == "native")
228 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
229 Features.AddFeature(String: Feature, Enable: IsEnabled);
230
231 for (auto const &MAttr : getMAttrs(C))
232 Features.AddFeature(String: MAttr);
233
234 return Features.getString();
235}
236
237std::vector<std::string>
238codegen::getFeatureList(const cl::LibraryOptionsContext &C) {
239 SubtargetFeatures Features;
240
241 // If user asked for the 'native' CPU, we need to autodetect features.
242 // This is necessary for x86 where the CPU might not support all the
243 // features the autodetected CPU name lists in the target. For example,
244 // not all Sandybridge processors support AVX.
245 if (getMCPU(C) == "native")
246 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
247 Features.AddFeature(String: Feature, Enable: IsEnabled);
248
249 for (auto const &MAttr : getMAttrs(C))
250 Features.AddFeature(String: MAttr);
251
252 return Features.getFeatures();
253}
254
255void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
256 B.addAttribute(A: Name, V: Val ? "true" : "false");
257}
258
259void codegen::setFunctionAttributes(Function &F, StringRef CPU,
260 StringRef Features, StringRef TuneCPU) {
261 auto &Ctx = F.getContext();
262 const CodeGenToolOptions &Opts = getCodeGenToolOptions(C: Ctx);
263 AttributeList Attrs = F.getAttributes();
264 AttrBuilder NewAttrs(Ctx);
265
266 if (!CPU.empty() && !F.hasFnAttribute(Kind: "target-cpu"))
267 NewAttrs.addAttribute(A: "target-cpu", V: CPU);
268 if (!TuneCPU.empty() && !F.hasFnAttribute(Kind: "tune-cpu"))
269 NewAttrs.addAttribute(A: "tune-cpu", V: TuneCPU);
270 if (!Features.empty()) {
271 // Append the command line features to any that are already on the function.
272 StringRef OldFeatures =
273 F.getFnAttribute(Kind: "target-features").getValueAsString();
274 if (OldFeatures.empty())
275 NewAttrs.addAttribute(A: "target-features", V: Features);
276 else {
277 SmallString<256> Appended(OldFeatures);
278 Appended.push_back(Elt: ',');
279 Appended.append(RHS: Features);
280 NewAttrs.addAttribute(A: "target-features", V: Appended);
281 }
282 }
283 if (Opts.frame_pointer && !F.hasFnAttribute(Kind: "frame-pointer")) {
284 if (*Opts.frame_pointer == FramePointerKind::All)
285 NewAttrs.addAttribute(A: "frame-pointer", V: "all");
286 else if (*Opts.frame_pointer == FramePointerKind::NonLeaf)
287 NewAttrs.addAttribute(A: "frame-pointer", V: "non-leaf");
288 else if (*Opts.frame_pointer == FramePointerKind::NonLeafNoReserve)
289 NewAttrs.addAttribute(A: "frame-pointer", V: "non-leaf-no-reserve");
290 else if (*Opts.frame_pointer == FramePointerKind::Reserved)
291 NewAttrs.addAttribute(A: "frame-pointer", V: "reserved");
292 else if (*Opts.frame_pointer == FramePointerKind::None)
293 NewAttrs.addAttribute(A: "frame-pointer", V: "none");
294 }
295 if (Opts.disable_tail_calls != BoolOrDefault::Default)
296 NewAttrs.addAttribute(A: "disable-tail-calls",
297 V: toStringRef(B: valueOr(X: Opts.disable_tail_calls, Default: false)));
298 if (Opts.stackrealign)
299 NewAttrs.addAttribute(A: "stackrealign");
300
301 if ((Opts.denormal_fp_math || Opts.denormal_fp_math_f32) &&
302 !F.hasFnAttribute(Kind: Attribute::DenormalFPEnv)) {
303 DenormalMode::DenormalModeKind DenormKind =
304 Opts.denormal_fp_math.value_or(u: DenormalMode::IEEE);
305 DenormalMode::DenormalModeKind DenormKindF32 =
306 Opts.denormal_fp_math_f32.value_or(u: DenormalMode::Invalid);
307
308 DenormalFPEnv FPEnv(DenormalMode{DenormKind, DenormKind},
309 DenormalMode{DenormKindF32, DenormKindF32});
310 // FIXME: Command line flag should expose separate input/output modes.
311 NewAttrs.addDenormalFPEnvAttr(Mode: FPEnv);
312 }
313
314 if (Opts.trap_func)
315 for (auto &B : F)
316 for (auto &I : B)
317 if (auto *Call = dyn_cast<CallInst>(Val: &I))
318 if (const auto *F = Call->getCalledFunction())
319 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
320 F->getIntrinsicID() == Intrinsic::trap)
321 Call->addFnAttr(
322 Attr: Attribute::get(Context&: Ctx, Kind: "trap-func-name", Val: *Opts.trap_func));
323
324 // Let NewAttrs override Attrs.
325 F.setAttributes(Attrs.addFnAttributes(C&: Ctx, B: NewAttrs));
326}
327
328void codegen::setFunctionAttributes(Module &M, StringRef CPU,
329 StringRef Features, StringRef TuneCPU) {
330 const cl::LibraryOptionsContext &C = M.getContext().getLibraryOptions();
331 // Synthesize the "float-abi" module flag from the -float-abi option.
332 FloatABI::ABIType ABI = getFloatABIForCalls(C);
333 if (ABI != FloatABI::Default) {
334 if (auto *Existing =
335 dyn_cast_or_null<MDString>(Val: M.getModuleFlag(Key: "float-abi"))) {
336 // The module already records a float ABI; -float-abi must not contradict
337 // it.
338 if (Existing->getString() != FloatABI::getABITypeName(ABI))
339 reportFatalUsageError(
340 reason: "-float-abi=" + FloatABI::getABITypeName(ABI) +
341 " conflicts with the \"float-abi\" module flag \"" +
342 Existing->getString() + "\"");
343 } else {
344 M.addModuleFlag(
345 Behavior: Module::Error, Key: "float-abi",
346 Val: MDString::get(Context&: M.getContext(), Str: FloatABI::getABITypeName(ABI)));
347 }
348 }
349
350 // Synthesize the "exception-model" module flag from the -exception-model
351 // option.
352 ExceptionHandling EH = getCodeGenToolOptions(C: M.getContext()).exception_model;
353 if (EH != ExceptionHandling::Default) {
354 if (auto *Existing =
355 dyn_cast_or_null<MDString>(Val: M.getModuleFlag(Key: "exception-model"))) {
356 // The module already records an exception model; -exception-model must
357 // not contradict it.
358 if (Existing->getString() != getExceptionModelName(EH)) {
359 reportFatalUsageError(
360 reason: "-exception-model=" + getExceptionModelName(EH) +
361 " conflicts with the \"exception-model\" module flag \"" +
362 Existing->getString() + "\"");
363 }
364 } else {
365 M.addModuleFlag(Behavior: Module::Error, Key: "exception-model",
366 Val: MDString::get(Context&: M.getContext(), Str: getExceptionModelName(EH)));
367 }
368 }
369
370 // Synthesize the "target-abi" module flag from the -target-abi option.
371 //
372 // FIXME: verifyOptionsConsistency validates consistency for target-abi. We
373 // should consistently handle all ABI module flags either here or there.
374 StringRef ABIName = mc::getABIName(C);
375 if (!ABIName.empty() && !M.getModuleFlag(Key: "target-abi")) {
376 M.addModuleFlag(Behavior: Module::Error, Key: "target-abi",
377 Val: MDString::get(Context&: M.getContext(), Str: ABIName));
378 }
379
380 for (Function &F : M)
381 setFunctionAttributes(F, CPU, Features, TuneCPU);
382}
383
384Expected<std::unique_ptr<TargetMachine>> codegen::createTargetMachineForTriple(
385 const cl::LibraryOptionsContext &LibraryOptions, const Triple &TargetTriple,
386 CodeGenOptLevel OptLevel) {
387 // lookupTarget may mutate the triple, so we need a copy.
388 Triple TheTriple(TargetTriple);
389 std::string Error;
390 const auto *TheTarget = TargetRegistry::lookupTarget(
391 ArchName: codegen::getMArch(C: LibraryOptions), TheTriple, Error);
392 if (!TheTarget)
393 return createStringError(EC: inconvertibleErrorCode(), S: Error);
394 TargetOptions Options = codegen::getTargetOptions(LibraryOptions, TheTriple);
395 auto *Target = TheTarget->createTargetMachine(
396 TT: TheTriple, CPU: codegen::getCPUStr(C: LibraryOptions),
397 Features: codegen::getFeaturesStr(C: LibraryOptions), Options,
398 RM: codegen::getExplicitRelocModel(C: LibraryOptions),
399 CM: codegen::getExplicitCodeModel(C: LibraryOptions), OL: OptLevel);
400 if (!Target)
401 return createStringError(EC: inconvertibleErrorCode(),
402 S: Twine("could not allocate target machine for ") +
403 TheTriple.str());
404 return std::unique_ptr<TargetMachine>(Target);
405}
406
407void codegen::maybeEnableStatistics(const cl::LibraryOptionsContext &C) {
408 if (getSaveStats(C) == SaveStatsMode::None)
409 return;
410
411 llvm::EnableStatistics(DoPrintOnExit: false);
412}
413
414int codegen::maybeSaveStatistics(const cl::LibraryOptionsContext &C,
415 StringRef OutputFilename, StringRef ToolName) {
416 auto SaveStatsValue = getSaveStats(C);
417 if (SaveStatsValue == codegen::SaveStatsMode::None)
418 return 0;
419
420 SmallString<128> StatsFilename;
421 if (SaveStatsValue == codegen::SaveStatsMode::Obj) {
422 StatsFilename = OutputFilename;
423 llvm::sys::path::remove_filename(path&: StatsFilename);
424 } else {
425 assert(SaveStatsValue == codegen::SaveStatsMode::Cwd &&
426 "Should have been a valid --save-stats value");
427 }
428
429 auto BaseName = llvm::sys::path::filename(path: OutputFilename);
430 llvm::sys::path::append(path&: StatsFilename, a: BaseName);
431 llvm::sys::path::replace_extension(path&: StatsFilename, extension: "stats");
432
433 auto FileFlags = llvm::sys::fs::OF_TextWithCRLF;
434 std::error_code EC;
435 auto StatsOS =
436 std::make_unique<llvm::raw_fd_ostream>(args&: StatsFilename, args&: EC, args&: FileFlags);
437 if (EC) {
438 WithColor::error(OS&: errs(), Prefix: ToolName)
439 << "Unable to open statistics file: " << EC.message() << "\n";
440 return 1;
441 }
442
443 llvm::PrintStatisticsJSON(OS&: *StatsOS);
444 return 0;
445}
446