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/TargetParser.h"
16 #include "llvm/Support/Host.h"
17 
18 using namespace clang::driver;
19 using namespace clang::driver::tools;
20 using namespace clang;
21 using namespace llvm::opt;
22 
23 // Get SubArch (vN).
24 int arm::getARMSubArchVersionNumber(const llvm::Triple &Triple) {
25   llvm::StringRef Arch = Triple.getArchName();
26   return llvm::ARM::parseArchVersion(Arch);
27 }
28 
29 // True if M-profile.
30 bool arm::isARMMProfile(const llvm::Triple &Triple) {
31   llvm::StringRef Arch = Triple.getArchName();
32   return llvm::ARM::parseArchProfile(Arch) == llvm::ARM::ProfileKind::M;
33 }
34 
35 // True if A-profile.
36 bool arm::isARMAProfile(const llvm::Triple &Triple) {
37   llvm::StringRef Arch = Triple.getArchName();
38   return llvm::ARM::parseArchProfile(Arch) == llvm::ARM::ProfileKind::A;
39 }
40 
41 // Get Arch/CPU from args.
42 void arm::getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
43                                 llvm::StringRef &CPU, bool FromAs) {
44   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ))
45     CPU = A->getValue();
46   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
47     Arch = A->getValue();
48   if (!FromAs)
49     return;
50 
51   for (const Arg *A :
52        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
53     // Use getValues because -Wa can have multiple arguments
54     // e.g. -Wa,-mcpu=foo,-mcpu=bar
55     for (StringRef Value : A->getValues()) {
56       if (Value.startswith("-mcpu="))
57         CPU = Value.substr(6);
58       if (Value.startswith("-march="))
59         Arch = Value.substr(7);
60     }
61   }
62 }
63 
64 // Handle -mhwdiv=.
65 // FIXME: Use ARMTargetParser.
66 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
67                                 const ArgList &Args, StringRef HWDiv,
68                                 std::vector<StringRef> &Features) {
69   uint64_t HWDivID = llvm::ARM::parseHWDiv(HWDiv);
70   if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
71     D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
72 }
73 
74 // Handle -mfpu=.
75 static unsigned getARMFPUFeatures(const Driver &D, const Arg *A,
76                                   const ArgList &Args, StringRef FPU,
77                                   std::vector<StringRef> &Features) {
78   unsigned FPUID = llvm::ARM::parseFPU(FPU);
79   if (!llvm::ARM::getFPUFeatures(FPUID, Features))
80     D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
81   return FPUID;
82 }
83 
84 // Decode ARM features from string like +[no]featureA+[no]featureB+...
85 static bool DecodeARMFeatures(const Driver &D, StringRef text, StringRef CPU,
86                               llvm::ARM::ArchKind ArchKind,
87                               std::vector<StringRef> &Features,
88                               unsigned &ArgFPUID) {
89   SmallVector<StringRef, 8> Split;
90   text.split(Split, StringRef("+"), -1, false);
91 
92   for (StringRef Feature : Split) {
93     if (!appendArchExtFeatures(CPU, ArchKind, Feature, Features, ArgFPUID))
94       return false;
95   }
96   return true;
97 }
98 
99 static void DecodeARMFeaturesFromCPU(const Driver &D, StringRef CPU,
100                                      std::vector<StringRef> &Features) {
101   CPU = CPU.split("+").first;
102   if (CPU != "generic") {
103     llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
104     uint64_t Extension = llvm::ARM::getDefaultExtensions(CPU, ArchKind);
105     llvm::ARM::getExtensionFeatures(Extension, Features);
106   }
107 }
108 
109 // Check if -march is valid by checking if it can be canonicalised and parsed.
110 // getARMArch is used here instead of just checking the -march value in order
111 // to handle -march=native correctly.
112 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
113                              llvm::StringRef ArchName, llvm::StringRef CPUName,
114                              std::vector<StringRef> &Features,
115                              const llvm::Triple &Triple, unsigned &ArgFPUID) {
116   std::pair<StringRef, StringRef> Split = ArchName.split("+");
117 
118   std::string MArch = arm::getARMArch(ArchName, Triple);
119   llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(MArch);
120   if (ArchKind == llvm::ARM::ArchKind::INVALID ||
121       (Split.second.size() && !DecodeARMFeatures(D, Split.second, CPUName,
122                                                  ArchKind, Features, ArgFPUID)))
123     D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
124 }
125 
126 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
127 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
128                             llvm::StringRef CPUName, llvm::StringRef ArchName,
129                             std::vector<StringRef> &Features,
130                             const llvm::Triple &Triple, unsigned &ArgFPUID) {
131   std::pair<StringRef, StringRef> Split = CPUName.split("+");
132 
133   std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
134   llvm::ARM::ArchKind ArchKind =
135     arm::getLLVMArchKindForARM(CPU, ArchName, Triple);
136   if (ArchKind == llvm::ARM::ArchKind::INVALID ||
137       (Split.second.size() &&
138        !DecodeARMFeatures(D, Split.second, CPU, ArchKind, Features, ArgFPUID)))
139     D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
140 }
141 
142 bool arm::useAAPCSForMachO(const llvm::Triple &T) {
143   // The backend is hardwired to assume AAPCS for M-class processors, ensure
144   // the frontend matches that.
145   return T.getEnvironment() == llvm::Triple::EABI ||
146          T.getEnvironment() == llvm::Triple::EABIHF ||
147          T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
148 }
149 
150 // Select mode for reading thread pointer (-mtp=soft/cp15).
151 arm::ReadTPMode arm::getReadTPMode(const Driver &D, const ArgList &Args) {
152   if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
153     arm::ReadTPMode ThreadPointer =
154         llvm::StringSwitch<arm::ReadTPMode>(A->getValue())
155             .Case("cp15", ReadTPMode::Cp15)
156             .Case("soft", ReadTPMode::Soft)
157             .Default(ReadTPMode::Invalid);
158     if (ThreadPointer != ReadTPMode::Invalid)
159       return ThreadPointer;
160     if (StringRef(A->getValue()).empty())
161       D.Diag(diag::err_drv_missing_arg_mtp) << A->getAsString(Args);
162     else
163       D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
164     return ReadTPMode::Invalid;
165   }
166   return ReadTPMode::Soft;
167 }
168 
169 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
170   return arm::getARMFloatABI(TC.getDriver(), TC.getEffectiveTriple(), Args);
171 }
172 
173 arm::FloatABI arm::getDefaultFloatABI(const llvm::Triple &Triple) {
174   auto SubArch = getARMSubArchVersionNumber(Triple);
175   switch (Triple.getOS()) {
176   case llvm::Triple::Darwin:
177   case llvm::Triple::MacOSX:
178   case llvm::Triple::IOS:
179   case llvm::Triple::TvOS:
180     // Darwin defaults to "softfp" for v6 and v7.
181     if (Triple.isWatchABI())
182       return FloatABI::Hard;
183     else
184       return (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
185 
186   case llvm::Triple::WatchOS:
187     return FloatABI::Hard;
188 
189   // FIXME: this is invalid for WindowsCE
190   case llvm::Triple::Win32:
191     return FloatABI::Hard;
192 
193   case llvm::Triple::NetBSD:
194     switch (Triple.getEnvironment()) {
195     case llvm::Triple::EABIHF:
196     case llvm::Triple::GNUEABIHF:
197       return FloatABI::Hard;
198     default:
199       return FloatABI::Soft;
200     }
201     break;
202 
203   case llvm::Triple::FreeBSD:
204     switch (Triple.getEnvironment()) {
205     case llvm::Triple::GNUEABIHF:
206       return FloatABI::Hard;
207     default:
208       // FreeBSD defaults to soft float
209       return FloatABI::Soft;
210     }
211     break;
212 
213   case llvm::Triple::OpenBSD:
214     return FloatABI::SoftFP;
215 
216   default:
217     switch (Triple.getEnvironment()) {
218     case llvm::Triple::GNUEABIHF:
219     case llvm::Triple::MuslEABIHF:
220     case llvm::Triple::EABIHF:
221       return FloatABI::Hard;
222     case llvm::Triple::GNUEABI:
223     case llvm::Triple::MuslEABI:
224     case llvm::Triple::EABI:
225       // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
226       return FloatABI::SoftFP;
227     case llvm::Triple::Android:
228       return (SubArch >= 7) ? FloatABI::SoftFP : FloatABI::Soft;
229     default:
230       return FloatABI::Invalid;
231     }
232   }
233   return FloatABI::Invalid;
234 }
235 
236 // Select the float ABI as determined by -msoft-float, -mhard-float, and
237 // -mfloat-abi=.
238 arm::FloatABI arm::getARMFloatABI(const Driver &D, const llvm::Triple &Triple,
239                                   const ArgList &Args) {
240   arm::FloatABI ABI = FloatABI::Invalid;
241   if (Arg *A =
242           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
243                           options::OPT_mfloat_abi_EQ)) {
244     if (A->getOption().matches(options::OPT_msoft_float)) {
245       ABI = FloatABI::Soft;
246     } else if (A->getOption().matches(options::OPT_mhard_float)) {
247       ABI = FloatABI::Hard;
248     } else {
249       ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
250                 .Case("soft", FloatABI::Soft)
251                 .Case("softfp", FloatABI::SoftFP)
252                 .Case("hard", FloatABI::Hard)
253                 .Default(FloatABI::Invalid);
254       if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
255         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
256         ABI = FloatABI::Soft;
257       }
258     }
259   }
260 
261   // If unspecified, choose the default based on the platform.
262   if (ABI == FloatABI::Invalid)
263     ABI = arm::getDefaultFloatABI(Triple);
264 
265   if (ABI == FloatABI::Invalid) {
266     // Assume "soft", but warn the user we are guessing.
267     if (Triple.isOSBinFormatMachO() &&
268         Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
269       ABI = FloatABI::Hard;
270     else
271       ABI = FloatABI::Soft;
272 
273     if (Triple.getOS() != llvm::Triple::UnknownOS ||
274         !Triple.isOSBinFormatMachO())
275       D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
276   }
277 
278   assert(ABI != FloatABI::Invalid && "must select an ABI");
279   return ABI;
280 }
281 
282 static bool hasIntegerMVE(const std::vector<StringRef> &F) {
283   auto MVE = llvm::find(llvm::reverse(F), "+mve");
284   auto NoMVE = llvm::find(llvm::reverse(F), "-mve");
285   return MVE != F.rend() &&
286          (NoMVE == F.rend() || std::distance(MVE, NoMVE) > 0);
287 }
288 
289 void arm::getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
290                                const ArgList &Args, ArgStringList &CmdArgs,
291                                std::vector<StringRef> &Features, bool ForAS) {
292   bool KernelOrKext =
293       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
294   arm::FloatABI ABI = arm::getARMFloatABI(D, Triple, Args);
295   arm::ReadTPMode ThreadPointer = arm::getReadTPMode(D, Args);
296   llvm::Optional<std::pair<const Arg *, StringRef>> WaCPU, WaFPU, WaHDiv,
297       WaArch;
298 
299   // This vector will accumulate features from the architecture
300   // extension suffixes on -mcpu and -march (e.g. the 'bar' in
301   // -mcpu=foo+bar). We want to apply those after the features derived
302   // from the FPU, in case -mfpu generates a negative feature which
303   // the +bar is supposed to override.
304   std::vector<StringRef> ExtensionFeatures;
305 
306   if (!ForAS) {
307     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
308     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
309     // stripped out by the ARM target. We should probably pass this a new
310     // -target-option, which is handled by the -cc1/-cc1as invocation.
311     //
312     // FIXME2:  For consistency, it would be ideal if we set up the target
313     // machine state the same when using the frontend or the assembler. We don't
314     // currently do that for the assembler, we pass the options directly to the
315     // backend and never even instantiate the frontend TargetInfo. If we did,
316     // and used its handleTargetFeatures hook, then we could ensure the
317     // assembler and the frontend behave the same.
318 
319     // Use software floating point operations?
320     if (ABI == arm::FloatABI::Soft)
321       Features.push_back("+soft-float");
322 
323     // Use software floating point argument passing?
324     if (ABI != arm::FloatABI::Hard)
325       Features.push_back("+soft-float-abi");
326   } else {
327     // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
328     // to the assembler correctly.
329     for (const Arg *A :
330          Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
331       // We use getValues here because you can have many options per -Wa
332       // We will keep the last one we find for each of these
333       for (StringRef Value : A->getValues()) {
334         if (Value.startswith("-mfpu=")) {
335           WaFPU = std::make_pair(A, Value.substr(6));
336         } else if (Value.startswith("-mcpu=")) {
337           WaCPU = std::make_pair(A, Value.substr(6));
338         } else if (Value.startswith("-mhwdiv=")) {
339           WaHDiv = std::make_pair(A, Value.substr(8));
340         } else if (Value.startswith("-march=")) {
341           WaArch = std::make_pair(A, Value.substr(7));
342         }
343       }
344     }
345   }
346 
347   if (ThreadPointer == arm::ReadTPMode::Cp15)
348     Features.push_back("+read-tp-hard");
349 
350   const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
351   const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
352   StringRef ArchName;
353   StringRef CPUName;
354   unsigned ArchArgFPUID = llvm::ARM::FK_INVALID;
355   unsigned CPUArgFPUID = llvm::ARM::FK_INVALID;
356 
357   // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
358   if (WaCPU) {
359     if (CPUArg)
360       D.Diag(clang::diag::warn_drv_unused_argument)
361           << CPUArg->getAsString(Args);
362     CPUName = WaCPU->second;
363     CPUArg = WaCPU->first;
364   } else if (CPUArg)
365     CPUName = CPUArg->getValue();
366 
367   // Check -march. ClangAs gives preference to -Wa,-march=.
368   if (WaArch) {
369     if (ArchArg)
370       D.Diag(clang::diag::warn_drv_unused_argument)
371           << ArchArg->getAsString(Args);
372     ArchName = WaArch->second;
373     // This will set any features after the base architecture.
374     checkARMArchName(D, WaArch->first, Args, ArchName, CPUName,
375                      ExtensionFeatures, Triple, ArchArgFPUID);
376     // The base architecture was handled in ToolChain::ComputeLLVMTriple because
377     // triple is read only by this point.
378   } else if (ArchArg) {
379     ArchName = ArchArg->getValue();
380     checkARMArchName(D, ArchArg, Args, ArchName, CPUName, ExtensionFeatures,
381                      Triple, ArchArgFPUID);
382   }
383 
384   // Add CPU features for generic CPUs
385   if (CPUName == "native") {
386     llvm::StringMap<bool> HostFeatures;
387     if (llvm::sys::getHostCPUFeatures(HostFeatures))
388       for (auto &F : HostFeatures)
389         Features.push_back(
390             Args.MakeArgString((F.second ? "+" : "-") + F.first()));
391   } else if (!CPUName.empty()) {
392     // This sets the default features for the specified CPU. We certainly don't
393     // want to override the features that have been explicitly specified on the
394     // command line. Therefore, process them directly instead of appending them
395     // at the end later.
396     DecodeARMFeaturesFromCPU(D, CPUName, Features);
397   }
398 
399   if (CPUArg)
400     checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, ExtensionFeatures,
401                     Triple, CPUArgFPUID);
402   // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
403   unsigned FPUID = llvm::ARM::FK_INVALID;
404   const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
405   if (WaFPU) {
406     if (FPUArg)
407       D.Diag(clang::diag::warn_drv_unused_argument)
408           << FPUArg->getAsString(Args);
409     (void)getARMFPUFeatures(D, WaFPU->first, Args, WaFPU->second, Features);
410   } else if (FPUArg) {
411     FPUID = getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
412   } else if (Triple.isAndroid() && getARMSubArchVersionNumber(Triple) >= 7) {
413     const char *AndroidFPU = "neon";
414     FPUID = llvm::ARM::parseFPU(AndroidFPU);
415     if (!llvm::ARM::getFPUFeatures(FPUID, Features))
416       D.Diag(clang::diag::err_drv_clang_unsupported)
417           << std::string("-mfpu=") + AndroidFPU;
418   }
419 
420   // Now we've finished accumulating features from arch, cpu and fpu,
421   // we can append the ones for architecture extensions that we
422   // collected separately.
423   Features.insert(std::end(Features),
424                   std::begin(ExtensionFeatures), std::end(ExtensionFeatures));
425 
426   // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
427   const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
428   if (WaHDiv) {
429     if (HDivArg)
430       D.Diag(clang::diag::warn_drv_unused_argument)
431           << HDivArg->getAsString(Args);
432     getARMHWDivFeatures(D, WaHDiv->first, Args, WaHDiv->second, Features);
433   } else if (HDivArg)
434     getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
435 
436   // Handle (arch-dependent) fp16fml/fullfp16 relationship.
437   // Must happen before any features are disabled due to soft-float.
438   // FIXME: this fp16fml option handling will be reimplemented after the
439   // TargetParser rewrite.
440   const auto ItRNoFullFP16 = std::find(Features.rbegin(), Features.rend(), "-fullfp16");
441   const auto ItRFP16FML = std::find(Features.rbegin(), Features.rend(), "+fp16fml");
442   if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_4a) {
443     const auto ItRFullFP16  = std::find(Features.rbegin(), Features.rend(), "+fullfp16");
444     if (ItRFullFP16 < ItRNoFullFP16 && ItRFullFP16 < ItRFP16FML) {
445       // Only entangled feature that can be to the right of this +fullfp16 is -fp16fml.
446       // Only append the +fp16fml if there is no -fp16fml after the +fullfp16.
447       if (std::find(Features.rbegin(), ItRFullFP16, "-fp16fml") == ItRFullFP16)
448         Features.push_back("+fp16fml");
449     }
450     else
451       goto fp16_fml_fallthrough;
452   }
453   else {
454 fp16_fml_fallthrough:
455     // In both of these cases, putting the 'other' feature on the end of the vector will
456     // result in the same effect as placing it immediately after the current feature.
457     if (ItRNoFullFP16 < ItRFP16FML)
458       Features.push_back("-fp16fml");
459     else if (ItRNoFullFP16 > ItRFP16FML)
460       Features.push_back("+fullfp16");
461   }
462 
463   // Setting -msoft-float/-mfloat-abi=soft, -mfpu=none, or adding +nofp to
464   // -march/-mcpu effectively disables the FPU (GCC ignores the -mfpu options in
465   // this case). Note that the ABI can also be set implicitly by the target
466   // selected.
467   if (ABI == arm::FloatABI::Soft) {
468     llvm::ARM::getFPUFeatures(llvm::ARM::FK_NONE, Features);
469 
470     // Disable all features relating to hardware FP, not already disabled by the
471     // above call.
472     Features.insert(Features.end(), {"-dotprod", "-fp16fml", "-bf16", "-mve",
473                                      "-mve.fp", "-fpregs"});
474   } else if (FPUID == llvm::ARM::FK_NONE ||
475              ArchArgFPUID == llvm::ARM::FK_NONE ||
476              CPUArgFPUID == llvm::ARM::FK_NONE) {
477     // -mfpu=none, -march=armvX+nofp or -mcpu=X+nofp is *very* similar to
478     // -mfloat-abi=soft, only that it should not disable MVE-I. They disable the
479     // FPU, but not the FPU registers, thus MVE-I, which depends only on the
480     // latter, is still supported.
481     Features.insert(Features.end(),
482                     {"-dotprod", "-fp16fml", "-bf16", "-mve.fp"});
483     if (!hasIntegerMVE(Features))
484       Features.emplace_back("-fpregs");
485   }
486 
487   // En/disable crc code generation.
488   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
489     if (A->getOption().matches(options::OPT_mcrc))
490       Features.push_back("+crc");
491     else
492       Features.push_back("-crc");
493   }
494 
495   // For Arch >= ARMv8.0 && A profile:  crypto = sha2 + aes
496   // FIXME: this needs reimplementation after the TargetParser rewrite
497   auto CryptoIt = llvm::find_if(llvm::reverse(Features), [](const StringRef F) {
498     return F.contains("crypto");
499   });
500   if (CryptoIt != Features.rend()) {
501     if (CryptoIt->take_front() == "+") {
502       StringRef ArchSuffix = arm::getLLVMArchSuffixForARM(
503           arm::getARMTargetCPU(CPUName, ArchName, Triple), ArchName, Triple);
504       if (llvm::ARM::parseArchVersion(ArchSuffix) >= 8 &&
505           llvm::ARM::parseArchProfile(ArchSuffix) ==
506               llvm::ARM::ProfileKind::A) {
507         if (ArchName.find_lower("+nosha2") == StringRef::npos &&
508             CPUName.find_lower("+nosha2") == StringRef::npos)
509           Features.push_back("+sha2");
510         if (ArchName.find_lower("+noaes") == StringRef::npos &&
511             CPUName.find_lower("+noaes") == StringRef::npos)
512           Features.push_back("+aes");
513       } else {
514         D.Diag(clang::diag::warn_target_unsupported_extension)
515             << "crypto"
516             << llvm::ARM::getArchName(llvm::ARM::parseArch(ArchSuffix));
517         // With -fno-integrated-as -mfpu=crypto-neon-fp-armv8 some assemblers such as the GNU assembler
518         // will permit the use of crypto instructions as the fpu will override the architecture.
519         // We keep the crypto feature in this case to preserve compatibility.
520         // In all other cases we remove the crypto feature.
521         if (!Args.hasArg(options::OPT_fno_integrated_as))
522           Features.push_back("-crypto");
523       }
524     }
525   }
526 
527   // CMSE: Check for target 8M (for -mcmse to be applicable) is performed later.
528   if (Args.getLastArg(options::OPT_mcmse))
529     Features.push_back("+8msecext");
530 
531   // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
532   // neither options are specified, see if we are compiling for kernel/kext and
533   // decide whether to pass "+long-calls" based on the OS and its version.
534   if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
535                                options::OPT_mno_long_calls)) {
536     if (A->getOption().matches(options::OPT_mlong_calls))
537       Features.push_back("+long-calls");
538   } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
539              !Triple.isWatchOS()) {
540       Features.push_back("+long-calls");
541   }
542 
543   // Generate execute-only output (no data access to code sections).
544   // This only makes sense for the compiler, not for the assembler.
545   if (!ForAS) {
546     // Supported only on ARMv6T2 and ARMv7 and above.
547     // Cannot be combined with -mno-movt or -mlong-calls
548     if (Arg *A = Args.getLastArg(options::OPT_mexecute_only, options::OPT_mno_execute_only)) {
549       if (A->getOption().matches(options::OPT_mexecute_only)) {
550         if (getARMSubArchVersionNumber(Triple) < 7 &&
551             llvm::ARM::parseArch(Triple.getArchName()) != llvm::ARM::ArchKind::ARMV6T2)
552               D.Diag(diag::err_target_unsupported_execute_only) << Triple.getArchName();
553         else if (Arg *B = Args.getLastArg(options::OPT_mno_movt))
554           D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
555         // Long calls create constant pool entries and have not yet been fixed up
556         // to play nicely with execute-only. Hence, they cannot be used in
557         // execute-only code for now
558         else if (Arg *B = Args.getLastArg(options::OPT_mlong_calls, options::OPT_mno_long_calls)) {
559           if (B->getOption().matches(options::OPT_mlong_calls))
560             D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
561         }
562         Features.push_back("+execute-only");
563       }
564     }
565   }
566 
567   // Kernel code has more strict alignment requirements.
568   if (KernelOrKext)
569     Features.push_back("+strict-align");
570   else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
571                                     options::OPT_munaligned_access)) {
572     if (A->getOption().matches(options::OPT_munaligned_access)) {
573       // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
574       if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
575         D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
576       // v8M Baseline follows on from v6M, so doesn't support unaligned memory
577       // access either.
578       else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
579         D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
580     } else
581       Features.push_back("+strict-align");
582   } else {
583     // Assume pre-ARMv6 doesn't support unaligned accesses.
584     //
585     // ARMv6 may or may not support unaligned accesses depending on the
586     // SCTLR.U bit, which is architecture-specific. We assume ARMv6
587     // Darwin and NetBSD targets support unaligned accesses, and others don't.
588     //
589     // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
590     // which raises an alignment fault on unaligned accesses. Linux
591     // defaults this bit to 0 and handles it as a system-wide (not
592     // per-process) setting. It is therefore safe to assume that ARMv7+
593     // Linux targets support unaligned accesses. The same goes for NaCl.
594     //
595     // The above behavior is consistent with GCC.
596     int VersionNum = getARMSubArchVersionNumber(Triple);
597     if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
598       if (VersionNum < 6 ||
599           Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
600         Features.push_back("+strict-align");
601     } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
602       if (VersionNum < 7)
603         Features.push_back("+strict-align");
604     } else
605       Features.push_back("+strict-align");
606   }
607 
608   // llvm does not support reserving registers in general. There is support
609   // for reserving r9 on ARM though (defined as a platform-specific register
610   // in ARM EABI).
611   if (Args.hasArg(options::OPT_ffixed_r9))
612     Features.push_back("+reserve-r9");
613 
614   // The kext linker doesn't know how to deal with movw/movt.
615   if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
616     Features.push_back("+no-movt");
617 
618   if (Args.hasArg(options::OPT_mno_neg_immediates))
619     Features.push_back("+no-neg-immediates");
620 
621   // Enable/disable straight line speculation hardening.
622   if (Arg *A = Args.getLastArg(options::OPT_mharden_sls_EQ)) {
623     StringRef Scope = A->getValue();
624     bool EnableRetBr = false;
625     bool EnableBlr = false;
626     if (Scope != "none" && Scope != "all") {
627       SmallVector<StringRef, 4> Opts;
628       Scope.split(Opts, ",");
629       for (auto Opt : Opts) {
630         Opt = Opt.trim();
631         if (Opt == "retbr") {
632           EnableRetBr = true;
633           continue;
634         }
635         if (Opt == "blr") {
636           EnableBlr = true;
637           continue;
638         }
639         D.Diag(diag::err_invalid_sls_hardening)
640             << Scope << A->getAsString(Args);
641         break;
642       }
643     } else if (Scope == "all") {
644       EnableRetBr = true;
645       EnableBlr = true;
646     }
647 
648     if (EnableRetBr || EnableBlr)
649       if (!(isARMAProfile(Triple) && getARMSubArchVersionNumber(Triple) >= 7))
650         D.Diag(diag::err_sls_hardening_arm_not_supported)
651             << Scope << A->getAsString(Args);
652 
653     if (EnableRetBr)
654       Features.push_back("+harden-sls-retbr");
655     if (EnableBlr)
656       Features.push_back("+harden-sls-blr");
657   }
658 
659 }
660 
661 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
662   std::string MArch;
663   if (!Arch.empty())
664     MArch = std::string(Arch);
665   else
666     MArch = std::string(Triple.getArchName());
667   MArch = StringRef(MArch).split("+").first.lower();
668 
669   // Handle -march=native.
670   if (MArch == "native") {
671     std::string CPU = std::string(llvm::sys::getHostCPUName());
672     if (CPU != "generic") {
673       // Translate the native cpu into the architecture suffix for that CPU.
674       StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
675       // If there is no valid architecture suffix for this CPU we don't know how
676       // to handle it, so return no architecture.
677       if (Suffix.empty())
678         MArch = "";
679       else
680         MArch = std::string("arm") + Suffix.str();
681     }
682   }
683 
684   return MArch;
685 }
686 
687 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
688 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
689   std::string MArch = getARMArch(Arch, Triple);
690   // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
691   // here means an -march=native that we can't handle, so instead return no CPU.
692   if (MArch.empty())
693     return StringRef();
694 
695   // We need to return an empty string here on invalid MArch values as the
696   // various places that call this function can't cope with a null result.
697   return Triple.getARMCPUForArch(MArch);
698 }
699 
700 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
701 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
702                                  const llvm::Triple &Triple) {
703   // FIXME: Warn on inconsistent use of -mcpu and -march.
704   // If we have -mcpu=, use that.
705   if (!CPU.empty()) {
706     std::string MCPU = StringRef(CPU).split("+").first.lower();
707     // Handle -mcpu=native.
708     if (MCPU == "native")
709       return std::string(llvm::sys::getHostCPUName());
710     else
711       return MCPU;
712   }
713 
714   return std::string(getARMCPUForMArch(Arch, Triple));
715 }
716 
717 /// getLLVMArchSuffixForARM - Get the LLVM ArchKind value to use for a
718 /// particular CPU (or Arch, if CPU is generic). This is needed to
719 /// pass to functions like llvm::ARM::getDefaultFPU which need an
720 /// ArchKind as well as a CPU name.
721 llvm::ARM::ArchKind arm::getLLVMArchKindForARM(StringRef CPU, StringRef Arch,
722                                                const llvm::Triple &Triple) {
723   llvm::ARM::ArchKind ArchKind;
724   if (CPU == "generic" || CPU.empty()) {
725     std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
726     ArchKind = llvm::ARM::parseArch(ARMArch);
727     if (ArchKind == llvm::ARM::ArchKind::INVALID)
728       // In case of generic Arch, i.e. "arm",
729       // extract arch from default cpu of the Triple
730       ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
731   } else {
732     // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
733     // armv7k triple if it's actually been specified via "-arch armv7k".
734     ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
735                           ? llvm::ARM::ArchKind::ARMV7K
736                           : llvm::ARM::parseCPUArch(CPU);
737   }
738   return ArchKind;
739 }
740 
741 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
742 /// CPU  (or Arch, if CPU is generic).
743 // FIXME: This is redundant with -mcpu, why does LLVM use this.
744 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
745                                        const llvm::Triple &Triple) {
746   llvm::ARM::ArchKind ArchKind = getLLVMArchKindForARM(CPU, Arch, Triple);
747   if (ArchKind == llvm::ARM::ArchKind::INVALID)
748     return "";
749   return llvm::ARM::getSubArch(ArchKind);
750 }
751 
752 void arm::appendBE8LinkFlag(const ArgList &Args, ArgStringList &CmdArgs,
753                             const llvm::Triple &Triple) {
754   if (Args.hasArg(options::OPT_r))
755     return;
756 
757   // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
758   // to generate BE-8 executables.
759   if (arm::getARMSubArchVersionNumber(Triple) >= 7 || arm::isARMMProfile(Triple))
760     CmdArgs.push_back("--be8");
761 }
762