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