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