1//===--- ARM.cpp - ARM (not AArch64) Helpers for Tools ----------*- 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#include "ARM.h"
10#include "clang/Driver/Driver.h"
11#include "clang/Options/Options.h"
12#include "llvm/ADT/StringSwitch.h"
13#include "llvm/Option/ArgList.h"
14#include "llvm/TargetParser/ARMTargetParser.h"
15#include "llvm/TargetParser/Host.h"
16
17using namespace clang::driver;
18using namespace clang::driver::tools;
19using namespace clang;
20using namespace llvm::opt;
21
22// Get SubArch (vN).
23int arm::getARMSubArchVersionNumber(const llvm::Triple &Triple) {
24 llvm::StringRef Arch = Triple.getArchName();
25 return llvm::ARM::parseArchVersion(Arch);
26}
27
28// True if M-profile.
29bool arm::isARMMProfile(const llvm::Triple &Triple) {
30 llvm::StringRef Arch = Triple.getArchName();
31 return llvm::ARM::parseArchProfile(Arch) == llvm::ARM::ProfileKind::M;
32}
33
34// On Arm the endianness of the output file is determined by the target and
35// can be overridden by the pseudo-target flags '-mlittle-endian'/'-EL' and
36// '-mbig-endian'/'-EB'. Unlike other targets the flag does not result in a
37// normalized triple so we must handle the flag here.
38bool arm::isARMBigEndian(const llvm::Triple &Triple, const ArgList &Args) {
39 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlittle_endian,
40 Ids: options::OPT_mbig_endian)) {
41 return !A->getOption().matches(ID: options::OPT_mlittle_endian);
42 }
43
44 return Triple.getArch() == llvm::Triple::armeb ||
45 Triple.getArch() == llvm::Triple::thumbeb;
46}
47
48// True if A-profile.
49bool arm::isARMAProfile(const llvm::Triple &Triple) {
50 llvm::StringRef Arch = Triple.getArchName();
51 return llvm::ARM::parseArchProfile(Arch) == llvm::ARM::ProfileKind::A;
52}
53
54/// Is the triple {arm,armeb,thumb,thumbeb}-none-none-{eabi,eabihf} ?
55bool arm::isARMEABIBareMetal(const llvm::Triple &Triple) {
56 auto arch = Triple.getArch();
57 if (arch != llvm::Triple::arm && arch != llvm::Triple::thumb &&
58 arch != llvm::Triple::armeb && arch != llvm::Triple::thumbeb)
59 return false;
60
61 if (Triple.getVendor() != llvm::Triple::UnknownVendor)
62 return false;
63
64 if (Triple.getOS() != llvm::Triple::UnknownOS)
65 return false;
66
67 if (Triple.getEnvironment() != llvm::Triple::EABI &&
68 Triple.getEnvironment() != llvm::Triple::EABIHF)
69 return false;
70
71 return true;
72}
73
74// Get Arch/CPU from args.
75void arm::getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
76 llvm::StringRef &CPU, bool FromAs) {
77 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ))
78 CPU = A->getValue();
79 if (const Arg *A = Args.getLastArg(Ids: options::OPT_march_EQ))
80 Arch = A->getValue();
81 if (!FromAs)
82 return;
83
84 for (const Arg *A :
85 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler)) {
86 // Use getValues because -Wa can have multiple arguments
87 // e.g. -Wa,-mcpu=foo,-mcpu=bar
88 for (StringRef Value : A->getValues()) {
89 if (Value.starts_with(Prefix: "-mcpu="))
90 CPU = Value.substr(Start: 6);
91 if (Value.starts_with(Prefix: "-march="))
92 Arch = Value.substr(Start: 7);
93 }
94 }
95}
96
97// Handle -mhwdiv=.
98// FIXME: Use ARMTargetParser.
99static void getARMHWDivFeatures(const Driver &D, const Arg *A,
100 const ArgList &Args, StringRef HWDiv,
101 std::vector<StringRef> &Features) {
102 uint64_t HWDivID = llvm::ARM::parseHWDiv(HWDiv);
103 if (!llvm::ARM::getHWDivFeatures(HWDivKind: HWDivID, Features))
104 D.Diag(DiagID: clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
105}
106
107// Handle -mfpu=.
108static llvm::ARM::FPUKind getARMFPUFeatures(const Driver &D, const Arg *A,
109 const ArgList &Args, StringRef FPU,
110 std::vector<StringRef> &Features) {
111 llvm::ARM::FPUKind FPUKind = llvm::ARM::parseFPU(FPU);
112 if (!llvm::ARM::getFPUFeatures(FPUKind, Features))
113 D.Diag(DiagID: clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
114 return FPUKind;
115}
116
117// Decode ARM features from string like +[no]featureA+[no]featureB+...
118static bool DecodeARMFeatures(const Driver &D, StringRef text, StringRef CPU,
119 llvm::ARM::ArchKind ArchKind,
120 std::vector<StringRef> &Features,
121 llvm::ARM::FPUKind &ArgFPUKind) {
122 SmallVector<StringRef, 8> Split;
123 text.split(A&: Split, Separator: StringRef("+"), MaxSplit: -1, KeepEmpty: false);
124
125 for (StringRef Feature : Split) {
126 if (!appendArchExtFeatures(CPU, AK: ArchKind, ArchExt: Feature, Features, ArgFPUKind))
127 return false;
128 }
129 return true;
130}
131
132static void DecodeARMFeaturesFromCPU(const Driver &D, StringRef CPU,
133 std::vector<StringRef> &Features) {
134 CPU = CPU.split(Separator: "+").first;
135 if (CPU != "generic") {
136 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
137 uint64_t Extension = llvm::ARM::getDefaultExtensions(CPU, AK: ArchKind);
138 llvm::ARM::getExtensionFeatures(Extensions: Extension, Features);
139 }
140}
141
142// Check if -march is valid by checking if it can be canonicalised and parsed.
143// getARMArch is used here instead of just checking the -march value in order
144// to handle -march=native correctly.
145static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
146 llvm::StringRef ArchName, llvm::StringRef CPUName,
147 std::vector<StringRef> &Features,
148 const llvm::Triple &Triple,
149 llvm::ARM::FPUKind &ArgFPUKind) {
150 std::pair<StringRef, StringRef> Split = ArchName.split(Separator: "+");
151
152 std::string MArch = arm::getARMArch(Arch: ArchName, Triple);
153 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Arch: MArch);
154 if (ArchKind == llvm::ARM::ArchKind::INVALID ||
155 (Split.second.size() &&
156 !DecodeARMFeatures(D, text: Split.second, CPU: CPUName, ArchKind, Features,
157 ArgFPUKind)))
158 D.Diag(DiagID: clang::diag::err_drv_unsupported_option_argument)
159 << A->getSpelling() << A->getValue();
160}
161
162// Check -mcpu=. Needs ArchName to handle -mcpu=generic.
163static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
164 llvm::StringRef CPUName, llvm::StringRef ArchName,
165 std::vector<StringRef> &Features,
166 const llvm::Triple &Triple,
167 llvm::ARM::FPUKind &ArgFPUKind) {
168 std::pair<StringRef, StringRef> Split = CPUName.split(Separator: "+");
169
170 std::string CPU = arm::getARMTargetCPU(CPU: CPUName, Arch: ArchName, Triple);
171 llvm::ARM::ArchKind ArchKind =
172 arm::getLLVMArchKindForARM(CPU, Arch: ArchName, Triple);
173 if (ArchKind == llvm::ARM::ArchKind::INVALID ||
174 (Split.second.size() && !DecodeARMFeatures(D, text: Split.second, CPU, ArchKind,
175 Features, ArgFPUKind)))
176 D.Diag(DiagID: clang::diag::err_drv_unsupported_option_argument)
177 << A->getSpelling() << A->getValue();
178}
179
180// If -mfloat-abi=hard or -mhard-float are specified explicitly then check that
181// floating point registers are available on the target CPU.
182static void checkARMFloatABI(const Driver &D, const ArgList &Args,
183 bool HasFPRegs) {
184 if (HasFPRegs)
185 return;
186 const Arg *A =
187 Args.getLastArg(Ids: options::OPT_msoft_float, Ids: options::OPT_mhard_float,
188 Ids: options::OPT_mfloat_abi_EQ);
189 if (A && (A->getOption().matches(ID: options::OPT_mhard_float) ||
190 (A->getOption().matches(ID: options::OPT_mfloat_abi_EQ) &&
191 A->getValue() == StringRef("hard"))))
192 D.Diag(DiagID: clang::diag::warn_drv_no_floating_point_registers)
193 << A->getAsString(Args);
194}
195
196bool arm::useAAPCSForMachO(const llvm::Triple &T) {
197 // The backend is hardwired to assume AAPCS for M-class processors, ensure
198 // the frontend matches that.
199 return T.getEnvironment() == llvm::Triple::EABI ||
200 T.getEnvironment() == llvm::Triple::EABIHF ||
201 T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(Triple: T);
202}
203
204// Check whether the architecture backend has support for the MRC/MCR
205// instructions that are used to set the hard thread pointer ("CP15 C13
206// Thread id").
207// This is not identical to ability to use the instruction, as the ARMV6K
208// variants can only use it in Arm mode since they don't support Thumb2
209// encoding.
210bool arm::isHardTPSupported(const llvm::Triple &Triple) {
211 int Ver = getARMSubArchVersionNumber(Triple);
212 llvm::ARM::ArchKind AK = llvm::ARM::parseArch(Arch: Triple.getArchName());
213 return AK == llvm::ARM::ArchKind::ARMV6K ||
214 AK == llvm::ARM::ArchKind::ARMV6KZ ||
215 (Ver >= 7 && !isARMMProfile(Triple));
216}
217
218// Checks whether the architecture is capable of supporting the Thumb2 encoding
219static bool supportsThumb2Encoding(const llvm::Triple &Triple) {
220 int Ver = arm::getARMSubArchVersionNumber(Triple);
221 llvm::ARM::ArchKind AK = llvm::ARM::parseArch(Arch: Triple.getArchName());
222 return AK == llvm::ARM::ArchKind::ARMV6T2 ||
223 (Ver >= 7 && AK != llvm::ARM::ArchKind::ARMV8MBaseline);
224}
225
226// Select mode for reading thread pointer (-mtp=soft/cp15).
227arm::ReadTPMode arm::getReadTPMode(const Driver &D, const ArgList &Args,
228 const llvm::Triple &Triple, bool ForAS) {
229 Arg *A = Args.getLastArg(Ids: options::OPT_mtp_mode_EQ);
230 if (A && A->getValue() != StringRef("auto")) {
231 arm::ReadTPMode ThreadPointer =
232 llvm::StringSwitch<arm::ReadTPMode>(A->getValue())
233 .Case(S: "cp15", Value: ReadTPMode::TPIDRURO)
234 .Case(S: "tpidrurw", Value: ReadTPMode::TPIDRURW)
235 .Case(S: "tpidruro", Value: ReadTPMode::TPIDRURO)
236 .Case(S: "tpidrprw", Value: ReadTPMode::TPIDRPRW)
237 .Case(S: "soft", Value: ReadTPMode::Soft)
238 .Default(Value: ReadTPMode::Invalid);
239 if ((ThreadPointer == ReadTPMode::TPIDRURW ||
240 ThreadPointer == ReadTPMode::TPIDRURO ||
241 ThreadPointer == ReadTPMode::TPIDRPRW) &&
242 !isHardTPSupported(Triple) && !ForAS) {
243 D.Diag(DiagID: diag::err_target_unsupported_tp_hard) << Triple.getArchName();
244 return ReadTPMode::Invalid;
245 }
246 if (ThreadPointer != ReadTPMode::Invalid)
247 return ThreadPointer;
248 if (StringRef(A->getValue()).empty())
249 D.Diag(DiagID: diag::err_drv_missing_arg_mtp) << A->getAsString(Args);
250 else
251 D.Diag(DiagID: diag::err_drv_invalid_mtp) << A->getAsString(Args);
252 return ReadTPMode::Invalid;
253 }
254 // In auto mode we enable HW mode only if both the hardware supports it and
255 // the thumb2 encoding. For example ARMV6T2 supports thumb2, but not hardware.
256 // ARMV6K has HW suport, but not thumb2. Otherwise we could enable it for
257 // ARMV6K in thumb mode.
258 bool autoUseHWTPMode =
259 isHardTPSupported(Triple) && supportsThumb2Encoding(Triple);
260 return autoUseHWTPMode ? ReadTPMode::TPIDRURO : ReadTPMode::Soft;
261}
262
263void arm::setArchNameInTriple(const Driver &D, const ArgList &Args,
264 types::ID InputType, llvm::Triple &Triple) {
265 StringRef MCPU, MArch;
266 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ))
267 MCPU = A->getValue();
268 if (const Arg *A = Args.getLastArg(Ids: options::OPT_march_EQ))
269 MArch = A->getValue();
270
271 std::string CPU = Triple.isOSBinFormatMachO()
272 ? tools::arm::getARMCPUForMArch(Arch: MArch, Triple).str()
273 : tools::arm::getARMTargetCPU(CPU: MCPU, Arch: MArch, Triple);
274 StringRef Suffix = tools::arm::getLLVMArchSuffixForARM(CPU, Arch: MArch, Triple);
275
276 bool IsBigEndian = Triple.getArch() == llvm::Triple::armeb ||
277 Triple.getArch() == llvm::Triple::thumbeb;
278 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
279 // '-mbig-endian'/'-EB'.
280 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlittle_endian,
281 Ids: options::OPT_mbig_endian)) {
282 IsBigEndian = !A->getOption().matches(ID: options::OPT_mlittle_endian);
283 }
284 std::string ArchName = IsBigEndian ? "armeb" : "arm";
285
286 // FIXME: Thumb should just be another -target-feaure, not in the triple.
287 bool IsMProfile =
288 llvm::ARM::parseArchProfile(Arch: Suffix) == llvm::ARM::ProfileKind::M;
289 bool ThumbDefault = IsMProfile ||
290 // Thumb2 is the default for V7 on Darwin.
291 (llvm::ARM::parseArchVersion(Arch: Suffix) == 7 &&
292 Triple.isOSBinFormatMachO()) ||
293 // Thumb2 is the default for Fuchsia.
294 Triple.isOSFuchsia() ||
295 // FIXME: this is invalid for WindowsCE
296 Triple.isOSWindows();
297
298 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
299 // M-Class CPUs/architecture variants, which is not supported.
300 bool ARMModeRequested =
301 !Args.hasFlag(Pos: options::OPT_mthumb, Neg: options::OPT_mno_thumb, Default: ThumbDefault);
302 if (IsMProfile && ARMModeRequested) {
303 if (MCPU.size())
304 D.Diag(DiagID: diag::err_cpu_unsupported_isa) << CPU << "ARM";
305 else
306 D.Diag(DiagID: diag::err_arch_unsupported_isa)
307 << tools::arm::getARMArch(Arch: MArch, Triple) << "ARM";
308 }
309
310 // Check to see if an explicit choice to use thumb has been made via
311 // -mthumb. For assembler files we must check for -mthumb in the options
312 // passed to the assembler via -Wa or -Xassembler.
313 bool IsThumb = false;
314 if (InputType != types::TY_PP_Asm)
315 IsThumb =
316 Args.hasFlag(Pos: options::OPT_mthumb, Neg: options::OPT_mno_thumb, Default: ThumbDefault);
317 else {
318 // Ideally we would check for these flags in
319 // CollectArgsForIntegratedAssembler but we can't change the ArchName at
320 // that point.
321 llvm::StringRef WaMArch, WaMCPU;
322 for (const auto *A :
323 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler)) {
324 for (StringRef Value : A->getValues()) {
325 // There is no assembler equivalent of -mno-thumb, -marm, or -mno-arm.
326 if (Value == "-mthumb")
327 IsThumb = true;
328 else if (Value.starts_with(Prefix: "-march="))
329 WaMArch = Value.substr(Start: 7);
330 else if (Value.starts_with(Prefix: "-mcpu="))
331 WaMCPU = Value.substr(Start: 6);
332 }
333 }
334
335 if (WaMCPU.size() || WaMArch.size()) {
336 // The way this works means that we prefer -Wa,-mcpu's architecture
337 // over -Wa,-march. Which matches the compiler behaviour.
338 Suffix = tools::arm::getLLVMArchSuffixForARM(CPU: WaMCPU, Arch: WaMArch, Triple);
339 }
340 }
341
342 // Assembly files should start in ARM mode, unless arch is M-profile, or
343 // -mthumb has been passed explicitly to the assembler. Windows is always
344 // thumb.
345 if (IsThumb || IsMProfile || Triple.isOSWindows()) {
346 if (IsBigEndian)
347 ArchName = "thumbeb";
348 else
349 ArchName = "thumb";
350 }
351 Triple.setArchName(ArchName + Suffix.str());
352}
353
354void arm::setFloatABIInTriple(const Driver &D, const ArgList &Args,
355 llvm::Triple &Triple) {
356 if (Triple.isOSLiteOS()) {
357 Triple.setEnvironment(llvm::Triple::OpenHOS);
358 return;
359 }
360
361 bool isHardFloat =
362 (arm::getARMFloatABI(D, Triple, Args) == arm::FloatABI::Hard);
363
364 switch (Triple.getEnvironment()) {
365 case llvm::Triple::GNUEABI:
366 case llvm::Triple::GNUEABIHF:
367 Triple.setEnvironment(isHardFloat ? llvm::Triple::GNUEABIHF
368 : llvm::Triple::GNUEABI);
369 break;
370 case llvm::Triple::GNUEABIT64:
371 case llvm::Triple::GNUEABIHFT64:
372 Triple.setEnvironment(isHardFloat ? llvm::Triple::GNUEABIHFT64
373 : llvm::Triple::GNUEABIT64);
374 break;
375 case llvm::Triple::EABI:
376 case llvm::Triple::EABIHF:
377 Triple.setEnvironment(isHardFloat ? llvm::Triple::EABIHF
378 : llvm::Triple::EABI);
379 break;
380 case llvm::Triple::MuslEABI:
381 case llvm::Triple::MuslEABIHF:
382 Triple.setEnvironment(isHardFloat ? llvm::Triple::MuslEABIHF
383 : llvm::Triple::MuslEABI);
384 break;
385 case llvm::Triple::OpenHOS:
386 break;
387 default: {
388 arm::FloatABI DefaultABI = arm::getDefaultFloatABI(Triple);
389 if (DefaultABI != arm::FloatABI::Invalid &&
390 isHardFloat != (DefaultABI == arm::FloatABI::Hard)) {
391 Arg *ABIArg =
392 Args.getLastArg(Ids: options::OPT_msoft_float, Ids: options::OPT_mhard_float,
393 Ids: options::OPT_mfloat_abi_EQ);
394 assert(ABIArg && "Non-default float abi expected to be from arg");
395 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
396 << ABIArg->getAsString(Args) << Triple.getTriple();
397 }
398 break;
399 }
400 }
401}
402
403arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
404 return arm::getARMFloatABI(D: TC.getDriver(), Triple: TC.getEffectiveTriple(), Args);
405}
406
407arm::FloatABI arm::getDefaultFloatABI(const llvm::Triple &Triple) {
408 auto SubArch = getARMSubArchVersionNumber(Triple);
409 switch (Triple.getOS()) {
410 case llvm::Triple::Darwin:
411 case llvm::Triple::MacOSX:
412 case llvm::Triple::IOS:
413 case llvm::Triple::TvOS:
414 case llvm::Triple::DriverKit:
415 case llvm::Triple::XROS:
416 // Darwin defaults to "softfp" for v6 and v7.
417 if (Triple.isWatchABI())
418 return FloatABI::Hard;
419 else
420 return (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
421
422 case llvm::Triple::WatchOS:
423 return FloatABI::Hard;
424
425 // FIXME: this is invalid for WindowsCE
426 case llvm::Triple::Win32:
427 // It is incorrect to select hard float ABI on MachO platforms if the ABI is
428 // "apcs-gnu".
429 if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(T: Triple))
430 return FloatABI::Soft;
431 return FloatABI::Hard;
432
433 case llvm::Triple::NetBSD:
434 switch (Triple.getEnvironment()) {
435 case llvm::Triple::EABIHF:
436 case llvm::Triple::GNUEABIHF:
437 return FloatABI::Hard;
438 default:
439 return FloatABI::Soft;
440 }
441 break;
442
443 case llvm::Triple::FreeBSD:
444 switch (Triple.getEnvironment()) {
445 case llvm::Triple::GNUEABIHF:
446 return FloatABI::Hard;
447 default:
448 // FreeBSD defaults to soft float
449 return FloatABI::Soft;
450 }
451 break;
452
453 case llvm::Triple::Haiku:
454 case llvm::Triple::OpenBSD:
455 return FloatABI::SoftFP;
456
457 case llvm::Triple::Fuchsia:
458 return FloatABI::Hard;
459
460 default:
461 if (Triple.isOHOSFamily())
462 return FloatABI::Soft;
463 switch (Triple.getEnvironment()) {
464 case llvm::Triple::GNUEABIHF:
465 case llvm::Triple::GNUEABIHFT64:
466 case llvm::Triple::MuslEABIHF:
467 case llvm::Triple::EABIHF:
468 return FloatABI::Hard;
469 case llvm::Triple::Android:
470 case llvm::Triple::GNUEABI:
471 case llvm::Triple::GNUEABIT64:
472 case llvm::Triple::MuslEABI:
473 case llvm::Triple::EABI:
474 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
475 return FloatABI::SoftFP;
476 default:
477 return FloatABI::Invalid;
478 }
479 }
480 return FloatABI::Invalid;
481}
482
483// Select the float ABI as determined by -msoft-float, -mhard-float, and
484// -mfloat-abi=.
485arm::FloatABI arm::getARMFloatABI(const Driver &D, const llvm::Triple &Triple,
486 const ArgList &Args) {
487 arm::FloatABI ABI = FloatABI::Invalid;
488 if (Arg *A =
489 Args.getLastArg(Ids: options::OPT_msoft_float, Ids: options::OPT_mhard_float,
490 Ids: options::OPT_mfloat_abi_EQ)) {
491 if (A->getOption().matches(ID: options::OPT_msoft_float)) {
492 ABI = FloatABI::Soft;
493 } else if (A->getOption().matches(ID: options::OPT_mhard_float)) {
494 ABI = FloatABI::Hard;
495 } else {
496 ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
497 .Case(S: "soft", Value: FloatABI::Soft)
498 .Case(S: "softfp", Value: FloatABI::SoftFP)
499 .Case(S: "hard", Value: FloatABI::Hard)
500 .Default(Value: FloatABI::Invalid);
501 if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
502 D.Diag(DiagID: diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
503 ABI = FloatABI::Soft;
504 }
505 }
506 }
507
508 // If unspecified, choose the default based on the platform.
509 if (ABI == FloatABI::Invalid)
510 ABI = arm::getDefaultFloatABI(Triple);
511
512 if (ABI == FloatABI::Invalid) {
513 // Assume "soft", but warn the user we are guessing.
514 if (Triple.isOSBinFormatMachO() &&
515 Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
516 ABI = FloatABI::Hard;
517 else
518 ABI = FloatABI::Soft;
519
520 if (((Triple.getOS() != llvm::Triple::UnknownOS) &&
521 !Triple.isOSFirmware()) ||
522 !Triple.isOSBinFormatMachO())
523 D.Diag(DiagID: diag::warn_drv_assuming_mfloat_abi_is) << "soft";
524 }
525
526 assert(ABI != FloatABI::Invalid && "must select an ABI");
527 return ABI;
528}
529
530static bool hasIntegerMVE(const std::vector<StringRef> &F) {
531 auto MVE = llvm::find(Range: llvm::reverse(C: F), Val: "+mve");
532 auto NoMVE = llvm::find(Range: llvm::reverse(C: F), Val: "-mve");
533 return MVE != F.rend() &&
534 (NoMVE == F.rend() || std::distance(first: MVE, last: NoMVE) > 0);
535}
536
537llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver &D,
538 const llvm::Triple &Triple,
539 const ArgList &Args,
540 std::vector<StringRef> &Features,
541 bool ForAS, bool ForMultilib) {
542 bool KernelOrKext =
543 Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext);
544 arm::FloatABI ABI = arm::getARMFloatABI(D, Triple, Args);
545 std::optional<std::pair<const Arg *, StringRef>> WaCPU, WaFPU, WaHDiv, WaArch;
546
547 // This vector will accumulate features from the architecture
548 // extension suffixes on -mcpu and -march (e.g. the 'bar' in
549 // -mcpu=foo+bar). We want to apply those after the features derived
550 // from the FPU, in case -mfpu generates a negative feature which
551 // the +bar is supposed to override.
552 std::vector<StringRef> ExtensionFeatures;
553
554 if (!ForAS) {
555 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
556 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
557 // stripped out by the ARM target. We should probably pass this a new
558 // -target-option, which is handled by the -cc1/-cc1as invocation.
559 //
560 // FIXME2: For consistency, it would be ideal if we set up the target
561 // machine state the same when using the frontend or the assembler. We don't
562 // currently do that for the assembler, we pass the options directly to the
563 // backend and never even instantiate the frontend TargetInfo. If we did,
564 // and used its handleTargetFeatures hook, then we could ensure the
565 // assembler and the frontend behave the same.
566
567 // Use software floating point operations?
568 if (ABI == arm::FloatABI::Soft)
569 Features.push_back(x: "+soft-float");
570
571 // Use software floating point argument passing?
572 if (ABI != arm::FloatABI::Hard)
573 Features.push_back(x: "+soft-float-abi");
574 } else {
575 // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
576 // to the assembler correctly.
577 for (const Arg *A :
578 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler)) {
579 // We use getValues here because you can have many options per -Wa
580 // We will keep the last one we find for each of these
581 for (StringRef Value : A->getValues()) {
582 if (Value.starts_with(Prefix: "-mfpu=")) {
583 WaFPU = std::make_pair(x&: A, y: Value.substr(Start: 6));
584 } else if (Value.starts_with(Prefix: "-mcpu=")) {
585 WaCPU = std::make_pair(x&: A, y: Value.substr(Start: 6));
586 } else if (Value.starts_with(Prefix: "-mhwdiv=")) {
587 WaHDiv = std::make_pair(x&: A, y: Value.substr(Start: 8));
588 } else if (Value.starts_with(Prefix: "-march=")) {
589 WaArch = std::make_pair(x&: A, y: Value.substr(Start: 7));
590 }
591 }
592 }
593
594 // The integrated assembler doesn't implement e_flags setting behavior for
595 // -meabi=gnu (gcc -mabi={apcs-gnu,atpcs} passes -meabi=gnu to gas). For
596 // compatibility we accept but warn.
597 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_mabi_EQ))
598 A->ignoreTargetSpecific();
599 }
600
601 arm::ReadTPMode TPMode = getReadTPMode(D, Args, Triple, ForAS);
602
603 if (TPMode == ReadTPMode::TPIDRURW)
604 Features.push_back(x: "+read-tp-tpidrurw");
605 else if (TPMode == ReadTPMode::TPIDRPRW)
606 Features.push_back(x: "+read-tp-tpidrprw");
607 else if (TPMode == ReadTPMode::TPIDRURO)
608 Features.push_back(x: "+read-tp-tpidruro");
609
610 const Arg *ArchArg = Args.getLastArg(Ids: options::OPT_march_EQ);
611 const Arg *CPUArg = Args.getLastArg(Ids: options::OPT_mcpu_EQ);
612 StringRef ArchName;
613 StringRef CPUName;
614 llvm::ARM::FPUKind ArchArgFPUKind = llvm::ARM::FK_INVALID;
615 llvm::ARM::FPUKind CPUArgFPUKind = llvm::ARM::FK_INVALID;
616
617 // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
618 if (WaCPU) {
619 if (CPUArg)
620 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
621 << CPUArg->getAsString(Args);
622 CPUName = WaCPU->second;
623 CPUArg = WaCPU->first;
624 } else if (CPUArg)
625 CPUName = CPUArg->getValue();
626
627 // Check -march. ClangAs gives preference to -Wa,-march=.
628 if (WaArch) {
629 if (ArchArg)
630 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
631 << ArchArg->getAsString(Args);
632 ArchName = WaArch->second;
633 // This will set any features after the base architecture.
634 checkARMArchName(D, A: WaArch->first, Args, ArchName, CPUName,
635 Features&: ExtensionFeatures, Triple, ArgFPUKind&: ArchArgFPUKind);
636 // The base architecture was handled in ToolChain::ComputeLLVMTriple because
637 // triple is read only by this point.
638 } else if (ArchArg) {
639 ArchName = ArchArg->getValue();
640 checkARMArchName(D, A: ArchArg, Args, ArchName, CPUName, Features&: ExtensionFeatures,
641 Triple, ArgFPUKind&: ArchArgFPUKind);
642 }
643
644 // Add CPU features for generic CPUs
645 if (CPUName == "native") {
646 for (auto &F : llvm::sys::getHostCPUFeatures())
647 Features.push_back(
648 x: Args.MakeArgString(Str: (F.second ? "+" : "-") + F.first()));
649 } else if (!CPUName.empty()) {
650 // This sets the default features for the specified CPU. We certainly don't
651 // want to override the features that have been explicitly specified on the
652 // command line. Therefore, process them directly instead of appending them
653 // at the end later.
654 DecodeARMFeaturesFromCPU(D, CPU: CPUName, Features);
655 }
656
657 if (CPUArg)
658 checkARMCPUName(D, A: CPUArg, Args, CPUName, ArchName, Features&: ExtensionFeatures,
659 Triple, ArgFPUKind&: CPUArgFPUKind);
660
661 // TODO Handle -mtune=. Suppress -Wunused-command-line-argument as a
662 // longstanding behavior.
663 (void)Args.getLastArg(Ids: options::OPT_mtune_EQ);
664
665 // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
666 llvm::ARM::FPUKind FPUKind = llvm::ARM::FK_INVALID;
667 const Arg *FPUArg = Args.getLastArg(Ids: options::OPT_mfpu_EQ);
668 if (WaFPU) {
669 if (FPUArg)
670 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
671 << FPUArg->getAsString(Args);
672 (void)getARMFPUFeatures(D, A: WaFPU->first, Args, FPU: WaFPU->second, Features);
673 } else if (FPUArg) {
674 FPUKind = getARMFPUFeatures(D, A: FPUArg, Args, FPU: FPUArg->getValue(), Features);
675 } else if (Triple.isAndroid() && getARMSubArchVersionNumber(Triple) == 7) {
676 const char *AndroidFPU = "neon";
677 FPUKind = llvm::ARM::parseFPU(FPU: AndroidFPU);
678 if (!llvm::ARM::getFPUFeatures(FPUKind, Features))
679 D.Diag(DiagID: clang::diag::err_drv_clang_unsupported)
680 << std::string("-mfpu=") + AndroidFPU;
681 } else if (ArchArgFPUKind != llvm::ARM::FK_INVALID ||
682 CPUArgFPUKind != llvm::ARM::FK_INVALID) {
683 FPUKind =
684 CPUArgFPUKind != llvm::ARM::FK_INVALID ? CPUArgFPUKind : ArchArgFPUKind;
685 (void)llvm::ARM::getFPUFeatures(FPUKind, Features);
686 } else {
687 std::string CPU = arm::getARMTargetCPU(CPU: CPUName, Arch: ArchName, Triple);
688 bool Generic = CPU == "generic";
689 if (Generic && (Triple.isOSWindows() || Triple.isOSDarwin()) &&
690 getARMSubArchVersionNumber(Triple) >= 7) {
691 FPUKind = llvm::ARM::parseFPU(FPU: "neon");
692 } else {
693 llvm::ARM::ArchKind ArchKind =
694 arm::getLLVMArchKindForARM(CPU, Arch: ArchName, Triple);
695 FPUKind = llvm::ARM::getDefaultFPU(CPU, AK: ArchKind);
696 }
697 (void)llvm::ARM::getFPUFeatures(FPUKind, Features);
698 }
699
700 // Now we've finished accumulating features from arch, cpu and fpu,
701 // we can append the ones for architecture extensions that we
702 // collected separately.
703 Features.insert(position: std::end(cont&: Features),
704 first: std::begin(cont&: ExtensionFeatures), last: std::end(cont&: ExtensionFeatures));
705
706 // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
707 const Arg *HDivArg = Args.getLastArg(Ids: options::OPT_mhwdiv_EQ);
708 if (WaHDiv) {
709 if (HDivArg)
710 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
711 << HDivArg->getAsString(Args);
712 getARMHWDivFeatures(D, A: WaHDiv->first, Args, HWDiv: WaHDiv->second, Features);
713 } else if (HDivArg)
714 getARMHWDivFeatures(D, A: HDivArg, Args, HWDiv: HDivArg->getValue(), Features);
715
716 // Handle (arch-dependent) fp16fml/fullfp16 relationship.
717 // Must happen before any features are disabled due to soft-float.
718 // FIXME: this fp16fml option handling will be reimplemented after the
719 // TargetParser rewrite.
720 const auto ItRNoFullFP16 = std::find(first: Features.rbegin(), last: Features.rend(), val: "-fullfp16");
721 const auto ItRFP16FML = std::find(first: Features.rbegin(), last: Features.rend(), val: "+fp16fml");
722 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_4a) {
723 const auto ItRFullFP16 = std::find(first: Features.rbegin(), last: Features.rend(), val: "+fullfp16");
724 if (ItRFullFP16 < ItRNoFullFP16 && ItRFullFP16 < ItRFP16FML) {
725 // Only entangled feature that can be to the right of this +fullfp16 is -fp16fml.
726 // Only append the +fp16fml if there is no -fp16fml after the +fullfp16.
727 if (std::find(first: Features.rbegin(), last: ItRFullFP16, val: "-fp16fml") == ItRFullFP16)
728 Features.push_back(x: "+fp16fml");
729 }
730 else
731 goto fp16_fml_fallthrough;
732 }
733 else {
734fp16_fml_fallthrough:
735 // In both of these cases, putting the 'other' feature on the end of the vector will
736 // result in the same effect as placing it immediately after the current feature.
737 if (ItRNoFullFP16 < ItRFP16FML)
738 Features.push_back(x: "-fp16fml");
739 else if (ItRNoFullFP16 > ItRFP16FML)
740 Features.push_back(x: "+fullfp16");
741 }
742
743 // Setting -msoft-float/-mfloat-abi=soft, -mfpu=none, or adding +nofp to
744 // -march/-mcpu effectively disables the FPU (GCC ignores the -mfpu options in
745 // this case). Note that the ABI can also be set implicitly by the target
746 // selected.
747 bool HasFPRegs = true;
748 if (ABI == arm::FloatABI::Soft) {
749 llvm::ARM::getFPUFeatures(FPUKind: llvm::ARM::FK_NONE, Features);
750
751 // Disable all features relating to hardware FP, not already disabled by the
752 // above call.
753 Features.insert(position: Features.end(),
754 l: {"-dotprod", "-fp16fml", "-bf16", "-mve", "-mve.fp"});
755 HasFPRegs = false;
756 FPUKind = llvm::ARM::FK_NONE;
757 } else if (FPUKind == llvm::ARM::FK_NONE ||
758 ArchArgFPUKind == llvm::ARM::FK_NONE ||
759 CPUArgFPUKind == llvm::ARM::FK_NONE) {
760 // -mfpu=none, -march=armvX+nofp or -mcpu=X+nofp is *very* similar to
761 // -mfloat-abi=soft, only that it should not disable MVE-I. They disable the
762 // FPU, but not the FPU registers, thus MVE-I, which depends only on the
763 // latter, is still supported.
764 Features.insert(position: Features.end(),
765 l: {"-dotprod", "-fp16fml", "-bf16", "-mve.fp"});
766 HasFPRegs = hasIntegerMVE(F: Features);
767 FPUKind = llvm::ARM::FK_NONE;
768 }
769 if (!HasFPRegs)
770 Features.emplace_back(args: "-fpregs");
771
772 // En/disable crc code generation.
773 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcrc, Ids: options::OPT_mnocrc)) {
774 if (A->getOption().matches(ID: options::OPT_mcrc))
775 Features.push_back(x: "+crc");
776 else
777 Features.push_back(x: "-crc");
778 }
779
780 // Invalid value of the __ARM_FEATURE_MVE macro when an explicit -mfpu= option
781 // disables MVE-FP -mfpu=fpv5-d16 or -mfpu=fpv5-sp-d16 disables the scalar
782 // half-precision floating-point operations feature. Therefore, because the
783 // M-profile Vector Extension (MVE) floating-point feature requires the scalar
784 // half-precision floating-point operations, this option also disables the MVE
785 // floating-point feature: -mve.fp
786 if (FPUKind == llvm::ARM::FK_FPV5_D16 || FPUKind == llvm::ARM::FK_FPV5_SP_D16)
787 Features.push_back(x: "-mve.fp");
788
789 // If SIMD has been disabled and the selected FPU supports NEON, then features
790 // that rely on NEON instructions should also be disabled.
791 bool HasSimd = false;
792 const auto ItSimd =
793 llvm::find_if(Range: llvm::reverse(C&: Features),
794 P: [](const StringRef F) { return F.contains(Other: "neon"); });
795 const bool FPUSupportsNeon = (llvm::ARM::FPUNames[FPUKind].NeonSupport ==
796 llvm::ARM::NeonSupportLevel::Neon) ||
797 (llvm::ARM::FPUNames[FPUKind].NeonSupport ==
798 llvm::ARM::NeonSupportLevel::Crypto);
799 if (ItSimd != Features.rend())
800 HasSimd = ItSimd->starts_with(Prefix: "+");
801 if (!HasSimd && FPUSupportsNeon)
802 Features.insert(position: Features.end(),
803 l: {"-sha2", "-aes", "-crypto", "-dotprod", "-bf16", "-i8mm"});
804
805 // For Arch >= ARMv8.0 && A or R profile: crypto = sha2 + aes
806 // Rather than replace within the feature vector, determine whether each
807 // algorithm is enabled and append this to the end of the vector.
808 // The algorithms can be controlled by their specific feature or the crypto
809 // feature, so their status can be determined by the last occurance of
810 // either in the vector. This allows one to supercede the other.
811 // e.g. +crypto+noaes in -march/-mcpu should enable sha2, but not aes
812 // FIXME: this needs reimplementation after the TargetParser rewrite
813 bool HasSHA2 = false;
814 bool HasAES = false;
815 bool HasBF16 = false;
816 bool HasDotprod = false;
817 bool HasI8MM = false;
818 const auto ItCrypto =
819 llvm::find_if(Range: llvm::reverse(C&: Features), P: [](const StringRef F) {
820 return F.contains(Other: "crypto");
821 });
822 const auto ItSHA2 =
823 llvm::find_if(Range: llvm::reverse(C&: Features), P: [](const StringRef F) {
824 return F.contains(Other: "crypto") || F.contains(Other: "sha2");
825 });
826 const auto ItAES =
827 llvm::find_if(Range: llvm::reverse(C&: Features), P: [](const StringRef F) {
828 return F.contains(Other: "crypto") || F.contains(Other: "aes");
829 });
830 const auto ItBF16 =
831 llvm::find_if(Range: llvm::reverse(C&: Features),
832 P: [](const StringRef F) { return F.contains(Other: "bf16"); });
833 const auto ItDotprod =
834 llvm::find_if(Range: llvm::reverse(C&: Features),
835 P: [](const StringRef F) { return F.contains(Other: "dotprod"); });
836 const auto ItI8MM =
837 llvm::find_if(Range: llvm::reverse(C&: Features),
838 P: [](const StringRef F) { return F.contains(Other: "i8mm"); });
839 if (ItSHA2 != Features.rend())
840 HasSHA2 = ItSHA2->starts_with(Prefix: "+");
841 if (ItAES != Features.rend())
842 HasAES = ItAES->starts_with(Prefix: "+");
843 if (ItBF16 != Features.rend())
844 HasBF16 = ItBF16->starts_with(Prefix: "+");
845 if (ItDotprod != Features.rend())
846 HasDotprod = ItDotprod->starts_with(Prefix: "+");
847 if (ItI8MM != Features.rend())
848 HasI8MM = ItI8MM->starts_with(Prefix: "+");
849 if (ItCrypto != Features.rend()) {
850 if (HasSHA2 && HasAES)
851 Features.push_back(x: "+crypto");
852 else
853 Features.push_back(x: "-crypto");
854 if (HasSHA2)
855 Features.push_back(x: "+sha2");
856 else
857 Features.push_back(x: "-sha2");
858 if (HasAES)
859 Features.push_back(x: "+aes");
860 else
861 Features.push_back(x: "-aes");
862 }
863 // If any of these features are enabled, NEON should also be enabled.
864 if (HasAES || HasSHA2 || HasBF16 || HasDotprod || HasI8MM)
865 Features.push_back(x: "+neon");
866
867 if (HasSHA2 || HasAES) {
868 StringRef ArchSuffix = arm::getLLVMArchSuffixForARM(
869 CPU: arm::getARMTargetCPU(CPU: CPUName, Arch: ArchName, Triple), Arch: ArchName, Triple);
870 llvm::ARM::ProfileKind ArchProfile =
871 llvm::ARM::parseArchProfile(Arch: ArchSuffix);
872 if (!((llvm::ARM::parseArchVersion(Arch: ArchSuffix) >= 8) &&
873 (ArchProfile == llvm::ARM::ProfileKind::A ||
874 ArchProfile == llvm::ARM::ProfileKind::R))) {
875 if (HasSHA2)
876 D.Diag(DiagID: clang::diag::warn_target_unsupported_extension)
877 << "sha2"
878 << llvm::ARM::getArchName(AK: llvm::ARM::parseArch(Arch: ArchSuffix));
879 if (HasAES)
880 D.Diag(DiagID: clang::diag::warn_target_unsupported_extension)
881 << "aes"
882 << llvm::ARM::getArchName(AK: llvm::ARM::parseArch(Arch: ArchSuffix));
883 // With -fno-integrated-as -mfpu=crypto-neon-fp-armv8 some assemblers such
884 // as the GNU assembler will permit the use of crypto instructions as the
885 // fpu will override the architecture. We keep the crypto feature in this
886 // case to preserve compatibility. In all other cases we remove the crypto
887 // feature.
888 if (!Args.hasArg(Ids: options::OPT_fno_integrated_as)) {
889 Features.push_back(x: "-sha2");
890 Features.push_back(x: "-aes");
891 }
892 }
893 }
894
895 // Propagate frame-chain model selection
896 if (Arg *A = Args.getLastArg(Ids: options::OPT_mframe_chain)) {
897 StringRef FrameChainOption = A->getValue();
898 if (FrameChainOption.starts_with(Prefix: "aapcs"))
899 Features.push_back(x: "+aapcs-frame-chain");
900 }
901
902 // CMSE: Check for target 8M (for -mcmse to be applicable) is performed later.
903 if (Args.getLastArg(Ids: options::OPT_mcmse))
904 Features.push_back(x: "+8msecext");
905
906 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfix_cmse_cve_2021_35465,
907 Ids: options::OPT_mno_fix_cmse_cve_2021_35465)) {
908 if (!Args.getLastArg(Ids: options::OPT_mcmse))
909 D.Diag(DiagID: diag::err_opt_not_valid_without_opt)
910 << A->getOption().getName() << "-mcmse";
911
912 if (A->getOption().matches(ID: options::OPT_mfix_cmse_cve_2021_35465))
913 Features.push_back(x: "+fix-cmse-cve-2021-35465");
914 else
915 Features.push_back(x: "-fix-cmse-cve-2021-35465");
916 }
917
918 // This also handles the -m(no-)fix-cortex-a72-1655431 arguments via aliases.
919 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfix_cortex_a57_aes_1742098,
920 Ids: options::OPT_mno_fix_cortex_a57_aes_1742098)) {
921 if (A->getOption().matches(ID: options::OPT_mfix_cortex_a57_aes_1742098)) {
922 Features.push_back(x: "+fix-cortex-a57-aes-1742098");
923 } else {
924 Features.push_back(x: "-fix-cortex-a57-aes-1742098");
925 }
926 }
927
928 // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
929 // neither options are specified, see if we are compiling for kernel/kext and
930 // decide whether to pass "+long-calls" based on the OS and its version.
931 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlong_calls,
932 Ids: options::OPT_mno_long_calls)) {
933 if (A->getOption().matches(ID: options::OPT_mlong_calls))
934 Features.push_back(x: "+long-calls");
935 } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(Major: 6)) &&
936 !Triple.isWatchOS() && !Triple.isXROS()) {
937 Features.push_back(x: "+long-calls");
938 }
939
940 // Generate execute-only output (no data access to code sections).
941 // This only makes sense for the compiler, not for the assembler.
942 // It's not needed for multilib selection and may hide an unused
943 // argument diagnostic if the code is always run.
944 if (!ForAS && !ForMultilib) {
945 // Supported only on ARMv6T2 and ARMv7 and above.
946 // Cannot be combined with -mno-movt.
947 if (Arg *A = Args.getLastArg(Ids: options::OPT_mexecute_only, Ids: options::OPT_mno_execute_only)) {
948 if (A->getOption().matches(ID: options::OPT_mexecute_only)) {
949 if (getARMSubArchVersionNumber(Triple) < 7 &&
950 llvm::ARM::parseArch(Arch: Triple.getArchName()) != llvm::ARM::ArchKind::ARMV6T2 &&
951 llvm::ARM::parseArch(Arch: Triple.getArchName()) != llvm::ARM::ArchKind::ARMV6M)
952 D.Diag(DiagID: diag::err_target_unsupported_execute_only) << Triple.getArchName();
953 else if (llvm::ARM::parseArch(Arch: Triple.getArchName()) == llvm::ARM::ArchKind::ARMV6M) {
954 if (Arg *PIArg = Args.getLastArg(Ids: options::OPT_fropi, Ids: options::OPT_frwpi,
955 Ids: options::OPT_fpic, Ids: options::OPT_fpie,
956 Ids: options::OPT_fPIC, Ids: options::OPT_fPIE))
957 D.Diag(DiagID: diag::err_opt_not_valid_with_opt_on_target)
958 << A->getAsString(Args) << PIArg->getAsString(Args) << Triple.getArchName();
959 } else if (Arg *B = Args.getLastArg(Ids: options::OPT_mno_movt))
960 D.Diag(DiagID: diag::err_opt_not_valid_with_opt)
961 << A->getAsString(Args) << B->getAsString(Args);
962 Features.push_back(x: "+execute-only");
963 }
964 }
965 }
966
967 if (Arg *A = Args.getLastArg(Ids: options::OPT_mno_unaligned_access,
968 Ids: options::OPT_munaligned_access,
969 Ids: options::OPT_mstrict_align,
970 Ids: options::OPT_mno_strict_align)) {
971 // Kernel code has more strict alignment requirements.
972 if (KernelOrKext ||
973 A->getOption().matches(ID: options::OPT_mno_unaligned_access) ||
974 A->getOption().matches(ID: options::OPT_mstrict_align)) {
975 Features.push_back(x: "+strict-align");
976 } else {
977 // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
978 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
979 D.Diag(DiagID: diag::err_target_unsupported_unaligned) << "v6m";
980 // v8M Baseline follows on from v6M, so doesn't support unaligned memory
981 // access either.
982 else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
983 D.Diag(DiagID: diag::err_target_unsupported_unaligned) << "v8m.base";
984 }
985 } else {
986 // Assume pre-ARMv6 doesn't support unaligned accesses.
987 //
988 // ARMv6 may or may not support unaligned accesses depending on the
989 // SCTLR.U bit, which is architecture-specific. We assume ARMv6
990 // Darwin and NetBSD targets support unaligned accesses, and others don't.
991 //
992 // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit which
993 // raises an alignment fault on unaligned accesses. Assume ARMv7+ supports
994 // unaligned accesses, except ARMv6-M, and ARMv8-M without the Main
995 // Extension. This aligns with the default behavior of ARM's downstream
996 // versions of GCC and Clang.
997 //
998 // Users can change the default behavior via -m[no-]unaliged-access.
999 int VersionNum = getARMSubArchVersionNumber(Triple);
1000 if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
1001 if (VersionNum < 6 ||
1002 Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
1003 Features.push_back(x: "+strict-align");
1004 } else if (Triple.getVendor() == llvm::Triple::Apple &&
1005 Triple.isOSBinFormatMachO()) {
1006 // Firmwares on Apple platforms are strict-align by default.
1007 Features.push_back(x: "+strict-align");
1008 } else if (VersionNum < 7 ||
1009 Triple.getSubArch() ==
1010 llvm::Triple::SubArchType::ARMSubArch_v6m ||
1011 Triple.getSubArch() ==
1012 llvm::Triple::SubArchType::ARMSubArch_v8m_baseline) {
1013 Features.push_back(x: "+strict-align");
1014 }
1015 }
1016
1017 // llvm does not support reserving registers in general. There is support
1018 // for reserving r9 on ARM though (defined as a platform-specific register
1019 // in ARM EABI).
1020 if (Args.hasArg(Ids: options::OPT_ffixed_r9))
1021 Features.push_back(x: "+reserve-r9");
1022
1023 // The kext linker doesn't know how to deal with movw/movt.
1024 if (KernelOrKext || Args.hasArg(Ids: options::OPT_mno_movt))
1025 Features.push_back(x: "+no-movt");
1026
1027 if (Args.hasArg(Ids: options::OPT_mno_neg_immediates))
1028 Features.push_back(x: "+no-neg-immediates");
1029
1030 // Enable/disable straight line speculation hardening.
1031 if (Arg *A = Args.getLastArg(Ids: options::OPT_mharden_sls_EQ)) {
1032 StringRef Scope = A->getValue();
1033 bool EnableRetBr = false;
1034 bool EnableBlr = false;
1035 bool DisableComdat = false;
1036 if (Scope != "none") {
1037 SmallVector<StringRef, 4> Opts;
1038 Scope.split(A&: Opts, Separator: ",");
1039 for (auto Opt : Opts) {
1040 Opt = Opt.trim();
1041 if (Opt == "all") {
1042 EnableBlr = true;
1043 EnableRetBr = true;
1044 continue;
1045 }
1046 if (Opt == "retbr") {
1047 EnableRetBr = true;
1048 continue;
1049 }
1050 if (Opt == "blr") {
1051 EnableBlr = true;
1052 continue;
1053 }
1054 if (Opt == "comdat") {
1055 DisableComdat = false;
1056 continue;
1057 }
1058 if (Opt == "nocomdat") {
1059 DisableComdat = true;
1060 continue;
1061 }
1062 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1063 << A->getSpelling() << Scope;
1064 break;
1065 }
1066 }
1067
1068 if (EnableRetBr || EnableBlr)
1069 if (!(isARMAProfile(Triple) && getARMSubArchVersionNumber(Triple) >= 7))
1070 D.Diag(DiagID: diag::err_sls_hardening_arm_not_supported)
1071 << Scope << A->getAsString(Args);
1072
1073 if (EnableRetBr)
1074 Features.push_back(x: "+harden-sls-retbr");
1075 if (EnableBlr)
1076 Features.push_back(x: "+harden-sls-blr");
1077 if (DisableComdat) {
1078 Features.push_back(x: "+harden-sls-nocomdat");
1079 }
1080 }
1081
1082 if (Args.getLastArg(Ids: options::OPT_mno_bti_at_return_twice))
1083 Features.push_back(x: "+no-bti-at-return-twice");
1084
1085 checkARMFloatABI(D, Args, HasFPRegs);
1086
1087 return FPUKind;
1088}
1089
1090std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
1091 std::string MArch;
1092 if (!Arch.empty())
1093 MArch = std::string(Arch);
1094 else
1095 MArch = std::string(Triple.getArchName());
1096 MArch = StringRef(MArch).split(Separator: "+").first.lower();
1097
1098 // Handle -march=native.
1099 if (MArch == "native") {
1100 std::string CPU = std::string(llvm::sys::getHostCPUName());
1101 if (CPU != "generic") {
1102 // Translate the native cpu into the architecture suffix for that CPU.
1103 StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, Arch: MArch, Triple);
1104 // If there is no valid architecture suffix for this CPU we don't know how
1105 // to handle it, so return no architecture.
1106 if (Suffix.empty())
1107 MArch = "";
1108 else
1109 MArch = std::string("arm") + Suffix.str();
1110 }
1111 }
1112
1113 return MArch;
1114}
1115
1116/// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
1117StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
1118 std::string MArch = getARMArch(Arch, Triple);
1119 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
1120 // here means an -march=native that we can't handle, so instead return no CPU.
1121 if (MArch.empty())
1122 return StringRef();
1123
1124 // We need to return an empty string here on invalid MArch values as the
1125 // various places that call this function can't cope with a null result.
1126 return llvm::ARM::getARMCPUForArch(Triple, MArch);
1127}
1128
1129/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
1130std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
1131 const llvm::Triple &Triple) {
1132 // FIXME: Warn on inconsistent use of -mcpu and -march.
1133 // If we have -mcpu=, use that.
1134 if (!CPU.empty()) {
1135 std::string MCPU = StringRef(CPU).split(Separator: "+").first.lower();
1136 // Handle -mcpu=native.
1137 if (MCPU == "native")
1138 return std::string(llvm::sys::getHostCPUName());
1139 else
1140 return MCPU;
1141 }
1142
1143 return std::string(getARMCPUForMArch(Arch, Triple));
1144}
1145
1146/// getLLVMArchSuffixForARM - Get the LLVM ArchKind value to use for a
1147/// particular CPU (or Arch, if CPU is generic). This is needed to
1148/// pass to functions like llvm::ARM::getDefaultFPU which need an
1149/// ArchKind as well as a CPU name.
1150llvm::ARM::ArchKind arm::getLLVMArchKindForARM(StringRef CPU, StringRef Arch,
1151 const llvm::Triple &Triple) {
1152 llvm::ARM::ArchKind ArchKind;
1153 if (CPU == "generic" || CPU.empty()) {
1154 std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
1155 ArchKind = llvm::ARM::parseArch(Arch: ARMArch);
1156 if (ArchKind == llvm::ARM::ArchKind::INVALID)
1157 // In case of generic Arch, i.e. "arm",
1158 // extract arch from default cpu of the Triple
1159 ArchKind =
1160 llvm::ARM::parseCPUArch(CPU: llvm::ARM::getARMCPUForArch(Triple, MArch: ARMArch));
1161 } else {
1162 // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
1163 // armv7k triple if it's actually been specified via "-arch armv7k".
1164 ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
1165 ? llvm::ARM::ArchKind::ARMV7K
1166 : llvm::ARM::parseCPUArch(CPU);
1167 }
1168 return ArchKind;
1169}
1170
1171/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
1172/// CPU (or Arch, if CPU is generic).
1173// FIXME: This is redundant with -mcpu, why does LLVM use this.
1174StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
1175 const llvm::Triple &Triple) {
1176 llvm::ARM::ArchKind ArchKind = getLLVMArchKindForARM(CPU, Arch, Triple);
1177 if (ArchKind == llvm::ARM::ArchKind::INVALID)
1178 return "";
1179 return llvm::ARM::getSubArch(AK: ArchKind);
1180}
1181
1182void arm::appendBE8LinkFlag(const ArgList &Args, ArgStringList &CmdArgs,
1183 const llvm::Triple &Triple) {
1184 if (Args.hasArg(Ids: options::OPT_r))
1185 return;
1186
1187 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
1188 // to generate BE-8 executables.
1189 if (arm::getARMSubArchVersionNumber(Triple) >= 7 || arm::isARMMProfile(Triple))
1190 CmdArgs.push_back(Elt: "--be8");
1191}
1192