Path: blob/main/contrib/llvm-project/clang/lib/Driver/ToolChains/Arch/ARM.cpp
35294 views
//===--- ARM.cpp - ARM (not AArch64) Helpers for Tools ----------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "ARM.h"9#include "clang/Driver/Driver.h"10#include "clang/Driver/DriverDiagnostic.h"11#include "clang/Driver/Options.h"12#include "llvm/ADT/StringSwitch.h"13#include "llvm/Option/ArgList.h"14#include "llvm/TargetParser/ARMTargetParser.h"15#include "llvm/TargetParser/Host.h"1617using namespace clang::driver;18using namespace clang::driver::tools;19using namespace clang;20using namespace llvm::opt;2122// Get SubArch (vN).23int arm::getARMSubArchVersionNumber(const llvm::Triple &Triple) {24llvm::StringRef Arch = Triple.getArchName();25return llvm::ARM::parseArchVersion(Arch);26}2728// True if M-profile.29bool arm::isARMMProfile(const llvm::Triple &Triple) {30llvm::StringRef Arch = Triple.getArchName();31return llvm::ARM::parseArchProfile(Arch) == llvm::ARM::ProfileKind::M;32}3334// On Arm the endianness of the output file is determined by the target and35// can be overridden by the pseudo-target flags '-mlittle-endian'/'-EL' and36// '-mbig-endian'/'-EB'. Unlike other targets the flag does not result in a37// normalized triple so we must handle the flag here.38bool arm::isARMBigEndian(const llvm::Triple &Triple, const ArgList &Args) {39if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,40options::OPT_mbig_endian)) {41return !A->getOption().matches(options::OPT_mlittle_endian);42}4344return Triple.getArch() == llvm::Triple::armeb ||45Triple.getArch() == llvm::Triple::thumbeb;46}4748// True if A-profile.49bool arm::isARMAProfile(const llvm::Triple &Triple) {50llvm::StringRef Arch = Triple.getArchName();51return llvm::ARM::parseArchProfile(Arch) == llvm::ARM::ProfileKind::A;52}5354// Get Arch/CPU from args.55void arm::getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,56llvm::StringRef &CPU, bool FromAs) {57if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ))58CPU = A->getValue();59if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))60Arch = A->getValue();61if (!FromAs)62return;6364for (const Arg *A :65Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {66// Use getValues because -Wa can have multiple arguments67// e.g. -Wa,-mcpu=foo,-mcpu=bar68for (StringRef Value : A->getValues()) {69if (Value.starts_with("-mcpu="))70CPU = Value.substr(6);71if (Value.starts_with("-march="))72Arch = Value.substr(7);73}74}75}7677// Handle -mhwdiv=.78// FIXME: Use ARMTargetParser.79static void getARMHWDivFeatures(const Driver &D, const Arg *A,80const ArgList &Args, StringRef HWDiv,81std::vector<StringRef> &Features) {82uint64_t HWDivID = llvm::ARM::parseHWDiv(HWDiv);83if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))84D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);85}8687// Handle -mfpu=.88static llvm::ARM::FPUKind getARMFPUFeatures(const Driver &D, const Arg *A,89const ArgList &Args, StringRef FPU,90std::vector<StringRef> &Features) {91llvm::ARM::FPUKind FPUKind = llvm::ARM::parseFPU(FPU);92if (!llvm::ARM::getFPUFeatures(FPUKind, Features))93D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);94return FPUKind;95}9697// Decode ARM features from string like +[no]featureA+[no]featureB+...98static bool DecodeARMFeatures(const Driver &D, StringRef text, StringRef CPU,99llvm::ARM::ArchKind ArchKind,100std::vector<StringRef> &Features,101llvm::ARM::FPUKind &ArgFPUKind) {102SmallVector<StringRef, 8> Split;103text.split(Split, StringRef("+"), -1, false);104105for (StringRef Feature : Split) {106if (!appendArchExtFeatures(CPU, ArchKind, Feature, Features, ArgFPUKind))107return false;108}109return true;110}111112static void DecodeARMFeaturesFromCPU(const Driver &D, StringRef CPU,113std::vector<StringRef> &Features) {114CPU = CPU.split("+").first;115if (CPU != "generic") {116llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);117uint64_t Extension = llvm::ARM::getDefaultExtensions(CPU, ArchKind);118llvm::ARM::getExtensionFeatures(Extension, Features);119}120}121122// Check if -march is valid by checking if it can be canonicalised and parsed.123// getARMArch is used here instead of just checking the -march value in order124// to handle -march=native correctly.125static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,126llvm::StringRef ArchName, llvm::StringRef CPUName,127std::vector<StringRef> &Features,128const llvm::Triple &Triple,129llvm::ARM::FPUKind &ArgFPUKind) {130std::pair<StringRef, StringRef> Split = ArchName.split("+");131132std::string MArch = arm::getARMArch(ArchName, Triple);133llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(MArch);134if (ArchKind == llvm::ARM::ArchKind::INVALID ||135(Split.second.size() &&136!DecodeARMFeatures(D, Split.second, CPUName, ArchKind, Features,137ArgFPUKind)))138D.Diag(clang::diag::err_drv_unsupported_option_argument)139<< A->getSpelling() << A->getValue();140}141142// Check -mcpu=. Needs ArchName to handle -mcpu=generic.143static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,144llvm::StringRef CPUName, llvm::StringRef ArchName,145std::vector<StringRef> &Features,146const llvm::Triple &Triple,147llvm::ARM::FPUKind &ArgFPUKind) {148std::pair<StringRef, StringRef> Split = CPUName.split("+");149150std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);151llvm::ARM::ArchKind ArchKind =152arm::getLLVMArchKindForARM(CPU, ArchName, Triple);153if (ArchKind == llvm::ARM::ArchKind::INVALID ||154(Split.second.size() && !DecodeARMFeatures(D, Split.second, CPU, ArchKind,155Features, ArgFPUKind)))156D.Diag(clang::diag::err_drv_unsupported_option_argument)157<< A->getSpelling() << A->getValue();158}159160// If -mfloat-abi=hard or -mhard-float are specified explicitly then check that161// floating point registers are available on the target CPU.162static void checkARMFloatABI(const Driver &D, const ArgList &Args,163bool HasFPRegs) {164if (HasFPRegs)165return;166const Arg *A =167Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,168options::OPT_mfloat_abi_EQ);169if (A && (A->getOption().matches(options::OPT_mhard_float) ||170(A->getOption().matches(options::OPT_mfloat_abi_EQ) &&171A->getValue() == StringRef("hard"))))172D.Diag(clang::diag::warn_drv_no_floating_point_registers)173<< A->getAsString(Args);174}175176bool arm::useAAPCSForMachO(const llvm::Triple &T) {177// The backend is hardwired to assume AAPCS for M-class processors, ensure178// the frontend matches that.179return T.getEnvironment() == llvm::Triple::EABI ||180T.getEnvironment() == llvm::Triple::EABIHF ||181T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);182}183184// We follow GCC and support when the backend has support for the MRC/MCR185// instructions that are used to set the hard thread pointer ("CP15 C13186// Thread id").187bool arm::isHardTPSupported(const llvm::Triple &Triple) {188int Ver = getARMSubArchVersionNumber(Triple);189llvm::ARM::ArchKind AK = llvm::ARM::parseArch(Triple.getArchName());190return Triple.isARM() || AK == llvm::ARM::ArchKind::ARMV6T2 ||191(Ver >= 7 && AK != llvm::ARM::ArchKind::ARMV8MBaseline);192}193194// Select mode for reading thread pointer (-mtp=soft/cp15).195arm::ReadTPMode arm::getReadTPMode(const Driver &D, const ArgList &Args,196const llvm::Triple &Triple, bool ForAS) {197if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {198arm::ReadTPMode ThreadPointer =199llvm::StringSwitch<arm::ReadTPMode>(A->getValue())200.Case("cp15", ReadTPMode::TPIDRURO)201.Case("tpidrurw", ReadTPMode::TPIDRURW)202.Case("tpidruro", ReadTPMode::TPIDRURO)203.Case("tpidrprw", ReadTPMode::TPIDRPRW)204.Case("soft", ReadTPMode::Soft)205.Default(ReadTPMode::Invalid);206if ((ThreadPointer == ReadTPMode::TPIDRURW ||207ThreadPointer == ReadTPMode::TPIDRURO ||208ThreadPointer == ReadTPMode::TPIDRPRW) &&209!isHardTPSupported(Triple) && !ForAS) {210D.Diag(diag::err_target_unsupported_tp_hard) << Triple.getArchName();211return ReadTPMode::Invalid;212}213if (ThreadPointer != ReadTPMode::Invalid)214return ThreadPointer;215if (StringRef(A->getValue()).empty())216D.Diag(diag::err_drv_missing_arg_mtp) << A->getAsString(Args);217else218D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);219return ReadTPMode::Invalid;220}221return ReadTPMode::Soft;222}223224void arm::setArchNameInTriple(const Driver &D, const ArgList &Args,225types::ID InputType, llvm::Triple &Triple) {226StringRef MCPU, MArch;227if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))228MCPU = A->getValue();229if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))230MArch = A->getValue();231232std::string CPU = Triple.isOSBinFormatMachO()233? tools::arm::getARMCPUForMArch(MArch, Triple).str()234: tools::arm::getARMTargetCPU(MCPU, MArch, Triple);235StringRef Suffix = tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);236237bool IsBigEndian = Triple.getArch() == llvm::Triple::armeb ||238Triple.getArch() == llvm::Triple::thumbeb;239// Handle pseudo-target flags '-mlittle-endian'/'-EL' and240// '-mbig-endian'/'-EB'.241if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,242options::OPT_mbig_endian)) {243IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);244}245std::string ArchName = IsBigEndian ? "armeb" : "arm";246247// FIXME: Thumb should just be another -target-feaure, not in the triple.248bool IsMProfile =249llvm::ARM::parseArchProfile(Suffix) == llvm::ARM::ProfileKind::M;250bool ThumbDefault = IsMProfile ||251// Thumb2 is the default for V7 on Darwin.252(llvm::ARM::parseArchVersion(Suffix) == 7 &&253Triple.isOSBinFormatMachO()) ||254// FIXME: this is invalid for WindowsCE255Triple.isOSWindows();256257// Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for258// M-Class CPUs/architecture variants, which is not supported.259bool ARMModeRequested =260!Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault);261if (IsMProfile && ARMModeRequested) {262if (MCPU.size())263D.Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";264else265D.Diag(diag::err_arch_unsupported_isa)266<< tools::arm::getARMArch(MArch, Triple) << "ARM";267}268269// Check to see if an explicit choice to use thumb has been made via270// -mthumb. For assembler files we must check for -mthumb in the options271// passed to the assembler via -Wa or -Xassembler.272bool IsThumb = false;273if (InputType != types::TY_PP_Asm)274IsThumb =275Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault);276else {277// Ideally we would check for these flags in278// CollectArgsForIntegratedAssembler but we can't change the ArchName at279// that point.280llvm::StringRef WaMArch, WaMCPU;281for (const auto *A :282Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {283for (StringRef Value : A->getValues()) {284// There is no assembler equivalent of -mno-thumb, -marm, or -mno-arm.285if (Value == "-mthumb")286IsThumb = true;287else if (Value.starts_with("-march="))288WaMArch = Value.substr(7);289else if (Value.starts_with("-mcpu="))290WaMCPU = Value.substr(6);291}292}293294if (WaMCPU.size() || WaMArch.size()) {295// The way this works means that we prefer -Wa,-mcpu's architecture296// over -Wa,-march. Which matches the compiler behaviour.297Suffix = tools::arm::getLLVMArchSuffixForARM(WaMCPU, WaMArch, Triple);298}299}300301// Assembly files should start in ARM mode, unless arch is M-profile, or302// -mthumb has been passed explicitly to the assembler. Windows is always303// thumb.304if (IsThumb || IsMProfile || Triple.isOSWindows()) {305if (IsBigEndian)306ArchName = "thumbeb";307else308ArchName = "thumb";309}310Triple.setArchName(ArchName + Suffix.str());311}312313void arm::setFloatABIInTriple(const Driver &D, const ArgList &Args,314llvm::Triple &Triple) {315if (Triple.isOSLiteOS()) {316Triple.setEnvironment(llvm::Triple::OpenHOS);317return;318}319320bool isHardFloat =321(arm::getARMFloatABI(D, Triple, Args) == arm::FloatABI::Hard);322323switch (Triple.getEnvironment()) {324case llvm::Triple::GNUEABI:325case llvm::Triple::GNUEABIHF:326Triple.setEnvironment(isHardFloat ? llvm::Triple::GNUEABIHF327: llvm::Triple::GNUEABI);328break;329case llvm::Triple::GNUEABIT64:330case llvm::Triple::GNUEABIHFT64:331Triple.setEnvironment(isHardFloat ? llvm::Triple::GNUEABIHFT64332: llvm::Triple::GNUEABIT64);333break;334case llvm::Triple::EABI:335case llvm::Triple::EABIHF:336Triple.setEnvironment(isHardFloat ? llvm::Triple::EABIHF337: llvm::Triple::EABI);338break;339case llvm::Triple::MuslEABI:340case llvm::Triple::MuslEABIHF:341Triple.setEnvironment(isHardFloat ? llvm::Triple::MuslEABIHF342: llvm::Triple::MuslEABI);343break;344case llvm::Triple::OpenHOS:345break;346default: {347arm::FloatABI DefaultABI = arm::getDefaultFloatABI(Triple);348if (DefaultABI != arm::FloatABI::Invalid &&349isHardFloat != (DefaultABI == arm::FloatABI::Hard)) {350Arg *ABIArg =351Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,352options::OPT_mfloat_abi_EQ);353assert(ABIArg && "Non-default float abi expected to be from arg");354D.Diag(diag::err_drv_unsupported_opt_for_target)355<< ABIArg->getAsString(Args) << Triple.getTriple();356}357break;358}359}360}361362arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {363return arm::getARMFloatABI(TC.getDriver(), TC.getEffectiveTriple(), Args);364}365366arm::FloatABI arm::getDefaultFloatABI(const llvm::Triple &Triple) {367auto SubArch = getARMSubArchVersionNumber(Triple);368switch (Triple.getOS()) {369case llvm::Triple::Darwin:370case llvm::Triple::MacOSX:371case llvm::Triple::IOS:372case llvm::Triple::TvOS:373case llvm::Triple::DriverKit:374case llvm::Triple::XROS:375// Darwin defaults to "softfp" for v6 and v7.376if (Triple.isWatchABI())377return FloatABI::Hard;378else379return (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;380381case llvm::Triple::WatchOS:382return FloatABI::Hard;383384// FIXME: this is invalid for WindowsCE385case llvm::Triple::Win32:386// It is incorrect to select hard float ABI on MachO platforms if the ABI is387// "apcs-gnu".388if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple))389return FloatABI::Soft;390return FloatABI::Hard;391392case llvm::Triple::NetBSD:393switch (Triple.getEnvironment()) {394case llvm::Triple::EABIHF:395case llvm::Triple::GNUEABIHF:396return FloatABI::Hard;397default:398return FloatABI::Soft;399}400break;401402case llvm::Triple::FreeBSD:403switch (Triple.getEnvironment()) {404case llvm::Triple::GNUEABIHF:405return FloatABI::Hard;406default:407// FreeBSD defaults to soft float408return FloatABI::Soft;409}410break;411412case llvm::Triple::Haiku:413case llvm::Triple::OpenBSD:414return FloatABI::SoftFP;415416default:417if (Triple.isOHOSFamily())418return FloatABI::Soft;419switch (Triple.getEnvironment()) {420case llvm::Triple::GNUEABIHF:421case llvm::Triple::GNUEABIHFT64:422case llvm::Triple::MuslEABIHF:423case llvm::Triple::EABIHF:424return FloatABI::Hard;425case llvm::Triple::GNUEABI:426case llvm::Triple::GNUEABIT64:427case llvm::Triple::MuslEABI:428case llvm::Triple::EABI:429// EABI is always AAPCS, and if it was not marked 'hard', it's softfp430return FloatABI::SoftFP;431case llvm::Triple::Android:432return (SubArch >= 7) ? FloatABI::SoftFP : FloatABI::Soft;433default:434return FloatABI::Invalid;435}436}437return FloatABI::Invalid;438}439440// Select the float ABI as determined by -msoft-float, -mhard-float, and441// -mfloat-abi=.442arm::FloatABI arm::getARMFloatABI(const Driver &D, const llvm::Triple &Triple,443const ArgList &Args) {444arm::FloatABI ABI = FloatABI::Invalid;445if (Arg *A =446Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,447options::OPT_mfloat_abi_EQ)) {448if (A->getOption().matches(options::OPT_msoft_float)) {449ABI = FloatABI::Soft;450} else if (A->getOption().matches(options::OPT_mhard_float)) {451ABI = FloatABI::Hard;452} else {453ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())454.Case("soft", FloatABI::Soft)455.Case("softfp", FloatABI::SoftFP)456.Case("hard", FloatABI::Hard)457.Default(FloatABI::Invalid);458if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {459D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);460ABI = FloatABI::Soft;461}462}463}464465// If unspecified, choose the default based on the platform.466if (ABI == FloatABI::Invalid)467ABI = arm::getDefaultFloatABI(Triple);468469if (ABI == FloatABI::Invalid) {470// Assume "soft", but warn the user we are guessing.471if (Triple.isOSBinFormatMachO() &&472Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)473ABI = FloatABI::Hard;474else475ABI = FloatABI::Soft;476477if (Triple.getOS() != llvm::Triple::UnknownOS ||478!Triple.isOSBinFormatMachO())479D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";480}481482assert(ABI != FloatABI::Invalid && "must select an ABI");483return ABI;484}485486static bool hasIntegerMVE(const std::vector<StringRef> &F) {487auto MVE = llvm::find(llvm::reverse(F), "+mve");488auto NoMVE = llvm::find(llvm::reverse(F), "-mve");489return MVE != F.rend() &&490(NoMVE == F.rend() || std::distance(MVE, NoMVE) > 0);491}492493llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver &D,494const llvm::Triple &Triple,495const ArgList &Args,496std::vector<StringRef> &Features,497bool ForAS, bool ForMultilib) {498bool KernelOrKext =499Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);500arm::FloatABI ABI = arm::getARMFloatABI(D, Triple, Args);501std::optional<std::pair<const Arg *, StringRef>> WaCPU, WaFPU, WaHDiv, WaArch;502503// This vector will accumulate features from the architecture504// extension suffixes on -mcpu and -march (e.g. the 'bar' in505// -mcpu=foo+bar). We want to apply those after the features derived506// from the FPU, in case -mfpu generates a negative feature which507// the +bar is supposed to override.508std::vector<StringRef> ExtensionFeatures;509510if (!ForAS) {511// FIXME: Note, this is a hack, the LLVM backend doesn't actually use these512// yet (it uses the -mfloat-abi and -msoft-float options), and it is513// stripped out by the ARM target. We should probably pass this a new514// -target-option, which is handled by the -cc1/-cc1as invocation.515//516// FIXME2: For consistency, it would be ideal if we set up the target517// machine state the same when using the frontend or the assembler. We don't518// currently do that for the assembler, we pass the options directly to the519// backend and never even instantiate the frontend TargetInfo. If we did,520// and used its handleTargetFeatures hook, then we could ensure the521// assembler and the frontend behave the same.522523// Use software floating point operations?524if (ABI == arm::FloatABI::Soft)525Features.push_back("+soft-float");526527// Use software floating point argument passing?528if (ABI != arm::FloatABI::Hard)529Features.push_back("+soft-float-abi");530} else {531// Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down532// to the assembler correctly.533for (const Arg *A :534Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {535// We use getValues here because you can have many options per -Wa536// We will keep the last one we find for each of these537for (StringRef Value : A->getValues()) {538if (Value.starts_with("-mfpu=")) {539WaFPU = std::make_pair(A, Value.substr(6));540} else if (Value.starts_with("-mcpu=")) {541WaCPU = std::make_pair(A, Value.substr(6));542} else if (Value.starts_with("-mhwdiv=")) {543WaHDiv = std::make_pair(A, Value.substr(8));544} else if (Value.starts_with("-march=")) {545WaArch = std::make_pair(A, Value.substr(7));546}547}548}549550// The integrated assembler doesn't implement e_flags setting behavior for551// -meabi=gnu (gcc -mabi={apcs-gnu,atpcs} passes -meabi=gnu to gas). For552// compatibility we accept but warn.553if (Arg *A = Args.getLastArgNoClaim(options::OPT_mabi_EQ))554A->ignoreTargetSpecific();555}556557if (getReadTPMode(D, Args, Triple, ForAS) == ReadTPMode::TPIDRURW)558Features.push_back("+read-tp-tpidrurw");559if (getReadTPMode(D, Args, Triple, ForAS) == ReadTPMode::TPIDRURO)560Features.push_back("+read-tp-tpidruro");561if (getReadTPMode(D, Args, Triple, ForAS) == ReadTPMode::TPIDRPRW)562Features.push_back("+read-tp-tpidrprw");563564const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);565const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);566StringRef ArchName;567StringRef CPUName;568llvm::ARM::FPUKind ArchArgFPUKind = llvm::ARM::FK_INVALID;569llvm::ARM::FPUKind CPUArgFPUKind = llvm::ARM::FK_INVALID;570571// Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.572if (WaCPU) {573if (CPUArg)574D.Diag(clang::diag::warn_drv_unused_argument)575<< CPUArg->getAsString(Args);576CPUName = WaCPU->second;577CPUArg = WaCPU->first;578} else if (CPUArg)579CPUName = CPUArg->getValue();580581// Check -march. ClangAs gives preference to -Wa,-march=.582if (WaArch) {583if (ArchArg)584D.Diag(clang::diag::warn_drv_unused_argument)585<< ArchArg->getAsString(Args);586ArchName = WaArch->second;587// This will set any features after the base architecture.588checkARMArchName(D, WaArch->first, Args, ArchName, CPUName,589ExtensionFeatures, Triple, ArchArgFPUKind);590// The base architecture was handled in ToolChain::ComputeLLVMTriple because591// triple is read only by this point.592} else if (ArchArg) {593ArchName = ArchArg->getValue();594checkARMArchName(D, ArchArg, Args, ArchName, CPUName, ExtensionFeatures,595Triple, ArchArgFPUKind);596}597598// Add CPU features for generic CPUs599if (CPUName == "native") {600for (auto &F : llvm::sys::getHostCPUFeatures())601Features.push_back(602Args.MakeArgString((F.second ? "+" : "-") + F.first()));603} else if (!CPUName.empty()) {604// This sets the default features for the specified CPU. We certainly don't605// want to override the features that have been explicitly specified on the606// command line. Therefore, process them directly instead of appending them607// at the end later.608DecodeARMFeaturesFromCPU(D, CPUName, Features);609}610611if (CPUArg)612checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, ExtensionFeatures,613Triple, CPUArgFPUKind);614615// TODO Handle -mtune=. Suppress -Wunused-command-line-argument as a616// longstanding behavior.617(void)Args.getLastArg(options::OPT_mtune_EQ);618619// Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.620llvm::ARM::FPUKind FPUKind = llvm::ARM::FK_INVALID;621const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);622if (WaFPU) {623if (FPUArg)624D.Diag(clang::diag::warn_drv_unused_argument)625<< FPUArg->getAsString(Args);626(void)getARMFPUFeatures(D, WaFPU->first, Args, WaFPU->second, Features);627} else if (FPUArg) {628FPUKind = getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);629} else if (Triple.isAndroid() && getARMSubArchVersionNumber(Triple) >= 7) {630const char *AndroidFPU = "neon";631FPUKind = llvm::ARM::parseFPU(AndroidFPU);632if (!llvm::ARM::getFPUFeatures(FPUKind, Features))633D.Diag(clang::diag::err_drv_clang_unsupported)634<< std::string("-mfpu=") + AndroidFPU;635} else if (ArchArgFPUKind != llvm::ARM::FK_INVALID ||636CPUArgFPUKind != llvm::ARM::FK_INVALID) {637FPUKind =638CPUArgFPUKind != llvm::ARM::FK_INVALID ? CPUArgFPUKind : ArchArgFPUKind;639(void)llvm::ARM::getFPUFeatures(FPUKind, Features);640} else {641if (!ForAS) {642std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);643llvm::ARM::ArchKind ArchKind =644arm::getLLVMArchKindForARM(CPU, ArchName, Triple);645FPUKind = llvm::ARM::getDefaultFPU(CPU, ArchKind);646(void)llvm::ARM::getFPUFeatures(FPUKind, Features);647}648}649650// Now we've finished accumulating features from arch, cpu and fpu,651// we can append the ones for architecture extensions that we652// collected separately.653Features.insert(std::end(Features),654std::begin(ExtensionFeatures), std::end(ExtensionFeatures));655656// Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.657const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);658if (WaHDiv) {659if (HDivArg)660D.Diag(clang::diag::warn_drv_unused_argument)661<< HDivArg->getAsString(Args);662getARMHWDivFeatures(D, WaHDiv->first, Args, WaHDiv->second, Features);663} else if (HDivArg)664getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);665666// Handle (arch-dependent) fp16fml/fullfp16 relationship.667// Must happen before any features are disabled due to soft-float.668// FIXME: this fp16fml option handling will be reimplemented after the669// TargetParser rewrite.670const auto ItRNoFullFP16 = std::find(Features.rbegin(), Features.rend(), "-fullfp16");671const auto ItRFP16FML = std::find(Features.rbegin(), Features.rend(), "+fp16fml");672if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_4a) {673const auto ItRFullFP16 = std::find(Features.rbegin(), Features.rend(), "+fullfp16");674if (ItRFullFP16 < ItRNoFullFP16 && ItRFullFP16 < ItRFP16FML) {675// Only entangled feature that can be to the right of this +fullfp16 is -fp16fml.676// Only append the +fp16fml if there is no -fp16fml after the +fullfp16.677if (std::find(Features.rbegin(), ItRFullFP16, "-fp16fml") == ItRFullFP16)678Features.push_back("+fp16fml");679}680else681goto fp16_fml_fallthrough;682}683else {684fp16_fml_fallthrough:685// In both of these cases, putting the 'other' feature on the end of the vector will686// result in the same effect as placing it immediately after the current feature.687if (ItRNoFullFP16 < ItRFP16FML)688Features.push_back("-fp16fml");689else if (ItRNoFullFP16 > ItRFP16FML)690Features.push_back("+fullfp16");691}692693// Setting -msoft-float/-mfloat-abi=soft, -mfpu=none, or adding +nofp to694// -march/-mcpu effectively disables the FPU (GCC ignores the -mfpu options in695// this case). Note that the ABI can also be set implicitly by the target696// selected.697bool HasFPRegs = true;698if (ABI == arm::FloatABI::Soft) {699llvm::ARM::getFPUFeatures(llvm::ARM::FK_NONE, Features);700701// Disable all features relating to hardware FP, not already disabled by the702// above call.703Features.insert(Features.end(),704{"-dotprod", "-fp16fml", "-bf16", "-mve", "-mve.fp"});705HasFPRegs = false;706FPUKind = llvm::ARM::FK_NONE;707} else if (FPUKind == llvm::ARM::FK_NONE ||708ArchArgFPUKind == llvm::ARM::FK_NONE ||709CPUArgFPUKind == llvm::ARM::FK_NONE) {710// -mfpu=none, -march=armvX+nofp or -mcpu=X+nofp is *very* similar to711// -mfloat-abi=soft, only that it should not disable MVE-I. They disable the712// FPU, but not the FPU registers, thus MVE-I, which depends only on the713// latter, is still supported.714Features.insert(Features.end(),715{"-dotprod", "-fp16fml", "-bf16", "-mve.fp"});716HasFPRegs = hasIntegerMVE(Features);717FPUKind = llvm::ARM::FK_NONE;718}719if (!HasFPRegs)720Features.emplace_back("-fpregs");721722// En/disable crc code generation.723if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {724if (A->getOption().matches(options::OPT_mcrc))725Features.push_back("+crc");726else727Features.push_back("-crc");728}729730// For Arch >= ARMv8.0 && A or R profile: crypto = sha2 + aes731// Rather than replace within the feature vector, determine whether each732// algorithm is enabled and append this to the end of the vector.733// The algorithms can be controlled by their specific feature or the crypto734// feature, so their status can be determined by the last occurance of735// either in the vector. This allows one to supercede the other.736// e.g. +crypto+noaes in -march/-mcpu should enable sha2, but not aes737// FIXME: this needs reimplementation after the TargetParser rewrite738bool HasSHA2 = false;739bool HasAES = false;740const auto ItCrypto =741llvm::find_if(llvm::reverse(Features), [](const StringRef F) {742return F.contains("crypto");743});744const auto ItSHA2 =745llvm::find_if(llvm::reverse(Features), [](const StringRef F) {746return F.contains("crypto") || F.contains("sha2");747});748const auto ItAES =749llvm::find_if(llvm::reverse(Features), [](const StringRef F) {750return F.contains("crypto") || F.contains("aes");751});752const bool FoundSHA2 = ItSHA2 != Features.rend();753const bool FoundAES = ItAES != Features.rend();754if (FoundSHA2)755HasSHA2 = ItSHA2->take_front() == "+";756if (FoundAES)757HasAES = ItAES->take_front() == "+";758if (ItCrypto != Features.rend()) {759if (HasSHA2 && HasAES)760Features.push_back("+crypto");761else762Features.push_back("-crypto");763if (HasSHA2)764Features.push_back("+sha2");765else766Features.push_back("-sha2");767if (HasAES)768Features.push_back("+aes");769else770Features.push_back("-aes");771}772773if (HasSHA2 || HasAES) {774StringRef ArchSuffix = arm::getLLVMArchSuffixForARM(775arm::getARMTargetCPU(CPUName, ArchName, Triple), ArchName, Triple);776llvm::ARM::ProfileKind ArchProfile =777llvm::ARM::parseArchProfile(ArchSuffix);778if (!((llvm::ARM::parseArchVersion(ArchSuffix) >= 8) &&779(ArchProfile == llvm::ARM::ProfileKind::A ||780ArchProfile == llvm::ARM::ProfileKind::R))) {781if (HasSHA2)782D.Diag(clang::diag::warn_target_unsupported_extension)783<< "sha2"784<< llvm::ARM::getArchName(llvm::ARM::parseArch(ArchSuffix));785if (HasAES)786D.Diag(clang::diag::warn_target_unsupported_extension)787<< "aes"788<< llvm::ARM::getArchName(llvm::ARM::parseArch(ArchSuffix));789// With -fno-integrated-as -mfpu=crypto-neon-fp-armv8 some assemblers such790// as the GNU assembler will permit the use of crypto instructions as the791// fpu will override the architecture. We keep the crypto feature in this792// case to preserve compatibility. In all other cases we remove the crypto793// feature.794if (!Args.hasArg(options::OPT_fno_integrated_as)) {795Features.push_back("-sha2");796Features.push_back("-aes");797}798}799}800801// Propagate frame-chain model selection802if (Arg *A = Args.getLastArg(options::OPT_mframe_chain)) {803StringRef FrameChainOption = A->getValue();804if (FrameChainOption.starts_with("aapcs"))805Features.push_back("+aapcs-frame-chain");806}807808// CMSE: Check for target 8M (for -mcmse to be applicable) is performed later.809if (Args.getLastArg(options::OPT_mcmse))810Features.push_back("+8msecext");811812if (Arg *A = Args.getLastArg(options::OPT_mfix_cmse_cve_2021_35465,813options::OPT_mno_fix_cmse_cve_2021_35465)) {814if (!Args.getLastArg(options::OPT_mcmse))815D.Diag(diag::err_opt_not_valid_without_opt)816<< A->getOption().getName() << "-mcmse";817818if (A->getOption().matches(options::OPT_mfix_cmse_cve_2021_35465))819Features.push_back("+fix-cmse-cve-2021-35465");820else821Features.push_back("-fix-cmse-cve-2021-35465");822}823824// This also handles the -m(no-)fix-cortex-a72-1655431 arguments via aliases.825if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a57_aes_1742098,826options::OPT_mno_fix_cortex_a57_aes_1742098)) {827if (A->getOption().matches(options::OPT_mfix_cortex_a57_aes_1742098)) {828Features.push_back("+fix-cortex-a57-aes-1742098");829} else {830Features.push_back("-fix-cortex-a57-aes-1742098");831}832}833834// Look for the last occurrence of -mlong-calls or -mno-long-calls. If835// neither options are specified, see if we are compiling for kernel/kext and836// decide whether to pass "+long-calls" based on the OS and its version.837if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,838options::OPT_mno_long_calls)) {839if (A->getOption().matches(options::OPT_mlong_calls))840Features.push_back("+long-calls");841} else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&842!Triple.isWatchOS() && !Triple.isXROS()) {843Features.push_back("+long-calls");844}845846// Generate execute-only output (no data access to code sections).847// This only makes sense for the compiler, not for the assembler.848// It's not needed for multilib selection and may hide an unused849// argument diagnostic if the code is always run.850if (!ForAS && !ForMultilib) {851// Supported only on ARMv6T2 and ARMv7 and above.852// Cannot be combined with -mno-movt.853if (Arg *A = Args.getLastArg(options::OPT_mexecute_only, options::OPT_mno_execute_only)) {854if (A->getOption().matches(options::OPT_mexecute_only)) {855if (getARMSubArchVersionNumber(Triple) < 7 &&856llvm::ARM::parseArch(Triple.getArchName()) != llvm::ARM::ArchKind::ARMV6T2 &&857llvm::ARM::parseArch(Triple.getArchName()) != llvm::ARM::ArchKind::ARMV6M)858D.Diag(diag::err_target_unsupported_execute_only) << Triple.getArchName();859else if (llvm::ARM::parseArch(Triple.getArchName()) == llvm::ARM::ArchKind::ARMV6M) {860if (Arg *PIArg = Args.getLastArg(options::OPT_fropi, options::OPT_frwpi,861options::OPT_fpic, options::OPT_fpie,862options::OPT_fPIC, options::OPT_fPIE))863D.Diag(diag::err_opt_not_valid_with_opt_on_target)864<< A->getAsString(Args) << PIArg->getAsString(Args) << Triple.getArchName();865} else if (Arg *B = Args.getLastArg(options::OPT_mno_movt))866D.Diag(diag::err_opt_not_valid_with_opt)867<< A->getAsString(Args) << B->getAsString(Args);868Features.push_back("+execute-only");869}870}871}872873if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,874options::OPT_munaligned_access,875options::OPT_mstrict_align,876options::OPT_mno_strict_align)) {877// Kernel code has more strict alignment requirements.878if (KernelOrKext ||879A->getOption().matches(options::OPT_mno_unaligned_access) ||880A->getOption().matches(options::OPT_mstrict_align)) {881Features.push_back("+strict-align");882} else {883// No v6M core supports unaligned memory access (v6M ARM ARM A3.2).884if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)885D.Diag(diag::err_target_unsupported_unaligned) << "v6m";886// v8M Baseline follows on from v6M, so doesn't support unaligned memory887// access either.888else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)889D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";890}891} else {892// Assume pre-ARMv6 doesn't support unaligned accesses.893//894// ARMv6 may or may not support unaligned accesses depending on the895// SCTLR.U bit, which is architecture-specific. We assume ARMv6896// Darwin and NetBSD targets support unaligned accesses, and others don't.897//898// ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit which899// raises an alignment fault on unaligned accesses. Assume ARMv7+ supports900// unaligned accesses, except ARMv6-M, and ARMv8-M without the Main901// Extension. This aligns with the default behavior of ARM's downstream902// versions of GCC and Clang.903//904// Users can change the default behavior via -m[no-]unaliged-access.905int VersionNum = getARMSubArchVersionNumber(Triple);906if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {907if (VersionNum < 6 ||908Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)909Features.push_back("+strict-align");910} else if (VersionNum < 7 ||911Triple.getSubArch() ==912llvm::Triple::SubArchType::ARMSubArch_v6m ||913Triple.getSubArch() ==914llvm::Triple::SubArchType::ARMSubArch_v8m_baseline) {915Features.push_back("+strict-align");916}917}918919// llvm does not support reserving registers in general. There is support920// for reserving r9 on ARM though (defined as a platform-specific register921// in ARM EABI).922if (Args.hasArg(options::OPT_ffixed_r9))923Features.push_back("+reserve-r9");924925// The kext linker doesn't know how to deal with movw/movt.926if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))927Features.push_back("+no-movt");928929if (Args.hasArg(options::OPT_mno_neg_immediates))930Features.push_back("+no-neg-immediates");931932// Enable/disable straight line speculation hardening.933if (Arg *A = Args.getLastArg(options::OPT_mharden_sls_EQ)) {934StringRef Scope = A->getValue();935bool EnableRetBr = false;936bool EnableBlr = false;937bool DisableComdat = false;938if (Scope != "none") {939SmallVector<StringRef, 4> Opts;940Scope.split(Opts, ",");941for (auto Opt : Opts) {942Opt = Opt.trim();943if (Opt == "all") {944EnableBlr = true;945EnableRetBr = true;946continue;947}948if (Opt == "retbr") {949EnableRetBr = true;950continue;951}952if (Opt == "blr") {953EnableBlr = true;954continue;955}956if (Opt == "comdat") {957DisableComdat = false;958continue;959}960if (Opt == "nocomdat") {961DisableComdat = true;962continue;963}964D.Diag(diag::err_drv_unsupported_option_argument)965<< A->getSpelling() << Scope;966break;967}968}969970if (EnableRetBr || EnableBlr)971if (!(isARMAProfile(Triple) && getARMSubArchVersionNumber(Triple) >= 7))972D.Diag(diag::err_sls_hardening_arm_not_supported)973<< Scope << A->getAsString(Args);974975if (EnableRetBr)976Features.push_back("+harden-sls-retbr");977if (EnableBlr)978Features.push_back("+harden-sls-blr");979if (DisableComdat) {980Features.push_back("+harden-sls-nocomdat");981}982}983984if (Args.getLastArg(options::OPT_mno_bti_at_return_twice))985Features.push_back("+no-bti-at-return-twice");986987checkARMFloatABI(D, Args, HasFPRegs);988989return FPUKind;990}991992std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {993std::string MArch;994if (!Arch.empty())995MArch = std::string(Arch);996else997MArch = std::string(Triple.getArchName());998MArch = StringRef(MArch).split("+").first.lower();9991000// Handle -march=native.1001if (MArch == "native") {1002std::string CPU = std::string(llvm::sys::getHostCPUName());1003if (CPU != "generic") {1004// Translate the native cpu into the architecture suffix for that CPU.1005StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);1006// If there is no valid architecture suffix for this CPU we don't know how1007// to handle it, so return no architecture.1008if (Suffix.empty())1009MArch = "";1010else1011MArch = std::string("arm") + Suffix.str();1012}1013}10141015return MArch;1016}10171018/// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.1019StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {1020std::string MArch = getARMArch(Arch, Triple);1021// getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch1022// here means an -march=native that we can't handle, so instead return no CPU.1023if (MArch.empty())1024return StringRef();10251026// We need to return an empty string here on invalid MArch values as the1027// various places that call this function can't cope with a null result.1028return llvm::ARM::getARMCPUForArch(Triple, MArch);1029}10301031/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.1032std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,1033const llvm::Triple &Triple) {1034// FIXME: Warn on inconsistent use of -mcpu and -march.1035// If we have -mcpu=, use that.1036if (!CPU.empty()) {1037std::string MCPU = StringRef(CPU).split("+").first.lower();1038// Handle -mcpu=native.1039if (MCPU == "native")1040return std::string(llvm::sys::getHostCPUName());1041else1042return MCPU;1043}10441045return std::string(getARMCPUForMArch(Arch, Triple));1046}10471048/// getLLVMArchSuffixForARM - Get the LLVM ArchKind value to use for a1049/// particular CPU (or Arch, if CPU is generic). This is needed to1050/// pass to functions like llvm::ARM::getDefaultFPU which need an1051/// ArchKind as well as a CPU name.1052llvm::ARM::ArchKind arm::getLLVMArchKindForARM(StringRef CPU, StringRef Arch,1053const llvm::Triple &Triple) {1054llvm::ARM::ArchKind ArchKind;1055if (CPU == "generic" || CPU.empty()) {1056std::string ARMArch = tools::arm::getARMArch(Arch, Triple);1057ArchKind = llvm::ARM::parseArch(ARMArch);1058if (ArchKind == llvm::ARM::ArchKind::INVALID)1059// In case of generic Arch, i.e. "arm",1060// extract arch from default cpu of the Triple1061ArchKind =1062llvm::ARM::parseCPUArch(llvm::ARM::getARMCPUForArch(Triple, ARMArch));1063} else {1064// FIXME: horrible hack to get around the fact that Cortex-A7 is only an1065// armv7k triple if it's actually been specified via "-arch armv7k".1066ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")1067? llvm::ARM::ArchKind::ARMV7K1068: llvm::ARM::parseCPUArch(CPU);1069}1070return ArchKind;1071}10721073/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular1074/// CPU (or Arch, if CPU is generic).1075// FIXME: This is redundant with -mcpu, why does LLVM use this.1076StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,1077const llvm::Triple &Triple) {1078llvm::ARM::ArchKind ArchKind = getLLVMArchKindForARM(CPU, Arch, Triple);1079if (ArchKind == llvm::ARM::ArchKind::INVALID)1080return "";1081return llvm::ARM::getSubArch(ArchKind);1082}10831084void arm::appendBE8LinkFlag(const ArgList &Args, ArgStringList &CmdArgs,1085const llvm::Triple &Triple) {1086if (Args.hasArg(options::OPT_r))1087return;10881089// ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker1090// to generate BE-8 executables.1091if (arm::getARMSubArchVersionNumber(Triple) >= 7 || arm::isARMMProfile(Triple))1092CmdArgs.push_back("--be8");1093}109410951096