1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===// 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 // This file defines the interfaces that ARM uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "ARMISelLowering.h" 15 #include "ARMBaseInstrInfo.h" 16 #include "ARMBaseRegisterInfo.h" 17 #include "ARMCallingConv.h" 18 #include "ARMConstantPoolValue.h" 19 #include "ARMMachineFunctionInfo.h" 20 #include "ARMPerfectShuffle.h" 21 #include "ARMRegisterInfo.h" 22 #include "ARMSelectionDAGInfo.h" 23 #include "ARMSubtarget.h" 24 #include "MCTargetDesc/ARMAddressingModes.h" 25 #include "MCTargetDesc/ARMBaseInfo.h" 26 #include "Utils/ARMBaseInfo.h" 27 #include "llvm/ADT/APFloat.h" 28 #include "llvm/ADT/APInt.h" 29 #include "llvm/ADT/ArrayRef.h" 30 #include "llvm/ADT/BitVector.h" 31 #include "llvm/ADT/DenseMap.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/ADT/StringRef.h" 38 #include "llvm/ADT/StringSwitch.h" 39 #include "llvm/ADT/Triple.h" 40 #include "llvm/ADT/Twine.h" 41 #include "llvm/Analysis/VectorUtils.h" 42 #include "llvm/CodeGen/CallingConvLower.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/IntrinsicLowering.h" 45 #include "llvm/CodeGen/MachineBasicBlock.h" 46 #include "llvm/CodeGen/MachineConstantPool.h" 47 #include "llvm/CodeGen/MachineFrameInfo.h" 48 #include "llvm/CodeGen/MachineFunction.h" 49 #include "llvm/CodeGen/MachineInstr.h" 50 #include "llvm/CodeGen/MachineInstrBuilder.h" 51 #include "llvm/CodeGen/MachineJumpTableInfo.h" 52 #include "llvm/CodeGen/MachineMemOperand.h" 53 #include "llvm/CodeGen/MachineOperand.h" 54 #include "llvm/CodeGen/MachineRegisterInfo.h" 55 #include "llvm/CodeGen/RuntimeLibcalls.h" 56 #include "llvm/CodeGen/SelectionDAG.h" 57 #include "llvm/CodeGen/SelectionDAGNodes.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/IR/Attributes.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DebugLoc.h" 70 #include "llvm/IR/DerivedTypes.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GlobalAlias.h" 73 #include "llvm/IR/GlobalValue.h" 74 #include "llvm/IR/GlobalVariable.h" 75 #include "llvm/IR/IRBuilder.h" 76 #include "llvm/IR/InlineAsm.h" 77 #include "llvm/IR/Instruction.h" 78 #include "llvm/IR/Instructions.h" 79 #include "llvm/IR/IntrinsicInst.h" 80 #include "llvm/IR/Intrinsics.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/Type.h" 83 #include "llvm/IR/User.h" 84 #include "llvm/IR/Value.h" 85 #include "llvm/MC/MCInstrDesc.h" 86 #include "llvm/MC/MCInstrItineraries.h" 87 #include "llvm/MC/MCRegisterInfo.h" 88 #include "llvm/MC/MCSchedule.h" 89 #include "llvm/Support/AtomicOrdering.h" 90 #include "llvm/Support/BranchProbability.h" 91 #include "llvm/Support/Casting.h" 92 #include "llvm/Support/CodeGen.h" 93 #include "llvm/Support/CommandLine.h" 94 #include "llvm/Support/Compiler.h" 95 #include "llvm/Support/Debug.h" 96 #include "llvm/Support/ErrorHandling.h" 97 #include "llvm/Support/KnownBits.h" 98 #include "llvm/Support/MachineValueType.h" 99 #include "llvm/Support/MathExtras.h" 100 #include "llvm/Support/raw_ostream.h" 101 #include "llvm/Target/TargetMachine.h" 102 #include "llvm/Target/TargetOptions.h" 103 #include <algorithm> 104 #include <cassert> 105 #include <cstdint> 106 #include <cstdlib> 107 #include <iterator> 108 #include <limits> 109 #include <string> 110 #include <tuple> 111 #include <utility> 112 #include <vector> 113 114 using namespace llvm; 115 116 #define DEBUG_TYPE "arm-isel" 117 118 STATISTIC(NumTailCalls, "Number of tail calls"); 119 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 120 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 121 STATISTIC(NumConstpoolPromoted, 122 "Number of constants with their storage promoted into constant pools"); 123 124 static cl::opt<bool> 125 ARMInterworking("arm-interworking", cl::Hidden, 126 cl::desc("Enable / disable ARM interworking (for debugging only)"), 127 cl::init(true)); 128 129 static cl::opt<bool> EnableConstpoolPromotion( 130 "arm-promote-constant", cl::Hidden, 131 cl::desc("Enable / disable promotion of unnamed_addr constants into " 132 "constant pools"), 133 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 134 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 135 "arm-promote-constant-max-size", cl::Hidden, 136 cl::desc("Maximum size of constant to promote into a constant pool"), 137 cl::init(64)); 138 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 139 "arm-promote-constant-max-total", cl::Hidden, 140 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 141 cl::init(128)); 142 143 // The APCS parameter registers. 144 static const MCPhysReg GPRArgRegs[] = { 145 ARM::R0, ARM::R1, ARM::R2, ARM::R3 146 }; 147 148 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 149 MVT PromotedBitwiseVT) { 150 if (VT != PromotedLdStVT) { 151 setOperationAction(ISD::LOAD, VT, Promote); 152 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 153 154 setOperationAction(ISD::STORE, VT, Promote); 155 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 156 } 157 158 MVT ElemTy = VT.getVectorElementType(); 159 if (ElemTy != MVT::f64) 160 setOperationAction(ISD::SETCC, VT, Custom); 161 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 162 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 163 if (ElemTy == MVT::i32) { 164 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 165 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 166 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 167 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 168 } else { 169 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 170 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 171 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 172 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 173 } 174 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 175 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 176 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 177 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 178 setOperationAction(ISD::SELECT, VT, Expand); 179 setOperationAction(ISD::SELECT_CC, VT, Expand); 180 setOperationAction(ISD::VSELECT, VT, Expand); 181 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 182 if (VT.isInteger()) { 183 setOperationAction(ISD::SHL, VT, Custom); 184 setOperationAction(ISD::SRA, VT, Custom); 185 setOperationAction(ISD::SRL, VT, Custom); 186 } 187 188 // Promote all bit-wise operations. 189 if (VT.isInteger() && VT != PromotedBitwiseVT) { 190 setOperationAction(ISD::AND, VT, Promote); 191 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 192 setOperationAction(ISD::OR, VT, Promote); 193 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 194 setOperationAction(ISD::XOR, VT, Promote); 195 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 196 } 197 198 // Neon does not support vector divide/remainder operations. 199 setOperationAction(ISD::SDIV, VT, Expand); 200 setOperationAction(ISD::UDIV, VT, Expand); 201 setOperationAction(ISD::FDIV, VT, Expand); 202 setOperationAction(ISD::SREM, VT, Expand); 203 setOperationAction(ISD::UREM, VT, Expand); 204 setOperationAction(ISD::FREM, VT, Expand); 205 206 if (!VT.isFloatingPoint() && 207 VT != MVT::v2i64 && VT != MVT::v1i64) 208 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 209 setOperationAction(Opcode, VT, Legal); 210 } 211 212 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 213 addRegisterClass(VT, &ARM::DPRRegClass); 214 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 215 } 216 217 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 218 addRegisterClass(VT, &ARM::DPairRegClass); 219 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 220 } 221 222 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 223 const ARMSubtarget &STI) 224 : TargetLowering(TM), Subtarget(&STI) { 225 RegInfo = Subtarget->getRegisterInfo(); 226 Itins = Subtarget->getInstrItineraryData(); 227 228 setBooleanContents(ZeroOrOneBooleanContent); 229 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 230 231 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 232 !Subtarget->isTargetWatchOS()) { 233 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 234 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 235 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 236 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 237 : CallingConv::ARM_AAPCS); 238 } 239 240 if (Subtarget->isTargetMachO()) { 241 // Uses VFP for Thumb libfuncs if available. 242 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 243 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 244 static const struct { 245 const RTLIB::Libcall Op; 246 const char * const Name; 247 const ISD::CondCode Cond; 248 } LibraryCalls[] = { 249 // Single-precision floating-point arithmetic. 250 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 251 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 252 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 253 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 254 255 // Double-precision floating-point arithmetic. 256 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 257 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 258 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 259 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 260 261 // Single-precision comparisons. 262 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 263 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 264 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 265 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 266 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 267 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 268 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 269 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 270 271 // Double-precision comparisons. 272 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 273 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 274 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 275 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 276 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 277 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 278 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 279 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 280 281 // Floating-point to integer conversions. 282 // i64 conversions are done via library routines even when generating VFP 283 // instructions, so use the same ones. 284 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 285 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 286 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 287 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 288 289 // Conversions between floating types. 290 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 291 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 292 293 // Integer to floating-point conversions. 294 // i64 conversions are done via library routines even when generating VFP 295 // instructions, so use the same ones. 296 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 297 // e.g., __floatunsidf vs. __floatunssidfvfp. 298 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 299 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 300 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 301 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 302 }; 303 304 for (const auto &LC : LibraryCalls) { 305 setLibcallName(LC.Op, LC.Name); 306 if (LC.Cond != ISD::SETCC_INVALID) 307 setCmpLibcallCC(LC.Op, LC.Cond); 308 } 309 } 310 } 311 312 // These libcalls are not available in 32-bit. 313 setLibcallName(RTLIB::SHL_I128, nullptr); 314 setLibcallName(RTLIB::SRL_I128, nullptr); 315 setLibcallName(RTLIB::SRA_I128, nullptr); 316 317 // RTLIB 318 if (Subtarget->isAAPCS_ABI() && 319 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 320 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 321 static const struct { 322 const RTLIB::Libcall Op; 323 const char * const Name; 324 const CallingConv::ID CC; 325 const ISD::CondCode Cond; 326 } LibraryCalls[] = { 327 // Double-precision floating-point arithmetic helper functions 328 // RTABI chapter 4.1.2, Table 2 329 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 330 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 331 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 334 // Double-precision floating-point comparison helper functions 335 // RTABI chapter 4.1.2, Table 3 336 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 337 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 338 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 339 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 340 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 341 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 342 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 343 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 344 345 // Single-precision floating-point arithmetic helper functions 346 // RTABI chapter 4.1.2, Table 4 347 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 348 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 349 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 350 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 351 352 // Single-precision floating-point comparison helper functions 353 // RTABI chapter 4.1.2, Table 5 354 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 355 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 356 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 357 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 358 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 359 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 360 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 361 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 362 363 // Floating-point to integer conversions. 364 // RTABI chapter 4.1.2, Table 6 365 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 366 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 367 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 368 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 369 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 370 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 371 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 372 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 373 374 // Conversions between floating types. 375 // RTABI chapter 4.1.2, Table 7 376 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 377 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 378 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 380 // Integer to floating-point conversions. 381 // RTABI chapter 4.1.2, Table 8 382 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 383 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 384 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 385 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 386 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 387 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 388 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 389 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 390 391 // Long long helper functions 392 // RTABI chapter 4.2, Table 9 393 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 394 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 395 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 398 // Integer division functions 399 // RTABI chapter 4.3.1 400 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 401 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 402 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 403 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 404 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 406 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 407 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 408 }; 409 410 for (const auto &LC : LibraryCalls) { 411 setLibcallName(LC.Op, LC.Name); 412 setLibcallCallingConv(LC.Op, LC.CC); 413 if (LC.Cond != ISD::SETCC_INVALID) 414 setCmpLibcallCC(LC.Op, LC.Cond); 415 } 416 417 // EABI dependent RTLIB 418 if (TM.Options.EABIVersion == EABI::EABI4 || 419 TM.Options.EABIVersion == EABI::EABI5) { 420 static const struct { 421 const RTLIB::Libcall Op; 422 const char *const Name; 423 const CallingConv::ID CC; 424 const ISD::CondCode Cond; 425 } MemOpsLibraryCalls[] = { 426 // Memory operations 427 // RTABI chapter 4.3.4 428 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 429 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 430 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 431 }; 432 433 for (const auto &LC : MemOpsLibraryCalls) { 434 setLibcallName(LC.Op, LC.Name); 435 setLibcallCallingConv(LC.Op, LC.CC); 436 if (LC.Cond != ISD::SETCC_INVALID) 437 setCmpLibcallCC(LC.Op, LC.Cond); 438 } 439 } 440 } 441 442 if (Subtarget->isTargetWindows()) { 443 static const struct { 444 const RTLIB::Libcall Op; 445 const char * const Name; 446 const CallingConv::ID CC; 447 } LibraryCalls[] = { 448 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 449 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 450 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 451 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 452 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 453 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 454 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 455 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 456 }; 457 458 for (const auto &LC : LibraryCalls) { 459 setLibcallName(LC.Op, LC.Name); 460 setLibcallCallingConv(LC.Op, LC.CC); 461 } 462 } 463 464 // Use divmod compiler-rt calls for iOS 5.0 and later. 465 if (Subtarget->isTargetMachO() && 466 !(Subtarget->isTargetIOS() && 467 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 468 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 469 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 470 } 471 472 // The half <-> float conversion functions are always soft-float on 473 // non-watchos platforms, but are needed for some targets which use a 474 // hard-float calling convention by default. 475 if (!Subtarget->isTargetWatchABI()) { 476 if (Subtarget->isAAPCS_ABI()) { 477 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 478 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 479 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 480 } else { 481 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 482 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 483 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 484 } 485 } 486 487 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 488 // a __gnu_ prefix (which is the default). 489 if (Subtarget->isTargetAEABI()) { 490 static const struct { 491 const RTLIB::Libcall Op; 492 const char * const Name; 493 const CallingConv::ID CC; 494 } LibraryCalls[] = { 495 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 496 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 497 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 498 }; 499 500 for (const auto &LC : LibraryCalls) { 501 setLibcallName(LC.Op, LC.Name); 502 setLibcallCallingConv(LC.Op, LC.CC); 503 } 504 } 505 506 if (Subtarget->isThumb1Only()) 507 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 508 else 509 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 510 511 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 512 !Subtarget->isThumb1Only()) { 513 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 514 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 515 } 516 517 if (Subtarget->hasFullFP16()) { 518 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 519 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 520 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 521 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 522 523 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 524 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 525 } 526 527 for (MVT VT : MVT::vector_valuetypes()) { 528 for (MVT InnerVT : MVT::vector_valuetypes()) { 529 setTruncStoreAction(VT, InnerVT, Expand); 530 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 531 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 532 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 533 } 534 535 setOperationAction(ISD::MULHS, VT, Expand); 536 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 537 setOperationAction(ISD::MULHU, VT, Expand); 538 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 539 540 setOperationAction(ISD::BSWAP, VT, Expand); 541 } 542 543 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 544 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 545 546 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 547 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 548 549 if (Subtarget->hasNEON()) { 550 addDRTypeForNEON(MVT::v2f32); 551 addDRTypeForNEON(MVT::v8i8); 552 addDRTypeForNEON(MVT::v4i16); 553 addDRTypeForNEON(MVT::v2i32); 554 addDRTypeForNEON(MVT::v1i64); 555 556 addQRTypeForNEON(MVT::v4f32); 557 addQRTypeForNEON(MVT::v2f64); 558 addQRTypeForNEON(MVT::v16i8); 559 addQRTypeForNEON(MVT::v8i16); 560 addQRTypeForNEON(MVT::v4i32); 561 addQRTypeForNEON(MVT::v2i64); 562 563 if (Subtarget->hasFullFP16()) { 564 addQRTypeForNEON(MVT::v8f16); 565 addDRTypeForNEON(MVT::v4f16); 566 } 567 568 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 569 // neither Neon nor VFP support any arithmetic operations on it. 570 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 571 // supported for v4f32. 572 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 573 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 574 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 575 // FIXME: Code duplication: FDIV and FREM are expanded always, see 576 // ARMTargetLowering::addTypeForNEON method for details. 577 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 578 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 579 // FIXME: Create unittest. 580 // In another words, find a way when "copysign" appears in DAG with vector 581 // operands. 582 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 583 // FIXME: Code duplication: SETCC has custom operation action, see 584 // ARMTargetLowering::addTypeForNEON method for details. 585 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 586 // FIXME: Create unittest for FNEG and for FABS. 587 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 588 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 589 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 590 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 591 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 592 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 593 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 594 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 595 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 596 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 597 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 598 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 599 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 600 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 601 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 602 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 603 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 604 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 605 606 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 607 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 608 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 609 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 610 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 611 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 612 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 613 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 614 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 615 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 616 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 617 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 618 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 619 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 620 621 // Mark v2f32 intrinsics. 622 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 623 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 624 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 625 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 626 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 627 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 628 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 629 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 630 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 631 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 632 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 633 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 634 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 635 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 636 637 // Neon does not support some operations on v1i64 and v2i64 types. 638 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 639 // Custom handling for some quad-vector types to detect VMULL. 640 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 641 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 642 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 643 // Custom handling for some vector types to avoid expensive expansions 644 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 645 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 646 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 647 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 648 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 649 // a destination type that is wider than the source, and nor does 650 // it have a FP_TO_[SU]INT instruction with a narrower destination than 651 // source. 652 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 653 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 654 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 655 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 656 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 657 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 658 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 659 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 660 661 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 662 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 663 664 // NEON does not have single instruction CTPOP for vectors with element 665 // types wider than 8-bits. However, custom lowering can leverage the 666 // v8i8/v16i8 vcnt instruction. 667 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 668 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 669 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 670 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 671 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 672 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 673 674 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 675 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 676 677 // NEON does not have single instruction CTTZ for vectors. 678 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 679 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 680 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 681 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 682 683 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 684 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 685 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 686 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 687 688 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 690 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 691 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 692 693 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 694 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 695 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 696 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 697 698 // NEON only has FMA instructions as of VFP4. 699 if (!Subtarget->hasVFP4()) { 700 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 701 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 702 } 703 704 setTargetDAGCombine(ISD::INTRINSIC_VOID); 705 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 706 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 707 setTargetDAGCombine(ISD::SHL); 708 setTargetDAGCombine(ISD::SRL); 709 setTargetDAGCombine(ISD::SRA); 710 setTargetDAGCombine(ISD::SIGN_EXTEND); 711 setTargetDAGCombine(ISD::ZERO_EXTEND); 712 setTargetDAGCombine(ISD::ANY_EXTEND); 713 setTargetDAGCombine(ISD::BUILD_VECTOR); 714 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 715 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 716 setTargetDAGCombine(ISD::STORE); 717 setTargetDAGCombine(ISD::FP_TO_SINT); 718 setTargetDAGCombine(ISD::FP_TO_UINT); 719 setTargetDAGCombine(ISD::FDIV); 720 setTargetDAGCombine(ISD::LOAD); 721 722 // It is legal to extload from v4i8 to v4i16 or v4i32. 723 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 724 MVT::v2i32}) { 725 for (MVT VT : MVT::integer_vector_valuetypes()) { 726 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 727 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 728 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 729 } 730 } 731 } 732 733 if (Subtarget->isFPOnlySP()) { 734 // When targeting a floating-point unit with only single-precision 735 // operations, f64 is legal for the few double-precision instructions which 736 // are present However, no double-precision operations other than moves, 737 // loads and stores are provided by the hardware. 738 setOperationAction(ISD::FADD, MVT::f64, Expand); 739 setOperationAction(ISD::FSUB, MVT::f64, Expand); 740 setOperationAction(ISD::FMUL, MVT::f64, Expand); 741 setOperationAction(ISD::FMA, MVT::f64, Expand); 742 setOperationAction(ISD::FDIV, MVT::f64, Expand); 743 setOperationAction(ISD::FREM, MVT::f64, Expand); 744 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 745 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 746 setOperationAction(ISD::FNEG, MVT::f64, Expand); 747 setOperationAction(ISD::FABS, MVT::f64, Expand); 748 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 749 setOperationAction(ISD::FSIN, MVT::f64, Expand); 750 setOperationAction(ISD::FCOS, MVT::f64, Expand); 751 setOperationAction(ISD::FPOW, MVT::f64, Expand); 752 setOperationAction(ISD::FLOG, MVT::f64, Expand); 753 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 754 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 755 setOperationAction(ISD::FEXP, MVT::f64, Expand); 756 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 757 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 758 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 759 setOperationAction(ISD::FRINT, MVT::f64, Expand); 760 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 761 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 762 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 763 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 764 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 765 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 766 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 767 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 768 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 769 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 770 } 771 772 computeRegisterProperties(Subtarget->getRegisterInfo()); 773 774 // ARM does not have floating-point extending loads. 775 for (MVT VT : MVT::fp_valuetypes()) { 776 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 777 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 778 } 779 780 // ... or truncating stores 781 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 782 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 783 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 784 785 // ARM does not have i1 sign extending load. 786 for (MVT VT : MVT::integer_valuetypes()) 787 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 788 789 // ARM supports all 4 flavors of integer indexed load / store. 790 if (!Subtarget->isThumb1Only()) { 791 for (unsigned im = (unsigned)ISD::PRE_INC; 792 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 793 setIndexedLoadAction(im, MVT::i1, Legal); 794 setIndexedLoadAction(im, MVT::i8, Legal); 795 setIndexedLoadAction(im, MVT::i16, Legal); 796 setIndexedLoadAction(im, MVT::i32, Legal); 797 setIndexedStoreAction(im, MVT::i1, Legal); 798 setIndexedStoreAction(im, MVT::i8, Legal); 799 setIndexedStoreAction(im, MVT::i16, Legal); 800 setIndexedStoreAction(im, MVT::i32, Legal); 801 } 802 } else { 803 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 804 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 805 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 806 } 807 808 setOperationAction(ISD::SADDO, MVT::i32, Custom); 809 setOperationAction(ISD::UADDO, MVT::i32, Custom); 810 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 811 setOperationAction(ISD::USUBO, MVT::i32, Custom); 812 813 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 814 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 815 816 // i64 operation support. 817 setOperationAction(ISD::MUL, MVT::i64, Expand); 818 setOperationAction(ISD::MULHU, MVT::i32, Expand); 819 if (Subtarget->isThumb1Only()) { 820 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 821 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 822 } 823 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 824 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 825 setOperationAction(ISD::MULHS, MVT::i32, Expand); 826 827 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 828 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 829 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 830 setOperationAction(ISD::SRL, MVT::i64, Custom); 831 setOperationAction(ISD::SRA, MVT::i64, Custom); 832 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 833 834 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 835 if (Subtarget->isThumb1Only()) { 836 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 837 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 838 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 839 } 840 841 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 842 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 843 844 // ARM does not have ROTL. 845 setOperationAction(ISD::ROTL, MVT::i32, Expand); 846 for (MVT VT : MVT::vector_valuetypes()) { 847 setOperationAction(ISD::ROTL, VT, Expand); 848 setOperationAction(ISD::ROTR, VT, Expand); 849 } 850 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 851 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 852 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 853 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 854 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 855 } 856 857 // @llvm.readcyclecounter requires the Performance Monitors extension. 858 // Default to the 0 expansion on unsupported platforms. 859 // FIXME: Technically there are older ARM CPUs that have 860 // implementation-specific ways of obtaining this information. 861 if (Subtarget->hasPerfMon()) 862 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 863 864 // Only ARMv6 has BSWAP. 865 if (!Subtarget->hasV6Ops()) 866 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 867 868 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 869 : Subtarget->hasDivideInARMMode(); 870 if (!hasDivide) { 871 // These are expanded into libcalls if the cpu doesn't have HW divider. 872 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 873 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 874 } 875 876 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 877 setOperationAction(ISD::SDIV, MVT::i32, Custom); 878 setOperationAction(ISD::UDIV, MVT::i32, Custom); 879 880 setOperationAction(ISD::SDIV, MVT::i64, Custom); 881 setOperationAction(ISD::UDIV, MVT::i64, Custom); 882 } 883 884 setOperationAction(ISD::SREM, MVT::i32, Expand); 885 setOperationAction(ISD::UREM, MVT::i32, Expand); 886 887 // Register based DivRem for AEABI (RTABI 4.2) 888 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 889 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 890 Subtarget->isTargetWindows()) { 891 setOperationAction(ISD::SREM, MVT::i64, Custom); 892 setOperationAction(ISD::UREM, MVT::i64, Custom); 893 HasStandaloneRem = false; 894 895 if (Subtarget->isTargetWindows()) { 896 const struct { 897 const RTLIB::Libcall Op; 898 const char * const Name; 899 const CallingConv::ID CC; 900 } LibraryCalls[] = { 901 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 902 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 903 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 904 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 905 906 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 907 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 908 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 909 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 910 }; 911 912 for (const auto &LC : LibraryCalls) { 913 setLibcallName(LC.Op, LC.Name); 914 setLibcallCallingConv(LC.Op, LC.CC); 915 } 916 } else { 917 const struct { 918 const RTLIB::Libcall Op; 919 const char * const Name; 920 const CallingConv::ID CC; 921 } LibraryCalls[] = { 922 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 923 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 924 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 925 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 926 927 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 928 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 929 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 930 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 931 }; 932 933 for (const auto &LC : LibraryCalls) { 934 setLibcallName(LC.Op, LC.Name); 935 setLibcallCallingConv(LC.Op, LC.CC); 936 } 937 } 938 939 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 940 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 941 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 942 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 943 } else { 944 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 945 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 946 } 947 948 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 949 for (auto &VT : {MVT::f32, MVT::f64}) 950 setOperationAction(ISD::FPOWI, VT, Custom); 951 952 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 953 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 954 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 955 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 956 957 setOperationAction(ISD::TRAP, MVT::Other, Legal); 958 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 959 960 // Use the default implementation. 961 setOperationAction(ISD::VASTART, MVT::Other, Custom); 962 setOperationAction(ISD::VAARG, MVT::Other, Expand); 963 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 964 setOperationAction(ISD::VAEND, MVT::Other, Expand); 965 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 966 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 967 968 if (Subtarget->isTargetWindows()) 969 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 970 else 971 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 972 973 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 974 // the default expansion. 975 InsertFencesForAtomic = false; 976 if (Subtarget->hasAnyDataBarrier() && 977 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 978 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 979 // to ldrex/strex loops already. 980 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 981 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 982 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 983 984 // On v8, we have particularly efficient implementations of atomic fences 985 // if they can be combined with nearby atomic loads and stores. 986 if (!Subtarget->hasAcquireRelease() || 987 getTargetMachine().getOptLevel() == 0) { 988 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 989 InsertFencesForAtomic = true; 990 } 991 } else { 992 // If there's anything we can use as a barrier, go through custom lowering 993 // for ATOMIC_FENCE. 994 // If target has DMB in thumb, Fences can be inserted. 995 if (Subtarget->hasDataBarrier()) 996 InsertFencesForAtomic = true; 997 998 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 999 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1000 1001 // Set them all for expansion, which will force libcalls. 1002 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1003 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1004 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1005 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1006 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1007 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1008 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1009 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1010 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1011 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1012 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1013 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1014 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1015 // Unordered/Monotonic case. 1016 if (!InsertFencesForAtomic) { 1017 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1018 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1019 } 1020 } 1021 1022 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1023 1024 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1025 if (!Subtarget->hasV6Ops()) { 1026 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1027 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1028 } 1029 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1030 1031 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1032 !Subtarget->isThumb1Only()) { 1033 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1034 // iff target supports vfp2. 1035 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1036 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1037 } 1038 1039 // We want to custom lower some of our intrinsics. 1040 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1041 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1042 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1043 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1044 if (Subtarget->useSjLjEH()) 1045 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1046 1047 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1048 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1049 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1050 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1051 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1052 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1053 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1054 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1055 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1056 if (Subtarget->hasFullFP16()) { 1057 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1058 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1059 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1060 } 1061 1062 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1063 1064 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1065 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1066 if (Subtarget->hasFullFP16()) 1067 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1068 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1069 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1070 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1071 1072 // We don't support sin/cos/fmod/copysign/pow 1073 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1074 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1075 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1076 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1077 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1078 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1079 setOperationAction(ISD::FREM, MVT::f64, Expand); 1080 setOperationAction(ISD::FREM, MVT::f32, Expand); 1081 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1082 !Subtarget->isThumb1Only()) { 1083 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1084 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1085 } 1086 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1087 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1088 1089 if (!Subtarget->hasVFP4()) { 1090 setOperationAction(ISD::FMA, MVT::f64, Expand); 1091 setOperationAction(ISD::FMA, MVT::f32, Expand); 1092 } 1093 1094 // Various VFP goodness 1095 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1096 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1097 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1098 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1099 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1100 } 1101 1102 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1103 if (!Subtarget->hasFP16()) { 1104 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1105 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1106 } 1107 } 1108 1109 // Use __sincos_stret if available. 1110 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1111 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1112 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1113 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1114 } 1115 1116 // FP-ARMv8 implements a lot of rounding-like FP operations. 1117 if (Subtarget->hasFPARMv8()) { 1118 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1119 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1120 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1121 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1122 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1123 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1124 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1125 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1126 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1127 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1128 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1129 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1130 1131 if (!Subtarget->isFPOnlySP()) { 1132 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1133 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1134 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1135 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1136 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1137 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1138 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1139 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1140 } 1141 } 1142 1143 if (Subtarget->hasNEON()) { 1144 // vmin and vmax aren't available in a scalar form, so we use 1145 // a NEON instruction with an undef lane instead. 1146 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1147 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1148 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1149 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1150 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1151 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1152 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1153 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1154 1155 if (Subtarget->hasFullFP16()) { 1156 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1157 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1158 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1159 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1160 1161 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1162 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1163 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1164 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1165 } 1166 } 1167 1168 // We have target-specific dag combine patterns for the following nodes: 1169 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1170 setTargetDAGCombine(ISD::ADD); 1171 setTargetDAGCombine(ISD::SUB); 1172 setTargetDAGCombine(ISD::MUL); 1173 setTargetDAGCombine(ISD::AND); 1174 setTargetDAGCombine(ISD::OR); 1175 setTargetDAGCombine(ISD::XOR); 1176 1177 if (Subtarget->hasV6Ops()) 1178 setTargetDAGCombine(ISD::SRL); 1179 if (Subtarget->isThumb1Only()) 1180 setTargetDAGCombine(ISD::SHL); 1181 1182 setStackPointerRegisterToSaveRestore(ARM::SP); 1183 1184 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1185 !Subtarget->hasVFP2()) 1186 setSchedulingPreference(Sched::RegPressure); 1187 else 1188 setSchedulingPreference(Sched::Hybrid); 1189 1190 //// temporary - rewrite interface to use type 1191 MaxStoresPerMemset = 8; 1192 MaxStoresPerMemsetOptSize = 4; 1193 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1194 MaxStoresPerMemcpyOptSize = 2; 1195 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1196 MaxStoresPerMemmoveOptSize = 2; 1197 1198 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1199 // are at least 4 bytes aligned. 1200 setMinStackArgumentAlignment(4); 1201 1202 // Prefer likely predicted branches to selects on out-of-order cores. 1203 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1204 1205 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment()); 1206 1207 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1208 } 1209 1210 bool ARMTargetLowering::useSoftFloat() const { 1211 return Subtarget->useSoftFloat(); 1212 } 1213 1214 // FIXME: It might make sense to define the representative register class as the 1215 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1216 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1217 // SPR's representative would be DPR_VFP2. This should work well if register 1218 // pressure tracking were modified such that a register use would increment the 1219 // pressure of the register class's representative and all of it's super 1220 // classes' representatives transitively. We have not implemented this because 1221 // of the difficulty prior to coalescing of modeling operand register classes 1222 // due to the common occurrence of cross class copies and subregister insertions 1223 // and extractions. 1224 std::pair<const TargetRegisterClass *, uint8_t> 1225 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1226 MVT VT) const { 1227 const TargetRegisterClass *RRC = nullptr; 1228 uint8_t Cost = 1; 1229 switch (VT.SimpleTy) { 1230 default: 1231 return TargetLowering::findRepresentativeClass(TRI, VT); 1232 // Use DPR as representative register class for all floating point 1233 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1234 // the cost is 1 for both f32 and f64. 1235 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1236 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1237 RRC = &ARM::DPRRegClass; 1238 // When NEON is used for SP, only half of the register file is available 1239 // because operations that define both SP and DP results will be constrained 1240 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1241 // coalescing by double-counting the SP regs. See the FIXME above. 1242 if (Subtarget->useNEONForSinglePrecisionFP()) 1243 Cost = 2; 1244 break; 1245 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1246 case MVT::v4f32: case MVT::v2f64: 1247 RRC = &ARM::DPRRegClass; 1248 Cost = 2; 1249 break; 1250 case MVT::v4i64: 1251 RRC = &ARM::DPRRegClass; 1252 Cost = 4; 1253 break; 1254 case MVT::v8i64: 1255 RRC = &ARM::DPRRegClass; 1256 Cost = 8; 1257 break; 1258 } 1259 return std::make_pair(RRC, Cost); 1260 } 1261 1262 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1263 switch ((ARMISD::NodeType)Opcode) { 1264 case ARMISD::FIRST_NUMBER: break; 1265 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1266 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1267 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1268 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1269 case ARMISD::CALL: return "ARMISD::CALL"; 1270 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1271 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1272 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1273 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1274 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1275 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1276 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1277 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1278 case ARMISD::CMP: return "ARMISD::CMP"; 1279 case ARMISD::CMN: return "ARMISD::CMN"; 1280 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1281 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1282 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1283 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1284 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1285 1286 case ARMISD::CMOV: return "ARMISD::CMOV"; 1287 case ARMISD::SUBS: return "ARMISD::SUBS"; 1288 1289 case ARMISD::SSAT: return "ARMISD::SSAT"; 1290 case ARMISD::USAT: return "ARMISD::USAT"; 1291 1292 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1293 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1294 case ARMISD::RRX: return "ARMISD::RRX"; 1295 1296 case ARMISD::ADDC: return "ARMISD::ADDC"; 1297 case ARMISD::ADDE: return "ARMISD::ADDE"; 1298 case ARMISD::SUBC: return "ARMISD::SUBC"; 1299 case ARMISD::SUBE: return "ARMISD::SUBE"; 1300 1301 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1302 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1303 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1304 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1305 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1306 1307 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1308 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1309 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1310 1311 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1312 1313 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1314 1315 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1316 1317 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1318 1319 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1320 1321 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1322 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1323 1324 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1325 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1326 case ARMISD::VCGE: return "ARMISD::VCGE"; 1327 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1328 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1329 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1330 case ARMISD::VCGT: return "ARMISD::VCGT"; 1331 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1332 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1333 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1334 case ARMISD::VTST: return "ARMISD::VTST"; 1335 1336 case ARMISD::VSHL: return "ARMISD::VSHL"; 1337 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1338 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1339 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1340 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1341 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1342 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1343 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1344 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1345 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1346 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1347 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1348 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1349 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1350 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1351 case ARMISD::VSLI: return "ARMISD::VSLI"; 1352 case ARMISD::VSRI: return "ARMISD::VSRI"; 1353 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1354 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1355 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1356 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1357 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1358 case ARMISD::VDUP: return "ARMISD::VDUP"; 1359 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1360 case ARMISD::VEXT: return "ARMISD::VEXT"; 1361 case ARMISD::VREV64: return "ARMISD::VREV64"; 1362 case ARMISD::VREV32: return "ARMISD::VREV32"; 1363 case ARMISD::VREV16: return "ARMISD::VREV16"; 1364 case ARMISD::VZIP: return "ARMISD::VZIP"; 1365 case ARMISD::VUZP: return "ARMISD::VUZP"; 1366 case ARMISD::VTRN: return "ARMISD::VTRN"; 1367 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1368 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1369 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1370 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1371 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1372 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1373 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1374 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1375 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1376 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1377 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1378 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1379 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1380 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1381 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1382 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1383 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1384 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1385 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1386 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1387 case ARMISD::BFI: return "ARMISD::BFI"; 1388 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1389 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1390 case ARMISD::VBSL: return "ARMISD::VBSL"; 1391 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1392 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1393 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1394 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1395 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1396 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1397 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1398 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1399 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1400 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1401 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1402 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1403 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1404 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1405 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1406 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1407 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1408 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1409 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1410 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1411 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1412 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1413 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1414 } 1415 return nullptr; 1416 } 1417 1418 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1419 EVT VT) const { 1420 if (!VT.isVector()) 1421 return getPointerTy(DL); 1422 return VT.changeVectorElementTypeToInteger(); 1423 } 1424 1425 /// getRegClassFor - Return the register class that should be used for the 1426 /// specified value type. 1427 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1428 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1429 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1430 // load / store 4 to 8 consecutive D registers. 1431 if (Subtarget->hasNEON()) { 1432 if (VT == MVT::v4i64) 1433 return &ARM::QQPRRegClass; 1434 if (VT == MVT::v8i64) 1435 return &ARM::QQQQPRRegClass; 1436 } 1437 return TargetLowering::getRegClassFor(VT); 1438 } 1439 1440 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1441 // source/dest is aligned and the copy size is large enough. We therefore want 1442 // to align such objects passed to memory intrinsics. 1443 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1444 unsigned &PrefAlign) const { 1445 if (!isa<MemIntrinsic>(CI)) 1446 return false; 1447 MinSize = 8; 1448 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1449 // cycle faster than 4-byte aligned LDM. 1450 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1451 return true; 1452 } 1453 1454 // Create a fast isel object. 1455 FastISel * 1456 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1457 const TargetLibraryInfo *libInfo) const { 1458 return ARM::createFastISel(funcInfo, libInfo); 1459 } 1460 1461 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1462 unsigned NumVals = N->getNumValues(); 1463 if (!NumVals) 1464 return Sched::RegPressure; 1465 1466 for (unsigned i = 0; i != NumVals; ++i) { 1467 EVT VT = N->getValueType(i); 1468 if (VT == MVT::Glue || VT == MVT::Other) 1469 continue; 1470 if (VT.isFloatingPoint() || VT.isVector()) 1471 return Sched::ILP; 1472 } 1473 1474 if (!N->isMachineOpcode()) 1475 return Sched::RegPressure; 1476 1477 // Load are scheduled for latency even if there instruction itinerary 1478 // is not available. 1479 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1480 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1481 1482 if (MCID.getNumDefs() == 0) 1483 return Sched::RegPressure; 1484 if (!Itins->isEmpty() && 1485 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1486 return Sched::ILP; 1487 1488 return Sched::RegPressure; 1489 } 1490 1491 //===----------------------------------------------------------------------===// 1492 // Lowering Code 1493 //===----------------------------------------------------------------------===// 1494 1495 static bool isSRL16(const SDValue &Op) { 1496 if (Op.getOpcode() != ISD::SRL) 1497 return false; 1498 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1499 return Const->getZExtValue() == 16; 1500 return false; 1501 } 1502 1503 static bool isSRA16(const SDValue &Op) { 1504 if (Op.getOpcode() != ISD::SRA) 1505 return false; 1506 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1507 return Const->getZExtValue() == 16; 1508 return false; 1509 } 1510 1511 static bool isSHL16(const SDValue &Op) { 1512 if (Op.getOpcode() != ISD::SHL) 1513 return false; 1514 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1515 return Const->getZExtValue() == 16; 1516 return false; 1517 } 1518 1519 // Check for a signed 16-bit value. We special case SRA because it makes it 1520 // more simple when also looking for SRAs that aren't sign extending a 1521 // smaller value. Without the check, we'd need to take extra care with 1522 // checking order for some operations. 1523 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1524 if (isSRA16(Op)) 1525 return isSHL16(Op.getOperand(0)); 1526 return DAG.ComputeNumSignBits(Op) == 17; 1527 } 1528 1529 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1530 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1531 switch (CC) { 1532 default: llvm_unreachable("Unknown condition code!"); 1533 case ISD::SETNE: return ARMCC::NE; 1534 case ISD::SETEQ: return ARMCC::EQ; 1535 case ISD::SETGT: return ARMCC::GT; 1536 case ISD::SETGE: return ARMCC::GE; 1537 case ISD::SETLT: return ARMCC::LT; 1538 case ISD::SETLE: return ARMCC::LE; 1539 case ISD::SETUGT: return ARMCC::HI; 1540 case ISD::SETUGE: return ARMCC::HS; 1541 case ISD::SETULT: return ARMCC::LO; 1542 case ISD::SETULE: return ARMCC::LS; 1543 } 1544 } 1545 1546 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1547 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1548 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1549 CondCode2 = ARMCC::AL; 1550 InvalidOnQNaN = true; 1551 switch (CC) { 1552 default: llvm_unreachable("Unknown FP condition!"); 1553 case ISD::SETEQ: 1554 case ISD::SETOEQ: 1555 CondCode = ARMCC::EQ; 1556 InvalidOnQNaN = false; 1557 break; 1558 case ISD::SETGT: 1559 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1560 case ISD::SETGE: 1561 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1562 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1563 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1564 case ISD::SETONE: 1565 CondCode = ARMCC::MI; 1566 CondCode2 = ARMCC::GT; 1567 InvalidOnQNaN = false; 1568 break; 1569 case ISD::SETO: CondCode = ARMCC::VC; break; 1570 case ISD::SETUO: CondCode = ARMCC::VS; break; 1571 case ISD::SETUEQ: 1572 CondCode = ARMCC::EQ; 1573 CondCode2 = ARMCC::VS; 1574 InvalidOnQNaN = false; 1575 break; 1576 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1577 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1578 case ISD::SETLT: 1579 case ISD::SETULT: CondCode = ARMCC::LT; break; 1580 case ISD::SETLE: 1581 case ISD::SETULE: CondCode = ARMCC::LE; break; 1582 case ISD::SETNE: 1583 case ISD::SETUNE: 1584 CondCode = ARMCC::NE; 1585 InvalidOnQNaN = false; 1586 break; 1587 } 1588 } 1589 1590 //===----------------------------------------------------------------------===// 1591 // Calling Convention Implementation 1592 //===----------------------------------------------------------------------===// 1593 1594 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1595 /// account presence of floating point hardware and calling convention 1596 /// limitations, such as support for variadic functions. 1597 CallingConv::ID 1598 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1599 bool isVarArg) const { 1600 switch (CC) { 1601 default: 1602 report_fatal_error("Unsupported calling convention"); 1603 case CallingConv::ARM_AAPCS: 1604 case CallingConv::ARM_APCS: 1605 case CallingConv::GHC: 1606 return CC; 1607 case CallingConv::PreserveMost: 1608 return CallingConv::PreserveMost; 1609 case CallingConv::ARM_AAPCS_VFP: 1610 case CallingConv::Swift: 1611 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1612 case CallingConv::C: 1613 if (!Subtarget->isAAPCS_ABI()) 1614 return CallingConv::ARM_APCS; 1615 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1616 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1617 !isVarArg) 1618 return CallingConv::ARM_AAPCS_VFP; 1619 else 1620 return CallingConv::ARM_AAPCS; 1621 case CallingConv::Fast: 1622 case CallingConv::CXX_FAST_TLS: 1623 if (!Subtarget->isAAPCS_ABI()) { 1624 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1625 return CallingConv::Fast; 1626 return CallingConv::ARM_APCS; 1627 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1628 return CallingConv::ARM_AAPCS_VFP; 1629 else 1630 return CallingConv::ARM_AAPCS; 1631 } 1632 } 1633 1634 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1635 bool isVarArg) const { 1636 return CCAssignFnForNode(CC, false, isVarArg); 1637 } 1638 1639 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1640 bool isVarArg) const { 1641 return CCAssignFnForNode(CC, true, isVarArg); 1642 } 1643 1644 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1645 /// CallingConvention. 1646 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1647 bool Return, 1648 bool isVarArg) const { 1649 switch (getEffectiveCallingConv(CC, isVarArg)) { 1650 default: 1651 report_fatal_error("Unsupported calling convention"); 1652 case CallingConv::ARM_APCS: 1653 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1654 case CallingConv::ARM_AAPCS: 1655 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1656 case CallingConv::ARM_AAPCS_VFP: 1657 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1658 case CallingConv::Fast: 1659 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1660 case CallingConv::GHC: 1661 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1662 case CallingConv::PreserveMost: 1663 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1664 } 1665 } 1666 1667 /// LowerCallResult - Lower the result values of a call into the 1668 /// appropriate copies out of appropriate physical registers. 1669 SDValue ARMTargetLowering::LowerCallResult( 1670 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1671 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1672 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1673 SDValue ThisVal) const { 1674 // Assign locations to each value returned by this call. 1675 SmallVector<CCValAssign, 16> RVLocs; 1676 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1677 *DAG.getContext()); 1678 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1679 1680 // Copy all of the result registers out of their specified physreg. 1681 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1682 CCValAssign VA = RVLocs[i]; 1683 1684 // Pass 'this' value directly from the argument to return value, to avoid 1685 // reg unit interference 1686 if (i == 0 && isThisReturn) { 1687 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1688 "unexpected return calling convention register assignment"); 1689 InVals.push_back(ThisVal); 1690 continue; 1691 } 1692 1693 SDValue Val; 1694 if (VA.needsCustom()) { 1695 // Handle f64 or half of a v2f64. 1696 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1697 InFlag); 1698 Chain = Lo.getValue(1); 1699 InFlag = Lo.getValue(2); 1700 VA = RVLocs[++i]; // skip ahead to next loc 1701 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1702 InFlag); 1703 Chain = Hi.getValue(1); 1704 InFlag = Hi.getValue(2); 1705 if (!Subtarget->isLittle()) 1706 std::swap (Lo, Hi); 1707 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1708 1709 if (VA.getLocVT() == MVT::v2f64) { 1710 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1711 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1712 DAG.getConstant(0, dl, MVT::i32)); 1713 1714 VA = RVLocs[++i]; // skip ahead to next loc 1715 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1716 Chain = Lo.getValue(1); 1717 InFlag = Lo.getValue(2); 1718 VA = RVLocs[++i]; // skip ahead to next loc 1719 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1720 Chain = Hi.getValue(1); 1721 InFlag = Hi.getValue(2); 1722 if (!Subtarget->isLittle()) 1723 std::swap (Lo, Hi); 1724 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1725 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1726 DAG.getConstant(1, dl, MVT::i32)); 1727 } 1728 } else { 1729 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1730 InFlag); 1731 Chain = Val.getValue(1); 1732 InFlag = Val.getValue(2); 1733 } 1734 1735 switch (VA.getLocInfo()) { 1736 default: llvm_unreachable("Unknown loc info!"); 1737 case CCValAssign::Full: break; 1738 case CCValAssign::BCvt: 1739 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1740 break; 1741 } 1742 1743 InVals.push_back(Val); 1744 } 1745 1746 return Chain; 1747 } 1748 1749 /// LowerMemOpCallTo - Store the argument to the stack. 1750 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1751 SDValue Arg, const SDLoc &dl, 1752 SelectionDAG &DAG, 1753 const CCValAssign &VA, 1754 ISD::ArgFlagsTy Flags) const { 1755 unsigned LocMemOffset = VA.getLocMemOffset(); 1756 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1757 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1758 StackPtr, PtrOff); 1759 return DAG.getStore( 1760 Chain, dl, Arg, PtrOff, 1761 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1762 } 1763 1764 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1765 SDValue Chain, SDValue &Arg, 1766 RegsToPassVector &RegsToPass, 1767 CCValAssign &VA, CCValAssign &NextVA, 1768 SDValue &StackPtr, 1769 SmallVectorImpl<SDValue> &MemOpChains, 1770 ISD::ArgFlagsTy Flags) const { 1771 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1772 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1773 unsigned id = Subtarget->isLittle() ? 0 : 1; 1774 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1775 1776 if (NextVA.isRegLoc()) 1777 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1778 else { 1779 assert(NextVA.isMemLoc()); 1780 if (!StackPtr.getNode()) 1781 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1782 getPointerTy(DAG.getDataLayout())); 1783 1784 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1785 dl, DAG, NextVA, 1786 Flags)); 1787 } 1788 } 1789 1790 /// LowerCall - Lowering a call into a callseq_start <- 1791 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1792 /// nodes. 1793 SDValue 1794 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1795 SmallVectorImpl<SDValue> &InVals) const { 1796 SelectionDAG &DAG = CLI.DAG; 1797 SDLoc &dl = CLI.DL; 1798 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1799 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1800 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1801 SDValue Chain = CLI.Chain; 1802 SDValue Callee = CLI.Callee; 1803 bool &isTailCall = CLI.IsTailCall; 1804 CallingConv::ID CallConv = CLI.CallConv; 1805 bool doesNotRet = CLI.DoesNotReturn; 1806 bool isVarArg = CLI.IsVarArg; 1807 1808 MachineFunction &MF = DAG.getMachineFunction(); 1809 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1810 bool isThisReturn = false; 1811 bool isSibCall = false; 1812 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1813 1814 // Disable tail calls if they're not supported. 1815 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1816 isTailCall = false; 1817 1818 if (isTailCall) { 1819 // Check if it's really possible to do a tail call. 1820 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1821 isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(), 1822 Outs, OutVals, Ins, DAG); 1823 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1824 report_fatal_error("failed to perform tail call elimination on a call " 1825 "site marked musttail"); 1826 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1827 // detected sibcalls. 1828 if (isTailCall) { 1829 ++NumTailCalls; 1830 isSibCall = true; 1831 } 1832 } 1833 1834 // Analyze operands of the call, assigning locations to each operand. 1835 SmallVector<CCValAssign, 16> ArgLocs; 1836 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1837 *DAG.getContext()); 1838 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1839 1840 // Get a count of how many bytes are to be pushed on the stack. 1841 unsigned NumBytes = CCInfo.getNextStackOffset(); 1842 1843 // For tail calls, memory operands are available in our caller's stack. 1844 if (isSibCall) 1845 NumBytes = 0; 1846 1847 // Adjust the stack pointer for the new arguments... 1848 // These operations are automatically eliminated by the prolog/epilog pass 1849 if (!isSibCall) 1850 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1851 1852 SDValue StackPtr = 1853 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1854 1855 RegsToPassVector RegsToPass; 1856 SmallVector<SDValue, 8> MemOpChains; 1857 1858 // Walk the register/memloc assignments, inserting copies/loads. In the case 1859 // of tail call optimization, arguments are handled later. 1860 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1861 i != e; 1862 ++i, ++realArgIdx) { 1863 CCValAssign &VA = ArgLocs[i]; 1864 SDValue Arg = OutVals[realArgIdx]; 1865 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1866 bool isByVal = Flags.isByVal(); 1867 1868 // Promote the value if needed. 1869 switch (VA.getLocInfo()) { 1870 default: llvm_unreachable("Unknown loc info!"); 1871 case CCValAssign::Full: break; 1872 case CCValAssign::SExt: 1873 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1874 break; 1875 case CCValAssign::ZExt: 1876 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1877 break; 1878 case CCValAssign::AExt: 1879 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1880 break; 1881 case CCValAssign::BCvt: 1882 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1883 break; 1884 } 1885 1886 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1887 if (VA.needsCustom()) { 1888 if (VA.getLocVT() == MVT::v2f64) { 1889 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1890 DAG.getConstant(0, dl, MVT::i32)); 1891 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1892 DAG.getConstant(1, dl, MVT::i32)); 1893 1894 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1895 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1896 1897 VA = ArgLocs[++i]; // skip ahead to next loc 1898 if (VA.isRegLoc()) { 1899 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1900 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1901 } else { 1902 assert(VA.isMemLoc()); 1903 1904 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1905 dl, DAG, VA, Flags)); 1906 } 1907 } else { 1908 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1909 StackPtr, MemOpChains, Flags); 1910 } 1911 } else if (VA.isRegLoc()) { 1912 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1913 Outs[0].VT == MVT::i32) { 1914 assert(VA.getLocVT() == MVT::i32 && 1915 "unexpected calling convention register assignment"); 1916 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1917 "unexpected use of 'returned'"); 1918 isThisReturn = true; 1919 } 1920 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1921 } else if (isByVal) { 1922 assert(VA.isMemLoc()); 1923 unsigned offset = 0; 1924 1925 // True if this byval aggregate will be split between registers 1926 // and memory. 1927 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1928 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1929 1930 if (CurByValIdx < ByValArgsCount) { 1931 1932 unsigned RegBegin, RegEnd; 1933 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1934 1935 EVT PtrVT = 1936 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1937 unsigned int i, j; 1938 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1939 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1940 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1941 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1942 MachinePointerInfo(), 1943 DAG.InferPtrAlignment(AddArg)); 1944 MemOpChains.push_back(Load.getValue(1)); 1945 RegsToPass.push_back(std::make_pair(j, Load)); 1946 } 1947 1948 // If parameter size outsides register area, "offset" value 1949 // helps us to calculate stack slot for remained part properly. 1950 offset = RegEnd - RegBegin; 1951 1952 CCInfo.nextInRegsParam(); 1953 } 1954 1955 if (Flags.getByValSize() > 4*offset) { 1956 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1957 unsigned LocMemOffset = VA.getLocMemOffset(); 1958 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1959 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1960 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1961 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1962 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1963 MVT::i32); 1964 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1965 MVT::i32); 1966 1967 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1968 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1969 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1970 Ops)); 1971 } 1972 } else if (!isSibCall) { 1973 assert(VA.isMemLoc()); 1974 1975 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1976 dl, DAG, VA, Flags)); 1977 } 1978 } 1979 1980 if (!MemOpChains.empty()) 1981 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1982 1983 // Build a sequence of copy-to-reg nodes chained together with token chain 1984 // and flag operands which copy the outgoing args into the appropriate regs. 1985 SDValue InFlag; 1986 // Tail call byval lowering might overwrite argument registers so in case of 1987 // tail call optimization the copies to registers are lowered later. 1988 if (!isTailCall) 1989 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1990 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1991 RegsToPass[i].second, InFlag); 1992 InFlag = Chain.getValue(1); 1993 } 1994 1995 // For tail calls lower the arguments to the 'real' stack slot. 1996 if (isTailCall) { 1997 // Force all the incoming stack arguments to be loaded from the stack 1998 // before any new outgoing arguments are stored to the stack, because the 1999 // outgoing stack slots may alias the incoming argument stack slots, and 2000 // the alias isn't otherwise explicit. This is slightly more conservative 2001 // than necessary, because it means that each store effectively depends 2002 // on every argument instead of just those arguments it would clobber. 2003 2004 // Do not flag preceding copytoreg stuff together with the following stuff. 2005 InFlag = SDValue(); 2006 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2007 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2008 RegsToPass[i].second, InFlag); 2009 InFlag = Chain.getValue(1); 2010 } 2011 InFlag = SDValue(); 2012 } 2013 2014 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2015 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2016 // node so that legalize doesn't hack it. 2017 bool isDirect = false; 2018 2019 const TargetMachine &TM = getTargetMachine(); 2020 const Module *Mod = MF.getFunction().getParent(); 2021 const GlobalValue *GV = nullptr; 2022 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2023 GV = G->getGlobal(); 2024 bool isStub = 2025 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2026 2027 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2028 bool isLocalARMFunc = false; 2029 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2030 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2031 2032 if (Subtarget->genLongCalls()) { 2033 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2034 "long-calls codegen is not position independent!"); 2035 // Handle a global address or an external symbol. If it's not one of 2036 // those, the target's already in a register, so we don't need to do 2037 // anything extra. 2038 if (isa<GlobalAddressSDNode>(Callee)) { 2039 // Create a constant pool entry for the callee address 2040 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2041 ARMConstantPoolValue *CPV = 2042 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2043 2044 // Get the address of the callee into a register 2045 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2046 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2047 Callee = DAG.getLoad( 2048 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2049 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2050 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2051 const char *Sym = S->getSymbol(); 2052 2053 // Create a constant pool entry for the callee address 2054 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2055 ARMConstantPoolValue *CPV = 2056 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2057 ARMPCLabelIndex, 0); 2058 // Get the address of the callee into a register 2059 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2060 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2061 Callee = DAG.getLoad( 2062 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2063 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2064 } 2065 } else if (isa<GlobalAddressSDNode>(Callee)) { 2066 // If we're optimizing for minimum size and the function is called three or 2067 // more times in this block, we can improve codesize by calling indirectly 2068 // as BLXr has a 16-bit encoding. 2069 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2070 auto *BB = CLI.CS.getParent(); 2071 bool PreferIndirect = 2072 Subtarget->isThumb() && Subtarget->optForMinSize() && 2073 count_if(GV->users(), [&BB](const User *U) { 2074 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2075 }) > 2; 2076 2077 if (!PreferIndirect) { 2078 isDirect = true; 2079 bool isDef = GV->isStrongDefinitionForLinker(); 2080 2081 // ARM call to a local ARM function is predicable. 2082 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2083 // tBX takes a register source operand. 2084 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2085 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2086 Callee = DAG.getNode( 2087 ARMISD::WrapperPIC, dl, PtrVt, 2088 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2089 Callee = DAG.getLoad( 2090 PtrVt, dl, DAG.getEntryNode(), Callee, 2091 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2092 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2093 MachineMemOperand::MOInvariant); 2094 } else if (Subtarget->isTargetCOFF()) { 2095 assert(Subtarget->isTargetWindows() && 2096 "Windows is the only supported COFF target"); 2097 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2098 ? ARMII::MO_DLLIMPORT 2099 : ARMII::MO_NO_FLAG; 2100 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2101 TargetFlags); 2102 if (GV->hasDLLImportStorageClass()) 2103 Callee = 2104 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2105 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2106 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2107 } else { 2108 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2109 } 2110 } 2111 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2112 isDirect = true; 2113 // tBX takes a register source operand. 2114 const char *Sym = S->getSymbol(); 2115 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2116 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2117 ARMConstantPoolValue *CPV = 2118 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2119 ARMPCLabelIndex, 4); 2120 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2121 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2122 Callee = DAG.getLoad( 2123 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2124 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2125 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2126 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2127 } else { 2128 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2129 } 2130 } 2131 2132 // FIXME: handle tail calls differently. 2133 unsigned CallOpc; 2134 if (Subtarget->isThumb()) { 2135 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2136 CallOpc = ARMISD::CALL_NOLINK; 2137 else 2138 CallOpc = ARMISD::CALL; 2139 } else { 2140 if (!isDirect && !Subtarget->hasV5TOps()) 2141 CallOpc = ARMISD::CALL_NOLINK; 2142 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2143 // Emit regular call when code size is the priority 2144 !Subtarget->optForMinSize()) 2145 // "mov lr, pc; b _foo" to avoid confusing the RSP 2146 CallOpc = ARMISD::CALL_NOLINK; 2147 else 2148 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2149 } 2150 2151 std::vector<SDValue> Ops; 2152 Ops.push_back(Chain); 2153 Ops.push_back(Callee); 2154 2155 // Add argument registers to the end of the list so that they are known live 2156 // into the call. 2157 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2158 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2159 RegsToPass[i].second.getValueType())); 2160 2161 // Add a register mask operand representing the call-preserved registers. 2162 if (!isTailCall) { 2163 const uint32_t *Mask; 2164 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2165 if (isThisReturn) { 2166 // For 'this' returns, use the R0-preserving mask if applicable 2167 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2168 if (!Mask) { 2169 // Set isThisReturn to false if the calling convention is not one that 2170 // allows 'returned' to be modeled in this way, so LowerCallResult does 2171 // not try to pass 'this' straight through 2172 isThisReturn = false; 2173 Mask = ARI->getCallPreservedMask(MF, CallConv); 2174 } 2175 } else 2176 Mask = ARI->getCallPreservedMask(MF, CallConv); 2177 2178 assert(Mask && "Missing call preserved mask for calling convention"); 2179 Ops.push_back(DAG.getRegisterMask(Mask)); 2180 } 2181 2182 if (InFlag.getNode()) 2183 Ops.push_back(InFlag); 2184 2185 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2186 if (isTailCall) { 2187 MF.getFrameInfo().setHasTailCall(); 2188 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2189 } 2190 2191 // Returns a chain and a flag for retval copy to use. 2192 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2193 InFlag = Chain.getValue(1); 2194 2195 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2196 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2197 if (!Ins.empty()) 2198 InFlag = Chain.getValue(1); 2199 2200 // Handle result values, copying them out of physregs into vregs that we 2201 // return. 2202 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2203 InVals, isThisReturn, 2204 isThisReturn ? OutVals[0] : SDValue()); 2205 } 2206 2207 /// HandleByVal - Every parameter *after* a byval parameter is passed 2208 /// on the stack. Remember the next parameter register to allocate, 2209 /// and then confiscate the rest of the parameter registers to insure 2210 /// this. 2211 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2212 unsigned Align) const { 2213 // Byval (as with any stack) slots are always at least 4 byte aligned. 2214 Align = std::max(Align, 4U); 2215 2216 unsigned Reg = State->AllocateReg(GPRArgRegs); 2217 if (!Reg) 2218 return; 2219 2220 unsigned AlignInRegs = Align / 4; 2221 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2222 for (unsigned i = 0; i < Waste; ++i) 2223 Reg = State->AllocateReg(GPRArgRegs); 2224 2225 if (!Reg) 2226 return; 2227 2228 unsigned Excess = 4 * (ARM::R4 - Reg); 2229 2230 // Special case when NSAA != SP and parameter size greater than size of 2231 // all remained GPR regs. In that case we can't split parameter, we must 2232 // send it to stack. We also must set NCRN to R4, so waste all 2233 // remained registers. 2234 const unsigned NSAAOffset = State->getNextStackOffset(); 2235 if (NSAAOffset != 0 && Size > Excess) { 2236 while (State->AllocateReg(GPRArgRegs)) 2237 ; 2238 return; 2239 } 2240 2241 // First register for byval parameter is the first register that wasn't 2242 // allocated before this method call, so it would be "reg". 2243 // If parameter is small enough to be saved in range [reg, r4), then 2244 // the end (first after last) register would be reg + param-size-in-regs, 2245 // else parameter would be splitted between registers and stack, 2246 // end register would be r4 in this case. 2247 unsigned ByValRegBegin = Reg; 2248 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2249 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2250 // Note, first register is allocated in the beginning of function already, 2251 // allocate remained amount of registers we need. 2252 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2253 State->AllocateReg(GPRArgRegs); 2254 // A byval parameter that is split between registers and memory needs its 2255 // size truncated here. 2256 // In the case where the entire structure fits in registers, we set the 2257 // size in memory to zero. 2258 Size = std::max<int>(Size - Excess, 0); 2259 } 2260 2261 /// MatchingStackOffset - Return true if the given stack call argument is 2262 /// already available in the same position (relatively) of the caller's 2263 /// incoming argument stack. 2264 static 2265 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2266 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2267 const TargetInstrInfo *TII) { 2268 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2269 int FI = std::numeric_limits<int>::max(); 2270 if (Arg.getOpcode() == ISD::CopyFromReg) { 2271 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2272 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2273 return false; 2274 MachineInstr *Def = MRI->getVRegDef(VR); 2275 if (!Def) 2276 return false; 2277 if (!Flags.isByVal()) { 2278 if (!TII->isLoadFromStackSlot(*Def, FI)) 2279 return false; 2280 } else { 2281 return false; 2282 } 2283 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2284 if (Flags.isByVal()) 2285 // ByVal argument is passed in as a pointer but it's now being 2286 // dereferenced. e.g. 2287 // define @foo(%struct.X* %A) { 2288 // tail call @bar(%struct.X* byval %A) 2289 // } 2290 return false; 2291 SDValue Ptr = Ld->getBasePtr(); 2292 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2293 if (!FINode) 2294 return false; 2295 FI = FINode->getIndex(); 2296 } else 2297 return false; 2298 2299 assert(FI != std::numeric_limits<int>::max()); 2300 if (!MFI.isFixedObjectIndex(FI)) 2301 return false; 2302 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2303 } 2304 2305 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2306 /// for tail call optimization. Targets which want to do tail call 2307 /// optimization should implement this function. 2308 bool 2309 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2310 CallingConv::ID CalleeCC, 2311 bool isVarArg, 2312 bool isCalleeStructRet, 2313 bool isCallerStructRet, 2314 const SmallVectorImpl<ISD::OutputArg> &Outs, 2315 const SmallVectorImpl<SDValue> &OutVals, 2316 const SmallVectorImpl<ISD::InputArg> &Ins, 2317 SelectionDAG& DAG) const { 2318 MachineFunction &MF = DAG.getMachineFunction(); 2319 const Function &CallerF = MF.getFunction(); 2320 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2321 2322 assert(Subtarget->supportsTailCall()); 2323 2324 // Tail calls to function pointers cannot be optimized for Thumb1 if the args 2325 // to the call take up r0-r3. The reason is that there are no legal registers 2326 // left to hold the pointer to the function to be called. 2327 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2328 !isa<GlobalAddressSDNode>(Callee.getNode())) 2329 return false; 2330 2331 // Look for obvious safe cases to perform tail call optimization that do not 2332 // require ABI changes. This is what gcc calls sibcall. 2333 2334 // Exception-handling functions need a special set of instructions to indicate 2335 // a return to the hardware. Tail-calling another function would probably 2336 // break this. 2337 if (CallerF.hasFnAttribute("interrupt")) 2338 return false; 2339 2340 // Also avoid sibcall optimization if either caller or callee uses struct 2341 // return semantics. 2342 if (isCalleeStructRet || isCallerStructRet) 2343 return false; 2344 2345 // Externally-defined functions with weak linkage should not be 2346 // tail-called on ARM when the OS does not support dynamic 2347 // pre-emption of symbols, as the AAELF spec requires normal calls 2348 // to undefined weak functions to be replaced with a NOP or jump to the 2349 // next instruction. The behaviour of branch instructions in this 2350 // situation (as used for tail calls) is implementation-defined, so we 2351 // cannot rely on the linker replacing the tail call with a return. 2352 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2353 const GlobalValue *GV = G->getGlobal(); 2354 const Triple &TT = getTargetMachine().getTargetTriple(); 2355 if (GV->hasExternalWeakLinkage() && 2356 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2357 return false; 2358 } 2359 2360 // Check that the call results are passed in the same way. 2361 LLVMContext &C = *DAG.getContext(); 2362 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2363 CCAssignFnForReturn(CalleeCC, isVarArg), 2364 CCAssignFnForReturn(CallerCC, isVarArg))) 2365 return false; 2366 // The callee has to preserve all registers the caller needs to preserve. 2367 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2368 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2369 if (CalleeCC != CallerCC) { 2370 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2371 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2372 return false; 2373 } 2374 2375 // If Caller's vararg or byval argument has been split between registers and 2376 // stack, do not perform tail call, since part of the argument is in caller's 2377 // local frame. 2378 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2379 if (AFI_Caller->getArgRegsSaveSize()) 2380 return false; 2381 2382 // If the callee takes no arguments then go on to check the results of the 2383 // call. 2384 if (!Outs.empty()) { 2385 // Check if stack adjustment is needed. For now, do not do this if any 2386 // argument is passed on the stack. 2387 SmallVector<CCValAssign, 16> ArgLocs; 2388 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2389 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2390 if (CCInfo.getNextStackOffset()) { 2391 // Check if the arguments are already laid out in the right way as 2392 // the caller's fixed stack objects. 2393 MachineFrameInfo &MFI = MF.getFrameInfo(); 2394 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2395 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2396 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2397 i != e; 2398 ++i, ++realArgIdx) { 2399 CCValAssign &VA = ArgLocs[i]; 2400 EVT RegVT = VA.getLocVT(); 2401 SDValue Arg = OutVals[realArgIdx]; 2402 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2403 if (VA.getLocInfo() == CCValAssign::Indirect) 2404 return false; 2405 if (VA.needsCustom()) { 2406 // f64 and vector types are split into multiple registers or 2407 // register/stack-slot combinations. The types will not match 2408 // the registers; give up on memory f64 refs until we figure 2409 // out what to do about this. 2410 if (!VA.isRegLoc()) 2411 return false; 2412 if (!ArgLocs[++i].isRegLoc()) 2413 return false; 2414 if (RegVT == MVT::v2f64) { 2415 if (!ArgLocs[++i].isRegLoc()) 2416 return false; 2417 if (!ArgLocs[++i].isRegLoc()) 2418 return false; 2419 } 2420 } else if (!VA.isRegLoc()) { 2421 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2422 MFI, MRI, TII)) 2423 return false; 2424 } 2425 } 2426 } 2427 2428 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2429 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2430 return false; 2431 } 2432 2433 return true; 2434 } 2435 2436 bool 2437 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2438 MachineFunction &MF, bool isVarArg, 2439 const SmallVectorImpl<ISD::OutputArg> &Outs, 2440 LLVMContext &Context) const { 2441 SmallVector<CCValAssign, 16> RVLocs; 2442 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2443 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2444 } 2445 2446 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2447 const SDLoc &DL, SelectionDAG &DAG) { 2448 const MachineFunction &MF = DAG.getMachineFunction(); 2449 const Function &F = MF.getFunction(); 2450 2451 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2452 2453 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2454 // version of the "preferred return address". These offsets affect the return 2455 // instruction if this is a return from PL1 without hypervisor extensions. 2456 // IRQ/FIQ: +4 "subs pc, lr, #4" 2457 // SWI: 0 "subs pc, lr, #0" 2458 // ABORT: +4 "subs pc, lr, #4" 2459 // UNDEF: +4/+2 "subs pc, lr, #0" 2460 // UNDEF varies depending on where the exception came from ARM or Thumb 2461 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2462 2463 int64_t LROffset; 2464 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2465 IntKind == "ABORT") 2466 LROffset = 4; 2467 else if (IntKind == "SWI" || IntKind == "UNDEF") 2468 LROffset = 0; 2469 else 2470 report_fatal_error("Unsupported interrupt attribute. If present, value " 2471 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2472 2473 RetOps.insert(RetOps.begin() + 1, 2474 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2475 2476 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2477 } 2478 2479 SDValue 2480 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2481 bool isVarArg, 2482 const SmallVectorImpl<ISD::OutputArg> &Outs, 2483 const SmallVectorImpl<SDValue> &OutVals, 2484 const SDLoc &dl, SelectionDAG &DAG) const { 2485 // CCValAssign - represent the assignment of the return value to a location. 2486 SmallVector<CCValAssign, 16> RVLocs; 2487 2488 // CCState - Info about the registers and stack slots. 2489 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2490 *DAG.getContext()); 2491 2492 // Analyze outgoing return values. 2493 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2494 2495 SDValue Flag; 2496 SmallVector<SDValue, 4> RetOps; 2497 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2498 bool isLittleEndian = Subtarget->isLittle(); 2499 2500 MachineFunction &MF = DAG.getMachineFunction(); 2501 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2502 AFI->setReturnRegsCount(RVLocs.size()); 2503 2504 // Copy the result values into the output registers. 2505 for (unsigned i = 0, realRVLocIdx = 0; 2506 i != RVLocs.size(); 2507 ++i, ++realRVLocIdx) { 2508 CCValAssign &VA = RVLocs[i]; 2509 assert(VA.isRegLoc() && "Can only return in registers!"); 2510 2511 SDValue Arg = OutVals[realRVLocIdx]; 2512 bool ReturnF16 = false; 2513 2514 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2515 // Half-precision return values can be returned like this: 2516 // 2517 // t11 f16 = fadd ... 2518 // t12: i16 = bitcast t11 2519 // t13: i32 = zero_extend t12 2520 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2521 // 2522 // to avoid code generation for bitcasts, we simply set Arg to the node 2523 // that produces the f16 value, t11 in this case. 2524 // 2525 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2526 SDValue ZE = Arg.getOperand(0); 2527 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2528 SDValue BC = ZE.getOperand(0); 2529 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2530 Arg = BC.getOperand(0); 2531 ReturnF16 = true; 2532 } 2533 } 2534 } 2535 } 2536 2537 switch (VA.getLocInfo()) { 2538 default: llvm_unreachable("Unknown loc info!"); 2539 case CCValAssign::Full: break; 2540 case CCValAssign::BCvt: 2541 if (!ReturnF16) 2542 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2543 break; 2544 } 2545 2546 if (VA.needsCustom()) { 2547 if (VA.getLocVT() == MVT::v2f64) { 2548 // Extract the first half and return it in two registers. 2549 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2550 DAG.getConstant(0, dl, MVT::i32)); 2551 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2552 DAG.getVTList(MVT::i32, MVT::i32), Half); 2553 2554 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2555 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2556 Flag); 2557 Flag = Chain.getValue(1); 2558 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2559 VA = RVLocs[++i]; // skip ahead to next loc 2560 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2561 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2562 Flag); 2563 Flag = Chain.getValue(1); 2564 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2565 VA = RVLocs[++i]; // skip ahead to next loc 2566 2567 // Extract the 2nd half and fall through to handle it as an f64 value. 2568 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2569 DAG.getConstant(1, dl, MVT::i32)); 2570 } 2571 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2572 // available. 2573 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2574 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2575 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2576 fmrrd.getValue(isLittleEndian ? 0 : 1), 2577 Flag); 2578 Flag = Chain.getValue(1); 2579 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2580 VA = RVLocs[++i]; // skip ahead to next loc 2581 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2582 fmrrd.getValue(isLittleEndian ? 1 : 0), 2583 Flag); 2584 } else 2585 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2586 2587 // Guarantee that all emitted copies are 2588 // stuck together, avoiding something bad. 2589 Flag = Chain.getValue(1); 2590 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2591 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2592 } 2593 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2594 const MCPhysReg *I = 2595 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2596 if (I) { 2597 for (; *I; ++I) { 2598 if (ARM::GPRRegClass.contains(*I)) 2599 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2600 else if (ARM::DPRRegClass.contains(*I)) 2601 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2602 else 2603 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2604 } 2605 } 2606 2607 // Update chain and glue. 2608 RetOps[0] = Chain; 2609 if (Flag.getNode()) 2610 RetOps.push_back(Flag); 2611 2612 // CPUs which aren't M-class use a special sequence to return from 2613 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2614 // though we use "subs pc, lr, #N"). 2615 // 2616 // M-class CPUs actually use a normal return sequence with a special 2617 // (hardware-provided) value in LR, so the normal code path works. 2618 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2619 !Subtarget->isMClass()) { 2620 if (Subtarget->isThumb1Only()) 2621 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2622 return LowerInterruptReturn(RetOps, dl, DAG); 2623 } 2624 2625 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2626 } 2627 2628 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2629 if (N->getNumValues() != 1) 2630 return false; 2631 if (!N->hasNUsesOfValue(1, 0)) 2632 return false; 2633 2634 SDValue TCChain = Chain; 2635 SDNode *Copy = *N->use_begin(); 2636 if (Copy->getOpcode() == ISD::CopyToReg) { 2637 // If the copy has a glue operand, we conservatively assume it isn't safe to 2638 // perform a tail call. 2639 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2640 return false; 2641 TCChain = Copy->getOperand(0); 2642 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2643 SDNode *VMov = Copy; 2644 // f64 returned in a pair of GPRs. 2645 SmallPtrSet<SDNode*, 2> Copies; 2646 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2647 UI != UE; ++UI) { 2648 if (UI->getOpcode() != ISD::CopyToReg) 2649 return false; 2650 Copies.insert(*UI); 2651 } 2652 if (Copies.size() > 2) 2653 return false; 2654 2655 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2656 UI != UE; ++UI) { 2657 SDValue UseChain = UI->getOperand(0); 2658 if (Copies.count(UseChain.getNode())) 2659 // Second CopyToReg 2660 Copy = *UI; 2661 else { 2662 // We are at the top of this chain. 2663 // If the copy has a glue operand, we conservatively assume it 2664 // isn't safe to perform a tail call. 2665 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2666 return false; 2667 // First CopyToReg 2668 TCChain = UseChain; 2669 } 2670 } 2671 } else if (Copy->getOpcode() == ISD::BITCAST) { 2672 // f32 returned in a single GPR. 2673 if (!Copy->hasOneUse()) 2674 return false; 2675 Copy = *Copy->use_begin(); 2676 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2677 return false; 2678 // If the copy has a glue operand, we conservatively assume it isn't safe to 2679 // perform a tail call. 2680 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2681 return false; 2682 TCChain = Copy->getOperand(0); 2683 } else { 2684 return false; 2685 } 2686 2687 bool HasRet = false; 2688 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2689 UI != UE; ++UI) { 2690 if (UI->getOpcode() != ARMISD::RET_FLAG && 2691 UI->getOpcode() != ARMISD::INTRET_FLAG) 2692 return false; 2693 HasRet = true; 2694 } 2695 2696 if (!HasRet) 2697 return false; 2698 2699 Chain = TCChain; 2700 return true; 2701 } 2702 2703 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2704 if (!Subtarget->supportsTailCall()) 2705 return false; 2706 2707 auto Attr = 2708 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2709 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2710 return false; 2711 2712 return true; 2713 } 2714 2715 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2716 // and pass the lower and high parts through. 2717 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2718 SDLoc DL(Op); 2719 SDValue WriteValue = Op->getOperand(2); 2720 2721 // This function is only supposed to be called for i64 type argument. 2722 assert(WriteValue.getValueType() == MVT::i64 2723 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2724 2725 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2726 DAG.getConstant(0, DL, MVT::i32)); 2727 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2728 DAG.getConstant(1, DL, MVT::i32)); 2729 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2730 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2731 } 2732 2733 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2734 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2735 // one of the above mentioned nodes. It has to be wrapped because otherwise 2736 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2737 // be used to form addressing mode. These wrapped nodes will be selected 2738 // into MOVi. 2739 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2740 SelectionDAG &DAG) const { 2741 EVT PtrVT = Op.getValueType(); 2742 // FIXME there is no actual debug info here 2743 SDLoc dl(Op); 2744 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2745 SDValue Res; 2746 2747 // When generating execute-only code Constant Pools must be promoted to the 2748 // global data section. It's a bit ugly that we can't share them across basic 2749 // blocks, but this way we guarantee that execute-only behaves correct with 2750 // position-independent addressing modes. 2751 if (Subtarget->genExecuteOnly()) { 2752 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2753 auto T = const_cast<Type*>(CP->getType()); 2754 auto C = const_cast<Constant*>(CP->getConstVal()); 2755 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2756 getFunction().getParent()); 2757 auto GV = new GlobalVariable( 2758 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2759 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2760 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2761 Twine(AFI->createPICLabelUId()) 2762 ); 2763 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2764 dl, PtrVT); 2765 return LowerGlobalAddress(GA, DAG); 2766 } 2767 2768 if (CP->isMachineConstantPoolEntry()) 2769 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2770 CP->getAlignment()); 2771 else 2772 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2773 CP->getAlignment()); 2774 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2775 } 2776 2777 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2778 return MachineJumpTableInfo::EK_Inline; 2779 } 2780 2781 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2782 SelectionDAG &DAG) const { 2783 MachineFunction &MF = DAG.getMachineFunction(); 2784 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2785 unsigned ARMPCLabelIndex = 0; 2786 SDLoc DL(Op); 2787 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2788 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2789 SDValue CPAddr; 2790 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2791 if (!IsPositionIndependent) { 2792 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2793 } else { 2794 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2795 ARMPCLabelIndex = AFI->createPICLabelUId(); 2796 ARMConstantPoolValue *CPV = 2797 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2798 ARMCP::CPBlockAddress, PCAdj); 2799 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2800 } 2801 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2802 SDValue Result = DAG.getLoad( 2803 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2804 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2805 if (!IsPositionIndependent) 2806 return Result; 2807 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2808 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2809 } 2810 2811 /// Convert a TLS address reference into the correct sequence of loads 2812 /// and calls to compute the variable's address for Darwin, and return an 2813 /// SDValue containing the final node. 2814 2815 /// Darwin only has one TLS scheme which must be capable of dealing with the 2816 /// fully general situation, in the worst case. This means: 2817 /// + "extern __thread" declaration. 2818 /// + Defined in a possibly unknown dynamic library. 2819 /// 2820 /// The general system is that each __thread variable has a [3 x i32] descriptor 2821 /// which contains information used by the runtime to calculate the address. The 2822 /// only part of this the compiler needs to know about is the first word, which 2823 /// contains a function pointer that must be called with the address of the 2824 /// entire descriptor in "r0". 2825 /// 2826 /// Since this descriptor may be in a different unit, in general access must 2827 /// proceed along the usual ARM rules. A common sequence to produce is: 2828 /// 2829 /// movw rT1, :lower16:_var$non_lazy_ptr 2830 /// movt rT1, :upper16:_var$non_lazy_ptr 2831 /// ldr r0, [rT1] 2832 /// ldr rT2, [r0] 2833 /// blx rT2 2834 /// [...address now in r0...] 2835 SDValue 2836 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2837 SelectionDAG &DAG) const { 2838 assert(Subtarget->isTargetDarwin() && 2839 "This function expects a Darwin target"); 2840 SDLoc DL(Op); 2841 2842 // First step is to get the address of the actua global symbol. This is where 2843 // the TLS descriptor lives. 2844 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2845 2846 // The first entry in the descriptor is a function pointer that we must call 2847 // to obtain the address of the variable. 2848 SDValue Chain = DAG.getEntryNode(); 2849 SDValue FuncTLVGet = DAG.getLoad( 2850 MVT::i32, DL, Chain, DescAddr, 2851 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2852 /* Alignment = */ 4, 2853 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2854 MachineMemOperand::MOInvariant); 2855 Chain = FuncTLVGet.getValue(1); 2856 2857 MachineFunction &F = DAG.getMachineFunction(); 2858 MachineFrameInfo &MFI = F.getFrameInfo(); 2859 MFI.setAdjustsStack(true); 2860 2861 // TLS calls preserve all registers except those that absolutely must be 2862 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2863 // silly). 2864 auto TRI = 2865 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2866 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2867 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2868 2869 // Finally, we can make the call. This is just a degenerate version of a 2870 // normal AArch64 call node: r0 takes the address of the descriptor, and 2871 // returns the address of the variable in this thread. 2872 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2873 Chain = 2874 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2875 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2876 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2877 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2878 } 2879 2880 SDValue 2881 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2882 SelectionDAG &DAG) const { 2883 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2884 2885 SDValue Chain = DAG.getEntryNode(); 2886 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2887 SDLoc DL(Op); 2888 2889 // Load the current TEB (thread environment block) 2890 SDValue Ops[] = {Chain, 2891 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2892 DAG.getConstant(15, DL, MVT::i32), 2893 DAG.getConstant(0, DL, MVT::i32), 2894 DAG.getConstant(13, DL, MVT::i32), 2895 DAG.getConstant(0, DL, MVT::i32), 2896 DAG.getConstant(2, DL, MVT::i32)}; 2897 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2898 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2899 2900 SDValue TEB = CurrentTEB.getValue(0); 2901 Chain = CurrentTEB.getValue(1); 2902 2903 // Load the ThreadLocalStoragePointer from the TEB 2904 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2905 SDValue TLSArray = 2906 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2907 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2908 2909 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2910 // offset into the TLSArray. 2911 2912 // Load the TLS index from the C runtime 2913 SDValue TLSIndex = 2914 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2915 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2916 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2917 2918 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2919 DAG.getConstant(2, DL, MVT::i32)); 2920 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2921 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2922 MachinePointerInfo()); 2923 2924 // Get the offset of the start of the .tls section (section base) 2925 const auto *GA = cast<GlobalAddressSDNode>(Op); 2926 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2927 SDValue Offset = DAG.getLoad( 2928 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2929 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2930 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2931 2932 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2933 } 2934 2935 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2936 SDValue 2937 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2938 SelectionDAG &DAG) const { 2939 SDLoc dl(GA); 2940 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2941 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2942 MachineFunction &MF = DAG.getMachineFunction(); 2943 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2944 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2945 ARMConstantPoolValue *CPV = 2946 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2947 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2948 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2949 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2950 Argument = DAG.getLoad( 2951 PtrVT, dl, DAG.getEntryNode(), Argument, 2952 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2953 SDValue Chain = Argument.getValue(1); 2954 2955 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2956 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2957 2958 // call __tls_get_addr. 2959 ArgListTy Args; 2960 ArgListEntry Entry; 2961 Entry.Node = Argument; 2962 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2963 Args.push_back(Entry); 2964 2965 // FIXME: is there useful debug info available here? 2966 TargetLowering::CallLoweringInfo CLI(DAG); 2967 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2968 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2969 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2970 2971 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2972 return CallResult.first; 2973 } 2974 2975 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2976 // "local exec" model. 2977 SDValue 2978 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2979 SelectionDAG &DAG, 2980 TLSModel::Model model) const { 2981 const GlobalValue *GV = GA->getGlobal(); 2982 SDLoc dl(GA); 2983 SDValue Offset; 2984 SDValue Chain = DAG.getEntryNode(); 2985 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2986 // Get the Thread Pointer 2987 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2988 2989 if (model == TLSModel::InitialExec) { 2990 MachineFunction &MF = DAG.getMachineFunction(); 2991 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2992 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2993 // Initial exec model. 2994 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2995 ARMConstantPoolValue *CPV = 2996 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2997 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2998 true); 2999 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3000 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3001 Offset = DAG.getLoad( 3002 PtrVT, dl, Chain, Offset, 3003 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3004 Chain = Offset.getValue(1); 3005 3006 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3007 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3008 3009 Offset = DAG.getLoad( 3010 PtrVT, dl, Chain, Offset, 3011 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3012 } else { 3013 // local exec model 3014 assert(model == TLSModel::LocalExec); 3015 ARMConstantPoolValue *CPV = 3016 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3017 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3018 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3019 Offset = DAG.getLoad( 3020 PtrVT, dl, Chain, Offset, 3021 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3022 } 3023 3024 // The address of the thread local variable is the add of the thread 3025 // pointer with the offset of the variable. 3026 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3027 } 3028 3029 SDValue 3030 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3031 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3032 if (DAG.getTarget().useEmulatedTLS()) 3033 return LowerToTLSEmulatedModel(GA, DAG); 3034 3035 if (Subtarget->isTargetDarwin()) 3036 return LowerGlobalTLSAddressDarwin(Op, DAG); 3037 3038 if (Subtarget->isTargetWindows()) 3039 return LowerGlobalTLSAddressWindows(Op, DAG); 3040 3041 // TODO: implement the "local dynamic" model 3042 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3043 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3044 3045 switch (model) { 3046 case TLSModel::GeneralDynamic: 3047 case TLSModel::LocalDynamic: 3048 return LowerToTLSGeneralDynamicModel(GA, DAG); 3049 case TLSModel::InitialExec: 3050 case TLSModel::LocalExec: 3051 return LowerToTLSExecModels(GA, DAG, model); 3052 } 3053 llvm_unreachable("bogus TLS model"); 3054 } 3055 3056 /// Return true if all users of V are within function F, looking through 3057 /// ConstantExprs. 3058 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3059 SmallVector<const User*,4> Worklist; 3060 for (auto *U : V->users()) 3061 Worklist.push_back(U); 3062 while (!Worklist.empty()) { 3063 auto *U = Worklist.pop_back_val(); 3064 if (isa<ConstantExpr>(U)) { 3065 for (auto *UU : U->users()) 3066 Worklist.push_back(UU); 3067 continue; 3068 } 3069 3070 auto *I = dyn_cast<Instruction>(U); 3071 if (!I || I->getParent()->getParent() != F) 3072 return false; 3073 } 3074 return true; 3075 } 3076 3077 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3078 const GlobalValue *GV, SelectionDAG &DAG, 3079 EVT PtrVT, const SDLoc &dl) { 3080 // If we're creating a pool entry for a constant global with unnamed address, 3081 // and the global is small enough, we can emit it inline into the constant pool 3082 // to save ourselves an indirection. 3083 // 3084 // This is a win if the constant is only used in one function (so it doesn't 3085 // need to be duplicated) or duplicating the constant wouldn't increase code 3086 // size (implying the constant is no larger than 4 bytes). 3087 const Function &F = DAG.getMachineFunction().getFunction(); 3088 3089 // We rely on this decision to inline being idemopotent and unrelated to the 3090 // use-site. We know that if we inline a variable at one use site, we'll 3091 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3092 // doesn't know about this optimization, so bail out if it's enabled else 3093 // we could decide to inline here (and thus never emit the GV) but require 3094 // the GV from fast-isel generated code. 3095 if (!EnableConstpoolPromotion || 3096 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3097 return SDValue(); 3098 3099 auto *GVar = dyn_cast<GlobalVariable>(GV); 3100 if (!GVar || !GVar->hasInitializer() || 3101 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3102 !GVar->hasLocalLinkage()) 3103 return SDValue(); 3104 3105 // If we inline a value that contains relocations, we move the relocations 3106 // from .data to .text. This is not allowed in position-independent code. 3107 auto *Init = GVar->getInitializer(); 3108 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3109 Init->needsRelocation()) 3110 return SDValue(); 3111 3112 // The constant islands pass can only really deal with alignment requests 3113 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3114 // any type wanting greater alignment requirements than 4 bytes. We also 3115 // can only promote constants that are multiples of 4 bytes in size or 3116 // are paddable to a multiple of 4. Currently we only try and pad constants 3117 // that are strings for simplicity. 3118 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3119 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3120 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3121 unsigned RequiredPadding = 4 - (Size % 4); 3122 bool PaddingPossible = 3123 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3124 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3125 Size == 0) 3126 return SDValue(); 3127 3128 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3129 MachineFunction &MF = DAG.getMachineFunction(); 3130 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3131 3132 // We can't bloat the constant pool too much, else the ConstantIslands pass 3133 // may fail to converge. If we haven't promoted this global yet (it may have 3134 // multiple uses), and promoting it would increase the constant pool size (Sz 3135 // > 4), ensure we have space to do so up to MaxTotal. 3136 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3137 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3138 ConstpoolPromotionMaxTotal) 3139 return SDValue(); 3140 3141 // This is only valid if all users are in a single function; we can't clone 3142 // the constant in general. The LLVM IR unnamed_addr allows merging 3143 // constants, but not cloning them. 3144 // 3145 // We could potentially allow cloning if we could prove all uses of the 3146 // constant in the current function don't care about the address, like 3147 // printf format strings. But that isn't implemented for now. 3148 if (!allUsersAreInFunction(GVar, &F)) 3149 return SDValue(); 3150 3151 // We're going to inline this global. Pad it out if needed. 3152 if (RequiredPadding != 4) { 3153 StringRef S = CDAInit->getAsString(); 3154 3155 SmallVector<uint8_t,16> V(S.size()); 3156 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3157 while (RequiredPadding--) 3158 V.push_back(0); 3159 Init = ConstantDataArray::get(*DAG.getContext(), V); 3160 } 3161 3162 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3163 SDValue CPAddr = 3164 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3165 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3166 AFI->markGlobalAsPromotedToConstantPool(GVar); 3167 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3168 PaddedSize - 4); 3169 } 3170 ++NumConstpoolPromoted; 3171 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3172 } 3173 3174 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3175 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3176 if (!(GV = GA->getBaseObject())) 3177 return false; 3178 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3179 return V->isConstant(); 3180 return isa<Function>(GV); 3181 } 3182 3183 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3184 SelectionDAG &DAG) const { 3185 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3186 default: llvm_unreachable("unknown object format"); 3187 case Triple::COFF: 3188 return LowerGlobalAddressWindows(Op, DAG); 3189 case Triple::ELF: 3190 return LowerGlobalAddressELF(Op, DAG); 3191 case Triple::MachO: 3192 return LowerGlobalAddressDarwin(Op, DAG); 3193 } 3194 } 3195 3196 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3197 SelectionDAG &DAG) const { 3198 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3199 SDLoc dl(Op); 3200 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3201 const TargetMachine &TM = getTargetMachine(); 3202 bool IsRO = isReadOnly(GV); 3203 3204 // promoteToConstantPool only if not generating XO text section 3205 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3206 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3207 return V; 3208 3209 if (isPositionIndependent()) { 3210 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3211 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3212 UseGOT_PREL ? ARMII::MO_GOT : 0); 3213 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3214 if (UseGOT_PREL) 3215 Result = 3216 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3217 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3218 return Result; 3219 } else if (Subtarget->isROPI() && IsRO) { 3220 // PC-relative. 3221 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3222 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3223 return Result; 3224 } else if (Subtarget->isRWPI() && !IsRO) { 3225 // SB-relative. 3226 SDValue RelAddr; 3227 if (Subtarget->useMovt()) { 3228 ++NumMovwMovt; 3229 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3230 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3231 } else { // use literal pool for address constant 3232 ARMConstantPoolValue *CPV = 3233 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3234 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3235 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3236 RelAddr = DAG.getLoad( 3237 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3238 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3239 } 3240 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3241 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3242 return Result; 3243 } 3244 3245 // If we have T2 ops, we can materialize the address directly via movt/movw 3246 // pair. This is always cheaper. 3247 if (Subtarget->useMovt()) { 3248 ++NumMovwMovt; 3249 // FIXME: Once remat is capable of dealing with instructions with register 3250 // operands, expand this into two nodes. 3251 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3252 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3253 } else { 3254 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3255 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3256 return DAG.getLoad( 3257 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3258 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3259 } 3260 } 3261 3262 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3263 SelectionDAG &DAG) const { 3264 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3265 "ROPI/RWPI not currently supported for Darwin"); 3266 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3267 SDLoc dl(Op); 3268 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3269 3270 if (Subtarget->useMovt()) 3271 ++NumMovwMovt; 3272 3273 // FIXME: Once remat is capable of dealing with instructions with register 3274 // operands, expand this into multiple nodes 3275 unsigned Wrapper = 3276 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3277 3278 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3279 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3280 3281 if (Subtarget->isGVIndirectSymbol(GV)) 3282 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3283 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3284 return Result; 3285 } 3286 3287 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3288 SelectionDAG &DAG) const { 3289 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3290 assert(Subtarget->useMovt() && 3291 "Windows on ARM expects to use movw/movt"); 3292 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3293 "ROPI/RWPI not currently supported for Windows"); 3294 3295 const TargetMachine &TM = getTargetMachine(); 3296 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3297 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3298 if (GV->hasDLLImportStorageClass()) 3299 TargetFlags = ARMII::MO_DLLIMPORT; 3300 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3301 TargetFlags = ARMII::MO_COFFSTUB; 3302 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3303 SDValue Result; 3304 SDLoc DL(Op); 3305 3306 ++NumMovwMovt; 3307 3308 // FIXME: Once remat is capable of dealing with instructions with register 3309 // operands, expand this into two nodes. 3310 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3311 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3312 TargetFlags)); 3313 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3314 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3315 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3316 return Result; 3317 } 3318 3319 SDValue 3320 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3321 SDLoc dl(Op); 3322 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3323 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3324 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3325 Op.getOperand(1), Val); 3326 } 3327 3328 SDValue 3329 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3330 SDLoc dl(Op); 3331 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3332 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3333 } 3334 3335 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3336 SelectionDAG &DAG) const { 3337 SDLoc dl(Op); 3338 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3339 Op.getOperand(0)); 3340 } 3341 3342 SDValue 3343 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3344 const ARMSubtarget *Subtarget) const { 3345 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3346 SDLoc dl(Op); 3347 switch (IntNo) { 3348 default: return SDValue(); // Don't custom lower most intrinsics. 3349 case Intrinsic::thread_pointer: { 3350 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3351 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3352 } 3353 case Intrinsic::eh_sjlj_lsda: { 3354 MachineFunction &MF = DAG.getMachineFunction(); 3355 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3356 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3357 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3358 SDValue CPAddr; 3359 bool IsPositionIndependent = isPositionIndependent(); 3360 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3361 ARMConstantPoolValue *CPV = 3362 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3363 ARMCP::CPLSDA, PCAdj); 3364 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3365 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3366 SDValue Result = DAG.getLoad( 3367 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3368 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3369 3370 if (IsPositionIndependent) { 3371 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3372 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3373 } 3374 return Result; 3375 } 3376 case Intrinsic::arm_neon_vabs: 3377 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3378 Op.getOperand(1)); 3379 case Intrinsic::arm_neon_vmulls: 3380 case Intrinsic::arm_neon_vmullu: { 3381 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3382 ? ARMISD::VMULLs : ARMISD::VMULLu; 3383 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3384 Op.getOperand(1), Op.getOperand(2)); 3385 } 3386 case Intrinsic::arm_neon_vminnm: 3387 case Intrinsic::arm_neon_vmaxnm: { 3388 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3389 ? ISD::FMINNUM : ISD::FMAXNUM; 3390 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3391 Op.getOperand(1), Op.getOperand(2)); 3392 } 3393 case Intrinsic::arm_neon_vminu: 3394 case Intrinsic::arm_neon_vmaxu: { 3395 if (Op.getValueType().isFloatingPoint()) 3396 return SDValue(); 3397 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3398 ? ISD::UMIN : ISD::UMAX; 3399 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3400 Op.getOperand(1), Op.getOperand(2)); 3401 } 3402 case Intrinsic::arm_neon_vmins: 3403 case Intrinsic::arm_neon_vmaxs: { 3404 // v{min,max}s is overloaded between signed integers and floats. 3405 if (!Op.getValueType().isFloatingPoint()) { 3406 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3407 ? ISD::SMIN : ISD::SMAX; 3408 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3409 Op.getOperand(1), Op.getOperand(2)); 3410 } 3411 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3412 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3413 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3414 Op.getOperand(1), Op.getOperand(2)); 3415 } 3416 case Intrinsic::arm_neon_vtbl1: 3417 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3418 Op.getOperand(1), Op.getOperand(2)); 3419 case Intrinsic::arm_neon_vtbl2: 3420 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3421 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3422 } 3423 } 3424 3425 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3426 const ARMSubtarget *Subtarget) { 3427 SDLoc dl(Op); 3428 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3429 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3430 if (SSID == SyncScope::SingleThread) 3431 return Op; 3432 3433 if (!Subtarget->hasDataBarrier()) { 3434 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3435 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3436 // here. 3437 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3438 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3439 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3440 DAG.getConstant(0, dl, MVT::i32)); 3441 } 3442 3443 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3444 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3445 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3446 if (Subtarget->isMClass()) { 3447 // Only a full system barrier exists in the M-class architectures. 3448 Domain = ARM_MB::SY; 3449 } else if (Subtarget->preferISHSTBarriers() && 3450 Ord == AtomicOrdering::Release) { 3451 // Swift happens to implement ISHST barriers in a way that's compatible with 3452 // Release semantics but weaker than ISH so we'd be fools not to use 3453 // it. Beware: other processors probably don't! 3454 Domain = ARM_MB::ISHST; 3455 } 3456 3457 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3458 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3459 DAG.getConstant(Domain, dl, MVT::i32)); 3460 } 3461 3462 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3463 const ARMSubtarget *Subtarget) { 3464 // ARM pre v5TE and Thumb1 does not have preload instructions. 3465 if (!(Subtarget->isThumb2() || 3466 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3467 // Just preserve the chain. 3468 return Op.getOperand(0); 3469 3470 SDLoc dl(Op); 3471 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3472 if (!isRead && 3473 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3474 // ARMv7 with MP extension has PLDW. 3475 return Op.getOperand(0); 3476 3477 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3478 if (Subtarget->isThumb()) { 3479 // Invert the bits. 3480 isRead = ~isRead & 1; 3481 isData = ~isData & 1; 3482 } 3483 3484 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3485 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3486 DAG.getConstant(isData, dl, MVT::i32)); 3487 } 3488 3489 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3490 MachineFunction &MF = DAG.getMachineFunction(); 3491 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3492 3493 // vastart just stores the address of the VarArgsFrameIndex slot into the 3494 // memory location argument. 3495 SDLoc dl(Op); 3496 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3497 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3498 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3499 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3500 MachinePointerInfo(SV)); 3501 } 3502 3503 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3504 CCValAssign &NextVA, 3505 SDValue &Root, 3506 SelectionDAG &DAG, 3507 const SDLoc &dl) const { 3508 MachineFunction &MF = DAG.getMachineFunction(); 3509 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3510 3511 const TargetRegisterClass *RC; 3512 if (AFI->isThumb1OnlyFunction()) 3513 RC = &ARM::tGPRRegClass; 3514 else 3515 RC = &ARM::GPRRegClass; 3516 3517 // Transform the arguments stored in physical registers into virtual ones. 3518 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3519 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3520 3521 SDValue ArgValue2; 3522 if (NextVA.isMemLoc()) { 3523 MachineFrameInfo &MFI = MF.getFrameInfo(); 3524 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3525 3526 // Create load node to retrieve arguments from the stack. 3527 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3528 ArgValue2 = DAG.getLoad( 3529 MVT::i32, dl, Root, FIN, 3530 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3531 } else { 3532 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3533 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3534 } 3535 if (!Subtarget->isLittle()) 3536 std::swap (ArgValue, ArgValue2); 3537 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3538 } 3539 3540 // The remaining GPRs hold either the beginning of variable-argument 3541 // data, or the beginning of an aggregate passed by value (usually 3542 // byval). Either way, we allocate stack slots adjacent to the data 3543 // provided by our caller, and store the unallocated registers there. 3544 // If this is a variadic function, the va_list pointer will begin with 3545 // these values; otherwise, this reassembles a (byval) structure that 3546 // was split between registers and memory. 3547 // Return: The frame index registers were stored into. 3548 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3549 const SDLoc &dl, SDValue &Chain, 3550 const Value *OrigArg, 3551 unsigned InRegsParamRecordIdx, 3552 int ArgOffset, unsigned ArgSize) const { 3553 // Currently, two use-cases possible: 3554 // Case #1. Non-var-args function, and we meet first byval parameter. 3555 // Setup first unallocated register as first byval register; 3556 // eat all remained registers 3557 // (these two actions are performed by HandleByVal method). 3558 // Then, here, we initialize stack frame with 3559 // "store-reg" instructions. 3560 // Case #2. Var-args function, that doesn't contain byval parameters. 3561 // The same: eat all remained unallocated registers, 3562 // initialize stack frame. 3563 3564 MachineFunction &MF = DAG.getMachineFunction(); 3565 MachineFrameInfo &MFI = MF.getFrameInfo(); 3566 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3567 unsigned RBegin, REnd; 3568 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3569 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3570 } else { 3571 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3572 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3573 REnd = ARM::R4; 3574 } 3575 3576 if (REnd != RBegin) 3577 ArgOffset = -4 * (ARM::R4 - RBegin); 3578 3579 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3580 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3581 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3582 3583 SmallVector<SDValue, 4> MemOps; 3584 const TargetRegisterClass *RC = 3585 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3586 3587 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3588 unsigned VReg = MF.addLiveIn(Reg, RC); 3589 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3590 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3591 MachinePointerInfo(OrigArg, 4 * i)); 3592 MemOps.push_back(Store); 3593 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3594 } 3595 3596 if (!MemOps.empty()) 3597 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3598 return FrameIndex; 3599 } 3600 3601 // Setup stack frame, the va_list pointer will start from. 3602 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3603 const SDLoc &dl, SDValue &Chain, 3604 unsigned ArgOffset, 3605 unsigned TotalArgRegsSaveSize, 3606 bool ForceMutable) const { 3607 MachineFunction &MF = DAG.getMachineFunction(); 3608 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3609 3610 // Try to store any remaining integer argument regs 3611 // to their spots on the stack so that they may be loaded by dereferencing 3612 // the result of va_next. 3613 // If there is no regs to be stored, just point address after last 3614 // argument passed via stack. 3615 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3616 CCInfo.getInRegsParamsCount(), 3617 CCInfo.getNextStackOffset(), 4); 3618 AFI->setVarArgsFrameIndex(FrameIndex); 3619 } 3620 3621 SDValue ARMTargetLowering::LowerFormalArguments( 3622 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3623 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3624 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3625 MachineFunction &MF = DAG.getMachineFunction(); 3626 MachineFrameInfo &MFI = MF.getFrameInfo(); 3627 3628 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3629 3630 // Assign locations to all of the incoming arguments. 3631 SmallVector<CCValAssign, 16> ArgLocs; 3632 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3633 *DAG.getContext()); 3634 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3635 3636 SmallVector<SDValue, 16> ArgValues; 3637 SDValue ArgValue; 3638 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3639 unsigned CurArgIdx = 0; 3640 3641 // Initially ArgRegsSaveSize is zero. 3642 // Then we increase this value each time we meet byval parameter. 3643 // We also increase this value in case of varargs function. 3644 AFI->setArgRegsSaveSize(0); 3645 3646 // Calculate the amount of stack space that we need to allocate to store 3647 // byval and variadic arguments that are passed in registers. 3648 // We need to know this before we allocate the first byval or variadic 3649 // argument, as they will be allocated a stack slot below the CFA (Canonical 3650 // Frame Address, the stack pointer at entry to the function). 3651 unsigned ArgRegBegin = ARM::R4; 3652 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3653 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3654 break; 3655 3656 CCValAssign &VA = ArgLocs[i]; 3657 unsigned Index = VA.getValNo(); 3658 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3659 if (!Flags.isByVal()) 3660 continue; 3661 3662 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3663 unsigned RBegin, REnd; 3664 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3665 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3666 3667 CCInfo.nextInRegsParam(); 3668 } 3669 CCInfo.rewindByValRegsInfo(); 3670 3671 int lastInsIndex = -1; 3672 if (isVarArg && MFI.hasVAStart()) { 3673 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3674 if (RegIdx != array_lengthof(GPRArgRegs)) 3675 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3676 } 3677 3678 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3679 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3680 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3681 3682 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3683 CCValAssign &VA = ArgLocs[i]; 3684 if (Ins[VA.getValNo()].isOrigArg()) { 3685 std::advance(CurOrigArg, 3686 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3687 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3688 } 3689 // Arguments stored in registers. 3690 if (VA.isRegLoc()) { 3691 EVT RegVT = VA.getLocVT(); 3692 3693 if (VA.needsCustom()) { 3694 // f64 and vector types are split up into multiple registers or 3695 // combinations of registers and stack slots. 3696 if (VA.getLocVT() == MVT::v2f64) { 3697 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3698 Chain, DAG, dl); 3699 VA = ArgLocs[++i]; // skip ahead to next loc 3700 SDValue ArgValue2; 3701 if (VA.isMemLoc()) { 3702 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3703 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3704 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3705 MachinePointerInfo::getFixedStack( 3706 DAG.getMachineFunction(), FI)); 3707 } else { 3708 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3709 Chain, DAG, dl); 3710 } 3711 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3712 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3713 ArgValue, ArgValue1, 3714 DAG.getIntPtrConstant(0, dl)); 3715 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3716 ArgValue, ArgValue2, 3717 DAG.getIntPtrConstant(1, dl)); 3718 } else 3719 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3720 } else { 3721 const TargetRegisterClass *RC; 3722 3723 3724 if (RegVT == MVT::f16) 3725 RC = &ARM::HPRRegClass; 3726 else if (RegVT == MVT::f32) 3727 RC = &ARM::SPRRegClass; 3728 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3729 RC = &ARM::DPRRegClass; 3730 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3731 RC = &ARM::QPRRegClass; 3732 else if (RegVT == MVT::i32) 3733 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3734 : &ARM::GPRRegClass; 3735 else 3736 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3737 3738 // Transform the arguments in physical registers into virtual ones. 3739 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3740 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3741 } 3742 3743 // If this is an 8 or 16-bit value, it is really passed promoted 3744 // to 32 bits. Insert an assert[sz]ext to capture this, then 3745 // truncate to the right size. 3746 switch (VA.getLocInfo()) { 3747 default: llvm_unreachable("Unknown loc info!"); 3748 case CCValAssign::Full: break; 3749 case CCValAssign::BCvt: 3750 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3751 break; 3752 case CCValAssign::SExt: 3753 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3754 DAG.getValueType(VA.getValVT())); 3755 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3756 break; 3757 case CCValAssign::ZExt: 3758 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3759 DAG.getValueType(VA.getValVT())); 3760 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3761 break; 3762 } 3763 3764 InVals.push_back(ArgValue); 3765 } else { // VA.isRegLoc() 3766 // sanity check 3767 assert(VA.isMemLoc()); 3768 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3769 3770 int index = VA.getValNo(); 3771 3772 // Some Ins[] entries become multiple ArgLoc[] entries. 3773 // Process them only once. 3774 if (index != lastInsIndex) 3775 { 3776 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3777 // FIXME: For now, all byval parameter objects are marked mutable. 3778 // This can be changed with more analysis. 3779 // In case of tail call optimization mark all arguments mutable. 3780 // Since they could be overwritten by lowering of arguments in case of 3781 // a tail call. 3782 if (Flags.isByVal()) { 3783 assert(Ins[index].isOrigArg() && 3784 "Byval arguments cannot be implicit"); 3785 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3786 3787 int FrameIndex = StoreByValRegs( 3788 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3789 VA.getLocMemOffset(), Flags.getByValSize()); 3790 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3791 CCInfo.nextInRegsParam(); 3792 } else { 3793 unsigned FIOffset = VA.getLocMemOffset(); 3794 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3795 FIOffset, true); 3796 3797 // Create load nodes to retrieve arguments from the stack. 3798 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3799 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3800 MachinePointerInfo::getFixedStack( 3801 DAG.getMachineFunction(), FI))); 3802 } 3803 lastInsIndex = index; 3804 } 3805 } 3806 } 3807 3808 // varargs 3809 if (isVarArg && MFI.hasVAStart()) 3810 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3811 CCInfo.getNextStackOffset(), 3812 TotalArgRegsSaveSize); 3813 3814 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3815 3816 return Chain; 3817 } 3818 3819 /// isFloatingPointZero - Return true if this is +0.0. 3820 static bool isFloatingPointZero(SDValue Op) { 3821 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3822 return CFP->getValueAPF().isPosZero(); 3823 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3824 // Maybe this has already been legalized into the constant pool? 3825 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3826 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3827 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3828 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3829 return CFP->getValueAPF().isPosZero(); 3830 } 3831 } else if (Op->getOpcode() == ISD::BITCAST && 3832 Op->getValueType(0) == MVT::f64) { 3833 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3834 // created by LowerConstantFP(). 3835 SDValue BitcastOp = Op->getOperand(0); 3836 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3837 isNullConstant(BitcastOp->getOperand(0))) 3838 return true; 3839 } 3840 return false; 3841 } 3842 3843 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3844 /// the given operands. 3845 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3846 SDValue &ARMcc, SelectionDAG &DAG, 3847 const SDLoc &dl) const { 3848 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3849 unsigned C = RHSC->getZExtValue(); 3850 if (!isLegalICmpImmediate((int32_t)C)) { 3851 // Constant does not fit, try adjusting it by one. 3852 switch (CC) { 3853 default: break; 3854 case ISD::SETLT: 3855 case ISD::SETGE: 3856 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3857 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3858 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3859 } 3860 break; 3861 case ISD::SETULT: 3862 case ISD::SETUGE: 3863 if (C != 0 && isLegalICmpImmediate(C-1)) { 3864 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3865 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3866 } 3867 break; 3868 case ISD::SETLE: 3869 case ISD::SETGT: 3870 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3871 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3872 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3873 } 3874 break; 3875 case ISD::SETULE: 3876 case ISD::SETUGT: 3877 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3878 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3879 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3880 } 3881 break; 3882 } 3883 } 3884 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3885 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3886 // In ARM and Thumb-2, the compare instructions can shift their second 3887 // operand. 3888 CC = ISD::getSetCCSwappedOperands(CC); 3889 std::swap(LHS, RHS); 3890 } 3891 3892 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3893 ARMISD::NodeType CompareType; 3894 switch (CondCode) { 3895 default: 3896 CompareType = ARMISD::CMP; 3897 break; 3898 case ARMCC::EQ: 3899 case ARMCC::NE: 3900 // Uses only Z Flag 3901 CompareType = ARMISD::CMPZ; 3902 break; 3903 } 3904 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3905 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3906 } 3907 3908 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3909 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3910 SelectionDAG &DAG, const SDLoc &dl, 3911 bool InvalidOnQNaN) const { 3912 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3913 SDValue Cmp; 3914 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3915 if (!isFloatingPointZero(RHS)) 3916 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3917 else 3918 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3919 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3920 } 3921 3922 /// duplicateCmp - Glue values can have only one use, so this function 3923 /// duplicates a comparison node. 3924 SDValue 3925 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3926 unsigned Opc = Cmp.getOpcode(); 3927 SDLoc DL(Cmp); 3928 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3929 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3930 3931 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3932 Cmp = Cmp.getOperand(0); 3933 Opc = Cmp.getOpcode(); 3934 if (Opc == ARMISD::CMPFP) 3935 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3936 Cmp.getOperand(1), Cmp.getOperand(2)); 3937 else { 3938 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3939 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3940 Cmp.getOperand(1)); 3941 } 3942 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3943 } 3944 3945 // This function returns three things: the arithmetic computation itself 3946 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 3947 // comparison and the condition code define the case in which the arithmetic 3948 // computation *does not* overflow. 3949 std::pair<SDValue, SDValue> 3950 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3951 SDValue &ARMcc) const { 3952 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3953 3954 SDValue Value, OverflowCmp; 3955 SDValue LHS = Op.getOperand(0); 3956 SDValue RHS = Op.getOperand(1); 3957 SDLoc dl(Op); 3958 3959 // FIXME: We are currently always generating CMPs because we don't support 3960 // generating CMN through the backend. This is not as good as the natural 3961 // CMP case because it causes a register dependency and cannot be folded 3962 // later. 3963 3964 switch (Op.getOpcode()) { 3965 default: 3966 llvm_unreachable("Unknown overflow instruction!"); 3967 case ISD::SADDO: 3968 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3969 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3970 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3971 break; 3972 case ISD::UADDO: 3973 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3974 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 3975 // We do not use it in the USUBO case as Value may not be used. 3976 Value = DAG.getNode(ARMISD::ADDC, dl, 3977 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 3978 .getValue(0); 3979 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3980 break; 3981 case ISD::SSUBO: 3982 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3983 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3984 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3985 break; 3986 case ISD::USUBO: 3987 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3988 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3989 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3990 break; 3991 case ISD::UMULO: 3992 // We generate a UMUL_LOHI and then check if the high word is 0. 3993 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 3994 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 3995 DAG.getVTList(Op.getValueType(), Op.getValueType()), 3996 LHS, RHS); 3997 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 3998 DAG.getConstant(0, dl, MVT::i32)); 3999 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4000 break; 4001 case ISD::SMULO: 4002 // We generate a SMUL_LOHI and then check if all the bits of the high word 4003 // are the same as the sign bit of the low word. 4004 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4005 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4006 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4007 LHS, RHS); 4008 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4009 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4010 Value.getValue(0), 4011 DAG.getConstant(31, dl, MVT::i32))); 4012 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4013 break; 4014 } // switch (...) 4015 4016 return std::make_pair(Value, OverflowCmp); 4017 } 4018 4019 SDValue 4020 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4021 // Let legalize expand this if it isn't a legal type yet. 4022 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4023 return SDValue(); 4024 4025 SDValue Value, OverflowCmp; 4026 SDValue ARMcc; 4027 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4028 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4029 SDLoc dl(Op); 4030 // We use 0 and 1 as false and true values. 4031 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4032 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4033 EVT VT = Op.getValueType(); 4034 4035 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4036 ARMcc, CCR, OverflowCmp); 4037 4038 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4039 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4040 } 4041 4042 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4043 SelectionDAG &DAG) { 4044 SDLoc DL(BoolCarry); 4045 EVT CarryVT = BoolCarry.getValueType(); 4046 4047 // This converts the boolean value carry into the carry flag by doing 4048 // ARMISD::SUBC Carry, 1 4049 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4050 DAG.getVTList(CarryVT, MVT::i32), 4051 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4052 return Carry.getValue(1); 4053 } 4054 4055 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4056 SelectionDAG &DAG) { 4057 SDLoc DL(Flags); 4058 4059 // Now convert the carry flag into a boolean carry. We do this 4060 // using ARMISD:ADDE 0, 0, Carry 4061 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4062 DAG.getConstant(0, DL, MVT::i32), 4063 DAG.getConstant(0, DL, MVT::i32), Flags); 4064 } 4065 4066 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4067 SelectionDAG &DAG) const { 4068 // Let legalize expand this if it isn't a legal type yet. 4069 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4070 return SDValue(); 4071 4072 SDValue LHS = Op.getOperand(0); 4073 SDValue RHS = Op.getOperand(1); 4074 SDLoc dl(Op); 4075 4076 EVT VT = Op.getValueType(); 4077 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4078 SDValue Value; 4079 SDValue Overflow; 4080 switch (Op.getOpcode()) { 4081 default: 4082 llvm_unreachable("Unknown overflow instruction!"); 4083 case ISD::UADDO: 4084 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4085 // Convert the carry flag into a boolean value. 4086 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4087 break; 4088 case ISD::USUBO: { 4089 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4090 // Convert the carry flag into a boolean value. 4091 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4092 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4093 // value. So compute 1 - C. 4094 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4095 DAG.getConstant(1, dl, MVT::i32), Overflow); 4096 break; 4097 } 4098 } 4099 4100 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4101 } 4102 4103 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4104 SDValue Cond = Op.getOperand(0); 4105 SDValue SelectTrue = Op.getOperand(1); 4106 SDValue SelectFalse = Op.getOperand(2); 4107 SDLoc dl(Op); 4108 unsigned Opc = Cond.getOpcode(); 4109 4110 if (Cond.getResNo() == 1 && 4111 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4112 Opc == ISD::USUBO)) { 4113 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4114 return SDValue(); 4115 4116 SDValue Value, OverflowCmp; 4117 SDValue ARMcc; 4118 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4119 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4120 EVT VT = Op.getValueType(); 4121 4122 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4123 OverflowCmp, DAG); 4124 } 4125 4126 // Convert: 4127 // 4128 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4129 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4130 // 4131 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4132 const ConstantSDNode *CMOVTrue = 4133 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4134 const ConstantSDNode *CMOVFalse = 4135 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4136 4137 if (CMOVTrue && CMOVFalse) { 4138 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4139 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4140 4141 SDValue True; 4142 SDValue False; 4143 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4144 True = SelectTrue; 4145 False = SelectFalse; 4146 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4147 True = SelectFalse; 4148 False = SelectTrue; 4149 } 4150 4151 if (True.getNode() && False.getNode()) { 4152 EVT VT = Op.getValueType(); 4153 SDValue ARMcc = Cond.getOperand(2); 4154 SDValue CCR = Cond.getOperand(3); 4155 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4156 assert(True.getValueType() == VT); 4157 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4158 } 4159 } 4160 } 4161 4162 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4163 // undefined bits before doing a full-word comparison with zero. 4164 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4165 DAG.getConstant(1, dl, Cond.getValueType())); 4166 4167 return DAG.getSelectCC(dl, Cond, 4168 DAG.getConstant(0, dl, Cond.getValueType()), 4169 SelectTrue, SelectFalse, ISD::SETNE); 4170 } 4171 4172 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4173 bool &swpCmpOps, bool &swpVselOps) { 4174 // Start by selecting the GE condition code for opcodes that return true for 4175 // 'equality' 4176 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4177 CC == ISD::SETULE) 4178 CondCode = ARMCC::GE; 4179 4180 // and GT for opcodes that return false for 'equality'. 4181 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4182 CC == ISD::SETULT) 4183 CondCode = ARMCC::GT; 4184 4185 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4186 // to swap the compare operands. 4187 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4188 CC == ISD::SETULT) 4189 swpCmpOps = true; 4190 4191 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4192 // If we have an unordered opcode, we need to swap the operands to the VSEL 4193 // instruction (effectively negating the condition). 4194 // 4195 // This also has the effect of swapping which one of 'less' or 'greater' 4196 // returns true, so we also swap the compare operands. It also switches 4197 // whether we return true for 'equality', so we compensate by picking the 4198 // opposite condition code to our original choice. 4199 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4200 CC == ISD::SETUGT) { 4201 swpCmpOps = !swpCmpOps; 4202 swpVselOps = !swpVselOps; 4203 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4204 } 4205 4206 // 'ordered' is 'anything but unordered', so use the VS condition code and 4207 // swap the VSEL operands. 4208 if (CC == ISD::SETO) { 4209 CondCode = ARMCC::VS; 4210 swpVselOps = true; 4211 } 4212 4213 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4214 // code and swap the VSEL operands. 4215 if (CC == ISD::SETUNE) { 4216 CondCode = ARMCC::EQ; 4217 swpVselOps = true; 4218 } 4219 } 4220 4221 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4222 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4223 SDValue Cmp, SelectionDAG &DAG) const { 4224 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4225 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4226 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4227 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4228 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4229 4230 SDValue TrueLow = TrueVal.getValue(0); 4231 SDValue TrueHigh = TrueVal.getValue(1); 4232 SDValue FalseLow = FalseVal.getValue(0); 4233 SDValue FalseHigh = FalseVal.getValue(1); 4234 4235 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4236 ARMcc, CCR, Cmp); 4237 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4238 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4239 4240 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4241 } else { 4242 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4243 Cmp); 4244 } 4245 } 4246 4247 static bool isGTorGE(ISD::CondCode CC) { 4248 return CC == ISD::SETGT || CC == ISD::SETGE; 4249 } 4250 4251 static bool isLTorLE(ISD::CondCode CC) { 4252 return CC == ISD::SETLT || CC == ISD::SETLE; 4253 } 4254 4255 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4256 // All of these conditions (and their <= and >= counterparts) will do: 4257 // x < k ? k : x 4258 // x > k ? x : k 4259 // k < x ? x : k 4260 // k > x ? k : x 4261 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4262 const SDValue TrueVal, const SDValue FalseVal, 4263 const ISD::CondCode CC, const SDValue K) { 4264 return (isGTorGE(CC) && 4265 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4266 (isLTorLE(CC) && 4267 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4268 } 4269 4270 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4271 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4272 const SDValue TrueVal, const SDValue FalseVal, 4273 const ISD::CondCode CC, const SDValue K) { 4274 return (isGTorGE(CC) && 4275 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4276 (isLTorLE(CC) && 4277 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4278 } 4279 4280 // Check if two chained conditionals could be converted into SSAT or USAT. 4281 // 4282 // SSAT can replace a set of two conditional selectors that bound a number to an 4283 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4284 // 4285 // x < -k ? -k : (x > k ? k : x) 4286 // x < -k ? -k : (x < k ? x : k) 4287 // x > -k ? (x > k ? k : x) : -k 4288 // x < k ? (x < -k ? -k : x) : k 4289 // etc. 4290 // 4291 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4292 // a power of 2. 4293 // 4294 // It returns true if the conversion can be done, false otherwise. 4295 // Additionally, the variable is returned in parameter V, the constant in K and 4296 // usat is set to true if the conditional represents an unsigned saturation 4297 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4298 uint64_t &K, bool &usat) { 4299 SDValue LHS1 = Op.getOperand(0); 4300 SDValue RHS1 = Op.getOperand(1); 4301 SDValue TrueVal1 = Op.getOperand(2); 4302 SDValue FalseVal1 = Op.getOperand(3); 4303 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4304 4305 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4306 if (Op2.getOpcode() != ISD::SELECT_CC) 4307 return false; 4308 4309 SDValue LHS2 = Op2.getOperand(0); 4310 SDValue RHS2 = Op2.getOperand(1); 4311 SDValue TrueVal2 = Op2.getOperand(2); 4312 SDValue FalseVal2 = Op2.getOperand(3); 4313 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4314 4315 // Find out which are the constants and which are the variables 4316 // in each conditional 4317 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4318 ? &RHS1 4319 : nullptr; 4320 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4321 ? &RHS2 4322 : nullptr; 4323 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4324 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4325 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4326 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4327 4328 // We must detect cases where the original operations worked with 16- or 4329 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4330 // must work with sign-extended values but the select operations return 4331 // the original non-extended value. 4332 SDValue V2TmpReg = V2Tmp; 4333 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4334 V2TmpReg = V2Tmp->getOperand(0); 4335 4336 // Check that the registers and the constants have the correct values 4337 // in both conditionals 4338 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4339 V2TmpReg != V2) 4340 return false; 4341 4342 // Figure out which conditional is saturating the lower/upper bound. 4343 const SDValue *LowerCheckOp = 4344 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4345 ? &Op 4346 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4347 ? &Op2 4348 : nullptr; 4349 const SDValue *UpperCheckOp = 4350 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4351 ? &Op 4352 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4353 ? &Op2 4354 : nullptr; 4355 4356 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4357 return false; 4358 4359 // Check that the constant in the lower-bound check is 4360 // the opposite of the constant in the upper-bound check 4361 // in 1's complement. 4362 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4363 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4364 int64_t PosVal = std::max(Val1, Val2); 4365 int64_t NegVal = std::min(Val1, Val2); 4366 4367 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4368 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4369 isPowerOf2_64(PosVal + 1)) { 4370 4371 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4372 if (Val1 == ~Val2) 4373 usat = false; 4374 else if (NegVal == 0) 4375 usat = true; 4376 else 4377 return false; 4378 4379 V = V2; 4380 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4381 4382 return true; 4383 } 4384 4385 return false; 4386 } 4387 4388 // Check if a condition of the type x < k ? k : x can be converted into a 4389 // bit operation instead of conditional moves. 4390 // Currently this is allowed given: 4391 // - The conditions and values match up 4392 // - k is 0 or -1 (all ones) 4393 // This function will not check the last condition, thats up to the caller 4394 // It returns true if the transformation can be made, and in such case 4395 // returns x in V, and k in SatK. 4396 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4397 SDValue &SatK) 4398 { 4399 SDValue LHS = Op.getOperand(0); 4400 SDValue RHS = Op.getOperand(1); 4401 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4402 SDValue TrueVal = Op.getOperand(2); 4403 SDValue FalseVal = Op.getOperand(3); 4404 4405 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4406 ? &RHS 4407 : nullptr; 4408 4409 // No constant operation in comparison, early out 4410 if (!K) 4411 return false; 4412 4413 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4414 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4415 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4416 4417 // If the constant on left and right side, or variable on left and right, 4418 // does not match, early out 4419 if (*K != KTmp || V != VTmp) 4420 return false; 4421 4422 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4423 SatK = *K; 4424 return true; 4425 } 4426 4427 return false; 4428 } 4429 4430 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4431 EVT VT = Op.getValueType(); 4432 SDLoc dl(Op); 4433 4434 // Try to convert two saturating conditional selects into a single SSAT 4435 SDValue SatValue; 4436 uint64_t SatConstant; 4437 bool SatUSat; 4438 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4439 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4440 if (SatUSat) 4441 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4442 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4443 else 4444 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4445 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4446 } 4447 4448 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4449 // into more efficient bit operations, which is possible when k is 0 or -1 4450 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4451 // single instructions. On Thumb the shift and the bit operation will be two 4452 // instructions. 4453 // Only allow this transformation on full-width (32-bit) operations 4454 SDValue LowerSatConstant; 4455 if (VT == MVT::i32 && 4456 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4457 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4458 DAG.getConstant(31, dl, VT)); 4459 if (isNullConstant(LowerSatConstant)) { 4460 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4461 DAG.getAllOnesConstant(dl, VT)); 4462 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4463 } else if (isAllOnesConstant(LowerSatConstant)) 4464 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4465 } 4466 4467 SDValue LHS = Op.getOperand(0); 4468 SDValue RHS = Op.getOperand(1); 4469 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4470 SDValue TrueVal = Op.getOperand(2); 4471 SDValue FalseVal = Op.getOperand(3); 4472 4473 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4474 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4475 dl); 4476 4477 // If softenSetCCOperands only returned one value, we should compare it to 4478 // zero. 4479 if (!RHS.getNode()) { 4480 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4481 CC = ISD::SETNE; 4482 } 4483 } 4484 4485 if (LHS.getValueType() == MVT::i32) { 4486 // Try to generate VSEL on ARMv8. 4487 // The VSEL instruction can't use all the usual ARM condition 4488 // codes: it only has two bits to select the condition code, so it's 4489 // constrained to use only GE, GT, VS and EQ. 4490 // 4491 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4492 // swap the operands of the previous compare instruction (effectively 4493 // inverting the compare condition, swapping 'less' and 'greater') and 4494 // sometimes need to swap the operands to the VSEL (which inverts the 4495 // condition in the sense of firing whenever the previous condition didn't) 4496 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4497 TrueVal.getValueType() == MVT::f64)) { 4498 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4499 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4500 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4501 CC = ISD::getSetCCInverse(CC, true); 4502 std::swap(TrueVal, FalseVal); 4503 } 4504 } 4505 4506 SDValue ARMcc; 4507 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4508 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4509 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4510 } 4511 4512 ARMCC::CondCodes CondCode, CondCode2; 4513 bool InvalidOnQNaN; 4514 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4515 4516 // Normalize the fp compare. If RHS is zero we keep it there so we match 4517 // CMPFPw0 instead of CMPFP. 4518 if (Subtarget->hasFPARMv8() && !isFloatingPointZero(RHS) && 4519 (TrueVal.getValueType() == MVT::f16 || 4520 TrueVal.getValueType() == MVT::f32 || 4521 TrueVal.getValueType() == MVT::f64)) { 4522 bool swpCmpOps = false; 4523 bool swpVselOps = false; 4524 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4525 4526 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4527 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4528 if (swpCmpOps) 4529 std::swap(LHS, RHS); 4530 if (swpVselOps) 4531 std::swap(TrueVal, FalseVal); 4532 } 4533 } 4534 4535 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4536 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4537 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4538 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4539 if (CondCode2 != ARMCC::AL) { 4540 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4541 // FIXME: Needs another CMP because flag can have but one use. 4542 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4543 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4544 } 4545 return Result; 4546 } 4547 4548 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4549 /// to morph to an integer compare sequence. 4550 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4551 const ARMSubtarget *Subtarget) { 4552 SDNode *N = Op.getNode(); 4553 if (!N->hasOneUse()) 4554 // Otherwise it requires moving the value from fp to integer registers. 4555 return false; 4556 if (!N->getNumValues()) 4557 return false; 4558 EVT VT = Op.getValueType(); 4559 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4560 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4561 // vmrs are very slow, e.g. cortex-a8. 4562 return false; 4563 4564 if (isFloatingPointZero(Op)) { 4565 SeenZero = true; 4566 return true; 4567 } 4568 return ISD::isNormalLoad(N); 4569 } 4570 4571 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4572 if (isFloatingPointZero(Op)) 4573 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4574 4575 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4576 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4577 Ld->getPointerInfo(), Ld->getAlignment(), 4578 Ld->getMemOperand()->getFlags()); 4579 4580 llvm_unreachable("Unknown VFP cmp argument!"); 4581 } 4582 4583 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4584 SDValue &RetVal1, SDValue &RetVal2) { 4585 SDLoc dl(Op); 4586 4587 if (isFloatingPointZero(Op)) { 4588 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4589 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4590 return; 4591 } 4592 4593 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4594 SDValue Ptr = Ld->getBasePtr(); 4595 RetVal1 = 4596 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4597 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4598 4599 EVT PtrType = Ptr.getValueType(); 4600 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4601 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4602 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4603 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4604 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4605 Ld->getMemOperand()->getFlags()); 4606 return; 4607 } 4608 4609 llvm_unreachable("Unknown VFP cmp argument!"); 4610 } 4611 4612 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4613 /// f32 and even f64 comparisons to integer ones. 4614 SDValue 4615 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4616 SDValue Chain = Op.getOperand(0); 4617 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4618 SDValue LHS = Op.getOperand(2); 4619 SDValue RHS = Op.getOperand(3); 4620 SDValue Dest = Op.getOperand(4); 4621 SDLoc dl(Op); 4622 4623 bool LHSSeenZero = false; 4624 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4625 bool RHSSeenZero = false; 4626 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4627 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4628 // If unsafe fp math optimization is enabled and there are no other uses of 4629 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4630 // to an integer comparison. 4631 if (CC == ISD::SETOEQ) 4632 CC = ISD::SETEQ; 4633 else if (CC == ISD::SETUNE) 4634 CC = ISD::SETNE; 4635 4636 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4637 SDValue ARMcc; 4638 if (LHS.getValueType() == MVT::f32) { 4639 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4640 bitcastf32Toi32(LHS, DAG), Mask); 4641 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4642 bitcastf32Toi32(RHS, DAG), Mask); 4643 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4644 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4645 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4646 Chain, Dest, ARMcc, CCR, Cmp); 4647 } 4648 4649 SDValue LHS1, LHS2; 4650 SDValue RHS1, RHS2; 4651 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4652 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4653 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4654 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4655 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4656 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4657 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4658 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4659 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4660 } 4661 4662 return SDValue(); 4663 } 4664 4665 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4666 SDValue Chain = Op.getOperand(0); 4667 SDValue Cond = Op.getOperand(1); 4668 SDValue Dest = Op.getOperand(2); 4669 SDLoc dl(Op); 4670 4671 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4672 // instruction. 4673 unsigned Opc = Cond.getOpcode(); 4674 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4675 !Subtarget->isThumb1Only(); 4676 if (Cond.getResNo() == 1 && 4677 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4678 Opc == ISD::USUBO || OptimizeMul)) { 4679 // Only lower legal XALUO ops. 4680 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4681 return SDValue(); 4682 4683 // The actual operation with overflow check. 4684 SDValue Value, OverflowCmp; 4685 SDValue ARMcc; 4686 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4687 4688 // Reverse the condition code. 4689 ARMCC::CondCodes CondCode = 4690 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4691 CondCode = ARMCC::getOppositeCondition(CondCode); 4692 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4693 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4694 4695 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4696 OverflowCmp); 4697 } 4698 4699 return SDValue(); 4700 } 4701 4702 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4703 SDValue Chain = Op.getOperand(0); 4704 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4705 SDValue LHS = Op.getOperand(2); 4706 SDValue RHS = Op.getOperand(3); 4707 SDValue Dest = Op.getOperand(4); 4708 SDLoc dl(Op); 4709 4710 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4711 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4712 dl); 4713 4714 // If softenSetCCOperands only returned one value, we should compare it to 4715 // zero. 4716 if (!RHS.getNode()) { 4717 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4718 CC = ISD::SETNE; 4719 } 4720 } 4721 4722 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4723 // instruction. 4724 unsigned Opc = LHS.getOpcode(); 4725 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4726 !Subtarget->isThumb1Only(); 4727 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4728 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4729 Opc == ISD::USUBO || OptimizeMul) && 4730 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4731 // Only lower legal XALUO ops. 4732 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4733 return SDValue(); 4734 4735 // The actual operation with overflow check. 4736 SDValue Value, OverflowCmp; 4737 SDValue ARMcc; 4738 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4739 4740 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4741 // Reverse the condition code. 4742 ARMCC::CondCodes CondCode = 4743 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4744 CondCode = ARMCC::getOppositeCondition(CondCode); 4745 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4746 } 4747 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4748 4749 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4750 OverflowCmp); 4751 } 4752 4753 if (LHS.getValueType() == MVT::i32) { 4754 SDValue ARMcc; 4755 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4756 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4757 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4758 Chain, Dest, ARMcc, CCR, Cmp); 4759 } 4760 4761 if (getTargetMachine().Options.UnsafeFPMath && 4762 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4763 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4764 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4765 return Result; 4766 } 4767 4768 ARMCC::CondCodes CondCode, CondCode2; 4769 bool InvalidOnQNaN; 4770 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4771 4772 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4773 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4774 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4775 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4776 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4777 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4778 if (CondCode2 != ARMCC::AL) { 4779 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4780 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4781 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4782 } 4783 return Res; 4784 } 4785 4786 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4787 SDValue Chain = Op.getOperand(0); 4788 SDValue Table = Op.getOperand(1); 4789 SDValue Index = Op.getOperand(2); 4790 SDLoc dl(Op); 4791 4792 EVT PTy = getPointerTy(DAG.getDataLayout()); 4793 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4794 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4795 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4796 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4797 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4798 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4799 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4800 // which does another jump to the destination. This also makes it easier 4801 // to translate it to TBB / TBH later (Thumb2 only). 4802 // FIXME: This might not work if the function is extremely large. 4803 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4804 Addr, Op.getOperand(2), JTI); 4805 } 4806 if (isPositionIndependent() || Subtarget->isROPI()) { 4807 Addr = 4808 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4809 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4810 Chain = Addr.getValue(1); 4811 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4812 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4813 } else { 4814 Addr = 4815 DAG.getLoad(PTy, dl, Chain, Addr, 4816 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4817 Chain = Addr.getValue(1); 4818 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4819 } 4820 } 4821 4822 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4823 EVT VT = Op.getValueType(); 4824 SDLoc dl(Op); 4825 4826 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4827 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4828 return Op; 4829 return DAG.UnrollVectorOp(Op.getNode()); 4830 } 4831 4832 const bool HasFullFP16 = 4833 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 4834 4835 EVT NewTy; 4836 const EVT OpTy = Op.getOperand(0).getValueType(); 4837 if (OpTy == MVT::v4f32) 4838 NewTy = MVT::v4i32; 4839 else if (OpTy == MVT::v4f16 && HasFullFP16) 4840 NewTy = MVT::v4i16; 4841 else if (OpTy == MVT::v8f16 && HasFullFP16) 4842 NewTy = MVT::v8i16; 4843 else 4844 llvm_unreachable("Invalid type for custom lowering!"); 4845 4846 if (VT != MVT::v4i16 && VT != MVT::v8i16) 4847 return DAG.UnrollVectorOp(Op.getNode()); 4848 4849 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 4850 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4851 } 4852 4853 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4854 EVT VT = Op.getValueType(); 4855 if (VT.isVector()) 4856 return LowerVectorFP_TO_INT(Op, DAG); 4857 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4858 RTLIB::Libcall LC; 4859 if (Op.getOpcode() == ISD::FP_TO_SINT) 4860 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4861 Op.getValueType()); 4862 else 4863 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4864 Op.getValueType()); 4865 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4866 /*isSigned*/ false, SDLoc(Op)).first; 4867 } 4868 4869 return Op; 4870 } 4871 4872 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4873 EVT VT = Op.getValueType(); 4874 SDLoc dl(Op); 4875 4876 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4877 if (VT.getVectorElementType() == MVT::f32) 4878 return Op; 4879 return DAG.UnrollVectorOp(Op.getNode()); 4880 } 4881 4882 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 4883 Op.getOperand(0).getValueType() == MVT::v8i16) && 4884 "Invalid type for custom lowering!"); 4885 4886 const bool HasFullFP16 = 4887 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 4888 4889 EVT DestVecType; 4890 if (VT == MVT::v4f32) 4891 DestVecType = MVT::v4i32; 4892 else if (VT == MVT::v4f16 && HasFullFP16) 4893 DestVecType = MVT::v4i16; 4894 else if (VT == MVT::v8f16 && HasFullFP16) 4895 DestVecType = MVT::v8i16; 4896 else 4897 return DAG.UnrollVectorOp(Op.getNode()); 4898 4899 unsigned CastOpc; 4900 unsigned Opc; 4901 switch (Op.getOpcode()) { 4902 default: llvm_unreachable("Invalid opcode!"); 4903 case ISD::SINT_TO_FP: 4904 CastOpc = ISD::SIGN_EXTEND; 4905 Opc = ISD::SINT_TO_FP; 4906 break; 4907 case ISD::UINT_TO_FP: 4908 CastOpc = ISD::ZERO_EXTEND; 4909 Opc = ISD::UINT_TO_FP; 4910 break; 4911 } 4912 4913 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 4914 return DAG.getNode(Opc, dl, VT, Op); 4915 } 4916 4917 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4918 EVT VT = Op.getValueType(); 4919 if (VT.isVector()) 4920 return LowerVectorINT_TO_FP(Op, DAG); 4921 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4922 RTLIB::Libcall LC; 4923 if (Op.getOpcode() == ISD::SINT_TO_FP) 4924 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4925 Op.getValueType()); 4926 else 4927 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4928 Op.getValueType()); 4929 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4930 /*isSigned*/ false, SDLoc(Op)).first; 4931 } 4932 4933 return Op; 4934 } 4935 4936 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4937 // Implement fcopysign with a fabs and a conditional fneg. 4938 SDValue Tmp0 = Op.getOperand(0); 4939 SDValue Tmp1 = Op.getOperand(1); 4940 SDLoc dl(Op); 4941 EVT VT = Op.getValueType(); 4942 EVT SrcVT = Tmp1.getValueType(); 4943 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4944 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4945 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4946 4947 if (UseNEON) { 4948 // Use VBSL to copy the sign bit. 4949 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4950 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4951 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4952 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4953 if (VT == MVT::f64) 4954 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4955 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4956 DAG.getConstant(32, dl, MVT::i32)); 4957 else /*if (VT == MVT::f32)*/ 4958 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4959 if (SrcVT == MVT::f32) { 4960 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4961 if (VT == MVT::f64) 4962 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4963 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4964 DAG.getConstant(32, dl, MVT::i32)); 4965 } else if (VT == MVT::f32) 4966 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4967 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4968 DAG.getConstant(32, dl, MVT::i32)); 4969 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4970 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4971 4972 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4973 dl, MVT::i32); 4974 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4975 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4976 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4977 4978 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4979 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4980 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4981 if (VT == MVT::f32) { 4982 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4983 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4984 DAG.getConstant(0, dl, MVT::i32)); 4985 } else { 4986 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4987 } 4988 4989 return Res; 4990 } 4991 4992 // Bitcast operand 1 to i32. 4993 if (SrcVT == MVT::f64) 4994 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4995 Tmp1).getValue(1); 4996 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4997 4998 // Or in the signbit with integer operations. 4999 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5000 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5001 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5002 if (VT == MVT::f32) { 5003 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5004 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5005 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5006 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5007 } 5008 5009 // f64: Or the high part with signbit and then combine two parts. 5010 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5011 Tmp0); 5012 SDValue Lo = Tmp0.getValue(0); 5013 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5014 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5015 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5016 } 5017 5018 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5019 MachineFunction &MF = DAG.getMachineFunction(); 5020 MachineFrameInfo &MFI = MF.getFrameInfo(); 5021 MFI.setReturnAddressIsTaken(true); 5022 5023 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5024 return SDValue(); 5025 5026 EVT VT = Op.getValueType(); 5027 SDLoc dl(Op); 5028 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5029 if (Depth) { 5030 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5031 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5032 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5033 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5034 MachinePointerInfo()); 5035 } 5036 5037 // Return LR, which contains the return address. Mark it an implicit live-in. 5038 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5039 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5040 } 5041 5042 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5043 const ARMBaseRegisterInfo &ARI = 5044 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5045 MachineFunction &MF = DAG.getMachineFunction(); 5046 MachineFrameInfo &MFI = MF.getFrameInfo(); 5047 MFI.setFrameAddressIsTaken(true); 5048 5049 EVT VT = Op.getValueType(); 5050 SDLoc dl(Op); // FIXME probably not meaningful 5051 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5052 unsigned FrameReg = ARI.getFrameRegister(MF); 5053 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5054 while (Depth--) 5055 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5056 MachinePointerInfo()); 5057 return FrameAddr; 5058 } 5059 5060 // FIXME? Maybe this could be a TableGen attribute on some registers and 5061 // this table could be generated automatically from RegInfo. 5062 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5063 SelectionDAG &DAG) const { 5064 unsigned Reg = StringSwitch<unsigned>(RegName) 5065 .Case("sp", ARM::SP) 5066 .Default(0); 5067 if (Reg) 5068 return Reg; 5069 report_fatal_error(Twine("Invalid register name \"" 5070 + StringRef(RegName) + "\".")); 5071 } 5072 5073 // Result is 64 bit value so split into two 32 bit values and return as a 5074 // pair of values. 5075 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5076 SelectionDAG &DAG) { 5077 SDLoc DL(N); 5078 5079 // This function is only supposed to be called for i64 type destination. 5080 assert(N->getValueType(0) == MVT::i64 5081 && "ExpandREAD_REGISTER called for non-i64 type result."); 5082 5083 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5084 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5085 N->getOperand(0), 5086 N->getOperand(1)); 5087 5088 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5089 Read.getValue(1))); 5090 Results.push_back(Read.getOperand(0)); 5091 } 5092 5093 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5094 /// When \p DstVT, the destination type of \p BC, is on the vector 5095 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5096 /// it might be possible to combine them, such that everything stays on the 5097 /// vector register bank. 5098 /// \p return The node that would replace \p BT, if the combine 5099 /// is possible. 5100 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5101 SelectionDAG &DAG) { 5102 SDValue Op = BC->getOperand(0); 5103 EVT DstVT = BC->getValueType(0); 5104 5105 // The only vector instruction that can produce a scalar (remember, 5106 // since the bitcast was about to be turned into VMOVDRR, the source 5107 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5108 // Moreover, we can do this combine only if there is one use. 5109 // Finally, if the destination type is not a vector, there is not 5110 // much point on forcing everything on the vector bank. 5111 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5112 !Op.hasOneUse()) 5113 return SDValue(); 5114 5115 // If the index is not constant, we will introduce an additional 5116 // multiply that will stick. 5117 // Give up in that case. 5118 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5119 if (!Index) 5120 return SDValue(); 5121 unsigned DstNumElt = DstVT.getVectorNumElements(); 5122 5123 // Compute the new index. 5124 const APInt &APIntIndex = Index->getAPIntValue(); 5125 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5126 NewIndex *= APIntIndex; 5127 // Check if the new constant index fits into i32. 5128 if (NewIndex.getBitWidth() > 32) 5129 return SDValue(); 5130 5131 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5132 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5133 SDLoc dl(Op); 5134 SDValue ExtractSrc = Op.getOperand(0); 5135 EVT VecVT = EVT::getVectorVT( 5136 *DAG.getContext(), DstVT.getScalarType(), 5137 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5138 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5139 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5140 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5141 } 5142 5143 /// ExpandBITCAST - If the target supports VFP, this function is called to 5144 /// expand a bit convert where either the source or destination type is i64 to 5145 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5146 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5147 /// vectors), since the legalizer won't know what to do with that. 5148 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5149 const ARMSubtarget *Subtarget) { 5150 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5151 SDLoc dl(N); 5152 SDValue Op = N->getOperand(0); 5153 5154 // This function is only supposed to be called for i64 types, either as the 5155 // source or destination of the bit convert. 5156 EVT SrcVT = Op.getValueType(); 5157 EVT DstVT = N->getValueType(0); 5158 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5159 5160 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5161 // FullFP16: half values are passed in S-registers, and we don't 5162 // need any of the bitcast and moves: 5163 // 5164 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5165 // t5: i32 = bitcast t2 5166 // t18: f16 = ARMISD::VMOVhr t5 5167 if (Op.getOpcode() != ISD::CopyFromReg || 5168 Op.getValueType() != MVT::f32) 5169 return SDValue(); 5170 5171 auto Move = N->use_begin(); 5172 if (Move->getOpcode() != ARMISD::VMOVhr) 5173 return SDValue(); 5174 5175 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5176 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5177 DAG.ReplaceAllUsesWith(*Move, &Copy); 5178 return Copy; 5179 } 5180 5181 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5182 if (!HasFullFP16) 5183 return SDValue(); 5184 // SoftFP: read half-precision arguments: 5185 // 5186 // t2: i32,ch = ... 5187 // t7: i16 = truncate t2 <~~~~ Op 5188 // t8: f16 = bitcast t7 <~~~~ N 5189 // 5190 if (Op.getOperand(0).getValueType() == MVT::i32) 5191 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5192 MVT::f16, Op.getOperand(0)); 5193 5194 return SDValue(); 5195 } 5196 5197 // Half-precision return values 5198 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5199 if (!HasFullFP16) 5200 return SDValue(); 5201 // 5202 // t11: f16 = fadd t8, t10 5203 // t12: i16 = bitcast t11 <~~~ SDNode N 5204 // t13: i32 = zero_extend t12 5205 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5206 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5207 // 5208 // transform this into: 5209 // 5210 // t20: i32 = ARMISD::VMOVrh t11 5211 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5212 // 5213 auto ZeroExtend = N->use_begin(); 5214 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5215 ZeroExtend->getValueType(0) != MVT::i32) 5216 return SDValue(); 5217 5218 auto Copy = ZeroExtend->use_begin(); 5219 if (Copy->getOpcode() == ISD::CopyToReg && 5220 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5221 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5222 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5223 return Cvt; 5224 } 5225 return SDValue(); 5226 } 5227 5228 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5229 return SDValue(); 5230 5231 // Turn i64->f64 into VMOVDRR. 5232 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5233 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5234 // if we can combine the bitcast with its source. 5235 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5236 return Val; 5237 5238 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5239 DAG.getConstant(0, dl, MVT::i32)); 5240 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5241 DAG.getConstant(1, dl, MVT::i32)); 5242 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5243 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5244 } 5245 5246 // Turn f64->i64 into VMOVRRD. 5247 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5248 SDValue Cvt; 5249 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5250 SrcVT.getVectorNumElements() > 1) 5251 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5252 DAG.getVTList(MVT::i32, MVT::i32), 5253 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5254 else 5255 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5256 DAG.getVTList(MVT::i32, MVT::i32), Op); 5257 // Merge the pieces into a single i64 value. 5258 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5259 } 5260 5261 return SDValue(); 5262 } 5263 5264 /// getZeroVector - Returns a vector of specified type with all zero elements. 5265 /// Zero vectors are used to represent vector negation and in those cases 5266 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5267 /// not support i64 elements, so sometimes the zero vectors will need to be 5268 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5269 /// zero vector. 5270 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5271 assert(VT.isVector() && "Expected a vector type"); 5272 // The canonical modified immediate encoding of a zero vector is....0! 5273 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5274 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5275 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5276 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5277 } 5278 5279 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5280 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5281 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5282 SelectionDAG &DAG) const { 5283 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5284 EVT VT = Op.getValueType(); 5285 unsigned VTBits = VT.getSizeInBits(); 5286 SDLoc dl(Op); 5287 SDValue ShOpLo = Op.getOperand(0); 5288 SDValue ShOpHi = Op.getOperand(1); 5289 SDValue ShAmt = Op.getOperand(2); 5290 SDValue ARMcc; 5291 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5292 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5293 5294 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5295 5296 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5297 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5298 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5299 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5300 DAG.getConstant(VTBits, dl, MVT::i32)); 5301 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5302 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5303 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5304 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5305 ISD::SETGE, ARMcc, DAG, dl); 5306 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5307 ARMcc, CCR, CmpLo); 5308 5309 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5310 SDValue HiBigShift = Opc == ISD::SRA 5311 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5312 DAG.getConstant(VTBits - 1, dl, VT)) 5313 : DAG.getConstant(0, dl, VT); 5314 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5315 ISD::SETGE, ARMcc, DAG, dl); 5316 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5317 ARMcc, CCR, CmpHi); 5318 5319 SDValue Ops[2] = { Lo, Hi }; 5320 return DAG.getMergeValues(Ops, dl); 5321 } 5322 5323 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5324 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5325 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5326 SelectionDAG &DAG) const { 5327 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5328 EVT VT = Op.getValueType(); 5329 unsigned VTBits = VT.getSizeInBits(); 5330 SDLoc dl(Op); 5331 SDValue ShOpLo = Op.getOperand(0); 5332 SDValue ShOpHi = Op.getOperand(1); 5333 SDValue ShAmt = Op.getOperand(2); 5334 SDValue ARMcc; 5335 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5336 5337 assert(Op.getOpcode() == ISD::SHL_PARTS); 5338 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5339 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5340 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5341 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5342 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5343 5344 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5345 DAG.getConstant(VTBits, dl, MVT::i32)); 5346 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5347 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5348 ISD::SETGE, ARMcc, DAG, dl); 5349 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5350 ARMcc, CCR, CmpHi); 5351 5352 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5353 ISD::SETGE, ARMcc, DAG, dl); 5354 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5355 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5356 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5357 5358 SDValue Ops[2] = { Lo, Hi }; 5359 return DAG.getMergeValues(Ops, dl); 5360 } 5361 5362 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5363 SelectionDAG &DAG) const { 5364 // The rounding mode is in bits 23:22 of the FPSCR. 5365 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5366 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5367 // so that the shift + and get folded into a bitfield extract. 5368 SDLoc dl(Op); 5369 SDValue Ops[] = { DAG.getEntryNode(), 5370 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5371 5372 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5373 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5374 DAG.getConstant(1U << 22, dl, MVT::i32)); 5375 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5376 DAG.getConstant(22, dl, MVT::i32)); 5377 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5378 DAG.getConstant(3, dl, MVT::i32)); 5379 } 5380 5381 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5382 const ARMSubtarget *ST) { 5383 SDLoc dl(N); 5384 EVT VT = N->getValueType(0); 5385 if (VT.isVector()) { 5386 assert(ST->hasNEON()); 5387 5388 // Compute the least significant set bit: LSB = X & -X 5389 SDValue X = N->getOperand(0); 5390 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5391 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5392 5393 EVT ElemTy = VT.getVectorElementType(); 5394 5395 if (ElemTy == MVT::i8) { 5396 // Compute with: cttz(x) = ctpop(lsb - 1) 5397 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5398 DAG.getTargetConstant(1, dl, ElemTy)); 5399 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5400 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5401 } 5402 5403 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5404 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5405 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5406 unsigned NumBits = ElemTy.getSizeInBits(); 5407 SDValue WidthMinus1 = 5408 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5409 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5410 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5411 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5412 } 5413 5414 // Compute with: cttz(x) = ctpop(lsb - 1) 5415 5416 // Compute LSB - 1. 5417 SDValue Bits; 5418 if (ElemTy == MVT::i64) { 5419 // Load constant 0xffff'ffff'ffff'ffff to register. 5420 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5421 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5422 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5423 } else { 5424 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5425 DAG.getTargetConstant(1, dl, ElemTy)); 5426 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5427 } 5428 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5429 } 5430 5431 if (!ST->hasV6T2Ops()) 5432 return SDValue(); 5433 5434 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5435 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5436 } 5437 5438 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5439 const ARMSubtarget *ST) { 5440 EVT VT = N->getValueType(0); 5441 SDLoc DL(N); 5442 5443 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5444 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5445 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5446 "Unexpected type for custom ctpop lowering"); 5447 5448 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5449 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5450 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 5451 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 5452 5453 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5454 unsigned EltSize = 8; 5455 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5456 while (EltSize != VT.getScalarSizeInBits()) { 5457 SmallVector<SDValue, 8> Ops; 5458 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 5459 TLI.getPointerTy(DAG.getDataLayout()))); 5460 Ops.push_back(Res); 5461 5462 EltSize *= 2; 5463 NumElts /= 2; 5464 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5465 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 5466 } 5467 5468 return Res; 5469 } 5470 5471 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5472 const ARMSubtarget *ST) { 5473 EVT VT = N->getValueType(0); 5474 SDLoc dl(N); 5475 5476 if (!VT.isVector()) 5477 return SDValue(); 5478 5479 // Lower vector shifts on NEON to use VSHL. 5480 assert(ST->hasNEON() && "unexpected vector shift"); 5481 5482 // Left shifts translate directly to the vshiftu intrinsic. 5483 if (N->getOpcode() == ISD::SHL) 5484 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5485 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5486 MVT::i32), 5487 N->getOperand(0), N->getOperand(1)); 5488 5489 assert((N->getOpcode() == ISD::SRA || 5490 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5491 5492 // NEON uses the same intrinsics for both left and right shifts. For 5493 // right shifts, the shift amounts are negative, so negate the vector of 5494 // shift amounts. 5495 EVT ShiftVT = N->getOperand(1).getValueType(); 5496 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5497 getZeroVector(ShiftVT, DAG, dl), 5498 N->getOperand(1)); 5499 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5500 Intrinsic::arm_neon_vshifts : 5501 Intrinsic::arm_neon_vshiftu); 5502 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5503 DAG.getConstant(vshiftInt, dl, MVT::i32), 5504 N->getOperand(0), NegatedCount); 5505 } 5506 5507 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5508 const ARMSubtarget *ST) { 5509 EVT VT = N->getValueType(0); 5510 SDLoc dl(N); 5511 5512 // We can get here for a node like i32 = ISD::SHL i32, i64 5513 if (VT != MVT::i64) 5514 return SDValue(); 5515 5516 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5517 "Unknown shift to lower!"); 5518 5519 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5520 if (!isOneConstant(N->getOperand(1))) 5521 return SDValue(); 5522 5523 // If we are in thumb mode, we don't have RRX. 5524 if (ST->isThumb1Only()) return SDValue(); 5525 5526 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5527 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5528 DAG.getConstant(0, dl, MVT::i32)); 5529 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5530 DAG.getConstant(1, dl, MVT::i32)); 5531 5532 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5533 // captures the result into a carry flag. 5534 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5535 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5536 5537 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5538 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5539 5540 // Merge the pieces into a single i64 value. 5541 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5542 } 5543 5544 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5545 SDValue TmpOp0, TmpOp1; 5546 bool Invert = false; 5547 bool Swap = false; 5548 unsigned Opc = 0; 5549 5550 SDValue Op0 = Op.getOperand(0); 5551 SDValue Op1 = Op.getOperand(1); 5552 SDValue CC = Op.getOperand(2); 5553 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5554 EVT VT = Op.getValueType(); 5555 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5556 SDLoc dl(Op); 5557 5558 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5559 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5560 // Special-case integer 64-bit equality comparisons. They aren't legal, 5561 // but they can be lowered with a few vector instructions. 5562 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5563 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5564 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5565 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5566 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5567 DAG.getCondCode(ISD::SETEQ)); 5568 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5569 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5570 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5571 if (SetCCOpcode == ISD::SETNE) 5572 Merged = DAG.getNOT(dl, Merged, CmpVT); 5573 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5574 return Merged; 5575 } 5576 5577 if (CmpVT.getVectorElementType() == MVT::i64) 5578 // 64-bit comparisons are not legal in general. 5579 return SDValue(); 5580 5581 if (Op1.getValueType().isFloatingPoint()) { 5582 switch (SetCCOpcode) { 5583 default: llvm_unreachable("Illegal FP comparison"); 5584 case ISD::SETUNE: 5585 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5586 case ISD::SETOEQ: 5587 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5588 case ISD::SETOLT: 5589 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5590 case ISD::SETOGT: 5591 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5592 case ISD::SETOLE: 5593 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5594 case ISD::SETOGE: 5595 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5596 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5597 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5598 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5599 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5600 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5601 case ISD::SETONE: 5602 // Expand this to (OLT | OGT). 5603 TmpOp0 = Op0; 5604 TmpOp1 = Op1; 5605 Opc = ISD::OR; 5606 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5607 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5608 break; 5609 case ISD::SETUO: 5610 Invert = true; 5611 LLVM_FALLTHROUGH; 5612 case ISD::SETO: 5613 // Expand this to (OLT | OGE). 5614 TmpOp0 = Op0; 5615 TmpOp1 = Op1; 5616 Opc = ISD::OR; 5617 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5618 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5619 break; 5620 } 5621 } else { 5622 // Integer comparisons. 5623 switch (SetCCOpcode) { 5624 default: llvm_unreachable("Illegal integer comparison"); 5625 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5626 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5627 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5628 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5629 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5630 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5631 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5632 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5633 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5634 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5635 } 5636 5637 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5638 if (Opc == ARMISD::VCEQ) { 5639 SDValue AndOp; 5640 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5641 AndOp = Op0; 5642 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5643 AndOp = Op1; 5644 5645 // Ignore bitconvert. 5646 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5647 AndOp = AndOp.getOperand(0); 5648 5649 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5650 Opc = ARMISD::VTST; 5651 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5652 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5653 Invert = !Invert; 5654 } 5655 } 5656 } 5657 5658 if (Swap) 5659 std::swap(Op0, Op1); 5660 5661 // If one of the operands is a constant vector zero, attempt to fold the 5662 // comparison to a specialized compare-against-zero form. 5663 SDValue SingleOp; 5664 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5665 SingleOp = Op0; 5666 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5667 if (Opc == ARMISD::VCGE) 5668 Opc = ARMISD::VCLEZ; 5669 else if (Opc == ARMISD::VCGT) 5670 Opc = ARMISD::VCLTZ; 5671 SingleOp = Op1; 5672 } 5673 5674 SDValue Result; 5675 if (SingleOp.getNode()) { 5676 switch (Opc) { 5677 case ARMISD::VCEQ: 5678 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5679 case ARMISD::VCGE: 5680 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5681 case ARMISD::VCLEZ: 5682 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5683 case ARMISD::VCGT: 5684 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5685 case ARMISD::VCLTZ: 5686 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5687 default: 5688 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5689 } 5690 } else { 5691 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5692 } 5693 5694 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5695 5696 if (Invert) 5697 Result = DAG.getNOT(dl, Result, VT); 5698 5699 return Result; 5700 } 5701 5702 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 5703 SDValue LHS = Op.getOperand(0); 5704 SDValue RHS = Op.getOperand(1); 5705 SDValue Carry = Op.getOperand(2); 5706 SDValue Cond = Op.getOperand(3); 5707 SDLoc DL(Op); 5708 5709 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 5710 5711 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 5712 // have to invert the carry first. 5713 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 5714 DAG.getConstant(1, DL, MVT::i32), Carry); 5715 // This converts the boolean value carry into the carry flag. 5716 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 5717 5718 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5719 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5720 5721 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5722 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5723 SDValue ARMcc = DAG.getConstant( 5724 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5725 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5726 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5727 Cmp.getValue(1), SDValue()); 5728 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5729 CCR, Chain.getValue(1)); 5730 } 5731 5732 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5733 /// valid vector constant for a NEON instruction with a "modified immediate" 5734 /// operand (e.g., VMOV). If so, return the encoded value. 5735 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5736 unsigned SplatBitSize, SelectionDAG &DAG, 5737 const SDLoc &dl, EVT &VT, bool is128Bits, 5738 NEONModImmType type) { 5739 unsigned OpCmode, Imm; 5740 5741 // SplatBitSize is set to the smallest size that splats the vector, so a 5742 // zero vector will always have SplatBitSize == 8. However, NEON modified 5743 // immediate instructions others than VMOV do not support the 8-bit encoding 5744 // of a zero vector, and the default encoding of zero is supposed to be the 5745 // 32-bit version. 5746 if (SplatBits == 0) 5747 SplatBitSize = 32; 5748 5749 switch (SplatBitSize) { 5750 case 8: 5751 if (type != VMOVModImm) 5752 return SDValue(); 5753 // Any 1-byte value is OK. Op=0, Cmode=1110. 5754 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5755 OpCmode = 0xe; 5756 Imm = SplatBits; 5757 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5758 break; 5759 5760 case 16: 5761 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5762 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5763 if ((SplatBits & ~0xff) == 0) { 5764 // Value = 0x00nn: Op=x, Cmode=100x. 5765 OpCmode = 0x8; 5766 Imm = SplatBits; 5767 break; 5768 } 5769 if ((SplatBits & ~0xff00) == 0) { 5770 // Value = 0xnn00: Op=x, Cmode=101x. 5771 OpCmode = 0xa; 5772 Imm = SplatBits >> 8; 5773 break; 5774 } 5775 return SDValue(); 5776 5777 case 32: 5778 // NEON's 32-bit VMOV supports splat values where: 5779 // * only one byte is nonzero, or 5780 // * the least significant byte is 0xff and the second byte is nonzero, or 5781 // * the least significant 2 bytes are 0xff and the third is nonzero. 5782 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5783 if ((SplatBits & ~0xff) == 0) { 5784 // Value = 0x000000nn: Op=x, Cmode=000x. 5785 OpCmode = 0; 5786 Imm = SplatBits; 5787 break; 5788 } 5789 if ((SplatBits & ~0xff00) == 0) { 5790 // Value = 0x0000nn00: Op=x, Cmode=001x. 5791 OpCmode = 0x2; 5792 Imm = SplatBits >> 8; 5793 break; 5794 } 5795 if ((SplatBits & ~0xff0000) == 0) { 5796 // Value = 0x00nn0000: Op=x, Cmode=010x. 5797 OpCmode = 0x4; 5798 Imm = SplatBits >> 16; 5799 break; 5800 } 5801 if ((SplatBits & ~0xff000000) == 0) { 5802 // Value = 0xnn000000: Op=x, Cmode=011x. 5803 OpCmode = 0x6; 5804 Imm = SplatBits >> 24; 5805 break; 5806 } 5807 5808 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5809 if (type == OtherModImm) return SDValue(); 5810 5811 if ((SplatBits & ~0xffff) == 0 && 5812 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5813 // Value = 0x0000nnff: Op=x, Cmode=1100. 5814 OpCmode = 0xc; 5815 Imm = SplatBits >> 8; 5816 break; 5817 } 5818 5819 if ((SplatBits & ~0xffffff) == 0 && 5820 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5821 // Value = 0x00nnffff: Op=x, Cmode=1101. 5822 OpCmode = 0xd; 5823 Imm = SplatBits >> 16; 5824 break; 5825 } 5826 5827 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5828 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5829 // VMOV.I32. A (very) minor optimization would be to replicate the value 5830 // and fall through here to test for a valid 64-bit splat. But, then the 5831 // caller would also need to check and handle the change in size. 5832 return SDValue(); 5833 5834 case 64: { 5835 if (type != VMOVModImm) 5836 return SDValue(); 5837 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5838 uint64_t BitMask = 0xff; 5839 uint64_t Val = 0; 5840 unsigned ImmMask = 1; 5841 Imm = 0; 5842 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5843 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5844 Val |= BitMask; 5845 Imm |= ImmMask; 5846 } else if ((SplatBits & BitMask) != 0) { 5847 return SDValue(); 5848 } 5849 BitMask <<= 8; 5850 ImmMask <<= 1; 5851 } 5852 5853 if (DAG.getDataLayout().isBigEndian()) 5854 // swap higher and lower 32 bit word 5855 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5856 5857 // Op=1, Cmode=1110. 5858 OpCmode = 0x1e; 5859 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5860 break; 5861 } 5862 5863 default: 5864 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5865 } 5866 5867 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5868 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5869 } 5870 5871 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5872 const ARMSubtarget *ST) const { 5873 EVT VT = Op.getValueType(); 5874 bool IsDouble = (VT == MVT::f64); 5875 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5876 const APFloat &FPVal = CFP->getValueAPF(); 5877 5878 // Prevent floating-point constants from using literal loads 5879 // when execute-only is enabled. 5880 if (ST->genExecuteOnly()) { 5881 // If we can represent the constant as an immediate, don't lower it 5882 if (isFPImmLegal(FPVal, VT)) 5883 return Op; 5884 // Otherwise, construct as integer, and move to float register 5885 APInt INTVal = FPVal.bitcastToAPInt(); 5886 SDLoc DL(CFP); 5887 switch (VT.getSimpleVT().SimpleTy) { 5888 default: 5889 llvm_unreachable("Unknown floating point type!"); 5890 break; 5891 case MVT::f64: { 5892 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5893 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5894 if (!ST->isLittle()) 5895 std::swap(Lo, Hi); 5896 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5897 } 5898 case MVT::f32: 5899 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 5900 DAG.getConstant(INTVal, DL, MVT::i32)); 5901 } 5902 } 5903 5904 if (!ST->hasVFP3()) 5905 return SDValue(); 5906 5907 // Use the default (constant pool) lowering for double constants when we have 5908 // an SP-only FPU 5909 if (IsDouble && Subtarget->isFPOnlySP()) 5910 return SDValue(); 5911 5912 // Try splatting with a VMOV.f32... 5913 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5914 5915 if (ImmVal != -1) { 5916 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5917 // We have code in place to select a valid ConstantFP already, no need to 5918 // do any mangling. 5919 return Op; 5920 } 5921 5922 // It's a float and we are trying to use NEON operations where 5923 // possible. Lower it to a splat followed by an extract. 5924 SDLoc DL(Op); 5925 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5926 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5927 NewVal); 5928 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5929 DAG.getConstant(0, DL, MVT::i32)); 5930 } 5931 5932 // The rest of our options are NEON only, make sure that's allowed before 5933 // proceeding.. 5934 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5935 return SDValue(); 5936 5937 EVT VMovVT; 5938 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5939 5940 // It wouldn't really be worth bothering for doubles except for one very 5941 // important value, which does happen to match: 0.0. So make sure we don't do 5942 // anything stupid. 5943 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5944 return SDValue(); 5945 5946 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5947 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5948 VMovVT, false, VMOVModImm); 5949 if (NewVal != SDValue()) { 5950 SDLoc DL(Op); 5951 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5952 NewVal); 5953 if (IsDouble) 5954 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5955 5956 // It's a float: cast and extract a vector element. 5957 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5958 VecConstant); 5959 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5960 DAG.getConstant(0, DL, MVT::i32)); 5961 } 5962 5963 // Finally, try a VMVN.i32 5964 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5965 false, VMVNModImm); 5966 if (NewVal != SDValue()) { 5967 SDLoc DL(Op); 5968 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5969 5970 if (IsDouble) 5971 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5972 5973 // It's a float: cast and extract a vector element. 5974 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5975 VecConstant); 5976 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5977 DAG.getConstant(0, DL, MVT::i32)); 5978 } 5979 5980 return SDValue(); 5981 } 5982 5983 // check if an VEXT instruction can handle the shuffle mask when the 5984 // vector sources of the shuffle are the same. 5985 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5986 unsigned NumElts = VT.getVectorNumElements(); 5987 5988 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5989 if (M[0] < 0) 5990 return false; 5991 5992 Imm = M[0]; 5993 5994 // If this is a VEXT shuffle, the immediate value is the index of the first 5995 // element. The other shuffle indices must be the successive elements after 5996 // the first one. 5997 unsigned ExpectedElt = Imm; 5998 for (unsigned i = 1; i < NumElts; ++i) { 5999 // Increment the expected index. If it wraps around, just follow it 6000 // back to index zero and keep going. 6001 ++ExpectedElt; 6002 if (ExpectedElt == NumElts) 6003 ExpectedElt = 0; 6004 6005 if (M[i] < 0) continue; // ignore UNDEF indices 6006 if (ExpectedElt != static_cast<unsigned>(M[i])) 6007 return false; 6008 } 6009 6010 return true; 6011 } 6012 6013 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6014 bool &ReverseVEXT, unsigned &Imm) { 6015 unsigned NumElts = VT.getVectorNumElements(); 6016 ReverseVEXT = false; 6017 6018 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6019 if (M[0] < 0) 6020 return false; 6021 6022 Imm = M[0]; 6023 6024 // If this is a VEXT shuffle, the immediate value is the index of the first 6025 // element. The other shuffle indices must be the successive elements after 6026 // the first one. 6027 unsigned ExpectedElt = Imm; 6028 for (unsigned i = 1; i < NumElts; ++i) { 6029 // Increment the expected index. If it wraps around, it may still be 6030 // a VEXT but the source vectors must be swapped. 6031 ExpectedElt += 1; 6032 if (ExpectedElt == NumElts * 2) { 6033 ExpectedElt = 0; 6034 ReverseVEXT = true; 6035 } 6036 6037 if (M[i] < 0) continue; // ignore UNDEF indices 6038 if (ExpectedElt != static_cast<unsigned>(M[i])) 6039 return false; 6040 } 6041 6042 // Adjust the index value if the source operands will be swapped. 6043 if (ReverseVEXT) 6044 Imm -= NumElts; 6045 6046 return true; 6047 } 6048 6049 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6050 /// instruction with the specified blocksize. (The order of the elements 6051 /// within each block of the vector is reversed.) 6052 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6053 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6054 "Only possible block sizes for VREV are: 16, 32, 64"); 6055 6056 unsigned EltSz = VT.getScalarSizeInBits(); 6057 if (EltSz == 64) 6058 return false; 6059 6060 unsigned NumElts = VT.getVectorNumElements(); 6061 unsigned BlockElts = M[0] + 1; 6062 // If the first shuffle index is UNDEF, be optimistic. 6063 if (M[0] < 0) 6064 BlockElts = BlockSize / EltSz; 6065 6066 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6067 return false; 6068 6069 for (unsigned i = 0; i < NumElts; ++i) { 6070 if (M[i] < 0) continue; // ignore UNDEF indices 6071 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6072 return false; 6073 } 6074 6075 return true; 6076 } 6077 6078 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6079 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6080 // range, then 0 is placed into the resulting vector. So pretty much any mask 6081 // of 8 elements can work here. 6082 return VT == MVT::v8i8 && M.size() == 8; 6083 } 6084 6085 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6086 unsigned Index) { 6087 if (Mask.size() == Elements * 2) 6088 return Index / Elements; 6089 return Mask[Index] == 0 ? 0 : 1; 6090 } 6091 6092 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6093 // checking that pairs of elements in the shuffle mask represent the same index 6094 // in each vector, incrementing the expected index by 2 at each step. 6095 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6096 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6097 // v2={e,f,g,h} 6098 // WhichResult gives the offset for each element in the mask based on which 6099 // of the two results it belongs to. 6100 // 6101 // The transpose can be represented either as: 6102 // result1 = shufflevector v1, v2, result1_shuffle_mask 6103 // result2 = shufflevector v1, v2, result2_shuffle_mask 6104 // where v1/v2 and the shuffle masks have the same number of elements 6105 // (here WhichResult (see below) indicates which result is being checked) 6106 // 6107 // or as: 6108 // results = shufflevector v1, v2, shuffle_mask 6109 // where both results are returned in one vector and the shuffle mask has twice 6110 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6111 // want to check the low half and high half of the shuffle mask as if it were 6112 // the other case 6113 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6114 unsigned EltSz = VT.getScalarSizeInBits(); 6115 if (EltSz == 64) 6116 return false; 6117 6118 unsigned NumElts = VT.getVectorNumElements(); 6119 if (M.size() != NumElts && M.size() != NumElts*2) 6120 return false; 6121 6122 // If the mask is twice as long as the input vector then we need to check the 6123 // upper and lower parts of the mask with a matching value for WhichResult 6124 // FIXME: A mask with only even values will be rejected in case the first 6125 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6126 // M[0] is used to determine WhichResult 6127 for (unsigned i = 0; i < M.size(); i += NumElts) { 6128 WhichResult = SelectPairHalf(NumElts, M, i); 6129 for (unsigned j = 0; j < NumElts; j += 2) { 6130 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6131 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6132 return false; 6133 } 6134 } 6135 6136 if (M.size() == NumElts*2) 6137 WhichResult = 0; 6138 6139 return true; 6140 } 6141 6142 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6143 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6144 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6145 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6146 unsigned EltSz = VT.getScalarSizeInBits(); 6147 if (EltSz == 64) 6148 return false; 6149 6150 unsigned NumElts = VT.getVectorNumElements(); 6151 if (M.size() != NumElts && M.size() != NumElts*2) 6152 return false; 6153 6154 for (unsigned i = 0; i < M.size(); i += NumElts) { 6155 WhichResult = SelectPairHalf(NumElts, M, i); 6156 for (unsigned j = 0; j < NumElts; j += 2) { 6157 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6158 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6159 return false; 6160 } 6161 } 6162 6163 if (M.size() == NumElts*2) 6164 WhichResult = 0; 6165 6166 return true; 6167 } 6168 6169 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6170 // that the mask elements are either all even and in steps of size 2 or all odd 6171 // and in steps of size 2. 6172 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6173 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6174 // v2={e,f,g,h} 6175 // Requires similar checks to that of isVTRNMask with 6176 // respect the how results are returned. 6177 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6178 unsigned EltSz = VT.getScalarSizeInBits(); 6179 if (EltSz == 64) 6180 return false; 6181 6182 unsigned NumElts = VT.getVectorNumElements(); 6183 if (M.size() != NumElts && M.size() != NumElts*2) 6184 return false; 6185 6186 for (unsigned i = 0; i < M.size(); i += NumElts) { 6187 WhichResult = SelectPairHalf(NumElts, M, i); 6188 for (unsigned j = 0; j < NumElts; ++j) { 6189 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6190 return false; 6191 } 6192 } 6193 6194 if (M.size() == NumElts*2) 6195 WhichResult = 0; 6196 6197 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6198 if (VT.is64BitVector() && EltSz == 32) 6199 return false; 6200 6201 return true; 6202 } 6203 6204 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6205 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6206 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6207 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6208 unsigned EltSz = VT.getScalarSizeInBits(); 6209 if (EltSz == 64) 6210 return false; 6211 6212 unsigned NumElts = VT.getVectorNumElements(); 6213 if (M.size() != NumElts && M.size() != NumElts*2) 6214 return false; 6215 6216 unsigned Half = NumElts / 2; 6217 for (unsigned i = 0; i < M.size(); i += NumElts) { 6218 WhichResult = SelectPairHalf(NumElts, M, i); 6219 for (unsigned j = 0; j < NumElts; j += Half) { 6220 unsigned Idx = WhichResult; 6221 for (unsigned k = 0; k < Half; ++k) { 6222 int MIdx = M[i + j + k]; 6223 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6224 return false; 6225 Idx += 2; 6226 } 6227 } 6228 } 6229 6230 if (M.size() == NumElts*2) 6231 WhichResult = 0; 6232 6233 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6234 if (VT.is64BitVector() && EltSz == 32) 6235 return false; 6236 6237 return true; 6238 } 6239 6240 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6241 // that pairs of elements of the shufflemask represent the same index in each 6242 // vector incrementing sequentially through the vectors. 6243 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6244 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6245 // v2={e,f,g,h} 6246 // Requires similar checks to that of isVTRNMask with respect the how results 6247 // are returned. 6248 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6249 unsigned EltSz = VT.getScalarSizeInBits(); 6250 if (EltSz == 64) 6251 return false; 6252 6253 unsigned NumElts = VT.getVectorNumElements(); 6254 if (M.size() != NumElts && M.size() != NumElts*2) 6255 return false; 6256 6257 for (unsigned i = 0; i < M.size(); i += NumElts) { 6258 WhichResult = SelectPairHalf(NumElts, M, i); 6259 unsigned Idx = WhichResult * NumElts / 2; 6260 for (unsigned j = 0; j < NumElts; j += 2) { 6261 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6262 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6263 return false; 6264 Idx += 1; 6265 } 6266 } 6267 6268 if (M.size() == NumElts*2) 6269 WhichResult = 0; 6270 6271 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6272 if (VT.is64BitVector() && EltSz == 32) 6273 return false; 6274 6275 return true; 6276 } 6277 6278 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6279 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6280 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6281 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6282 unsigned EltSz = VT.getScalarSizeInBits(); 6283 if (EltSz == 64) 6284 return false; 6285 6286 unsigned NumElts = VT.getVectorNumElements(); 6287 if (M.size() != NumElts && M.size() != NumElts*2) 6288 return false; 6289 6290 for (unsigned i = 0; i < M.size(); i += NumElts) { 6291 WhichResult = SelectPairHalf(NumElts, M, i); 6292 unsigned Idx = WhichResult * NumElts / 2; 6293 for (unsigned j = 0; j < NumElts; j += 2) { 6294 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6295 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6296 return false; 6297 Idx += 1; 6298 } 6299 } 6300 6301 if (M.size() == NumElts*2) 6302 WhichResult = 0; 6303 6304 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6305 if (VT.is64BitVector() && EltSz == 32) 6306 return false; 6307 6308 return true; 6309 } 6310 6311 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6312 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6313 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6314 unsigned &WhichResult, 6315 bool &isV_UNDEF) { 6316 isV_UNDEF = false; 6317 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6318 return ARMISD::VTRN; 6319 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6320 return ARMISD::VUZP; 6321 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6322 return ARMISD::VZIP; 6323 6324 isV_UNDEF = true; 6325 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6326 return ARMISD::VTRN; 6327 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6328 return ARMISD::VUZP; 6329 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6330 return ARMISD::VZIP; 6331 6332 return 0; 6333 } 6334 6335 /// \return true if this is a reverse operation on an vector. 6336 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6337 unsigned NumElts = VT.getVectorNumElements(); 6338 // Make sure the mask has the right size. 6339 if (NumElts != M.size()) 6340 return false; 6341 6342 // Look for <15, ..., 3, -1, 1, 0>. 6343 for (unsigned i = 0; i != NumElts; ++i) 6344 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6345 return false; 6346 6347 return true; 6348 } 6349 6350 // If N is an integer constant that can be moved into a register in one 6351 // instruction, return an SDValue of such a constant (will become a MOV 6352 // instruction). Otherwise return null. 6353 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6354 const ARMSubtarget *ST, const SDLoc &dl) { 6355 uint64_t Val; 6356 if (!isa<ConstantSDNode>(N)) 6357 return SDValue(); 6358 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6359 6360 if (ST->isThumb1Only()) { 6361 if (Val <= 255 || ~Val <= 255) 6362 return DAG.getConstant(Val, dl, MVT::i32); 6363 } else { 6364 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6365 return DAG.getConstant(Val, dl, MVT::i32); 6366 } 6367 return SDValue(); 6368 } 6369 6370 // If this is a case we can't handle, return null and let the default 6371 // expansion code take care of it. 6372 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6373 const ARMSubtarget *ST) const { 6374 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6375 SDLoc dl(Op); 6376 EVT VT = Op.getValueType(); 6377 6378 APInt SplatBits, SplatUndef; 6379 unsigned SplatBitSize; 6380 bool HasAnyUndefs; 6381 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6382 if (SplatUndef.isAllOnesValue()) 6383 return DAG.getUNDEF(VT); 6384 6385 if (SplatBitSize <= 64) { 6386 // Check if an immediate VMOV works. 6387 EVT VmovVT; 6388 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6389 SplatUndef.getZExtValue(), SplatBitSize, 6390 DAG, dl, VmovVT, VT.is128BitVector(), 6391 VMOVModImm); 6392 if (Val.getNode()) { 6393 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6394 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6395 } 6396 6397 // Try an immediate VMVN. 6398 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6399 Val = isNEONModifiedImm(NegatedImm, 6400 SplatUndef.getZExtValue(), SplatBitSize, 6401 DAG, dl, VmovVT, VT.is128BitVector(), 6402 VMVNModImm); 6403 if (Val.getNode()) { 6404 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6405 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6406 } 6407 6408 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6409 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6410 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6411 if (ImmVal != -1) { 6412 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6413 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6414 } 6415 } 6416 } 6417 } 6418 6419 // Scan through the operands to see if only one value is used. 6420 // 6421 // As an optimisation, even if more than one value is used it may be more 6422 // profitable to splat with one value then change some lanes. 6423 // 6424 // Heuristically we decide to do this if the vector has a "dominant" value, 6425 // defined as splatted to more than half of the lanes. 6426 unsigned NumElts = VT.getVectorNumElements(); 6427 bool isOnlyLowElement = true; 6428 bool usesOnlyOneValue = true; 6429 bool hasDominantValue = false; 6430 bool isConstant = true; 6431 6432 // Map of the number of times a particular SDValue appears in the 6433 // element list. 6434 DenseMap<SDValue, unsigned> ValueCounts; 6435 SDValue Value; 6436 for (unsigned i = 0; i < NumElts; ++i) { 6437 SDValue V = Op.getOperand(i); 6438 if (V.isUndef()) 6439 continue; 6440 if (i > 0) 6441 isOnlyLowElement = false; 6442 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6443 isConstant = false; 6444 6445 ValueCounts.insert(std::make_pair(V, 0)); 6446 unsigned &Count = ValueCounts[V]; 6447 6448 // Is this value dominant? (takes up more than half of the lanes) 6449 if (++Count > (NumElts / 2)) { 6450 hasDominantValue = true; 6451 Value = V; 6452 } 6453 } 6454 if (ValueCounts.size() != 1) 6455 usesOnlyOneValue = false; 6456 if (!Value.getNode() && !ValueCounts.empty()) 6457 Value = ValueCounts.begin()->first; 6458 6459 if (ValueCounts.empty()) 6460 return DAG.getUNDEF(VT); 6461 6462 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6463 // Keep going if we are hitting this case. 6464 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6465 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6466 6467 unsigned EltSize = VT.getScalarSizeInBits(); 6468 6469 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6470 // i32 and try again. 6471 if (hasDominantValue && EltSize <= 32) { 6472 if (!isConstant) { 6473 SDValue N; 6474 6475 // If we are VDUPing a value that comes directly from a vector, that will 6476 // cause an unnecessary move to and from a GPR, where instead we could 6477 // just use VDUPLANE. We can only do this if the lane being extracted 6478 // is at a constant index, as the VDUP from lane instructions only have 6479 // constant-index forms. 6480 ConstantSDNode *constIndex; 6481 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6482 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6483 // We need to create a new undef vector to use for the VDUPLANE if the 6484 // size of the vector from which we get the value is different than the 6485 // size of the vector that we need to create. We will insert the element 6486 // such that the register coalescer will remove unnecessary copies. 6487 if (VT != Value->getOperand(0).getValueType()) { 6488 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6489 VT.getVectorNumElements(); 6490 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6491 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6492 Value, DAG.getConstant(index, dl, MVT::i32)), 6493 DAG.getConstant(index, dl, MVT::i32)); 6494 } else 6495 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6496 Value->getOperand(0), Value->getOperand(1)); 6497 } else 6498 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6499 6500 if (!usesOnlyOneValue) { 6501 // The dominant value was splatted as 'N', but we now have to insert 6502 // all differing elements. 6503 for (unsigned I = 0; I < NumElts; ++I) { 6504 if (Op.getOperand(I) == Value) 6505 continue; 6506 SmallVector<SDValue, 3> Ops; 6507 Ops.push_back(N); 6508 Ops.push_back(Op.getOperand(I)); 6509 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6510 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6511 } 6512 } 6513 return N; 6514 } 6515 if (VT.getVectorElementType().isFloatingPoint()) { 6516 SmallVector<SDValue, 8> Ops; 6517 for (unsigned i = 0; i < NumElts; ++i) 6518 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6519 Op.getOperand(i))); 6520 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6521 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6522 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6523 if (Val.getNode()) 6524 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6525 } 6526 if (usesOnlyOneValue) { 6527 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6528 if (isConstant && Val.getNode()) 6529 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6530 } 6531 } 6532 6533 // If all elements are constants and the case above didn't get hit, fall back 6534 // to the default expansion, which will generate a load from the constant 6535 // pool. 6536 if (isConstant) 6537 return SDValue(); 6538 6539 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6540 if (NumElts >= 4) { 6541 SDValue shuffle = ReconstructShuffle(Op, DAG); 6542 if (shuffle != SDValue()) 6543 return shuffle; 6544 } 6545 6546 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6547 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6548 // into two 64-bit vectors; we might discover a better way to lower it. 6549 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6550 EVT ExtVT = VT.getVectorElementType(); 6551 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6552 SDValue Lower = 6553 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6554 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6555 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6556 SDValue Upper = DAG.getBuildVector( 6557 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6558 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6559 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6560 if (Lower && Upper) 6561 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6562 } 6563 6564 // Vectors with 32- or 64-bit elements can be built by directly assigning 6565 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6566 // will be legalized. 6567 if (EltSize >= 32) { 6568 // Do the expansion with floating-point types, since that is what the VFP 6569 // registers are defined to use, and since i64 is not legal. 6570 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6571 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6572 SmallVector<SDValue, 8> Ops; 6573 for (unsigned i = 0; i < NumElts; ++i) 6574 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6575 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6576 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6577 } 6578 6579 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6580 // know the default expansion would otherwise fall back on something even 6581 // worse. For a vector with one or two non-undef values, that's 6582 // scalar_to_vector for the elements followed by a shuffle (provided the 6583 // shuffle is valid for the target) and materialization element by element 6584 // on the stack followed by a load for everything else. 6585 if (!isConstant && !usesOnlyOneValue) { 6586 SDValue Vec = DAG.getUNDEF(VT); 6587 for (unsigned i = 0 ; i < NumElts; ++i) { 6588 SDValue V = Op.getOperand(i); 6589 if (V.isUndef()) 6590 continue; 6591 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6592 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6593 } 6594 return Vec; 6595 } 6596 6597 return SDValue(); 6598 } 6599 6600 // Gather data to see if the operation can be modelled as a 6601 // shuffle in combination with VEXTs. 6602 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6603 SelectionDAG &DAG) const { 6604 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6605 SDLoc dl(Op); 6606 EVT VT = Op.getValueType(); 6607 unsigned NumElts = VT.getVectorNumElements(); 6608 6609 struct ShuffleSourceInfo { 6610 SDValue Vec; 6611 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6612 unsigned MaxElt = 0; 6613 6614 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6615 // be compatible with the shuffle we intend to construct. As a result 6616 // ShuffleVec will be some sliding window into the original Vec. 6617 SDValue ShuffleVec; 6618 6619 // Code should guarantee that element i in Vec starts at element "WindowBase 6620 // + i * WindowScale in ShuffleVec". 6621 int WindowBase = 0; 6622 int WindowScale = 1; 6623 6624 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6625 6626 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6627 }; 6628 6629 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6630 // node. 6631 SmallVector<ShuffleSourceInfo, 2> Sources; 6632 for (unsigned i = 0; i < NumElts; ++i) { 6633 SDValue V = Op.getOperand(i); 6634 if (V.isUndef()) 6635 continue; 6636 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6637 // A shuffle can only come from building a vector from various 6638 // elements of other vectors. 6639 return SDValue(); 6640 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6641 // Furthermore, shuffles require a constant mask, whereas extractelts 6642 // accept variable indices. 6643 return SDValue(); 6644 } 6645 6646 // Add this element source to the list if it's not already there. 6647 SDValue SourceVec = V.getOperand(0); 6648 auto Source = llvm::find(Sources, SourceVec); 6649 if (Source == Sources.end()) 6650 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6651 6652 // Update the minimum and maximum lane number seen. 6653 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6654 Source->MinElt = std::min(Source->MinElt, EltNo); 6655 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6656 } 6657 6658 // Currently only do something sane when at most two source vectors 6659 // are involved. 6660 if (Sources.size() > 2) 6661 return SDValue(); 6662 6663 // Find out the smallest element size among result and two sources, and use 6664 // it as element size to build the shuffle_vector. 6665 EVT SmallestEltTy = VT.getVectorElementType(); 6666 for (auto &Source : Sources) { 6667 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6668 if (SrcEltTy.bitsLT(SmallestEltTy)) 6669 SmallestEltTy = SrcEltTy; 6670 } 6671 unsigned ResMultiplier = 6672 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6673 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6674 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6675 6676 // If the source vector is too wide or too narrow, we may nevertheless be able 6677 // to construct a compatible shuffle either by concatenating it with UNDEF or 6678 // extracting a suitable range of elements. 6679 for (auto &Src : Sources) { 6680 EVT SrcVT = Src.ShuffleVec.getValueType(); 6681 6682 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6683 continue; 6684 6685 // This stage of the search produces a source with the same element type as 6686 // the original, but with a total width matching the BUILD_VECTOR output. 6687 EVT EltVT = SrcVT.getVectorElementType(); 6688 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6689 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6690 6691 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6692 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6693 return SDValue(); 6694 // We can pad out the smaller vector for free, so if it's part of a 6695 // shuffle... 6696 Src.ShuffleVec = 6697 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6698 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6699 continue; 6700 } 6701 6702 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6703 return SDValue(); 6704 6705 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6706 // Span too large for a VEXT to cope 6707 return SDValue(); 6708 } 6709 6710 if (Src.MinElt >= NumSrcElts) { 6711 // The extraction can just take the second half 6712 Src.ShuffleVec = 6713 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6714 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6715 Src.WindowBase = -NumSrcElts; 6716 } else if (Src.MaxElt < NumSrcElts) { 6717 // The extraction can just take the first half 6718 Src.ShuffleVec = 6719 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6720 DAG.getConstant(0, dl, MVT::i32)); 6721 } else { 6722 // An actual VEXT is needed 6723 SDValue VEXTSrc1 = 6724 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6725 DAG.getConstant(0, dl, MVT::i32)); 6726 SDValue VEXTSrc2 = 6727 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6728 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6729 6730 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6731 VEXTSrc2, 6732 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6733 Src.WindowBase = -Src.MinElt; 6734 } 6735 } 6736 6737 // Another possible incompatibility occurs from the vector element types. We 6738 // can fix this by bitcasting the source vectors to the same type we intend 6739 // for the shuffle. 6740 for (auto &Src : Sources) { 6741 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6742 if (SrcEltTy == SmallestEltTy) 6743 continue; 6744 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6745 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6746 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6747 Src.WindowBase *= Src.WindowScale; 6748 } 6749 6750 // Final sanity check before we try to actually produce a shuffle. 6751 LLVM_DEBUG(for (auto Src 6752 : Sources) 6753 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6754 6755 // The stars all align, our next step is to produce the mask for the shuffle. 6756 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6757 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6758 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6759 SDValue Entry = Op.getOperand(i); 6760 if (Entry.isUndef()) 6761 continue; 6762 6763 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6764 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6765 6766 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6767 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6768 // segment. 6769 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6770 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6771 VT.getScalarSizeInBits()); 6772 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6773 6774 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6775 // starting at the appropriate offset. 6776 int *LaneMask = &Mask[i * ResMultiplier]; 6777 6778 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6779 ExtractBase += NumElts * (Src - Sources.begin()); 6780 for (int j = 0; j < LanesDefined; ++j) 6781 LaneMask[j] = ExtractBase + j; 6782 } 6783 6784 // Final check before we try to produce nonsense... 6785 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6786 return SDValue(); 6787 6788 // We can't handle more than two sources. This should have already 6789 // been checked before this point. 6790 assert(Sources.size() <= 2 && "Too many sources!"); 6791 6792 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6793 for (unsigned i = 0; i < Sources.size(); ++i) 6794 ShuffleOps[i] = Sources[i].ShuffleVec; 6795 6796 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6797 ShuffleOps[1], Mask); 6798 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6799 } 6800 6801 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6802 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6803 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6804 /// are assumed to be legal. 6805 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6806 if (VT.getVectorNumElements() == 4 && 6807 (VT.is128BitVector() || VT.is64BitVector())) { 6808 unsigned PFIndexes[4]; 6809 for (unsigned i = 0; i != 4; ++i) { 6810 if (M[i] < 0) 6811 PFIndexes[i] = 8; 6812 else 6813 PFIndexes[i] = M[i]; 6814 } 6815 6816 // Compute the index in the perfect shuffle table. 6817 unsigned PFTableIndex = 6818 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6819 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6820 unsigned Cost = (PFEntry >> 30); 6821 6822 if (Cost <= 4) 6823 return true; 6824 } 6825 6826 bool ReverseVEXT, isV_UNDEF; 6827 unsigned Imm, WhichResult; 6828 6829 unsigned EltSize = VT.getScalarSizeInBits(); 6830 return (EltSize >= 32 || 6831 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6832 isVREVMask(M, VT, 64) || 6833 isVREVMask(M, VT, 32) || 6834 isVREVMask(M, VT, 16) || 6835 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6836 isVTBLMask(M, VT) || 6837 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6838 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6839 } 6840 6841 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6842 /// the specified operations to build the shuffle. 6843 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6844 SDValue RHS, SelectionDAG &DAG, 6845 const SDLoc &dl) { 6846 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6847 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6848 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6849 6850 enum { 6851 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6852 OP_VREV, 6853 OP_VDUP0, 6854 OP_VDUP1, 6855 OP_VDUP2, 6856 OP_VDUP3, 6857 OP_VEXT1, 6858 OP_VEXT2, 6859 OP_VEXT3, 6860 OP_VUZPL, // VUZP, left result 6861 OP_VUZPR, // VUZP, right result 6862 OP_VZIPL, // VZIP, left result 6863 OP_VZIPR, // VZIP, right result 6864 OP_VTRNL, // VTRN, left result 6865 OP_VTRNR // VTRN, right result 6866 }; 6867 6868 if (OpNum == OP_COPY) { 6869 if (LHSID == (1*9+2)*9+3) return LHS; 6870 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6871 return RHS; 6872 } 6873 6874 SDValue OpLHS, OpRHS; 6875 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6876 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6877 EVT VT = OpLHS.getValueType(); 6878 6879 switch (OpNum) { 6880 default: llvm_unreachable("Unknown shuffle opcode!"); 6881 case OP_VREV: 6882 // VREV divides the vector in half and swaps within the half. 6883 if (VT.getVectorElementType() == MVT::i32 || 6884 VT.getVectorElementType() == MVT::f32) 6885 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6886 // vrev <4 x i16> -> VREV32 6887 if (VT.getVectorElementType() == MVT::i16) 6888 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6889 // vrev <4 x i8> -> VREV16 6890 assert(VT.getVectorElementType() == MVT::i8); 6891 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6892 case OP_VDUP0: 6893 case OP_VDUP1: 6894 case OP_VDUP2: 6895 case OP_VDUP3: 6896 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6897 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6898 case OP_VEXT1: 6899 case OP_VEXT2: 6900 case OP_VEXT3: 6901 return DAG.getNode(ARMISD::VEXT, dl, VT, 6902 OpLHS, OpRHS, 6903 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6904 case OP_VUZPL: 6905 case OP_VUZPR: 6906 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6907 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6908 case OP_VZIPL: 6909 case OP_VZIPR: 6910 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6911 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6912 case OP_VTRNL: 6913 case OP_VTRNR: 6914 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6915 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6916 } 6917 } 6918 6919 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6920 ArrayRef<int> ShuffleMask, 6921 SelectionDAG &DAG) { 6922 // Check to see if we can use the VTBL instruction. 6923 SDValue V1 = Op.getOperand(0); 6924 SDValue V2 = Op.getOperand(1); 6925 SDLoc DL(Op); 6926 6927 SmallVector<SDValue, 8> VTBLMask; 6928 for (ArrayRef<int>::iterator 6929 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6930 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6931 6932 if (V2.getNode()->isUndef()) 6933 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6934 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6935 6936 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6937 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6938 } 6939 6940 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6941 SelectionDAG &DAG) { 6942 SDLoc DL(Op); 6943 SDValue OpLHS = Op.getOperand(0); 6944 EVT VT = OpLHS.getValueType(); 6945 6946 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6947 "Expect an v8i16/v16i8 type"); 6948 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6949 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6950 // extract the first 8 bytes into the top double word and the last 8 bytes 6951 // into the bottom double word. The v8i16 case is similar. 6952 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6953 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6954 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6955 } 6956 6957 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6958 SDValue V1 = Op.getOperand(0); 6959 SDValue V2 = Op.getOperand(1); 6960 SDLoc dl(Op); 6961 EVT VT = Op.getValueType(); 6962 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6963 6964 // Convert shuffles that are directly supported on NEON to target-specific 6965 // DAG nodes, instead of keeping them as shuffles and matching them again 6966 // during code selection. This is more efficient and avoids the possibility 6967 // of inconsistencies between legalization and selection. 6968 // FIXME: floating-point vectors should be canonicalized to integer vectors 6969 // of the same time so that they get CSEd properly. 6970 ArrayRef<int> ShuffleMask = SVN->getMask(); 6971 6972 unsigned EltSize = VT.getScalarSizeInBits(); 6973 if (EltSize <= 32) { 6974 if (SVN->isSplat()) { 6975 int Lane = SVN->getSplatIndex(); 6976 // If this is undef splat, generate it via "just" vdup, if possible. 6977 if (Lane == -1) Lane = 0; 6978 6979 // Test if V1 is a SCALAR_TO_VECTOR. 6980 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6981 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6982 } 6983 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6984 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6985 // reaches it). 6986 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6987 !isa<ConstantSDNode>(V1.getOperand(0))) { 6988 bool IsScalarToVector = true; 6989 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6990 if (!V1.getOperand(i).isUndef()) { 6991 IsScalarToVector = false; 6992 break; 6993 } 6994 if (IsScalarToVector) 6995 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6996 } 6997 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6998 DAG.getConstant(Lane, dl, MVT::i32)); 6999 } 7000 7001 bool ReverseVEXT; 7002 unsigned Imm; 7003 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7004 if (ReverseVEXT) 7005 std::swap(V1, V2); 7006 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7007 DAG.getConstant(Imm, dl, MVT::i32)); 7008 } 7009 7010 if (isVREVMask(ShuffleMask, VT, 64)) 7011 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7012 if (isVREVMask(ShuffleMask, VT, 32)) 7013 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7014 if (isVREVMask(ShuffleMask, VT, 16)) 7015 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7016 7017 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7018 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7019 DAG.getConstant(Imm, dl, MVT::i32)); 7020 } 7021 7022 // Check for Neon shuffles that modify both input vectors in place. 7023 // If both results are used, i.e., if there are two shuffles with the same 7024 // source operands and with masks corresponding to both results of one of 7025 // these operations, DAG memoization will ensure that a single node is 7026 // used for both shuffles. 7027 unsigned WhichResult; 7028 bool isV_UNDEF; 7029 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7030 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7031 if (isV_UNDEF) 7032 V2 = V1; 7033 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7034 .getValue(WhichResult); 7035 } 7036 7037 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7038 // shuffles that produce a result larger than their operands with: 7039 // shuffle(concat(v1, undef), concat(v2, undef)) 7040 // -> 7041 // shuffle(concat(v1, v2), undef) 7042 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7043 // 7044 // This is useful in the general case, but there are special cases where 7045 // native shuffles produce larger results: the two-result ops. 7046 // 7047 // Look through the concat when lowering them: 7048 // shuffle(concat(v1, v2), undef) 7049 // -> 7050 // concat(VZIP(v1, v2):0, :1) 7051 // 7052 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7053 SDValue SubV1 = V1->getOperand(0); 7054 SDValue SubV2 = V1->getOperand(1); 7055 EVT SubVT = SubV1.getValueType(); 7056 7057 // We expect these to have been canonicalized to -1. 7058 assert(llvm::all_of(ShuffleMask, [&](int i) { 7059 return i < (int)VT.getVectorNumElements(); 7060 }) && "Unexpected shuffle index into UNDEF operand!"); 7061 7062 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7063 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7064 if (isV_UNDEF) 7065 SubV2 = SubV1; 7066 assert((WhichResult == 0) && 7067 "In-place shuffle of concat can only have one result!"); 7068 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7069 SubV1, SubV2); 7070 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7071 Res.getValue(1)); 7072 } 7073 } 7074 } 7075 7076 // If the shuffle is not directly supported and it has 4 elements, use 7077 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7078 unsigned NumElts = VT.getVectorNumElements(); 7079 if (NumElts == 4) { 7080 unsigned PFIndexes[4]; 7081 for (unsigned i = 0; i != 4; ++i) { 7082 if (ShuffleMask[i] < 0) 7083 PFIndexes[i] = 8; 7084 else 7085 PFIndexes[i] = ShuffleMask[i]; 7086 } 7087 7088 // Compute the index in the perfect shuffle table. 7089 unsigned PFTableIndex = 7090 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7091 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7092 unsigned Cost = (PFEntry >> 30); 7093 7094 if (Cost <= 4) 7095 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7096 } 7097 7098 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7099 if (EltSize >= 32) { 7100 // Do the expansion with floating-point types, since that is what the VFP 7101 // registers are defined to use, and since i64 is not legal. 7102 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7103 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7104 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7105 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7106 SmallVector<SDValue, 8> Ops; 7107 for (unsigned i = 0; i < NumElts; ++i) { 7108 if (ShuffleMask[i] < 0) 7109 Ops.push_back(DAG.getUNDEF(EltVT)); 7110 else 7111 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7112 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7113 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7114 dl, MVT::i32))); 7115 } 7116 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7117 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7118 } 7119 7120 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7121 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7122 7123 if (VT == MVT::v8i8) 7124 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7125 return NewOp; 7126 7127 return SDValue(); 7128 } 7129 7130 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7131 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7132 SDValue Lane = Op.getOperand(2); 7133 if (!isa<ConstantSDNode>(Lane)) 7134 return SDValue(); 7135 7136 return Op; 7137 } 7138 7139 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7140 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7141 SDValue Lane = Op.getOperand(1); 7142 if (!isa<ConstantSDNode>(Lane)) 7143 return SDValue(); 7144 7145 SDValue Vec = Op.getOperand(0); 7146 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7147 SDLoc dl(Op); 7148 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7149 } 7150 7151 return Op; 7152 } 7153 7154 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7155 // The only time a CONCAT_VECTORS operation can have legal types is when 7156 // two 64-bit vectors are concatenated to a 128-bit vector. 7157 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7158 "unexpected CONCAT_VECTORS"); 7159 SDLoc dl(Op); 7160 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7161 SDValue Op0 = Op.getOperand(0); 7162 SDValue Op1 = Op.getOperand(1); 7163 if (!Op0.isUndef()) 7164 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7165 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7166 DAG.getIntPtrConstant(0, dl)); 7167 if (!Op1.isUndef()) 7168 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7169 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7170 DAG.getIntPtrConstant(1, dl)); 7171 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7172 } 7173 7174 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7175 /// element has been zero/sign-extended, depending on the isSigned parameter, 7176 /// from an integer type half its size. 7177 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7178 bool isSigned) { 7179 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7180 EVT VT = N->getValueType(0); 7181 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7182 SDNode *BVN = N->getOperand(0).getNode(); 7183 if (BVN->getValueType(0) != MVT::v4i32 || 7184 BVN->getOpcode() != ISD::BUILD_VECTOR) 7185 return false; 7186 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7187 unsigned HiElt = 1 - LoElt; 7188 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7189 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7190 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7191 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7192 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7193 return false; 7194 if (isSigned) { 7195 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7196 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7197 return true; 7198 } else { 7199 if (Hi0->isNullValue() && Hi1->isNullValue()) 7200 return true; 7201 } 7202 return false; 7203 } 7204 7205 if (N->getOpcode() != ISD::BUILD_VECTOR) 7206 return false; 7207 7208 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7209 SDNode *Elt = N->getOperand(i).getNode(); 7210 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7211 unsigned EltSize = VT.getScalarSizeInBits(); 7212 unsigned HalfSize = EltSize / 2; 7213 if (isSigned) { 7214 if (!isIntN(HalfSize, C->getSExtValue())) 7215 return false; 7216 } else { 7217 if (!isUIntN(HalfSize, C->getZExtValue())) 7218 return false; 7219 } 7220 continue; 7221 } 7222 return false; 7223 } 7224 7225 return true; 7226 } 7227 7228 /// isSignExtended - Check if a node is a vector value that is sign-extended 7229 /// or a constant BUILD_VECTOR with sign-extended elements. 7230 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7231 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7232 return true; 7233 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7234 return true; 7235 return false; 7236 } 7237 7238 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7239 /// or a constant BUILD_VECTOR with zero-extended elements. 7240 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7241 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7242 return true; 7243 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7244 return true; 7245 return false; 7246 } 7247 7248 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7249 if (OrigVT.getSizeInBits() >= 64) 7250 return OrigVT; 7251 7252 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7253 7254 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7255 switch (OrigSimpleTy) { 7256 default: llvm_unreachable("Unexpected Vector Type"); 7257 case MVT::v2i8: 7258 case MVT::v2i16: 7259 return MVT::v2i32; 7260 case MVT::v4i8: 7261 return MVT::v4i16; 7262 } 7263 } 7264 7265 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7266 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7267 /// We insert the required extension here to get the vector to fill a D register. 7268 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7269 const EVT &OrigTy, 7270 const EVT &ExtTy, 7271 unsigned ExtOpcode) { 7272 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7273 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7274 // 64-bits we need to insert a new extension so that it will be 64-bits. 7275 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7276 if (OrigTy.getSizeInBits() >= 64) 7277 return N; 7278 7279 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7280 EVT NewVT = getExtensionTo64Bits(OrigTy); 7281 7282 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7283 } 7284 7285 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7286 /// does not do any sign/zero extension. If the original vector is less 7287 /// than 64 bits, an appropriate extension will be added after the load to 7288 /// reach a total size of 64 bits. We have to add the extension separately 7289 /// because ARM does not have a sign/zero extending load for vectors. 7290 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7291 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7292 7293 // The load already has the right type. 7294 if (ExtendedTy == LD->getMemoryVT()) 7295 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7296 LD->getBasePtr(), LD->getPointerInfo(), 7297 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7298 7299 // We need to create a zextload/sextload. We cannot just create a load 7300 // followed by a zext/zext node because LowerMUL is also run during normal 7301 // operation legalization where we can't create illegal types. 7302 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7303 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7304 LD->getMemoryVT(), LD->getAlignment(), 7305 LD->getMemOperand()->getFlags()); 7306 } 7307 7308 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7309 /// extending load, or BUILD_VECTOR with extended elements, return the 7310 /// unextended value. The unextended vector should be 64 bits so that it can 7311 /// be used as an operand to a VMULL instruction. If the original vector size 7312 /// before extension is less than 64 bits we add a an extension to resize 7313 /// the vector to 64 bits. 7314 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7315 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7316 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7317 N->getOperand(0)->getValueType(0), 7318 N->getValueType(0), 7319 N->getOpcode()); 7320 7321 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7322 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7323 "Expected extending load"); 7324 7325 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7326 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7327 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7328 SDValue extLoad = 7329 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7330 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7331 7332 return newLoad; 7333 } 7334 7335 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7336 // have been legalized as a BITCAST from v4i32. 7337 if (N->getOpcode() == ISD::BITCAST) { 7338 SDNode *BVN = N->getOperand(0).getNode(); 7339 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7340 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7341 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7342 return DAG.getBuildVector( 7343 MVT::v2i32, SDLoc(N), 7344 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7345 } 7346 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7347 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7348 EVT VT = N->getValueType(0); 7349 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7350 unsigned NumElts = VT.getVectorNumElements(); 7351 MVT TruncVT = MVT::getIntegerVT(EltSize); 7352 SmallVector<SDValue, 8> Ops; 7353 SDLoc dl(N); 7354 for (unsigned i = 0; i != NumElts; ++i) { 7355 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7356 const APInt &CInt = C->getAPIntValue(); 7357 // Element types smaller than 32 bits are not legal, so use i32 elements. 7358 // The values are implicitly truncated so sext vs. zext doesn't matter. 7359 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7360 } 7361 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7362 } 7363 7364 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7365 unsigned Opcode = N->getOpcode(); 7366 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7367 SDNode *N0 = N->getOperand(0).getNode(); 7368 SDNode *N1 = N->getOperand(1).getNode(); 7369 return N0->hasOneUse() && N1->hasOneUse() && 7370 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7371 } 7372 return false; 7373 } 7374 7375 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7376 unsigned Opcode = N->getOpcode(); 7377 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7378 SDNode *N0 = N->getOperand(0).getNode(); 7379 SDNode *N1 = N->getOperand(1).getNode(); 7380 return N0->hasOneUse() && N1->hasOneUse() && 7381 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7382 } 7383 return false; 7384 } 7385 7386 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7387 // Multiplications are only custom-lowered for 128-bit vectors so that 7388 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7389 EVT VT = Op.getValueType(); 7390 assert(VT.is128BitVector() && VT.isInteger() && 7391 "unexpected type for custom-lowering ISD::MUL"); 7392 SDNode *N0 = Op.getOperand(0).getNode(); 7393 SDNode *N1 = Op.getOperand(1).getNode(); 7394 unsigned NewOpc = 0; 7395 bool isMLA = false; 7396 bool isN0SExt = isSignExtended(N0, DAG); 7397 bool isN1SExt = isSignExtended(N1, DAG); 7398 if (isN0SExt && isN1SExt) 7399 NewOpc = ARMISD::VMULLs; 7400 else { 7401 bool isN0ZExt = isZeroExtended(N0, DAG); 7402 bool isN1ZExt = isZeroExtended(N1, DAG); 7403 if (isN0ZExt && isN1ZExt) 7404 NewOpc = ARMISD::VMULLu; 7405 else if (isN1SExt || isN1ZExt) { 7406 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7407 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7408 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7409 NewOpc = ARMISD::VMULLs; 7410 isMLA = true; 7411 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7412 NewOpc = ARMISD::VMULLu; 7413 isMLA = true; 7414 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7415 std::swap(N0, N1); 7416 NewOpc = ARMISD::VMULLu; 7417 isMLA = true; 7418 } 7419 } 7420 7421 if (!NewOpc) { 7422 if (VT == MVT::v2i64) 7423 // Fall through to expand this. It is not legal. 7424 return SDValue(); 7425 else 7426 // Other vector multiplications are legal. 7427 return Op; 7428 } 7429 } 7430 7431 // Legalize to a VMULL instruction. 7432 SDLoc DL(Op); 7433 SDValue Op0; 7434 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7435 if (!isMLA) { 7436 Op0 = SkipExtensionForVMULL(N0, DAG); 7437 assert(Op0.getValueType().is64BitVector() && 7438 Op1.getValueType().is64BitVector() && 7439 "unexpected types for extended operands to VMULL"); 7440 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7441 } 7442 7443 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7444 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7445 // vmull q0, d4, d6 7446 // vmlal q0, d5, d6 7447 // is faster than 7448 // vaddl q0, d4, d5 7449 // vmovl q1, d6 7450 // vmul q0, q0, q1 7451 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7452 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7453 EVT Op1VT = Op1.getValueType(); 7454 return DAG.getNode(N0->getOpcode(), DL, VT, 7455 DAG.getNode(NewOpc, DL, VT, 7456 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7457 DAG.getNode(NewOpc, DL, VT, 7458 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7459 } 7460 7461 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7462 SelectionDAG &DAG) { 7463 // TODO: Should this propagate fast-math-flags? 7464 7465 // Convert to float 7466 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7467 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7468 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7469 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7470 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7471 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7472 // Get reciprocal estimate. 7473 // float4 recip = vrecpeq_f32(yf); 7474 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7475 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7476 Y); 7477 // Because char has a smaller range than uchar, we can actually get away 7478 // without any newton steps. This requires that we use a weird bias 7479 // of 0xb000, however (again, this has been exhaustively tested). 7480 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7481 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7482 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7483 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7484 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7485 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7486 // Convert back to short. 7487 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7488 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7489 return X; 7490 } 7491 7492 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7493 SelectionDAG &DAG) { 7494 // TODO: Should this propagate fast-math-flags? 7495 7496 SDValue N2; 7497 // Convert to float. 7498 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7499 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7500 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7501 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7502 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7503 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7504 7505 // Use reciprocal estimate and one refinement step. 7506 // float4 recip = vrecpeq_f32(yf); 7507 // recip *= vrecpsq_f32(yf, recip); 7508 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7509 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7510 N1); 7511 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7512 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7513 N1, N2); 7514 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7515 // Because short has a smaller range than ushort, we can actually get away 7516 // with only a single newton step. This requires that we use a weird bias 7517 // of 89, however (again, this has been exhaustively tested). 7518 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7519 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7520 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7521 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7522 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7523 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7524 // Convert back to integer and return. 7525 // return vmovn_s32(vcvt_s32_f32(result)); 7526 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7527 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7528 return N0; 7529 } 7530 7531 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7532 EVT VT = Op.getValueType(); 7533 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7534 "unexpected type for custom-lowering ISD::SDIV"); 7535 7536 SDLoc dl(Op); 7537 SDValue N0 = Op.getOperand(0); 7538 SDValue N1 = Op.getOperand(1); 7539 SDValue N2, N3; 7540 7541 if (VT == MVT::v8i8) { 7542 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7543 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7544 7545 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7546 DAG.getIntPtrConstant(4, dl)); 7547 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7548 DAG.getIntPtrConstant(4, dl)); 7549 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7550 DAG.getIntPtrConstant(0, dl)); 7551 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7552 DAG.getIntPtrConstant(0, dl)); 7553 7554 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7555 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7556 7557 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7558 N0 = LowerCONCAT_VECTORS(N0, DAG); 7559 7560 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7561 return N0; 7562 } 7563 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7564 } 7565 7566 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7567 // TODO: Should this propagate fast-math-flags? 7568 EVT VT = Op.getValueType(); 7569 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7570 "unexpected type for custom-lowering ISD::UDIV"); 7571 7572 SDLoc dl(Op); 7573 SDValue N0 = Op.getOperand(0); 7574 SDValue N1 = Op.getOperand(1); 7575 SDValue N2, N3; 7576 7577 if (VT == MVT::v8i8) { 7578 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7579 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7580 7581 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7582 DAG.getIntPtrConstant(4, dl)); 7583 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7584 DAG.getIntPtrConstant(4, dl)); 7585 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7586 DAG.getIntPtrConstant(0, dl)); 7587 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7588 DAG.getIntPtrConstant(0, dl)); 7589 7590 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7591 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7592 7593 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7594 N0 = LowerCONCAT_VECTORS(N0, DAG); 7595 7596 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7597 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7598 MVT::i32), 7599 N0); 7600 return N0; 7601 } 7602 7603 // v4i16 sdiv ... Convert to float. 7604 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7605 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7606 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7607 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7608 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7609 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7610 7611 // Use reciprocal estimate and two refinement steps. 7612 // float4 recip = vrecpeq_f32(yf); 7613 // recip *= vrecpsq_f32(yf, recip); 7614 // recip *= vrecpsq_f32(yf, recip); 7615 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7616 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7617 BN1); 7618 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7619 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7620 BN1, N2); 7621 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7622 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7623 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7624 BN1, N2); 7625 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7626 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7627 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7628 // and that it will never cause us to return an answer too large). 7629 // float4 result = as_float4(as_int4(xf*recip) + 2); 7630 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7631 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7632 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7633 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7634 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7635 // Convert back to integer and return. 7636 // return vmovn_u32(vcvt_s32_f32(result)); 7637 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7638 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7639 return N0; 7640 } 7641 7642 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7643 SDNode *N = Op.getNode(); 7644 EVT VT = N->getValueType(0); 7645 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7646 7647 SDValue Carry = Op.getOperand(2); 7648 7649 SDLoc DL(Op); 7650 7651 SDValue Result; 7652 if (Op.getOpcode() == ISD::ADDCARRY) { 7653 // This converts the boolean value carry into the carry flag. 7654 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7655 7656 // Do the addition proper using the carry flag we wanted. 7657 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7658 Op.getOperand(1), Carry); 7659 7660 // Now convert the carry flag into a boolean value. 7661 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7662 } else { 7663 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7664 // have to invert the carry first. 7665 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7666 DAG.getConstant(1, DL, MVT::i32), Carry); 7667 // This converts the boolean value carry into the carry flag. 7668 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7669 7670 // Do the subtraction proper using the carry flag we wanted. 7671 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7672 Op.getOperand(1), Carry); 7673 7674 // Now convert the carry flag into a boolean value. 7675 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7676 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7677 // by ISD::SUBCARRY, so compute 1 - C. 7678 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7679 DAG.getConstant(1, DL, MVT::i32), Carry); 7680 } 7681 7682 // Return both values. 7683 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7684 } 7685 7686 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7687 assert(Subtarget->isTargetDarwin()); 7688 7689 // For iOS, we want to call an alternative entry point: __sincos_stret, 7690 // return values are passed via sret. 7691 SDLoc dl(Op); 7692 SDValue Arg = Op.getOperand(0); 7693 EVT ArgVT = Arg.getValueType(); 7694 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7695 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7696 7697 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7699 7700 // Pair of floats / doubles used to pass the result. 7701 Type *RetTy = StructType::get(ArgTy, ArgTy); 7702 auto &DL = DAG.getDataLayout(); 7703 7704 ArgListTy Args; 7705 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7706 SDValue SRet; 7707 if (ShouldUseSRet) { 7708 // Create stack object for sret. 7709 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7710 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7711 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7712 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7713 7714 ArgListEntry Entry; 7715 Entry.Node = SRet; 7716 Entry.Ty = RetTy->getPointerTo(); 7717 Entry.IsSExt = false; 7718 Entry.IsZExt = false; 7719 Entry.IsSRet = true; 7720 Args.push_back(Entry); 7721 RetTy = Type::getVoidTy(*DAG.getContext()); 7722 } 7723 7724 ArgListEntry Entry; 7725 Entry.Node = Arg; 7726 Entry.Ty = ArgTy; 7727 Entry.IsSExt = false; 7728 Entry.IsZExt = false; 7729 Args.push_back(Entry); 7730 7731 RTLIB::Libcall LC = 7732 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 7733 const char *LibcallName = getLibcallName(LC); 7734 CallingConv::ID CC = getLibcallCallingConv(LC); 7735 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7736 7737 TargetLowering::CallLoweringInfo CLI(DAG); 7738 CLI.setDebugLoc(dl) 7739 .setChain(DAG.getEntryNode()) 7740 .setCallee(CC, RetTy, Callee, std::move(Args)) 7741 .setDiscardResult(ShouldUseSRet); 7742 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7743 7744 if (!ShouldUseSRet) 7745 return CallResult.first; 7746 7747 SDValue LoadSin = 7748 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7749 7750 // Address of cos field. 7751 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7752 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7753 SDValue LoadCos = 7754 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7755 7756 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7757 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7758 LoadSin.getValue(0), LoadCos.getValue(0)); 7759 } 7760 7761 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7762 bool Signed, 7763 SDValue &Chain) const { 7764 EVT VT = Op.getValueType(); 7765 assert((VT == MVT::i32 || VT == MVT::i64) && 7766 "unexpected type for custom lowering DIV"); 7767 SDLoc dl(Op); 7768 7769 const auto &DL = DAG.getDataLayout(); 7770 const auto &TLI = DAG.getTargetLoweringInfo(); 7771 7772 const char *Name = nullptr; 7773 if (Signed) 7774 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7775 else 7776 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7777 7778 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7779 7780 ARMTargetLowering::ArgListTy Args; 7781 7782 for (auto AI : {1, 0}) { 7783 ArgListEntry Arg; 7784 Arg.Node = Op.getOperand(AI); 7785 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7786 Args.push_back(Arg); 7787 } 7788 7789 CallLoweringInfo CLI(DAG); 7790 CLI.setDebugLoc(dl) 7791 .setChain(Chain) 7792 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7793 ES, std::move(Args)); 7794 7795 return LowerCallTo(CLI).first; 7796 } 7797 7798 // This is a code size optimisation: return the original SDIV node to 7799 // DAGCombiner when we don't want to expand SDIV into a sequence of 7800 // instructions, and an empty node otherwise which will cause the 7801 // SDIV to be expanded in DAGCombine. 7802 SDValue 7803 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 7804 SelectionDAG &DAG, 7805 SmallVectorImpl<SDNode *> &Created) const { 7806 // TODO: Support SREM 7807 if (N->getOpcode() != ISD::SDIV) 7808 return SDValue(); 7809 7810 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 7811 const bool MinSize = ST.optForMinSize(); 7812 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 7813 : ST.hasDivideInARMMode(); 7814 7815 // Don't touch vector types; rewriting this may lead to scalarizing 7816 // the int divs. 7817 if (N->getOperand(0).getValueType().isVector()) 7818 return SDValue(); 7819 7820 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 7821 // hwdiv support for this to be really profitable. 7822 if (!(MinSize && HasDivide)) 7823 return SDValue(); 7824 7825 // ARM mode is a bit simpler than Thumb: we can handle large power 7826 // of 2 immediates with 1 mov instruction; no further checks required, 7827 // just return the sdiv node. 7828 if (!ST.isThumb()) 7829 return SDValue(N, 0); 7830 7831 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 7832 // and thus lose the code size benefits of a MOVS that requires only 2. 7833 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 7834 // but as it's doing exactly this, it's not worth the trouble to get TTI. 7835 if (Divisor.sgt(128)) 7836 return SDValue(); 7837 7838 return SDValue(N, 0); 7839 } 7840 7841 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7842 bool Signed) const { 7843 assert(Op.getValueType() == MVT::i32 && 7844 "unexpected type for custom lowering DIV"); 7845 SDLoc dl(Op); 7846 7847 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7848 DAG.getEntryNode(), Op.getOperand(1)); 7849 7850 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7851 } 7852 7853 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7854 SDLoc DL(N); 7855 SDValue Op = N->getOperand(1); 7856 if (N->getValueType(0) == MVT::i32) 7857 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7858 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7859 DAG.getConstant(0, DL, MVT::i32)); 7860 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7861 DAG.getConstant(1, DL, MVT::i32)); 7862 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7863 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7864 } 7865 7866 void ARMTargetLowering::ExpandDIV_Windows( 7867 SDValue Op, SelectionDAG &DAG, bool Signed, 7868 SmallVectorImpl<SDValue> &Results) const { 7869 const auto &DL = DAG.getDataLayout(); 7870 const auto &TLI = DAG.getTargetLoweringInfo(); 7871 7872 assert(Op.getValueType() == MVT::i64 && 7873 "unexpected type for custom lowering DIV"); 7874 SDLoc dl(Op); 7875 7876 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7877 7878 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7879 7880 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7881 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7882 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7883 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7884 7885 Results.push_back(Lower); 7886 Results.push_back(Upper); 7887 } 7888 7889 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7890 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7891 // Acquire/Release load/store is not legal for targets without a dmb or 7892 // equivalent available. 7893 return SDValue(); 7894 7895 // Monotonic load/store is legal for all targets. 7896 return Op; 7897 } 7898 7899 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7900 SmallVectorImpl<SDValue> &Results, 7901 SelectionDAG &DAG, 7902 const ARMSubtarget *Subtarget) { 7903 SDLoc DL(N); 7904 // Under Power Management extensions, the cycle-count is: 7905 // mrc p15, #0, <Rt>, c9, c13, #0 7906 SDValue Ops[] = { N->getOperand(0), // Chain 7907 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7908 DAG.getConstant(15, DL, MVT::i32), 7909 DAG.getConstant(0, DL, MVT::i32), 7910 DAG.getConstant(9, DL, MVT::i32), 7911 DAG.getConstant(13, DL, MVT::i32), 7912 DAG.getConstant(0, DL, MVT::i32) 7913 }; 7914 7915 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7916 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7917 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7918 DAG.getConstant(0, DL, MVT::i32))); 7919 Results.push_back(Cycles32.getValue(1)); 7920 } 7921 7922 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7923 SDLoc dl(V.getNode()); 7924 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7925 SDValue VHi = DAG.getAnyExtOrTrunc( 7926 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7927 dl, MVT::i32); 7928 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7929 if (isBigEndian) 7930 std::swap (VLo, VHi); 7931 SDValue RegClass = 7932 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7933 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7934 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7935 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7936 return SDValue( 7937 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7938 } 7939 7940 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7941 SmallVectorImpl<SDValue> & Results, 7942 SelectionDAG &DAG) { 7943 assert(N->getValueType(0) == MVT::i64 && 7944 "AtomicCmpSwap on types less than 64 should be legal"); 7945 SDValue Ops[] = {N->getOperand(1), 7946 createGPRPairNode(DAG, N->getOperand(2)), 7947 createGPRPairNode(DAG, N->getOperand(3)), 7948 N->getOperand(0)}; 7949 SDNode *CmpSwap = DAG.getMachineNode( 7950 ARM::CMP_SWAP_64, SDLoc(N), 7951 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7952 7953 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 7954 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 7955 7956 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7957 7958 Results.push_back( 7959 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 7960 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7961 Results.push_back( 7962 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 7963 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7964 Results.push_back(SDValue(CmpSwap, 2)); 7965 } 7966 7967 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7968 SelectionDAG &DAG) { 7969 const auto &TLI = DAG.getTargetLoweringInfo(); 7970 7971 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7972 "Custom lowering is MSVCRT specific!"); 7973 7974 SDLoc dl(Op); 7975 SDValue Val = Op.getOperand(0); 7976 MVT Ty = Val->getSimpleValueType(0); 7977 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7978 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7979 TLI.getPointerTy(DAG.getDataLayout())); 7980 7981 TargetLowering::ArgListTy Args; 7982 TargetLowering::ArgListEntry Entry; 7983 7984 Entry.Node = Val; 7985 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7986 Entry.IsZExt = true; 7987 Args.push_back(Entry); 7988 7989 Entry.Node = Exponent; 7990 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7991 Entry.IsZExt = true; 7992 Args.push_back(Entry); 7993 7994 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7995 7996 // In the in-chain to the call is the entry node If we are emitting a 7997 // tailcall, the chain will be mutated if the node has a non-entry input 7998 // chain. 7999 SDValue InChain = DAG.getEntryNode(); 8000 SDValue TCChain = InChain; 8001 8002 const Function &F = DAG.getMachineFunction().getFunction(); 8003 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8004 F.getReturnType() == LCRTy; 8005 if (IsTC) 8006 InChain = TCChain; 8007 8008 TargetLowering::CallLoweringInfo CLI(DAG); 8009 CLI.setDebugLoc(dl) 8010 .setChain(InChain) 8011 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8012 .setTailCall(IsTC); 8013 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8014 8015 // Return the chain (the DAG root) if it is a tail call 8016 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8017 } 8018 8019 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8020 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8021 switch (Op.getOpcode()) { 8022 default: llvm_unreachable("Don't know how to custom lower this!"); 8023 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8024 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8025 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8026 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8027 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8028 case ISD::SELECT: return LowerSELECT(Op, DAG); 8029 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8030 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8031 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8032 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8033 case ISD::VASTART: return LowerVASTART(Op, DAG); 8034 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8035 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8036 case ISD::SINT_TO_FP: 8037 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8038 case ISD::FP_TO_SINT: 8039 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8040 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8041 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8042 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8043 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8044 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8045 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8046 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8047 Subtarget); 8048 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8049 case ISD::SHL: 8050 case ISD::SRL: 8051 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8052 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8053 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8054 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8055 case ISD::SRL_PARTS: 8056 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8057 case ISD::CTTZ: 8058 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8059 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8060 case ISD::SETCC: return LowerVSETCC(Op, DAG); 8061 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8062 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8063 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8064 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 8065 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8066 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8067 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 8068 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8069 case ISD::MUL: return LowerMUL(Op, DAG); 8070 case ISD::SDIV: 8071 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8072 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8073 return LowerSDIV(Op, DAG); 8074 case ISD::UDIV: 8075 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8076 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8077 return LowerUDIV(Op, DAG); 8078 case ISD::ADDCARRY: 8079 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8080 case ISD::SADDO: 8081 case ISD::SSUBO: 8082 return LowerSignedALUO(Op, DAG); 8083 case ISD::UADDO: 8084 case ISD::USUBO: 8085 return LowerUnsignedALUO(Op, DAG); 8086 case ISD::ATOMIC_LOAD: 8087 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8088 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8089 case ISD::SDIVREM: 8090 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8091 case ISD::DYNAMIC_STACKALLOC: 8092 if (Subtarget->isTargetWindows()) 8093 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8094 llvm_unreachable("Don't know how to custom lower this!"); 8095 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8096 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8097 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8098 case ARMISD::WIN__DBZCHK: return SDValue(); 8099 } 8100 } 8101 8102 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8103 SelectionDAG &DAG) { 8104 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8105 unsigned Opc = 0; 8106 if (IntNo == Intrinsic::arm_smlald) 8107 Opc = ARMISD::SMLALD; 8108 else if (IntNo == Intrinsic::arm_smlaldx) 8109 Opc = ARMISD::SMLALDX; 8110 else if (IntNo == Intrinsic::arm_smlsld) 8111 Opc = ARMISD::SMLSLD; 8112 else if (IntNo == Intrinsic::arm_smlsldx) 8113 Opc = ARMISD::SMLSLDX; 8114 else 8115 return; 8116 8117 SDLoc dl(N); 8118 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8119 N->getOperand(3), 8120 DAG.getConstant(0, dl, MVT::i32)); 8121 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8122 N->getOperand(3), 8123 DAG.getConstant(1, dl, MVT::i32)); 8124 8125 SDValue LongMul = DAG.getNode(Opc, dl, 8126 DAG.getVTList(MVT::i32, MVT::i32), 8127 N->getOperand(1), N->getOperand(2), 8128 Lo, Hi); 8129 Results.push_back(LongMul.getValue(0)); 8130 Results.push_back(LongMul.getValue(1)); 8131 } 8132 8133 /// ReplaceNodeResults - Replace the results of node with an illegal result 8134 /// type with new values built out of custom code. 8135 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8136 SmallVectorImpl<SDValue> &Results, 8137 SelectionDAG &DAG) const { 8138 SDValue Res; 8139 switch (N->getOpcode()) { 8140 default: 8141 llvm_unreachable("Don't know how to custom expand this!"); 8142 case ISD::READ_REGISTER: 8143 ExpandREAD_REGISTER(N, Results, DAG); 8144 break; 8145 case ISD::BITCAST: 8146 Res = ExpandBITCAST(N, DAG, Subtarget); 8147 break; 8148 case ISD::SRL: 8149 case ISD::SRA: 8150 Res = Expand64BitShift(N, DAG, Subtarget); 8151 break; 8152 case ISD::SREM: 8153 case ISD::UREM: 8154 Res = LowerREM(N, DAG); 8155 break; 8156 case ISD::SDIVREM: 8157 case ISD::UDIVREM: 8158 Res = LowerDivRem(SDValue(N, 0), DAG); 8159 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8160 Results.push_back(Res.getValue(0)); 8161 Results.push_back(Res.getValue(1)); 8162 return; 8163 case ISD::READCYCLECOUNTER: 8164 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8165 return; 8166 case ISD::UDIV: 8167 case ISD::SDIV: 8168 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8169 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8170 Results); 8171 case ISD::ATOMIC_CMP_SWAP: 8172 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8173 return; 8174 case ISD::INTRINSIC_WO_CHAIN: 8175 return ReplaceLongIntrinsic(N, Results, DAG); 8176 } 8177 if (Res.getNode()) 8178 Results.push_back(Res); 8179 } 8180 8181 //===----------------------------------------------------------------------===// 8182 // ARM Scheduler Hooks 8183 //===----------------------------------------------------------------------===// 8184 8185 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8186 /// registers the function context. 8187 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8188 MachineBasicBlock *MBB, 8189 MachineBasicBlock *DispatchBB, 8190 int FI) const { 8191 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8192 "ROPI/RWPI not currently supported with SjLj"); 8193 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8194 DebugLoc dl = MI.getDebugLoc(); 8195 MachineFunction *MF = MBB->getParent(); 8196 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8197 MachineConstantPool *MCP = MF->getConstantPool(); 8198 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8199 const Function &F = MF->getFunction(); 8200 8201 bool isThumb = Subtarget->isThumb(); 8202 bool isThumb2 = Subtarget->isThumb2(); 8203 8204 unsigned PCLabelId = AFI->createPICLabelUId(); 8205 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8206 ARMConstantPoolValue *CPV = 8207 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8208 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8209 8210 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8211 : &ARM::GPRRegClass; 8212 8213 // Grab constant pool and fixed stack memory operands. 8214 MachineMemOperand *CPMMO = 8215 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8216 MachineMemOperand::MOLoad, 4, 4); 8217 8218 MachineMemOperand *FIMMOSt = 8219 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8220 MachineMemOperand::MOStore, 4, 4); 8221 8222 // Load the address of the dispatch MBB into the jump buffer. 8223 if (isThumb2) { 8224 // Incoming value: jbuf 8225 // ldr.n r5, LCPI1_1 8226 // orr r5, r5, #1 8227 // add r5, pc 8228 // str r5, [$jbuf, #+4] ; &jbuf[1] 8229 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8230 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8231 .addConstantPoolIndex(CPI) 8232 .addMemOperand(CPMMO) 8233 .add(predOps(ARMCC::AL)); 8234 // Set the low bit because of thumb mode. 8235 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8236 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8237 .addReg(NewVReg1, RegState::Kill) 8238 .addImm(0x01) 8239 .add(predOps(ARMCC::AL)) 8240 .add(condCodeOp()); 8241 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8242 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8243 .addReg(NewVReg2, RegState::Kill) 8244 .addImm(PCLabelId); 8245 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8246 .addReg(NewVReg3, RegState::Kill) 8247 .addFrameIndex(FI) 8248 .addImm(36) // &jbuf[1] :: pc 8249 .addMemOperand(FIMMOSt) 8250 .add(predOps(ARMCC::AL)); 8251 } else if (isThumb) { 8252 // Incoming value: jbuf 8253 // ldr.n r1, LCPI1_4 8254 // add r1, pc 8255 // mov r2, #1 8256 // orrs r1, r2 8257 // add r2, $jbuf, #+4 ; &jbuf[1] 8258 // str r1, [r2] 8259 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8260 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8261 .addConstantPoolIndex(CPI) 8262 .addMemOperand(CPMMO) 8263 .add(predOps(ARMCC::AL)); 8264 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8265 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8266 .addReg(NewVReg1, RegState::Kill) 8267 .addImm(PCLabelId); 8268 // Set the low bit because of thumb mode. 8269 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8270 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8271 .addReg(ARM::CPSR, RegState::Define) 8272 .addImm(1) 8273 .add(predOps(ARMCC::AL)); 8274 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8275 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8276 .addReg(ARM::CPSR, RegState::Define) 8277 .addReg(NewVReg2, RegState::Kill) 8278 .addReg(NewVReg3, RegState::Kill) 8279 .add(predOps(ARMCC::AL)); 8280 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8281 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8282 .addFrameIndex(FI) 8283 .addImm(36); // &jbuf[1] :: pc 8284 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8285 .addReg(NewVReg4, RegState::Kill) 8286 .addReg(NewVReg5, RegState::Kill) 8287 .addImm(0) 8288 .addMemOperand(FIMMOSt) 8289 .add(predOps(ARMCC::AL)); 8290 } else { 8291 // Incoming value: jbuf 8292 // ldr r1, LCPI1_1 8293 // add r1, pc, r1 8294 // str r1, [$jbuf, #+4] ; &jbuf[1] 8295 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8296 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8297 .addConstantPoolIndex(CPI) 8298 .addImm(0) 8299 .addMemOperand(CPMMO) 8300 .add(predOps(ARMCC::AL)); 8301 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8302 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8303 .addReg(NewVReg1, RegState::Kill) 8304 .addImm(PCLabelId) 8305 .add(predOps(ARMCC::AL)); 8306 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8307 .addReg(NewVReg2, RegState::Kill) 8308 .addFrameIndex(FI) 8309 .addImm(36) // &jbuf[1] :: pc 8310 .addMemOperand(FIMMOSt) 8311 .add(predOps(ARMCC::AL)); 8312 } 8313 } 8314 8315 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8316 MachineBasicBlock *MBB) const { 8317 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8318 DebugLoc dl = MI.getDebugLoc(); 8319 MachineFunction *MF = MBB->getParent(); 8320 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8321 MachineFrameInfo &MFI = MF->getFrameInfo(); 8322 int FI = MFI.getFunctionContextIndex(); 8323 8324 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8325 : &ARM::GPRnopcRegClass; 8326 8327 // Get a mapping of the call site numbers to all of the landing pads they're 8328 // associated with. 8329 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8330 unsigned MaxCSNum = 0; 8331 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8332 ++BB) { 8333 if (!BB->isEHPad()) continue; 8334 8335 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8336 // pad. 8337 for (MachineBasicBlock::iterator 8338 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8339 if (!II->isEHLabel()) continue; 8340 8341 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8342 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8343 8344 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8345 for (SmallVectorImpl<unsigned>::iterator 8346 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8347 CSI != CSE; ++CSI) { 8348 CallSiteNumToLPad[*CSI].push_back(&*BB); 8349 MaxCSNum = std::max(MaxCSNum, *CSI); 8350 } 8351 break; 8352 } 8353 } 8354 8355 // Get an ordered list of the machine basic blocks for the jump table. 8356 std::vector<MachineBasicBlock*> LPadList; 8357 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8358 LPadList.reserve(CallSiteNumToLPad.size()); 8359 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8360 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8361 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8362 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8363 LPadList.push_back(*II); 8364 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8365 } 8366 } 8367 8368 assert(!LPadList.empty() && 8369 "No landing pad destinations for the dispatch jump table!"); 8370 8371 // Create the jump table and associated information. 8372 MachineJumpTableInfo *JTI = 8373 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8374 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8375 8376 // Create the MBBs for the dispatch code. 8377 8378 // Shove the dispatch's address into the return slot in the function context. 8379 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8380 DispatchBB->setIsEHPad(); 8381 8382 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8383 unsigned trap_opcode; 8384 if (Subtarget->isThumb()) 8385 trap_opcode = ARM::tTRAP; 8386 else 8387 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8388 8389 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8390 DispatchBB->addSuccessor(TrapBB); 8391 8392 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8393 DispatchBB->addSuccessor(DispContBB); 8394 8395 // Insert and MBBs. 8396 MF->insert(MF->end(), DispatchBB); 8397 MF->insert(MF->end(), DispContBB); 8398 MF->insert(MF->end(), TrapBB); 8399 8400 // Insert code into the entry block that creates and registers the function 8401 // context. 8402 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8403 8404 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8405 MachinePointerInfo::getFixedStack(*MF, FI), 8406 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8407 8408 MachineInstrBuilder MIB; 8409 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8410 8411 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8412 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8413 8414 // Add a register mask with no preserved registers. This results in all 8415 // registers being marked as clobbered. This can't work if the dispatch block 8416 // is in a Thumb1 function and is linked with ARM code which uses the FP 8417 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8418 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8419 8420 bool IsPositionIndependent = isPositionIndependent(); 8421 unsigned NumLPads = LPadList.size(); 8422 if (Subtarget->isThumb2()) { 8423 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8424 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8425 .addFrameIndex(FI) 8426 .addImm(4) 8427 .addMemOperand(FIMMOLd) 8428 .add(predOps(ARMCC::AL)); 8429 8430 if (NumLPads < 256) { 8431 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8432 .addReg(NewVReg1) 8433 .addImm(LPadList.size()) 8434 .add(predOps(ARMCC::AL)); 8435 } else { 8436 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8437 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8438 .addImm(NumLPads & 0xFFFF) 8439 .add(predOps(ARMCC::AL)); 8440 8441 unsigned VReg2 = VReg1; 8442 if ((NumLPads & 0xFFFF0000) != 0) { 8443 VReg2 = MRI->createVirtualRegister(TRC); 8444 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8445 .addReg(VReg1) 8446 .addImm(NumLPads >> 16) 8447 .add(predOps(ARMCC::AL)); 8448 } 8449 8450 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8451 .addReg(NewVReg1) 8452 .addReg(VReg2) 8453 .add(predOps(ARMCC::AL)); 8454 } 8455 8456 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8457 .addMBB(TrapBB) 8458 .addImm(ARMCC::HI) 8459 .addReg(ARM::CPSR); 8460 8461 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8462 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8463 .addJumpTableIndex(MJTI) 8464 .add(predOps(ARMCC::AL)); 8465 8466 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8467 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8468 .addReg(NewVReg3, RegState::Kill) 8469 .addReg(NewVReg1) 8470 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8471 .add(predOps(ARMCC::AL)) 8472 .add(condCodeOp()); 8473 8474 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8475 .addReg(NewVReg4, RegState::Kill) 8476 .addReg(NewVReg1) 8477 .addJumpTableIndex(MJTI); 8478 } else if (Subtarget->isThumb()) { 8479 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8480 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8481 .addFrameIndex(FI) 8482 .addImm(1) 8483 .addMemOperand(FIMMOLd) 8484 .add(predOps(ARMCC::AL)); 8485 8486 if (NumLPads < 256) { 8487 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8488 .addReg(NewVReg1) 8489 .addImm(NumLPads) 8490 .add(predOps(ARMCC::AL)); 8491 } else { 8492 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8493 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8494 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8495 8496 // MachineConstantPool wants an explicit alignment. 8497 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8498 if (Align == 0) 8499 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8500 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8501 8502 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8503 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8504 .addReg(VReg1, RegState::Define) 8505 .addConstantPoolIndex(Idx) 8506 .add(predOps(ARMCC::AL)); 8507 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8508 .addReg(NewVReg1) 8509 .addReg(VReg1) 8510 .add(predOps(ARMCC::AL)); 8511 } 8512 8513 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8514 .addMBB(TrapBB) 8515 .addImm(ARMCC::HI) 8516 .addReg(ARM::CPSR); 8517 8518 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8519 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8520 .addReg(ARM::CPSR, RegState::Define) 8521 .addReg(NewVReg1) 8522 .addImm(2) 8523 .add(predOps(ARMCC::AL)); 8524 8525 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8526 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8527 .addJumpTableIndex(MJTI) 8528 .add(predOps(ARMCC::AL)); 8529 8530 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8531 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8532 .addReg(ARM::CPSR, RegState::Define) 8533 .addReg(NewVReg2, RegState::Kill) 8534 .addReg(NewVReg3) 8535 .add(predOps(ARMCC::AL)); 8536 8537 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8538 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8539 8540 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8541 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8542 .addReg(NewVReg4, RegState::Kill) 8543 .addImm(0) 8544 .addMemOperand(JTMMOLd) 8545 .add(predOps(ARMCC::AL)); 8546 8547 unsigned NewVReg6 = NewVReg5; 8548 if (IsPositionIndependent) { 8549 NewVReg6 = MRI->createVirtualRegister(TRC); 8550 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8551 .addReg(ARM::CPSR, RegState::Define) 8552 .addReg(NewVReg5, RegState::Kill) 8553 .addReg(NewVReg3) 8554 .add(predOps(ARMCC::AL)); 8555 } 8556 8557 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8558 .addReg(NewVReg6, RegState::Kill) 8559 .addJumpTableIndex(MJTI); 8560 } else { 8561 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8562 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8563 .addFrameIndex(FI) 8564 .addImm(4) 8565 .addMemOperand(FIMMOLd) 8566 .add(predOps(ARMCC::AL)); 8567 8568 if (NumLPads < 256) { 8569 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8570 .addReg(NewVReg1) 8571 .addImm(NumLPads) 8572 .add(predOps(ARMCC::AL)); 8573 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8574 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8575 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8576 .addImm(NumLPads & 0xFFFF) 8577 .add(predOps(ARMCC::AL)); 8578 8579 unsigned VReg2 = VReg1; 8580 if ((NumLPads & 0xFFFF0000) != 0) { 8581 VReg2 = MRI->createVirtualRegister(TRC); 8582 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8583 .addReg(VReg1) 8584 .addImm(NumLPads >> 16) 8585 .add(predOps(ARMCC::AL)); 8586 } 8587 8588 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8589 .addReg(NewVReg1) 8590 .addReg(VReg2) 8591 .add(predOps(ARMCC::AL)); 8592 } else { 8593 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8594 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8595 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8596 8597 // MachineConstantPool wants an explicit alignment. 8598 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8599 if (Align == 0) 8600 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8601 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8602 8603 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8604 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8605 .addReg(VReg1, RegState::Define) 8606 .addConstantPoolIndex(Idx) 8607 .addImm(0) 8608 .add(predOps(ARMCC::AL)); 8609 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8610 .addReg(NewVReg1) 8611 .addReg(VReg1, RegState::Kill) 8612 .add(predOps(ARMCC::AL)); 8613 } 8614 8615 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8616 .addMBB(TrapBB) 8617 .addImm(ARMCC::HI) 8618 .addReg(ARM::CPSR); 8619 8620 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8621 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8622 .addReg(NewVReg1) 8623 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8624 .add(predOps(ARMCC::AL)) 8625 .add(condCodeOp()); 8626 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8627 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8628 .addJumpTableIndex(MJTI) 8629 .add(predOps(ARMCC::AL)); 8630 8631 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8632 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8633 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8634 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8635 .addReg(NewVReg3, RegState::Kill) 8636 .addReg(NewVReg4) 8637 .addImm(0) 8638 .addMemOperand(JTMMOLd) 8639 .add(predOps(ARMCC::AL)); 8640 8641 if (IsPositionIndependent) { 8642 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8643 .addReg(NewVReg5, RegState::Kill) 8644 .addReg(NewVReg4) 8645 .addJumpTableIndex(MJTI); 8646 } else { 8647 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8648 .addReg(NewVReg5, RegState::Kill) 8649 .addJumpTableIndex(MJTI); 8650 } 8651 } 8652 8653 // Add the jump table entries as successors to the MBB. 8654 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8655 for (std::vector<MachineBasicBlock*>::iterator 8656 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8657 MachineBasicBlock *CurMBB = *I; 8658 if (SeenMBBs.insert(CurMBB).second) 8659 DispContBB->addSuccessor(CurMBB); 8660 } 8661 8662 // N.B. the order the invoke BBs are processed in doesn't matter here. 8663 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8664 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8665 for (MachineBasicBlock *BB : InvokeBBs) { 8666 8667 // Remove the landing pad successor from the invoke block and replace it 8668 // with the new dispatch block. 8669 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8670 BB->succ_end()); 8671 while (!Successors.empty()) { 8672 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8673 if (SMBB->isEHPad()) { 8674 BB->removeSuccessor(SMBB); 8675 MBBLPads.push_back(SMBB); 8676 } 8677 } 8678 8679 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8680 BB->normalizeSuccProbs(); 8681 8682 // Find the invoke call and mark all of the callee-saved registers as 8683 // 'implicit defined' so that they're spilled. This prevents code from 8684 // moving instructions to before the EH block, where they will never be 8685 // executed. 8686 for (MachineBasicBlock::reverse_iterator 8687 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8688 if (!II->isCall()) continue; 8689 8690 DenseMap<unsigned, bool> DefRegs; 8691 for (MachineInstr::mop_iterator 8692 OI = II->operands_begin(), OE = II->operands_end(); 8693 OI != OE; ++OI) { 8694 if (!OI->isReg()) continue; 8695 DefRegs[OI->getReg()] = true; 8696 } 8697 8698 MachineInstrBuilder MIB(*MF, &*II); 8699 8700 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8701 unsigned Reg = SavedRegs[i]; 8702 if (Subtarget->isThumb2() && 8703 !ARM::tGPRRegClass.contains(Reg) && 8704 !ARM::hGPRRegClass.contains(Reg)) 8705 continue; 8706 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8707 continue; 8708 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8709 continue; 8710 if (!DefRegs[Reg]) 8711 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8712 } 8713 8714 break; 8715 } 8716 } 8717 8718 // Mark all former landing pads as non-landing pads. The dispatch is the only 8719 // landing pad now. 8720 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8721 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8722 (*I)->setIsEHPad(false); 8723 8724 // The instruction is gone now. 8725 MI.eraseFromParent(); 8726 } 8727 8728 static 8729 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8730 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8731 E = MBB->succ_end(); I != E; ++I) 8732 if (*I != Succ) 8733 return *I; 8734 llvm_unreachable("Expecting a BB with two successors!"); 8735 } 8736 8737 /// Return the load opcode for a given load size. If load size >= 8, 8738 /// neon opcode will be returned. 8739 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8740 if (LdSize >= 8) 8741 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8742 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8743 if (IsThumb1) 8744 return LdSize == 4 ? ARM::tLDRi 8745 : LdSize == 2 ? ARM::tLDRHi 8746 : LdSize == 1 ? ARM::tLDRBi : 0; 8747 if (IsThumb2) 8748 return LdSize == 4 ? ARM::t2LDR_POST 8749 : LdSize == 2 ? ARM::t2LDRH_POST 8750 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8751 return LdSize == 4 ? ARM::LDR_POST_IMM 8752 : LdSize == 2 ? ARM::LDRH_POST 8753 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8754 } 8755 8756 /// Return the store opcode for a given store size. If store size >= 8, 8757 /// neon opcode will be returned. 8758 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8759 if (StSize >= 8) 8760 return StSize == 16 ? ARM::VST1q32wb_fixed 8761 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8762 if (IsThumb1) 8763 return StSize == 4 ? ARM::tSTRi 8764 : StSize == 2 ? ARM::tSTRHi 8765 : StSize == 1 ? ARM::tSTRBi : 0; 8766 if (IsThumb2) 8767 return StSize == 4 ? ARM::t2STR_POST 8768 : StSize == 2 ? ARM::t2STRH_POST 8769 : StSize == 1 ? ARM::t2STRB_POST : 0; 8770 return StSize == 4 ? ARM::STR_POST_IMM 8771 : StSize == 2 ? ARM::STRH_POST 8772 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8773 } 8774 8775 /// Emit a post-increment load operation with given size. The instructions 8776 /// will be added to BB at Pos. 8777 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8778 const TargetInstrInfo *TII, const DebugLoc &dl, 8779 unsigned LdSize, unsigned Data, unsigned AddrIn, 8780 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8781 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8782 assert(LdOpc != 0 && "Should have a load opcode"); 8783 if (LdSize >= 8) { 8784 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8785 .addReg(AddrOut, RegState::Define) 8786 .addReg(AddrIn) 8787 .addImm(0) 8788 .add(predOps(ARMCC::AL)); 8789 } else if (IsThumb1) { 8790 // load + update AddrIn 8791 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8792 .addReg(AddrIn) 8793 .addImm(0) 8794 .add(predOps(ARMCC::AL)); 8795 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8796 .add(t1CondCodeOp()) 8797 .addReg(AddrIn) 8798 .addImm(LdSize) 8799 .add(predOps(ARMCC::AL)); 8800 } else if (IsThumb2) { 8801 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8802 .addReg(AddrOut, RegState::Define) 8803 .addReg(AddrIn) 8804 .addImm(LdSize) 8805 .add(predOps(ARMCC::AL)); 8806 } else { // arm 8807 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8808 .addReg(AddrOut, RegState::Define) 8809 .addReg(AddrIn) 8810 .addReg(0) 8811 .addImm(LdSize) 8812 .add(predOps(ARMCC::AL)); 8813 } 8814 } 8815 8816 /// Emit a post-increment store operation with given size. The instructions 8817 /// will be added to BB at Pos. 8818 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8819 const TargetInstrInfo *TII, const DebugLoc &dl, 8820 unsigned StSize, unsigned Data, unsigned AddrIn, 8821 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8822 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8823 assert(StOpc != 0 && "Should have a store opcode"); 8824 if (StSize >= 8) { 8825 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8826 .addReg(AddrIn) 8827 .addImm(0) 8828 .addReg(Data) 8829 .add(predOps(ARMCC::AL)); 8830 } else if (IsThumb1) { 8831 // store + update AddrIn 8832 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8833 .addReg(Data) 8834 .addReg(AddrIn) 8835 .addImm(0) 8836 .add(predOps(ARMCC::AL)); 8837 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8838 .add(t1CondCodeOp()) 8839 .addReg(AddrIn) 8840 .addImm(StSize) 8841 .add(predOps(ARMCC::AL)); 8842 } else if (IsThumb2) { 8843 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8844 .addReg(Data) 8845 .addReg(AddrIn) 8846 .addImm(StSize) 8847 .add(predOps(ARMCC::AL)); 8848 } else { // arm 8849 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8850 .addReg(Data) 8851 .addReg(AddrIn) 8852 .addReg(0) 8853 .addImm(StSize) 8854 .add(predOps(ARMCC::AL)); 8855 } 8856 } 8857 8858 MachineBasicBlock * 8859 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8860 MachineBasicBlock *BB) const { 8861 // This pseudo instruction has 3 operands: dst, src, size 8862 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8863 // Otherwise, we will generate unrolled scalar copies. 8864 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8865 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8866 MachineFunction::iterator It = ++BB->getIterator(); 8867 8868 unsigned dest = MI.getOperand(0).getReg(); 8869 unsigned src = MI.getOperand(1).getReg(); 8870 unsigned SizeVal = MI.getOperand(2).getImm(); 8871 unsigned Align = MI.getOperand(3).getImm(); 8872 DebugLoc dl = MI.getDebugLoc(); 8873 8874 MachineFunction *MF = BB->getParent(); 8875 MachineRegisterInfo &MRI = MF->getRegInfo(); 8876 unsigned UnitSize = 0; 8877 const TargetRegisterClass *TRC = nullptr; 8878 const TargetRegisterClass *VecTRC = nullptr; 8879 8880 bool IsThumb1 = Subtarget->isThumb1Only(); 8881 bool IsThumb2 = Subtarget->isThumb2(); 8882 bool IsThumb = Subtarget->isThumb(); 8883 8884 if (Align & 1) { 8885 UnitSize = 1; 8886 } else if (Align & 2) { 8887 UnitSize = 2; 8888 } else { 8889 // Check whether we can use NEON instructions. 8890 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 8891 Subtarget->hasNEON()) { 8892 if ((Align % 16 == 0) && SizeVal >= 16) 8893 UnitSize = 16; 8894 else if ((Align % 8 == 0) && SizeVal >= 8) 8895 UnitSize = 8; 8896 } 8897 // Can't use NEON instructions. 8898 if (UnitSize == 0) 8899 UnitSize = 4; 8900 } 8901 8902 // Select the correct opcode and register class for unit size load/store 8903 bool IsNeon = UnitSize >= 8; 8904 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8905 if (IsNeon) 8906 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8907 : UnitSize == 8 ? &ARM::DPRRegClass 8908 : nullptr; 8909 8910 unsigned BytesLeft = SizeVal % UnitSize; 8911 unsigned LoopSize = SizeVal - BytesLeft; 8912 8913 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8914 // Use LDR and STR to copy. 8915 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8916 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8917 unsigned srcIn = src; 8918 unsigned destIn = dest; 8919 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8920 unsigned srcOut = MRI.createVirtualRegister(TRC); 8921 unsigned destOut = MRI.createVirtualRegister(TRC); 8922 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8923 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8924 IsThumb1, IsThumb2); 8925 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8926 IsThumb1, IsThumb2); 8927 srcIn = srcOut; 8928 destIn = destOut; 8929 } 8930 8931 // Handle the leftover bytes with LDRB and STRB. 8932 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8933 // [destOut] = STRB_POST(scratch, destIn, 1) 8934 for (unsigned i = 0; i < BytesLeft; i++) { 8935 unsigned srcOut = MRI.createVirtualRegister(TRC); 8936 unsigned destOut = MRI.createVirtualRegister(TRC); 8937 unsigned scratch = MRI.createVirtualRegister(TRC); 8938 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8939 IsThumb1, IsThumb2); 8940 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8941 IsThumb1, IsThumb2); 8942 srcIn = srcOut; 8943 destIn = destOut; 8944 } 8945 MI.eraseFromParent(); // The instruction is gone now. 8946 return BB; 8947 } 8948 8949 // Expand the pseudo op to a loop. 8950 // thisMBB: 8951 // ... 8952 // movw varEnd, # --> with thumb2 8953 // movt varEnd, # 8954 // ldrcp varEnd, idx --> without thumb2 8955 // fallthrough --> loopMBB 8956 // loopMBB: 8957 // PHI varPhi, varEnd, varLoop 8958 // PHI srcPhi, src, srcLoop 8959 // PHI destPhi, dst, destLoop 8960 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8961 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8962 // subs varLoop, varPhi, #UnitSize 8963 // bne loopMBB 8964 // fallthrough --> exitMBB 8965 // exitMBB: 8966 // epilogue to handle left-over bytes 8967 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8968 // [destOut] = STRB_POST(scratch, destLoop, 1) 8969 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8970 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8971 MF->insert(It, loopMBB); 8972 MF->insert(It, exitMBB); 8973 8974 // Transfer the remainder of BB and its successor edges to exitMBB. 8975 exitMBB->splice(exitMBB->begin(), BB, 8976 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8977 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8978 8979 // Load an immediate to varEnd. 8980 unsigned varEnd = MRI.createVirtualRegister(TRC); 8981 if (Subtarget->useMovt()) { 8982 unsigned Vtmp = varEnd; 8983 if ((LoopSize & 0xFFFF0000) != 0) 8984 Vtmp = MRI.createVirtualRegister(TRC); 8985 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8986 .addImm(LoopSize & 0xFFFF) 8987 .add(predOps(ARMCC::AL)); 8988 8989 if ((LoopSize & 0xFFFF0000) != 0) 8990 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 8991 .addReg(Vtmp) 8992 .addImm(LoopSize >> 16) 8993 .add(predOps(ARMCC::AL)); 8994 } else { 8995 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8996 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8997 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8998 8999 // MachineConstantPool wants an explicit alignment. 9000 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9001 if (Align == 0) 9002 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9003 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9004 9005 if (IsThumb) 9006 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9007 .addReg(varEnd, RegState::Define) 9008 .addConstantPoolIndex(Idx) 9009 .add(predOps(ARMCC::AL)); 9010 else 9011 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9012 .addReg(varEnd, RegState::Define) 9013 .addConstantPoolIndex(Idx) 9014 .addImm(0) 9015 .add(predOps(ARMCC::AL)); 9016 } 9017 BB->addSuccessor(loopMBB); 9018 9019 // Generate the loop body: 9020 // varPhi = PHI(varLoop, varEnd) 9021 // srcPhi = PHI(srcLoop, src) 9022 // destPhi = PHI(destLoop, dst) 9023 MachineBasicBlock *entryBB = BB; 9024 BB = loopMBB; 9025 unsigned varLoop = MRI.createVirtualRegister(TRC); 9026 unsigned varPhi = MRI.createVirtualRegister(TRC); 9027 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9028 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9029 unsigned destLoop = MRI.createVirtualRegister(TRC); 9030 unsigned destPhi = MRI.createVirtualRegister(TRC); 9031 9032 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9033 .addReg(varLoop).addMBB(loopMBB) 9034 .addReg(varEnd).addMBB(entryBB); 9035 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9036 .addReg(srcLoop).addMBB(loopMBB) 9037 .addReg(src).addMBB(entryBB); 9038 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9039 .addReg(destLoop).addMBB(loopMBB) 9040 .addReg(dest).addMBB(entryBB); 9041 9042 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9043 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9044 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9045 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9046 IsThumb1, IsThumb2); 9047 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9048 IsThumb1, IsThumb2); 9049 9050 // Decrement loop variable by UnitSize. 9051 if (IsThumb1) { 9052 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9053 .add(t1CondCodeOp()) 9054 .addReg(varPhi) 9055 .addImm(UnitSize) 9056 .add(predOps(ARMCC::AL)); 9057 } else { 9058 MachineInstrBuilder MIB = 9059 BuildMI(*BB, BB->end(), dl, 9060 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9061 MIB.addReg(varPhi) 9062 .addImm(UnitSize) 9063 .add(predOps(ARMCC::AL)) 9064 .add(condCodeOp()); 9065 MIB->getOperand(5).setReg(ARM::CPSR); 9066 MIB->getOperand(5).setIsDef(true); 9067 } 9068 BuildMI(*BB, BB->end(), dl, 9069 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9070 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9071 9072 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9073 BB->addSuccessor(loopMBB); 9074 BB->addSuccessor(exitMBB); 9075 9076 // Add epilogue to handle BytesLeft. 9077 BB = exitMBB; 9078 auto StartOfExit = exitMBB->begin(); 9079 9080 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9081 // [destOut] = STRB_POST(scratch, destLoop, 1) 9082 unsigned srcIn = srcLoop; 9083 unsigned destIn = destLoop; 9084 for (unsigned i = 0; i < BytesLeft; i++) { 9085 unsigned srcOut = MRI.createVirtualRegister(TRC); 9086 unsigned destOut = MRI.createVirtualRegister(TRC); 9087 unsigned scratch = MRI.createVirtualRegister(TRC); 9088 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9089 IsThumb1, IsThumb2); 9090 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9091 IsThumb1, IsThumb2); 9092 srcIn = srcOut; 9093 destIn = destOut; 9094 } 9095 9096 MI.eraseFromParent(); // The instruction is gone now. 9097 return BB; 9098 } 9099 9100 MachineBasicBlock * 9101 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9102 MachineBasicBlock *MBB) const { 9103 const TargetMachine &TM = getTargetMachine(); 9104 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9105 DebugLoc DL = MI.getDebugLoc(); 9106 9107 assert(Subtarget->isTargetWindows() && 9108 "__chkstk is only supported on Windows"); 9109 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9110 9111 // __chkstk takes the number of words to allocate on the stack in R4, and 9112 // returns the stack adjustment in number of bytes in R4. This will not 9113 // clober any other registers (other than the obvious lr). 9114 // 9115 // Although, technically, IP should be considered a register which may be 9116 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9117 // thumb-2 environment, so there is no interworking required. As a result, we 9118 // do not expect a veneer to be emitted by the linker, clobbering IP. 9119 // 9120 // Each module receives its own copy of __chkstk, so no import thunk is 9121 // required, again, ensuring that IP is not clobbered. 9122 // 9123 // Finally, although some linkers may theoretically provide a trampoline for 9124 // out of range calls (which is quite common due to a 32M range limitation of 9125 // branches for Thumb), we can generate the long-call version via 9126 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9127 // IP. 9128 9129 switch (TM.getCodeModel()) { 9130 case CodeModel::Tiny: 9131 llvm_unreachable("Tiny code model not available on ARM."); 9132 case CodeModel::Small: 9133 case CodeModel::Medium: 9134 case CodeModel::Kernel: 9135 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9136 .add(predOps(ARMCC::AL)) 9137 .addExternalSymbol("__chkstk") 9138 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9139 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9140 .addReg(ARM::R12, 9141 RegState::Implicit | RegState::Define | RegState::Dead) 9142 .addReg(ARM::CPSR, 9143 RegState::Implicit | RegState::Define | RegState::Dead); 9144 break; 9145 case CodeModel::Large: { 9146 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9147 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9148 9149 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9150 .addExternalSymbol("__chkstk"); 9151 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9152 .add(predOps(ARMCC::AL)) 9153 .addReg(Reg, RegState::Kill) 9154 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9155 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9156 .addReg(ARM::R12, 9157 RegState::Implicit | RegState::Define | RegState::Dead) 9158 .addReg(ARM::CPSR, 9159 RegState::Implicit | RegState::Define | RegState::Dead); 9160 break; 9161 } 9162 } 9163 9164 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9165 .addReg(ARM::SP, RegState::Kill) 9166 .addReg(ARM::R4, RegState::Kill) 9167 .setMIFlags(MachineInstr::FrameSetup) 9168 .add(predOps(ARMCC::AL)) 9169 .add(condCodeOp()); 9170 9171 MI.eraseFromParent(); 9172 return MBB; 9173 } 9174 9175 MachineBasicBlock * 9176 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9177 MachineBasicBlock *MBB) const { 9178 DebugLoc DL = MI.getDebugLoc(); 9179 MachineFunction *MF = MBB->getParent(); 9180 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9181 9182 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9183 MF->insert(++MBB->getIterator(), ContBB); 9184 ContBB->splice(ContBB->begin(), MBB, 9185 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9186 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9187 MBB->addSuccessor(ContBB); 9188 9189 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9190 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9191 MF->push_back(TrapBB); 9192 MBB->addSuccessor(TrapBB); 9193 9194 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9195 .addReg(MI.getOperand(0).getReg()) 9196 .addImm(0) 9197 .add(predOps(ARMCC::AL)); 9198 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9199 .addMBB(TrapBB) 9200 .addImm(ARMCC::EQ) 9201 .addReg(ARM::CPSR); 9202 9203 MI.eraseFromParent(); 9204 return ContBB; 9205 } 9206 9207 // The CPSR operand of SelectItr might be missing a kill marker 9208 // because there were multiple uses of CPSR, and ISel didn't know 9209 // which to mark. Figure out whether SelectItr should have had a 9210 // kill marker, and set it if it should. Returns the correct kill 9211 // marker value. 9212 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 9213 MachineBasicBlock* BB, 9214 const TargetRegisterInfo* TRI) { 9215 // Scan forward through BB for a use/def of CPSR. 9216 MachineBasicBlock::iterator miI(std::next(SelectItr)); 9217 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 9218 const MachineInstr& mi = *miI; 9219 if (mi.readsRegister(ARM::CPSR)) 9220 return false; 9221 if (mi.definesRegister(ARM::CPSR)) 9222 break; // Should have kill-flag - update below. 9223 } 9224 9225 // If we hit the end of the block, check whether CPSR is live into a 9226 // successor. 9227 if (miI == BB->end()) { 9228 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 9229 sEnd = BB->succ_end(); 9230 sItr != sEnd; ++sItr) { 9231 MachineBasicBlock* succ = *sItr; 9232 if (succ->isLiveIn(ARM::CPSR)) 9233 return false; 9234 } 9235 } 9236 9237 // We found a def, or hit the end of the basic block and CPSR wasn't live 9238 // out. SelectMI should have a kill flag on CPSR. 9239 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 9240 return true; 9241 } 9242 9243 MachineBasicBlock * 9244 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9245 MachineBasicBlock *BB) const { 9246 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9247 DebugLoc dl = MI.getDebugLoc(); 9248 bool isThumb2 = Subtarget->isThumb2(); 9249 switch (MI.getOpcode()) { 9250 default: { 9251 MI.print(errs()); 9252 llvm_unreachable("Unexpected instr type to insert"); 9253 } 9254 9255 // Thumb1 post-indexed loads are really just single-register LDMs. 9256 case ARM::tLDR_postidx: { 9257 MachineOperand Def(MI.getOperand(1)); 9258 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9259 .add(Def) // Rn_wb 9260 .add(MI.getOperand(2)) // Rn 9261 .add(MI.getOperand(3)) // PredImm 9262 .add(MI.getOperand(4)) // PredReg 9263 .add(MI.getOperand(0)); // Rt 9264 MI.eraseFromParent(); 9265 return BB; 9266 } 9267 9268 // The Thumb2 pre-indexed stores have the same MI operands, they just 9269 // define them differently in the .td files from the isel patterns, so 9270 // they need pseudos. 9271 case ARM::t2STR_preidx: 9272 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9273 return BB; 9274 case ARM::t2STRB_preidx: 9275 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9276 return BB; 9277 case ARM::t2STRH_preidx: 9278 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9279 return BB; 9280 9281 case ARM::STRi_preidx: 9282 case ARM::STRBi_preidx: { 9283 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9284 : ARM::STRB_PRE_IMM; 9285 // Decode the offset. 9286 unsigned Offset = MI.getOperand(4).getImm(); 9287 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9288 Offset = ARM_AM::getAM2Offset(Offset); 9289 if (isSub) 9290 Offset = -Offset; 9291 9292 MachineMemOperand *MMO = *MI.memoperands_begin(); 9293 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9294 .add(MI.getOperand(0)) // Rn_wb 9295 .add(MI.getOperand(1)) // Rt 9296 .add(MI.getOperand(2)) // Rn 9297 .addImm(Offset) // offset (skip GPR==zero_reg) 9298 .add(MI.getOperand(5)) // pred 9299 .add(MI.getOperand(6)) 9300 .addMemOperand(MMO); 9301 MI.eraseFromParent(); 9302 return BB; 9303 } 9304 case ARM::STRr_preidx: 9305 case ARM::STRBr_preidx: 9306 case ARM::STRH_preidx: { 9307 unsigned NewOpc; 9308 switch (MI.getOpcode()) { 9309 default: llvm_unreachable("unexpected opcode!"); 9310 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9311 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9312 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9313 } 9314 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9315 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9316 MIB.add(MI.getOperand(i)); 9317 MI.eraseFromParent(); 9318 return BB; 9319 } 9320 9321 case ARM::tMOVCCr_pseudo: { 9322 // To "insert" a SELECT_CC instruction, we actually have to insert the 9323 // diamond control-flow pattern. The incoming instruction knows the 9324 // destination vreg to set, the condition code register to branch on, the 9325 // true/false values to select between, and a branch opcode to use. 9326 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9327 MachineFunction::iterator It = ++BB->getIterator(); 9328 9329 // thisMBB: 9330 // ... 9331 // TrueVal = ... 9332 // cmpTY ccX, r1, r2 9333 // bCC copy1MBB 9334 // fallthrough --> copy0MBB 9335 MachineBasicBlock *thisMBB = BB; 9336 MachineFunction *F = BB->getParent(); 9337 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9338 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9339 F->insert(It, copy0MBB); 9340 F->insert(It, sinkMBB); 9341 9342 // Check whether CPSR is live past the tMOVCCr_pseudo. 9343 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 9344 if (!MI.killsRegister(ARM::CPSR) && 9345 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 9346 copy0MBB->addLiveIn(ARM::CPSR); 9347 sinkMBB->addLiveIn(ARM::CPSR); 9348 } 9349 9350 // Transfer the remainder of BB and its successor edges to sinkMBB. 9351 sinkMBB->splice(sinkMBB->begin(), BB, 9352 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9353 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9354 9355 BB->addSuccessor(copy0MBB); 9356 BB->addSuccessor(sinkMBB); 9357 9358 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9359 .addMBB(sinkMBB) 9360 .addImm(MI.getOperand(3).getImm()) 9361 .addReg(MI.getOperand(4).getReg()); 9362 9363 // copy0MBB: 9364 // %FalseValue = ... 9365 // # fallthrough to sinkMBB 9366 BB = copy0MBB; 9367 9368 // Update machine-CFG edges 9369 BB->addSuccessor(sinkMBB); 9370 9371 // sinkMBB: 9372 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9373 // ... 9374 BB = sinkMBB; 9375 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9376 .addReg(MI.getOperand(1).getReg()) 9377 .addMBB(copy0MBB) 9378 .addReg(MI.getOperand(2).getReg()) 9379 .addMBB(thisMBB); 9380 9381 MI.eraseFromParent(); // The pseudo instruction is gone now. 9382 return BB; 9383 } 9384 9385 case ARM::BCCi64: 9386 case ARM::BCCZi64: { 9387 // If there is an unconditional branch to the other successor, remove it. 9388 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9389 9390 // Compare both parts that make up the double comparison separately for 9391 // equality. 9392 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9393 9394 unsigned LHS1 = MI.getOperand(1).getReg(); 9395 unsigned LHS2 = MI.getOperand(2).getReg(); 9396 if (RHSisZero) { 9397 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9398 .addReg(LHS1) 9399 .addImm(0) 9400 .add(predOps(ARMCC::AL)); 9401 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9402 .addReg(LHS2).addImm(0) 9403 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9404 } else { 9405 unsigned RHS1 = MI.getOperand(3).getReg(); 9406 unsigned RHS2 = MI.getOperand(4).getReg(); 9407 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9408 .addReg(LHS1) 9409 .addReg(RHS1) 9410 .add(predOps(ARMCC::AL)); 9411 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9412 .addReg(LHS2).addReg(RHS2) 9413 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9414 } 9415 9416 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9417 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9418 if (MI.getOperand(0).getImm() == ARMCC::NE) 9419 std::swap(destMBB, exitMBB); 9420 9421 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9422 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9423 if (isThumb2) 9424 BuildMI(BB, dl, TII->get(ARM::t2B)) 9425 .addMBB(exitMBB) 9426 .add(predOps(ARMCC::AL)); 9427 else 9428 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9429 9430 MI.eraseFromParent(); // The pseudo instruction is gone now. 9431 return BB; 9432 } 9433 9434 case ARM::Int_eh_sjlj_setjmp: 9435 case ARM::Int_eh_sjlj_setjmp_nofp: 9436 case ARM::tInt_eh_sjlj_setjmp: 9437 case ARM::t2Int_eh_sjlj_setjmp: 9438 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9439 return BB; 9440 9441 case ARM::Int_eh_sjlj_setup_dispatch: 9442 EmitSjLjDispatchBlock(MI, BB); 9443 return BB; 9444 9445 case ARM::ABS: 9446 case ARM::t2ABS: { 9447 // To insert an ABS instruction, we have to insert the 9448 // diamond control-flow pattern. The incoming instruction knows the 9449 // source vreg to test against 0, the destination vreg to set, 9450 // the condition code register to branch on, the 9451 // true/false values to select between, and a branch opcode to use. 9452 // It transforms 9453 // V1 = ABS V0 9454 // into 9455 // V2 = MOVS V0 9456 // BCC (branch to SinkBB if V0 >= 0) 9457 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9458 // SinkBB: V1 = PHI(V2, V3) 9459 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9460 MachineFunction::iterator BBI = ++BB->getIterator(); 9461 MachineFunction *Fn = BB->getParent(); 9462 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9463 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9464 Fn->insert(BBI, RSBBB); 9465 Fn->insert(BBI, SinkBB); 9466 9467 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9468 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9469 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9470 bool isThumb2 = Subtarget->isThumb2(); 9471 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9472 // In Thumb mode S must not be specified if source register is the SP or 9473 // PC and if destination register is the SP, so restrict register class 9474 unsigned NewRsbDstReg = 9475 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9476 9477 // Transfer the remainder of BB and its successor edges to sinkMBB. 9478 SinkBB->splice(SinkBB->begin(), BB, 9479 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9480 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9481 9482 BB->addSuccessor(RSBBB); 9483 BB->addSuccessor(SinkBB); 9484 9485 // fall through to SinkMBB 9486 RSBBB->addSuccessor(SinkBB); 9487 9488 // insert a cmp at the end of BB 9489 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9490 .addReg(ABSSrcReg) 9491 .addImm(0) 9492 .add(predOps(ARMCC::AL)); 9493 9494 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9495 BuildMI(BB, dl, 9496 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9497 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9498 9499 // insert rsbri in RSBBB 9500 // Note: BCC and rsbri will be converted into predicated rsbmi 9501 // by if-conversion pass 9502 BuildMI(*RSBBB, RSBBB->begin(), dl, 9503 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9504 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9505 .addImm(0) 9506 .add(predOps(ARMCC::AL)) 9507 .add(condCodeOp()); 9508 9509 // insert PHI in SinkBB, 9510 // reuse ABSDstReg to not change uses of ABS instruction 9511 BuildMI(*SinkBB, SinkBB->begin(), dl, 9512 TII->get(ARM::PHI), ABSDstReg) 9513 .addReg(NewRsbDstReg).addMBB(RSBBB) 9514 .addReg(ABSSrcReg).addMBB(BB); 9515 9516 // remove ABS instruction 9517 MI.eraseFromParent(); 9518 9519 // return last added BB 9520 return SinkBB; 9521 } 9522 case ARM::COPY_STRUCT_BYVAL_I32: 9523 ++NumLoopByVals; 9524 return EmitStructByval(MI, BB); 9525 case ARM::WIN__CHKSTK: 9526 return EmitLowered__chkstk(MI, BB); 9527 case ARM::WIN__DBZCHK: 9528 return EmitLowered__dbzchk(MI, BB); 9529 } 9530 } 9531 9532 /// Attaches vregs to MEMCPY that it will use as scratch registers 9533 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9534 /// instead of as a custom inserter because we need the use list from the SDNode. 9535 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9536 MachineInstr &MI, const SDNode *Node) { 9537 bool isThumb1 = Subtarget->isThumb1Only(); 9538 9539 DebugLoc DL = MI.getDebugLoc(); 9540 MachineFunction *MF = MI.getParent()->getParent(); 9541 MachineRegisterInfo &MRI = MF->getRegInfo(); 9542 MachineInstrBuilder MIB(*MF, MI); 9543 9544 // If the new dst/src is unused mark it as dead. 9545 if (!Node->hasAnyUseOfValue(0)) { 9546 MI.getOperand(0).setIsDead(true); 9547 } 9548 if (!Node->hasAnyUseOfValue(1)) { 9549 MI.getOperand(1).setIsDead(true); 9550 } 9551 9552 // The MEMCPY both defines and kills the scratch registers. 9553 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9554 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9555 : &ARM::GPRRegClass); 9556 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9557 } 9558 } 9559 9560 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9561 SDNode *Node) const { 9562 if (MI.getOpcode() == ARM::MEMCPY) { 9563 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9564 return; 9565 } 9566 9567 const MCInstrDesc *MCID = &MI.getDesc(); 9568 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9569 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9570 // operand is still set to noreg. If needed, set the optional operand's 9571 // register to CPSR, and remove the redundant implicit def. 9572 // 9573 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9574 9575 // Rename pseudo opcodes. 9576 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9577 unsigned ccOutIdx; 9578 if (NewOpc) { 9579 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9580 MCID = &TII->get(NewOpc); 9581 9582 assert(MCID->getNumOperands() == 9583 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9584 && "converted opcode should be the same except for cc_out" 9585 " (and, on Thumb1, pred)"); 9586 9587 MI.setDesc(*MCID); 9588 9589 // Add the optional cc_out operand 9590 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9591 9592 // On Thumb1, move all input operands to the end, then add the predicate 9593 if (Subtarget->isThumb1Only()) { 9594 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9595 MI.addOperand(MI.getOperand(1)); 9596 MI.RemoveOperand(1); 9597 } 9598 9599 // Restore the ties 9600 for (unsigned i = MI.getNumOperands(); i--;) { 9601 const MachineOperand& op = MI.getOperand(i); 9602 if (op.isReg() && op.isUse()) { 9603 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9604 if (DefIdx != -1) 9605 MI.tieOperands(DefIdx, i); 9606 } 9607 } 9608 9609 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9610 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9611 ccOutIdx = 1; 9612 } else 9613 ccOutIdx = MCID->getNumOperands() - 1; 9614 } else 9615 ccOutIdx = MCID->getNumOperands() - 1; 9616 9617 // Any ARM instruction that sets the 's' bit should specify an optional 9618 // "cc_out" operand in the last operand position. 9619 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9620 assert(!NewOpc && "Optional cc_out operand required"); 9621 return; 9622 } 9623 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9624 // since we already have an optional CPSR def. 9625 bool definesCPSR = false; 9626 bool deadCPSR = false; 9627 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9628 ++i) { 9629 const MachineOperand &MO = MI.getOperand(i); 9630 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9631 definesCPSR = true; 9632 if (MO.isDead()) 9633 deadCPSR = true; 9634 MI.RemoveOperand(i); 9635 break; 9636 } 9637 } 9638 if (!definesCPSR) { 9639 assert(!NewOpc && "Optional cc_out operand required"); 9640 return; 9641 } 9642 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9643 if (deadCPSR) { 9644 assert(!MI.getOperand(ccOutIdx).getReg() && 9645 "expect uninitialized optional cc_out operand"); 9646 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9647 if (!Subtarget->isThumb1Only()) 9648 return; 9649 } 9650 9651 // If this instruction was defined with an optional CPSR def and its dag node 9652 // had a live implicit CPSR def, then activate the optional CPSR def. 9653 MachineOperand &MO = MI.getOperand(ccOutIdx); 9654 MO.setReg(ARM::CPSR); 9655 MO.setIsDef(true); 9656 } 9657 9658 //===----------------------------------------------------------------------===// 9659 // ARM Optimization Hooks 9660 //===----------------------------------------------------------------------===// 9661 9662 // Helper function that checks if N is a null or all ones constant. 9663 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9664 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9665 } 9666 9667 // Return true if N is conditionally 0 or all ones. 9668 // Detects these expressions where cc is an i1 value: 9669 // 9670 // (select cc 0, y) [AllOnes=0] 9671 // (select cc y, 0) [AllOnes=0] 9672 // (zext cc) [AllOnes=0] 9673 // (sext cc) [AllOnes=0/1] 9674 // (select cc -1, y) [AllOnes=1] 9675 // (select cc y, -1) [AllOnes=1] 9676 // 9677 // Invert is set when N is the null/all ones constant when CC is false. 9678 // OtherOp is set to the alternative value of N. 9679 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9680 SDValue &CC, bool &Invert, 9681 SDValue &OtherOp, 9682 SelectionDAG &DAG) { 9683 switch (N->getOpcode()) { 9684 default: return false; 9685 case ISD::SELECT: { 9686 CC = N->getOperand(0); 9687 SDValue N1 = N->getOperand(1); 9688 SDValue N2 = N->getOperand(2); 9689 if (isZeroOrAllOnes(N1, AllOnes)) { 9690 Invert = false; 9691 OtherOp = N2; 9692 return true; 9693 } 9694 if (isZeroOrAllOnes(N2, AllOnes)) { 9695 Invert = true; 9696 OtherOp = N1; 9697 return true; 9698 } 9699 return false; 9700 } 9701 case ISD::ZERO_EXTEND: 9702 // (zext cc) can never be the all ones value. 9703 if (AllOnes) 9704 return false; 9705 LLVM_FALLTHROUGH; 9706 case ISD::SIGN_EXTEND: { 9707 SDLoc dl(N); 9708 EVT VT = N->getValueType(0); 9709 CC = N->getOperand(0); 9710 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9711 return false; 9712 Invert = !AllOnes; 9713 if (AllOnes) 9714 // When looking for an AllOnes constant, N is an sext, and the 'other' 9715 // value is 0. 9716 OtherOp = DAG.getConstant(0, dl, VT); 9717 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9718 // When looking for a 0 constant, N can be zext or sext. 9719 OtherOp = DAG.getConstant(1, dl, VT); 9720 else 9721 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9722 VT); 9723 return true; 9724 } 9725 } 9726 } 9727 9728 // Combine a constant select operand into its use: 9729 // 9730 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9731 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9732 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9733 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9734 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9735 // 9736 // The transform is rejected if the select doesn't have a constant operand that 9737 // is null, or all ones when AllOnes is set. 9738 // 9739 // Also recognize sext/zext from i1: 9740 // 9741 // (add (zext cc), x) -> (select cc (add x, 1), x) 9742 // (add (sext cc), x) -> (select cc (add x, -1), x) 9743 // 9744 // These transformations eventually create predicated instructions. 9745 // 9746 // @param N The node to transform. 9747 // @param Slct The N operand that is a select. 9748 // @param OtherOp The other N operand (x above). 9749 // @param DCI Context. 9750 // @param AllOnes Require the select constant to be all ones instead of null. 9751 // @returns The new node, or SDValue() on failure. 9752 static 9753 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9754 TargetLowering::DAGCombinerInfo &DCI, 9755 bool AllOnes = false) { 9756 SelectionDAG &DAG = DCI.DAG; 9757 EVT VT = N->getValueType(0); 9758 SDValue NonConstantVal; 9759 SDValue CCOp; 9760 bool SwapSelectOps; 9761 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9762 NonConstantVal, DAG)) 9763 return SDValue(); 9764 9765 // Slct is now know to be the desired identity constant when CC is true. 9766 SDValue TrueVal = OtherOp; 9767 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9768 OtherOp, NonConstantVal); 9769 // Unless SwapSelectOps says CC should be false. 9770 if (SwapSelectOps) 9771 std::swap(TrueVal, FalseVal); 9772 9773 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9774 CCOp, TrueVal, FalseVal); 9775 } 9776 9777 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9778 static 9779 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9780 TargetLowering::DAGCombinerInfo &DCI) { 9781 SDValue N0 = N->getOperand(0); 9782 SDValue N1 = N->getOperand(1); 9783 if (N0.getNode()->hasOneUse()) 9784 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9785 return Result; 9786 if (N1.getNode()->hasOneUse()) 9787 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9788 return Result; 9789 return SDValue(); 9790 } 9791 9792 static bool IsVUZPShuffleNode(SDNode *N) { 9793 // VUZP shuffle node. 9794 if (N->getOpcode() == ARMISD::VUZP) 9795 return true; 9796 9797 // "VUZP" on i32 is an alias for VTRN. 9798 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9799 return true; 9800 9801 return false; 9802 } 9803 9804 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9805 TargetLowering::DAGCombinerInfo &DCI, 9806 const ARMSubtarget *Subtarget) { 9807 // Look for ADD(VUZP.0, VUZP.1). 9808 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9809 N0 == N1) 9810 return SDValue(); 9811 9812 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9813 if (!N->getValueType(0).is64BitVector()) 9814 return SDValue(); 9815 9816 // Generate vpadd. 9817 SelectionDAG &DAG = DCI.DAG; 9818 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9819 SDLoc dl(N); 9820 SDNode *Unzip = N0.getNode(); 9821 EVT VT = N->getValueType(0); 9822 9823 SmallVector<SDValue, 8> Ops; 9824 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9825 TLI.getPointerTy(DAG.getDataLayout()))); 9826 Ops.push_back(Unzip->getOperand(0)); 9827 Ops.push_back(Unzip->getOperand(1)); 9828 9829 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9830 } 9831 9832 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9833 TargetLowering::DAGCombinerInfo &DCI, 9834 const ARMSubtarget *Subtarget) { 9835 // Check for two extended operands. 9836 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9837 N1.getOpcode() == ISD::SIGN_EXTEND) && 9838 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9839 N1.getOpcode() == ISD::ZERO_EXTEND)) 9840 return SDValue(); 9841 9842 SDValue N00 = N0.getOperand(0); 9843 SDValue N10 = N1.getOperand(0); 9844 9845 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9846 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9847 N00 == N10) 9848 return SDValue(); 9849 9850 // We only recognize Q register paddl here; this can't be reached until 9851 // after type legalization. 9852 if (!N00.getValueType().is64BitVector() || 9853 !N0.getValueType().is128BitVector()) 9854 return SDValue(); 9855 9856 // Generate vpaddl. 9857 SelectionDAG &DAG = DCI.DAG; 9858 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9859 SDLoc dl(N); 9860 EVT VT = N->getValueType(0); 9861 9862 SmallVector<SDValue, 8> Ops; 9863 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9864 unsigned Opcode; 9865 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9866 Opcode = Intrinsic::arm_neon_vpaddls; 9867 else 9868 Opcode = Intrinsic::arm_neon_vpaddlu; 9869 Ops.push_back(DAG.getConstant(Opcode, dl, 9870 TLI.getPointerTy(DAG.getDataLayout()))); 9871 EVT ElemTy = N00.getValueType().getVectorElementType(); 9872 unsigned NumElts = VT.getVectorNumElements(); 9873 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9874 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9875 N00.getOperand(0), N00.getOperand(1)); 9876 Ops.push_back(Concat); 9877 9878 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9879 } 9880 9881 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9882 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9883 // much easier to match. 9884 static SDValue 9885 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9886 TargetLowering::DAGCombinerInfo &DCI, 9887 const ARMSubtarget *Subtarget) { 9888 // Only perform optimization if after legalize, and if NEON is available. We 9889 // also expected both operands to be BUILD_VECTORs. 9890 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9891 || N0.getOpcode() != ISD::BUILD_VECTOR 9892 || N1.getOpcode() != ISD::BUILD_VECTOR) 9893 return SDValue(); 9894 9895 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9896 EVT VT = N->getValueType(0); 9897 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9898 return SDValue(); 9899 9900 // Check that the vector operands are of the right form. 9901 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9902 // operands, where N is the size of the formed vector. 9903 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9904 // index such that we have a pair wise add pattern. 9905 9906 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9907 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9908 return SDValue(); 9909 SDValue Vec = N0->getOperand(0)->getOperand(0); 9910 SDNode *V = Vec.getNode(); 9911 unsigned nextIndex = 0; 9912 9913 // For each operands to the ADD which are BUILD_VECTORs, 9914 // check to see if each of their operands are an EXTRACT_VECTOR with 9915 // the same vector and appropriate index. 9916 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9917 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9918 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9919 9920 SDValue ExtVec0 = N0->getOperand(i); 9921 SDValue ExtVec1 = N1->getOperand(i); 9922 9923 // First operand is the vector, verify its the same. 9924 if (V != ExtVec0->getOperand(0).getNode() || 9925 V != ExtVec1->getOperand(0).getNode()) 9926 return SDValue(); 9927 9928 // Second is the constant, verify its correct. 9929 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9930 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9931 9932 // For the constant, we want to see all the even or all the odd. 9933 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9934 || C1->getZExtValue() != nextIndex+1) 9935 return SDValue(); 9936 9937 // Increment index. 9938 nextIndex+=2; 9939 } else 9940 return SDValue(); 9941 } 9942 9943 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9944 // we're using the entire input vector, otherwise there's a size/legality 9945 // mismatch somewhere. 9946 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9947 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9948 return SDValue(); 9949 9950 // Create VPADDL node. 9951 SelectionDAG &DAG = DCI.DAG; 9952 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9953 9954 SDLoc dl(N); 9955 9956 // Build operand list. 9957 SmallVector<SDValue, 8> Ops; 9958 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9959 TLI.getPointerTy(DAG.getDataLayout()))); 9960 9961 // Input is the vector. 9962 Ops.push_back(Vec); 9963 9964 // Get widened type and narrowed type. 9965 MVT widenType; 9966 unsigned numElem = VT.getVectorNumElements(); 9967 9968 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9969 switch (inputLaneType.getSimpleVT().SimpleTy) { 9970 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9971 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9972 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9973 default: 9974 llvm_unreachable("Invalid vector element type for padd optimization."); 9975 } 9976 9977 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9978 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9979 return DAG.getNode(ExtOp, dl, VT, tmp); 9980 } 9981 9982 static SDValue findMUL_LOHI(SDValue V) { 9983 if (V->getOpcode() == ISD::UMUL_LOHI || 9984 V->getOpcode() == ISD::SMUL_LOHI) 9985 return V; 9986 return SDValue(); 9987 } 9988 9989 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 9990 TargetLowering::DAGCombinerInfo &DCI, 9991 const ARMSubtarget *Subtarget) { 9992 if (Subtarget->isThumb()) { 9993 if (!Subtarget->hasDSP()) 9994 return SDValue(); 9995 } else if (!Subtarget->hasV5TEOps()) 9996 return SDValue(); 9997 9998 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 9999 // accumulates the product into a 64-bit value. The 16-bit values will 10000 // be sign extended somehow or SRA'd into 32-bit values 10001 // (addc (adde (mul 16bit, 16bit), lo), hi) 10002 SDValue Mul = AddcNode->getOperand(0); 10003 SDValue Lo = AddcNode->getOperand(1); 10004 if (Mul.getOpcode() != ISD::MUL) { 10005 Lo = AddcNode->getOperand(0); 10006 Mul = AddcNode->getOperand(1); 10007 if (Mul.getOpcode() != ISD::MUL) 10008 return SDValue(); 10009 } 10010 10011 SDValue SRA = AddeNode->getOperand(0); 10012 SDValue Hi = AddeNode->getOperand(1); 10013 if (SRA.getOpcode() != ISD::SRA) { 10014 SRA = AddeNode->getOperand(1); 10015 Hi = AddeNode->getOperand(0); 10016 if (SRA.getOpcode() != ISD::SRA) 10017 return SDValue(); 10018 } 10019 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10020 if (Const->getZExtValue() != 31) 10021 return SDValue(); 10022 } else 10023 return SDValue(); 10024 10025 if (SRA.getOperand(0) != Mul) 10026 return SDValue(); 10027 10028 SelectionDAG &DAG = DCI.DAG; 10029 SDLoc dl(AddcNode); 10030 unsigned Opcode = 0; 10031 SDValue Op0; 10032 SDValue Op1; 10033 10034 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10035 Opcode = ARMISD::SMLALBB; 10036 Op0 = Mul.getOperand(0); 10037 Op1 = Mul.getOperand(1); 10038 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10039 Opcode = ARMISD::SMLALBT; 10040 Op0 = Mul.getOperand(0); 10041 Op1 = Mul.getOperand(1).getOperand(0); 10042 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10043 Opcode = ARMISD::SMLALTB; 10044 Op0 = Mul.getOperand(0).getOperand(0); 10045 Op1 = Mul.getOperand(1); 10046 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10047 Opcode = ARMISD::SMLALTT; 10048 Op0 = Mul->getOperand(0).getOperand(0); 10049 Op1 = Mul->getOperand(1).getOperand(0); 10050 } 10051 10052 if (!Op0 || !Op1) 10053 return SDValue(); 10054 10055 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10056 Op0, Op1, Lo, Hi); 10057 // Replace the ADDs' nodes uses by the MLA node's values. 10058 SDValue HiMLALResult(SMLAL.getNode(), 1); 10059 SDValue LoMLALResult(SMLAL.getNode(), 0); 10060 10061 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10062 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10063 10064 // Return original node to notify the driver to stop replacing. 10065 SDValue resNode(AddcNode, 0); 10066 return resNode; 10067 } 10068 10069 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10070 TargetLowering::DAGCombinerInfo &DCI, 10071 const ARMSubtarget *Subtarget) { 10072 // Look for multiply add opportunities. 10073 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10074 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10075 // a glue link from the first add to the second add. 10076 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10077 // a S/UMLAL instruction. 10078 // UMUL_LOHI 10079 // / :lo \ :hi 10080 // V \ [no multiline comment] 10081 // loAdd -> ADDC | 10082 // \ :carry / 10083 // V V 10084 // ADDE <- hiAdd 10085 // 10086 // In the special case where only the higher part of a signed result is used 10087 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10088 // a constant with the exact value of 0x80000000, we recognize we are dealing 10089 // with a "rounded multiply and add" (or subtract) and transform it into 10090 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10091 10092 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10093 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10094 "Expect an ADDE or SUBE"); 10095 10096 assert(AddeSubeNode->getNumOperands() == 3 && 10097 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10098 "ADDE node has the wrong inputs"); 10099 10100 // Check that we are chained to the right ADDC or SUBC node. 10101 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10102 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10103 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10104 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10105 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10106 return SDValue(); 10107 10108 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10109 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10110 10111 // Check if the two operands are from the same mul_lohi node. 10112 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10113 return SDValue(); 10114 10115 assert(AddcSubcNode->getNumValues() == 2 && 10116 AddcSubcNode->getValueType(0) == MVT::i32 && 10117 "Expect ADDC with two result values. First: i32"); 10118 10119 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10120 // maybe a SMLAL which multiplies two 16-bit values. 10121 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10122 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10123 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10124 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10125 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10126 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10127 10128 // Check for the triangle shape. 10129 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10130 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10131 10132 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10133 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10134 return SDValue(); 10135 10136 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10137 bool IsLeftOperandMUL = false; 10138 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10139 if (MULOp == SDValue()) 10140 MULOp = findMUL_LOHI(AddeSubeOp1); 10141 else 10142 IsLeftOperandMUL = true; 10143 if (MULOp == SDValue()) 10144 return SDValue(); 10145 10146 // Figure out the right opcode. 10147 unsigned Opc = MULOp->getOpcode(); 10148 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10149 10150 // Figure out the high and low input values to the MLAL node. 10151 SDValue *HiAddSub = nullptr; 10152 SDValue *LoMul = nullptr; 10153 SDValue *LowAddSub = nullptr; 10154 10155 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10156 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10157 return SDValue(); 10158 10159 if (IsLeftOperandMUL) 10160 HiAddSub = &AddeSubeOp1; 10161 else 10162 HiAddSub = &AddeSubeOp0; 10163 10164 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10165 // whose low result is fed to the ADDC/SUBC we are checking. 10166 10167 if (AddcSubcOp0 == MULOp.getValue(0)) { 10168 LoMul = &AddcSubcOp0; 10169 LowAddSub = &AddcSubcOp1; 10170 } 10171 if (AddcSubcOp1 == MULOp.getValue(0)) { 10172 LoMul = &AddcSubcOp1; 10173 LowAddSub = &AddcSubcOp0; 10174 } 10175 10176 if (!LoMul) 10177 return SDValue(); 10178 10179 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10180 // the replacement below will create a cycle. 10181 if (AddcSubcNode == HiAddSub->getNode() || 10182 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10183 return SDValue(); 10184 10185 // Create the merged node. 10186 SelectionDAG &DAG = DCI.DAG; 10187 10188 // Start building operand list. 10189 SmallVector<SDValue, 8> Ops; 10190 Ops.push_back(LoMul->getOperand(0)); 10191 Ops.push_back(LoMul->getOperand(1)); 10192 10193 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10194 // the case, we must be doing signed multiplication and only use the higher 10195 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10196 // addition or subtraction with the value of 0x800000. 10197 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10198 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10199 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10200 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10201 0x80000000) { 10202 Ops.push_back(*HiAddSub); 10203 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10204 FinalOpc = ARMISD::SMMLSR; 10205 } else { 10206 FinalOpc = ARMISD::SMMLAR; 10207 } 10208 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10209 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10210 10211 return SDValue(AddeSubeNode, 0); 10212 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10213 // SMMLS is generated during instruction selection and the rest of this 10214 // function can not handle the case where AddcSubcNode is a SUBC. 10215 return SDValue(); 10216 10217 // Finish building the operand list for {U/S}MLAL 10218 Ops.push_back(*LowAddSub); 10219 Ops.push_back(*HiAddSub); 10220 10221 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 10222 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10223 10224 // Replace the ADDs' nodes uses by the MLA node's values. 10225 SDValue HiMLALResult(MLALNode.getNode(), 1); 10226 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 10227 10228 SDValue LoMLALResult(MLALNode.getNode(), 0); 10229 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 10230 10231 // Return original node to notify the driver to stop replacing. 10232 return SDValue(AddeSubeNode, 0); 10233 } 10234 10235 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 10236 TargetLowering::DAGCombinerInfo &DCI, 10237 const ARMSubtarget *Subtarget) { 10238 // UMAAL is similar to UMLAL except that it adds two unsigned values. 10239 // While trying to combine for the other MLAL nodes, first search for the 10240 // chance to use UMAAL. Check if Addc uses a node which has already 10241 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 10242 // as the addend, and it's handled in PerformUMLALCombine. 10243 10244 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10245 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10246 10247 // Check that we have a glued ADDC node. 10248 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10249 if (AddcNode->getOpcode() != ARMISD::ADDC) 10250 return SDValue(); 10251 10252 // Find the converted UMAAL or quit if it doesn't exist. 10253 SDNode *UmlalNode = nullptr; 10254 SDValue AddHi; 10255 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10256 UmlalNode = AddcNode->getOperand(0).getNode(); 10257 AddHi = AddcNode->getOperand(1); 10258 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10259 UmlalNode = AddcNode->getOperand(1).getNode(); 10260 AddHi = AddcNode->getOperand(0); 10261 } else { 10262 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10263 } 10264 10265 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10266 // the ADDC as well as Zero. 10267 if (!isNullConstant(UmlalNode->getOperand(3))) 10268 return SDValue(); 10269 10270 if ((isNullConstant(AddeNode->getOperand(0)) && 10271 AddeNode->getOperand(1).getNode() == UmlalNode) || 10272 (AddeNode->getOperand(0).getNode() == UmlalNode && 10273 isNullConstant(AddeNode->getOperand(1)))) { 10274 SelectionDAG &DAG = DCI.DAG; 10275 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10276 UmlalNode->getOperand(2), AddHi }; 10277 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10278 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10279 10280 // Replace the ADDs' nodes uses by the UMAAL node's values. 10281 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10282 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10283 10284 // Return original node to notify the driver to stop replacing. 10285 return SDValue(AddeNode, 0); 10286 } 10287 return SDValue(); 10288 } 10289 10290 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10291 const ARMSubtarget *Subtarget) { 10292 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10293 return SDValue(); 10294 10295 // Check that we have a pair of ADDC and ADDE as operands. 10296 // Both addends of the ADDE must be zero. 10297 SDNode* AddcNode = N->getOperand(2).getNode(); 10298 SDNode* AddeNode = N->getOperand(3).getNode(); 10299 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10300 (AddeNode->getOpcode() == ARMISD::ADDE) && 10301 isNullConstant(AddeNode->getOperand(0)) && 10302 isNullConstant(AddeNode->getOperand(1)) && 10303 (AddeNode->getOperand(2).getNode() == AddcNode)) 10304 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10305 DAG.getVTList(MVT::i32, MVT::i32), 10306 {N->getOperand(0), N->getOperand(1), 10307 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10308 else 10309 return SDValue(); 10310 } 10311 10312 static SDValue PerformAddcSubcCombine(SDNode *N, 10313 TargetLowering::DAGCombinerInfo &DCI, 10314 const ARMSubtarget *Subtarget) { 10315 SelectionDAG &DAG(DCI.DAG); 10316 10317 if (N->getOpcode() == ARMISD::SUBC) { 10318 // (SUBC (ADDE 0, 0, C), 1) -> C 10319 SDValue LHS = N->getOperand(0); 10320 SDValue RHS = N->getOperand(1); 10321 if (LHS->getOpcode() == ARMISD::ADDE && 10322 isNullConstant(LHS->getOperand(0)) && 10323 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 10324 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10325 } 10326 } 10327 10328 if (Subtarget->isThumb1Only()) { 10329 SDValue RHS = N->getOperand(1); 10330 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10331 int32_t imm = C->getSExtValue(); 10332 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10333 SDLoc DL(N); 10334 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10335 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10336 : ARMISD::ADDC; 10337 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10338 } 10339 } 10340 } 10341 10342 return SDValue(); 10343 } 10344 10345 static SDValue PerformAddeSubeCombine(SDNode *N, 10346 TargetLowering::DAGCombinerInfo &DCI, 10347 const ARMSubtarget *Subtarget) { 10348 if (Subtarget->isThumb1Only()) { 10349 SelectionDAG &DAG = DCI.DAG; 10350 SDValue RHS = N->getOperand(1); 10351 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10352 int64_t imm = C->getSExtValue(); 10353 if (imm < 0) { 10354 SDLoc DL(N); 10355 10356 // The with-carry-in form matches bitwise not instead of the negation. 10357 // Effectively, the inverse interpretation of the carry flag already 10358 // accounts for part of the negation. 10359 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10360 10361 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10362 : ARMISD::ADDE; 10363 return DAG.getNode(Opcode, DL, N->getVTList(), 10364 N->getOperand(0), RHS, N->getOperand(2)); 10365 } 10366 } 10367 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 10368 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 10369 } 10370 return SDValue(); 10371 } 10372 10373 /// PerformADDECombine - Target-specific dag combine transform from 10374 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10375 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10376 static SDValue PerformADDECombine(SDNode *N, 10377 TargetLowering::DAGCombinerInfo &DCI, 10378 const ARMSubtarget *Subtarget) { 10379 // Only ARM and Thumb2 support UMLAL/SMLAL. 10380 if (Subtarget->isThumb1Only()) 10381 return PerformAddeSubeCombine(N, DCI, Subtarget); 10382 10383 // Only perform the checks after legalize when the pattern is available. 10384 if (DCI.isBeforeLegalize()) return SDValue(); 10385 10386 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10387 } 10388 10389 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10390 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10391 /// called with the default operands, and if that fails, with commuted 10392 /// operands. 10393 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10394 TargetLowering::DAGCombinerInfo &DCI, 10395 const ARMSubtarget *Subtarget){ 10396 // Attempt to create vpadd for this add. 10397 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10398 return Result; 10399 10400 // Attempt to create vpaddl for this add. 10401 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10402 return Result; 10403 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10404 Subtarget)) 10405 return Result; 10406 10407 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10408 if (N0.getNode()->hasOneUse()) 10409 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10410 return Result; 10411 return SDValue(); 10412 } 10413 10414 bool 10415 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 10416 CombineLevel Level) const { 10417 if (Level == BeforeLegalizeTypes) 10418 return true; 10419 10420 if (N->getOpcode() != ISD::SHL) 10421 return true; 10422 10423 if (Subtarget->isThumb1Only()) { 10424 // Avoid making expensive immediates by commuting shifts. (This logic 10425 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 10426 // for free.) 10427 if (N->getOpcode() != ISD::SHL) 10428 return true; 10429 SDValue N1 = N->getOperand(0); 10430 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 10431 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 10432 return true; 10433 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 10434 if (Const->getAPIntValue().ult(256)) 10435 return false; 10436 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 10437 Const->getAPIntValue().sgt(-256)) 10438 return false; 10439 } 10440 return true; 10441 } 10442 10443 // Turn off commute-with-shift transform after legalization, so it doesn't 10444 // conflict with PerformSHLSimplify. (We could try to detect when 10445 // PerformSHLSimplify would trigger more precisely, but it isn't 10446 // really necessary.) 10447 return false; 10448 } 10449 10450 bool 10451 ARMTargetLowering::shouldFoldShiftPairToMask(const SDNode *N, 10452 CombineLevel Level) const { 10453 if (!Subtarget->isThumb1Only()) 10454 return true; 10455 10456 if (Level == BeforeLegalizeTypes) 10457 return true; 10458 10459 return false; 10460 } 10461 10462 static SDValue PerformSHLSimplify(SDNode *N, 10463 TargetLowering::DAGCombinerInfo &DCI, 10464 const ARMSubtarget *ST) { 10465 // Allow the generic combiner to identify potential bswaps. 10466 if (DCI.isBeforeLegalize()) 10467 return SDValue(); 10468 10469 // DAG combiner will fold: 10470 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10471 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10472 // Other code patterns that can be also be modified have the following form: 10473 // b + ((a << 1) | 510) 10474 // b + ((a << 1) & 510) 10475 // b + ((a << 1) ^ 510) 10476 // b + ((a << 1) + 510) 10477 10478 // Many instructions can perform the shift for free, but it requires both 10479 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10480 // instruction will needed. So, unfold back to the original pattern if: 10481 // - if c1 and c2 are small enough that they don't require mov imms. 10482 // - the user(s) of the node can perform an shl 10483 10484 // No shifted operands for 16-bit instructions. 10485 if (ST->isThumb() && ST->isThumb1Only()) 10486 return SDValue(); 10487 10488 // Check that all the users could perform the shl themselves. 10489 for (auto U : N->uses()) { 10490 switch(U->getOpcode()) { 10491 default: 10492 return SDValue(); 10493 case ISD::SUB: 10494 case ISD::ADD: 10495 case ISD::AND: 10496 case ISD::OR: 10497 case ISD::XOR: 10498 case ISD::SETCC: 10499 case ARMISD::CMP: 10500 // Check that the user isn't already using a constant because there 10501 // aren't any instructions that support an immediate operand and a 10502 // shifted operand. 10503 if (isa<ConstantSDNode>(U->getOperand(0)) || 10504 isa<ConstantSDNode>(U->getOperand(1))) 10505 return SDValue(); 10506 10507 // Check that it's not already using a shift. 10508 if (U->getOperand(0).getOpcode() == ISD::SHL || 10509 U->getOperand(1).getOpcode() == ISD::SHL) 10510 return SDValue(); 10511 break; 10512 } 10513 } 10514 10515 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10516 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10517 return SDValue(); 10518 10519 if (N->getOperand(0).getOpcode() != ISD::SHL) 10520 return SDValue(); 10521 10522 SDValue SHL = N->getOperand(0); 10523 10524 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10525 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10526 if (!C1ShlC2 || !C2) 10527 return SDValue(); 10528 10529 APInt C2Int = C2->getAPIntValue(); 10530 APInt C1Int = C1ShlC2->getAPIntValue(); 10531 10532 // Check that performing a lshr will not lose any information. 10533 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10534 C2Int.getBitWidth() - C2->getZExtValue()); 10535 if ((C1Int & Mask) != C1Int) 10536 return SDValue(); 10537 10538 // Shift the first constant. 10539 C1Int.lshrInPlace(C2Int); 10540 10541 // The immediates are encoded as an 8-bit value that can be rotated. 10542 auto LargeImm = [](const APInt &Imm) { 10543 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 10544 return Imm.getBitWidth() - Zeros > 8; 10545 }; 10546 10547 if (LargeImm(C1Int) || LargeImm(C2Int)) 10548 return SDValue(); 10549 10550 SelectionDAG &DAG = DCI.DAG; 10551 SDLoc dl(N); 10552 SDValue X = SHL.getOperand(0); 10553 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10554 DAG.getConstant(C1Int, dl, MVT::i32)); 10555 // Shift left to compensate for the lshr of C1Int. 10556 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10557 10558 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 10559 SHL.dump(); N->dump()); 10560 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 10561 return Res; 10562 } 10563 10564 10565 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10566 /// 10567 static SDValue PerformADDCombine(SDNode *N, 10568 TargetLowering::DAGCombinerInfo &DCI, 10569 const ARMSubtarget *Subtarget) { 10570 SDValue N0 = N->getOperand(0); 10571 SDValue N1 = N->getOperand(1); 10572 10573 // Only works one way, because it needs an immediate operand. 10574 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10575 return Result; 10576 10577 // First try with the default operand order. 10578 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10579 return Result; 10580 10581 // If that didn't work, try again with the operands commuted. 10582 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10583 } 10584 10585 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10586 /// 10587 static SDValue PerformSUBCombine(SDNode *N, 10588 TargetLowering::DAGCombinerInfo &DCI) { 10589 SDValue N0 = N->getOperand(0); 10590 SDValue N1 = N->getOperand(1); 10591 10592 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10593 if (N1.getNode()->hasOneUse()) 10594 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10595 return Result; 10596 10597 return SDValue(); 10598 } 10599 10600 /// PerformVMULCombine 10601 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10602 /// special multiplier accumulator forwarding. 10603 /// vmul d3, d0, d2 10604 /// vmla d3, d1, d2 10605 /// is faster than 10606 /// vadd d3, d0, d1 10607 /// vmul d3, d3, d2 10608 // However, for (A + B) * (A + B), 10609 // vadd d2, d0, d1 10610 // vmul d3, d0, d2 10611 // vmla d3, d1, d2 10612 // is slower than 10613 // vadd d2, d0, d1 10614 // vmul d3, d2, d2 10615 static SDValue PerformVMULCombine(SDNode *N, 10616 TargetLowering::DAGCombinerInfo &DCI, 10617 const ARMSubtarget *Subtarget) { 10618 if (!Subtarget->hasVMLxForwarding()) 10619 return SDValue(); 10620 10621 SelectionDAG &DAG = DCI.DAG; 10622 SDValue N0 = N->getOperand(0); 10623 SDValue N1 = N->getOperand(1); 10624 unsigned Opcode = N0.getOpcode(); 10625 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10626 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10627 Opcode = N1.getOpcode(); 10628 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10629 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10630 return SDValue(); 10631 std::swap(N0, N1); 10632 } 10633 10634 if (N0 == N1) 10635 return SDValue(); 10636 10637 EVT VT = N->getValueType(0); 10638 SDLoc DL(N); 10639 SDValue N00 = N0->getOperand(0); 10640 SDValue N01 = N0->getOperand(1); 10641 return DAG.getNode(Opcode, DL, VT, 10642 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10643 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10644 } 10645 10646 static SDValue PerformMULCombine(SDNode *N, 10647 TargetLowering::DAGCombinerInfo &DCI, 10648 const ARMSubtarget *Subtarget) { 10649 SelectionDAG &DAG = DCI.DAG; 10650 10651 if (Subtarget->isThumb1Only()) 10652 return SDValue(); 10653 10654 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10655 return SDValue(); 10656 10657 EVT VT = N->getValueType(0); 10658 if (VT.is64BitVector() || VT.is128BitVector()) 10659 return PerformVMULCombine(N, DCI, Subtarget); 10660 if (VT != MVT::i32) 10661 return SDValue(); 10662 10663 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10664 if (!C) 10665 return SDValue(); 10666 10667 int64_t MulAmt = C->getSExtValue(); 10668 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10669 10670 ShiftAmt = ShiftAmt & (32 - 1); 10671 SDValue V = N->getOperand(0); 10672 SDLoc DL(N); 10673 10674 SDValue Res; 10675 MulAmt >>= ShiftAmt; 10676 10677 if (MulAmt >= 0) { 10678 if (isPowerOf2_32(MulAmt - 1)) { 10679 // (mul x, 2^N + 1) => (add (shl x, N), x) 10680 Res = DAG.getNode(ISD::ADD, DL, VT, 10681 V, 10682 DAG.getNode(ISD::SHL, DL, VT, 10683 V, 10684 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10685 MVT::i32))); 10686 } else if (isPowerOf2_32(MulAmt + 1)) { 10687 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10688 Res = DAG.getNode(ISD::SUB, DL, VT, 10689 DAG.getNode(ISD::SHL, DL, VT, 10690 V, 10691 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10692 MVT::i32)), 10693 V); 10694 } else 10695 return SDValue(); 10696 } else { 10697 uint64_t MulAmtAbs = -MulAmt; 10698 if (isPowerOf2_32(MulAmtAbs + 1)) { 10699 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10700 Res = DAG.getNode(ISD::SUB, DL, VT, 10701 V, 10702 DAG.getNode(ISD::SHL, DL, VT, 10703 V, 10704 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10705 MVT::i32))); 10706 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10707 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10708 Res = DAG.getNode(ISD::ADD, DL, VT, 10709 V, 10710 DAG.getNode(ISD::SHL, DL, VT, 10711 V, 10712 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10713 MVT::i32))); 10714 Res = DAG.getNode(ISD::SUB, DL, VT, 10715 DAG.getConstant(0, DL, MVT::i32), Res); 10716 } else 10717 return SDValue(); 10718 } 10719 10720 if (ShiftAmt != 0) 10721 Res = DAG.getNode(ISD::SHL, DL, VT, 10722 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10723 10724 // Do not add new nodes to DAG combiner worklist. 10725 DCI.CombineTo(N, Res, false); 10726 return SDValue(); 10727 } 10728 10729 static SDValue CombineANDShift(SDNode *N, 10730 TargetLowering::DAGCombinerInfo &DCI, 10731 const ARMSubtarget *Subtarget) { 10732 // Allow DAGCombine to pattern-match before we touch the canonical form. 10733 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10734 return SDValue(); 10735 10736 if (N->getValueType(0) != MVT::i32) 10737 return SDValue(); 10738 10739 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10740 if (!N1C) 10741 return SDValue(); 10742 10743 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 10744 // Don't transform uxtb/uxth. 10745 if (C1 == 255 || C1 == 65535) 10746 return SDValue(); 10747 10748 SDNode *N0 = N->getOperand(0).getNode(); 10749 if (!N0->hasOneUse()) 10750 return SDValue(); 10751 10752 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 10753 return SDValue(); 10754 10755 bool LeftShift = N0->getOpcode() == ISD::SHL; 10756 10757 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 10758 if (!N01C) 10759 return SDValue(); 10760 10761 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 10762 if (!C2 || C2 >= 32) 10763 return SDValue(); 10764 10765 // Clear irrelevant bits in the mask. 10766 if (LeftShift) 10767 C1 &= (-1U << C2); 10768 else 10769 C1 &= (-1U >> C2); 10770 10771 SelectionDAG &DAG = DCI.DAG; 10772 SDLoc DL(N); 10773 10774 // We have a pattern of the form "(and (shl x, c2) c1)" or 10775 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 10776 // transform to a pair of shifts, to save materializing c1. 10777 10778 // First pattern: right shift, then mask off leading bits. 10779 // FIXME: Use demanded bits? 10780 if (!LeftShift && isMask_32(C1)) { 10781 uint32_t C3 = countLeadingZeros(C1); 10782 if (C2 < C3) { 10783 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 10784 DAG.getConstant(C3 - C2, DL, MVT::i32)); 10785 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 10786 DAG.getConstant(C3, DL, MVT::i32)); 10787 } 10788 } 10789 10790 // First pattern, reversed: left shift, then mask off trailing bits. 10791 if (LeftShift && isMask_32(~C1)) { 10792 uint32_t C3 = countTrailingZeros(C1); 10793 if (C2 < C3) { 10794 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 10795 DAG.getConstant(C3 - C2, DL, MVT::i32)); 10796 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 10797 DAG.getConstant(C3, DL, MVT::i32)); 10798 } 10799 } 10800 10801 // Second pattern: left shift, then mask off leading bits. 10802 // FIXME: Use demanded bits? 10803 if (LeftShift && isShiftedMask_32(C1)) { 10804 uint32_t Trailing = countTrailingZeros(C1); 10805 uint32_t C3 = countLeadingZeros(C1); 10806 if (Trailing == C2 && C2 + C3 < 32) { 10807 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 10808 DAG.getConstant(C2 + C3, DL, MVT::i32)); 10809 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 10810 DAG.getConstant(C3, DL, MVT::i32)); 10811 } 10812 } 10813 10814 // Second pattern, reversed: right shift, then mask off trailing bits. 10815 // FIXME: Handle other patterns of known/demanded bits. 10816 if (!LeftShift && isShiftedMask_32(C1)) { 10817 uint32_t Leading = countLeadingZeros(C1); 10818 uint32_t C3 = countTrailingZeros(C1); 10819 if (Leading == C2 && C2 + C3 < 32) { 10820 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 10821 DAG.getConstant(C2 + C3, DL, MVT::i32)); 10822 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 10823 DAG.getConstant(C3, DL, MVT::i32)); 10824 } 10825 } 10826 10827 // FIXME: Transform "(and (shl x, c2) c1)" -> 10828 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 10829 // c1. 10830 return SDValue(); 10831 } 10832 10833 static SDValue PerformANDCombine(SDNode *N, 10834 TargetLowering::DAGCombinerInfo &DCI, 10835 const ARMSubtarget *Subtarget) { 10836 // Attempt to use immediate-form VBIC 10837 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10838 SDLoc dl(N); 10839 EVT VT = N->getValueType(0); 10840 SelectionDAG &DAG = DCI.DAG; 10841 10842 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10843 return SDValue(); 10844 10845 APInt SplatBits, SplatUndef; 10846 unsigned SplatBitSize; 10847 bool HasAnyUndefs; 10848 if (BVN && 10849 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10850 if (SplatBitSize <= 64) { 10851 EVT VbicVT; 10852 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10853 SplatUndef.getZExtValue(), SplatBitSize, 10854 DAG, dl, VbicVT, VT.is128BitVector(), 10855 OtherModImm); 10856 if (Val.getNode()) { 10857 SDValue Input = 10858 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10859 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10860 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10861 } 10862 } 10863 } 10864 10865 if (!Subtarget->isThumb1Only()) { 10866 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10867 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10868 return Result; 10869 10870 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10871 return Result; 10872 } 10873 10874 if (Subtarget->isThumb1Only()) 10875 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 10876 return Result; 10877 10878 return SDValue(); 10879 } 10880 10881 // Try combining OR nodes to SMULWB, SMULWT. 10882 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10883 TargetLowering::DAGCombinerInfo &DCI, 10884 const ARMSubtarget *Subtarget) { 10885 if (!Subtarget->hasV6Ops() || 10886 (Subtarget->isThumb() && 10887 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10888 return SDValue(); 10889 10890 SDValue SRL = OR->getOperand(0); 10891 SDValue SHL = OR->getOperand(1); 10892 10893 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10894 SRL = OR->getOperand(1); 10895 SHL = OR->getOperand(0); 10896 } 10897 if (!isSRL16(SRL) || !isSHL16(SHL)) 10898 return SDValue(); 10899 10900 // The first operands to the shifts need to be the two results from the 10901 // same smul_lohi node. 10902 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10903 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10904 return SDValue(); 10905 10906 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10907 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10908 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10909 return SDValue(); 10910 10911 // Now we have: 10912 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10913 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10914 // For SMUWB the 16-bit value will signed extended somehow. 10915 // For SMULWT only the SRA is required. 10916 // Check both sides of SMUL_LOHI 10917 SDValue OpS16 = SMULLOHI->getOperand(0); 10918 SDValue OpS32 = SMULLOHI->getOperand(1); 10919 10920 SelectionDAG &DAG = DCI.DAG; 10921 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10922 OpS16 = OpS32; 10923 OpS32 = SMULLOHI->getOperand(0); 10924 } 10925 10926 SDLoc dl(OR); 10927 unsigned Opcode = 0; 10928 if (isS16(OpS16, DAG)) 10929 Opcode = ARMISD::SMULWB; 10930 else if (isSRA16(OpS16)) { 10931 Opcode = ARMISD::SMULWT; 10932 OpS16 = OpS16->getOperand(0); 10933 } 10934 else 10935 return SDValue(); 10936 10937 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10938 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10939 return SDValue(OR, 0); 10940 } 10941 10942 static SDValue PerformORCombineToBFI(SDNode *N, 10943 TargetLowering::DAGCombinerInfo &DCI, 10944 const ARMSubtarget *Subtarget) { 10945 // BFI is only available on V6T2+ 10946 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10947 return SDValue(); 10948 10949 EVT VT = N->getValueType(0); 10950 SDValue N0 = N->getOperand(0); 10951 SDValue N1 = N->getOperand(1); 10952 SelectionDAG &DAG = DCI.DAG; 10953 SDLoc DL(N); 10954 // 1) or (and A, mask), val => ARMbfi A, val, mask 10955 // iff (val & mask) == val 10956 // 10957 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10958 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10959 // && mask == ~mask2 10960 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10961 // && ~mask == mask2 10962 // (i.e., copy a bitfield value into another bitfield of the same width) 10963 10964 if (VT != MVT::i32) 10965 return SDValue(); 10966 10967 SDValue N00 = N0.getOperand(0); 10968 10969 // The value and the mask need to be constants so we can verify this is 10970 // actually a bitfield set. If the mask is 0xffff, we can do better 10971 // via a movt instruction, so don't use BFI in that case. 10972 SDValue MaskOp = N0.getOperand(1); 10973 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10974 if (!MaskC) 10975 return SDValue(); 10976 unsigned Mask = MaskC->getZExtValue(); 10977 if (Mask == 0xffff) 10978 return SDValue(); 10979 SDValue Res; 10980 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10981 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10982 if (N1C) { 10983 unsigned Val = N1C->getZExtValue(); 10984 if ((Val & ~Mask) != Val) 10985 return SDValue(); 10986 10987 if (ARM::isBitFieldInvertedMask(Mask)) { 10988 Val >>= countTrailingZeros(~Mask); 10989 10990 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10991 DAG.getConstant(Val, DL, MVT::i32), 10992 DAG.getConstant(Mask, DL, MVT::i32)); 10993 10994 DCI.CombineTo(N, Res, false); 10995 // Return value from the original node to inform the combiner than N is 10996 // now dead. 10997 return SDValue(N, 0); 10998 } 10999 } else if (N1.getOpcode() == ISD::AND) { 11000 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11001 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11002 if (!N11C) 11003 return SDValue(); 11004 unsigned Mask2 = N11C->getZExtValue(); 11005 11006 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 11007 // as is to match. 11008 if (ARM::isBitFieldInvertedMask(Mask) && 11009 (Mask == ~Mask2)) { 11010 // The pack halfword instruction works better for masks that fit it, 11011 // so use that when it's available. 11012 if (Subtarget->hasDSP() && 11013 (Mask == 0xffff || Mask == 0xffff0000)) 11014 return SDValue(); 11015 // 2a 11016 unsigned amt = countTrailingZeros(Mask2); 11017 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 11018 DAG.getConstant(amt, DL, MVT::i32)); 11019 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 11020 DAG.getConstant(Mask, DL, MVT::i32)); 11021 DCI.CombineTo(N, Res, false); 11022 // Return value from the original node to inform the combiner than N is 11023 // now dead. 11024 return SDValue(N, 0); 11025 } else if (ARM::isBitFieldInvertedMask(~Mask) && 11026 (~Mask == Mask2)) { 11027 // The pack halfword instruction works better for masks that fit it, 11028 // so use that when it's available. 11029 if (Subtarget->hasDSP() && 11030 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 11031 return SDValue(); 11032 // 2b 11033 unsigned lsb = countTrailingZeros(Mask); 11034 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 11035 DAG.getConstant(lsb, DL, MVT::i32)); 11036 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 11037 DAG.getConstant(Mask2, DL, MVT::i32)); 11038 DCI.CombineTo(N, Res, false); 11039 // Return value from the original node to inform the combiner than N is 11040 // now dead. 11041 return SDValue(N, 0); 11042 } 11043 } 11044 11045 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 11046 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 11047 ARM::isBitFieldInvertedMask(~Mask)) { 11048 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 11049 // where lsb(mask) == #shamt and masked bits of B are known zero. 11050 SDValue ShAmt = N00.getOperand(1); 11051 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 11052 unsigned LSB = countTrailingZeros(Mask); 11053 if (ShAmtC != LSB) 11054 return SDValue(); 11055 11056 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 11057 DAG.getConstant(~Mask, DL, MVT::i32)); 11058 11059 DCI.CombineTo(N, Res, false); 11060 // Return value from the original node to inform the combiner than N is 11061 // now dead. 11062 return SDValue(N, 0); 11063 } 11064 11065 return SDValue(); 11066 } 11067 11068 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 11069 static SDValue PerformORCombine(SDNode *N, 11070 TargetLowering::DAGCombinerInfo &DCI, 11071 const ARMSubtarget *Subtarget) { 11072 // Attempt to use immediate-form VORR 11073 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11074 SDLoc dl(N); 11075 EVT VT = N->getValueType(0); 11076 SelectionDAG &DAG = DCI.DAG; 11077 11078 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11079 return SDValue(); 11080 11081 APInt SplatBits, SplatUndef; 11082 unsigned SplatBitSize; 11083 bool HasAnyUndefs; 11084 if (BVN && Subtarget->hasNEON() && 11085 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11086 if (SplatBitSize <= 64) { 11087 EVT VorrVT; 11088 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 11089 SplatUndef.getZExtValue(), SplatBitSize, 11090 DAG, dl, VorrVT, VT.is128BitVector(), 11091 OtherModImm); 11092 if (Val.getNode()) { 11093 SDValue Input = 11094 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 11095 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 11096 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 11097 } 11098 } 11099 } 11100 11101 if (!Subtarget->isThumb1Only()) { 11102 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11103 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11104 return Result; 11105 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 11106 return Result; 11107 } 11108 11109 SDValue N0 = N->getOperand(0); 11110 SDValue N1 = N->getOperand(1); 11111 11112 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 11113 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 11114 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 11115 11116 // The code below optimizes (or (and X, Y), Z). 11117 // The AND operand needs to have a single user to make these optimizations 11118 // profitable. 11119 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 11120 return SDValue(); 11121 11122 APInt SplatUndef; 11123 unsigned SplatBitSize; 11124 bool HasAnyUndefs; 11125 11126 APInt SplatBits0, SplatBits1; 11127 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 11128 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 11129 // Ensure that the second operand of both ands are constants 11130 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 11131 HasAnyUndefs) && !HasAnyUndefs) { 11132 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 11133 HasAnyUndefs) && !HasAnyUndefs) { 11134 // Ensure that the bit width of the constants are the same and that 11135 // the splat arguments are logical inverses as per the pattern we 11136 // are trying to simplify. 11137 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 11138 SplatBits0 == ~SplatBits1) { 11139 // Canonicalize the vector type to make instruction selection 11140 // simpler. 11141 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 11142 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 11143 N0->getOperand(1), 11144 N0->getOperand(0), 11145 N1->getOperand(0)); 11146 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 11147 } 11148 } 11149 } 11150 } 11151 11152 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 11153 // reasonable. 11154 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 11155 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 11156 return Res; 11157 } 11158 11159 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11160 return Result; 11161 11162 return SDValue(); 11163 } 11164 11165 static SDValue PerformXORCombine(SDNode *N, 11166 TargetLowering::DAGCombinerInfo &DCI, 11167 const ARMSubtarget *Subtarget) { 11168 EVT VT = N->getValueType(0); 11169 SelectionDAG &DAG = DCI.DAG; 11170 11171 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11172 return SDValue(); 11173 11174 if (!Subtarget->isThumb1Only()) { 11175 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11176 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11177 return Result; 11178 11179 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11180 return Result; 11181 } 11182 11183 return SDValue(); 11184 } 11185 11186 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 11187 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 11188 // their position in "to" (Rd). 11189 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 11190 assert(N->getOpcode() == ARMISD::BFI); 11191 11192 SDValue From = N->getOperand(1); 11193 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 11194 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 11195 11196 // If the Base came from a SHR #C, we can deduce that it is really testing bit 11197 // #C in the base of the SHR. 11198 if (From->getOpcode() == ISD::SRL && 11199 isa<ConstantSDNode>(From->getOperand(1))) { 11200 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 11201 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 11202 FromMask <<= Shift.getLimitedValue(31); 11203 From = From->getOperand(0); 11204 } 11205 11206 return From; 11207 } 11208 11209 // If A and B contain one contiguous set of bits, does A | B == A . B? 11210 // 11211 // Neither A nor B must be zero. 11212 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 11213 unsigned LastActiveBitInA = A.countTrailingZeros(); 11214 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 11215 return LastActiveBitInA - 1 == FirstActiveBitInB; 11216 } 11217 11218 static SDValue FindBFIToCombineWith(SDNode *N) { 11219 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 11220 // if one exists. 11221 APInt ToMask, FromMask; 11222 SDValue From = ParseBFI(N, ToMask, FromMask); 11223 SDValue To = N->getOperand(0); 11224 11225 // Now check for a compatible BFI to merge with. We can pass through BFIs that 11226 // aren't compatible, but not if they set the same bit in their destination as 11227 // we do (or that of any BFI we're going to combine with). 11228 SDValue V = To; 11229 APInt CombinedToMask = ToMask; 11230 while (V.getOpcode() == ARMISD::BFI) { 11231 APInt NewToMask, NewFromMask; 11232 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 11233 if (NewFrom != From) { 11234 // This BFI has a different base. Keep going. 11235 CombinedToMask |= NewToMask; 11236 V = V.getOperand(0); 11237 continue; 11238 } 11239 11240 // Do the written bits conflict with any we've seen so far? 11241 if ((NewToMask & CombinedToMask).getBoolValue()) 11242 // Conflicting bits - bail out because going further is unsafe. 11243 return SDValue(); 11244 11245 // Are the new bits contiguous when combined with the old bits? 11246 if (BitsProperlyConcatenate(ToMask, NewToMask) && 11247 BitsProperlyConcatenate(FromMask, NewFromMask)) 11248 return V; 11249 if (BitsProperlyConcatenate(NewToMask, ToMask) && 11250 BitsProperlyConcatenate(NewFromMask, FromMask)) 11251 return V; 11252 11253 // We've seen a write to some bits, so track it. 11254 CombinedToMask |= NewToMask; 11255 // Keep going... 11256 V = V.getOperand(0); 11257 } 11258 11259 return SDValue(); 11260 } 11261 11262 static SDValue PerformBFICombine(SDNode *N, 11263 TargetLowering::DAGCombinerInfo &DCI) { 11264 SDValue N1 = N->getOperand(1); 11265 if (N1.getOpcode() == ISD::AND) { 11266 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 11267 // the bits being cleared by the AND are not demanded by the BFI. 11268 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11269 if (!N11C) 11270 return SDValue(); 11271 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11272 unsigned LSB = countTrailingZeros(~InvMask); 11273 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 11274 assert(Width < 11275 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 11276 "undefined behavior"); 11277 unsigned Mask = (1u << Width) - 1; 11278 unsigned Mask2 = N11C->getZExtValue(); 11279 if ((Mask & (~Mask2)) == 0) 11280 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 11281 N->getOperand(0), N1.getOperand(0), 11282 N->getOperand(2)); 11283 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 11284 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 11285 // Keep track of any consecutive bits set that all come from the same base 11286 // value. We can combine these together into a single BFI. 11287 SDValue CombineBFI = FindBFIToCombineWith(N); 11288 if (CombineBFI == SDValue()) 11289 return SDValue(); 11290 11291 // We've found a BFI. 11292 APInt ToMask1, FromMask1; 11293 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 11294 11295 APInt ToMask2, FromMask2; 11296 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 11297 assert(From1 == From2); 11298 (void)From2; 11299 11300 // First, unlink CombineBFI. 11301 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 11302 // Then create a new BFI, combining the two together. 11303 APInt NewFromMask = FromMask1 | FromMask2; 11304 APInt NewToMask = ToMask1 | ToMask2; 11305 11306 EVT VT = N->getValueType(0); 11307 SDLoc dl(N); 11308 11309 if (NewFromMask[0] == 0) 11310 From1 = DCI.DAG.getNode( 11311 ISD::SRL, dl, VT, From1, 11312 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 11313 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 11314 DCI.DAG.getConstant(~NewToMask, dl, VT)); 11315 } 11316 return SDValue(); 11317 } 11318 11319 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 11320 /// ARMISD::VMOVRRD. 11321 static SDValue PerformVMOVRRDCombine(SDNode *N, 11322 TargetLowering::DAGCombinerInfo &DCI, 11323 const ARMSubtarget *Subtarget) { 11324 // vmovrrd(vmovdrr x, y) -> x,y 11325 SDValue InDouble = N->getOperand(0); 11326 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 11327 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 11328 11329 // vmovrrd(load f64) -> (load i32), (load i32) 11330 SDNode *InNode = InDouble.getNode(); 11331 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 11332 InNode->getValueType(0) == MVT::f64 && 11333 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 11334 !cast<LoadSDNode>(InNode)->isVolatile()) { 11335 // TODO: Should this be done for non-FrameIndex operands? 11336 LoadSDNode *LD = cast<LoadSDNode>(InNode); 11337 11338 SelectionDAG &DAG = DCI.DAG; 11339 SDLoc DL(LD); 11340 SDValue BasePtr = LD->getBasePtr(); 11341 SDValue NewLD1 = 11342 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 11343 LD->getAlignment(), LD->getMemOperand()->getFlags()); 11344 11345 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11346 DAG.getConstant(4, DL, MVT::i32)); 11347 SDValue NewLD2 = DAG.getLoad( 11348 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 11349 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 11350 11351 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 11352 if (DCI.DAG.getDataLayout().isBigEndian()) 11353 std::swap (NewLD1, NewLD2); 11354 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 11355 return Result; 11356 } 11357 11358 return SDValue(); 11359 } 11360 11361 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 11362 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 11363 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 11364 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 11365 SDValue Op0 = N->getOperand(0); 11366 SDValue Op1 = N->getOperand(1); 11367 if (Op0.getOpcode() == ISD::BITCAST) 11368 Op0 = Op0.getOperand(0); 11369 if (Op1.getOpcode() == ISD::BITCAST) 11370 Op1 = Op1.getOperand(0); 11371 if (Op0.getOpcode() == ARMISD::VMOVRRD && 11372 Op0.getNode() == Op1.getNode() && 11373 Op0.getResNo() == 0 && Op1.getResNo() == 1) 11374 return DAG.getNode(ISD::BITCAST, SDLoc(N), 11375 N->getValueType(0), Op0.getOperand(0)); 11376 return SDValue(); 11377 } 11378 11379 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 11380 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 11381 /// i64 vector to have f64 elements, since the value can then be loaded 11382 /// directly into a VFP register. 11383 static bool hasNormalLoadOperand(SDNode *N) { 11384 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 11385 for (unsigned i = 0; i < NumElts; ++i) { 11386 SDNode *Elt = N->getOperand(i).getNode(); 11387 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 11388 return true; 11389 } 11390 return false; 11391 } 11392 11393 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 11394 /// ISD::BUILD_VECTOR. 11395 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 11396 TargetLowering::DAGCombinerInfo &DCI, 11397 const ARMSubtarget *Subtarget) { 11398 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 11399 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 11400 // into a pair of GPRs, which is fine when the value is used as a scalar, 11401 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 11402 SelectionDAG &DAG = DCI.DAG; 11403 if (N->getNumOperands() == 2) 11404 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 11405 return RV; 11406 11407 // Load i64 elements as f64 values so that type legalization does not split 11408 // them up into i32 values. 11409 EVT VT = N->getValueType(0); 11410 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11411 return SDValue(); 11412 SDLoc dl(N); 11413 SmallVector<SDValue, 8> Ops; 11414 unsigned NumElts = VT.getVectorNumElements(); 11415 for (unsigned i = 0; i < NumElts; ++i) { 11416 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11417 Ops.push_back(V); 11418 // Make the DAGCombiner fold the bitcast. 11419 DCI.AddToWorklist(V.getNode()); 11420 } 11421 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11422 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11423 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11424 } 11425 11426 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11427 static SDValue 11428 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11429 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11430 // At that time, we may have inserted bitcasts from integer to float. 11431 // If these bitcasts have survived DAGCombine, change the lowering of this 11432 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11433 // force to use floating point types. 11434 11435 // Make sure we can change the type of the vector. 11436 // This is possible iff: 11437 // 1. The vector is only used in a bitcast to a integer type. I.e., 11438 // 1.1. Vector is used only once. 11439 // 1.2. Use is a bit convert to an integer type. 11440 // 2. The size of its operands are 32-bits (64-bits are not legal). 11441 EVT VT = N->getValueType(0); 11442 EVT EltVT = VT.getVectorElementType(); 11443 11444 // Check 1.1. and 2. 11445 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11446 return SDValue(); 11447 11448 // By construction, the input type must be float. 11449 assert(EltVT == MVT::f32 && "Unexpected type!"); 11450 11451 // Check 1.2. 11452 SDNode *Use = *N->use_begin(); 11453 if (Use->getOpcode() != ISD::BITCAST || 11454 Use->getValueType(0).isFloatingPoint()) 11455 return SDValue(); 11456 11457 // Check profitability. 11458 // Model is, if more than half of the relevant operands are bitcast from 11459 // i32, turn the build_vector into a sequence of insert_vector_elt. 11460 // Relevant operands are everything that is not statically 11461 // (i.e., at compile time) bitcasted. 11462 unsigned NumOfBitCastedElts = 0; 11463 unsigned NumElts = VT.getVectorNumElements(); 11464 unsigned NumOfRelevantElts = NumElts; 11465 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11466 SDValue Elt = N->getOperand(Idx); 11467 if (Elt->getOpcode() == ISD::BITCAST) { 11468 // Assume only bit cast to i32 will go away. 11469 if (Elt->getOperand(0).getValueType() == MVT::i32) 11470 ++NumOfBitCastedElts; 11471 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11472 // Constants are statically casted, thus do not count them as 11473 // relevant operands. 11474 --NumOfRelevantElts; 11475 } 11476 11477 // Check if more than half of the elements require a non-free bitcast. 11478 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11479 return SDValue(); 11480 11481 SelectionDAG &DAG = DCI.DAG; 11482 // Create the new vector type. 11483 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11484 // Check if the type is legal. 11485 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11486 if (!TLI.isTypeLegal(VecVT)) 11487 return SDValue(); 11488 11489 // Combine: 11490 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11491 // => BITCAST INSERT_VECTOR_ELT 11492 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11493 // (BITCAST EN), N. 11494 SDValue Vec = DAG.getUNDEF(VecVT); 11495 SDLoc dl(N); 11496 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11497 SDValue V = N->getOperand(Idx); 11498 if (V.isUndef()) 11499 continue; 11500 if (V.getOpcode() == ISD::BITCAST && 11501 V->getOperand(0).getValueType() == MVT::i32) 11502 // Fold obvious case. 11503 V = V.getOperand(0); 11504 else { 11505 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11506 // Make the DAGCombiner fold the bitcasts. 11507 DCI.AddToWorklist(V.getNode()); 11508 } 11509 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11510 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11511 } 11512 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11513 // Make the DAGCombiner fold the bitcasts. 11514 DCI.AddToWorklist(Vec.getNode()); 11515 return Vec; 11516 } 11517 11518 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11519 /// ISD::INSERT_VECTOR_ELT. 11520 static SDValue PerformInsertEltCombine(SDNode *N, 11521 TargetLowering::DAGCombinerInfo &DCI) { 11522 // Bitcast an i64 load inserted into a vector to f64. 11523 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11524 EVT VT = N->getValueType(0); 11525 SDNode *Elt = N->getOperand(1).getNode(); 11526 if (VT.getVectorElementType() != MVT::i64 || 11527 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11528 return SDValue(); 11529 11530 SelectionDAG &DAG = DCI.DAG; 11531 SDLoc dl(N); 11532 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11533 VT.getVectorNumElements()); 11534 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11535 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11536 // Make the DAGCombiner fold the bitcasts. 11537 DCI.AddToWorklist(Vec.getNode()); 11538 DCI.AddToWorklist(V.getNode()); 11539 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11540 Vec, V, N->getOperand(2)); 11541 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11542 } 11543 11544 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11545 /// ISD::VECTOR_SHUFFLE. 11546 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11547 // The LLVM shufflevector instruction does not require the shuffle mask 11548 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11549 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11550 // operands do not match the mask length, they are extended by concatenating 11551 // them with undef vectors. That is probably the right thing for other 11552 // targets, but for NEON it is better to concatenate two double-register 11553 // size vector operands into a single quad-register size vector. Do that 11554 // transformation here: 11555 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11556 // shuffle(concat(v1, v2), undef) 11557 SDValue Op0 = N->getOperand(0); 11558 SDValue Op1 = N->getOperand(1); 11559 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11560 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11561 Op0.getNumOperands() != 2 || 11562 Op1.getNumOperands() != 2) 11563 return SDValue(); 11564 SDValue Concat0Op1 = Op0.getOperand(1); 11565 SDValue Concat1Op1 = Op1.getOperand(1); 11566 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11567 return SDValue(); 11568 // Skip the transformation if any of the types are illegal. 11569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11570 EVT VT = N->getValueType(0); 11571 if (!TLI.isTypeLegal(VT) || 11572 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11573 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11574 return SDValue(); 11575 11576 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11577 Op0.getOperand(0), Op1.getOperand(0)); 11578 // Translate the shuffle mask. 11579 SmallVector<int, 16> NewMask; 11580 unsigned NumElts = VT.getVectorNumElements(); 11581 unsigned HalfElts = NumElts/2; 11582 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11583 for (unsigned n = 0; n < NumElts; ++n) { 11584 int MaskElt = SVN->getMaskElt(n); 11585 int NewElt = -1; 11586 if (MaskElt < (int)HalfElts) 11587 NewElt = MaskElt; 11588 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11589 NewElt = HalfElts + MaskElt - NumElts; 11590 NewMask.push_back(NewElt); 11591 } 11592 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11593 DAG.getUNDEF(VT), NewMask); 11594 } 11595 11596 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11597 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11598 /// base address updates. 11599 /// For generic load/stores, the memory type is assumed to be a vector. 11600 /// The caller is assumed to have checked legality. 11601 static SDValue CombineBaseUpdate(SDNode *N, 11602 TargetLowering::DAGCombinerInfo &DCI) { 11603 SelectionDAG &DAG = DCI.DAG; 11604 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11605 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11606 const bool isStore = N->getOpcode() == ISD::STORE; 11607 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11608 SDValue Addr = N->getOperand(AddrOpIdx); 11609 MemSDNode *MemN = cast<MemSDNode>(N); 11610 SDLoc dl(N); 11611 11612 // Search for a use of the address operand that is an increment. 11613 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11614 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11615 SDNode *User = *UI; 11616 if (User->getOpcode() != ISD::ADD || 11617 UI.getUse().getResNo() != Addr.getResNo()) 11618 continue; 11619 11620 // Check that the add is independent of the load/store. Otherwise, folding 11621 // it would create a cycle. We can avoid searching through Addr as it's a 11622 // predecessor to both. 11623 SmallPtrSet<const SDNode *, 32> Visited; 11624 SmallVector<const SDNode *, 16> Worklist; 11625 Visited.insert(Addr.getNode()); 11626 Worklist.push_back(N); 11627 Worklist.push_back(User); 11628 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 11629 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 11630 continue; 11631 11632 // Find the new opcode for the updating load/store. 11633 bool isLoadOp = true; 11634 bool isLaneOp = false; 11635 unsigned NewOpc = 0; 11636 unsigned NumVecs = 0; 11637 if (isIntrinsic) { 11638 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11639 switch (IntNo) { 11640 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11641 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11642 NumVecs = 1; break; 11643 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11644 NumVecs = 2; break; 11645 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11646 NumVecs = 3; break; 11647 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11648 NumVecs = 4; break; 11649 case Intrinsic::arm_neon_vld2dup: 11650 case Intrinsic::arm_neon_vld3dup: 11651 case Intrinsic::arm_neon_vld4dup: 11652 // TODO: Support updating VLDxDUP nodes. For now, we just skip 11653 // combining base updates for such intrinsics. 11654 continue; 11655 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11656 NumVecs = 2; isLaneOp = true; break; 11657 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11658 NumVecs = 3; isLaneOp = true; break; 11659 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11660 NumVecs = 4; isLaneOp = true; break; 11661 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11662 NumVecs = 1; isLoadOp = false; break; 11663 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11664 NumVecs = 2; isLoadOp = false; break; 11665 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11666 NumVecs = 3; isLoadOp = false; break; 11667 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11668 NumVecs = 4; isLoadOp = false; break; 11669 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11670 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11671 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11672 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11673 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11674 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11675 } 11676 } else { 11677 isLaneOp = true; 11678 switch (N->getOpcode()) { 11679 default: llvm_unreachable("unexpected opcode for Neon base update"); 11680 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11681 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11682 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11683 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11684 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11685 NumVecs = 1; isLaneOp = false; break; 11686 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11687 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11688 } 11689 } 11690 11691 // Find the size of memory referenced by the load/store. 11692 EVT VecTy; 11693 if (isLoadOp) { 11694 VecTy = N->getValueType(0); 11695 } else if (isIntrinsic) { 11696 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11697 } else { 11698 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11699 VecTy = N->getOperand(1).getValueType(); 11700 } 11701 11702 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11703 if (isLaneOp) 11704 NumBytes /= VecTy.getVectorNumElements(); 11705 11706 // If the increment is a constant, it must match the memory ref size. 11707 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11708 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11709 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11710 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11711 // separate instructions that make it harder to use a non-constant update. 11712 continue; 11713 } 11714 11715 // OK, we found an ADD we can fold into the base update. 11716 // Now, create a _UPD node, taking care of not breaking alignment. 11717 11718 EVT AlignedVecTy = VecTy; 11719 unsigned Alignment = MemN->getAlignment(); 11720 11721 // If this is a less-than-standard-aligned load/store, change the type to 11722 // match the standard alignment. 11723 // The alignment is overlooked when selecting _UPD variants; and it's 11724 // easier to introduce bitcasts here than fix that. 11725 // There are 3 ways to get to this base-update combine: 11726 // - intrinsics: they are assumed to be properly aligned (to the standard 11727 // alignment of the memory type), so we don't need to do anything. 11728 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11729 // intrinsics, so, likewise, there's nothing to do. 11730 // - generic load/store instructions: the alignment is specified as an 11731 // explicit operand, rather than implicitly as the standard alignment 11732 // of the memory type (like the intrisics). We need to change the 11733 // memory type to match the explicit alignment. That way, we don't 11734 // generate non-standard-aligned ARMISD::VLDx nodes. 11735 if (isa<LSBaseSDNode>(N)) { 11736 if (Alignment == 0) 11737 Alignment = 1; 11738 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11739 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11740 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11741 assert(!isLaneOp && "Unexpected generic load/store lane."); 11742 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11743 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11744 } 11745 // Don't set an explicit alignment on regular load/stores that we want 11746 // to transform to VLD/VST 1_UPD nodes. 11747 // This matches the behavior of regular load/stores, which only get an 11748 // explicit alignment if the MMO alignment is larger than the standard 11749 // alignment of the memory type. 11750 // Intrinsics, however, always get an explicit alignment, set to the 11751 // alignment of the MMO. 11752 Alignment = 1; 11753 } 11754 11755 // Create the new updating load/store node. 11756 // First, create an SDVTList for the new updating node's results. 11757 EVT Tys[6]; 11758 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11759 unsigned n; 11760 for (n = 0; n < NumResultVecs; ++n) 11761 Tys[n] = AlignedVecTy; 11762 Tys[n++] = MVT::i32; 11763 Tys[n] = MVT::Other; 11764 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11765 11766 // Then, gather the new node's operands. 11767 SmallVector<SDValue, 8> Ops; 11768 Ops.push_back(N->getOperand(0)); // incoming chain 11769 Ops.push_back(N->getOperand(AddrOpIdx)); 11770 Ops.push_back(Inc); 11771 11772 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11773 // Try to match the intrinsic's signature 11774 Ops.push_back(StN->getValue()); 11775 } else { 11776 // Loads (and of course intrinsics) match the intrinsics' signature, 11777 // so just add all but the alignment operand. 11778 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11779 Ops.push_back(N->getOperand(i)); 11780 } 11781 11782 // For all node types, the alignment operand is always the last one. 11783 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11784 11785 // If this is a non-standard-aligned STORE, the penultimate operand is the 11786 // stored value. Bitcast it to the aligned type. 11787 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11788 SDValue &StVal = Ops[Ops.size()-2]; 11789 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11790 } 11791 11792 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11793 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11794 MemN->getMemOperand()); 11795 11796 // Update the uses. 11797 SmallVector<SDValue, 5> NewResults; 11798 for (unsigned i = 0; i < NumResultVecs; ++i) 11799 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11800 11801 // If this is an non-standard-aligned LOAD, the first result is the loaded 11802 // value. Bitcast it to the expected result type. 11803 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11804 SDValue &LdVal = NewResults[0]; 11805 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11806 } 11807 11808 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11809 DCI.CombineTo(N, NewResults); 11810 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11811 11812 break; 11813 } 11814 return SDValue(); 11815 } 11816 11817 static SDValue PerformVLDCombine(SDNode *N, 11818 TargetLowering::DAGCombinerInfo &DCI) { 11819 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11820 return SDValue(); 11821 11822 return CombineBaseUpdate(N, DCI); 11823 } 11824 11825 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11826 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11827 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11828 /// return true. 11829 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11830 SelectionDAG &DAG = DCI.DAG; 11831 EVT VT = N->getValueType(0); 11832 // vldN-dup instructions only support 64-bit vectors for N > 1. 11833 if (!VT.is64BitVector()) 11834 return false; 11835 11836 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11837 SDNode *VLD = N->getOperand(0).getNode(); 11838 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11839 return false; 11840 unsigned NumVecs = 0; 11841 unsigned NewOpc = 0; 11842 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11843 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11844 NumVecs = 2; 11845 NewOpc = ARMISD::VLD2DUP; 11846 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11847 NumVecs = 3; 11848 NewOpc = ARMISD::VLD3DUP; 11849 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11850 NumVecs = 4; 11851 NewOpc = ARMISD::VLD4DUP; 11852 } else { 11853 return false; 11854 } 11855 11856 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11857 // numbers match the load. 11858 unsigned VLDLaneNo = 11859 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11860 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11861 UI != UE; ++UI) { 11862 // Ignore uses of the chain result. 11863 if (UI.getUse().getResNo() == NumVecs) 11864 continue; 11865 SDNode *User = *UI; 11866 if (User->getOpcode() != ARMISD::VDUPLANE || 11867 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11868 return false; 11869 } 11870 11871 // Create the vldN-dup node. 11872 EVT Tys[5]; 11873 unsigned n; 11874 for (n = 0; n < NumVecs; ++n) 11875 Tys[n] = VT; 11876 Tys[n] = MVT::Other; 11877 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11878 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11879 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11880 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11881 Ops, VLDMemInt->getMemoryVT(), 11882 VLDMemInt->getMemOperand()); 11883 11884 // Update the uses. 11885 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11886 UI != UE; ++UI) { 11887 unsigned ResNo = UI.getUse().getResNo(); 11888 // Ignore uses of the chain result. 11889 if (ResNo == NumVecs) 11890 continue; 11891 SDNode *User = *UI; 11892 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11893 } 11894 11895 // Now the vldN-lane intrinsic is dead except for its chain result. 11896 // Update uses of the chain. 11897 std::vector<SDValue> VLDDupResults; 11898 for (unsigned n = 0; n < NumVecs; ++n) 11899 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11900 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11901 DCI.CombineTo(VLD, VLDDupResults); 11902 11903 return true; 11904 } 11905 11906 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11907 /// ARMISD::VDUPLANE. 11908 static SDValue PerformVDUPLANECombine(SDNode *N, 11909 TargetLowering::DAGCombinerInfo &DCI) { 11910 SDValue Op = N->getOperand(0); 11911 11912 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11913 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11914 if (CombineVLDDUP(N, DCI)) 11915 return SDValue(N, 0); 11916 11917 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11918 // redundant. Ignore bit_converts for now; element sizes are checked below. 11919 while (Op.getOpcode() == ISD::BITCAST) 11920 Op = Op.getOperand(0); 11921 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11922 return SDValue(); 11923 11924 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11925 unsigned EltSize = Op.getScalarValueSizeInBits(); 11926 // The canonical VMOV for a zero vector uses a 32-bit element size. 11927 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11928 unsigned EltBits; 11929 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11930 EltSize = 8; 11931 EVT VT = N->getValueType(0); 11932 if (EltSize > VT.getScalarSizeInBits()) 11933 return SDValue(); 11934 11935 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11936 } 11937 11938 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11939 static SDValue PerformVDUPCombine(SDNode *N, 11940 TargetLowering::DAGCombinerInfo &DCI) { 11941 SelectionDAG &DAG = DCI.DAG; 11942 SDValue Op = N->getOperand(0); 11943 11944 // Match VDUP(LOAD) -> VLD1DUP. 11945 // We match this pattern here rather than waiting for isel because the 11946 // transform is only legal for unindexed loads. 11947 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11948 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11949 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11950 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11951 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11952 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11953 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11954 Ops, LD->getMemoryVT(), 11955 LD->getMemOperand()); 11956 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11957 return VLDDup; 11958 } 11959 11960 return SDValue(); 11961 } 11962 11963 static SDValue PerformLOADCombine(SDNode *N, 11964 TargetLowering::DAGCombinerInfo &DCI) { 11965 EVT VT = N->getValueType(0); 11966 11967 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11968 if (ISD::isNormalLoad(N) && VT.isVector() && 11969 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11970 return CombineBaseUpdate(N, DCI); 11971 11972 return SDValue(); 11973 } 11974 11975 /// PerformSTORECombine - Target-specific dag combine xforms for 11976 /// ISD::STORE. 11977 static SDValue PerformSTORECombine(SDNode *N, 11978 TargetLowering::DAGCombinerInfo &DCI) { 11979 StoreSDNode *St = cast<StoreSDNode>(N); 11980 if (St->isVolatile()) 11981 return SDValue(); 11982 11983 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11984 // pack all of the elements in one place. Next, store to memory in fewer 11985 // chunks. 11986 SDValue StVal = St->getValue(); 11987 EVT VT = StVal.getValueType(); 11988 if (St->isTruncatingStore() && VT.isVector()) { 11989 SelectionDAG &DAG = DCI.DAG; 11990 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11991 EVT StVT = St->getMemoryVT(); 11992 unsigned NumElems = VT.getVectorNumElements(); 11993 assert(StVT != VT && "Cannot truncate to the same type"); 11994 unsigned FromEltSz = VT.getScalarSizeInBits(); 11995 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11996 11997 // From, To sizes and ElemCount must be pow of two 11998 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11999 12000 // We are going to use the original vector elt for storing. 12001 // Accumulated smaller vector elements must be a multiple of the store size. 12002 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 12003 12004 unsigned SizeRatio = FromEltSz / ToEltSz; 12005 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 12006 12007 // Create a type on which we perform the shuffle. 12008 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 12009 NumElems*SizeRatio); 12010 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 12011 12012 SDLoc DL(St); 12013 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 12014 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 12015 for (unsigned i = 0; i < NumElems; ++i) 12016 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 12017 ? (i + 1) * SizeRatio - 1 12018 : i * SizeRatio; 12019 12020 // Can't shuffle using an illegal type. 12021 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 12022 12023 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 12024 DAG.getUNDEF(WideVec.getValueType()), 12025 ShuffleVec); 12026 // At this point all of the data is stored at the bottom of the 12027 // register. We now need to save it to mem. 12028 12029 // Find the largest store unit 12030 MVT StoreType = MVT::i8; 12031 for (MVT Tp : MVT::integer_valuetypes()) { 12032 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 12033 StoreType = Tp; 12034 } 12035 // Didn't find a legal store type. 12036 if (!TLI.isTypeLegal(StoreType)) 12037 return SDValue(); 12038 12039 // Bitcast the original vector into a vector of store-size units 12040 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 12041 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 12042 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 12043 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 12044 SmallVector<SDValue, 8> Chains; 12045 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 12046 TLI.getPointerTy(DAG.getDataLayout())); 12047 SDValue BasePtr = St->getBasePtr(); 12048 12049 // Perform one or more big stores into memory. 12050 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 12051 for (unsigned I = 0; I < E; I++) { 12052 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 12053 StoreType, ShuffWide, 12054 DAG.getIntPtrConstant(I, DL)); 12055 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 12056 St->getPointerInfo(), St->getAlignment(), 12057 St->getMemOperand()->getFlags()); 12058 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 12059 Increment); 12060 Chains.push_back(Ch); 12061 } 12062 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 12063 } 12064 12065 if (!ISD::isNormalStore(St)) 12066 return SDValue(); 12067 12068 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 12069 // ARM stores of arguments in the same cache line. 12070 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 12071 StVal.getNode()->hasOneUse()) { 12072 SelectionDAG &DAG = DCI.DAG; 12073 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 12074 SDLoc DL(St); 12075 SDValue BasePtr = St->getBasePtr(); 12076 SDValue NewST1 = DAG.getStore( 12077 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 12078 BasePtr, St->getPointerInfo(), St->getAlignment(), 12079 St->getMemOperand()->getFlags()); 12080 12081 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12082 DAG.getConstant(4, DL, MVT::i32)); 12083 return DAG.getStore(NewST1.getValue(0), DL, 12084 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 12085 OffsetPtr, St->getPointerInfo(), 12086 std::min(4U, St->getAlignment() / 2), 12087 St->getMemOperand()->getFlags()); 12088 } 12089 12090 if (StVal.getValueType() == MVT::i64 && 12091 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12092 12093 // Bitcast an i64 store extracted from a vector to f64. 12094 // Otherwise, the i64 value will be legalized to a pair of i32 values. 12095 SelectionDAG &DAG = DCI.DAG; 12096 SDLoc dl(StVal); 12097 SDValue IntVec = StVal.getOperand(0); 12098 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 12099 IntVec.getValueType().getVectorNumElements()); 12100 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 12101 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 12102 Vec, StVal.getOperand(1)); 12103 dl = SDLoc(N); 12104 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 12105 // Make the DAGCombiner fold the bitcasts. 12106 DCI.AddToWorklist(Vec.getNode()); 12107 DCI.AddToWorklist(ExtElt.getNode()); 12108 DCI.AddToWorklist(V.getNode()); 12109 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 12110 St->getPointerInfo(), St->getAlignment(), 12111 St->getMemOperand()->getFlags(), St->getAAInfo()); 12112 } 12113 12114 // If this is a legal vector store, try to combine it into a VST1_UPD. 12115 if (ISD::isNormalStore(N) && VT.isVector() && 12116 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12117 return CombineBaseUpdate(N, DCI); 12118 12119 return SDValue(); 12120 } 12121 12122 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 12123 /// can replace combinations of VMUL and VCVT (floating-point to integer) 12124 /// when the VMUL has a constant operand that is a power of 2. 12125 /// 12126 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12127 /// vmul.f32 d16, d17, d16 12128 /// vcvt.s32.f32 d16, d16 12129 /// becomes: 12130 /// vcvt.s32.f32 d16, d16, #3 12131 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 12132 const ARMSubtarget *Subtarget) { 12133 if (!Subtarget->hasNEON()) 12134 return SDValue(); 12135 12136 SDValue Op = N->getOperand(0); 12137 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12138 Op.getOpcode() != ISD::FMUL) 12139 return SDValue(); 12140 12141 SDValue ConstVec = Op->getOperand(1); 12142 if (!isa<BuildVectorSDNode>(ConstVec)) 12143 return SDValue(); 12144 12145 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 12146 uint32_t FloatBits = FloatTy.getSizeInBits(); 12147 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 12148 uint32_t IntBits = IntTy.getSizeInBits(); 12149 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12150 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 12151 // These instructions only exist converting from f32 to i32. We can handle 12152 // smaller integers by generating an extra truncate, but larger ones would 12153 // be lossy. We also can't handle more then 4 lanes, since these intructions 12154 // only support v2i32/v4i32 types. 12155 return SDValue(); 12156 } 12157 12158 BitVector UndefElements; 12159 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12160 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12161 if (C == -1 || C == 0 || C > 32) 12162 return SDValue(); 12163 12164 SDLoc dl(N); 12165 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 12166 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 12167 Intrinsic::arm_neon_vcvtfp2fxu; 12168 SDValue FixConv = DAG.getNode( 12169 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12170 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 12171 DAG.getConstant(C, dl, MVT::i32)); 12172 12173 if (IntBits < FloatBits) 12174 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 12175 12176 return FixConv; 12177 } 12178 12179 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 12180 /// can replace combinations of VCVT (integer to floating-point) and VDIV 12181 /// when the VDIV has a constant operand that is a power of 2. 12182 /// 12183 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12184 /// vcvt.f32.s32 d16, d16 12185 /// vdiv.f32 d16, d17, d16 12186 /// becomes: 12187 /// vcvt.f32.s32 d16, d16, #3 12188 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 12189 const ARMSubtarget *Subtarget) { 12190 if (!Subtarget->hasNEON()) 12191 return SDValue(); 12192 12193 SDValue Op = N->getOperand(0); 12194 unsigned OpOpcode = Op.getNode()->getOpcode(); 12195 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 12196 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 12197 return SDValue(); 12198 12199 SDValue ConstVec = N->getOperand(1); 12200 if (!isa<BuildVectorSDNode>(ConstVec)) 12201 return SDValue(); 12202 12203 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12204 uint32_t FloatBits = FloatTy.getSizeInBits(); 12205 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12206 uint32_t IntBits = IntTy.getSizeInBits(); 12207 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12208 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 12209 // These instructions only exist converting from i32 to f32. We can handle 12210 // smaller integers by generating an extra extend, but larger ones would 12211 // be lossy. We also can't handle more then 4 lanes, since these intructions 12212 // only support v2i32/v4i32 types. 12213 return SDValue(); 12214 } 12215 12216 BitVector UndefElements; 12217 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12218 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12219 if (C == -1 || C == 0 || C > 32) 12220 return SDValue(); 12221 12222 SDLoc dl(N); 12223 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 12224 SDValue ConvInput = Op.getOperand(0); 12225 if (IntBits < FloatBits) 12226 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12227 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12228 ConvInput); 12229 12230 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 12231 Intrinsic::arm_neon_vcvtfxu2fp; 12232 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 12233 Op.getValueType(), 12234 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 12235 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 12236 } 12237 12238 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 12239 /// operand of a vector shift operation, where all the elements of the 12240 /// build_vector must have the same constant integer value. 12241 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 12242 // Ignore bit_converts. 12243 while (Op.getOpcode() == ISD::BITCAST) 12244 Op = Op.getOperand(0); 12245 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 12246 APInt SplatBits, SplatUndef; 12247 unsigned SplatBitSize; 12248 bool HasAnyUndefs; 12249 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 12250 HasAnyUndefs, ElementBits) || 12251 SplatBitSize > ElementBits) 12252 return false; 12253 Cnt = SplatBits.getSExtValue(); 12254 return true; 12255 } 12256 12257 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 12258 /// operand of a vector shift left operation. That value must be in the range: 12259 /// 0 <= Value < ElementBits for a left shift; or 12260 /// 0 <= Value <= ElementBits for a long left shift. 12261 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 12262 assert(VT.isVector() && "vector shift count is not a vector type"); 12263 int64_t ElementBits = VT.getScalarSizeInBits(); 12264 if (! getVShiftImm(Op, ElementBits, Cnt)) 12265 return false; 12266 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 12267 } 12268 12269 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 12270 /// operand of a vector shift right operation. For a shift opcode, the value 12271 /// is positive, but for an intrinsic the value count must be negative. The 12272 /// absolute value must be in the range: 12273 /// 1 <= |Value| <= ElementBits for a right shift; or 12274 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 12275 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 12276 int64_t &Cnt) { 12277 assert(VT.isVector() && "vector shift count is not a vector type"); 12278 int64_t ElementBits = VT.getScalarSizeInBits(); 12279 if (! getVShiftImm(Op, ElementBits, Cnt)) 12280 return false; 12281 if (!isIntrinsic) 12282 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 12283 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 12284 Cnt = -Cnt; 12285 return true; 12286 } 12287 return false; 12288 } 12289 12290 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 12291 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 12292 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12293 switch (IntNo) { 12294 default: 12295 // Don't do anything for most intrinsics. 12296 break; 12297 12298 // Vector shifts: check for immediate versions and lower them. 12299 // Note: This is done during DAG combining instead of DAG legalizing because 12300 // the build_vectors for 64-bit vector element shift counts are generally 12301 // not legal, and it is hard to see their values after they get legalized to 12302 // loads from a constant pool. 12303 case Intrinsic::arm_neon_vshifts: 12304 case Intrinsic::arm_neon_vshiftu: 12305 case Intrinsic::arm_neon_vrshifts: 12306 case Intrinsic::arm_neon_vrshiftu: 12307 case Intrinsic::arm_neon_vrshiftn: 12308 case Intrinsic::arm_neon_vqshifts: 12309 case Intrinsic::arm_neon_vqshiftu: 12310 case Intrinsic::arm_neon_vqshiftsu: 12311 case Intrinsic::arm_neon_vqshiftns: 12312 case Intrinsic::arm_neon_vqshiftnu: 12313 case Intrinsic::arm_neon_vqshiftnsu: 12314 case Intrinsic::arm_neon_vqrshiftns: 12315 case Intrinsic::arm_neon_vqrshiftnu: 12316 case Intrinsic::arm_neon_vqrshiftnsu: { 12317 EVT VT = N->getOperand(1).getValueType(); 12318 int64_t Cnt; 12319 unsigned VShiftOpc = 0; 12320 12321 switch (IntNo) { 12322 case Intrinsic::arm_neon_vshifts: 12323 case Intrinsic::arm_neon_vshiftu: 12324 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 12325 VShiftOpc = ARMISD::VSHL; 12326 break; 12327 } 12328 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 12329 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 12330 ARMISD::VSHRs : ARMISD::VSHRu); 12331 break; 12332 } 12333 return SDValue(); 12334 12335 case Intrinsic::arm_neon_vrshifts: 12336 case Intrinsic::arm_neon_vrshiftu: 12337 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 12338 break; 12339 return SDValue(); 12340 12341 case Intrinsic::arm_neon_vqshifts: 12342 case Intrinsic::arm_neon_vqshiftu: 12343 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12344 break; 12345 return SDValue(); 12346 12347 case Intrinsic::arm_neon_vqshiftsu: 12348 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12349 break; 12350 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 12351 12352 case Intrinsic::arm_neon_vrshiftn: 12353 case Intrinsic::arm_neon_vqshiftns: 12354 case Intrinsic::arm_neon_vqshiftnu: 12355 case Intrinsic::arm_neon_vqshiftnsu: 12356 case Intrinsic::arm_neon_vqrshiftns: 12357 case Intrinsic::arm_neon_vqrshiftnu: 12358 case Intrinsic::arm_neon_vqrshiftnsu: 12359 // Narrowing shifts require an immediate right shift. 12360 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 12361 break; 12362 llvm_unreachable("invalid shift count for narrowing vector shift " 12363 "intrinsic"); 12364 12365 default: 12366 llvm_unreachable("unhandled vector shift"); 12367 } 12368 12369 switch (IntNo) { 12370 case Intrinsic::arm_neon_vshifts: 12371 case Intrinsic::arm_neon_vshiftu: 12372 // Opcode already set above. 12373 break; 12374 case Intrinsic::arm_neon_vrshifts: 12375 VShiftOpc = ARMISD::VRSHRs; break; 12376 case Intrinsic::arm_neon_vrshiftu: 12377 VShiftOpc = ARMISD::VRSHRu; break; 12378 case Intrinsic::arm_neon_vrshiftn: 12379 VShiftOpc = ARMISD::VRSHRN; break; 12380 case Intrinsic::arm_neon_vqshifts: 12381 VShiftOpc = ARMISD::VQSHLs; break; 12382 case Intrinsic::arm_neon_vqshiftu: 12383 VShiftOpc = ARMISD::VQSHLu; break; 12384 case Intrinsic::arm_neon_vqshiftsu: 12385 VShiftOpc = ARMISD::VQSHLsu; break; 12386 case Intrinsic::arm_neon_vqshiftns: 12387 VShiftOpc = ARMISD::VQSHRNs; break; 12388 case Intrinsic::arm_neon_vqshiftnu: 12389 VShiftOpc = ARMISD::VQSHRNu; break; 12390 case Intrinsic::arm_neon_vqshiftnsu: 12391 VShiftOpc = ARMISD::VQSHRNsu; break; 12392 case Intrinsic::arm_neon_vqrshiftns: 12393 VShiftOpc = ARMISD::VQRSHRNs; break; 12394 case Intrinsic::arm_neon_vqrshiftnu: 12395 VShiftOpc = ARMISD::VQRSHRNu; break; 12396 case Intrinsic::arm_neon_vqrshiftnsu: 12397 VShiftOpc = ARMISD::VQRSHRNsu; break; 12398 } 12399 12400 SDLoc dl(N); 12401 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12402 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 12403 } 12404 12405 case Intrinsic::arm_neon_vshiftins: { 12406 EVT VT = N->getOperand(1).getValueType(); 12407 int64_t Cnt; 12408 unsigned VShiftOpc = 0; 12409 12410 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 12411 VShiftOpc = ARMISD::VSLI; 12412 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 12413 VShiftOpc = ARMISD::VSRI; 12414 else { 12415 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 12416 } 12417 12418 SDLoc dl(N); 12419 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12420 N->getOperand(1), N->getOperand(2), 12421 DAG.getConstant(Cnt, dl, MVT::i32)); 12422 } 12423 12424 case Intrinsic::arm_neon_vqrshifts: 12425 case Intrinsic::arm_neon_vqrshiftu: 12426 // No immediate versions of these to check for. 12427 break; 12428 } 12429 12430 return SDValue(); 12431 } 12432 12433 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12434 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12435 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12436 /// vector element shift counts are generally not legal, and it is hard to see 12437 /// their values after they get legalized to loads from a constant pool. 12438 static SDValue PerformShiftCombine(SDNode *N, 12439 TargetLowering::DAGCombinerInfo &DCI, 12440 const ARMSubtarget *ST) { 12441 SelectionDAG &DAG = DCI.DAG; 12442 EVT VT = N->getValueType(0); 12443 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12444 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12445 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12446 SDValue N1 = N->getOperand(1); 12447 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12448 SDValue N0 = N->getOperand(0); 12449 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12450 DAG.MaskedValueIsZero(N0.getOperand(0), 12451 APInt::getHighBitsSet(32, 16))) 12452 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12453 } 12454 } 12455 12456 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 12457 N->getOperand(0)->getOpcode() == ISD::AND && 12458 N->getOperand(0)->hasOneUse()) { 12459 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12460 return SDValue(); 12461 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 12462 // usually show up because instcombine prefers to canonicalize it to 12463 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 12464 // out of GEP lowering in some cases. 12465 SDValue N0 = N->getOperand(0); 12466 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12467 if (!ShiftAmtNode) 12468 return SDValue(); 12469 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 12470 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12471 if (!AndMaskNode) 12472 return SDValue(); 12473 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 12474 // Don't transform uxtb/uxth. 12475 if (AndMask == 255 || AndMask == 65535) 12476 return SDValue(); 12477 if (isMask_32(AndMask)) { 12478 uint32_t MaskedBits = countLeadingZeros(AndMask); 12479 if (MaskedBits > ShiftAmt) { 12480 SDLoc DL(N); 12481 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12482 DAG.getConstant(MaskedBits, DL, MVT::i32)); 12483 return DAG.getNode( 12484 ISD::SRL, DL, MVT::i32, SHL, 12485 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 12486 } 12487 } 12488 } 12489 12490 // Nothing to be done for scalar shifts. 12491 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12492 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12493 return SDValue(); 12494 12495 assert(ST->hasNEON() && "unexpected vector shift"); 12496 int64_t Cnt; 12497 12498 switch (N->getOpcode()) { 12499 default: llvm_unreachable("unexpected shift opcode"); 12500 12501 case ISD::SHL: 12502 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12503 SDLoc dl(N); 12504 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 12505 DAG.getConstant(Cnt, dl, MVT::i32)); 12506 } 12507 break; 12508 12509 case ISD::SRA: 12510 case ISD::SRL: 12511 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12512 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 12513 ARMISD::VSHRs : ARMISD::VSHRu); 12514 SDLoc dl(N); 12515 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12516 DAG.getConstant(Cnt, dl, MVT::i32)); 12517 } 12518 } 12519 return SDValue(); 12520 } 12521 12522 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12523 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12524 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12525 const ARMSubtarget *ST) { 12526 SDValue N0 = N->getOperand(0); 12527 12528 // Check for sign- and zero-extensions of vector extract operations of 8- 12529 // and 16-bit vector elements. NEON supports these directly. They are 12530 // handled during DAG combining because type legalization will promote them 12531 // to 32-bit types and it is messy to recognize the operations after that. 12532 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12533 SDValue Vec = N0.getOperand(0); 12534 SDValue Lane = N0.getOperand(1); 12535 EVT VT = N->getValueType(0); 12536 EVT EltVT = N0.getValueType(); 12537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12538 12539 if (VT == MVT::i32 && 12540 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12541 TLI.isTypeLegal(Vec.getValueType()) && 12542 isa<ConstantSDNode>(Lane)) { 12543 12544 unsigned Opc = 0; 12545 switch (N->getOpcode()) { 12546 default: llvm_unreachable("unexpected opcode"); 12547 case ISD::SIGN_EXTEND: 12548 Opc = ARMISD::VGETLANEs; 12549 break; 12550 case ISD::ZERO_EXTEND: 12551 case ISD::ANY_EXTEND: 12552 Opc = ARMISD::VGETLANEu; 12553 break; 12554 } 12555 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12556 } 12557 } 12558 12559 return SDValue(); 12560 } 12561 12562 static const APInt *isPowerOf2Constant(SDValue V) { 12563 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12564 if (!C) 12565 return nullptr; 12566 const APInt *CV = &C->getAPIntValue(); 12567 return CV->isPowerOf2() ? CV : nullptr; 12568 } 12569 12570 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12571 // If we have a CMOV, OR and AND combination such as: 12572 // if (x & CN) 12573 // y |= CM; 12574 // 12575 // And: 12576 // * CN is a single bit; 12577 // * All bits covered by CM are known zero in y 12578 // 12579 // Then we can convert this into a sequence of BFI instructions. This will 12580 // always be a win if CM is a single bit, will always be no worse than the 12581 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12582 // three bits (due to the extra IT instruction). 12583 12584 SDValue Op0 = CMOV->getOperand(0); 12585 SDValue Op1 = CMOV->getOperand(1); 12586 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12587 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12588 SDValue CmpZ = CMOV->getOperand(4); 12589 12590 // The compare must be against zero. 12591 if (!isNullConstant(CmpZ->getOperand(1))) 12592 return SDValue(); 12593 12594 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12595 SDValue And = CmpZ->getOperand(0); 12596 if (And->getOpcode() != ISD::AND) 12597 return SDValue(); 12598 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12599 if (!AndC) 12600 return SDValue(); 12601 SDValue X = And->getOperand(0); 12602 12603 if (CC == ARMCC::EQ) { 12604 // We're performing an "equal to zero" compare. Swap the operands so we 12605 // canonicalize on a "not equal to zero" compare. 12606 std::swap(Op0, Op1); 12607 } else { 12608 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12609 } 12610 12611 if (Op1->getOpcode() != ISD::OR) 12612 return SDValue(); 12613 12614 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12615 if (!OrC) 12616 return SDValue(); 12617 SDValue Y = Op1->getOperand(0); 12618 12619 if (Op0 != Y) 12620 return SDValue(); 12621 12622 // Now, is it profitable to continue? 12623 APInt OrCI = OrC->getAPIntValue(); 12624 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12625 if (OrCI.countPopulation() > Heuristic) 12626 return SDValue(); 12627 12628 // Lastly, can we determine that the bits defined by OrCI 12629 // are zero in Y? 12630 KnownBits Known = DAG.computeKnownBits(Y); 12631 if ((OrCI & Known.Zero) != OrCI) 12632 return SDValue(); 12633 12634 // OK, we can do the combine. 12635 SDValue V = Y; 12636 SDLoc dl(X); 12637 EVT VT = X.getValueType(); 12638 unsigned BitInX = AndC->logBase2(); 12639 12640 if (BitInX != 0) { 12641 // We must shift X first. 12642 X = DAG.getNode(ISD::SRL, dl, VT, X, 12643 DAG.getConstant(BitInX, dl, VT)); 12644 } 12645 12646 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12647 BitInY < NumActiveBits; ++BitInY) { 12648 if (OrCI[BitInY] == 0) 12649 continue; 12650 APInt Mask(VT.getSizeInBits(), 0); 12651 Mask.setBit(BitInY); 12652 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12653 // Confusingly, the operand is an *inverted* mask. 12654 DAG.getConstant(~Mask, dl, VT)); 12655 } 12656 12657 return V; 12658 } 12659 12660 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12661 SDValue 12662 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12663 SDValue Cmp = N->getOperand(4); 12664 if (Cmp.getOpcode() != ARMISD::CMPZ) 12665 // Only looking at NE cases. 12666 return SDValue(); 12667 12668 EVT VT = N->getValueType(0); 12669 SDLoc dl(N); 12670 SDValue LHS = Cmp.getOperand(0); 12671 SDValue RHS = Cmp.getOperand(1); 12672 SDValue Chain = N->getOperand(0); 12673 SDValue BB = N->getOperand(1); 12674 SDValue ARMcc = N->getOperand(2); 12675 ARMCC::CondCodes CC = 12676 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12677 12678 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12679 // -> (brcond Chain BB CC CPSR Cmp) 12680 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12681 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12682 LHS->getOperand(0)->hasOneUse()) { 12683 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12684 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12685 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12686 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12687 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12688 (LHS01C && LHS01C->getZExtValue() == 1) && 12689 (LHS1C && LHS1C->getZExtValue() == 1) && 12690 (RHSC && RHSC->getZExtValue() == 0)) { 12691 return DAG.getNode( 12692 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12693 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12694 } 12695 } 12696 12697 return SDValue(); 12698 } 12699 12700 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12701 SDValue 12702 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12703 SDValue Cmp = N->getOperand(4); 12704 if (Cmp.getOpcode() != ARMISD::CMPZ) 12705 // Only looking at EQ and NE cases. 12706 return SDValue(); 12707 12708 EVT VT = N->getValueType(0); 12709 SDLoc dl(N); 12710 SDValue LHS = Cmp.getOperand(0); 12711 SDValue RHS = Cmp.getOperand(1); 12712 SDValue FalseVal = N->getOperand(0); 12713 SDValue TrueVal = N->getOperand(1); 12714 SDValue ARMcc = N->getOperand(2); 12715 ARMCC::CondCodes CC = 12716 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12717 12718 // BFI is only available on V6T2+. 12719 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12720 SDValue R = PerformCMOVToBFICombine(N, DAG); 12721 if (R) 12722 return R; 12723 } 12724 12725 // Simplify 12726 // mov r1, r0 12727 // cmp r1, x 12728 // mov r0, y 12729 // moveq r0, x 12730 // to 12731 // cmp r0, x 12732 // movne r0, y 12733 // 12734 // mov r1, r0 12735 // cmp r1, x 12736 // mov r0, x 12737 // movne r0, y 12738 // to 12739 // cmp r0, x 12740 // movne r0, y 12741 /// FIXME: Turn this into a target neutral optimization? 12742 SDValue Res; 12743 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12744 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12745 N->getOperand(3), Cmp); 12746 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12747 SDValue ARMcc; 12748 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12749 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12750 N->getOperand(3), NewCmp); 12751 } 12752 12753 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12754 // -> (cmov F T CC CPSR Cmp) 12755 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12756 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12757 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12758 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12759 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12760 (LHS1C && LHS1C->getZExtValue() == 1) && 12761 (RHSC && RHSC->getZExtValue() == 0)) { 12762 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12763 LHS->getOperand(2), LHS->getOperand(3), 12764 LHS->getOperand(4)); 12765 } 12766 } 12767 12768 if (!VT.isInteger()) 12769 return SDValue(); 12770 12771 // Materialize a boolean comparison for integers so we can avoid branching. 12772 if (isNullConstant(FalseVal)) { 12773 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 12774 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 12775 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 12776 // right 5 bits will make that 32 be 1, otherwise it will be 0. 12777 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 12778 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12779 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 12780 DAG.getConstant(5, dl, MVT::i32)); 12781 } else { 12782 // CMOV 0, 1, ==, (CMPZ x, y) -> 12783 // (ADDCARRY (SUB x, y), t:0, t:1) 12784 // where t = (SUBCARRY 0, (SUB x, y), 0) 12785 // 12786 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 12787 // x != y. In other words, a carry C == 1 when x == y, C == 0 12788 // otherwise. 12789 // The final ADDCARRY computes 12790 // x - y + (0 - (x - y)) + C == C 12791 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12792 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12793 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 12794 // ISD::SUBCARRY returns a borrow but we want the carry here 12795 // actually. 12796 SDValue Carry = 12797 DAG.getNode(ISD::SUB, dl, MVT::i32, 12798 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 12799 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 12800 } 12801 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 12802 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 12803 // This seems pointless but will allow us to combine it further below. 12804 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 12805 SDValue Sub = 12806 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 12807 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 12808 Sub.getValue(1), SDValue()); 12809 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 12810 N->getOperand(3), CPSRGlue.getValue(1)); 12811 FalseVal = Sub; 12812 } 12813 } else if (isNullConstant(TrueVal)) { 12814 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 12815 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 12816 // This seems pointless but will allow us to combine it further below 12817 // Note that we change == for != as this is the dual for the case above. 12818 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 12819 SDValue Sub = 12820 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 12821 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 12822 Sub.getValue(1), SDValue()); 12823 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 12824 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 12825 N->getOperand(3), CPSRGlue.getValue(1)); 12826 FalseVal = Sub; 12827 } 12828 } 12829 12830 // On Thumb1, the DAG above may be further combined if z is a power of 2 12831 // (z == 2 ^ K). 12832 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 12833 // merge t3, t4 12834 // where t1 = (SUBCARRY (SUB x, y), z, 0) 12835 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 12836 // t3 = if K != 0 then (SHL t2:0, K) else t2:0 12837 // t4 = (SUB 1, t2:1) [ we want a carry, not a borrow ] 12838 const APInt *TrueConst; 12839 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 12840 (FalseVal.getOpcode() == ARMISD::SUBS) && 12841 (FalseVal.getOperand(0) == LHS) && (FalseVal.getOperand(1) == RHS) && 12842 (TrueConst = isPowerOf2Constant(TrueVal))) { 12843 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12844 unsigned ShiftAmount = TrueConst->logBase2(); 12845 if (ShiftAmount) 12846 TrueVal = DAG.getConstant(1, dl, VT); 12847 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 12848 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 12849 // Make it a carry, not a borrow. 12850 SDValue Carry = DAG.getNode( 12851 ISD::SUB, dl, VT, DAG.getConstant(1, dl, MVT::i32), Res.getValue(1)); 12852 Res = DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Res, Carry); 12853 12854 if (ShiftAmount) 12855 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 12856 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 12857 } 12858 12859 if (Res.getNode()) { 12860 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 12861 // Capture demanded bits information that would be otherwise lost. 12862 if (Known.Zero == 0xfffffffe) 12863 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12864 DAG.getValueType(MVT::i1)); 12865 else if (Known.Zero == 0xffffff00) 12866 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12867 DAG.getValueType(MVT::i8)); 12868 else if (Known.Zero == 0xffff0000) 12869 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12870 DAG.getValueType(MVT::i16)); 12871 } 12872 12873 return Res; 12874 } 12875 12876 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12877 DAGCombinerInfo &DCI) const { 12878 switch (N->getOpcode()) { 12879 default: break; 12880 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12881 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12882 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12883 case ISD::SUB: return PerformSUBCombine(N, DCI); 12884 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12885 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12886 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12887 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12888 case ARMISD::ADDC: 12889 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12890 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 12891 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12892 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12893 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12894 case ISD::STORE: return PerformSTORECombine(N, DCI); 12895 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12896 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12897 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12898 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12899 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12900 case ISD::FP_TO_SINT: 12901 case ISD::FP_TO_UINT: 12902 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12903 case ISD::FDIV: 12904 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12905 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12906 case ISD::SHL: 12907 case ISD::SRA: 12908 case ISD::SRL: 12909 return PerformShiftCombine(N, DCI, Subtarget); 12910 case ISD::SIGN_EXTEND: 12911 case ISD::ZERO_EXTEND: 12912 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12913 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12914 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12915 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12916 case ARMISD::VLD1DUP: 12917 case ARMISD::VLD2DUP: 12918 case ARMISD::VLD3DUP: 12919 case ARMISD::VLD4DUP: 12920 return PerformVLDCombine(N, DCI); 12921 case ARMISD::BUILD_VECTOR: 12922 return PerformARMBUILD_VECTORCombine(N, DCI); 12923 case ARMISD::SMULWB: { 12924 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12925 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12926 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12927 return SDValue(); 12928 break; 12929 } 12930 case ARMISD::SMULWT: { 12931 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12932 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12933 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12934 return SDValue(); 12935 break; 12936 } 12937 case ARMISD::SMLALBB: { 12938 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12939 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12940 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12941 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12942 return SDValue(); 12943 break; 12944 } 12945 case ARMISD::SMLALBT: { 12946 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12947 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12948 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12949 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12950 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12951 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12952 return SDValue(); 12953 break; 12954 } 12955 case ARMISD::SMLALTB: { 12956 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12957 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12958 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12959 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12960 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12961 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12962 return SDValue(); 12963 break; 12964 } 12965 case ARMISD::SMLALTT: { 12966 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12967 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12968 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12969 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12970 return SDValue(); 12971 break; 12972 } 12973 case ISD::INTRINSIC_VOID: 12974 case ISD::INTRINSIC_W_CHAIN: 12975 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12976 case Intrinsic::arm_neon_vld1: 12977 case Intrinsic::arm_neon_vld1x2: 12978 case Intrinsic::arm_neon_vld1x3: 12979 case Intrinsic::arm_neon_vld1x4: 12980 case Intrinsic::arm_neon_vld2: 12981 case Intrinsic::arm_neon_vld3: 12982 case Intrinsic::arm_neon_vld4: 12983 case Intrinsic::arm_neon_vld2lane: 12984 case Intrinsic::arm_neon_vld3lane: 12985 case Intrinsic::arm_neon_vld4lane: 12986 case Intrinsic::arm_neon_vld2dup: 12987 case Intrinsic::arm_neon_vld3dup: 12988 case Intrinsic::arm_neon_vld4dup: 12989 case Intrinsic::arm_neon_vst1: 12990 case Intrinsic::arm_neon_vst1x2: 12991 case Intrinsic::arm_neon_vst1x3: 12992 case Intrinsic::arm_neon_vst1x4: 12993 case Intrinsic::arm_neon_vst2: 12994 case Intrinsic::arm_neon_vst3: 12995 case Intrinsic::arm_neon_vst4: 12996 case Intrinsic::arm_neon_vst2lane: 12997 case Intrinsic::arm_neon_vst3lane: 12998 case Intrinsic::arm_neon_vst4lane: 12999 return PerformVLDCombine(N, DCI); 13000 default: break; 13001 } 13002 break; 13003 } 13004 return SDValue(); 13005 } 13006 13007 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 13008 EVT VT) const { 13009 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 13010 } 13011 13012 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 13013 unsigned, 13014 unsigned, 13015 bool *Fast) const { 13016 // Depends what it gets converted into if the type is weird. 13017 if (!VT.isSimple()) 13018 return false; 13019 13020 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 13021 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 13022 13023 switch (VT.getSimpleVT().SimpleTy) { 13024 default: 13025 return false; 13026 case MVT::i8: 13027 case MVT::i16: 13028 case MVT::i32: { 13029 // Unaligned access can use (for example) LRDB, LRDH, LDR 13030 if (AllowsUnaligned) { 13031 if (Fast) 13032 *Fast = Subtarget->hasV7Ops(); 13033 return true; 13034 } 13035 return false; 13036 } 13037 case MVT::f64: 13038 case MVT::v2f64: { 13039 // For any little-endian targets with neon, we can support unaligned ld/st 13040 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 13041 // A big-endian target may also explicitly support unaligned accesses 13042 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 13043 if (Fast) 13044 *Fast = true; 13045 return true; 13046 } 13047 return false; 13048 } 13049 } 13050 } 13051 13052 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 13053 unsigned AlignCheck) { 13054 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 13055 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 13056 } 13057 13058 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 13059 unsigned DstAlign, unsigned SrcAlign, 13060 bool IsMemset, bool ZeroMemset, 13061 bool MemcpyStrSrc, 13062 MachineFunction &MF) const { 13063 const Function &F = MF.getFunction(); 13064 13065 // See if we can use NEON instructions for this... 13066 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 13067 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 13068 bool Fast; 13069 if (Size >= 16 && 13070 (memOpAlign(SrcAlign, DstAlign, 16) || 13071 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 13072 return MVT::v2f64; 13073 } else if (Size >= 8 && 13074 (memOpAlign(SrcAlign, DstAlign, 8) || 13075 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 13076 Fast))) { 13077 return MVT::f64; 13078 } 13079 } 13080 13081 // Let the target-independent logic figure it out. 13082 return MVT::Other; 13083 } 13084 13085 // 64-bit integers are split into their high and low parts and held in two 13086 // different registers, so the trunc is free since the low register can just 13087 // be used. 13088 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 13089 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 13090 return false; 13091 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 13092 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 13093 return (SrcBits == 64 && DestBits == 32); 13094 } 13095 13096 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 13097 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 13098 !DstVT.isInteger()) 13099 return false; 13100 unsigned SrcBits = SrcVT.getSizeInBits(); 13101 unsigned DestBits = DstVT.getSizeInBits(); 13102 return (SrcBits == 64 && DestBits == 32); 13103 } 13104 13105 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13106 if (Val.getOpcode() != ISD::LOAD) 13107 return false; 13108 13109 EVT VT1 = Val.getValueType(); 13110 if (!VT1.isSimple() || !VT1.isInteger() || 13111 !VT2.isSimple() || !VT2.isInteger()) 13112 return false; 13113 13114 switch (VT1.getSimpleVT().SimpleTy) { 13115 default: break; 13116 case MVT::i1: 13117 case MVT::i8: 13118 case MVT::i16: 13119 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 13120 return true; 13121 } 13122 13123 return false; 13124 } 13125 13126 bool ARMTargetLowering::isFNegFree(EVT VT) const { 13127 if (!VT.isSimple()) 13128 return false; 13129 13130 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 13131 // negate values directly (fneg is free). So, we don't want to let the DAG 13132 // combiner rewrite fneg into xors and some other instructions. For f16 and 13133 // FullFP16 argument passing, some bitcast nodes may be introduced, 13134 // triggering this DAG combine rewrite, so we are avoiding that with this. 13135 switch (VT.getSimpleVT().SimpleTy) { 13136 default: break; 13137 case MVT::f16: 13138 return Subtarget->hasFullFP16(); 13139 } 13140 13141 return false; 13142 } 13143 13144 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 13145 EVT VT = ExtVal.getValueType(); 13146 13147 if (!isTypeLegal(VT)) 13148 return false; 13149 13150 // Don't create a loadext if we can fold the extension into a wide/long 13151 // instruction. 13152 // If there's more than one user instruction, the loadext is desirable no 13153 // matter what. There can be two uses by the same instruction. 13154 if (ExtVal->use_empty() || 13155 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 13156 return true; 13157 13158 SDNode *U = *ExtVal->use_begin(); 13159 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 13160 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 13161 return false; 13162 13163 return true; 13164 } 13165 13166 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 13167 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13168 return false; 13169 13170 if (!isTypeLegal(EVT::getEVT(Ty1))) 13171 return false; 13172 13173 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 13174 13175 // Assuming the caller doesn't have a zeroext or signext return parameter, 13176 // truncation all the way down to i1 is valid. 13177 return true; 13178 } 13179 13180 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 13181 const AddrMode &AM, Type *Ty, 13182 unsigned AS) const { 13183 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 13184 if (Subtarget->hasFPAO()) 13185 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 13186 return 0; 13187 } 13188 return -1; 13189 } 13190 13191 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 13192 if (V < 0) 13193 return false; 13194 13195 unsigned Scale = 1; 13196 switch (VT.getSimpleVT().SimpleTy) { 13197 default: return false; 13198 case MVT::i1: 13199 case MVT::i8: 13200 // Scale == 1; 13201 break; 13202 case MVT::i16: 13203 // Scale == 2; 13204 Scale = 2; 13205 break; 13206 case MVT::i32: 13207 // Scale == 4; 13208 Scale = 4; 13209 break; 13210 } 13211 13212 if ((V & (Scale - 1)) != 0) 13213 return false; 13214 V /= Scale; 13215 return V == (V & ((1LL << 5) - 1)); 13216 } 13217 13218 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 13219 const ARMSubtarget *Subtarget) { 13220 bool isNeg = false; 13221 if (V < 0) { 13222 isNeg = true; 13223 V = - V; 13224 } 13225 13226 switch (VT.getSimpleVT().SimpleTy) { 13227 default: return false; 13228 case MVT::i1: 13229 case MVT::i8: 13230 case MVT::i16: 13231 case MVT::i32: 13232 // + imm12 or - imm8 13233 if (isNeg) 13234 return V == (V & ((1LL << 8) - 1)); 13235 return V == (V & ((1LL << 12) - 1)); 13236 case MVT::f32: 13237 case MVT::f64: 13238 // Same as ARM mode. FIXME: NEON? 13239 if (!Subtarget->hasVFP2()) 13240 return false; 13241 if ((V & 3) != 0) 13242 return false; 13243 V >>= 2; 13244 return V == (V & ((1LL << 8) - 1)); 13245 } 13246 } 13247 13248 /// isLegalAddressImmediate - Return true if the integer value can be used 13249 /// as the offset of the target addressing mode for load / store of the 13250 /// given type. 13251 static bool isLegalAddressImmediate(int64_t V, EVT VT, 13252 const ARMSubtarget *Subtarget) { 13253 if (V == 0) 13254 return true; 13255 13256 if (!VT.isSimple()) 13257 return false; 13258 13259 if (Subtarget->isThumb1Only()) 13260 return isLegalT1AddressImmediate(V, VT); 13261 else if (Subtarget->isThumb2()) 13262 return isLegalT2AddressImmediate(V, VT, Subtarget); 13263 13264 // ARM mode. 13265 if (V < 0) 13266 V = - V; 13267 switch (VT.getSimpleVT().SimpleTy) { 13268 default: return false; 13269 case MVT::i1: 13270 case MVT::i8: 13271 case MVT::i32: 13272 // +- imm12 13273 return V == (V & ((1LL << 12) - 1)); 13274 case MVT::i16: 13275 // +- imm8 13276 return V == (V & ((1LL << 8) - 1)); 13277 case MVT::f32: 13278 case MVT::f64: 13279 if (!Subtarget->hasVFP2()) // FIXME: NEON? 13280 return false; 13281 if ((V & 3) != 0) 13282 return false; 13283 V >>= 2; 13284 return V == (V & ((1LL << 8) - 1)); 13285 } 13286 } 13287 13288 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 13289 EVT VT) const { 13290 int Scale = AM.Scale; 13291 if (Scale < 0) 13292 return false; 13293 13294 switch (VT.getSimpleVT().SimpleTy) { 13295 default: return false; 13296 case MVT::i1: 13297 case MVT::i8: 13298 case MVT::i16: 13299 case MVT::i32: 13300 if (Scale == 1) 13301 return true; 13302 // r + r << imm 13303 Scale = Scale & ~1; 13304 return Scale == 2 || Scale == 4 || Scale == 8; 13305 case MVT::i64: 13306 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 13307 // version in Thumb mode. 13308 // r + r 13309 if (Scale == 1) 13310 return true; 13311 // r * 2 (this can be lowered to r + r). 13312 if (!AM.HasBaseReg && Scale == 2) 13313 return true; 13314 return false; 13315 case MVT::isVoid: 13316 // Note, we allow "void" uses (basically, uses that aren't loads or 13317 // stores), because arm allows folding a scale into many arithmetic 13318 // operations. This should be made more precise and revisited later. 13319 13320 // Allow r << imm, but the imm has to be a multiple of two. 13321 if (Scale & 1) return false; 13322 return isPowerOf2_32(Scale); 13323 } 13324 } 13325 13326 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 13327 EVT VT) const { 13328 const int Scale = AM.Scale; 13329 13330 // Negative scales are not supported in Thumb1. 13331 if (Scale < 0) 13332 return false; 13333 13334 // Thumb1 addressing modes do not support register scaling excepting the 13335 // following cases: 13336 // 1. Scale == 1 means no scaling. 13337 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 13338 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 13339 } 13340 13341 /// isLegalAddressingMode - Return true if the addressing mode represented 13342 /// by AM is legal for this target, for a load/store of the specified type. 13343 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13344 const AddrMode &AM, Type *Ty, 13345 unsigned AS, Instruction *I) const { 13346 EVT VT = getValueType(DL, Ty, true); 13347 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 13348 return false; 13349 13350 // Can never fold addr of global into load/store. 13351 if (AM.BaseGV) 13352 return false; 13353 13354 switch (AM.Scale) { 13355 case 0: // no scale reg, must be "r+i" or "r", or "i". 13356 break; 13357 default: 13358 // ARM doesn't support any R+R*scale+imm addr modes. 13359 if (AM.BaseOffs) 13360 return false; 13361 13362 if (!VT.isSimple()) 13363 return false; 13364 13365 if (Subtarget->isThumb1Only()) 13366 return isLegalT1ScaledAddressingMode(AM, VT); 13367 13368 if (Subtarget->isThumb2()) 13369 return isLegalT2ScaledAddressingMode(AM, VT); 13370 13371 int Scale = AM.Scale; 13372 switch (VT.getSimpleVT().SimpleTy) { 13373 default: return false; 13374 case MVT::i1: 13375 case MVT::i8: 13376 case MVT::i32: 13377 if (Scale < 0) Scale = -Scale; 13378 if (Scale == 1) 13379 return true; 13380 // r + r << imm 13381 return isPowerOf2_32(Scale & ~1); 13382 case MVT::i16: 13383 case MVT::i64: 13384 // r +/- r 13385 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 13386 return true; 13387 // r * 2 (this can be lowered to r + r). 13388 if (!AM.HasBaseReg && Scale == 2) 13389 return true; 13390 return false; 13391 13392 case MVT::isVoid: 13393 // Note, we allow "void" uses (basically, uses that aren't loads or 13394 // stores), because arm allows folding a scale into many arithmetic 13395 // operations. This should be made more precise and revisited later. 13396 13397 // Allow r << imm, but the imm has to be a multiple of two. 13398 if (Scale & 1) return false; 13399 return isPowerOf2_32(Scale); 13400 } 13401 } 13402 return true; 13403 } 13404 13405 /// isLegalICmpImmediate - Return true if the specified immediate is legal 13406 /// icmp immediate, that is the target has icmp instructions which can compare 13407 /// a register against the immediate without having to materialize the 13408 /// immediate into a register. 13409 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13410 // Thumb2 and ARM modes can use cmn for negative immediates. 13411 if (!Subtarget->isThumb()) 13412 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 13413 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 13414 if (Subtarget->isThumb2()) 13415 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 13416 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 13417 // Thumb1 doesn't have cmn, and only 8-bit immediates. 13418 return Imm >= 0 && Imm <= 255; 13419 } 13420 13421 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 13422 /// *or sub* immediate, that is the target has add or sub instructions which can 13423 /// add a register with the immediate without having to materialize the 13424 /// immediate into a register. 13425 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13426 // Same encoding for add/sub, just flip the sign. 13427 int64_t AbsImm = std::abs(Imm); 13428 if (!Subtarget->isThumb()) 13429 return ARM_AM::getSOImmVal(AbsImm) != -1; 13430 if (Subtarget->isThumb2()) 13431 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 13432 // Thumb1 only has 8-bit unsigned immediate. 13433 return AbsImm >= 0 && AbsImm <= 255; 13434 } 13435 13436 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 13437 bool isSEXTLoad, SDValue &Base, 13438 SDValue &Offset, bool &isInc, 13439 SelectionDAG &DAG) { 13440 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13441 return false; 13442 13443 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 13444 // AddressingMode 3 13445 Base = Ptr->getOperand(0); 13446 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13447 int RHSC = (int)RHS->getZExtValue(); 13448 if (RHSC < 0 && RHSC > -256) { 13449 assert(Ptr->getOpcode() == ISD::ADD); 13450 isInc = false; 13451 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13452 return true; 13453 } 13454 } 13455 isInc = (Ptr->getOpcode() == ISD::ADD); 13456 Offset = Ptr->getOperand(1); 13457 return true; 13458 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 13459 // AddressingMode 2 13460 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13461 int RHSC = (int)RHS->getZExtValue(); 13462 if (RHSC < 0 && RHSC > -0x1000) { 13463 assert(Ptr->getOpcode() == ISD::ADD); 13464 isInc = false; 13465 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13466 Base = Ptr->getOperand(0); 13467 return true; 13468 } 13469 } 13470 13471 if (Ptr->getOpcode() == ISD::ADD) { 13472 isInc = true; 13473 ARM_AM::ShiftOpc ShOpcVal= 13474 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 13475 if (ShOpcVal != ARM_AM::no_shift) { 13476 Base = Ptr->getOperand(1); 13477 Offset = Ptr->getOperand(0); 13478 } else { 13479 Base = Ptr->getOperand(0); 13480 Offset = Ptr->getOperand(1); 13481 } 13482 return true; 13483 } 13484 13485 isInc = (Ptr->getOpcode() == ISD::ADD); 13486 Base = Ptr->getOperand(0); 13487 Offset = Ptr->getOperand(1); 13488 return true; 13489 } 13490 13491 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 13492 return false; 13493 } 13494 13495 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 13496 bool isSEXTLoad, SDValue &Base, 13497 SDValue &Offset, bool &isInc, 13498 SelectionDAG &DAG) { 13499 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13500 return false; 13501 13502 Base = Ptr->getOperand(0); 13503 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13504 int RHSC = (int)RHS->getZExtValue(); 13505 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 13506 assert(Ptr->getOpcode() == ISD::ADD); 13507 isInc = false; 13508 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13509 return true; 13510 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 13511 isInc = Ptr->getOpcode() == ISD::ADD; 13512 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13513 return true; 13514 } 13515 } 13516 13517 return false; 13518 } 13519 13520 /// getPreIndexedAddressParts - returns true by value, base pointer and 13521 /// offset pointer and addressing mode by reference if the node's address 13522 /// can be legally represented as pre-indexed load / store address. 13523 bool 13524 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13525 SDValue &Offset, 13526 ISD::MemIndexedMode &AM, 13527 SelectionDAG &DAG) const { 13528 if (Subtarget->isThumb1Only()) 13529 return false; 13530 13531 EVT VT; 13532 SDValue Ptr; 13533 bool isSEXTLoad = false; 13534 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13535 Ptr = LD->getBasePtr(); 13536 VT = LD->getMemoryVT(); 13537 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13538 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13539 Ptr = ST->getBasePtr(); 13540 VT = ST->getMemoryVT(); 13541 } else 13542 return false; 13543 13544 bool isInc; 13545 bool isLegal = false; 13546 if (Subtarget->isThumb2()) 13547 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13548 Offset, isInc, DAG); 13549 else 13550 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13551 Offset, isInc, DAG); 13552 if (!isLegal) 13553 return false; 13554 13555 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 13556 return true; 13557 } 13558 13559 /// getPostIndexedAddressParts - returns true by value, base pointer and 13560 /// offset pointer and addressing mode by reference if this node can be 13561 /// combined with a load / store to form a post-indexed load / store. 13562 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 13563 SDValue &Base, 13564 SDValue &Offset, 13565 ISD::MemIndexedMode &AM, 13566 SelectionDAG &DAG) const { 13567 EVT VT; 13568 SDValue Ptr; 13569 bool isSEXTLoad = false, isNonExt; 13570 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13571 VT = LD->getMemoryVT(); 13572 Ptr = LD->getBasePtr(); 13573 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13574 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 13575 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13576 VT = ST->getMemoryVT(); 13577 Ptr = ST->getBasePtr(); 13578 isNonExt = !ST->isTruncatingStore(); 13579 } else 13580 return false; 13581 13582 if (Subtarget->isThumb1Only()) { 13583 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 13584 // must be non-extending/truncating, i32, with an offset of 4. 13585 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 13586 if (Op->getOpcode() != ISD::ADD || !isNonExt) 13587 return false; 13588 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 13589 if (!RHS || RHS->getZExtValue() != 4) 13590 return false; 13591 13592 Offset = Op->getOperand(1); 13593 Base = Op->getOperand(0); 13594 AM = ISD::POST_INC; 13595 return true; 13596 } 13597 13598 bool isInc; 13599 bool isLegal = false; 13600 if (Subtarget->isThumb2()) 13601 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13602 isInc, DAG); 13603 else 13604 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13605 isInc, DAG); 13606 if (!isLegal) 13607 return false; 13608 13609 if (Ptr != Base) { 13610 // Swap base ptr and offset to catch more post-index load / store when 13611 // it's legal. In Thumb2 mode, offset must be an immediate. 13612 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 13613 !Subtarget->isThumb2()) 13614 std::swap(Base, Offset); 13615 13616 // Post-indexed load / store update the base pointer. 13617 if (Ptr != Base) 13618 return false; 13619 } 13620 13621 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 13622 return true; 13623 } 13624 13625 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13626 KnownBits &Known, 13627 const APInt &DemandedElts, 13628 const SelectionDAG &DAG, 13629 unsigned Depth) const { 13630 unsigned BitWidth = Known.getBitWidth(); 13631 Known.resetAll(); 13632 switch (Op.getOpcode()) { 13633 default: break; 13634 case ARMISD::ADDC: 13635 case ARMISD::ADDE: 13636 case ARMISD::SUBC: 13637 case ARMISD::SUBE: 13638 // Special cases when we convert a carry to a boolean. 13639 if (Op.getResNo() == 0) { 13640 SDValue LHS = Op.getOperand(0); 13641 SDValue RHS = Op.getOperand(1); 13642 // (ADDE 0, 0, C) will give us a single bit. 13643 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 13644 isNullConstant(RHS)) { 13645 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 13646 return; 13647 } 13648 } 13649 break; 13650 case ARMISD::CMOV: { 13651 // Bits are known zero/one if known on the LHS and RHS. 13652 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 13653 if (Known.isUnknown()) 13654 return; 13655 13656 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 13657 Known.Zero &= KnownRHS.Zero; 13658 Known.One &= KnownRHS.One; 13659 return; 13660 } 13661 case ISD::INTRINSIC_W_CHAIN: { 13662 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 13663 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13664 switch (IntID) { 13665 default: return; 13666 case Intrinsic::arm_ldaex: 13667 case Intrinsic::arm_ldrex: { 13668 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 13669 unsigned MemBits = VT.getScalarSizeInBits(); 13670 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 13671 return; 13672 } 13673 } 13674 } 13675 case ARMISD::BFI: { 13676 // Conservatively, we can recurse down the first operand 13677 // and just mask out all affected bits. 13678 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 13679 13680 // The operand to BFI is already a mask suitable for removing the bits it 13681 // sets. 13682 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 13683 const APInt &Mask = CI->getAPIntValue(); 13684 Known.Zero &= Mask; 13685 Known.One &= Mask; 13686 return; 13687 } 13688 case ARMISD::VGETLANEs: 13689 case ARMISD::VGETLANEu: { 13690 const SDValue &SrcSV = Op.getOperand(0); 13691 EVT VecVT = SrcSV.getValueType(); 13692 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 13693 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 13694 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 13695 assert(Pos->getAPIntValue().ult(NumSrcElts) && 13696 "VGETLANE index out of bounds"); 13697 unsigned Idx = Pos->getZExtValue(); 13698 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 13699 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 13700 13701 EVT VT = Op.getValueType(); 13702 const unsigned DstSz = VT.getScalarSizeInBits(); 13703 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 13704 assert(SrcSz == Known.getBitWidth()); 13705 assert(DstSz > SrcSz); 13706 if (Op.getOpcode() == ARMISD::VGETLANEs) 13707 Known = Known.sext(DstSz); 13708 else { 13709 Known = Known.zext(DstSz); 13710 Known.Zero.setBitsFrom(SrcSz); 13711 } 13712 assert(DstSz == Known.getBitWidth()); 13713 break; 13714 } 13715 } 13716 } 13717 13718 bool 13719 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 13720 const APInt &DemandedAPInt, 13721 TargetLoweringOpt &TLO) const { 13722 // Delay optimization, so we don't have to deal with illegal types, or block 13723 // optimizations. 13724 if (!TLO.LegalOps) 13725 return false; 13726 13727 // Only optimize AND for now. 13728 if (Op.getOpcode() != ISD::AND) 13729 return false; 13730 13731 EVT VT = Op.getValueType(); 13732 13733 // Ignore vectors. 13734 if (VT.isVector()) 13735 return false; 13736 13737 assert(VT == MVT::i32 && "Unexpected integer type"); 13738 13739 // Make sure the RHS really is a constant. 13740 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13741 if (!C) 13742 return false; 13743 13744 unsigned Mask = C->getZExtValue(); 13745 13746 unsigned Demanded = DemandedAPInt.getZExtValue(); 13747 unsigned ShrunkMask = Mask & Demanded; 13748 unsigned ExpandedMask = Mask | ~Demanded; 13749 13750 // If the mask is all zeros, let the target-independent code replace the 13751 // result with zero. 13752 if (ShrunkMask == 0) 13753 return false; 13754 13755 // If the mask is all ones, erase the AND. (Currently, the target-independent 13756 // code won't do this, so we have to do it explicitly to avoid an infinite 13757 // loop in obscure cases.) 13758 if (ExpandedMask == ~0U) 13759 return TLO.CombineTo(Op, Op.getOperand(0)); 13760 13761 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 13762 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 13763 }; 13764 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 13765 if (NewMask == Mask) 13766 return true; 13767 SDLoc DL(Op); 13768 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 13769 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 13770 return TLO.CombineTo(Op, NewOp); 13771 }; 13772 13773 // Prefer uxtb mask. 13774 if (IsLegalMask(0xFF)) 13775 return UseMask(0xFF); 13776 13777 // Prefer uxth mask. 13778 if (IsLegalMask(0xFFFF)) 13779 return UseMask(0xFFFF); 13780 13781 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 13782 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 13783 if (ShrunkMask < 256) 13784 return UseMask(ShrunkMask); 13785 13786 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 13787 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 13788 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 13789 return UseMask(ExpandedMask); 13790 13791 // Potential improvements: 13792 // 13793 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 13794 // We could try to prefer Thumb1 immediates which can be lowered to a 13795 // two-instruction sequence. 13796 // We could try to recognize more legal ARM/Thumb2 immediates here. 13797 13798 return false; 13799 } 13800 13801 13802 //===----------------------------------------------------------------------===// 13803 // ARM Inline Assembly Support 13804 //===----------------------------------------------------------------------===// 13805 13806 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 13807 // Looking for "rev" which is V6+. 13808 if (!Subtarget->hasV6Ops()) 13809 return false; 13810 13811 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 13812 std::string AsmStr = IA->getAsmString(); 13813 SmallVector<StringRef, 4> AsmPieces; 13814 SplitString(AsmStr, AsmPieces, ";\n"); 13815 13816 switch (AsmPieces.size()) { 13817 default: return false; 13818 case 1: 13819 AsmStr = AsmPieces[0]; 13820 AsmPieces.clear(); 13821 SplitString(AsmStr, AsmPieces, " \t,"); 13822 13823 // rev $0, $1 13824 if (AsmPieces.size() == 3 && 13825 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 13826 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 13827 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 13828 if (Ty && Ty->getBitWidth() == 32) 13829 return IntrinsicLowering::LowerToByteSwap(CI); 13830 } 13831 break; 13832 } 13833 13834 return false; 13835 } 13836 13837 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 13838 // At this point, we have to lower this constraint to something else, so we 13839 // lower it to an "r" or "w". However, by doing this we will force the result 13840 // to be in register, while the X constraint is much more permissive. 13841 // 13842 // Although we are correct (we are free to emit anything, without 13843 // constraints), we might break use cases that would expect us to be more 13844 // efficient and emit something else. 13845 if (!Subtarget->hasVFP2()) 13846 return "r"; 13847 if (ConstraintVT.isFloatingPoint()) 13848 return "w"; 13849 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 13850 (ConstraintVT.getSizeInBits() == 64 || 13851 ConstraintVT.getSizeInBits() == 128)) 13852 return "w"; 13853 13854 return "r"; 13855 } 13856 13857 /// getConstraintType - Given a constraint letter, return the type of 13858 /// constraint it is for this target. 13859 ARMTargetLowering::ConstraintType 13860 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 13861 if (Constraint.size() == 1) { 13862 switch (Constraint[0]) { 13863 default: break; 13864 case 'l': return C_RegisterClass; 13865 case 'w': return C_RegisterClass; 13866 case 'h': return C_RegisterClass; 13867 case 'x': return C_RegisterClass; 13868 case 't': return C_RegisterClass; 13869 case 'j': return C_Other; // Constant for movw. 13870 // An address with a single base register. Due to the way we 13871 // currently handle addresses it is the same as an 'r' memory constraint. 13872 case 'Q': return C_Memory; 13873 } 13874 } else if (Constraint.size() == 2) { 13875 switch (Constraint[0]) { 13876 default: break; 13877 // All 'U+' constraints are addresses. 13878 case 'U': return C_Memory; 13879 } 13880 } 13881 return TargetLowering::getConstraintType(Constraint); 13882 } 13883 13884 /// Examine constraint type and operand type and determine a weight value. 13885 /// This object must already have been set up with the operand type 13886 /// and the current alternative constraint selected. 13887 TargetLowering::ConstraintWeight 13888 ARMTargetLowering::getSingleConstraintMatchWeight( 13889 AsmOperandInfo &info, const char *constraint) const { 13890 ConstraintWeight weight = CW_Invalid; 13891 Value *CallOperandVal = info.CallOperandVal; 13892 // If we don't have a value, we can't do a match, 13893 // but allow it at the lowest weight. 13894 if (!CallOperandVal) 13895 return CW_Default; 13896 Type *type = CallOperandVal->getType(); 13897 // Look at the constraint type. 13898 switch (*constraint) { 13899 default: 13900 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13901 break; 13902 case 'l': 13903 if (type->isIntegerTy()) { 13904 if (Subtarget->isThumb()) 13905 weight = CW_SpecificReg; 13906 else 13907 weight = CW_Register; 13908 } 13909 break; 13910 case 'w': 13911 if (type->isFloatingPointTy()) 13912 weight = CW_Register; 13913 break; 13914 } 13915 return weight; 13916 } 13917 13918 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13919 13920 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13921 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13922 if (Constraint.size() == 1) { 13923 // GCC ARM Constraint Letters 13924 switch (Constraint[0]) { 13925 case 'l': // Low regs or general regs. 13926 if (Subtarget->isThumb()) 13927 return RCPair(0U, &ARM::tGPRRegClass); 13928 return RCPair(0U, &ARM::GPRRegClass); 13929 case 'h': // High regs or no regs. 13930 if (Subtarget->isThumb()) 13931 return RCPair(0U, &ARM::hGPRRegClass); 13932 break; 13933 case 'r': 13934 if (Subtarget->isThumb1Only()) 13935 return RCPair(0U, &ARM::tGPRRegClass); 13936 return RCPair(0U, &ARM::GPRRegClass); 13937 case 'w': 13938 if (VT == MVT::Other) 13939 break; 13940 if (VT == MVT::f32) 13941 return RCPair(0U, &ARM::SPRRegClass); 13942 if (VT.getSizeInBits() == 64) 13943 return RCPair(0U, &ARM::DPRRegClass); 13944 if (VT.getSizeInBits() == 128) 13945 return RCPair(0U, &ARM::QPRRegClass); 13946 break; 13947 case 'x': 13948 if (VT == MVT::Other) 13949 break; 13950 if (VT == MVT::f32) 13951 return RCPair(0U, &ARM::SPR_8RegClass); 13952 if (VT.getSizeInBits() == 64) 13953 return RCPair(0U, &ARM::DPR_8RegClass); 13954 if (VT.getSizeInBits() == 128) 13955 return RCPair(0U, &ARM::QPR_8RegClass); 13956 break; 13957 case 't': 13958 if (VT == MVT::Other) 13959 break; 13960 if (VT == MVT::f32 || VT == MVT::i32) 13961 return RCPair(0U, &ARM::SPRRegClass); 13962 if (VT.getSizeInBits() == 64) 13963 return RCPair(0U, &ARM::DPR_VFP2RegClass); 13964 if (VT.getSizeInBits() == 128) 13965 return RCPair(0U, &ARM::QPR_VFP2RegClass); 13966 break; 13967 } 13968 } 13969 if (StringRef("{cc}").equals_lower(Constraint)) 13970 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 13971 13972 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13973 } 13974 13975 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13976 /// vector. If it is invalid, don't add anything to Ops. 13977 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13978 std::string &Constraint, 13979 std::vector<SDValue>&Ops, 13980 SelectionDAG &DAG) const { 13981 SDValue Result; 13982 13983 // Currently only support length 1 constraints. 13984 if (Constraint.length() != 1) return; 13985 13986 char ConstraintLetter = Constraint[0]; 13987 switch (ConstraintLetter) { 13988 default: break; 13989 case 'j': 13990 case 'I': case 'J': case 'K': case 'L': 13991 case 'M': case 'N': case 'O': 13992 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 13993 if (!C) 13994 return; 13995 13996 int64_t CVal64 = C->getSExtValue(); 13997 int CVal = (int) CVal64; 13998 // None of these constraints allow values larger than 32 bits. Check 13999 // that the value fits in an int. 14000 if (CVal != CVal64) 14001 return; 14002 14003 switch (ConstraintLetter) { 14004 case 'j': 14005 // Constant suitable for movw, must be between 0 and 14006 // 65535. 14007 if (Subtarget->hasV6T2Ops()) 14008 if (CVal >= 0 && CVal <= 65535) 14009 break; 14010 return; 14011 case 'I': 14012 if (Subtarget->isThumb1Only()) { 14013 // This must be a constant between 0 and 255, for ADD 14014 // immediates. 14015 if (CVal >= 0 && CVal <= 255) 14016 break; 14017 } else if (Subtarget->isThumb2()) { 14018 // A constant that can be used as an immediate value in a 14019 // data-processing instruction. 14020 if (ARM_AM::getT2SOImmVal(CVal) != -1) 14021 break; 14022 } else { 14023 // A constant that can be used as an immediate value in a 14024 // data-processing instruction. 14025 if (ARM_AM::getSOImmVal(CVal) != -1) 14026 break; 14027 } 14028 return; 14029 14030 case 'J': 14031 if (Subtarget->isThumb1Only()) { 14032 // This must be a constant between -255 and -1, for negated ADD 14033 // immediates. This can be used in GCC with an "n" modifier that 14034 // prints the negated value, for use with SUB instructions. It is 14035 // not useful otherwise but is implemented for compatibility. 14036 if (CVal >= -255 && CVal <= -1) 14037 break; 14038 } else { 14039 // This must be a constant between -4095 and 4095. It is not clear 14040 // what this constraint is intended for. Implemented for 14041 // compatibility with GCC. 14042 if (CVal >= -4095 && CVal <= 4095) 14043 break; 14044 } 14045 return; 14046 14047 case 'K': 14048 if (Subtarget->isThumb1Only()) { 14049 // A 32-bit value where only one byte has a nonzero value. Exclude 14050 // zero to match GCC. This constraint is used by GCC internally for 14051 // constants that can be loaded with a move/shift combination. 14052 // It is not useful otherwise but is implemented for compatibility. 14053 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 14054 break; 14055 } else if (Subtarget->isThumb2()) { 14056 // A constant whose bitwise inverse can be used as an immediate 14057 // value in a data-processing instruction. This can be used in GCC 14058 // with a "B" modifier that prints the inverted value, for use with 14059 // BIC and MVN instructions. It is not useful otherwise but is 14060 // implemented for compatibility. 14061 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 14062 break; 14063 } else { 14064 // A constant whose bitwise inverse can be used as an immediate 14065 // value in a data-processing instruction. This can be used in GCC 14066 // with a "B" modifier that prints the inverted value, for use with 14067 // BIC and MVN instructions. It is not useful otherwise but is 14068 // implemented for compatibility. 14069 if (ARM_AM::getSOImmVal(~CVal) != -1) 14070 break; 14071 } 14072 return; 14073 14074 case 'L': 14075 if (Subtarget->isThumb1Only()) { 14076 // This must be a constant between -7 and 7, 14077 // for 3-operand ADD/SUB immediate instructions. 14078 if (CVal >= -7 && CVal < 7) 14079 break; 14080 } else if (Subtarget->isThumb2()) { 14081 // A constant whose negation can be used as an immediate value in a 14082 // data-processing instruction. This can be used in GCC with an "n" 14083 // modifier that prints the negated value, for use with SUB 14084 // instructions. It is not useful otherwise but is implemented for 14085 // compatibility. 14086 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 14087 break; 14088 } else { 14089 // A constant whose negation can be used as an immediate value in a 14090 // data-processing instruction. This can be used in GCC with an "n" 14091 // modifier that prints the negated value, for use with SUB 14092 // instructions. It is not useful otherwise but is implemented for 14093 // compatibility. 14094 if (ARM_AM::getSOImmVal(-CVal) != -1) 14095 break; 14096 } 14097 return; 14098 14099 case 'M': 14100 if (Subtarget->isThumb1Only()) { 14101 // This must be a multiple of 4 between 0 and 1020, for 14102 // ADD sp + immediate. 14103 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 14104 break; 14105 } else { 14106 // A power of two or a constant between 0 and 32. This is used in 14107 // GCC for the shift amount on shifted register operands, but it is 14108 // useful in general for any shift amounts. 14109 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 14110 break; 14111 } 14112 return; 14113 14114 case 'N': 14115 if (Subtarget->isThumb()) { // FIXME thumb2 14116 // This must be a constant between 0 and 31, for shift amounts. 14117 if (CVal >= 0 && CVal <= 31) 14118 break; 14119 } 14120 return; 14121 14122 case 'O': 14123 if (Subtarget->isThumb()) { // FIXME thumb2 14124 // This must be a multiple of 4 between -508 and 508, for 14125 // ADD/SUB sp = sp + immediate. 14126 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 14127 break; 14128 } 14129 return; 14130 } 14131 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 14132 break; 14133 } 14134 14135 if (Result.getNode()) { 14136 Ops.push_back(Result); 14137 return; 14138 } 14139 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14140 } 14141 14142 static RTLIB::Libcall getDivRemLibcall( 14143 const SDNode *N, MVT::SimpleValueType SVT) { 14144 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 14145 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 14146 "Unhandled Opcode in getDivRemLibcall"); 14147 bool isSigned = N->getOpcode() == ISD::SDIVREM || 14148 N->getOpcode() == ISD::SREM; 14149 RTLIB::Libcall LC; 14150 switch (SVT) { 14151 default: llvm_unreachable("Unexpected request for libcall!"); 14152 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 14153 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 14154 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 14155 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 14156 } 14157 return LC; 14158 } 14159 14160 static TargetLowering::ArgListTy getDivRemArgList( 14161 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 14162 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 14163 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 14164 "Unhandled Opcode in getDivRemArgList"); 14165 bool isSigned = N->getOpcode() == ISD::SDIVREM || 14166 N->getOpcode() == ISD::SREM; 14167 TargetLowering::ArgListTy Args; 14168 TargetLowering::ArgListEntry Entry; 14169 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14170 EVT ArgVT = N->getOperand(i).getValueType(); 14171 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 14172 Entry.Node = N->getOperand(i); 14173 Entry.Ty = ArgTy; 14174 Entry.IsSExt = isSigned; 14175 Entry.IsZExt = !isSigned; 14176 Args.push_back(Entry); 14177 } 14178 if (Subtarget->isTargetWindows() && Args.size() >= 2) 14179 std::swap(Args[0], Args[1]); 14180 return Args; 14181 } 14182 14183 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 14184 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 14185 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 14186 Subtarget->isTargetWindows()) && 14187 "Register-based DivRem lowering only"); 14188 unsigned Opcode = Op->getOpcode(); 14189 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 14190 "Invalid opcode for Div/Rem lowering"); 14191 bool isSigned = (Opcode == ISD::SDIVREM); 14192 EVT VT = Op->getValueType(0); 14193 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 14194 SDLoc dl(Op); 14195 14196 // If the target has hardware divide, use divide + multiply + subtract: 14197 // div = a / b 14198 // rem = a - b * div 14199 // return {div, rem} 14200 // This should be lowered into UDIV/SDIV + MLS later on. 14201 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 14202 : Subtarget->hasDivideInARMMode(); 14203 if (hasDivide && Op->getValueType(0).isSimple() && 14204 Op->getSimpleValueType(0) == MVT::i32) { 14205 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 14206 const SDValue Dividend = Op->getOperand(0); 14207 const SDValue Divisor = Op->getOperand(1); 14208 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 14209 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 14210 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 14211 14212 SDValue Values[2] = {Div, Rem}; 14213 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 14214 } 14215 14216 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 14217 VT.getSimpleVT().SimpleTy); 14218 SDValue InChain = DAG.getEntryNode(); 14219 14220 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 14221 DAG.getContext(), 14222 Subtarget); 14223 14224 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 14225 getPointerTy(DAG.getDataLayout())); 14226 14227 Type *RetTy = StructType::get(Ty, Ty); 14228 14229 if (Subtarget->isTargetWindows()) 14230 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 14231 14232 TargetLowering::CallLoweringInfo CLI(DAG); 14233 CLI.setDebugLoc(dl).setChain(InChain) 14234 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 14235 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 14236 14237 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 14238 return CallInfo.first; 14239 } 14240 14241 // Lowers REM using divmod helpers 14242 // see RTABI section 4.2/4.3 14243 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 14244 // Build return types (div and rem) 14245 std::vector<Type*> RetTyParams; 14246 Type *RetTyElement; 14247 14248 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 14249 default: llvm_unreachable("Unexpected request for libcall!"); 14250 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 14251 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 14252 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 14253 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 14254 } 14255 14256 RetTyParams.push_back(RetTyElement); 14257 RetTyParams.push_back(RetTyElement); 14258 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 14259 Type *RetTy = StructType::get(*DAG.getContext(), ret); 14260 14261 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 14262 SimpleTy); 14263 SDValue InChain = DAG.getEntryNode(); 14264 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 14265 Subtarget); 14266 bool isSigned = N->getOpcode() == ISD::SREM; 14267 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 14268 getPointerTy(DAG.getDataLayout())); 14269 14270 if (Subtarget->isTargetWindows()) 14271 InChain = WinDBZCheckDenominator(DAG, N, InChain); 14272 14273 // Lower call 14274 CallLoweringInfo CLI(DAG); 14275 CLI.setChain(InChain) 14276 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 14277 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 14278 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 14279 14280 // Return second (rem) result operand (first contains div) 14281 SDNode *ResNode = CallResult.first.getNode(); 14282 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 14283 return ResNode->getOperand(1); 14284 } 14285 14286 SDValue 14287 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 14288 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 14289 SDLoc DL(Op); 14290 14291 // Get the inputs. 14292 SDValue Chain = Op.getOperand(0); 14293 SDValue Size = Op.getOperand(1); 14294 14295 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 14296 "no-stack-arg-probe")) { 14297 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 14298 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14299 Chain = SP.getValue(1); 14300 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 14301 if (Align) 14302 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 14303 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 14304 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 14305 SDValue Ops[2] = { SP, Chain }; 14306 return DAG.getMergeValues(Ops, DL); 14307 } 14308 14309 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 14310 DAG.getConstant(2, DL, MVT::i32)); 14311 14312 SDValue Flag; 14313 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 14314 Flag = Chain.getValue(1); 14315 14316 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 14317 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 14318 14319 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14320 Chain = NewSP.getValue(1); 14321 14322 SDValue Ops[2] = { NewSP, Chain }; 14323 return DAG.getMergeValues(Ops, DL); 14324 } 14325 14326 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 14327 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 14328 "Unexpected type for custom-lowering FP_EXTEND"); 14329 14330 RTLIB::Libcall LC; 14331 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 14332 14333 SDValue SrcVal = Op.getOperand(0); 14334 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14335 SDLoc(Op)).first; 14336 } 14337 14338 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 14339 assert(Op.getOperand(0).getValueType() == MVT::f64 && 14340 Subtarget->isFPOnlySP() && 14341 "Unexpected type for custom-lowering FP_ROUND"); 14342 14343 RTLIB::Libcall LC; 14344 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 14345 14346 SDValue SrcVal = Op.getOperand(0); 14347 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14348 SDLoc(Op)).first; 14349 } 14350 14351 bool 14352 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14353 // The ARM target isn't yet aware of offsets. 14354 return false; 14355 } 14356 14357 bool ARM::isBitFieldInvertedMask(unsigned v) { 14358 if (v == 0xffffffff) 14359 return false; 14360 14361 // there can be 1's on either or both "outsides", all the "inside" 14362 // bits must be 0's 14363 return isShiftedMask_32(~v); 14364 } 14365 14366 /// isFPImmLegal - Returns true if the target can instruction select the 14367 /// specified FP immediate natively. If false, the legalizer will 14368 /// materialize the FP immediate as a load from a constant pool. 14369 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 14370 if (!Subtarget->hasVFP3()) 14371 return false; 14372 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 14373 return ARM_AM::getFP16Imm(Imm) != -1; 14374 if (VT == MVT::f32) 14375 return ARM_AM::getFP32Imm(Imm) != -1; 14376 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 14377 return ARM_AM::getFP64Imm(Imm) != -1; 14378 return false; 14379 } 14380 14381 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 14382 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 14383 /// specified in the intrinsic calls. 14384 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14385 const CallInst &I, 14386 MachineFunction &MF, 14387 unsigned Intrinsic) const { 14388 switch (Intrinsic) { 14389 case Intrinsic::arm_neon_vld1: 14390 case Intrinsic::arm_neon_vld2: 14391 case Intrinsic::arm_neon_vld3: 14392 case Intrinsic::arm_neon_vld4: 14393 case Intrinsic::arm_neon_vld2lane: 14394 case Intrinsic::arm_neon_vld3lane: 14395 case Intrinsic::arm_neon_vld4lane: 14396 case Intrinsic::arm_neon_vld2dup: 14397 case Intrinsic::arm_neon_vld3dup: 14398 case Intrinsic::arm_neon_vld4dup: { 14399 Info.opc = ISD::INTRINSIC_W_CHAIN; 14400 // Conservatively set memVT to the entire set of vectors loaded. 14401 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14402 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14403 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14404 Info.ptrVal = I.getArgOperand(0); 14405 Info.offset = 0; 14406 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14407 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14408 // volatile loads with NEON intrinsics not supported 14409 Info.flags = MachineMemOperand::MOLoad; 14410 return true; 14411 } 14412 case Intrinsic::arm_neon_vld1x2: 14413 case Intrinsic::arm_neon_vld1x3: 14414 case Intrinsic::arm_neon_vld1x4: { 14415 Info.opc = ISD::INTRINSIC_W_CHAIN; 14416 // Conservatively set memVT to the entire set of vectors loaded. 14417 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14418 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14419 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14420 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 14421 Info.offset = 0; 14422 Info.align = 0; 14423 // volatile loads with NEON intrinsics not supported 14424 Info.flags = MachineMemOperand::MOLoad; 14425 return true; 14426 } 14427 case Intrinsic::arm_neon_vst1: 14428 case Intrinsic::arm_neon_vst2: 14429 case Intrinsic::arm_neon_vst3: 14430 case Intrinsic::arm_neon_vst4: 14431 case Intrinsic::arm_neon_vst2lane: 14432 case Intrinsic::arm_neon_vst3lane: 14433 case Intrinsic::arm_neon_vst4lane: { 14434 Info.opc = ISD::INTRINSIC_VOID; 14435 // Conservatively set memVT to the entire set of vectors stored. 14436 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14437 unsigned NumElts = 0; 14438 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14439 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14440 if (!ArgTy->isVectorTy()) 14441 break; 14442 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14443 } 14444 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14445 Info.ptrVal = I.getArgOperand(0); 14446 Info.offset = 0; 14447 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14448 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14449 // volatile stores with NEON intrinsics not supported 14450 Info.flags = MachineMemOperand::MOStore; 14451 return true; 14452 } 14453 case Intrinsic::arm_neon_vst1x2: 14454 case Intrinsic::arm_neon_vst1x3: 14455 case Intrinsic::arm_neon_vst1x4: { 14456 Info.opc = ISD::INTRINSIC_VOID; 14457 // Conservatively set memVT to the entire set of vectors stored. 14458 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14459 unsigned NumElts = 0; 14460 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14461 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14462 if (!ArgTy->isVectorTy()) 14463 break; 14464 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14465 } 14466 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14467 Info.ptrVal = I.getArgOperand(0); 14468 Info.offset = 0; 14469 Info.align = 0; 14470 // volatile stores with NEON intrinsics not supported 14471 Info.flags = MachineMemOperand::MOStore; 14472 return true; 14473 } 14474 case Intrinsic::arm_ldaex: 14475 case Intrinsic::arm_ldrex: { 14476 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14477 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 14478 Info.opc = ISD::INTRINSIC_W_CHAIN; 14479 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14480 Info.ptrVal = I.getArgOperand(0); 14481 Info.offset = 0; 14482 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14483 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14484 return true; 14485 } 14486 case Intrinsic::arm_stlex: 14487 case Intrinsic::arm_strex: { 14488 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14489 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 14490 Info.opc = ISD::INTRINSIC_W_CHAIN; 14491 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14492 Info.ptrVal = I.getArgOperand(1); 14493 Info.offset = 0; 14494 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14495 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14496 return true; 14497 } 14498 case Intrinsic::arm_stlexd: 14499 case Intrinsic::arm_strexd: 14500 Info.opc = ISD::INTRINSIC_W_CHAIN; 14501 Info.memVT = MVT::i64; 14502 Info.ptrVal = I.getArgOperand(2); 14503 Info.offset = 0; 14504 Info.align = 8; 14505 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14506 return true; 14507 14508 case Intrinsic::arm_ldaexd: 14509 case Intrinsic::arm_ldrexd: 14510 Info.opc = ISD::INTRINSIC_W_CHAIN; 14511 Info.memVT = MVT::i64; 14512 Info.ptrVal = I.getArgOperand(0); 14513 Info.offset = 0; 14514 Info.align = 8; 14515 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14516 return true; 14517 14518 default: 14519 break; 14520 } 14521 14522 return false; 14523 } 14524 14525 /// Returns true if it is beneficial to convert a load of a constant 14526 /// to just the constant itself. 14527 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14528 Type *Ty) const { 14529 assert(Ty->isIntegerTy()); 14530 14531 unsigned Bits = Ty->getPrimitiveSizeInBits(); 14532 if (Bits == 0 || Bits > 32) 14533 return false; 14534 return true; 14535 } 14536 14537 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 14538 unsigned Index) const { 14539 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 14540 return false; 14541 14542 return (Index == 0 || Index == ResVT.getVectorNumElements()); 14543 } 14544 14545 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 14546 ARM_MB::MemBOpt Domain) const { 14547 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14548 14549 // First, if the target has no DMB, see what fallback we can use. 14550 if (!Subtarget->hasDataBarrier()) { 14551 // Some ARMv6 cpus can support data barriers with an mcr instruction. 14552 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 14553 // here. 14554 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 14555 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 14556 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 14557 Builder.getInt32(0), Builder.getInt32(7), 14558 Builder.getInt32(10), Builder.getInt32(5)}; 14559 return Builder.CreateCall(MCR, args); 14560 } else { 14561 // Instead of using barriers, atomic accesses on these subtargets use 14562 // libcalls. 14563 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 14564 } 14565 } else { 14566 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 14567 // Only a full system barrier exists in the M-class architectures. 14568 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 14569 Constant *CDomain = Builder.getInt32(Domain); 14570 return Builder.CreateCall(DMB, CDomain); 14571 } 14572 } 14573 14574 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 14575 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 14576 Instruction *Inst, 14577 AtomicOrdering Ord) const { 14578 switch (Ord) { 14579 case AtomicOrdering::NotAtomic: 14580 case AtomicOrdering::Unordered: 14581 llvm_unreachable("Invalid fence: unordered/non-atomic"); 14582 case AtomicOrdering::Monotonic: 14583 case AtomicOrdering::Acquire: 14584 return nullptr; // Nothing to do 14585 case AtomicOrdering::SequentiallyConsistent: 14586 if (!Inst->hasAtomicStore()) 14587 return nullptr; // Nothing to do 14588 LLVM_FALLTHROUGH; 14589 case AtomicOrdering::Release: 14590 case AtomicOrdering::AcquireRelease: 14591 if (Subtarget->preferISHSTBarriers()) 14592 return makeDMB(Builder, ARM_MB::ISHST); 14593 // FIXME: add a comment with a link to documentation justifying this. 14594 else 14595 return makeDMB(Builder, ARM_MB::ISH); 14596 } 14597 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 14598 } 14599 14600 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 14601 Instruction *Inst, 14602 AtomicOrdering Ord) const { 14603 switch (Ord) { 14604 case AtomicOrdering::NotAtomic: 14605 case AtomicOrdering::Unordered: 14606 llvm_unreachable("Invalid fence: unordered/not-atomic"); 14607 case AtomicOrdering::Monotonic: 14608 case AtomicOrdering::Release: 14609 return nullptr; // Nothing to do 14610 case AtomicOrdering::Acquire: 14611 case AtomicOrdering::AcquireRelease: 14612 case AtomicOrdering::SequentiallyConsistent: 14613 return makeDMB(Builder, ARM_MB::ISH); 14614 } 14615 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 14616 } 14617 14618 // Loads and stores less than 64-bits are already atomic; ones above that 14619 // are doomed anyway, so defer to the default libcall and blame the OS when 14620 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14621 // anything for those. 14622 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 14623 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 14624 return (Size == 64) && !Subtarget->isMClass(); 14625 } 14626 14627 // Loads and stores less than 64-bits are already atomic; ones above that 14628 // are doomed anyway, so defer to the default libcall and blame the OS when 14629 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14630 // anything for those. 14631 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 14632 // guarantee, see DDI0406C ARM architecture reference manual, 14633 // sections A8.8.72-74 LDRD) 14634 TargetLowering::AtomicExpansionKind 14635 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 14636 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 14637 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 14638 : AtomicExpansionKind::None; 14639 } 14640 14641 // For the real atomic operations, we have ldrex/strex up to 32 bits, 14642 // and up to 64 bits on the non-M profiles 14643 TargetLowering::AtomicExpansionKind 14644 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 14645 if (AI->isFloatingPointOperation()) 14646 return AtomicExpansionKind::CmpXChg; 14647 14648 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 14649 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14650 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 14651 ? AtomicExpansionKind::LLSC 14652 : AtomicExpansionKind::None; 14653 } 14654 14655 TargetLowering::AtomicExpansionKind 14656 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 14657 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 14658 // implement cmpxchg without spilling. If the address being exchanged is also 14659 // on the stack and close enough to the spill slot, this can lead to a 14660 // situation where the monitor always gets cleared and the atomic operation 14661 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 14662 bool HasAtomicCmpXchg = 14663 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14664 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 14665 return AtomicExpansionKind::LLSC; 14666 return AtomicExpansionKind::None; 14667 } 14668 14669 bool ARMTargetLowering::shouldInsertFencesForAtomic( 14670 const Instruction *I) const { 14671 return InsertFencesForAtomic; 14672 } 14673 14674 // This has so far only been implemented for MachO. 14675 bool ARMTargetLowering::useLoadStackGuardNode() const { 14676 return Subtarget->isTargetMachO(); 14677 } 14678 14679 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 14680 unsigned &Cost) const { 14681 // If we do not have NEON, vector types are not natively supported. 14682 if (!Subtarget->hasNEON()) 14683 return false; 14684 14685 // Floating point values and vector values map to the same register file. 14686 // Therefore, although we could do a store extract of a vector type, this is 14687 // better to leave at float as we have more freedom in the addressing mode for 14688 // those. 14689 if (VectorTy->isFPOrFPVectorTy()) 14690 return false; 14691 14692 // If the index is unknown at compile time, this is very expensive to lower 14693 // and it is not possible to combine the store with the extract. 14694 if (!isa<ConstantInt>(Idx)) 14695 return false; 14696 14697 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 14698 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 14699 // We can do a store + vector extract on any vector that fits perfectly in a D 14700 // or Q register. 14701 if (BitWidth == 64 || BitWidth == 128) { 14702 Cost = 0; 14703 return true; 14704 } 14705 return false; 14706 } 14707 14708 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 14709 return Subtarget->hasV6T2Ops(); 14710 } 14711 14712 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 14713 return Subtarget->hasV6T2Ops(); 14714 } 14715 14716 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 14717 return !Subtarget->optForMinSize(); 14718 } 14719 14720 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 14721 AtomicOrdering Ord) const { 14722 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14723 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 14724 bool IsAcquire = isAcquireOrStronger(Ord); 14725 14726 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 14727 // intrinsic must return {i32, i32} and we have to recombine them into a 14728 // single i64 here. 14729 if (ValTy->getPrimitiveSizeInBits() == 64) { 14730 Intrinsic::ID Int = 14731 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 14732 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 14733 14734 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14735 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 14736 14737 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 14738 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 14739 if (!Subtarget->isLittle()) 14740 std::swap (Lo, Hi); 14741 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 14742 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 14743 return Builder.CreateOr( 14744 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 14745 } 14746 14747 Type *Tys[] = { Addr->getType() }; 14748 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 14749 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 14750 14751 return Builder.CreateTruncOrBitCast( 14752 Builder.CreateCall(Ldrex, Addr), 14753 cast<PointerType>(Addr->getType())->getElementType()); 14754 } 14755 14756 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 14757 IRBuilder<> &Builder) const { 14758 if (!Subtarget->hasV7Ops()) 14759 return; 14760 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14761 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 14762 } 14763 14764 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 14765 Value *Addr, 14766 AtomicOrdering Ord) const { 14767 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14768 bool IsRelease = isReleaseOrStronger(Ord); 14769 14770 // Since the intrinsics must have legal type, the i64 intrinsics take two 14771 // parameters: "i32, i32". We must marshal Val into the appropriate form 14772 // before the call. 14773 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 14774 Intrinsic::ID Int = 14775 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 14776 Function *Strex = Intrinsic::getDeclaration(M, Int); 14777 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 14778 14779 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 14780 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 14781 if (!Subtarget->isLittle()) 14782 std::swap(Lo, Hi); 14783 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14784 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 14785 } 14786 14787 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 14788 Type *Tys[] = { Addr->getType() }; 14789 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 14790 14791 return Builder.CreateCall( 14792 Strex, {Builder.CreateZExtOrBitCast( 14793 Val, Strex->getFunctionType()->getParamType(0)), 14794 Addr}); 14795 } 14796 14797 14798 bool ARMTargetLowering::alignLoopsWithOptSize() const { 14799 return Subtarget->isMClass(); 14800 } 14801 14802 /// A helper function for determining the number of interleaved accesses we 14803 /// will generate when lowering accesses of the given type. 14804 unsigned 14805 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 14806 const DataLayout &DL) const { 14807 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 14808 } 14809 14810 bool ARMTargetLowering::isLegalInterleavedAccessType( 14811 VectorType *VecTy, const DataLayout &DL) const { 14812 14813 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 14814 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 14815 14816 // Ensure the vector doesn't have f16 elements. Even though we could do an 14817 // i16 vldN, we can't hold the f16 vectors and will end up converting via 14818 // f32. 14819 if (VecTy->getElementType()->isHalfTy()) 14820 return false; 14821 14822 // Ensure the number of vector elements is greater than 1. 14823 if (VecTy->getNumElements() < 2) 14824 return false; 14825 14826 // Ensure the element type is legal. 14827 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 14828 return false; 14829 14830 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 14831 // 128 will be split into multiple interleaved accesses. 14832 return VecSize == 64 || VecSize % 128 == 0; 14833 } 14834 14835 /// Lower an interleaved load into a vldN intrinsic. 14836 /// 14837 /// E.g. Lower an interleaved load (Factor = 2): 14838 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 14839 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 14840 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 14841 /// 14842 /// Into: 14843 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 14844 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 14845 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 14846 bool ARMTargetLowering::lowerInterleavedLoad( 14847 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 14848 ArrayRef<unsigned> Indices, unsigned Factor) const { 14849 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14850 "Invalid interleave factor"); 14851 assert(!Shuffles.empty() && "Empty shufflevector input"); 14852 assert(Shuffles.size() == Indices.size() && 14853 "Unmatched number of shufflevectors and indices"); 14854 14855 VectorType *VecTy = Shuffles[0]->getType(); 14856 Type *EltTy = VecTy->getVectorElementType(); 14857 14858 const DataLayout &DL = LI->getModule()->getDataLayout(); 14859 14860 // Skip if we do not have NEON and skip illegal vector types. We can 14861 // "legalize" wide vector types into multiple interleaved accesses as long as 14862 // the vector types are divisible by 128. 14863 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 14864 return false; 14865 14866 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 14867 14868 // A pointer vector can not be the return type of the ldN intrinsics. Need to 14869 // load integer vectors first and then convert to pointer vectors. 14870 if (EltTy->isPointerTy()) 14871 VecTy = 14872 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 14873 14874 IRBuilder<> Builder(LI); 14875 14876 // The base address of the load. 14877 Value *BaseAddr = LI->getPointerOperand(); 14878 14879 if (NumLoads > 1) { 14880 // If we're going to generate more than one load, reset the sub-vector type 14881 // to something legal. 14882 VecTy = VectorType::get(VecTy->getVectorElementType(), 14883 VecTy->getVectorNumElements() / NumLoads); 14884 14885 // We will compute the pointer operand of each load from the original base 14886 // address using GEPs. Cast the base address to a pointer to the scalar 14887 // element type. 14888 BaseAddr = Builder.CreateBitCast( 14889 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 14890 LI->getPointerAddressSpace())); 14891 } 14892 14893 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 14894 14895 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 14896 Type *Tys[] = {VecTy, Int8Ptr}; 14897 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 14898 Intrinsic::arm_neon_vld3, 14899 Intrinsic::arm_neon_vld4}; 14900 Function *VldnFunc = 14901 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 14902 14903 // Holds sub-vectors extracted from the load intrinsic return values. The 14904 // sub-vectors are associated with the shufflevector instructions they will 14905 // replace. 14906 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 14907 14908 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 14909 // If we're generating more than one load, compute the base address of 14910 // subsequent loads as an offset from the previous. 14911 if (LoadCount > 0) 14912 BaseAddr = 14913 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 14914 VecTy->getVectorNumElements() * Factor); 14915 14916 SmallVector<Value *, 2> Ops; 14917 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14918 Ops.push_back(Builder.getInt32(LI->getAlignment())); 14919 14920 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 14921 14922 // Replace uses of each shufflevector with the corresponding vector loaded 14923 // by ldN. 14924 for (unsigned i = 0; i < Shuffles.size(); i++) { 14925 ShuffleVectorInst *SV = Shuffles[i]; 14926 unsigned Index = Indices[i]; 14927 14928 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 14929 14930 // Convert the integer vector to pointer vector if the element is pointer. 14931 if (EltTy->isPointerTy()) 14932 SubVec = Builder.CreateIntToPtr( 14933 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 14934 VecTy->getVectorNumElements())); 14935 14936 SubVecs[SV].push_back(SubVec); 14937 } 14938 } 14939 14940 // Replace uses of the shufflevector instructions with the sub-vectors 14941 // returned by the load intrinsic. If a shufflevector instruction is 14942 // associated with more than one sub-vector, those sub-vectors will be 14943 // concatenated into a single wide vector. 14944 for (ShuffleVectorInst *SVI : Shuffles) { 14945 auto &SubVec = SubVecs[SVI]; 14946 auto *WideVec = 14947 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 14948 SVI->replaceAllUsesWith(WideVec); 14949 } 14950 14951 return true; 14952 } 14953 14954 /// Lower an interleaved store into a vstN intrinsic. 14955 /// 14956 /// E.g. Lower an interleaved store (Factor = 3): 14957 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 14958 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 14959 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 14960 /// 14961 /// Into: 14962 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 14963 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 14964 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 14965 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14966 /// 14967 /// Note that the new shufflevectors will be removed and we'll only generate one 14968 /// vst3 instruction in CodeGen. 14969 /// 14970 /// Example for a more general valid mask (Factor 3). Lower: 14971 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 14972 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 14973 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 14974 /// 14975 /// Into: 14976 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 14977 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 14978 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 14979 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14980 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 14981 ShuffleVectorInst *SVI, 14982 unsigned Factor) const { 14983 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14984 "Invalid interleave factor"); 14985 14986 VectorType *VecTy = SVI->getType(); 14987 assert(VecTy->getVectorNumElements() % Factor == 0 && 14988 "Invalid interleaved store"); 14989 14990 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 14991 Type *EltTy = VecTy->getVectorElementType(); 14992 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 14993 14994 const DataLayout &DL = SI->getModule()->getDataLayout(); 14995 14996 // Skip if we do not have NEON and skip illegal vector types. We can 14997 // "legalize" wide vector types into multiple interleaved accesses as long as 14998 // the vector types are divisible by 128. 14999 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 15000 return false; 15001 15002 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 15003 15004 Value *Op0 = SVI->getOperand(0); 15005 Value *Op1 = SVI->getOperand(1); 15006 IRBuilder<> Builder(SI); 15007 15008 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 15009 // vectors to integer vectors. 15010 if (EltTy->isPointerTy()) { 15011 Type *IntTy = DL.getIntPtrType(EltTy); 15012 15013 // Convert to the corresponding integer vector. 15014 Type *IntVecTy = 15015 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 15016 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 15017 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 15018 15019 SubVecTy = VectorType::get(IntTy, LaneLen); 15020 } 15021 15022 // The base address of the store. 15023 Value *BaseAddr = SI->getPointerOperand(); 15024 15025 if (NumStores > 1) { 15026 // If we're going to generate more than one store, reset the lane length 15027 // and sub-vector type to something legal. 15028 LaneLen /= NumStores; 15029 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 15030 15031 // We will compute the pointer operand of each store from the original base 15032 // address using GEPs. Cast the base address to a pointer to the scalar 15033 // element type. 15034 BaseAddr = Builder.CreateBitCast( 15035 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 15036 SI->getPointerAddressSpace())); 15037 } 15038 15039 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 15040 15041 auto Mask = SVI->getShuffleMask(); 15042 15043 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 15044 Type *Tys[] = {Int8Ptr, SubVecTy}; 15045 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 15046 Intrinsic::arm_neon_vst3, 15047 Intrinsic::arm_neon_vst4}; 15048 15049 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 15050 // If we generating more than one store, we compute the base address of 15051 // subsequent stores as an offset from the previous. 15052 if (StoreCount > 0) 15053 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 15054 BaseAddr, LaneLen * Factor); 15055 15056 SmallVector<Value *, 6> Ops; 15057 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 15058 15059 Function *VstNFunc = 15060 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 15061 15062 // Split the shufflevector operands into sub vectors for the new vstN call. 15063 for (unsigned i = 0; i < Factor; i++) { 15064 unsigned IdxI = StoreCount * LaneLen * Factor + i; 15065 if (Mask[IdxI] >= 0) { 15066 Ops.push_back(Builder.CreateShuffleVector( 15067 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 15068 } else { 15069 unsigned StartMask = 0; 15070 for (unsigned j = 1; j < LaneLen; j++) { 15071 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 15072 if (Mask[IdxJ * Factor + IdxI] >= 0) { 15073 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 15074 break; 15075 } 15076 } 15077 // Note: If all elements in a chunk are undefs, StartMask=0! 15078 // Note: Filling undef gaps with random elements is ok, since 15079 // those elements were being written anyway (with undefs). 15080 // In the case of all undefs we're defaulting to using elems from 0 15081 // Note: StartMask cannot be negative, it's checked in 15082 // isReInterleaveMask 15083 Ops.push_back(Builder.CreateShuffleVector( 15084 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 15085 } 15086 } 15087 15088 Ops.push_back(Builder.getInt32(SI->getAlignment())); 15089 Builder.CreateCall(VstNFunc, Ops); 15090 } 15091 return true; 15092 } 15093 15094 enum HABaseType { 15095 HA_UNKNOWN = 0, 15096 HA_FLOAT, 15097 HA_DOUBLE, 15098 HA_VECT64, 15099 HA_VECT128 15100 }; 15101 15102 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 15103 uint64_t &Members) { 15104 if (auto *ST = dyn_cast<StructType>(Ty)) { 15105 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 15106 uint64_t SubMembers = 0; 15107 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 15108 return false; 15109 Members += SubMembers; 15110 } 15111 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 15112 uint64_t SubMembers = 0; 15113 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 15114 return false; 15115 Members += SubMembers * AT->getNumElements(); 15116 } else if (Ty->isFloatTy()) { 15117 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 15118 return false; 15119 Members = 1; 15120 Base = HA_FLOAT; 15121 } else if (Ty->isDoubleTy()) { 15122 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 15123 return false; 15124 Members = 1; 15125 Base = HA_DOUBLE; 15126 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 15127 Members = 1; 15128 switch (Base) { 15129 case HA_FLOAT: 15130 case HA_DOUBLE: 15131 return false; 15132 case HA_VECT64: 15133 return VT->getBitWidth() == 64; 15134 case HA_VECT128: 15135 return VT->getBitWidth() == 128; 15136 case HA_UNKNOWN: 15137 switch (VT->getBitWidth()) { 15138 case 64: 15139 Base = HA_VECT64; 15140 return true; 15141 case 128: 15142 Base = HA_VECT128; 15143 return true; 15144 default: 15145 return false; 15146 } 15147 } 15148 } 15149 15150 return (Members > 0 && Members <= 4); 15151 } 15152 15153 /// Return the correct alignment for the current calling convention. 15154 unsigned 15155 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 15156 DataLayout DL) const { 15157 if (!ArgTy->isVectorTy()) 15158 return DL.getABITypeAlignment(ArgTy); 15159 15160 // Avoid over-aligning vector parameters. It would require realigning the 15161 // stack and waste space for no real benefit. 15162 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 15163 } 15164 15165 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 15166 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 15167 /// passing according to AAPCS rules. 15168 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 15169 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 15170 if (getEffectiveCallingConv(CallConv, isVarArg) != 15171 CallingConv::ARM_AAPCS_VFP) 15172 return false; 15173 15174 HABaseType Base = HA_UNKNOWN; 15175 uint64_t Members = 0; 15176 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 15177 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 15178 15179 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 15180 return IsHA || IsIntArray; 15181 } 15182 15183 unsigned ARMTargetLowering::getExceptionPointerRegister( 15184 const Constant *PersonalityFn) const { 15185 // Platforms which do not use SjLj EH may return values in these registers 15186 // via the personality function. 15187 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 15188 } 15189 15190 unsigned ARMTargetLowering::getExceptionSelectorRegister( 15191 const Constant *PersonalityFn) const { 15192 // Platforms which do not use SjLj EH may return values in these registers 15193 // via the personality function. 15194 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 15195 } 15196 15197 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15198 // Update IsSplitCSR in ARMFunctionInfo. 15199 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 15200 AFI->setIsSplitCSR(true); 15201 } 15202 15203 void ARMTargetLowering::insertCopiesSplitCSR( 15204 MachineBasicBlock *Entry, 15205 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15206 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 15207 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15208 if (!IStart) 15209 return; 15210 15211 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 15212 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15213 MachineBasicBlock::iterator MBBI = Entry->begin(); 15214 for (const MCPhysReg *I = IStart; *I; ++I) { 15215 const TargetRegisterClass *RC = nullptr; 15216 if (ARM::GPRRegClass.contains(*I)) 15217 RC = &ARM::GPRRegClass; 15218 else if (ARM::DPRRegClass.contains(*I)) 15219 RC = &ARM::DPRRegClass; 15220 else 15221 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15222 15223 unsigned NewVR = MRI->createVirtualRegister(RC); 15224 // Create copy from CSR to a virtual register. 15225 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15226 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15227 // nounwind. If we want to generalize this later, we may need to emit 15228 // CFI pseudo-instructions. 15229 assert(Entry->getParent()->getFunction().hasFnAttribute( 15230 Attribute::NoUnwind) && 15231 "Function should be nounwind in insertCopiesSplitCSR!"); 15232 Entry->addLiveIn(*I); 15233 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15234 .addReg(*I); 15235 15236 // Insert the copy-back instructions right before the terminator. 15237 for (auto *Exit : Exits) 15238 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15239 TII->get(TargetOpcode::COPY), *I) 15240 .addReg(NewVR); 15241 } 15242 } 15243 15244 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 15245 MF.getFrameInfo().computeMaxCallFrameSize(MF); 15246 TargetLoweringBase::finalizeLowering(MF); 15247 } 15248