1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMBaseInstrInfo.h" 17 #include "ARMBaseRegisterInfo.h" 18 #include "ARMCallingConv.h" 19 #include "ARMConstantPoolValue.h" 20 #include "ARMMachineFunctionInfo.h" 21 #include "ARMPerfectShuffle.h" 22 #include "ARMRegisterInfo.h" 23 #include "ARMSelectionDAGInfo.h" 24 #include "ARMSubtarget.h" 25 #include "MCTargetDesc/ARMAddressingModes.h" 26 #include "MCTargetDesc/ARMBaseInfo.h" 27 #include "Utils/ARMBaseInfo.h" 28 #include "llvm/ADT/APFloat.h" 29 #include "llvm/ADT/APInt.h" 30 #include "llvm/ADT/ArrayRef.h" 31 #include "llvm/ADT/BitVector.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallVector.h" 36 #include "llvm/ADT/Statistic.h" 37 #include "llvm/ADT/StringExtras.h" 38 #include "llvm/ADT/StringRef.h" 39 #include "llvm/ADT/StringSwitch.h" 40 #include "llvm/ADT/Triple.h" 41 #include "llvm/ADT/Twine.h" 42 #include "llvm/Analysis/VectorUtils.h" 43 #include "llvm/CodeGen/CallingConvLower.h" 44 #include "llvm/CodeGen/ISDOpcodes.h" 45 #include "llvm/CodeGen/IntrinsicLowering.h" 46 #include "llvm/CodeGen/MachineBasicBlock.h" 47 #include "llvm/CodeGen/MachineConstantPool.h" 48 #include "llvm/CodeGen/MachineFrameInfo.h" 49 #include "llvm/CodeGen/MachineFunction.h" 50 #include "llvm/CodeGen/MachineInstr.h" 51 #include "llvm/CodeGen/MachineInstrBuilder.h" 52 #include "llvm/CodeGen/MachineJumpTableInfo.h" 53 #include "llvm/CodeGen/MachineMemOperand.h" 54 #include "llvm/CodeGen/MachineOperand.h" 55 #include "llvm/CodeGen/MachineRegisterInfo.h" 56 #include "llvm/CodeGen/MachineValueType.h" 57 #include "llvm/CodeGen/RuntimeLibcalls.h" 58 #include "llvm/CodeGen/SelectionDAG.h" 59 #include "llvm/CodeGen/SelectionDAGNodes.h" 60 #include "llvm/CodeGen/ValueTypes.h" 61 #include "llvm/IR/Attributes.h" 62 #include "llvm/IR/CallingConv.h" 63 #include "llvm/IR/Constant.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugLoc.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/Function.h" 69 #include "llvm/IR/GlobalAlias.h" 70 #include "llvm/IR/GlobalValue.h" 71 #include "llvm/IR/GlobalVariable.h" 72 #include "llvm/IR/IRBuilder.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/Instruction.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/Module.h" 79 #include "llvm/IR/Type.h" 80 #include "llvm/IR/User.h" 81 #include "llvm/IR/Value.h" 82 #include "llvm/MC/MCInstrDesc.h" 83 #include "llvm/MC/MCInstrItineraries.h" 84 #include "llvm/MC/MCRegisterInfo.h" 85 #include "llvm/MC/MCSchedule.h" 86 #include "llvm/Support/AtomicOrdering.h" 87 #include "llvm/Support/BranchProbability.h" 88 #include "llvm/Support/Casting.h" 89 #include "llvm/Support/CodeGen.h" 90 #include "llvm/Support/CommandLine.h" 91 #include "llvm/Support/Compiler.h" 92 #include "llvm/Support/Debug.h" 93 #include "llvm/Support/ErrorHandling.h" 94 #include "llvm/Support/KnownBits.h" 95 #include "llvm/Support/MathExtras.h" 96 #include "llvm/Support/raw_ostream.h" 97 #include "llvm/Target/TargetInstrInfo.h" 98 #include "llvm/Target/TargetLowering.h" 99 #include "llvm/Target/TargetMachine.h" 100 #include "llvm/Target/TargetOpcodes.h" 101 #include "llvm/Target/TargetOptions.h" 102 #include "llvm/Target/TargetRegisterInfo.h" 103 #include "llvm/Target/TargetSubtargetInfo.h" 104 #include <algorithm> 105 #include <cassert> 106 #include <cstdint> 107 #include <cstdlib> 108 #include <iterator> 109 #include <limits> 110 #include <string> 111 #include <tuple> 112 #include <utility> 113 #include <vector> 114 115 using namespace llvm; 116 117 #define DEBUG_TYPE "arm-isel" 118 119 STATISTIC(NumTailCalls, "Number of tail calls"); 120 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 121 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 122 STATISTIC(NumConstpoolPromoted, 123 "Number of constants with their storage promoted into constant pools"); 124 125 static cl::opt<bool> 126 ARMInterworking("arm-interworking", cl::Hidden, 127 cl::desc("Enable / disable ARM interworking (for debugging only)"), 128 cl::init(true)); 129 130 static cl::opt<bool> EnableConstpoolPromotion( 131 "arm-promote-constant", cl::Hidden, 132 cl::desc("Enable / disable promotion of unnamed_addr constants into " 133 "constant pools"), 134 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 135 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 136 "arm-promote-constant-max-size", cl::Hidden, 137 cl::desc("Maximum size of constant to promote into a constant pool"), 138 cl::init(64)); 139 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 140 "arm-promote-constant-max-total", cl::Hidden, 141 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 142 cl::init(128)); 143 144 // The APCS parameter registers. 145 static const MCPhysReg GPRArgRegs[] = { 146 ARM::R0, ARM::R1, ARM::R2, ARM::R3 147 }; 148 149 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 150 MVT PromotedBitwiseVT) { 151 if (VT != PromotedLdStVT) { 152 setOperationAction(ISD::LOAD, VT, Promote); 153 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 154 155 setOperationAction(ISD::STORE, VT, Promote); 156 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 157 } 158 159 MVT ElemTy = VT.getVectorElementType(); 160 if (ElemTy != MVT::f64) 161 setOperationAction(ISD::SETCC, VT, Custom); 162 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 163 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 164 if (ElemTy == MVT::i32) { 165 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 166 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 167 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 168 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 169 } else { 170 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 171 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 172 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 173 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 174 } 175 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 176 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 177 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 178 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 179 setOperationAction(ISD::SELECT, VT, Expand); 180 setOperationAction(ISD::SELECT_CC, VT, Expand); 181 setOperationAction(ISD::VSELECT, VT, Expand); 182 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 183 if (VT.isInteger()) { 184 setOperationAction(ISD::SHL, VT, Custom); 185 setOperationAction(ISD::SRA, VT, Custom); 186 setOperationAction(ISD::SRL, VT, Custom); 187 } 188 189 // Promote all bit-wise operations. 190 if (VT.isInteger() && VT != PromotedBitwiseVT) { 191 setOperationAction(ISD::AND, VT, Promote); 192 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 193 setOperationAction(ISD::OR, VT, Promote); 194 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 195 setOperationAction(ISD::XOR, VT, Promote); 196 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 197 } 198 199 // Neon does not support vector divide/remainder operations. 200 setOperationAction(ISD::SDIV, VT, Expand); 201 setOperationAction(ISD::UDIV, VT, Expand); 202 setOperationAction(ISD::FDIV, VT, Expand); 203 setOperationAction(ISD::SREM, VT, Expand); 204 setOperationAction(ISD::UREM, VT, Expand); 205 setOperationAction(ISD::FREM, VT, Expand); 206 207 if (!VT.isFloatingPoint() && 208 VT != MVT::v2i64 && VT != MVT::v1i64) 209 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 210 setOperationAction(Opcode, VT, Legal); 211 } 212 213 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 214 addRegisterClass(VT, &ARM::DPRRegClass); 215 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 216 } 217 218 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 219 addRegisterClass(VT, &ARM::DPairRegClass); 220 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 221 } 222 223 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 224 const ARMSubtarget &STI) 225 : TargetLowering(TM), Subtarget(&STI) { 226 RegInfo = Subtarget->getRegisterInfo(); 227 Itins = Subtarget->getInstrItineraryData(); 228 229 setBooleanContents(ZeroOrOneBooleanContent); 230 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 231 232 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 233 !Subtarget->isTargetWatchOS()) { 234 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 235 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 236 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 237 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 238 : CallingConv::ARM_AAPCS); 239 } 240 241 if (Subtarget->isTargetMachO()) { 242 // Uses VFP for Thumb libfuncs if available. 243 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 244 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 245 static const struct { 246 const RTLIB::Libcall Op; 247 const char * const Name; 248 const ISD::CondCode Cond; 249 } LibraryCalls[] = { 250 // Single-precision floating-point arithmetic. 251 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 252 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 253 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 254 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 255 256 // Double-precision floating-point arithmetic. 257 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 258 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 259 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 260 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 261 262 // Single-precision comparisons. 263 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 264 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 265 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 266 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 267 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 268 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 269 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 270 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 271 272 // Double-precision comparisons. 273 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 274 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 275 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 276 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 277 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 278 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 279 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 280 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 281 282 // Floating-point to integer conversions. 283 // i64 conversions are done via library routines even when generating VFP 284 // instructions, so use the same ones. 285 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 286 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 287 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 288 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 289 290 // Conversions between floating types. 291 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 292 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 293 294 // Integer to floating-point conversions. 295 // i64 conversions are done via library routines even when generating VFP 296 // instructions, so use the same ones. 297 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 298 // e.g., __floatunsidf vs. __floatunssidfvfp. 299 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 300 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 301 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 302 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 303 }; 304 305 for (const auto &LC : LibraryCalls) { 306 setLibcallName(LC.Op, LC.Name); 307 if (LC.Cond != ISD::SETCC_INVALID) 308 setCmpLibcallCC(LC.Op, LC.Cond); 309 } 310 } 311 312 // Set the correct calling convention for ARMv7k WatchOS. It's just 313 // AAPCS_VFP for functions as simple as libcalls. 314 if (Subtarget->isTargetWatchABI()) { 315 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 316 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 317 } 318 } 319 320 // These libcalls are not available in 32-bit. 321 setLibcallName(RTLIB::SHL_I128, nullptr); 322 setLibcallName(RTLIB::SRL_I128, nullptr); 323 setLibcallName(RTLIB::SRA_I128, nullptr); 324 325 // RTLIB 326 if (Subtarget->isAAPCS_ABI() && 327 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 328 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 329 static const struct { 330 const RTLIB::Libcall Op; 331 const char * const Name; 332 const CallingConv::ID CC; 333 const ISD::CondCode Cond; 334 } LibraryCalls[] = { 335 // Double-precision floating-point arithmetic helper functions 336 // RTABI chapter 4.1.2, Table 2 337 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 342 // Double-precision floating-point comparison helper functions 343 // RTABI chapter 4.1.2, Table 3 344 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 345 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 346 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 347 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 348 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 349 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 350 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 351 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 352 353 // Single-precision floating-point arithmetic helper functions 354 // RTABI chapter 4.1.2, Table 4 355 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 356 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 357 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 358 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 359 360 // Single-precision floating-point comparison helper functions 361 // RTABI chapter 4.1.2, Table 5 362 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 363 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 364 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 365 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 366 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 367 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 368 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 369 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 370 371 // Floating-point to integer conversions. 372 // RTABI chapter 4.1.2, Table 6 373 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 374 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 375 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 376 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 377 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 378 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 380 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 381 382 // Conversions between floating types. 383 // RTABI chapter 4.1.2, Table 7 384 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 385 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 386 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 387 388 // Integer to floating-point conversions. 389 // RTABI chapter 4.1.2, Table 8 390 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 391 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 392 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 393 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 394 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 395 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 398 399 // Long long helper functions 400 // RTABI chapter 4.2, Table 9 401 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 402 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 403 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 404 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 406 // Integer division functions 407 // RTABI chapter 4.3.1 408 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 409 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 410 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 411 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 412 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 413 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 414 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 415 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 416 }; 417 418 for (const auto &LC : LibraryCalls) { 419 setLibcallName(LC.Op, LC.Name); 420 setLibcallCallingConv(LC.Op, LC.CC); 421 if (LC.Cond != ISD::SETCC_INVALID) 422 setCmpLibcallCC(LC.Op, LC.Cond); 423 } 424 425 // EABI dependent RTLIB 426 if (TM.Options.EABIVersion == EABI::EABI4 || 427 TM.Options.EABIVersion == EABI::EABI5) { 428 static const struct { 429 const RTLIB::Libcall Op; 430 const char *const Name; 431 const CallingConv::ID CC; 432 const ISD::CondCode Cond; 433 } MemOpsLibraryCalls[] = { 434 // Memory operations 435 // RTABI chapter 4.3.4 436 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 437 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 438 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 439 }; 440 441 for (const auto &LC : MemOpsLibraryCalls) { 442 setLibcallName(LC.Op, LC.Name); 443 setLibcallCallingConv(LC.Op, LC.CC); 444 if (LC.Cond != ISD::SETCC_INVALID) 445 setCmpLibcallCC(LC.Op, LC.Cond); 446 } 447 } 448 } 449 450 if (Subtarget->isTargetWindows()) { 451 static const struct { 452 const RTLIB::Libcall Op; 453 const char * const Name; 454 const CallingConv::ID CC; 455 } LibraryCalls[] = { 456 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 457 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 458 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 459 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 460 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 461 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 462 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 463 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 464 }; 465 466 for (const auto &LC : LibraryCalls) { 467 setLibcallName(LC.Op, LC.Name); 468 setLibcallCallingConv(LC.Op, LC.CC); 469 } 470 } 471 472 // Use divmod compiler-rt calls for iOS 5.0 and later. 473 if (Subtarget->isTargetMachO() && 474 !(Subtarget->isTargetIOS() && 475 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 476 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 477 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 478 } 479 480 // The half <-> float conversion functions are always soft-float on 481 // non-watchos platforms, but are needed for some targets which use a 482 // hard-float calling convention by default. 483 if (!Subtarget->isTargetWatchABI()) { 484 if (Subtarget->isAAPCS_ABI()) { 485 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 486 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 487 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 488 } else { 489 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 490 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 491 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 492 } 493 } 494 495 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 496 // a __gnu_ prefix (which is the default). 497 if (Subtarget->isTargetAEABI()) { 498 static const struct { 499 const RTLIB::Libcall Op; 500 const char * const Name; 501 const CallingConv::ID CC; 502 } LibraryCalls[] = { 503 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 504 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 505 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 506 }; 507 508 for (const auto &LC : LibraryCalls) { 509 setLibcallName(LC.Op, LC.Name); 510 setLibcallCallingConv(LC.Op, LC.CC); 511 } 512 } 513 514 if (Subtarget->isThumb1Only()) 515 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 516 else 517 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 518 519 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 520 !Subtarget->isThumb1Only()) { 521 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 522 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 523 } 524 525 for (MVT VT : MVT::vector_valuetypes()) { 526 for (MVT InnerVT : MVT::vector_valuetypes()) { 527 setTruncStoreAction(VT, InnerVT, Expand); 528 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 529 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 530 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 531 } 532 533 setOperationAction(ISD::MULHS, VT, Expand); 534 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 535 setOperationAction(ISD::MULHU, VT, Expand); 536 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 537 538 setOperationAction(ISD::BSWAP, VT, Expand); 539 } 540 541 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 542 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 543 544 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 545 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 546 547 if (Subtarget->hasNEON()) { 548 addDRTypeForNEON(MVT::v2f32); 549 addDRTypeForNEON(MVT::v8i8); 550 addDRTypeForNEON(MVT::v4i16); 551 addDRTypeForNEON(MVT::v2i32); 552 addDRTypeForNEON(MVT::v1i64); 553 554 addQRTypeForNEON(MVT::v4f32); 555 addQRTypeForNEON(MVT::v2f64); 556 addQRTypeForNEON(MVT::v16i8); 557 addQRTypeForNEON(MVT::v8i16); 558 addQRTypeForNEON(MVT::v4i32); 559 addQRTypeForNEON(MVT::v2i64); 560 561 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 562 // neither Neon nor VFP support any arithmetic operations on it. 563 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 564 // supported for v4f32. 565 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 566 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 567 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 568 // FIXME: Code duplication: FDIV and FREM are expanded always, see 569 // ARMTargetLowering::addTypeForNEON method for details. 570 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 571 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 572 // FIXME: Create unittest. 573 // In another words, find a way when "copysign" appears in DAG with vector 574 // operands. 575 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 576 // FIXME: Code duplication: SETCC has custom operation action, see 577 // ARMTargetLowering::addTypeForNEON method for details. 578 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 579 // FIXME: Create unittest for FNEG and for FABS. 580 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 581 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 582 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 583 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 584 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 585 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 586 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 587 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 588 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 589 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 590 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 591 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 592 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 593 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 594 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 595 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 596 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 597 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 598 599 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 600 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 601 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 602 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 603 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 604 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 605 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 606 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 607 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 608 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 609 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 610 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 611 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 612 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 613 614 // Mark v2f32 intrinsics. 615 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 616 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 617 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 618 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 619 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 620 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 621 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 622 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 623 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 624 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 625 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 626 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 627 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 628 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 629 630 // Neon does not support some operations on v1i64 and v2i64 types. 631 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 632 // Custom handling for some quad-vector types to detect VMULL. 633 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 634 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 635 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 636 // Custom handling for some vector types to avoid expensive expansions 637 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 638 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 639 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 640 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 641 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 642 // a destination type that is wider than the source, and nor does 643 // it have a FP_TO_[SU]INT instruction with a narrower destination than 644 // source. 645 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 646 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 647 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 648 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 649 650 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 651 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 652 653 // NEON does not have single instruction CTPOP for vectors with element 654 // types wider than 8-bits. However, custom lowering can leverage the 655 // v8i8/v16i8 vcnt instruction. 656 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 657 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 658 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 659 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 660 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 661 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 662 663 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 664 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 665 666 // NEON does not have single instruction CTTZ for vectors. 667 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 668 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 669 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 670 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 671 672 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 673 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 674 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 675 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 676 677 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 678 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 679 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 680 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 681 682 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 683 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 684 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 686 687 // NEON only has FMA instructions as of VFP4. 688 if (!Subtarget->hasVFP4()) { 689 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 690 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 691 } 692 693 setTargetDAGCombine(ISD::INTRINSIC_VOID); 694 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 695 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 696 setTargetDAGCombine(ISD::SHL); 697 setTargetDAGCombine(ISD::SRL); 698 setTargetDAGCombine(ISD::SRA); 699 setTargetDAGCombine(ISD::SIGN_EXTEND); 700 setTargetDAGCombine(ISD::ZERO_EXTEND); 701 setTargetDAGCombine(ISD::ANY_EXTEND); 702 setTargetDAGCombine(ISD::BUILD_VECTOR); 703 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 704 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 705 setTargetDAGCombine(ISD::STORE); 706 setTargetDAGCombine(ISD::FP_TO_SINT); 707 setTargetDAGCombine(ISD::FP_TO_UINT); 708 setTargetDAGCombine(ISD::FDIV); 709 setTargetDAGCombine(ISD::LOAD); 710 711 // It is legal to extload from v4i8 to v4i16 or v4i32. 712 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 713 MVT::v2i32}) { 714 for (MVT VT : MVT::integer_vector_valuetypes()) { 715 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 716 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 717 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 718 } 719 } 720 } 721 722 if (Subtarget->isFPOnlySP()) { 723 // When targeting a floating-point unit with only single-precision 724 // operations, f64 is legal for the few double-precision instructions which 725 // are present However, no double-precision operations other than moves, 726 // loads and stores are provided by the hardware. 727 setOperationAction(ISD::FADD, MVT::f64, Expand); 728 setOperationAction(ISD::FSUB, MVT::f64, Expand); 729 setOperationAction(ISD::FMUL, MVT::f64, Expand); 730 setOperationAction(ISD::FMA, MVT::f64, Expand); 731 setOperationAction(ISD::FDIV, MVT::f64, Expand); 732 setOperationAction(ISD::FREM, MVT::f64, Expand); 733 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 734 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 735 setOperationAction(ISD::FNEG, MVT::f64, Expand); 736 setOperationAction(ISD::FABS, MVT::f64, Expand); 737 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 738 setOperationAction(ISD::FSIN, MVT::f64, Expand); 739 setOperationAction(ISD::FCOS, MVT::f64, Expand); 740 setOperationAction(ISD::FPOW, MVT::f64, Expand); 741 setOperationAction(ISD::FLOG, MVT::f64, Expand); 742 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 743 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 744 setOperationAction(ISD::FEXP, MVT::f64, Expand); 745 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 746 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 747 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 748 setOperationAction(ISD::FRINT, MVT::f64, Expand); 749 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 750 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 751 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 752 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 753 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 754 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 755 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 756 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 757 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 758 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 759 } 760 761 computeRegisterProperties(Subtarget->getRegisterInfo()); 762 763 // ARM does not have floating-point extending loads. 764 for (MVT VT : MVT::fp_valuetypes()) { 765 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 766 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 767 } 768 769 // ... or truncating stores 770 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 771 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 772 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 773 774 // ARM does not have i1 sign extending load. 775 for (MVT VT : MVT::integer_valuetypes()) 776 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 777 778 // ARM supports all 4 flavors of integer indexed load / store. 779 if (!Subtarget->isThumb1Only()) { 780 for (unsigned im = (unsigned)ISD::PRE_INC; 781 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 782 setIndexedLoadAction(im, MVT::i1, Legal); 783 setIndexedLoadAction(im, MVT::i8, Legal); 784 setIndexedLoadAction(im, MVT::i16, Legal); 785 setIndexedLoadAction(im, MVT::i32, Legal); 786 setIndexedStoreAction(im, MVT::i1, Legal); 787 setIndexedStoreAction(im, MVT::i8, Legal); 788 setIndexedStoreAction(im, MVT::i16, Legal); 789 setIndexedStoreAction(im, MVT::i32, Legal); 790 } 791 } else { 792 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 793 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 794 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 795 } 796 797 setOperationAction(ISD::SADDO, MVT::i32, Custom); 798 setOperationAction(ISD::UADDO, MVT::i32, Custom); 799 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 800 setOperationAction(ISD::USUBO, MVT::i32, Custom); 801 802 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 803 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 804 805 // i64 operation support. 806 setOperationAction(ISD::MUL, MVT::i64, Expand); 807 setOperationAction(ISD::MULHU, MVT::i32, Expand); 808 if (Subtarget->isThumb1Only()) { 809 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 810 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 811 } 812 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 813 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 814 setOperationAction(ISD::MULHS, MVT::i32, Expand); 815 816 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 817 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 818 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 819 setOperationAction(ISD::SRL, MVT::i64, Custom); 820 setOperationAction(ISD::SRA, MVT::i64, Custom); 821 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 822 823 setOperationAction(ISD::ADDC, MVT::i32, Custom); 824 setOperationAction(ISD::ADDE, MVT::i32, Custom); 825 setOperationAction(ISD::SUBC, MVT::i32, Custom); 826 setOperationAction(ISD::SUBE, MVT::i32, Custom); 827 828 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 829 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 830 831 // ARM does not have ROTL. 832 setOperationAction(ISD::ROTL, MVT::i32, Expand); 833 for (MVT VT : MVT::vector_valuetypes()) { 834 setOperationAction(ISD::ROTL, VT, Expand); 835 setOperationAction(ISD::ROTR, VT, Expand); 836 } 837 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 838 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 839 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 840 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 841 842 // @llvm.readcyclecounter requires the Performance Monitors extension. 843 // Default to the 0 expansion on unsupported platforms. 844 // FIXME: Technically there are older ARM CPUs that have 845 // implementation-specific ways of obtaining this information. 846 if (Subtarget->hasPerfMon()) 847 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 848 849 // Only ARMv6 has BSWAP. 850 if (!Subtarget->hasV6Ops()) 851 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 852 853 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 854 : Subtarget->hasDivideInARMMode(); 855 if (!hasDivide) { 856 // These are expanded into libcalls if the cpu doesn't have HW divider. 857 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 858 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 859 } 860 861 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 862 setOperationAction(ISD::SDIV, MVT::i32, Custom); 863 setOperationAction(ISD::UDIV, MVT::i32, Custom); 864 865 setOperationAction(ISD::SDIV, MVT::i64, Custom); 866 setOperationAction(ISD::UDIV, MVT::i64, Custom); 867 } 868 869 setOperationAction(ISD::SREM, MVT::i32, Expand); 870 setOperationAction(ISD::UREM, MVT::i32, Expand); 871 872 // Register based DivRem for AEABI (RTABI 4.2) 873 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 874 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 875 Subtarget->isTargetWindows()) { 876 setOperationAction(ISD::SREM, MVT::i64, Custom); 877 setOperationAction(ISD::UREM, MVT::i64, Custom); 878 HasStandaloneRem = false; 879 880 if (Subtarget->isTargetWindows()) { 881 const struct { 882 const RTLIB::Libcall Op; 883 const char * const Name; 884 const CallingConv::ID CC; 885 } LibraryCalls[] = { 886 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 887 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 888 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 889 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 890 891 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 892 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 893 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 894 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 895 }; 896 897 for (const auto &LC : LibraryCalls) { 898 setLibcallName(LC.Op, LC.Name); 899 setLibcallCallingConv(LC.Op, LC.CC); 900 } 901 } else { 902 const struct { 903 const RTLIB::Libcall Op; 904 const char * const Name; 905 const CallingConv::ID CC; 906 } LibraryCalls[] = { 907 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 908 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 909 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 910 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 911 912 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 913 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 914 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 915 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 916 }; 917 918 for (const auto &LC : LibraryCalls) { 919 setLibcallName(LC.Op, LC.Name); 920 setLibcallCallingConv(LC.Op, LC.CC); 921 } 922 } 923 924 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 925 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 926 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 927 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 928 } else { 929 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 930 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 931 } 932 933 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 934 for (auto &VT : {MVT::f32, MVT::f64}) 935 setOperationAction(ISD::FPOWI, VT, Custom); 936 937 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 938 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 939 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 940 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 941 942 setOperationAction(ISD::TRAP, MVT::Other, Legal); 943 944 // Use the default implementation. 945 setOperationAction(ISD::VASTART, MVT::Other, Custom); 946 setOperationAction(ISD::VAARG, MVT::Other, Expand); 947 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 948 setOperationAction(ISD::VAEND, MVT::Other, Expand); 949 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 950 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 951 952 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 953 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 954 else 955 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 956 957 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 958 // the default expansion. 959 InsertFencesForAtomic = false; 960 if (Subtarget->hasAnyDataBarrier() && 961 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 962 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 963 // to ldrex/strex loops already. 964 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 965 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 966 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 967 968 // On v8, we have particularly efficient implementations of atomic fences 969 // if they can be combined with nearby atomic loads and stores. 970 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 971 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 972 InsertFencesForAtomic = true; 973 } 974 } else { 975 // If there's anything we can use as a barrier, go through custom lowering 976 // for ATOMIC_FENCE. 977 // If target has DMB in thumb, Fences can be inserted. 978 if (Subtarget->hasDataBarrier()) 979 InsertFencesForAtomic = true; 980 981 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 982 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 983 984 // Set them all for expansion, which will force libcalls. 985 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 986 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 987 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 988 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 989 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 990 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 991 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 992 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 993 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 994 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 995 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 996 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 997 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 998 // Unordered/Monotonic case. 999 if (!InsertFencesForAtomic) { 1000 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1001 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1002 } 1003 } 1004 1005 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1006 1007 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1008 if (!Subtarget->hasV6Ops()) { 1009 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1010 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1011 } 1012 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1013 1014 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1015 !Subtarget->isThumb1Only()) { 1016 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1017 // iff target supports vfp2. 1018 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1019 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1020 } 1021 1022 // We want to custom lower some of our intrinsics. 1023 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1024 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1025 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1026 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1027 if (Subtarget->useSjLjEH()) 1028 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1029 1030 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1031 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1032 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1033 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1034 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1035 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1036 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1037 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1038 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1039 1040 // Thumb-1 cannot currently select ARMISD::SUBE. 1041 if (!Subtarget->isThumb1Only()) 1042 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1043 1044 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 1045 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1046 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1047 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1048 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1049 1050 // We don't support sin/cos/fmod/copysign/pow 1051 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1052 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1053 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1054 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1055 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1056 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1057 setOperationAction(ISD::FREM, MVT::f64, Expand); 1058 setOperationAction(ISD::FREM, MVT::f32, Expand); 1059 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1060 !Subtarget->isThumb1Only()) { 1061 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1062 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1063 } 1064 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1065 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1066 1067 if (!Subtarget->hasVFP4()) { 1068 setOperationAction(ISD::FMA, MVT::f64, Expand); 1069 setOperationAction(ISD::FMA, MVT::f32, Expand); 1070 } 1071 1072 // Various VFP goodness 1073 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1074 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1075 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1076 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1077 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1078 } 1079 1080 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1081 if (!Subtarget->hasFP16()) { 1082 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1083 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1084 } 1085 } 1086 1087 // Combine sin / cos into one node or libcall if possible. 1088 if (Subtarget->hasSinCos()) { 1089 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 1090 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 1091 if (Subtarget->isTargetWatchABI()) { 1092 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 1093 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 1094 } 1095 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 1096 // For iOS, we don't want to the normal expansion of a libcall to 1097 // sincos. We want to issue a libcall to __sincos_stret. 1098 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1099 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1100 } 1101 } 1102 1103 // FP-ARMv8 implements a lot of rounding-like FP operations. 1104 if (Subtarget->hasFPARMv8()) { 1105 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1106 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1107 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1108 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1109 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1110 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1111 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1112 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1113 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1114 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1115 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1116 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1117 1118 if (!Subtarget->isFPOnlySP()) { 1119 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1120 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1121 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1122 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1123 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1124 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1125 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1126 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1127 } 1128 } 1129 1130 if (Subtarget->hasNEON()) { 1131 // vmin and vmax aren't available in a scalar form, so we use 1132 // a NEON instruction with an undef lane instead. 1133 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1134 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1135 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1136 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1137 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1138 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1139 } 1140 1141 // We have target-specific dag combine patterns for the following nodes: 1142 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1143 setTargetDAGCombine(ISD::ADD); 1144 setTargetDAGCombine(ISD::SUB); 1145 setTargetDAGCombine(ISD::MUL); 1146 setTargetDAGCombine(ISD::AND); 1147 setTargetDAGCombine(ISD::OR); 1148 setTargetDAGCombine(ISD::XOR); 1149 1150 if (Subtarget->hasV6Ops()) 1151 setTargetDAGCombine(ISD::SRL); 1152 1153 setStackPointerRegisterToSaveRestore(ARM::SP); 1154 1155 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1156 !Subtarget->hasVFP2()) 1157 setSchedulingPreference(Sched::RegPressure); 1158 else 1159 setSchedulingPreference(Sched::Hybrid); 1160 1161 //// temporary - rewrite interface to use type 1162 MaxStoresPerMemset = 8; 1163 MaxStoresPerMemsetOptSize = 4; 1164 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1165 MaxStoresPerMemcpyOptSize = 2; 1166 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1167 MaxStoresPerMemmoveOptSize = 2; 1168 1169 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1170 // are at least 4 bytes aligned. 1171 setMinStackArgumentAlignment(4); 1172 1173 // Prefer likely predicted branches to selects on out-of-order cores. 1174 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1175 1176 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1177 } 1178 1179 bool ARMTargetLowering::useSoftFloat() const { 1180 return Subtarget->useSoftFloat(); 1181 } 1182 1183 // FIXME: It might make sense to define the representative register class as the 1184 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1185 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1186 // SPR's representative would be DPR_VFP2. This should work well if register 1187 // pressure tracking were modified such that a register use would increment the 1188 // pressure of the register class's representative and all of it's super 1189 // classes' representatives transitively. We have not implemented this because 1190 // of the difficulty prior to coalescing of modeling operand register classes 1191 // due to the common occurrence of cross class copies and subregister insertions 1192 // and extractions. 1193 std::pair<const TargetRegisterClass *, uint8_t> 1194 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1195 MVT VT) const { 1196 const TargetRegisterClass *RRC = nullptr; 1197 uint8_t Cost = 1; 1198 switch (VT.SimpleTy) { 1199 default: 1200 return TargetLowering::findRepresentativeClass(TRI, VT); 1201 // Use DPR as representative register class for all floating point 1202 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1203 // the cost is 1 for both f32 and f64. 1204 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1205 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1206 RRC = &ARM::DPRRegClass; 1207 // When NEON is used for SP, only half of the register file is available 1208 // because operations that define both SP and DP results will be constrained 1209 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1210 // coalescing by double-counting the SP regs. See the FIXME above. 1211 if (Subtarget->useNEONForSinglePrecisionFP()) 1212 Cost = 2; 1213 break; 1214 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1215 case MVT::v4f32: case MVT::v2f64: 1216 RRC = &ARM::DPRRegClass; 1217 Cost = 2; 1218 break; 1219 case MVT::v4i64: 1220 RRC = &ARM::DPRRegClass; 1221 Cost = 4; 1222 break; 1223 case MVT::v8i64: 1224 RRC = &ARM::DPRRegClass; 1225 Cost = 8; 1226 break; 1227 } 1228 return std::make_pair(RRC, Cost); 1229 } 1230 1231 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1232 switch ((ARMISD::NodeType)Opcode) { 1233 case ARMISD::FIRST_NUMBER: break; 1234 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1235 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1236 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1237 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1238 case ARMISD::CALL: return "ARMISD::CALL"; 1239 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1240 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1241 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1242 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1243 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1244 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1245 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1246 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1247 case ARMISD::CMP: return "ARMISD::CMP"; 1248 case ARMISD::CMN: return "ARMISD::CMN"; 1249 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1250 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1251 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1252 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1253 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1254 1255 case ARMISD::CMOV: return "ARMISD::CMOV"; 1256 1257 case ARMISD::SSAT: return "ARMISD::SSAT"; 1258 1259 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1260 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1261 case ARMISD::RRX: return "ARMISD::RRX"; 1262 1263 case ARMISD::ADDC: return "ARMISD::ADDC"; 1264 case ARMISD::ADDE: return "ARMISD::ADDE"; 1265 case ARMISD::SUBC: return "ARMISD::SUBC"; 1266 case ARMISD::SUBE: return "ARMISD::SUBE"; 1267 1268 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1269 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1270 1271 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1272 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1273 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1274 1275 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1276 1277 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1278 1279 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1280 1281 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1282 1283 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1284 1285 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1286 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1287 1288 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1289 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1290 case ARMISD::VCGE: return "ARMISD::VCGE"; 1291 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1292 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1293 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1294 case ARMISD::VCGT: return "ARMISD::VCGT"; 1295 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1296 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1297 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1298 case ARMISD::VTST: return "ARMISD::VTST"; 1299 1300 case ARMISD::VSHL: return "ARMISD::VSHL"; 1301 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1302 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1303 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1304 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1305 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1306 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1307 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1308 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1309 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1310 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1311 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1312 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1313 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1314 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1315 case ARMISD::VSLI: return "ARMISD::VSLI"; 1316 case ARMISD::VSRI: return "ARMISD::VSRI"; 1317 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1318 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1319 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1320 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1321 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1322 case ARMISD::VDUP: return "ARMISD::VDUP"; 1323 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1324 case ARMISD::VEXT: return "ARMISD::VEXT"; 1325 case ARMISD::VREV64: return "ARMISD::VREV64"; 1326 case ARMISD::VREV32: return "ARMISD::VREV32"; 1327 case ARMISD::VREV16: return "ARMISD::VREV16"; 1328 case ARMISD::VZIP: return "ARMISD::VZIP"; 1329 case ARMISD::VUZP: return "ARMISD::VUZP"; 1330 case ARMISD::VTRN: return "ARMISD::VTRN"; 1331 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1332 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1333 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1334 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1335 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1336 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1337 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1338 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1339 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1340 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1341 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1342 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1343 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1344 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1345 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1346 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1347 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1348 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1349 case ARMISD::BFI: return "ARMISD::BFI"; 1350 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1351 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1352 case ARMISD::VBSL: return "ARMISD::VBSL"; 1353 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1354 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1355 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1356 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1357 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1358 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1359 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1360 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1361 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1362 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1363 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1364 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1365 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1366 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1367 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1368 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1369 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1370 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1371 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1372 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1373 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1374 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1375 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1376 } 1377 return nullptr; 1378 } 1379 1380 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1381 EVT VT) const { 1382 if (!VT.isVector()) 1383 return getPointerTy(DL); 1384 return VT.changeVectorElementTypeToInteger(); 1385 } 1386 1387 /// getRegClassFor - Return the register class that should be used for the 1388 /// specified value type. 1389 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1390 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1391 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1392 // load / store 4 to 8 consecutive D registers. 1393 if (Subtarget->hasNEON()) { 1394 if (VT == MVT::v4i64) 1395 return &ARM::QQPRRegClass; 1396 if (VT == MVT::v8i64) 1397 return &ARM::QQQQPRRegClass; 1398 } 1399 return TargetLowering::getRegClassFor(VT); 1400 } 1401 1402 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1403 // source/dest is aligned and the copy size is large enough. We therefore want 1404 // to align such objects passed to memory intrinsics. 1405 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1406 unsigned &PrefAlign) const { 1407 if (!isa<MemIntrinsic>(CI)) 1408 return false; 1409 MinSize = 8; 1410 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1411 // cycle faster than 4-byte aligned LDM. 1412 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1413 return true; 1414 } 1415 1416 // Create a fast isel object. 1417 FastISel * 1418 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1419 const TargetLibraryInfo *libInfo) const { 1420 return ARM::createFastISel(funcInfo, libInfo); 1421 } 1422 1423 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1424 unsigned NumVals = N->getNumValues(); 1425 if (!NumVals) 1426 return Sched::RegPressure; 1427 1428 for (unsigned i = 0; i != NumVals; ++i) { 1429 EVT VT = N->getValueType(i); 1430 if (VT == MVT::Glue || VT == MVT::Other) 1431 continue; 1432 if (VT.isFloatingPoint() || VT.isVector()) 1433 return Sched::ILP; 1434 } 1435 1436 if (!N->isMachineOpcode()) 1437 return Sched::RegPressure; 1438 1439 // Load are scheduled for latency even if there instruction itinerary 1440 // is not available. 1441 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1442 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1443 1444 if (MCID.getNumDefs() == 0) 1445 return Sched::RegPressure; 1446 if (!Itins->isEmpty() && 1447 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1448 return Sched::ILP; 1449 1450 return Sched::RegPressure; 1451 } 1452 1453 //===----------------------------------------------------------------------===// 1454 // Lowering Code 1455 //===----------------------------------------------------------------------===// 1456 1457 static bool isSRL16(const SDValue &Op) { 1458 if (Op.getOpcode() != ISD::SRL) 1459 return false; 1460 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1461 return Const->getZExtValue() == 16; 1462 return false; 1463 } 1464 1465 static bool isSRA16(const SDValue &Op) { 1466 if (Op.getOpcode() != ISD::SRA) 1467 return false; 1468 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1469 return Const->getZExtValue() == 16; 1470 return false; 1471 } 1472 1473 static bool isSHL16(const SDValue &Op) { 1474 if (Op.getOpcode() != ISD::SHL) 1475 return false; 1476 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1477 return Const->getZExtValue() == 16; 1478 return false; 1479 } 1480 1481 // Check for a signed 16-bit value. We special case SRA because it makes it 1482 // more simple when also looking for SRAs that aren't sign extending a 1483 // smaller value. Without the check, we'd need to take extra care with 1484 // checking order for some operations. 1485 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1486 if (isSRA16(Op)) 1487 return isSHL16(Op.getOperand(0)); 1488 return DAG.ComputeNumSignBits(Op) == 17; 1489 } 1490 1491 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1492 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1493 switch (CC) { 1494 default: llvm_unreachable("Unknown condition code!"); 1495 case ISD::SETNE: return ARMCC::NE; 1496 case ISD::SETEQ: return ARMCC::EQ; 1497 case ISD::SETGT: return ARMCC::GT; 1498 case ISD::SETGE: return ARMCC::GE; 1499 case ISD::SETLT: return ARMCC::LT; 1500 case ISD::SETLE: return ARMCC::LE; 1501 case ISD::SETUGT: return ARMCC::HI; 1502 case ISD::SETUGE: return ARMCC::HS; 1503 case ISD::SETULT: return ARMCC::LO; 1504 case ISD::SETULE: return ARMCC::LS; 1505 } 1506 } 1507 1508 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1509 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1510 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1511 CondCode2 = ARMCC::AL; 1512 InvalidOnQNaN = true; 1513 switch (CC) { 1514 default: llvm_unreachable("Unknown FP condition!"); 1515 case ISD::SETEQ: 1516 case ISD::SETOEQ: 1517 CondCode = ARMCC::EQ; 1518 InvalidOnQNaN = false; 1519 break; 1520 case ISD::SETGT: 1521 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1522 case ISD::SETGE: 1523 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1524 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1525 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1526 case ISD::SETONE: 1527 CondCode = ARMCC::MI; 1528 CondCode2 = ARMCC::GT; 1529 InvalidOnQNaN = false; 1530 break; 1531 case ISD::SETO: CondCode = ARMCC::VC; break; 1532 case ISD::SETUO: CondCode = ARMCC::VS; break; 1533 case ISD::SETUEQ: 1534 CondCode = ARMCC::EQ; 1535 CondCode2 = ARMCC::VS; 1536 InvalidOnQNaN = false; 1537 break; 1538 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1539 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1540 case ISD::SETLT: 1541 case ISD::SETULT: CondCode = ARMCC::LT; break; 1542 case ISD::SETLE: 1543 case ISD::SETULE: CondCode = ARMCC::LE; break; 1544 case ISD::SETNE: 1545 case ISD::SETUNE: 1546 CondCode = ARMCC::NE; 1547 InvalidOnQNaN = false; 1548 break; 1549 } 1550 } 1551 1552 //===----------------------------------------------------------------------===// 1553 // Calling Convention Implementation 1554 //===----------------------------------------------------------------------===// 1555 1556 #include "ARMGenCallingConv.inc" 1557 1558 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1559 /// account presence of floating point hardware and calling convention 1560 /// limitations, such as support for variadic functions. 1561 CallingConv::ID 1562 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1563 bool isVarArg) const { 1564 switch (CC) { 1565 default: 1566 report_fatal_error("Unsupported calling convention"); 1567 case CallingConv::ARM_AAPCS: 1568 case CallingConv::ARM_APCS: 1569 case CallingConv::GHC: 1570 return CC; 1571 case CallingConv::PreserveMost: 1572 return CallingConv::PreserveMost; 1573 case CallingConv::ARM_AAPCS_VFP: 1574 case CallingConv::Swift: 1575 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1576 case CallingConv::C: 1577 if (!Subtarget->isAAPCS_ABI()) 1578 return CallingConv::ARM_APCS; 1579 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1580 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1581 !isVarArg) 1582 return CallingConv::ARM_AAPCS_VFP; 1583 else 1584 return CallingConv::ARM_AAPCS; 1585 case CallingConv::Fast: 1586 case CallingConv::CXX_FAST_TLS: 1587 if (!Subtarget->isAAPCS_ABI()) { 1588 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1589 return CallingConv::Fast; 1590 return CallingConv::ARM_APCS; 1591 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1592 return CallingConv::ARM_AAPCS_VFP; 1593 else 1594 return CallingConv::ARM_AAPCS; 1595 } 1596 } 1597 1598 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1599 bool isVarArg) const { 1600 return CCAssignFnForNode(CC, false, isVarArg); 1601 } 1602 1603 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1604 bool isVarArg) const { 1605 return CCAssignFnForNode(CC, true, isVarArg); 1606 } 1607 1608 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1609 /// CallingConvention. 1610 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1611 bool Return, 1612 bool isVarArg) const { 1613 switch (getEffectiveCallingConv(CC, isVarArg)) { 1614 default: 1615 report_fatal_error("Unsupported calling convention"); 1616 case CallingConv::ARM_APCS: 1617 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1618 case CallingConv::ARM_AAPCS: 1619 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1620 case CallingConv::ARM_AAPCS_VFP: 1621 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1622 case CallingConv::Fast: 1623 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1624 case CallingConv::GHC: 1625 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1626 case CallingConv::PreserveMost: 1627 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1628 } 1629 } 1630 1631 /// LowerCallResult - Lower the result values of a call into the 1632 /// appropriate copies out of appropriate physical registers. 1633 SDValue ARMTargetLowering::LowerCallResult( 1634 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1635 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1636 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1637 SDValue ThisVal) const { 1638 // Assign locations to each value returned by this call. 1639 SmallVector<CCValAssign, 16> RVLocs; 1640 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1641 *DAG.getContext()); 1642 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1643 1644 // Copy all of the result registers out of their specified physreg. 1645 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1646 CCValAssign VA = RVLocs[i]; 1647 1648 // Pass 'this' value directly from the argument to return value, to avoid 1649 // reg unit interference 1650 if (i == 0 && isThisReturn) { 1651 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1652 "unexpected return calling convention register assignment"); 1653 InVals.push_back(ThisVal); 1654 continue; 1655 } 1656 1657 SDValue Val; 1658 if (VA.needsCustom()) { 1659 // Handle f64 or half of a v2f64. 1660 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1661 InFlag); 1662 Chain = Lo.getValue(1); 1663 InFlag = Lo.getValue(2); 1664 VA = RVLocs[++i]; // skip ahead to next loc 1665 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1666 InFlag); 1667 Chain = Hi.getValue(1); 1668 InFlag = Hi.getValue(2); 1669 if (!Subtarget->isLittle()) 1670 std::swap (Lo, Hi); 1671 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1672 1673 if (VA.getLocVT() == MVT::v2f64) { 1674 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1675 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1676 DAG.getConstant(0, dl, MVT::i32)); 1677 1678 VA = RVLocs[++i]; // skip ahead to next loc 1679 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1680 Chain = Lo.getValue(1); 1681 InFlag = Lo.getValue(2); 1682 VA = RVLocs[++i]; // skip ahead to next loc 1683 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1684 Chain = Hi.getValue(1); 1685 InFlag = Hi.getValue(2); 1686 if (!Subtarget->isLittle()) 1687 std::swap (Lo, Hi); 1688 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1689 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1690 DAG.getConstant(1, dl, MVT::i32)); 1691 } 1692 } else { 1693 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1694 InFlag); 1695 Chain = Val.getValue(1); 1696 InFlag = Val.getValue(2); 1697 } 1698 1699 switch (VA.getLocInfo()) { 1700 default: llvm_unreachable("Unknown loc info!"); 1701 case CCValAssign::Full: break; 1702 case CCValAssign::BCvt: 1703 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1704 break; 1705 } 1706 1707 InVals.push_back(Val); 1708 } 1709 1710 return Chain; 1711 } 1712 1713 /// LowerMemOpCallTo - Store the argument to the stack. 1714 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1715 SDValue Arg, const SDLoc &dl, 1716 SelectionDAG &DAG, 1717 const CCValAssign &VA, 1718 ISD::ArgFlagsTy Flags) const { 1719 unsigned LocMemOffset = VA.getLocMemOffset(); 1720 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1721 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1722 StackPtr, PtrOff); 1723 return DAG.getStore( 1724 Chain, dl, Arg, PtrOff, 1725 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1726 } 1727 1728 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1729 SDValue Chain, SDValue &Arg, 1730 RegsToPassVector &RegsToPass, 1731 CCValAssign &VA, CCValAssign &NextVA, 1732 SDValue &StackPtr, 1733 SmallVectorImpl<SDValue> &MemOpChains, 1734 ISD::ArgFlagsTy Flags) const { 1735 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1736 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1737 unsigned id = Subtarget->isLittle() ? 0 : 1; 1738 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1739 1740 if (NextVA.isRegLoc()) 1741 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1742 else { 1743 assert(NextVA.isMemLoc()); 1744 if (!StackPtr.getNode()) 1745 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1746 getPointerTy(DAG.getDataLayout())); 1747 1748 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1749 dl, DAG, NextVA, 1750 Flags)); 1751 } 1752 } 1753 1754 /// LowerCall - Lowering a call into a callseq_start <- 1755 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1756 /// nodes. 1757 SDValue 1758 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1759 SmallVectorImpl<SDValue> &InVals) const { 1760 SelectionDAG &DAG = CLI.DAG; 1761 SDLoc &dl = CLI.DL; 1762 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1763 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1764 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1765 SDValue Chain = CLI.Chain; 1766 SDValue Callee = CLI.Callee; 1767 bool &isTailCall = CLI.IsTailCall; 1768 CallingConv::ID CallConv = CLI.CallConv; 1769 bool doesNotRet = CLI.DoesNotReturn; 1770 bool isVarArg = CLI.IsVarArg; 1771 1772 MachineFunction &MF = DAG.getMachineFunction(); 1773 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1774 bool isThisReturn = false; 1775 bool isSibCall = false; 1776 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1777 1778 // Disable tail calls if they're not supported. 1779 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1780 isTailCall = false; 1781 1782 if (isTailCall) { 1783 // Check if it's really possible to do a tail call. 1784 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1785 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1786 Outs, OutVals, Ins, DAG); 1787 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1788 report_fatal_error("failed to perform tail call elimination on a call " 1789 "site marked musttail"); 1790 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1791 // detected sibcalls. 1792 if (isTailCall) { 1793 ++NumTailCalls; 1794 isSibCall = true; 1795 } 1796 } 1797 1798 // Analyze operands of the call, assigning locations to each operand. 1799 SmallVector<CCValAssign, 16> ArgLocs; 1800 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1801 *DAG.getContext()); 1802 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1803 1804 // Get a count of how many bytes are to be pushed on the stack. 1805 unsigned NumBytes = CCInfo.getNextStackOffset(); 1806 1807 // For tail calls, memory operands are available in our caller's stack. 1808 if (isSibCall) 1809 NumBytes = 0; 1810 1811 // Adjust the stack pointer for the new arguments... 1812 // These operations are automatically eliminated by the prolog/epilog pass 1813 if (!isSibCall) 1814 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1815 1816 SDValue StackPtr = 1817 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1818 1819 RegsToPassVector RegsToPass; 1820 SmallVector<SDValue, 8> MemOpChains; 1821 1822 // Walk the register/memloc assignments, inserting copies/loads. In the case 1823 // of tail call optimization, arguments are handled later. 1824 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1825 i != e; 1826 ++i, ++realArgIdx) { 1827 CCValAssign &VA = ArgLocs[i]; 1828 SDValue Arg = OutVals[realArgIdx]; 1829 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1830 bool isByVal = Flags.isByVal(); 1831 1832 // Promote the value if needed. 1833 switch (VA.getLocInfo()) { 1834 default: llvm_unreachable("Unknown loc info!"); 1835 case CCValAssign::Full: break; 1836 case CCValAssign::SExt: 1837 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1838 break; 1839 case CCValAssign::ZExt: 1840 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1841 break; 1842 case CCValAssign::AExt: 1843 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1844 break; 1845 case CCValAssign::BCvt: 1846 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1847 break; 1848 } 1849 1850 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1851 if (VA.needsCustom()) { 1852 if (VA.getLocVT() == MVT::v2f64) { 1853 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1854 DAG.getConstant(0, dl, MVT::i32)); 1855 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1856 DAG.getConstant(1, dl, MVT::i32)); 1857 1858 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1859 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1860 1861 VA = ArgLocs[++i]; // skip ahead to next loc 1862 if (VA.isRegLoc()) { 1863 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1864 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1865 } else { 1866 assert(VA.isMemLoc()); 1867 1868 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1869 dl, DAG, VA, Flags)); 1870 } 1871 } else { 1872 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1873 StackPtr, MemOpChains, Flags); 1874 } 1875 } else if (VA.isRegLoc()) { 1876 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1877 Outs[0].VT == MVT::i32) { 1878 assert(VA.getLocVT() == MVT::i32 && 1879 "unexpected calling convention register assignment"); 1880 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1881 "unexpected use of 'returned'"); 1882 isThisReturn = true; 1883 } 1884 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1885 } else if (isByVal) { 1886 assert(VA.isMemLoc()); 1887 unsigned offset = 0; 1888 1889 // True if this byval aggregate will be split between registers 1890 // and memory. 1891 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1892 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1893 1894 if (CurByValIdx < ByValArgsCount) { 1895 1896 unsigned RegBegin, RegEnd; 1897 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1898 1899 EVT PtrVT = 1900 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1901 unsigned int i, j; 1902 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1903 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1904 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1905 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1906 MachinePointerInfo(), 1907 DAG.InferPtrAlignment(AddArg)); 1908 MemOpChains.push_back(Load.getValue(1)); 1909 RegsToPass.push_back(std::make_pair(j, Load)); 1910 } 1911 1912 // If parameter size outsides register area, "offset" value 1913 // helps us to calculate stack slot for remained part properly. 1914 offset = RegEnd - RegBegin; 1915 1916 CCInfo.nextInRegsParam(); 1917 } 1918 1919 if (Flags.getByValSize() > 4*offset) { 1920 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1921 unsigned LocMemOffset = VA.getLocMemOffset(); 1922 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1923 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1924 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1925 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1926 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1927 MVT::i32); 1928 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1929 MVT::i32); 1930 1931 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1932 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1933 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1934 Ops)); 1935 } 1936 } else if (!isSibCall) { 1937 assert(VA.isMemLoc()); 1938 1939 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1940 dl, DAG, VA, Flags)); 1941 } 1942 } 1943 1944 if (!MemOpChains.empty()) 1945 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1946 1947 // Build a sequence of copy-to-reg nodes chained together with token chain 1948 // and flag operands which copy the outgoing args into the appropriate regs. 1949 SDValue InFlag; 1950 // Tail call byval lowering might overwrite argument registers so in case of 1951 // tail call optimization the copies to registers are lowered later. 1952 if (!isTailCall) 1953 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1954 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1955 RegsToPass[i].second, InFlag); 1956 InFlag = Chain.getValue(1); 1957 } 1958 1959 // For tail calls lower the arguments to the 'real' stack slot. 1960 if (isTailCall) { 1961 // Force all the incoming stack arguments to be loaded from the stack 1962 // before any new outgoing arguments are stored to the stack, because the 1963 // outgoing stack slots may alias the incoming argument stack slots, and 1964 // the alias isn't otherwise explicit. This is slightly more conservative 1965 // than necessary, because it means that each store effectively depends 1966 // on every argument instead of just those arguments it would clobber. 1967 1968 // Do not flag preceding copytoreg stuff together with the following stuff. 1969 InFlag = SDValue(); 1970 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1971 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1972 RegsToPass[i].second, InFlag); 1973 InFlag = Chain.getValue(1); 1974 } 1975 InFlag = SDValue(); 1976 } 1977 1978 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1979 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1980 // node so that legalize doesn't hack it. 1981 bool isDirect = false; 1982 1983 const TargetMachine &TM = getTargetMachine(); 1984 const Module *Mod = MF.getFunction()->getParent(); 1985 const GlobalValue *GV = nullptr; 1986 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1987 GV = G->getGlobal(); 1988 bool isStub = 1989 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1990 1991 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1992 bool isLocalARMFunc = false; 1993 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1994 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1995 1996 if (Subtarget->genLongCalls()) { 1997 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 1998 "long-calls codegen is not position independent!"); 1999 // Handle a global address or an external symbol. If it's not one of 2000 // those, the target's already in a register, so we don't need to do 2001 // anything extra. 2002 if (isa<GlobalAddressSDNode>(Callee)) { 2003 // Create a constant pool entry for the callee address 2004 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2005 ARMConstantPoolValue *CPV = 2006 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2007 2008 // Get the address of the callee into a register 2009 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2010 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2011 Callee = DAG.getLoad( 2012 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2013 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2014 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2015 const char *Sym = S->getSymbol(); 2016 2017 // Create a constant pool entry for the callee address 2018 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2019 ARMConstantPoolValue *CPV = 2020 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2021 ARMPCLabelIndex, 0); 2022 // Get the address of the callee into a register 2023 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2024 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2025 Callee = DAG.getLoad( 2026 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2027 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2028 } 2029 } else if (isa<GlobalAddressSDNode>(Callee)) { 2030 // If we're optimizing for minimum size and the function is called three or 2031 // more times in this block, we can improve codesize by calling indirectly 2032 // as BLXr has a 16-bit encoding. 2033 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2034 auto *BB = CLI.CS.getParent(); 2035 bool PreferIndirect = 2036 Subtarget->isThumb() && MF.getFunction()->optForMinSize() && 2037 count_if(GV->users(), [&BB](const User *U) { 2038 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2039 }) > 2; 2040 2041 if (!PreferIndirect) { 2042 isDirect = true; 2043 bool isDef = GV->isStrongDefinitionForLinker(); 2044 2045 // ARM call to a local ARM function is predicable. 2046 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2047 // tBX takes a register source operand. 2048 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2049 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2050 Callee = DAG.getNode( 2051 ARMISD::WrapperPIC, dl, PtrVt, 2052 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2053 Callee = DAG.getLoad( 2054 PtrVt, dl, DAG.getEntryNode(), Callee, 2055 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2056 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2057 MachineMemOperand::MOInvariant); 2058 } else if (Subtarget->isTargetCOFF()) { 2059 assert(Subtarget->isTargetWindows() && 2060 "Windows is the only supported COFF target"); 2061 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2062 ? ARMII::MO_DLLIMPORT 2063 : ARMII::MO_NO_FLAG; 2064 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2065 TargetFlags); 2066 if (GV->hasDLLImportStorageClass()) 2067 Callee = 2068 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2069 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2070 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2071 } else { 2072 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2073 } 2074 } 2075 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2076 isDirect = true; 2077 // tBX takes a register source operand. 2078 const char *Sym = S->getSymbol(); 2079 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2080 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2081 ARMConstantPoolValue *CPV = 2082 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2083 ARMPCLabelIndex, 4); 2084 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2085 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2086 Callee = DAG.getLoad( 2087 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2088 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2089 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2090 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2091 } else { 2092 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2093 } 2094 } 2095 2096 // FIXME: handle tail calls differently. 2097 unsigned CallOpc; 2098 if (Subtarget->isThumb()) { 2099 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2100 CallOpc = ARMISD::CALL_NOLINK; 2101 else 2102 CallOpc = ARMISD::CALL; 2103 } else { 2104 if (!isDirect && !Subtarget->hasV5TOps()) 2105 CallOpc = ARMISD::CALL_NOLINK; 2106 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2107 // Emit regular call when code size is the priority 2108 !MF.getFunction()->optForMinSize()) 2109 // "mov lr, pc; b _foo" to avoid confusing the RSP 2110 CallOpc = ARMISD::CALL_NOLINK; 2111 else 2112 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2113 } 2114 2115 std::vector<SDValue> Ops; 2116 Ops.push_back(Chain); 2117 Ops.push_back(Callee); 2118 2119 // Add argument registers to the end of the list so that they are known live 2120 // into the call. 2121 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2122 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2123 RegsToPass[i].second.getValueType())); 2124 2125 // Add a register mask operand representing the call-preserved registers. 2126 if (!isTailCall) { 2127 const uint32_t *Mask; 2128 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2129 if (isThisReturn) { 2130 // For 'this' returns, use the R0-preserving mask if applicable 2131 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2132 if (!Mask) { 2133 // Set isThisReturn to false if the calling convention is not one that 2134 // allows 'returned' to be modeled in this way, so LowerCallResult does 2135 // not try to pass 'this' straight through 2136 isThisReturn = false; 2137 Mask = ARI->getCallPreservedMask(MF, CallConv); 2138 } 2139 } else 2140 Mask = ARI->getCallPreservedMask(MF, CallConv); 2141 2142 assert(Mask && "Missing call preserved mask for calling convention"); 2143 Ops.push_back(DAG.getRegisterMask(Mask)); 2144 } 2145 2146 if (InFlag.getNode()) 2147 Ops.push_back(InFlag); 2148 2149 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2150 if (isTailCall) { 2151 MF.getFrameInfo().setHasTailCall(); 2152 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2153 } 2154 2155 // Returns a chain and a flag for retval copy to use. 2156 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2157 InFlag = Chain.getValue(1); 2158 2159 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2160 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2161 if (!Ins.empty()) 2162 InFlag = Chain.getValue(1); 2163 2164 // Handle result values, copying them out of physregs into vregs that we 2165 // return. 2166 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2167 InVals, isThisReturn, 2168 isThisReturn ? OutVals[0] : SDValue()); 2169 } 2170 2171 /// HandleByVal - Every parameter *after* a byval parameter is passed 2172 /// on the stack. Remember the next parameter register to allocate, 2173 /// and then confiscate the rest of the parameter registers to insure 2174 /// this. 2175 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2176 unsigned Align) const { 2177 // Byval (as with any stack) slots are always at least 4 byte aligned. 2178 Align = std::max(Align, 4U); 2179 2180 unsigned Reg = State->AllocateReg(GPRArgRegs); 2181 if (!Reg) 2182 return; 2183 2184 unsigned AlignInRegs = Align / 4; 2185 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2186 for (unsigned i = 0; i < Waste; ++i) 2187 Reg = State->AllocateReg(GPRArgRegs); 2188 2189 if (!Reg) 2190 return; 2191 2192 unsigned Excess = 4 * (ARM::R4 - Reg); 2193 2194 // Special case when NSAA != SP and parameter size greater than size of 2195 // all remained GPR regs. In that case we can't split parameter, we must 2196 // send it to stack. We also must set NCRN to R4, so waste all 2197 // remained registers. 2198 const unsigned NSAAOffset = State->getNextStackOffset(); 2199 if (NSAAOffset != 0 && Size > Excess) { 2200 while (State->AllocateReg(GPRArgRegs)) 2201 ; 2202 return; 2203 } 2204 2205 // First register for byval parameter is the first register that wasn't 2206 // allocated before this method call, so it would be "reg". 2207 // If parameter is small enough to be saved in range [reg, r4), then 2208 // the end (first after last) register would be reg + param-size-in-regs, 2209 // else parameter would be splitted between registers and stack, 2210 // end register would be r4 in this case. 2211 unsigned ByValRegBegin = Reg; 2212 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2213 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2214 // Note, first register is allocated in the beginning of function already, 2215 // allocate remained amount of registers we need. 2216 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2217 State->AllocateReg(GPRArgRegs); 2218 // A byval parameter that is split between registers and memory needs its 2219 // size truncated here. 2220 // In the case where the entire structure fits in registers, we set the 2221 // size in memory to zero. 2222 Size = std::max<int>(Size - Excess, 0); 2223 } 2224 2225 /// MatchingStackOffset - Return true if the given stack call argument is 2226 /// already available in the same position (relatively) of the caller's 2227 /// incoming argument stack. 2228 static 2229 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2230 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2231 const TargetInstrInfo *TII) { 2232 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2233 int FI = std::numeric_limits<int>::max(); 2234 if (Arg.getOpcode() == ISD::CopyFromReg) { 2235 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2236 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2237 return false; 2238 MachineInstr *Def = MRI->getVRegDef(VR); 2239 if (!Def) 2240 return false; 2241 if (!Flags.isByVal()) { 2242 if (!TII->isLoadFromStackSlot(*Def, FI)) 2243 return false; 2244 } else { 2245 return false; 2246 } 2247 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2248 if (Flags.isByVal()) 2249 // ByVal argument is passed in as a pointer but it's now being 2250 // dereferenced. e.g. 2251 // define @foo(%struct.X* %A) { 2252 // tail call @bar(%struct.X* byval %A) 2253 // } 2254 return false; 2255 SDValue Ptr = Ld->getBasePtr(); 2256 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2257 if (!FINode) 2258 return false; 2259 FI = FINode->getIndex(); 2260 } else 2261 return false; 2262 2263 assert(FI != std::numeric_limits<int>::max()); 2264 if (!MFI.isFixedObjectIndex(FI)) 2265 return false; 2266 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2267 } 2268 2269 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2270 /// for tail call optimization. Targets which want to do tail call 2271 /// optimization should implement this function. 2272 bool 2273 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2274 CallingConv::ID CalleeCC, 2275 bool isVarArg, 2276 bool isCalleeStructRet, 2277 bool isCallerStructRet, 2278 const SmallVectorImpl<ISD::OutputArg> &Outs, 2279 const SmallVectorImpl<SDValue> &OutVals, 2280 const SmallVectorImpl<ISD::InputArg> &Ins, 2281 SelectionDAG& DAG) const { 2282 MachineFunction &MF = DAG.getMachineFunction(); 2283 const Function *CallerF = MF.getFunction(); 2284 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2285 2286 assert(Subtarget->supportsTailCall()); 2287 2288 // Look for obvious safe cases to perform tail call optimization that do not 2289 // require ABI changes. This is what gcc calls sibcall. 2290 2291 // Exception-handling functions need a special set of instructions to indicate 2292 // a return to the hardware. Tail-calling another function would probably 2293 // break this. 2294 if (CallerF->hasFnAttribute("interrupt")) 2295 return false; 2296 2297 // Also avoid sibcall optimization if either caller or callee uses struct 2298 // return semantics. 2299 if (isCalleeStructRet || isCallerStructRet) 2300 return false; 2301 2302 // Externally-defined functions with weak linkage should not be 2303 // tail-called on ARM when the OS does not support dynamic 2304 // pre-emption of symbols, as the AAELF spec requires normal calls 2305 // to undefined weak functions to be replaced with a NOP or jump to the 2306 // next instruction. The behaviour of branch instructions in this 2307 // situation (as used for tail calls) is implementation-defined, so we 2308 // cannot rely on the linker replacing the tail call with a return. 2309 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2310 const GlobalValue *GV = G->getGlobal(); 2311 const Triple &TT = getTargetMachine().getTargetTriple(); 2312 if (GV->hasExternalWeakLinkage() && 2313 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2314 return false; 2315 } 2316 2317 // Check that the call results are passed in the same way. 2318 LLVMContext &C = *DAG.getContext(); 2319 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2320 CCAssignFnForReturn(CalleeCC, isVarArg), 2321 CCAssignFnForReturn(CallerCC, isVarArg))) 2322 return false; 2323 // The callee has to preserve all registers the caller needs to preserve. 2324 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2325 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2326 if (CalleeCC != CallerCC) { 2327 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2328 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2329 return false; 2330 } 2331 2332 // If Caller's vararg or byval argument has been split between registers and 2333 // stack, do not perform tail call, since part of the argument is in caller's 2334 // local frame. 2335 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2336 if (AFI_Caller->getArgRegsSaveSize()) 2337 return false; 2338 2339 // If the callee takes no arguments then go on to check the results of the 2340 // call. 2341 if (!Outs.empty()) { 2342 // Check if stack adjustment is needed. For now, do not do this if any 2343 // argument is passed on the stack. 2344 SmallVector<CCValAssign, 16> ArgLocs; 2345 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2346 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2347 if (CCInfo.getNextStackOffset()) { 2348 // Check if the arguments are already laid out in the right way as 2349 // the caller's fixed stack objects. 2350 MachineFrameInfo &MFI = MF.getFrameInfo(); 2351 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2352 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2353 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2354 i != e; 2355 ++i, ++realArgIdx) { 2356 CCValAssign &VA = ArgLocs[i]; 2357 EVT RegVT = VA.getLocVT(); 2358 SDValue Arg = OutVals[realArgIdx]; 2359 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2360 if (VA.getLocInfo() == CCValAssign::Indirect) 2361 return false; 2362 if (VA.needsCustom()) { 2363 // f64 and vector types are split into multiple registers or 2364 // register/stack-slot combinations. The types will not match 2365 // the registers; give up on memory f64 refs until we figure 2366 // out what to do about this. 2367 if (!VA.isRegLoc()) 2368 return false; 2369 if (!ArgLocs[++i].isRegLoc()) 2370 return false; 2371 if (RegVT == MVT::v2f64) { 2372 if (!ArgLocs[++i].isRegLoc()) 2373 return false; 2374 if (!ArgLocs[++i].isRegLoc()) 2375 return false; 2376 } 2377 } else if (!VA.isRegLoc()) { 2378 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2379 MFI, MRI, TII)) 2380 return false; 2381 } 2382 } 2383 } 2384 2385 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2386 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2387 return false; 2388 } 2389 2390 return true; 2391 } 2392 2393 bool 2394 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2395 MachineFunction &MF, bool isVarArg, 2396 const SmallVectorImpl<ISD::OutputArg> &Outs, 2397 LLVMContext &Context) const { 2398 SmallVector<CCValAssign, 16> RVLocs; 2399 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2400 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2401 } 2402 2403 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2404 const SDLoc &DL, SelectionDAG &DAG) { 2405 const MachineFunction &MF = DAG.getMachineFunction(); 2406 const Function *F = MF.getFunction(); 2407 2408 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2409 2410 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2411 // version of the "preferred return address". These offsets affect the return 2412 // instruction if this is a return from PL1 without hypervisor extensions. 2413 // IRQ/FIQ: +4 "subs pc, lr, #4" 2414 // SWI: 0 "subs pc, lr, #0" 2415 // ABORT: +4 "subs pc, lr, #4" 2416 // UNDEF: +4/+2 "subs pc, lr, #0" 2417 // UNDEF varies depending on where the exception came from ARM or Thumb 2418 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2419 2420 int64_t LROffset; 2421 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2422 IntKind == "ABORT") 2423 LROffset = 4; 2424 else if (IntKind == "SWI" || IntKind == "UNDEF") 2425 LROffset = 0; 2426 else 2427 report_fatal_error("Unsupported interrupt attribute. If present, value " 2428 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2429 2430 RetOps.insert(RetOps.begin() + 1, 2431 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2432 2433 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2434 } 2435 2436 SDValue 2437 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2438 bool isVarArg, 2439 const SmallVectorImpl<ISD::OutputArg> &Outs, 2440 const SmallVectorImpl<SDValue> &OutVals, 2441 const SDLoc &dl, SelectionDAG &DAG) const { 2442 // CCValAssign - represent the assignment of the return value to a location. 2443 SmallVector<CCValAssign, 16> RVLocs; 2444 2445 // CCState - Info about the registers and stack slots. 2446 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2447 *DAG.getContext()); 2448 2449 // Analyze outgoing return values. 2450 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2451 2452 SDValue Flag; 2453 SmallVector<SDValue, 4> RetOps; 2454 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2455 bool isLittleEndian = Subtarget->isLittle(); 2456 2457 MachineFunction &MF = DAG.getMachineFunction(); 2458 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2459 AFI->setReturnRegsCount(RVLocs.size()); 2460 2461 // Copy the result values into the output registers. 2462 for (unsigned i = 0, realRVLocIdx = 0; 2463 i != RVLocs.size(); 2464 ++i, ++realRVLocIdx) { 2465 CCValAssign &VA = RVLocs[i]; 2466 assert(VA.isRegLoc() && "Can only return in registers!"); 2467 2468 SDValue Arg = OutVals[realRVLocIdx]; 2469 2470 switch (VA.getLocInfo()) { 2471 default: llvm_unreachable("Unknown loc info!"); 2472 case CCValAssign::Full: break; 2473 case CCValAssign::BCvt: 2474 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2475 break; 2476 } 2477 2478 if (VA.needsCustom()) { 2479 if (VA.getLocVT() == MVT::v2f64) { 2480 // Extract the first half and return it in two registers. 2481 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2482 DAG.getConstant(0, dl, MVT::i32)); 2483 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2484 DAG.getVTList(MVT::i32, MVT::i32), Half); 2485 2486 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2487 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2488 Flag); 2489 Flag = Chain.getValue(1); 2490 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2491 VA = RVLocs[++i]; // skip ahead to next loc 2492 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2493 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2494 Flag); 2495 Flag = Chain.getValue(1); 2496 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2497 VA = RVLocs[++i]; // skip ahead to next loc 2498 2499 // Extract the 2nd half and fall through to handle it as an f64 value. 2500 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2501 DAG.getConstant(1, dl, MVT::i32)); 2502 } 2503 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2504 // available. 2505 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2506 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2507 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2508 fmrrd.getValue(isLittleEndian ? 0 : 1), 2509 Flag); 2510 Flag = Chain.getValue(1); 2511 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2512 VA = RVLocs[++i]; // skip ahead to next loc 2513 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2514 fmrrd.getValue(isLittleEndian ? 1 : 0), 2515 Flag); 2516 } else 2517 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2518 2519 // Guarantee that all emitted copies are 2520 // stuck together, avoiding something bad. 2521 Flag = Chain.getValue(1); 2522 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2523 } 2524 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2525 const MCPhysReg *I = 2526 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2527 if (I) { 2528 for (; *I; ++I) { 2529 if (ARM::GPRRegClass.contains(*I)) 2530 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2531 else if (ARM::DPRRegClass.contains(*I)) 2532 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2533 else 2534 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2535 } 2536 } 2537 2538 // Update chain and glue. 2539 RetOps[0] = Chain; 2540 if (Flag.getNode()) 2541 RetOps.push_back(Flag); 2542 2543 // CPUs which aren't M-class use a special sequence to return from 2544 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2545 // though we use "subs pc, lr, #N"). 2546 // 2547 // M-class CPUs actually use a normal return sequence with a special 2548 // (hardware-provided) value in LR, so the normal code path works. 2549 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2550 !Subtarget->isMClass()) { 2551 if (Subtarget->isThumb1Only()) 2552 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2553 return LowerInterruptReturn(RetOps, dl, DAG); 2554 } 2555 2556 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2557 } 2558 2559 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2560 if (N->getNumValues() != 1) 2561 return false; 2562 if (!N->hasNUsesOfValue(1, 0)) 2563 return false; 2564 2565 SDValue TCChain = Chain; 2566 SDNode *Copy = *N->use_begin(); 2567 if (Copy->getOpcode() == ISD::CopyToReg) { 2568 // If the copy has a glue operand, we conservatively assume it isn't safe to 2569 // perform a tail call. 2570 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2571 return false; 2572 TCChain = Copy->getOperand(0); 2573 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2574 SDNode *VMov = Copy; 2575 // f64 returned in a pair of GPRs. 2576 SmallPtrSet<SDNode*, 2> Copies; 2577 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2578 UI != UE; ++UI) { 2579 if (UI->getOpcode() != ISD::CopyToReg) 2580 return false; 2581 Copies.insert(*UI); 2582 } 2583 if (Copies.size() > 2) 2584 return false; 2585 2586 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2587 UI != UE; ++UI) { 2588 SDValue UseChain = UI->getOperand(0); 2589 if (Copies.count(UseChain.getNode())) 2590 // Second CopyToReg 2591 Copy = *UI; 2592 else { 2593 // We are at the top of this chain. 2594 // If the copy has a glue operand, we conservatively assume it 2595 // isn't safe to perform a tail call. 2596 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2597 return false; 2598 // First CopyToReg 2599 TCChain = UseChain; 2600 } 2601 } 2602 } else if (Copy->getOpcode() == ISD::BITCAST) { 2603 // f32 returned in a single GPR. 2604 if (!Copy->hasOneUse()) 2605 return false; 2606 Copy = *Copy->use_begin(); 2607 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2608 return false; 2609 // If the copy has a glue operand, we conservatively assume it isn't safe to 2610 // perform a tail call. 2611 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2612 return false; 2613 TCChain = Copy->getOperand(0); 2614 } else { 2615 return false; 2616 } 2617 2618 bool HasRet = false; 2619 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2620 UI != UE; ++UI) { 2621 if (UI->getOpcode() != ARMISD::RET_FLAG && 2622 UI->getOpcode() != ARMISD::INTRET_FLAG) 2623 return false; 2624 HasRet = true; 2625 } 2626 2627 if (!HasRet) 2628 return false; 2629 2630 Chain = TCChain; 2631 return true; 2632 } 2633 2634 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2635 if (!Subtarget->supportsTailCall()) 2636 return false; 2637 2638 auto Attr = 2639 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2640 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2641 return false; 2642 2643 return true; 2644 } 2645 2646 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2647 // and pass the lower and high parts through. 2648 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2649 SDLoc DL(Op); 2650 SDValue WriteValue = Op->getOperand(2); 2651 2652 // This function is only supposed to be called for i64 type argument. 2653 assert(WriteValue.getValueType() == MVT::i64 2654 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2655 2656 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2657 DAG.getConstant(0, DL, MVT::i32)); 2658 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2659 DAG.getConstant(1, DL, MVT::i32)); 2660 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2661 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2662 } 2663 2664 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2665 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2666 // one of the above mentioned nodes. It has to be wrapped because otherwise 2667 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2668 // be used to form addressing mode. These wrapped nodes will be selected 2669 // into MOVi. 2670 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2671 SelectionDAG &DAG) const { 2672 EVT PtrVT = Op.getValueType(); 2673 // FIXME there is no actual debug info here 2674 SDLoc dl(Op); 2675 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2676 SDValue Res; 2677 2678 // When generating execute-only code Constant Pools must be promoted to the 2679 // global data section. It's a bit ugly that we can't share them across basic 2680 // blocks, but this way we guarantee that execute-only behaves correct with 2681 // position-independent addressing modes. 2682 if (Subtarget->genExecuteOnly()) { 2683 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2684 auto T = const_cast<Type*>(CP->getType()); 2685 auto C = const_cast<Constant*>(CP->getConstVal()); 2686 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2687 getFunction()->getParent()); 2688 auto GV = new GlobalVariable( 2689 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2690 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2691 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2692 Twine(AFI->createPICLabelUId()) 2693 ); 2694 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2695 dl, PtrVT); 2696 return LowerGlobalAddress(GA, DAG); 2697 } 2698 2699 if (CP->isMachineConstantPoolEntry()) 2700 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2701 CP->getAlignment()); 2702 else 2703 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2704 CP->getAlignment()); 2705 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2706 } 2707 2708 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2709 return MachineJumpTableInfo::EK_Inline; 2710 } 2711 2712 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2713 SelectionDAG &DAG) const { 2714 MachineFunction &MF = DAG.getMachineFunction(); 2715 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2716 unsigned ARMPCLabelIndex = 0; 2717 SDLoc DL(Op); 2718 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2719 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2720 SDValue CPAddr; 2721 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2722 if (!IsPositionIndependent) { 2723 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2724 } else { 2725 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2726 ARMPCLabelIndex = AFI->createPICLabelUId(); 2727 ARMConstantPoolValue *CPV = 2728 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2729 ARMCP::CPBlockAddress, PCAdj); 2730 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2731 } 2732 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2733 SDValue Result = DAG.getLoad( 2734 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2735 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2736 if (!IsPositionIndependent) 2737 return Result; 2738 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2739 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2740 } 2741 2742 /// \brief Convert a TLS address reference into the correct sequence of loads 2743 /// and calls to compute the variable's address for Darwin, and return an 2744 /// SDValue containing the final node. 2745 2746 /// Darwin only has one TLS scheme which must be capable of dealing with the 2747 /// fully general situation, in the worst case. This means: 2748 /// + "extern __thread" declaration. 2749 /// + Defined in a possibly unknown dynamic library. 2750 /// 2751 /// The general system is that each __thread variable has a [3 x i32] descriptor 2752 /// which contains information used by the runtime to calculate the address. The 2753 /// only part of this the compiler needs to know about is the first word, which 2754 /// contains a function pointer that must be called with the address of the 2755 /// entire descriptor in "r0". 2756 /// 2757 /// Since this descriptor may be in a different unit, in general access must 2758 /// proceed along the usual ARM rules. A common sequence to produce is: 2759 /// 2760 /// movw rT1, :lower16:_var$non_lazy_ptr 2761 /// movt rT1, :upper16:_var$non_lazy_ptr 2762 /// ldr r0, [rT1] 2763 /// ldr rT2, [r0] 2764 /// blx rT2 2765 /// [...address now in r0...] 2766 SDValue 2767 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2768 SelectionDAG &DAG) const { 2769 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2770 SDLoc DL(Op); 2771 2772 // First step is to get the address of the actua global symbol. This is where 2773 // the TLS descriptor lives. 2774 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2775 2776 // The first entry in the descriptor is a function pointer that we must call 2777 // to obtain the address of the variable. 2778 SDValue Chain = DAG.getEntryNode(); 2779 SDValue FuncTLVGet = DAG.getLoad( 2780 MVT::i32, DL, Chain, DescAddr, 2781 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2782 /* Alignment = */ 4, 2783 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2784 MachineMemOperand::MOInvariant); 2785 Chain = FuncTLVGet.getValue(1); 2786 2787 MachineFunction &F = DAG.getMachineFunction(); 2788 MachineFrameInfo &MFI = F.getFrameInfo(); 2789 MFI.setAdjustsStack(true); 2790 2791 // TLS calls preserve all registers except those that absolutely must be 2792 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2793 // silly). 2794 auto TRI = 2795 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2796 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2797 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2798 2799 // Finally, we can make the call. This is just a degenerate version of a 2800 // normal AArch64 call node: r0 takes the address of the descriptor, and 2801 // returns the address of the variable in this thread. 2802 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2803 Chain = 2804 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2805 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2806 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2807 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2808 } 2809 2810 SDValue 2811 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2812 SelectionDAG &DAG) const { 2813 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2814 2815 SDValue Chain = DAG.getEntryNode(); 2816 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2817 SDLoc DL(Op); 2818 2819 // Load the current TEB (thread environment block) 2820 SDValue Ops[] = {Chain, 2821 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2822 DAG.getConstant(15, DL, MVT::i32), 2823 DAG.getConstant(0, DL, MVT::i32), 2824 DAG.getConstant(13, DL, MVT::i32), 2825 DAG.getConstant(0, DL, MVT::i32), 2826 DAG.getConstant(2, DL, MVT::i32)}; 2827 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2828 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2829 2830 SDValue TEB = CurrentTEB.getValue(0); 2831 Chain = CurrentTEB.getValue(1); 2832 2833 // Load the ThreadLocalStoragePointer from the TEB 2834 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2835 SDValue TLSArray = 2836 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2837 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2838 2839 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2840 // offset into the TLSArray. 2841 2842 // Load the TLS index from the C runtime 2843 SDValue TLSIndex = 2844 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2845 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2846 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2847 2848 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2849 DAG.getConstant(2, DL, MVT::i32)); 2850 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2851 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2852 MachinePointerInfo()); 2853 2854 // Get the offset of the start of the .tls section (section base) 2855 const auto *GA = cast<GlobalAddressSDNode>(Op); 2856 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2857 SDValue Offset = DAG.getLoad( 2858 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2859 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2860 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2861 2862 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2863 } 2864 2865 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2866 SDValue 2867 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2868 SelectionDAG &DAG) const { 2869 SDLoc dl(GA); 2870 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2871 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2872 MachineFunction &MF = DAG.getMachineFunction(); 2873 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2874 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2875 ARMConstantPoolValue *CPV = 2876 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2877 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2878 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2879 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2880 Argument = DAG.getLoad( 2881 PtrVT, dl, DAG.getEntryNode(), Argument, 2882 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2883 SDValue Chain = Argument.getValue(1); 2884 2885 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2886 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2887 2888 // call __tls_get_addr. 2889 ArgListTy Args; 2890 ArgListEntry Entry; 2891 Entry.Node = Argument; 2892 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2893 Args.push_back(Entry); 2894 2895 // FIXME: is there useful debug info available here? 2896 TargetLowering::CallLoweringInfo CLI(DAG); 2897 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2898 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2899 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2900 2901 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2902 return CallResult.first; 2903 } 2904 2905 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2906 // "local exec" model. 2907 SDValue 2908 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2909 SelectionDAG &DAG, 2910 TLSModel::Model model) const { 2911 const GlobalValue *GV = GA->getGlobal(); 2912 SDLoc dl(GA); 2913 SDValue Offset; 2914 SDValue Chain = DAG.getEntryNode(); 2915 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2916 // Get the Thread Pointer 2917 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2918 2919 if (model == TLSModel::InitialExec) { 2920 MachineFunction &MF = DAG.getMachineFunction(); 2921 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2922 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2923 // Initial exec model. 2924 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2925 ARMConstantPoolValue *CPV = 2926 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2927 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2928 true); 2929 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2930 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2931 Offset = DAG.getLoad( 2932 PtrVT, dl, Chain, Offset, 2933 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2934 Chain = Offset.getValue(1); 2935 2936 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2937 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2938 2939 Offset = DAG.getLoad( 2940 PtrVT, dl, Chain, Offset, 2941 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2942 } else { 2943 // local exec model 2944 assert(model == TLSModel::LocalExec); 2945 ARMConstantPoolValue *CPV = 2946 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2947 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2948 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2949 Offset = DAG.getLoad( 2950 PtrVT, dl, Chain, Offset, 2951 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2952 } 2953 2954 // The address of the thread local variable is the add of the thread 2955 // pointer with the offset of the variable. 2956 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2957 } 2958 2959 SDValue 2960 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2961 if (Subtarget->isTargetDarwin()) 2962 return LowerGlobalTLSAddressDarwin(Op, DAG); 2963 2964 if (Subtarget->isTargetWindows()) 2965 return LowerGlobalTLSAddressWindows(Op, DAG); 2966 2967 // TODO: implement the "local dynamic" model 2968 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2969 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2970 if (DAG.getTarget().Options.EmulatedTLS) 2971 return LowerToTLSEmulatedModel(GA, DAG); 2972 2973 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2974 2975 switch (model) { 2976 case TLSModel::GeneralDynamic: 2977 case TLSModel::LocalDynamic: 2978 return LowerToTLSGeneralDynamicModel(GA, DAG); 2979 case TLSModel::InitialExec: 2980 case TLSModel::LocalExec: 2981 return LowerToTLSExecModels(GA, DAG, model); 2982 } 2983 llvm_unreachable("bogus TLS model"); 2984 } 2985 2986 /// Return true if all users of V are within function F, looking through 2987 /// ConstantExprs. 2988 static bool allUsersAreInFunction(const Value *V, const Function *F) { 2989 SmallVector<const User*,4> Worklist; 2990 for (auto *U : V->users()) 2991 Worklist.push_back(U); 2992 while (!Worklist.empty()) { 2993 auto *U = Worklist.pop_back_val(); 2994 if (isa<ConstantExpr>(U)) { 2995 for (auto *UU : U->users()) 2996 Worklist.push_back(UU); 2997 continue; 2998 } 2999 3000 auto *I = dyn_cast<Instruction>(U); 3001 if (!I || I->getParent()->getParent() != F) 3002 return false; 3003 } 3004 return true; 3005 } 3006 3007 /// Return true if all users of V are within some (any) function, looking through 3008 /// ConstantExprs. In other words, are there any global constant users? 3009 static bool allUsersAreInFunctions(const Value *V) { 3010 SmallVector<const User*,4> Worklist; 3011 for (auto *U : V->users()) 3012 Worklist.push_back(U); 3013 while (!Worklist.empty()) { 3014 auto *U = Worklist.pop_back_val(); 3015 if (isa<ConstantExpr>(U)) { 3016 for (auto *UU : U->users()) 3017 Worklist.push_back(UU); 3018 continue; 3019 } 3020 3021 if (!isa<Instruction>(U)) 3022 return false; 3023 } 3024 return true; 3025 } 3026 3027 // Return true if T is an integer, float or an array/vector of either. 3028 static bool isSimpleType(Type *T) { 3029 if (T->isIntegerTy() || T->isFloatingPointTy()) 3030 return true; 3031 Type *SubT = nullptr; 3032 if (T->isArrayTy()) 3033 SubT = T->getArrayElementType(); 3034 else if (T->isVectorTy()) 3035 SubT = T->getVectorElementType(); 3036 else 3037 return false; 3038 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3039 } 3040 3041 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3042 EVT PtrVT, const SDLoc &dl) { 3043 // If we're creating a pool entry for a constant global with unnamed address, 3044 // and the global is small enough, we can emit it inline into the constant pool 3045 // to save ourselves an indirection. 3046 // 3047 // This is a win if the constant is only used in one function (so it doesn't 3048 // need to be duplicated) or duplicating the constant wouldn't increase code 3049 // size (implying the constant is no larger than 4 bytes). 3050 const Function *F = DAG.getMachineFunction().getFunction(); 3051 3052 // We rely on this decision to inline being idemopotent and unrelated to the 3053 // use-site. We know that if we inline a variable at one use site, we'll 3054 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3055 // doesn't know about this optimization, so bail out if it's enabled else 3056 // we could decide to inline here (and thus never emit the GV) but require 3057 // the GV from fast-isel generated code. 3058 if (!EnableConstpoolPromotion || 3059 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3060 return SDValue(); 3061 3062 auto *GVar = dyn_cast<GlobalVariable>(GV); 3063 if (!GVar || !GVar->hasInitializer() || 3064 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3065 !GVar->hasLocalLinkage()) 3066 return SDValue(); 3067 3068 // Ensure that we don't try and inline any type that contains pointers. If 3069 // we inline a value that contains relocations, we move the relocations from 3070 // .data to .text which is not ideal. 3071 auto *Init = GVar->getInitializer(); 3072 if (!isSimpleType(Init->getType())) 3073 return SDValue(); 3074 3075 // The constant islands pass can only really deal with alignment requests 3076 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3077 // any type wanting greater alignment requirements than 4 bytes. We also 3078 // can only promote constants that are multiples of 4 bytes in size or 3079 // are paddable to a multiple of 4. Currently we only try and pad constants 3080 // that are strings for simplicity. 3081 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3082 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3083 unsigned Align = GVar->getAlignment(); 3084 unsigned RequiredPadding = 4 - (Size % 4); 3085 bool PaddingPossible = 3086 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3087 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3088 Size == 0) 3089 return SDValue(); 3090 3091 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3092 MachineFunction &MF = DAG.getMachineFunction(); 3093 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3094 3095 // We can't bloat the constant pool too much, else the ConstantIslands pass 3096 // may fail to converge. If we haven't promoted this global yet (it may have 3097 // multiple uses), and promoting it would increase the constant pool size (Sz 3098 // > 4), ensure we have space to do so up to MaxTotal. 3099 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3100 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3101 ConstpoolPromotionMaxTotal) 3102 return SDValue(); 3103 3104 // This is only valid if all users are in a single function OR it has users 3105 // in multiple functions but it no larger than a pointer. We also check if 3106 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3107 // address taken. 3108 if (!allUsersAreInFunction(GVar, F) && 3109 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3110 return SDValue(); 3111 3112 // We're going to inline this global. Pad it out if needed. 3113 if (RequiredPadding != 4) { 3114 StringRef S = CDAInit->getAsString(); 3115 3116 SmallVector<uint8_t,16> V(S.size()); 3117 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3118 while (RequiredPadding--) 3119 V.push_back(0); 3120 Init = ConstantDataArray::get(*DAG.getContext(), V); 3121 } 3122 3123 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3124 SDValue CPAddr = 3125 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3126 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3127 AFI->markGlobalAsPromotedToConstantPool(GVar); 3128 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3129 PaddedSize - 4); 3130 } 3131 ++NumConstpoolPromoted; 3132 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3133 } 3134 3135 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3136 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3137 GV = GA->getBaseObject(); 3138 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3139 isa<Function>(GV); 3140 } 3141 3142 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3143 SelectionDAG &DAG) const { 3144 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3145 default: llvm_unreachable("unknown object format"); 3146 case Triple::COFF: 3147 return LowerGlobalAddressWindows(Op, DAG); 3148 case Triple::ELF: 3149 return LowerGlobalAddressELF(Op, DAG); 3150 case Triple::MachO: 3151 return LowerGlobalAddressDarwin(Op, DAG); 3152 } 3153 } 3154 3155 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3156 SelectionDAG &DAG) const { 3157 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3158 SDLoc dl(Op); 3159 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3160 const TargetMachine &TM = getTargetMachine(); 3161 bool IsRO = isReadOnly(GV); 3162 3163 // promoteToConstantPool only if not generating XO text section 3164 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3165 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3166 return V; 3167 3168 if (isPositionIndependent()) { 3169 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3170 3171 MachineFunction &MF = DAG.getMachineFunction(); 3172 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3173 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3174 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3175 SDLoc dl(Op); 3176 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3177 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 3178 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 3179 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 3180 /*AddCurrentAddress=*/UseGOT_PREL); 3181 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3182 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3183 SDValue Result = DAG.getLoad( 3184 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3185 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3186 SDValue Chain = Result.getValue(1); 3187 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3188 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3189 if (UseGOT_PREL) 3190 Result = 3191 DAG.getLoad(PtrVT, dl, Chain, Result, 3192 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3193 return Result; 3194 } else if (Subtarget->isROPI() && IsRO) { 3195 // PC-relative. 3196 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3197 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3198 return Result; 3199 } else if (Subtarget->isRWPI() && !IsRO) { 3200 // SB-relative. 3201 SDValue RelAddr; 3202 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3203 ++NumMovwMovt; 3204 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3205 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3206 } else { // use literal pool for address constant 3207 ARMConstantPoolValue *CPV = 3208 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3209 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3210 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3211 RelAddr = DAG.getLoad( 3212 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3213 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3214 } 3215 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3216 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3217 return Result; 3218 } 3219 3220 // If we have T2 ops, we can materialize the address directly via movt/movw 3221 // pair. This is always cheaper. 3222 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3223 ++NumMovwMovt; 3224 // FIXME: Once remat is capable of dealing with instructions with register 3225 // operands, expand this into two nodes. 3226 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3227 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3228 } else { 3229 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3230 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3231 return DAG.getLoad( 3232 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3233 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3234 } 3235 } 3236 3237 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3238 SelectionDAG &DAG) const { 3239 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3240 "ROPI/RWPI not currently supported for Darwin"); 3241 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3242 SDLoc dl(Op); 3243 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3244 3245 if (Subtarget->useMovt(DAG.getMachineFunction())) 3246 ++NumMovwMovt; 3247 3248 // FIXME: Once remat is capable of dealing with instructions with register 3249 // operands, expand this into multiple nodes 3250 unsigned Wrapper = 3251 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3252 3253 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3254 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3255 3256 if (Subtarget->isGVIndirectSymbol(GV)) 3257 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3258 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3259 return Result; 3260 } 3261 3262 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3263 SelectionDAG &DAG) const { 3264 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3265 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3266 "Windows on ARM expects to use movw/movt"); 3267 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3268 "ROPI/RWPI not currently supported for Windows"); 3269 3270 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3271 const ARMII::TOF TargetFlags = 3272 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3273 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3274 SDValue Result; 3275 SDLoc DL(Op); 3276 3277 ++NumMovwMovt; 3278 3279 // FIXME: Once remat is capable of dealing with instructions with register 3280 // operands, expand this into two nodes. 3281 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3282 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3283 TargetFlags)); 3284 if (GV->hasDLLImportStorageClass()) 3285 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3286 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3287 return Result; 3288 } 3289 3290 SDValue 3291 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3292 SDLoc dl(Op); 3293 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3294 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3295 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3296 Op.getOperand(1), Val); 3297 } 3298 3299 SDValue 3300 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3301 SDLoc dl(Op); 3302 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3303 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3304 } 3305 3306 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3307 SelectionDAG &DAG) const { 3308 SDLoc dl(Op); 3309 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3310 Op.getOperand(0)); 3311 } 3312 3313 SDValue 3314 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3315 const ARMSubtarget *Subtarget) const { 3316 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3317 SDLoc dl(Op); 3318 switch (IntNo) { 3319 default: return SDValue(); // Don't custom lower most intrinsics. 3320 case Intrinsic::thread_pointer: { 3321 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3322 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3323 } 3324 case Intrinsic::eh_sjlj_lsda: { 3325 MachineFunction &MF = DAG.getMachineFunction(); 3326 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3327 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3328 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3329 SDValue CPAddr; 3330 bool IsPositionIndependent = isPositionIndependent(); 3331 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3332 ARMConstantPoolValue *CPV = 3333 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 3334 ARMCP::CPLSDA, PCAdj); 3335 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3336 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3337 SDValue Result = DAG.getLoad( 3338 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3339 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3340 3341 if (IsPositionIndependent) { 3342 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3343 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3344 } 3345 return Result; 3346 } 3347 case Intrinsic::arm_neon_vabs: 3348 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3349 Op.getOperand(1)); 3350 case Intrinsic::arm_neon_vmulls: 3351 case Intrinsic::arm_neon_vmullu: { 3352 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3353 ? ARMISD::VMULLs : ARMISD::VMULLu; 3354 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3355 Op.getOperand(1), Op.getOperand(2)); 3356 } 3357 case Intrinsic::arm_neon_vminnm: 3358 case Intrinsic::arm_neon_vmaxnm: { 3359 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3360 ? ISD::FMINNUM : ISD::FMAXNUM; 3361 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3362 Op.getOperand(1), Op.getOperand(2)); 3363 } 3364 case Intrinsic::arm_neon_vminu: 3365 case Intrinsic::arm_neon_vmaxu: { 3366 if (Op.getValueType().isFloatingPoint()) 3367 return SDValue(); 3368 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3369 ? ISD::UMIN : ISD::UMAX; 3370 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3371 Op.getOperand(1), Op.getOperand(2)); 3372 } 3373 case Intrinsic::arm_neon_vmins: 3374 case Intrinsic::arm_neon_vmaxs: { 3375 // v{min,max}s is overloaded between signed integers and floats. 3376 if (!Op.getValueType().isFloatingPoint()) { 3377 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3378 ? ISD::SMIN : ISD::SMAX; 3379 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3380 Op.getOperand(1), Op.getOperand(2)); 3381 } 3382 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3383 ? ISD::FMINNAN : ISD::FMAXNAN; 3384 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3385 Op.getOperand(1), Op.getOperand(2)); 3386 } 3387 case Intrinsic::arm_neon_vtbl1: 3388 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3389 Op.getOperand(1), Op.getOperand(2)); 3390 case Intrinsic::arm_neon_vtbl2: 3391 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3392 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3393 } 3394 } 3395 3396 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3397 const ARMSubtarget *Subtarget) { 3398 SDLoc dl(Op); 3399 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3400 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3401 if (SSID == SyncScope::SingleThread) 3402 return Op; 3403 3404 if (!Subtarget->hasDataBarrier()) { 3405 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3406 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3407 // here. 3408 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3409 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3410 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3411 DAG.getConstant(0, dl, MVT::i32)); 3412 } 3413 3414 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3415 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3416 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3417 if (Subtarget->isMClass()) { 3418 // Only a full system barrier exists in the M-class architectures. 3419 Domain = ARM_MB::SY; 3420 } else if (Subtarget->preferISHSTBarriers() && 3421 Ord == AtomicOrdering::Release) { 3422 // Swift happens to implement ISHST barriers in a way that's compatible with 3423 // Release semantics but weaker than ISH so we'd be fools not to use 3424 // it. Beware: other processors probably don't! 3425 Domain = ARM_MB::ISHST; 3426 } 3427 3428 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3429 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3430 DAG.getConstant(Domain, dl, MVT::i32)); 3431 } 3432 3433 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3434 const ARMSubtarget *Subtarget) { 3435 // ARM pre v5TE and Thumb1 does not have preload instructions. 3436 if (!(Subtarget->isThumb2() || 3437 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3438 // Just preserve the chain. 3439 return Op.getOperand(0); 3440 3441 SDLoc dl(Op); 3442 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3443 if (!isRead && 3444 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3445 // ARMv7 with MP extension has PLDW. 3446 return Op.getOperand(0); 3447 3448 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3449 if (Subtarget->isThumb()) { 3450 // Invert the bits. 3451 isRead = ~isRead & 1; 3452 isData = ~isData & 1; 3453 } 3454 3455 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3456 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3457 DAG.getConstant(isData, dl, MVT::i32)); 3458 } 3459 3460 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3461 MachineFunction &MF = DAG.getMachineFunction(); 3462 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3463 3464 // vastart just stores the address of the VarArgsFrameIndex slot into the 3465 // memory location argument. 3466 SDLoc dl(Op); 3467 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3468 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3469 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3470 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3471 MachinePointerInfo(SV)); 3472 } 3473 3474 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3475 CCValAssign &NextVA, 3476 SDValue &Root, 3477 SelectionDAG &DAG, 3478 const SDLoc &dl) const { 3479 MachineFunction &MF = DAG.getMachineFunction(); 3480 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3481 3482 const TargetRegisterClass *RC; 3483 if (AFI->isThumb1OnlyFunction()) 3484 RC = &ARM::tGPRRegClass; 3485 else 3486 RC = &ARM::GPRRegClass; 3487 3488 // Transform the arguments stored in physical registers into virtual ones. 3489 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3490 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3491 3492 SDValue ArgValue2; 3493 if (NextVA.isMemLoc()) { 3494 MachineFrameInfo &MFI = MF.getFrameInfo(); 3495 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3496 3497 // Create load node to retrieve arguments from the stack. 3498 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3499 ArgValue2 = DAG.getLoad( 3500 MVT::i32, dl, Root, FIN, 3501 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3502 } else { 3503 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3504 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3505 } 3506 if (!Subtarget->isLittle()) 3507 std::swap (ArgValue, ArgValue2); 3508 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3509 } 3510 3511 // The remaining GPRs hold either the beginning of variable-argument 3512 // data, or the beginning of an aggregate passed by value (usually 3513 // byval). Either way, we allocate stack slots adjacent to the data 3514 // provided by our caller, and store the unallocated registers there. 3515 // If this is a variadic function, the va_list pointer will begin with 3516 // these values; otherwise, this reassembles a (byval) structure that 3517 // was split between registers and memory. 3518 // Return: The frame index registers were stored into. 3519 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3520 const SDLoc &dl, SDValue &Chain, 3521 const Value *OrigArg, 3522 unsigned InRegsParamRecordIdx, 3523 int ArgOffset, unsigned ArgSize) const { 3524 // Currently, two use-cases possible: 3525 // Case #1. Non-var-args function, and we meet first byval parameter. 3526 // Setup first unallocated register as first byval register; 3527 // eat all remained registers 3528 // (these two actions are performed by HandleByVal method). 3529 // Then, here, we initialize stack frame with 3530 // "store-reg" instructions. 3531 // Case #2. Var-args function, that doesn't contain byval parameters. 3532 // The same: eat all remained unallocated registers, 3533 // initialize stack frame. 3534 3535 MachineFunction &MF = DAG.getMachineFunction(); 3536 MachineFrameInfo &MFI = MF.getFrameInfo(); 3537 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3538 unsigned RBegin, REnd; 3539 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3540 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3541 } else { 3542 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3543 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3544 REnd = ARM::R4; 3545 } 3546 3547 if (REnd != RBegin) 3548 ArgOffset = -4 * (ARM::R4 - RBegin); 3549 3550 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3551 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3552 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3553 3554 SmallVector<SDValue, 4> MemOps; 3555 const TargetRegisterClass *RC = 3556 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3557 3558 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3559 unsigned VReg = MF.addLiveIn(Reg, RC); 3560 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3561 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3562 MachinePointerInfo(OrigArg, 4 * i)); 3563 MemOps.push_back(Store); 3564 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3565 } 3566 3567 if (!MemOps.empty()) 3568 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3569 return FrameIndex; 3570 } 3571 3572 // Setup stack frame, the va_list pointer will start from. 3573 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3574 const SDLoc &dl, SDValue &Chain, 3575 unsigned ArgOffset, 3576 unsigned TotalArgRegsSaveSize, 3577 bool ForceMutable) const { 3578 MachineFunction &MF = DAG.getMachineFunction(); 3579 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3580 3581 // Try to store any remaining integer argument regs 3582 // to their spots on the stack so that they may be loaded by dereferencing 3583 // the result of va_next. 3584 // If there is no regs to be stored, just point address after last 3585 // argument passed via stack. 3586 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3587 CCInfo.getInRegsParamsCount(), 3588 CCInfo.getNextStackOffset(), 4); 3589 AFI->setVarArgsFrameIndex(FrameIndex); 3590 } 3591 3592 SDValue ARMTargetLowering::LowerFormalArguments( 3593 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3594 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3595 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3596 MachineFunction &MF = DAG.getMachineFunction(); 3597 MachineFrameInfo &MFI = MF.getFrameInfo(); 3598 3599 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3600 3601 // Assign locations to all of the incoming arguments. 3602 SmallVector<CCValAssign, 16> ArgLocs; 3603 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3604 *DAG.getContext()); 3605 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3606 3607 SmallVector<SDValue, 16> ArgValues; 3608 SDValue ArgValue; 3609 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3610 unsigned CurArgIdx = 0; 3611 3612 // Initially ArgRegsSaveSize is zero. 3613 // Then we increase this value each time we meet byval parameter. 3614 // We also increase this value in case of varargs function. 3615 AFI->setArgRegsSaveSize(0); 3616 3617 // Calculate the amount of stack space that we need to allocate to store 3618 // byval and variadic arguments that are passed in registers. 3619 // We need to know this before we allocate the first byval or variadic 3620 // argument, as they will be allocated a stack slot below the CFA (Canonical 3621 // Frame Address, the stack pointer at entry to the function). 3622 unsigned ArgRegBegin = ARM::R4; 3623 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3624 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3625 break; 3626 3627 CCValAssign &VA = ArgLocs[i]; 3628 unsigned Index = VA.getValNo(); 3629 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3630 if (!Flags.isByVal()) 3631 continue; 3632 3633 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3634 unsigned RBegin, REnd; 3635 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3636 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3637 3638 CCInfo.nextInRegsParam(); 3639 } 3640 CCInfo.rewindByValRegsInfo(); 3641 3642 int lastInsIndex = -1; 3643 if (isVarArg && MFI.hasVAStart()) { 3644 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3645 if (RegIdx != array_lengthof(GPRArgRegs)) 3646 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3647 } 3648 3649 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3650 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3651 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3652 3653 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3654 CCValAssign &VA = ArgLocs[i]; 3655 if (Ins[VA.getValNo()].isOrigArg()) { 3656 std::advance(CurOrigArg, 3657 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3658 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3659 } 3660 // Arguments stored in registers. 3661 if (VA.isRegLoc()) { 3662 EVT RegVT = VA.getLocVT(); 3663 3664 if (VA.needsCustom()) { 3665 // f64 and vector types are split up into multiple registers or 3666 // combinations of registers and stack slots. 3667 if (VA.getLocVT() == MVT::v2f64) { 3668 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3669 Chain, DAG, dl); 3670 VA = ArgLocs[++i]; // skip ahead to next loc 3671 SDValue ArgValue2; 3672 if (VA.isMemLoc()) { 3673 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3674 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3675 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3676 MachinePointerInfo::getFixedStack( 3677 DAG.getMachineFunction(), FI)); 3678 } else { 3679 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3680 Chain, DAG, dl); 3681 } 3682 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3683 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3684 ArgValue, ArgValue1, 3685 DAG.getIntPtrConstant(0, dl)); 3686 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3687 ArgValue, ArgValue2, 3688 DAG.getIntPtrConstant(1, dl)); 3689 } else 3690 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3691 } else { 3692 const TargetRegisterClass *RC; 3693 3694 if (RegVT == MVT::f32) 3695 RC = &ARM::SPRRegClass; 3696 else if (RegVT == MVT::f64) 3697 RC = &ARM::DPRRegClass; 3698 else if (RegVT == MVT::v2f64) 3699 RC = &ARM::QPRRegClass; 3700 else if (RegVT == MVT::i32) 3701 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3702 : &ARM::GPRRegClass; 3703 else 3704 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3705 3706 // Transform the arguments in physical registers into virtual ones. 3707 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3708 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3709 } 3710 3711 // If this is an 8 or 16-bit value, it is really passed promoted 3712 // to 32 bits. Insert an assert[sz]ext to capture this, then 3713 // truncate to the right size. 3714 switch (VA.getLocInfo()) { 3715 default: llvm_unreachable("Unknown loc info!"); 3716 case CCValAssign::Full: break; 3717 case CCValAssign::BCvt: 3718 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3719 break; 3720 case CCValAssign::SExt: 3721 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3722 DAG.getValueType(VA.getValVT())); 3723 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3724 break; 3725 case CCValAssign::ZExt: 3726 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3727 DAG.getValueType(VA.getValVT())); 3728 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3729 break; 3730 } 3731 3732 InVals.push_back(ArgValue); 3733 } else { // VA.isRegLoc() 3734 // sanity check 3735 assert(VA.isMemLoc()); 3736 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3737 3738 int index = VA.getValNo(); 3739 3740 // Some Ins[] entries become multiple ArgLoc[] entries. 3741 // Process them only once. 3742 if (index != lastInsIndex) 3743 { 3744 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3745 // FIXME: For now, all byval parameter objects are marked mutable. 3746 // This can be changed with more analysis. 3747 // In case of tail call optimization mark all arguments mutable. 3748 // Since they could be overwritten by lowering of arguments in case of 3749 // a tail call. 3750 if (Flags.isByVal()) { 3751 assert(Ins[index].isOrigArg() && 3752 "Byval arguments cannot be implicit"); 3753 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3754 3755 int FrameIndex = StoreByValRegs( 3756 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3757 VA.getLocMemOffset(), Flags.getByValSize()); 3758 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3759 CCInfo.nextInRegsParam(); 3760 } else { 3761 unsigned FIOffset = VA.getLocMemOffset(); 3762 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3763 FIOffset, true); 3764 3765 // Create load nodes to retrieve arguments from the stack. 3766 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3767 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3768 MachinePointerInfo::getFixedStack( 3769 DAG.getMachineFunction(), FI))); 3770 } 3771 lastInsIndex = index; 3772 } 3773 } 3774 } 3775 3776 // varargs 3777 if (isVarArg && MFI.hasVAStart()) 3778 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3779 CCInfo.getNextStackOffset(), 3780 TotalArgRegsSaveSize); 3781 3782 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3783 3784 return Chain; 3785 } 3786 3787 /// isFloatingPointZero - Return true if this is +0.0. 3788 static bool isFloatingPointZero(SDValue Op) { 3789 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3790 return CFP->getValueAPF().isPosZero(); 3791 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3792 // Maybe this has already been legalized into the constant pool? 3793 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3794 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3795 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3796 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3797 return CFP->getValueAPF().isPosZero(); 3798 } 3799 } else if (Op->getOpcode() == ISD::BITCAST && 3800 Op->getValueType(0) == MVT::f64) { 3801 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3802 // created by LowerConstantFP(). 3803 SDValue BitcastOp = Op->getOperand(0); 3804 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3805 isNullConstant(BitcastOp->getOperand(0))) 3806 return true; 3807 } 3808 return false; 3809 } 3810 3811 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3812 /// the given operands. 3813 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3814 SDValue &ARMcc, SelectionDAG &DAG, 3815 const SDLoc &dl) const { 3816 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3817 unsigned C = RHSC->getZExtValue(); 3818 if (!isLegalICmpImmediate(C)) { 3819 // Constant does not fit, try adjusting it by one? 3820 switch (CC) { 3821 default: break; 3822 case ISD::SETLT: 3823 case ISD::SETGE: 3824 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3825 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3826 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3827 } 3828 break; 3829 case ISD::SETULT: 3830 case ISD::SETUGE: 3831 if (C != 0 && isLegalICmpImmediate(C-1)) { 3832 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3833 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3834 } 3835 break; 3836 case ISD::SETLE: 3837 case ISD::SETGT: 3838 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3839 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3840 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3841 } 3842 break; 3843 case ISD::SETULE: 3844 case ISD::SETUGT: 3845 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3846 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3847 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3848 } 3849 break; 3850 } 3851 } 3852 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3853 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3854 // In ARM and Thumb-2, the compare instructions can shift their second 3855 // operand. 3856 CC = ISD::getSetCCSwappedOperands(CC); 3857 std::swap(LHS, RHS); 3858 } 3859 3860 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3861 ARMISD::NodeType CompareType; 3862 switch (CondCode) { 3863 default: 3864 CompareType = ARMISD::CMP; 3865 break; 3866 case ARMCC::EQ: 3867 case ARMCC::NE: 3868 // Uses only Z Flag 3869 CompareType = ARMISD::CMPZ; 3870 break; 3871 } 3872 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3873 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3874 } 3875 3876 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3877 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3878 SelectionDAG &DAG, const SDLoc &dl, 3879 bool InvalidOnQNaN) const { 3880 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3881 SDValue Cmp; 3882 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3883 if (!isFloatingPointZero(RHS)) 3884 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3885 else 3886 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3887 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3888 } 3889 3890 /// duplicateCmp - Glue values can have only one use, so this function 3891 /// duplicates a comparison node. 3892 SDValue 3893 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3894 unsigned Opc = Cmp.getOpcode(); 3895 SDLoc DL(Cmp); 3896 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3897 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3898 3899 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3900 Cmp = Cmp.getOperand(0); 3901 Opc = Cmp.getOpcode(); 3902 if (Opc == ARMISD::CMPFP) 3903 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3904 Cmp.getOperand(1), Cmp.getOperand(2)); 3905 else { 3906 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3907 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3908 Cmp.getOperand(1)); 3909 } 3910 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3911 } 3912 3913 std::pair<SDValue, SDValue> 3914 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3915 SDValue &ARMcc) const { 3916 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3917 3918 SDValue Value, OverflowCmp; 3919 SDValue LHS = Op.getOperand(0); 3920 SDValue RHS = Op.getOperand(1); 3921 SDLoc dl(Op); 3922 3923 // FIXME: We are currently always generating CMPs because we don't support 3924 // generating CMN through the backend. This is not as good as the natural 3925 // CMP case because it causes a register dependency and cannot be folded 3926 // later. 3927 3928 switch (Op.getOpcode()) { 3929 default: 3930 llvm_unreachable("Unknown overflow instruction!"); 3931 case ISD::SADDO: 3932 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3933 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3934 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3935 break; 3936 case ISD::UADDO: 3937 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3938 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3939 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3940 break; 3941 case ISD::SSUBO: 3942 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3943 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3944 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3945 break; 3946 case ISD::USUBO: 3947 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3948 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3949 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3950 break; 3951 } // switch (...) 3952 3953 return std::make_pair(Value, OverflowCmp); 3954 } 3955 3956 SDValue 3957 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 3958 // Let legalize expand this if it isn't a legal type yet. 3959 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3960 return SDValue(); 3961 3962 SDValue Value, OverflowCmp; 3963 SDValue ARMcc; 3964 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3965 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3966 SDLoc dl(Op); 3967 // We use 0 and 1 as false and true values. 3968 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3969 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3970 EVT VT = Op.getValueType(); 3971 3972 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3973 ARMcc, CCR, OverflowCmp); 3974 3975 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3976 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3977 } 3978 3979 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 3980 SelectionDAG &DAG) { 3981 SDLoc DL(BoolCarry); 3982 EVT CarryVT = BoolCarry.getValueType(); 3983 3984 APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits()); 3985 // This converts the boolean value carry into the carry flag by doing 3986 // ARMISD::ADDC Carry, ~0 3987 return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32), 3988 BoolCarry, DAG.getConstant(NegOne, DL, CarryVT)); 3989 } 3990 3991 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 3992 SelectionDAG &DAG) { 3993 SDLoc DL(Flags); 3994 3995 // Now convert the carry flag into a boolean carry. We do this 3996 // using ARMISD:ADDE 0, 0, Carry 3997 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 3998 DAG.getConstant(0, DL, MVT::i32), 3999 DAG.getConstant(0, DL, MVT::i32), Flags); 4000 } 4001 4002 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4003 SelectionDAG &DAG) const { 4004 // Let legalize expand this if it isn't a legal type yet. 4005 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4006 return SDValue(); 4007 4008 SDValue LHS = Op.getOperand(0); 4009 SDValue RHS = Op.getOperand(1); 4010 SDLoc dl(Op); 4011 4012 EVT VT = Op.getValueType(); 4013 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4014 SDValue Value; 4015 SDValue Overflow; 4016 switch (Op.getOpcode()) { 4017 default: 4018 llvm_unreachable("Unknown overflow instruction!"); 4019 case ISD::UADDO: 4020 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4021 // Convert the carry flag into a boolean value. 4022 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4023 break; 4024 case ISD::USUBO: 4025 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4026 // Convert the carry flag into a boolean value. 4027 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4028 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4029 // value. So compute 1 - C. 4030 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4031 DAG.getConstant(1, dl, MVT::i32), Overflow); 4032 break; 4033 } 4034 4035 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4036 } 4037 4038 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4039 SDValue Cond = Op.getOperand(0); 4040 SDValue SelectTrue = Op.getOperand(1); 4041 SDValue SelectFalse = Op.getOperand(2); 4042 SDLoc dl(Op); 4043 unsigned Opc = Cond.getOpcode(); 4044 4045 if (Cond.getResNo() == 1 && 4046 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4047 Opc == ISD::USUBO)) { 4048 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4049 return SDValue(); 4050 4051 SDValue Value, OverflowCmp; 4052 SDValue ARMcc; 4053 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4054 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4055 EVT VT = Op.getValueType(); 4056 4057 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4058 OverflowCmp, DAG); 4059 } 4060 4061 // Convert: 4062 // 4063 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4064 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4065 // 4066 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4067 const ConstantSDNode *CMOVTrue = 4068 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4069 const ConstantSDNode *CMOVFalse = 4070 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4071 4072 if (CMOVTrue && CMOVFalse) { 4073 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4074 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4075 4076 SDValue True; 4077 SDValue False; 4078 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4079 True = SelectTrue; 4080 False = SelectFalse; 4081 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4082 True = SelectFalse; 4083 False = SelectTrue; 4084 } 4085 4086 if (True.getNode() && False.getNode()) { 4087 EVT VT = Op.getValueType(); 4088 SDValue ARMcc = Cond.getOperand(2); 4089 SDValue CCR = Cond.getOperand(3); 4090 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4091 assert(True.getValueType() == VT); 4092 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4093 } 4094 } 4095 } 4096 4097 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4098 // undefined bits before doing a full-word comparison with zero. 4099 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4100 DAG.getConstant(1, dl, Cond.getValueType())); 4101 4102 return DAG.getSelectCC(dl, Cond, 4103 DAG.getConstant(0, dl, Cond.getValueType()), 4104 SelectTrue, SelectFalse, ISD::SETNE); 4105 } 4106 4107 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4108 bool &swpCmpOps, bool &swpVselOps) { 4109 // Start by selecting the GE condition code for opcodes that return true for 4110 // 'equality' 4111 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4112 CC == ISD::SETULE) 4113 CondCode = ARMCC::GE; 4114 4115 // and GT for opcodes that return false for 'equality'. 4116 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4117 CC == ISD::SETULT) 4118 CondCode = ARMCC::GT; 4119 4120 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4121 // to swap the compare operands. 4122 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4123 CC == ISD::SETULT) 4124 swpCmpOps = true; 4125 4126 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4127 // If we have an unordered opcode, we need to swap the operands to the VSEL 4128 // instruction (effectively negating the condition). 4129 // 4130 // This also has the effect of swapping which one of 'less' or 'greater' 4131 // returns true, so we also swap the compare operands. It also switches 4132 // whether we return true for 'equality', so we compensate by picking the 4133 // opposite condition code to our original choice. 4134 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4135 CC == ISD::SETUGT) { 4136 swpCmpOps = !swpCmpOps; 4137 swpVselOps = !swpVselOps; 4138 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4139 } 4140 4141 // 'ordered' is 'anything but unordered', so use the VS condition code and 4142 // swap the VSEL operands. 4143 if (CC == ISD::SETO) { 4144 CondCode = ARMCC::VS; 4145 swpVselOps = true; 4146 } 4147 4148 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4149 // code and swap the VSEL operands. 4150 if (CC == ISD::SETUNE) { 4151 CondCode = ARMCC::EQ; 4152 swpVselOps = true; 4153 } 4154 } 4155 4156 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4157 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4158 SDValue Cmp, SelectionDAG &DAG) const { 4159 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4160 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4161 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4162 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4163 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4164 4165 SDValue TrueLow = TrueVal.getValue(0); 4166 SDValue TrueHigh = TrueVal.getValue(1); 4167 SDValue FalseLow = FalseVal.getValue(0); 4168 SDValue FalseHigh = FalseVal.getValue(1); 4169 4170 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4171 ARMcc, CCR, Cmp); 4172 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4173 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4174 4175 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4176 } else { 4177 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4178 Cmp); 4179 } 4180 } 4181 4182 static bool isGTorGE(ISD::CondCode CC) { 4183 return CC == ISD::SETGT || CC == ISD::SETGE; 4184 } 4185 4186 static bool isLTorLE(ISD::CondCode CC) { 4187 return CC == ISD::SETLT || CC == ISD::SETLE; 4188 } 4189 4190 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4191 // All of these conditions (and their <= and >= counterparts) will do: 4192 // x < k ? k : x 4193 // x > k ? x : k 4194 // k < x ? x : k 4195 // k > x ? k : x 4196 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4197 const SDValue TrueVal, const SDValue FalseVal, 4198 const ISD::CondCode CC, const SDValue K) { 4199 return (isGTorGE(CC) && 4200 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4201 (isLTorLE(CC) && 4202 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4203 } 4204 4205 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4206 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4207 const SDValue TrueVal, const SDValue FalseVal, 4208 const ISD::CondCode CC, const SDValue K) { 4209 return (isGTorGE(CC) && 4210 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4211 (isLTorLE(CC) && 4212 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4213 } 4214 4215 // Check if two chained conditionals could be converted into SSAT. 4216 // 4217 // SSAT can replace a set of two conditional selectors that bound a number to an 4218 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4219 // 4220 // x < -k ? -k : (x > k ? k : x) 4221 // x < -k ? -k : (x < k ? x : k) 4222 // x > -k ? (x > k ? k : x) : -k 4223 // x < k ? (x < -k ? -k : x) : k 4224 // etc. 4225 // 4226 // It returns true if the conversion can be done, false otherwise. 4227 // Additionally, the variable is returned in parameter V and the constant in K. 4228 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4229 uint64_t &K) { 4230 SDValue LHS1 = Op.getOperand(0); 4231 SDValue RHS1 = Op.getOperand(1); 4232 SDValue TrueVal1 = Op.getOperand(2); 4233 SDValue FalseVal1 = Op.getOperand(3); 4234 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4235 4236 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4237 if (Op2.getOpcode() != ISD::SELECT_CC) 4238 return false; 4239 4240 SDValue LHS2 = Op2.getOperand(0); 4241 SDValue RHS2 = Op2.getOperand(1); 4242 SDValue TrueVal2 = Op2.getOperand(2); 4243 SDValue FalseVal2 = Op2.getOperand(3); 4244 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4245 4246 // Find out which are the constants and which are the variables 4247 // in each conditional 4248 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4249 ? &RHS1 4250 : nullptr; 4251 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4252 ? &RHS2 4253 : nullptr; 4254 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4255 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4256 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4257 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4258 4259 // We must detect cases where the original operations worked with 16- or 4260 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4261 // must work with sign-extended values but the select operations return 4262 // the original non-extended value. 4263 SDValue V2TmpReg = V2Tmp; 4264 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4265 V2TmpReg = V2Tmp->getOperand(0); 4266 4267 // Check that the registers and the constants have the correct values 4268 // in both conditionals 4269 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4270 V2TmpReg != V2) 4271 return false; 4272 4273 // Figure out which conditional is saturating the lower/upper bound. 4274 const SDValue *LowerCheckOp = 4275 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4276 ? &Op 4277 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4278 ? &Op2 4279 : nullptr; 4280 const SDValue *UpperCheckOp = 4281 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4282 ? &Op 4283 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4284 ? &Op2 4285 : nullptr; 4286 4287 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4288 return false; 4289 4290 // Check that the constant in the lower-bound check is 4291 // the opposite of the constant in the upper-bound check 4292 // in 1's complement. 4293 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4294 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4295 int64_t PosVal = std::max(Val1, Val2); 4296 4297 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4298 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4299 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 4300 4301 V = V2; 4302 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4303 return true; 4304 } 4305 4306 return false; 4307 } 4308 4309 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4310 EVT VT = Op.getValueType(); 4311 SDLoc dl(Op); 4312 4313 // Try to convert two saturating conditional selects into a single SSAT 4314 SDValue SatValue; 4315 uint64_t SatConstant; 4316 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4317 isSaturatingConditional(Op, SatValue, SatConstant)) 4318 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4319 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4320 4321 SDValue LHS = Op.getOperand(0); 4322 SDValue RHS = Op.getOperand(1); 4323 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4324 SDValue TrueVal = Op.getOperand(2); 4325 SDValue FalseVal = Op.getOperand(3); 4326 4327 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4328 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4329 dl); 4330 4331 // If softenSetCCOperands only returned one value, we should compare it to 4332 // zero. 4333 if (!RHS.getNode()) { 4334 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4335 CC = ISD::SETNE; 4336 } 4337 } 4338 4339 if (LHS.getValueType() == MVT::i32) { 4340 // Try to generate VSEL on ARMv8. 4341 // The VSEL instruction can't use all the usual ARM condition 4342 // codes: it only has two bits to select the condition code, so it's 4343 // constrained to use only GE, GT, VS and EQ. 4344 // 4345 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4346 // swap the operands of the previous compare instruction (effectively 4347 // inverting the compare condition, swapping 'less' and 'greater') and 4348 // sometimes need to swap the operands to the VSEL (which inverts the 4349 // condition in the sense of firing whenever the previous condition didn't) 4350 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4351 TrueVal.getValueType() == MVT::f64)) { 4352 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4353 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4354 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4355 CC = ISD::getSetCCInverse(CC, true); 4356 std::swap(TrueVal, FalseVal); 4357 } 4358 } 4359 4360 SDValue ARMcc; 4361 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4362 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4363 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4364 } 4365 4366 ARMCC::CondCodes CondCode, CondCode2; 4367 bool InvalidOnQNaN; 4368 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4369 4370 // Try to generate VMAXNM/VMINNM on ARMv8. 4371 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4372 TrueVal.getValueType() == MVT::f64)) { 4373 bool swpCmpOps = false; 4374 bool swpVselOps = false; 4375 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4376 4377 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4378 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4379 if (swpCmpOps) 4380 std::swap(LHS, RHS); 4381 if (swpVselOps) 4382 std::swap(TrueVal, FalseVal); 4383 } 4384 } 4385 4386 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4387 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4388 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4389 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4390 if (CondCode2 != ARMCC::AL) { 4391 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4392 // FIXME: Needs another CMP because flag can have but one use. 4393 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4394 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4395 } 4396 return Result; 4397 } 4398 4399 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4400 /// to morph to an integer compare sequence. 4401 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4402 const ARMSubtarget *Subtarget) { 4403 SDNode *N = Op.getNode(); 4404 if (!N->hasOneUse()) 4405 // Otherwise it requires moving the value from fp to integer registers. 4406 return false; 4407 if (!N->getNumValues()) 4408 return false; 4409 EVT VT = Op.getValueType(); 4410 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4411 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4412 // vmrs are very slow, e.g. cortex-a8. 4413 return false; 4414 4415 if (isFloatingPointZero(Op)) { 4416 SeenZero = true; 4417 return true; 4418 } 4419 return ISD::isNormalLoad(N); 4420 } 4421 4422 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4423 if (isFloatingPointZero(Op)) 4424 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4425 4426 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4427 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4428 Ld->getPointerInfo(), Ld->getAlignment(), 4429 Ld->getMemOperand()->getFlags()); 4430 4431 llvm_unreachable("Unknown VFP cmp argument!"); 4432 } 4433 4434 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4435 SDValue &RetVal1, SDValue &RetVal2) { 4436 SDLoc dl(Op); 4437 4438 if (isFloatingPointZero(Op)) { 4439 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4440 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4441 return; 4442 } 4443 4444 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4445 SDValue Ptr = Ld->getBasePtr(); 4446 RetVal1 = 4447 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4448 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4449 4450 EVT PtrType = Ptr.getValueType(); 4451 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4452 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4453 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4454 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4455 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4456 Ld->getMemOperand()->getFlags()); 4457 return; 4458 } 4459 4460 llvm_unreachable("Unknown VFP cmp argument!"); 4461 } 4462 4463 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4464 /// f32 and even f64 comparisons to integer ones. 4465 SDValue 4466 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4467 SDValue Chain = Op.getOperand(0); 4468 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4469 SDValue LHS = Op.getOperand(2); 4470 SDValue RHS = Op.getOperand(3); 4471 SDValue Dest = Op.getOperand(4); 4472 SDLoc dl(Op); 4473 4474 bool LHSSeenZero = false; 4475 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4476 bool RHSSeenZero = false; 4477 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4478 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4479 // If unsafe fp math optimization is enabled and there are no other uses of 4480 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4481 // to an integer comparison. 4482 if (CC == ISD::SETOEQ) 4483 CC = ISD::SETEQ; 4484 else if (CC == ISD::SETUNE) 4485 CC = ISD::SETNE; 4486 4487 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4488 SDValue ARMcc; 4489 if (LHS.getValueType() == MVT::f32) { 4490 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4491 bitcastf32Toi32(LHS, DAG), Mask); 4492 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4493 bitcastf32Toi32(RHS, DAG), Mask); 4494 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4495 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4496 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4497 Chain, Dest, ARMcc, CCR, Cmp); 4498 } 4499 4500 SDValue LHS1, LHS2; 4501 SDValue RHS1, RHS2; 4502 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4503 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4504 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4505 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4506 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4507 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4508 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4509 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4510 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4511 } 4512 4513 return SDValue(); 4514 } 4515 4516 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4517 SDValue Chain = Op.getOperand(0); 4518 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4519 SDValue LHS = Op.getOperand(2); 4520 SDValue RHS = Op.getOperand(3); 4521 SDValue Dest = Op.getOperand(4); 4522 SDLoc dl(Op); 4523 4524 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4525 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4526 dl); 4527 4528 // If softenSetCCOperands only returned one value, we should compare it to 4529 // zero. 4530 if (!RHS.getNode()) { 4531 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4532 CC = ISD::SETNE; 4533 } 4534 } 4535 4536 if (LHS.getValueType() == MVT::i32) { 4537 SDValue ARMcc; 4538 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4539 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4540 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4541 Chain, Dest, ARMcc, CCR, Cmp); 4542 } 4543 4544 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4545 4546 if (getTargetMachine().Options.UnsafeFPMath && 4547 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4548 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4549 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4550 return Result; 4551 } 4552 4553 ARMCC::CondCodes CondCode, CondCode2; 4554 bool InvalidOnQNaN; 4555 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4556 4557 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4558 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4559 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4560 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4561 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4562 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4563 if (CondCode2 != ARMCC::AL) { 4564 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4565 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4566 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4567 } 4568 return Res; 4569 } 4570 4571 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4572 SDValue Chain = Op.getOperand(0); 4573 SDValue Table = Op.getOperand(1); 4574 SDValue Index = Op.getOperand(2); 4575 SDLoc dl(Op); 4576 4577 EVT PTy = getPointerTy(DAG.getDataLayout()); 4578 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4579 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4580 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4581 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4582 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4583 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4584 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4585 // which does another jump to the destination. This also makes it easier 4586 // to translate it to TBB / TBH later (Thumb2 only). 4587 // FIXME: This might not work if the function is extremely large. 4588 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4589 Addr, Op.getOperand(2), JTI); 4590 } 4591 if (isPositionIndependent() || Subtarget->isROPI()) { 4592 Addr = 4593 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4594 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4595 Chain = Addr.getValue(1); 4596 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4597 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4598 } else { 4599 Addr = 4600 DAG.getLoad(PTy, dl, Chain, Addr, 4601 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4602 Chain = Addr.getValue(1); 4603 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4604 } 4605 } 4606 4607 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4608 EVT VT = Op.getValueType(); 4609 SDLoc dl(Op); 4610 4611 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4612 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4613 return Op; 4614 return DAG.UnrollVectorOp(Op.getNode()); 4615 } 4616 4617 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4618 "Invalid type for custom lowering!"); 4619 if (VT != MVT::v4i16) 4620 return DAG.UnrollVectorOp(Op.getNode()); 4621 4622 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4623 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4624 } 4625 4626 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4627 EVT VT = Op.getValueType(); 4628 if (VT.isVector()) 4629 return LowerVectorFP_TO_INT(Op, DAG); 4630 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4631 RTLIB::Libcall LC; 4632 if (Op.getOpcode() == ISD::FP_TO_SINT) 4633 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4634 Op.getValueType()); 4635 else 4636 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4637 Op.getValueType()); 4638 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4639 /*isSigned*/ false, SDLoc(Op)).first; 4640 } 4641 4642 return Op; 4643 } 4644 4645 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4646 EVT VT = Op.getValueType(); 4647 SDLoc dl(Op); 4648 4649 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4650 if (VT.getVectorElementType() == MVT::f32) 4651 return Op; 4652 return DAG.UnrollVectorOp(Op.getNode()); 4653 } 4654 4655 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4656 "Invalid type for custom lowering!"); 4657 if (VT != MVT::v4f32) 4658 return DAG.UnrollVectorOp(Op.getNode()); 4659 4660 unsigned CastOpc; 4661 unsigned Opc; 4662 switch (Op.getOpcode()) { 4663 default: llvm_unreachable("Invalid opcode!"); 4664 case ISD::SINT_TO_FP: 4665 CastOpc = ISD::SIGN_EXTEND; 4666 Opc = ISD::SINT_TO_FP; 4667 break; 4668 case ISD::UINT_TO_FP: 4669 CastOpc = ISD::ZERO_EXTEND; 4670 Opc = ISD::UINT_TO_FP; 4671 break; 4672 } 4673 4674 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4675 return DAG.getNode(Opc, dl, VT, Op); 4676 } 4677 4678 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4679 EVT VT = Op.getValueType(); 4680 if (VT.isVector()) 4681 return LowerVectorINT_TO_FP(Op, DAG); 4682 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4683 RTLIB::Libcall LC; 4684 if (Op.getOpcode() == ISD::SINT_TO_FP) 4685 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4686 Op.getValueType()); 4687 else 4688 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4689 Op.getValueType()); 4690 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4691 /*isSigned*/ false, SDLoc(Op)).first; 4692 } 4693 4694 return Op; 4695 } 4696 4697 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4698 // Implement fcopysign with a fabs and a conditional fneg. 4699 SDValue Tmp0 = Op.getOperand(0); 4700 SDValue Tmp1 = Op.getOperand(1); 4701 SDLoc dl(Op); 4702 EVT VT = Op.getValueType(); 4703 EVT SrcVT = Tmp1.getValueType(); 4704 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4705 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4706 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4707 4708 if (UseNEON) { 4709 // Use VBSL to copy the sign bit. 4710 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4711 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4712 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4713 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4714 if (VT == MVT::f64) 4715 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4716 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4717 DAG.getConstant(32, dl, MVT::i32)); 4718 else /*if (VT == MVT::f32)*/ 4719 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4720 if (SrcVT == MVT::f32) { 4721 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4722 if (VT == MVT::f64) 4723 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4724 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4725 DAG.getConstant(32, dl, MVT::i32)); 4726 } else if (VT == MVT::f32) 4727 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4728 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4729 DAG.getConstant(32, dl, MVT::i32)); 4730 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4731 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4732 4733 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4734 dl, MVT::i32); 4735 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4736 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4737 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4738 4739 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4740 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4741 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4742 if (VT == MVT::f32) { 4743 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4744 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4745 DAG.getConstant(0, dl, MVT::i32)); 4746 } else { 4747 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4748 } 4749 4750 return Res; 4751 } 4752 4753 // Bitcast operand 1 to i32. 4754 if (SrcVT == MVT::f64) 4755 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4756 Tmp1).getValue(1); 4757 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4758 4759 // Or in the signbit with integer operations. 4760 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4761 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4762 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4763 if (VT == MVT::f32) { 4764 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4765 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4766 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4767 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4768 } 4769 4770 // f64: Or the high part with signbit and then combine two parts. 4771 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4772 Tmp0); 4773 SDValue Lo = Tmp0.getValue(0); 4774 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4775 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4776 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4777 } 4778 4779 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4780 MachineFunction &MF = DAG.getMachineFunction(); 4781 MachineFrameInfo &MFI = MF.getFrameInfo(); 4782 MFI.setReturnAddressIsTaken(true); 4783 4784 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4785 return SDValue(); 4786 4787 EVT VT = Op.getValueType(); 4788 SDLoc dl(Op); 4789 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4790 if (Depth) { 4791 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4792 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4793 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4794 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4795 MachinePointerInfo()); 4796 } 4797 4798 // Return LR, which contains the return address. Mark it an implicit live-in. 4799 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4800 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4801 } 4802 4803 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4804 const ARMBaseRegisterInfo &ARI = 4805 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4806 MachineFunction &MF = DAG.getMachineFunction(); 4807 MachineFrameInfo &MFI = MF.getFrameInfo(); 4808 MFI.setFrameAddressIsTaken(true); 4809 4810 EVT VT = Op.getValueType(); 4811 SDLoc dl(Op); // FIXME probably not meaningful 4812 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4813 unsigned FrameReg = ARI.getFrameRegister(MF); 4814 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4815 while (Depth--) 4816 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4817 MachinePointerInfo()); 4818 return FrameAddr; 4819 } 4820 4821 // FIXME? Maybe this could be a TableGen attribute on some registers and 4822 // this table could be generated automatically from RegInfo. 4823 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4824 SelectionDAG &DAG) const { 4825 unsigned Reg = StringSwitch<unsigned>(RegName) 4826 .Case("sp", ARM::SP) 4827 .Default(0); 4828 if (Reg) 4829 return Reg; 4830 report_fatal_error(Twine("Invalid register name \"" 4831 + StringRef(RegName) + "\".")); 4832 } 4833 4834 // Result is 64 bit value so split into two 32 bit values and return as a 4835 // pair of values. 4836 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4837 SelectionDAG &DAG) { 4838 SDLoc DL(N); 4839 4840 // This function is only supposed to be called for i64 type destination. 4841 assert(N->getValueType(0) == MVT::i64 4842 && "ExpandREAD_REGISTER called for non-i64 type result."); 4843 4844 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4845 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4846 N->getOperand(0), 4847 N->getOperand(1)); 4848 4849 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4850 Read.getValue(1))); 4851 Results.push_back(Read.getOperand(0)); 4852 } 4853 4854 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4855 /// When \p DstVT, the destination type of \p BC, is on the vector 4856 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4857 /// it might be possible to combine them, such that everything stays on the 4858 /// vector register bank. 4859 /// \p return The node that would replace \p BT, if the combine 4860 /// is possible. 4861 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4862 SelectionDAG &DAG) { 4863 SDValue Op = BC->getOperand(0); 4864 EVT DstVT = BC->getValueType(0); 4865 4866 // The only vector instruction that can produce a scalar (remember, 4867 // since the bitcast was about to be turned into VMOVDRR, the source 4868 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4869 // Moreover, we can do this combine only if there is one use. 4870 // Finally, if the destination type is not a vector, there is not 4871 // much point on forcing everything on the vector bank. 4872 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4873 !Op.hasOneUse()) 4874 return SDValue(); 4875 4876 // If the index is not constant, we will introduce an additional 4877 // multiply that will stick. 4878 // Give up in that case. 4879 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4880 if (!Index) 4881 return SDValue(); 4882 unsigned DstNumElt = DstVT.getVectorNumElements(); 4883 4884 // Compute the new index. 4885 const APInt &APIntIndex = Index->getAPIntValue(); 4886 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4887 NewIndex *= APIntIndex; 4888 // Check if the new constant index fits into i32. 4889 if (NewIndex.getBitWidth() > 32) 4890 return SDValue(); 4891 4892 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4893 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4894 SDLoc dl(Op); 4895 SDValue ExtractSrc = Op.getOperand(0); 4896 EVT VecVT = EVT::getVectorVT( 4897 *DAG.getContext(), DstVT.getScalarType(), 4898 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4899 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4900 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4901 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4902 } 4903 4904 /// ExpandBITCAST - If the target supports VFP, this function is called to 4905 /// expand a bit convert where either the source or destination type is i64 to 4906 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4907 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4908 /// vectors), since the legalizer won't know what to do with that. 4909 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4910 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4911 SDLoc dl(N); 4912 SDValue Op = N->getOperand(0); 4913 4914 // This function is only supposed to be called for i64 types, either as the 4915 // source or destination of the bit convert. 4916 EVT SrcVT = Op.getValueType(); 4917 EVT DstVT = N->getValueType(0); 4918 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4919 "ExpandBITCAST called for non-i64 type"); 4920 4921 // Turn i64->f64 into VMOVDRR. 4922 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4923 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4924 // if we can combine the bitcast with its source. 4925 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4926 return Val; 4927 4928 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4929 DAG.getConstant(0, dl, MVT::i32)); 4930 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4931 DAG.getConstant(1, dl, MVT::i32)); 4932 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4933 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4934 } 4935 4936 // Turn f64->i64 into VMOVRRD. 4937 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4938 SDValue Cvt; 4939 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4940 SrcVT.getVectorNumElements() > 1) 4941 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4942 DAG.getVTList(MVT::i32, MVT::i32), 4943 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4944 else 4945 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4946 DAG.getVTList(MVT::i32, MVT::i32), Op); 4947 // Merge the pieces into a single i64 value. 4948 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4949 } 4950 4951 return SDValue(); 4952 } 4953 4954 /// getZeroVector - Returns a vector of specified type with all zero elements. 4955 /// Zero vectors are used to represent vector negation and in those cases 4956 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4957 /// not support i64 elements, so sometimes the zero vectors will need to be 4958 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4959 /// zero vector. 4960 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4961 assert(VT.isVector() && "Expected a vector type"); 4962 // The canonical modified immediate encoding of a zero vector is....0! 4963 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4964 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4965 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4966 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4967 } 4968 4969 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4970 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4971 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4972 SelectionDAG &DAG) const { 4973 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4974 EVT VT = Op.getValueType(); 4975 unsigned VTBits = VT.getSizeInBits(); 4976 SDLoc dl(Op); 4977 SDValue ShOpLo = Op.getOperand(0); 4978 SDValue ShOpHi = Op.getOperand(1); 4979 SDValue ShAmt = Op.getOperand(2); 4980 SDValue ARMcc; 4981 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4982 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4983 4984 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4985 4986 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4987 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4988 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4989 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4990 DAG.getConstant(VTBits, dl, MVT::i32)); 4991 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4992 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4993 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4994 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4995 ISD::SETGE, ARMcc, DAG, dl); 4996 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 4997 ARMcc, CCR, CmpLo); 4998 4999 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5000 SDValue HiBigShift = Opc == ISD::SRA 5001 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5002 DAG.getConstant(VTBits - 1, dl, VT)) 5003 : DAG.getConstant(0, dl, VT); 5004 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5005 ISD::SETGE, ARMcc, DAG, dl); 5006 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5007 ARMcc, CCR, CmpHi); 5008 5009 SDValue Ops[2] = { Lo, Hi }; 5010 return DAG.getMergeValues(Ops, dl); 5011 } 5012 5013 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5014 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5015 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5016 SelectionDAG &DAG) const { 5017 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5018 EVT VT = Op.getValueType(); 5019 unsigned VTBits = VT.getSizeInBits(); 5020 SDLoc dl(Op); 5021 SDValue ShOpLo = Op.getOperand(0); 5022 SDValue ShOpHi = Op.getOperand(1); 5023 SDValue ShAmt = Op.getOperand(2); 5024 SDValue ARMcc; 5025 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5026 5027 assert(Op.getOpcode() == ISD::SHL_PARTS); 5028 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5029 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5030 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5031 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5032 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5033 5034 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5035 DAG.getConstant(VTBits, dl, MVT::i32)); 5036 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5037 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5038 ISD::SETGE, ARMcc, DAG, dl); 5039 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5040 ARMcc, CCR, CmpHi); 5041 5042 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5043 ISD::SETGE, ARMcc, DAG, dl); 5044 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5045 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5046 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5047 5048 SDValue Ops[2] = { Lo, Hi }; 5049 return DAG.getMergeValues(Ops, dl); 5050 } 5051 5052 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5053 SelectionDAG &DAG) const { 5054 // The rounding mode is in bits 23:22 of the FPSCR. 5055 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5056 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5057 // so that the shift + and get folded into a bitfield extract. 5058 SDLoc dl(Op); 5059 SDValue Ops[] = { DAG.getEntryNode(), 5060 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5061 5062 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5063 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5064 DAG.getConstant(1U << 22, dl, MVT::i32)); 5065 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5066 DAG.getConstant(22, dl, MVT::i32)); 5067 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5068 DAG.getConstant(3, dl, MVT::i32)); 5069 } 5070 5071 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5072 const ARMSubtarget *ST) { 5073 SDLoc dl(N); 5074 EVT VT = N->getValueType(0); 5075 if (VT.isVector()) { 5076 assert(ST->hasNEON()); 5077 5078 // Compute the least significant set bit: LSB = X & -X 5079 SDValue X = N->getOperand(0); 5080 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5081 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5082 5083 EVT ElemTy = VT.getVectorElementType(); 5084 5085 if (ElemTy == MVT::i8) { 5086 // Compute with: cttz(x) = ctpop(lsb - 1) 5087 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5088 DAG.getTargetConstant(1, dl, ElemTy)); 5089 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5090 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5091 } 5092 5093 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5094 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5095 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5096 unsigned NumBits = ElemTy.getSizeInBits(); 5097 SDValue WidthMinus1 = 5098 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5099 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5100 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5101 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5102 } 5103 5104 // Compute with: cttz(x) = ctpop(lsb - 1) 5105 5106 // Since we can only compute the number of bits in a byte with vcnt.8, we 5107 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 5108 // and i64. 5109 5110 // Compute LSB - 1. 5111 SDValue Bits; 5112 if (ElemTy == MVT::i64) { 5113 // Load constant 0xffff'ffff'ffff'ffff to register. 5114 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5115 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5116 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5117 } else { 5118 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5119 DAG.getTargetConstant(1, dl, ElemTy)); 5120 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5121 } 5122 5123 // Count #bits with vcnt.8. 5124 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5125 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5126 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5127 5128 // Gather the #bits with vpaddl (pairwise add.) 5129 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5130 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5131 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5132 Cnt8); 5133 if (ElemTy == MVT::i16) 5134 return Cnt16; 5135 5136 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5137 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5138 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5139 Cnt16); 5140 if (ElemTy == MVT::i32) 5141 return Cnt32; 5142 5143 assert(ElemTy == MVT::i64); 5144 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5145 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5146 Cnt32); 5147 return Cnt64; 5148 } 5149 5150 if (!ST->hasV6T2Ops()) 5151 return SDValue(); 5152 5153 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5154 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5155 } 5156 5157 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5158 /// for each 16-bit element from operand, repeated. The basic idea is to 5159 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5160 /// 5161 /// Trace for v4i16: 5162 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5163 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5164 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5165 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5166 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5167 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5168 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5169 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5170 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5171 EVT VT = N->getValueType(0); 5172 SDLoc DL(N); 5173 5174 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5175 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5176 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5177 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5178 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5179 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5180 } 5181 5182 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5183 /// bit-count for each 16-bit element from the operand. We need slightly 5184 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5185 /// 64/128-bit registers. 5186 /// 5187 /// Trace for v4i16: 5188 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5189 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5190 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5191 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5192 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5193 EVT VT = N->getValueType(0); 5194 SDLoc DL(N); 5195 5196 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5197 if (VT.is64BitVector()) { 5198 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5199 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5200 DAG.getIntPtrConstant(0, DL)); 5201 } else { 5202 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5203 BitCounts, DAG.getIntPtrConstant(0, DL)); 5204 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5205 } 5206 } 5207 5208 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5209 /// bit-count for each 32-bit element from the operand. The idea here is 5210 /// to split the vector into 16-bit elements, leverage the 16-bit count 5211 /// routine, and then combine the results. 5212 /// 5213 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5214 /// input = [v0 v1 ] (vi: 32-bit elements) 5215 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5216 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5217 /// vrev: N0 = [k1 k0 k3 k2 ] 5218 /// [k0 k1 k2 k3 ] 5219 /// N1 =+[k1 k0 k3 k2 ] 5220 /// [k0 k2 k1 k3 ] 5221 /// N2 =+[k1 k3 k0 k2 ] 5222 /// [k0 k2 k1 k3 ] 5223 /// Extended =+[k1 k3 k0 k2 ] 5224 /// [k0 k2 ] 5225 /// Extracted=+[k1 k3 ] 5226 /// 5227 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5228 EVT VT = N->getValueType(0); 5229 SDLoc DL(N); 5230 5231 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5232 5233 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5234 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5235 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5236 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5237 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5238 5239 if (VT.is64BitVector()) { 5240 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5241 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5242 DAG.getIntPtrConstant(0, DL)); 5243 } else { 5244 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5245 DAG.getIntPtrConstant(0, DL)); 5246 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5247 } 5248 } 5249 5250 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5251 const ARMSubtarget *ST) { 5252 EVT VT = N->getValueType(0); 5253 5254 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5255 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5256 VT == MVT::v4i16 || VT == MVT::v8i16) && 5257 "Unexpected type for custom ctpop lowering"); 5258 5259 if (VT.getVectorElementType() == MVT::i32) 5260 return lowerCTPOP32BitElements(N, DAG); 5261 else 5262 return lowerCTPOP16BitElements(N, DAG); 5263 } 5264 5265 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5266 const ARMSubtarget *ST) { 5267 EVT VT = N->getValueType(0); 5268 SDLoc dl(N); 5269 5270 if (!VT.isVector()) 5271 return SDValue(); 5272 5273 // Lower vector shifts on NEON to use VSHL. 5274 assert(ST->hasNEON() && "unexpected vector shift"); 5275 5276 // Left shifts translate directly to the vshiftu intrinsic. 5277 if (N->getOpcode() == ISD::SHL) 5278 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5279 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5280 MVT::i32), 5281 N->getOperand(0), N->getOperand(1)); 5282 5283 assert((N->getOpcode() == ISD::SRA || 5284 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5285 5286 // NEON uses the same intrinsics for both left and right shifts. For 5287 // right shifts, the shift amounts are negative, so negate the vector of 5288 // shift amounts. 5289 EVT ShiftVT = N->getOperand(1).getValueType(); 5290 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5291 getZeroVector(ShiftVT, DAG, dl), 5292 N->getOperand(1)); 5293 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5294 Intrinsic::arm_neon_vshifts : 5295 Intrinsic::arm_neon_vshiftu); 5296 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5297 DAG.getConstant(vshiftInt, dl, MVT::i32), 5298 N->getOperand(0), NegatedCount); 5299 } 5300 5301 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5302 const ARMSubtarget *ST) { 5303 EVT VT = N->getValueType(0); 5304 SDLoc dl(N); 5305 5306 // We can get here for a node like i32 = ISD::SHL i32, i64 5307 if (VT != MVT::i64) 5308 return SDValue(); 5309 5310 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5311 "Unknown shift to lower!"); 5312 5313 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5314 if (!isOneConstant(N->getOperand(1))) 5315 return SDValue(); 5316 5317 // If we are in thumb mode, we don't have RRX. 5318 if (ST->isThumb1Only()) return SDValue(); 5319 5320 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5321 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5322 DAG.getConstant(0, dl, MVT::i32)); 5323 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5324 DAG.getConstant(1, dl, MVT::i32)); 5325 5326 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5327 // captures the result into a carry flag. 5328 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5329 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5330 5331 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5332 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5333 5334 // Merge the pieces into a single i64 value. 5335 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5336 } 5337 5338 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5339 SDValue TmpOp0, TmpOp1; 5340 bool Invert = false; 5341 bool Swap = false; 5342 unsigned Opc = 0; 5343 5344 SDValue Op0 = Op.getOperand(0); 5345 SDValue Op1 = Op.getOperand(1); 5346 SDValue CC = Op.getOperand(2); 5347 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5348 EVT VT = Op.getValueType(); 5349 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5350 SDLoc dl(Op); 5351 5352 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5353 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5354 // Special-case integer 64-bit equality comparisons. They aren't legal, 5355 // but they can be lowered with a few vector instructions. 5356 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5357 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5358 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5359 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5360 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5361 DAG.getCondCode(ISD::SETEQ)); 5362 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5363 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5364 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5365 if (SetCCOpcode == ISD::SETNE) 5366 Merged = DAG.getNOT(dl, Merged, CmpVT); 5367 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5368 return Merged; 5369 } 5370 5371 if (CmpVT.getVectorElementType() == MVT::i64) 5372 // 64-bit comparisons are not legal in general. 5373 return SDValue(); 5374 5375 if (Op1.getValueType().isFloatingPoint()) { 5376 switch (SetCCOpcode) { 5377 default: llvm_unreachable("Illegal FP comparison"); 5378 case ISD::SETUNE: 5379 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5380 case ISD::SETOEQ: 5381 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5382 case ISD::SETOLT: 5383 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5384 case ISD::SETOGT: 5385 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5386 case ISD::SETOLE: 5387 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5388 case ISD::SETOGE: 5389 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5390 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5391 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5392 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5393 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5394 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5395 case ISD::SETONE: 5396 // Expand this to (OLT | OGT). 5397 TmpOp0 = Op0; 5398 TmpOp1 = Op1; 5399 Opc = ISD::OR; 5400 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5401 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5402 break; 5403 case ISD::SETUO: 5404 Invert = true; 5405 LLVM_FALLTHROUGH; 5406 case ISD::SETO: 5407 // Expand this to (OLT | OGE). 5408 TmpOp0 = Op0; 5409 TmpOp1 = Op1; 5410 Opc = ISD::OR; 5411 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5412 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5413 break; 5414 } 5415 } else { 5416 // Integer comparisons. 5417 switch (SetCCOpcode) { 5418 default: llvm_unreachable("Illegal integer comparison"); 5419 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5420 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5421 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5422 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5423 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5424 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5425 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5426 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5427 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5428 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5429 } 5430 5431 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5432 if (Opc == ARMISD::VCEQ) { 5433 SDValue AndOp; 5434 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5435 AndOp = Op0; 5436 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5437 AndOp = Op1; 5438 5439 // Ignore bitconvert. 5440 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5441 AndOp = AndOp.getOperand(0); 5442 5443 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5444 Opc = ARMISD::VTST; 5445 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5446 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5447 Invert = !Invert; 5448 } 5449 } 5450 } 5451 5452 if (Swap) 5453 std::swap(Op0, Op1); 5454 5455 // If one of the operands is a constant vector zero, attempt to fold the 5456 // comparison to a specialized compare-against-zero form. 5457 SDValue SingleOp; 5458 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5459 SingleOp = Op0; 5460 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5461 if (Opc == ARMISD::VCGE) 5462 Opc = ARMISD::VCLEZ; 5463 else if (Opc == ARMISD::VCGT) 5464 Opc = ARMISD::VCLTZ; 5465 SingleOp = Op1; 5466 } 5467 5468 SDValue Result; 5469 if (SingleOp.getNode()) { 5470 switch (Opc) { 5471 case ARMISD::VCEQ: 5472 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5473 case ARMISD::VCGE: 5474 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5475 case ARMISD::VCLEZ: 5476 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5477 case ARMISD::VCGT: 5478 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5479 case ARMISD::VCLTZ: 5480 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5481 default: 5482 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5483 } 5484 } else { 5485 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5486 } 5487 5488 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5489 5490 if (Invert) 5491 Result = DAG.getNOT(dl, Result, VT); 5492 5493 return Result; 5494 } 5495 5496 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5497 SDValue LHS = Op.getOperand(0); 5498 SDValue RHS = Op.getOperand(1); 5499 SDValue Carry = Op.getOperand(2); 5500 SDValue Cond = Op.getOperand(3); 5501 SDLoc DL(Op); 5502 5503 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5504 5505 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5506 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5507 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5508 5509 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5510 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5511 SDValue ARMcc = DAG.getConstant( 5512 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5513 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5514 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5515 Cmp.getValue(1), SDValue()); 5516 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5517 CCR, Chain.getValue(1)); 5518 } 5519 5520 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5521 /// valid vector constant for a NEON instruction with a "modified immediate" 5522 /// operand (e.g., VMOV). If so, return the encoded value. 5523 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5524 unsigned SplatBitSize, SelectionDAG &DAG, 5525 const SDLoc &dl, EVT &VT, bool is128Bits, 5526 NEONModImmType type) { 5527 unsigned OpCmode, Imm; 5528 5529 // SplatBitSize is set to the smallest size that splats the vector, so a 5530 // zero vector will always have SplatBitSize == 8. However, NEON modified 5531 // immediate instructions others than VMOV do not support the 8-bit encoding 5532 // of a zero vector, and the default encoding of zero is supposed to be the 5533 // 32-bit version. 5534 if (SplatBits == 0) 5535 SplatBitSize = 32; 5536 5537 switch (SplatBitSize) { 5538 case 8: 5539 if (type != VMOVModImm) 5540 return SDValue(); 5541 // Any 1-byte value is OK. Op=0, Cmode=1110. 5542 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5543 OpCmode = 0xe; 5544 Imm = SplatBits; 5545 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5546 break; 5547 5548 case 16: 5549 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5550 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5551 if ((SplatBits & ~0xff) == 0) { 5552 // Value = 0x00nn: Op=x, Cmode=100x. 5553 OpCmode = 0x8; 5554 Imm = SplatBits; 5555 break; 5556 } 5557 if ((SplatBits & ~0xff00) == 0) { 5558 // Value = 0xnn00: Op=x, Cmode=101x. 5559 OpCmode = 0xa; 5560 Imm = SplatBits >> 8; 5561 break; 5562 } 5563 return SDValue(); 5564 5565 case 32: 5566 // NEON's 32-bit VMOV supports splat values where: 5567 // * only one byte is nonzero, or 5568 // * the least significant byte is 0xff and the second byte is nonzero, or 5569 // * the least significant 2 bytes are 0xff and the third is nonzero. 5570 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5571 if ((SplatBits & ~0xff) == 0) { 5572 // Value = 0x000000nn: Op=x, Cmode=000x. 5573 OpCmode = 0; 5574 Imm = SplatBits; 5575 break; 5576 } 5577 if ((SplatBits & ~0xff00) == 0) { 5578 // Value = 0x0000nn00: Op=x, Cmode=001x. 5579 OpCmode = 0x2; 5580 Imm = SplatBits >> 8; 5581 break; 5582 } 5583 if ((SplatBits & ~0xff0000) == 0) { 5584 // Value = 0x00nn0000: Op=x, Cmode=010x. 5585 OpCmode = 0x4; 5586 Imm = SplatBits >> 16; 5587 break; 5588 } 5589 if ((SplatBits & ~0xff000000) == 0) { 5590 // Value = 0xnn000000: Op=x, Cmode=011x. 5591 OpCmode = 0x6; 5592 Imm = SplatBits >> 24; 5593 break; 5594 } 5595 5596 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5597 if (type == OtherModImm) return SDValue(); 5598 5599 if ((SplatBits & ~0xffff) == 0 && 5600 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5601 // Value = 0x0000nnff: Op=x, Cmode=1100. 5602 OpCmode = 0xc; 5603 Imm = SplatBits >> 8; 5604 break; 5605 } 5606 5607 if ((SplatBits & ~0xffffff) == 0 && 5608 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5609 // Value = 0x00nnffff: Op=x, Cmode=1101. 5610 OpCmode = 0xd; 5611 Imm = SplatBits >> 16; 5612 break; 5613 } 5614 5615 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5616 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5617 // VMOV.I32. A (very) minor optimization would be to replicate the value 5618 // and fall through here to test for a valid 64-bit splat. But, then the 5619 // caller would also need to check and handle the change in size. 5620 return SDValue(); 5621 5622 case 64: { 5623 if (type != VMOVModImm) 5624 return SDValue(); 5625 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5626 uint64_t BitMask = 0xff; 5627 uint64_t Val = 0; 5628 unsigned ImmMask = 1; 5629 Imm = 0; 5630 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5631 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5632 Val |= BitMask; 5633 Imm |= ImmMask; 5634 } else if ((SplatBits & BitMask) != 0) { 5635 return SDValue(); 5636 } 5637 BitMask <<= 8; 5638 ImmMask <<= 1; 5639 } 5640 5641 if (DAG.getDataLayout().isBigEndian()) 5642 // swap higher and lower 32 bit word 5643 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5644 5645 // Op=1, Cmode=1110. 5646 OpCmode = 0x1e; 5647 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5648 break; 5649 } 5650 5651 default: 5652 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5653 } 5654 5655 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5656 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5657 } 5658 5659 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5660 const ARMSubtarget *ST) const { 5661 bool IsDouble = Op.getValueType() == MVT::f64; 5662 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5663 const APFloat &FPVal = CFP->getValueAPF(); 5664 5665 // Prevent floating-point constants from using literal loads 5666 // when execute-only is enabled. 5667 if (ST->genExecuteOnly()) { 5668 APInt INTVal = FPVal.bitcastToAPInt(); 5669 SDLoc DL(CFP); 5670 if (IsDouble) { 5671 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5672 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5673 if (!ST->isLittle()) 5674 std::swap(Lo, Hi); 5675 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5676 } else { 5677 return DAG.getConstant(INTVal, DL, MVT::i32); 5678 } 5679 } 5680 5681 if (!ST->hasVFP3()) 5682 return SDValue(); 5683 5684 // Use the default (constant pool) lowering for double constants when we have 5685 // an SP-only FPU 5686 if (IsDouble && Subtarget->isFPOnlySP()) 5687 return SDValue(); 5688 5689 // Try splatting with a VMOV.f32... 5690 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5691 5692 if (ImmVal != -1) { 5693 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5694 // We have code in place to select a valid ConstantFP already, no need to 5695 // do any mangling. 5696 return Op; 5697 } 5698 5699 // It's a float and we are trying to use NEON operations where 5700 // possible. Lower it to a splat followed by an extract. 5701 SDLoc DL(Op); 5702 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5703 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5704 NewVal); 5705 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5706 DAG.getConstant(0, DL, MVT::i32)); 5707 } 5708 5709 // The rest of our options are NEON only, make sure that's allowed before 5710 // proceeding.. 5711 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5712 return SDValue(); 5713 5714 EVT VMovVT; 5715 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5716 5717 // It wouldn't really be worth bothering for doubles except for one very 5718 // important value, which does happen to match: 0.0. So make sure we don't do 5719 // anything stupid. 5720 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5721 return SDValue(); 5722 5723 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5724 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5725 VMovVT, false, VMOVModImm); 5726 if (NewVal != SDValue()) { 5727 SDLoc DL(Op); 5728 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5729 NewVal); 5730 if (IsDouble) 5731 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5732 5733 // It's a float: cast and extract a vector element. 5734 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5735 VecConstant); 5736 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5737 DAG.getConstant(0, DL, MVT::i32)); 5738 } 5739 5740 // Finally, try a VMVN.i32 5741 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5742 false, VMVNModImm); 5743 if (NewVal != SDValue()) { 5744 SDLoc DL(Op); 5745 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5746 5747 if (IsDouble) 5748 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5749 5750 // It's a float: cast and extract a vector element. 5751 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5752 VecConstant); 5753 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5754 DAG.getConstant(0, DL, MVT::i32)); 5755 } 5756 5757 return SDValue(); 5758 } 5759 5760 // check if an VEXT instruction can handle the shuffle mask when the 5761 // vector sources of the shuffle are the same. 5762 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5763 unsigned NumElts = VT.getVectorNumElements(); 5764 5765 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5766 if (M[0] < 0) 5767 return false; 5768 5769 Imm = M[0]; 5770 5771 // If this is a VEXT shuffle, the immediate value is the index of the first 5772 // element. The other shuffle indices must be the successive elements after 5773 // the first one. 5774 unsigned ExpectedElt = Imm; 5775 for (unsigned i = 1; i < NumElts; ++i) { 5776 // Increment the expected index. If it wraps around, just follow it 5777 // back to index zero and keep going. 5778 ++ExpectedElt; 5779 if (ExpectedElt == NumElts) 5780 ExpectedElt = 0; 5781 5782 if (M[i] < 0) continue; // ignore UNDEF indices 5783 if (ExpectedElt != static_cast<unsigned>(M[i])) 5784 return false; 5785 } 5786 5787 return true; 5788 } 5789 5790 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5791 bool &ReverseVEXT, unsigned &Imm) { 5792 unsigned NumElts = VT.getVectorNumElements(); 5793 ReverseVEXT = false; 5794 5795 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5796 if (M[0] < 0) 5797 return false; 5798 5799 Imm = M[0]; 5800 5801 // If this is a VEXT shuffle, the immediate value is the index of the first 5802 // element. The other shuffle indices must be the successive elements after 5803 // the first one. 5804 unsigned ExpectedElt = Imm; 5805 for (unsigned i = 1; i < NumElts; ++i) { 5806 // Increment the expected index. If it wraps around, it may still be 5807 // a VEXT but the source vectors must be swapped. 5808 ExpectedElt += 1; 5809 if (ExpectedElt == NumElts * 2) { 5810 ExpectedElt = 0; 5811 ReverseVEXT = true; 5812 } 5813 5814 if (M[i] < 0) continue; // ignore UNDEF indices 5815 if (ExpectedElt != static_cast<unsigned>(M[i])) 5816 return false; 5817 } 5818 5819 // Adjust the index value if the source operands will be swapped. 5820 if (ReverseVEXT) 5821 Imm -= NumElts; 5822 5823 return true; 5824 } 5825 5826 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5827 /// instruction with the specified blocksize. (The order of the elements 5828 /// within each block of the vector is reversed.) 5829 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5830 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5831 "Only possible block sizes for VREV are: 16, 32, 64"); 5832 5833 unsigned EltSz = VT.getScalarSizeInBits(); 5834 if (EltSz == 64) 5835 return false; 5836 5837 unsigned NumElts = VT.getVectorNumElements(); 5838 unsigned BlockElts = M[0] + 1; 5839 // If the first shuffle index is UNDEF, be optimistic. 5840 if (M[0] < 0) 5841 BlockElts = BlockSize / EltSz; 5842 5843 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5844 return false; 5845 5846 for (unsigned i = 0; i < NumElts; ++i) { 5847 if (M[i] < 0) continue; // ignore UNDEF indices 5848 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5849 return false; 5850 } 5851 5852 return true; 5853 } 5854 5855 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5856 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5857 // range, then 0 is placed into the resulting vector. So pretty much any mask 5858 // of 8 elements can work here. 5859 return VT == MVT::v8i8 && M.size() == 8; 5860 } 5861 5862 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 5863 unsigned Index) { 5864 if (Mask.size() == Elements * 2) 5865 return Index / Elements; 5866 return Mask[Index] == 0 ? 0 : 1; 5867 } 5868 5869 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5870 // checking that pairs of elements in the shuffle mask represent the same index 5871 // in each vector, incrementing the expected index by 2 at each step. 5872 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5873 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5874 // v2={e,f,g,h} 5875 // WhichResult gives the offset for each element in the mask based on which 5876 // of the two results it belongs to. 5877 // 5878 // The transpose can be represented either as: 5879 // result1 = shufflevector v1, v2, result1_shuffle_mask 5880 // result2 = shufflevector v1, v2, result2_shuffle_mask 5881 // where v1/v2 and the shuffle masks have the same number of elements 5882 // (here WhichResult (see below) indicates which result is being checked) 5883 // 5884 // or as: 5885 // results = shufflevector v1, v2, shuffle_mask 5886 // where both results are returned in one vector and the shuffle mask has twice 5887 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5888 // want to check the low half and high half of the shuffle mask as if it were 5889 // the other case 5890 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5891 unsigned EltSz = VT.getScalarSizeInBits(); 5892 if (EltSz == 64) 5893 return false; 5894 5895 unsigned NumElts = VT.getVectorNumElements(); 5896 if (M.size() != NumElts && M.size() != NumElts*2) 5897 return false; 5898 5899 // If the mask is twice as long as the input vector then we need to check the 5900 // upper and lower parts of the mask with a matching value for WhichResult 5901 // FIXME: A mask with only even values will be rejected in case the first 5902 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5903 // M[0] is used to determine WhichResult 5904 for (unsigned i = 0; i < M.size(); i += NumElts) { 5905 WhichResult = SelectPairHalf(NumElts, M, i); 5906 for (unsigned j = 0; j < NumElts; j += 2) { 5907 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5908 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5909 return false; 5910 } 5911 } 5912 5913 if (M.size() == NumElts*2) 5914 WhichResult = 0; 5915 5916 return true; 5917 } 5918 5919 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5920 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5921 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5922 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5923 unsigned EltSz = VT.getScalarSizeInBits(); 5924 if (EltSz == 64) 5925 return false; 5926 5927 unsigned NumElts = VT.getVectorNumElements(); 5928 if (M.size() != NumElts && M.size() != NumElts*2) 5929 return false; 5930 5931 for (unsigned i = 0; i < M.size(); i += NumElts) { 5932 WhichResult = SelectPairHalf(NumElts, M, i); 5933 for (unsigned j = 0; j < NumElts; j += 2) { 5934 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5935 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5936 return false; 5937 } 5938 } 5939 5940 if (M.size() == NumElts*2) 5941 WhichResult = 0; 5942 5943 return true; 5944 } 5945 5946 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5947 // that the mask elements are either all even and in steps of size 2 or all odd 5948 // and in steps of size 2. 5949 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5950 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5951 // v2={e,f,g,h} 5952 // Requires similar checks to that of isVTRNMask with 5953 // respect the how results are returned. 5954 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5955 unsigned EltSz = VT.getScalarSizeInBits(); 5956 if (EltSz == 64) 5957 return false; 5958 5959 unsigned NumElts = VT.getVectorNumElements(); 5960 if (M.size() != NumElts && M.size() != NumElts*2) 5961 return false; 5962 5963 for (unsigned i = 0; i < M.size(); i += NumElts) { 5964 WhichResult = SelectPairHalf(NumElts, M, i); 5965 for (unsigned j = 0; j < NumElts; ++j) { 5966 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5967 return false; 5968 } 5969 } 5970 5971 if (M.size() == NumElts*2) 5972 WhichResult = 0; 5973 5974 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5975 if (VT.is64BitVector() && EltSz == 32) 5976 return false; 5977 5978 return true; 5979 } 5980 5981 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5982 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5983 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5984 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5985 unsigned EltSz = VT.getScalarSizeInBits(); 5986 if (EltSz == 64) 5987 return false; 5988 5989 unsigned NumElts = VT.getVectorNumElements(); 5990 if (M.size() != NumElts && M.size() != NumElts*2) 5991 return false; 5992 5993 unsigned Half = NumElts / 2; 5994 for (unsigned i = 0; i < M.size(); i += NumElts) { 5995 WhichResult = SelectPairHalf(NumElts, M, i); 5996 for (unsigned j = 0; j < NumElts; j += Half) { 5997 unsigned Idx = WhichResult; 5998 for (unsigned k = 0; k < Half; ++k) { 5999 int MIdx = M[i + j + k]; 6000 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6001 return false; 6002 Idx += 2; 6003 } 6004 } 6005 } 6006 6007 if (M.size() == NumElts*2) 6008 WhichResult = 0; 6009 6010 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6011 if (VT.is64BitVector() && EltSz == 32) 6012 return false; 6013 6014 return true; 6015 } 6016 6017 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6018 // that pairs of elements of the shufflemask represent the same index in each 6019 // vector incrementing sequentially through the vectors. 6020 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6021 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6022 // v2={e,f,g,h} 6023 // Requires similar checks to that of isVTRNMask with respect the how results 6024 // are returned. 6025 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6026 unsigned EltSz = VT.getScalarSizeInBits(); 6027 if (EltSz == 64) 6028 return false; 6029 6030 unsigned NumElts = VT.getVectorNumElements(); 6031 if (M.size() != NumElts && M.size() != NumElts*2) 6032 return false; 6033 6034 for (unsigned i = 0; i < M.size(); i += NumElts) { 6035 WhichResult = SelectPairHalf(NumElts, M, i); 6036 unsigned Idx = WhichResult * NumElts / 2; 6037 for (unsigned j = 0; j < NumElts; j += 2) { 6038 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6039 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6040 return false; 6041 Idx += 1; 6042 } 6043 } 6044 6045 if (M.size() == NumElts*2) 6046 WhichResult = 0; 6047 6048 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6049 if (VT.is64BitVector() && EltSz == 32) 6050 return false; 6051 6052 return true; 6053 } 6054 6055 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6056 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6057 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6058 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6059 unsigned EltSz = VT.getScalarSizeInBits(); 6060 if (EltSz == 64) 6061 return false; 6062 6063 unsigned NumElts = VT.getVectorNumElements(); 6064 if (M.size() != NumElts && M.size() != NumElts*2) 6065 return false; 6066 6067 for (unsigned i = 0; i < M.size(); i += NumElts) { 6068 WhichResult = SelectPairHalf(NumElts, M, i); 6069 unsigned Idx = WhichResult * NumElts / 2; 6070 for (unsigned j = 0; j < NumElts; j += 2) { 6071 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6072 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6073 return false; 6074 Idx += 1; 6075 } 6076 } 6077 6078 if (M.size() == NumElts*2) 6079 WhichResult = 0; 6080 6081 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6082 if (VT.is64BitVector() && EltSz == 32) 6083 return false; 6084 6085 return true; 6086 } 6087 6088 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6089 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6090 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6091 unsigned &WhichResult, 6092 bool &isV_UNDEF) { 6093 isV_UNDEF = false; 6094 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6095 return ARMISD::VTRN; 6096 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6097 return ARMISD::VUZP; 6098 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6099 return ARMISD::VZIP; 6100 6101 isV_UNDEF = true; 6102 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6103 return ARMISD::VTRN; 6104 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6105 return ARMISD::VUZP; 6106 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6107 return ARMISD::VZIP; 6108 6109 return 0; 6110 } 6111 6112 /// \return true if this is a reverse operation on an vector. 6113 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6114 unsigned NumElts = VT.getVectorNumElements(); 6115 // Make sure the mask has the right size. 6116 if (NumElts != M.size()) 6117 return false; 6118 6119 // Look for <15, ..., 3, -1, 1, 0>. 6120 for (unsigned i = 0; i != NumElts; ++i) 6121 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6122 return false; 6123 6124 return true; 6125 } 6126 6127 // If N is an integer constant that can be moved into a register in one 6128 // instruction, return an SDValue of such a constant (will become a MOV 6129 // instruction). Otherwise return null. 6130 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6131 const ARMSubtarget *ST, const SDLoc &dl) { 6132 uint64_t Val; 6133 if (!isa<ConstantSDNode>(N)) 6134 return SDValue(); 6135 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6136 6137 if (ST->isThumb1Only()) { 6138 if (Val <= 255 || ~Val <= 255) 6139 return DAG.getConstant(Val, dl, MVT::i32); 6140 } else { 6141 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6142 return DAG.getConstant(Val, dl, MVT::i32); 6143 } 6144 return SDValue(); 6145 } 6146 6147 // If this is a case we can't handle, return null and let the default 6148 // expansion code take care of it. 6149 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6150 const ARMSubtarget *ST) const { 6151 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6152 SDLoc dl(Op); 6153 EVT VT = Op.getValueType(); 6154 6155 APInt SplatBits, SplatUndef; 6156 unsigned SplatBitSize; 6157 bool HasAnyUndefs; 6158 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6159 if (SplatUndef.isAllOnesValue()) 6160 return DAG.getUNDEF(VT); 6161 6162 if (SplatBitSize <= 64) { 6163 // Check if an immediate VMOV works. 6164 EVT VmovVT; 6165 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6166 SplatUndef.getZExtValue(), SplatBitSize, 6167 DAG, dl, VmovVT, VT.is128BitVector(), 6168 VMOVModImm); 6169 if (Val.getNode()) { 6170 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6171 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6172 } 6173 6174 // Try an immediate VMVN. 6175 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6176 Val = isNEONModifiedImm(NegatedImm, 6177 SplatUndef.getZExtValue(), SplatBitSize, 6178 DAG, dl, VmovVT, VT.is128BitVector(), 6179 VMVNModImm); 6180 if (Val.getNode()) { 6181 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6182 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6183 } 6184 6185 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6186 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6187 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6188 if (ImmVal != -1) { 6189 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6190 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6191 } 6192 } 6193 } 6194 } 6195 6196 // Scan through the operands to see if only one value is used. 6197 // 6198 // As an optimisation, even if more than one value is used it may be more 6199 // profitable to splat with one value then change some lanes. 6200 // 6201 // Heuristically we decide to do this if the vector has a "dominant" value, 6202 // defined as splatted to more than half of the lanes. 6203 unsigned NumElts = VT.getVectorNumElements(); 6204 bool isOnlyLowElement = true; 6205 bool usesOnlyOneValue = true; 6206 bool hasDominantValue = false; 6207 bool isConstant = true; 6208 6209 // Map of the number of times a particular SDValue appears in the 6210 // element list. 6211 DenseMap<SDValue, unsigned> ValueCounts; 6212 SDValue Value; 6213 for (unsigned i = 0; i < NumElts; ++i) { 6214 SDValue V = Op.getOperand(i); 6215 if (V.isUndef()) 6216 continue; 6217 if (i > 0) 6218 isOnlyLowElement = false; 6219 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6220 isConstant = false; 6221 6222 ValueCounts.insert(std::make_pair(V, 0)); 6223 unsigned &Count = ValueCounts[V]; 6224 6225 // Is this value dominant? (takes up more than half of the lanes) 6226 if (++Count > (NumElts / 2)) { 6227 hasDominantValue = true; 6228 Value = V; 6229 } 6230 } 6231 if (ValueCounts.size() != 1) 6232 usesOnlyOneValue = false; 6233 if (!Value.getNode() && !ValueCounts.empty()) 6234 Value = ValueCounts.begin()->first; 6235 6236 if (ValueCounts.empty()) 6237 return DAG.getUNDEF(VT); 6238 6239 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6240 // Keep going if we are hitting this case. 6241 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6242 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6243 6244 unsigned EltSize = VT.getScalarSizeInBits(); 6245 6246 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6247 // i32 and try again. 6248 if (hasDominantValue && EltSize <= 32) { 6249 if (!isConstant) { 6250 SDValue N; 6251 6252 // If we are VDUPing a value that comes directly from a vector, that will 6253 // cause an unnecessary move to and from a GPR, where instead we could 6254 // just use VDUPLANE. We can only do this if the lane being extracted 6255 // is at a constant index, as the VDUP from lane instructions only have 6256 // constant-index forms. 6257 ConstantSDNode *constIndex; 6258 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6259 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6260 // We need to create a new undef vector to use for the VDUPLANE if the 6261 // size of the vector from which we get the value is different than the 6262 // size of the vector that we need to create. We will insert the element 6263 // such that the register coalescer will remove unnecessary copies. 6264 if (VT != Value->getOperand(0).getValueType()) { 6265 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6266 VT.getVectorNumElements(); 6267 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6268 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6269 Value, DAG.getConstant(index, dl, MVT::i32)), 6270 DAG.getConstant(index, dl, MVT::i32)); 6271 } else 6272 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6273 Value->getOperand(0), Value->getOperand(1)); 6274 } else 6275 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6276 6277 if (!usesOnlyOneValue) { 6278 // The dominant value was splatted as 'N', but we now have to insert 6279 // all differing elements. 6280 for (unsigned I = 0; I < NumElts; ++I) { 6281 if (Op.getOperand(I) == Value) 6282 continue; 6283 SmallVector<SDValue, 3> Ops; 6284 Ops.push_back(N); 6285 Ops.push_back(Op.getOperand(I)); 6286 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6287 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6288 } 6289 } 6290 return N; 6291 } 6292 if (VT.getVectorElementType().isFloatingPoint()) { 6293 SmallVector<SDValue, 8> Ops; 6294 for (unsigned i = 0; i < NumElts; ++i) 6295 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6296 Op.getOperand(i))); 6297 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6298 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6299 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6300 if (Val.getNode()) 6301 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6302 } 6303 if (usesOnlyOneValue) { 6304 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6305 if (isConstant && Val.getNode()) 6306 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6307 } 6308 } 6309 6310 // If all elements are constants and the case above didn't get hit, fall back 6311 // to the default expansion, which will generate a load from the constant 6312 // pool. 6313 if (isConstant) 6314 return SDValue(); 6315 6316 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6317 if (NumElts >= 4) { 6318 SDValue shuffle = ReconstructShuffle(Op, DAG); 6319 if (shuffle != SDValue()) 6320 return shuffle; 6321 } 6322 6323 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6324 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6325 // into two 64-bit vectors; we might discover a better way to lower it. 6326 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6327 EVT ExtVT = VT.getVectorElementType(); 6328 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6329 SDValue Lower = 6330 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6331 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6332 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6333 SDValue Upper = DAG.getBuildVector( 6334 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6335 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6336 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6337 if (Lower && Upper) 6338 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6339 } 6340 6341 // Vectors with 32- or 64-bit elements can be built by directly assigning 6342 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6343 // will be legalized. 6344 if (EltSize >= 32) { 6345 // Do the expansion with floating-point types, since that is what the VFP 6346 // registers are defined to use, and since i64 is not legal. 6347 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6348 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6349 SmallVector<SDValue, 8> Ops; 6350 for (unsigned i = 0; i < NumElts; ++i) 6351 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6352 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6353 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6354 } 6355 6356 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6357 // know the default expansion would otherwise fall back on something even 6358 // worse. For a vector with one or two non-undef values, that's 6359 // scalar_to_vector for the elements followed by a shuffle (provided the 6360 // shuffle is valid for the target) and materialization element by element 6361 // on the stack followed by a load for everything else. 6362 if (!isConstant && !usesOnlyOneValue) { 6363 SDValue Vec = DAG.getUNDEF(VT); 6364 for (unsigned i = 0 ; i < NumElts; ++i) { 6365 SDValue V = Op.getOperand(i); 6366 if (V.isUndef()) 6367 continue; 6368 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6369 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6370 } 6371 return Vec; 6372 } 6373 6374 return SDValue(); 6375 } 6376 6377 // Gather data to see if the operation can be modelled as a 6378 // shuffle in combination with VEXTs. 6379 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6380 SelectionDAG &DAG) const { 6381 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6382 SDLoc dl(Op); 6383 EVT VT = Op.getValueType(); 6384 unsigned NumElts = VT.getVectorNumElements(); 6385 6386 struct ShuffleSourceInfo { 6387 SDValue Vec; 6388 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6389 unsigned MaxElt = 0; 6390 6391 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6392 // be compatible with the shuffle we intend to construct. As a result 6393 // ShuffleVec will be some sliding window into the original Vec. 6394 SDValue ShuffleVec; 6395 6396 // Code should guarantee that element i in Vec starts at element "WindowBase 6397 // + i * WindowScale in ShuffleVec". 6398 int WindowBase = 0; 6399 int WindowScale = 1; 6400 6401 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6402 6403 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6404 }; 6405 6406 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6407 // node. 6408 SmallVector<ShuffleSourceInfo, 2> Sources; 6409 for (unsigned i = 0; i < NumElts; ++i) { 6410 SDValue V = Op.getOperand(i); 6411 if (V.isUndef()) 6412 continue; 6413 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6414 // A shuffle can only come from building a vector from various 6415 // elements of other vectors. 6416 return SDValue(); 6417 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6418 // Furthermore, shuffles require a constant mask, whereas extractelts 6419 // accept variable indices. 6420 return SDValue(); 6421 } 6422 6423 // Add this element source to the list if it's not already there. 6424 SDValue SourceVec = V.getOperand(0); 6425 auto Source = llvm::find(Sources, SourceVec); 6426 if (Source == Sources.end()) 6427 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6428 6429 // Update the minimum and maximum lane number seen. 6430 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6431 Source->MinElt = std::min(Source->MinElt, EltNo); 6432 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6433 } 6434 6435 // Currently only do something sane when at most two source vectors 6436 // are involved. 6437 if (Sources.size() > 2) 6438 return SDValue(); 6439 6440 // Find out the smallest element size among result and two sources, and use 6441 // it as element size to build the shuffle_vector. 6442 EVT SmallestEltTy = VT.getVectorElementType(); 6443 for (auto &Source : Sources) { 6444 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6445 if (SrcEltTy.bitsLT(SmallestEltTy)) 6446 SmallestEltTy = SrcEltTy; 6447 } 6448 unsigned ResMultiplier = 6449 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6450 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6451 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6452 6453 // If the source vector is too wide or too narrow, we may nevertheless be able 6454 // to construct a compatible shuffle either by concatenating it with UNDEF or 6455 // extracting a suitable range of elements. 6456 for (auto &Src : Sources) { 6457 EVT SrcVT = Src.ShuffleVec.getValueType(); 6458 6459 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6460 continue; 6461 6462 // This stage of the search produces a source with the same element type as 6463 // the original, but with a total width matching the BUILD_VECTOR output. 6464 EVT EltVT = SrcVT.getVectorElementType(); 6465 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6466 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6467 6468 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6469 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6470 return SDValue(); 6471 // We can pad out the smaller vector for free, so if it's part of a 6472 // shuffle... 6473 Src.ShuffleVec = 6474 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6475 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6476 continue; 6477 } 6478 6479 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6480 return SDValue(); 6481 6482 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6483 // Span too large for a VEXT to cope 6484 return SDValue(); 6485 } 6486 6487 if (Src.MinElt >= NumSrcElts) { 6488 // The extraction can just take the second half 6489 Src.ShuffleVec = 6490 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6491 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6492 Src.WindowBase = -NumSrcElts; 6493 } else if (Src.MaxElt < NumSrcElts) { 6494 // The extraction can just take the first half 6495 Src.ShuffleVec = 6496 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6497 DAG.getConstant(0, dl, MVT::i32)); 6498 } else { 6499 // An actual VEXT is needed 6500 SDValue VEXTSrc1 = 6501 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6502 DAG.getConstant(0, dl, MVT::i32)); 6503 SDValue VEXTSrc2 = 6504 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6505 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6506 6507 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6508 VEXTSrc2, 6509 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6510 Src.WindowBase = -Src.MinElt; 6511 } 6512 } 6513 6514 // Another possible incompatibility occurs from the vector element types. We 6515 // can fix this by bitcasting the source vectors to the same type we intend 6516 // for the shuffle. 6517 for (auto &Src : Sources) { 6518 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6519 if (SrcEltTy == SmallestEltTy) 6520 continue; 6521 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6522 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6523 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6524 Src.WindowBase *= Src.WindowScale; 6525 } 6526 6527 // Final sanity check before we try to actually produce a shuffle. 6528 DEBUG( 6529 for (auto Src : Sources) 6530 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6531 ); 6532 6533 // The stars all align, our next step is to produce the mask for the shuffle. 6534 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6535 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6536 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6537 SDValue Entry = Op.getOperand(i); 6538 if (Entry.isUndef()) 6539 continue; 6540 6541 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6542 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6543 6544 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6545 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6546 // segment. 6547 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6548 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6549 VT.getScalarSizeInBits()); 6550 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6551 6552 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6553 // starting at the appropriate offset. 6554 int *LaneMask = &Mask[i * ResMultiplier]; 6555 6556 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6557 ExtractBase += NumElts * (Src - Sources.begin()); 6558 for (int j = 0; j < LanesDefined; ++j) 6559 LaneMask[j] = ExtractBase + j; 6560 } 6561 6562 // Final check before we try to produce nonsense... 6563 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6564 return SDValue(); 6565 6566 // We can't handle more than two sources. This should have already 6567 // been checked before this point. 6568 assert(Sources.size() <= 2 && "Too many sources!"); 6569 6570 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6571 for (unsigned i = 0; i < Sources.size(); ++i) 6572 ShuffleOps[i] = Sources[i].ShuffleVec; 6573 6574 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6575 ShuffleOps[1], Mask); 6576 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6577 } 6578 6579 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6580 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6581 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6582 /// are assumed to be legal. 6583 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6584 if (VT.getVectorNumElements() == 4 && 6585 (VT.is128BitVector() || VT.is64BitVector())) { 6586 unsigned PFIndexes[4]; 6587 for (unsigned i = 0; i != 4; ++i) { 6588 if (M[i] < 0) 6589 PFIndexes[i] = 8; 6590 else 6591 PFIndexes[i] = M[i]; 6592 } 6593 6594 // Compute the index in the perfect shuffle table. 6595 unsigned PFTableIndex = 6596 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6597 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6598 unsigned Cost = (PFEntry >> 30); 6599 6600 if (Cost <= 4) 6601 return true; 6602 } 6603 6604 bool ReverseVEXT, isV_UNDEF; 6605 unsigned Imm, WhichResult; 6606 6607 unsigned EltSize = VT.getScalarSizeInBits(); 6608 return (EltSize >= 32 || 6609 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6610 isVREVMask(M, VT, 64) || 6611 isVREVMask(M, VT, 32) || 6612 isVREVMask(M, VT, 16) || 6613 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6614 isVTBLMask(M, VT) || 6615 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6616 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6617 } 6618 6619 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6620 /// the specified operations to build the shuffle. 6621 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6622 SDValue RHS, SelectionDAG &DAG, 6623 const SDLoc &dl) { 6624 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6625 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6626 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6627 6628 enum { 6629 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6630 OP_VREV, 6631 OP_VDUP0, 6632 OP_VDUP1, 6633 OP_VDUP2, 6634 OP_VDUP3, 6635 OP_VEXT1, 6636 OP_VEXT2, 6637 OP_VEXT3, 6638 OP_VUZPL, // VUZP, left result 6639 OP_VUZPR, // VUZP, right result 6640 OP_VZIPL, // VZIP, left result 6641 OP_VZIPR, // VZIP, right result 6642 OP_VTRNL, // VTRN, left result 6643 OP_VTRNR // VTRN, right result 6644 }; 6645 6646 if (OpNum == OP_COPY) { 6647 if (LHSID == (1*9+2)*9+3) return LHS; 6648 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6649 return RHS; 6650 } 6651 6652 SDValue OpLHS, OpRHS; 6653 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6654 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6655 EVT VT = OpLHS.getValueType(); 6656 6657 switch (OpNum) { 6658 default: llvm_unreachable("Unknown shuffle opcode!"); 6659 case OP_VREV: 6660 // VREV divides the vector in half and swaps within the half. 6661 if (VT.getVectorElementType() == MVT::i32 || 6662 VT.getVectorElementType() == MVT::f32) 6663 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6664 // vrev <4 x i16> -> VREV32 6665 if (VT.getVectorElementType() == MVT::i16) 6666 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6667 // vrev <4 x i8> -> VREV16 6668 assert(VT.getVectorElementType() == MVT::i8); 6669 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6670 case OP_VDUP0: 6671 case OP_VDUP1: 6672 case OP_VDUP2: 6673 case OP_VDUP3: 6674 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6675 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6676 case OP_VEXT1: 6677 case OP_VEXT2: 6678 case OP_VEXT3: 6679 return DAG.getNode(ARMISD::VEXT, dl, VT, 6680 OpLHS, OpRHS, 6681 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6682 case OP_VUZPL: 6683 case OP_VUZPR: 6684 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6685 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6686 case OP_VZIPL: 6687 case OP_VZIPR: 6688 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6689 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6690 case OP_VTRNL: 6691 case OP_VTRNR: 6692 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6693 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6694 } 6695 } 6696 6697 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6698 ArrayRef<int> ShuffleMask, 6699 SelectionDAG &DAG) { 6700 // Check to see if we can use the VTBL instruction. 6701 SDValue V1 = Op.getOperand(0); 6702 SDValue V2 = Op.getOperand(1); 6703 SDLoc DL(Op); 6704 6705 SmallVector<SDValue, 8> VTBLMask; 6706 for (ArrayRef<int>::iterator 6707 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6708 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6709 6710 if (V2.getNode()->isUndef()) 6711 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6712 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6713 6714 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6715 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6716 } 6717 6718 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6719 SelectionDAG &DAG) { 6720 SDLoc DL(Op); 6721 SDValue OpLHS = Op.getOperand(0); 6722 EVT VT = OpLHS.getValueType(); 6723 6724 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6725 "Expect an v8i16/v16i8 type"); 6726 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6727 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6728 // extract the first 8 bytes into the top double word and the last 8 bytes 6729 // into the bottom double word. The v8i16 case is similar. 6730 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6731 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6732 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6733 } 6734 6735 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6736 SDValue V1 = Op.getOperand(0); 6737 SDValue V2 = Op.getOperand(1); 6738 SDLoc dl(Op); 6739 EVT VT = Op.getValueType(); 6740 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6741 6742 // Convert shuffles that are directly supported on NEON to target-specific 6743 // DAG nodes, instead of keeping them as shuffles and matching them again 6744 // during code selection. This is more efficient and avoids the possibility 6745 // of inconsistencies between legalization and selection. 6746 // FIXME: floating-point vectors should be canonicalized to integer vectors 6747 // of the same time so that they get CSEd properly. 6748 ArrayRef<int> ShuffleMask = SVN->getMask(); 6749 6750 unsigned EltSize = VT.getScalarSizeInBits(); 6751 if (EltSize <= 32) { 6752 if (SVN->isSplat()) { 6753 int Lane = SVN->getSplatIndex(); 6754 // If this is undef splat, generate it via "just" vdup, if possible. 6755 if (Lane == -1) Lane = 0; 6756 6757 // Test if V1 is a SCALAR_TO_VECTOR. 6758 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6759 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6760 } 6761 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6762 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6763 // reaches it). 6764 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6765 !isa<ConstantSDNode>(V1.getOperand(0))) { 6766 bool IsScalarToVector = true; 6767 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6768 if (!V1.getOperand(i).isUndef()) { 6769 IsScalarToVector = false; 6770 break; 6771 } 6772 if (IsScalarToVector) 6773 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6774 } 6775 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6776 DAG.getConstant(Lane, dl, MVT::i32)); 6777 } 6778 6779 bool ReverseVEXT; 6780 unsigned Imm; 6781 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6782 if (ReverseVEXT) 6783 std::swap(V1, V2); 6784 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6785 DAG.getConstant(Imm, dl, MVT::i32)); 6786 } 6787 6788 if (isVREVMask(ShuffleMask, VT, 64)) 6789 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6790 if (isVREVMask(ShuffleMask, VT, 32)) 6791 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6792 if (isVREVMask(ShuffleMask, VT, 16)) 6793 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6794 6795 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6796 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6797 DAG.getConstant(Imm, dl, MVT::i32)); 6798 } 6799 6800 // Check for Neon shuffles that modify both input vectors in place. 6801 // If both results are used, i.e., if there are two shuffles with the same 6802 // source operands and with masks corresponding to both results of one of 6803 // these operations, DAG memoization will ensure that a single node is 6804 // used for both shuffles. 6805 unsigned WhichResult; 6806 bool isV_UNDEF; 6807 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6808 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6809 if (isV_UNDEF) 6810 V2 = V1; 6811 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6812 .getValue(WhichResult); 6813 } 6814 6815 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6816 // shuffles that produce a result larger than their operands with: 6817 // shuffle(concat(v1, undef), concat(v2, undef)) 6818 // -> 6819 // shuffle(concat(v1, v2), undef) 6820 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6821 // 6822 // This is useful in the general case, but there are special cases where 6823 // native shuffles produce larger results: the two-result ops. 6824 // 6825 // Look through the concat when lowering them: 6826 // shuffle(concat(v1, v2), undef) 6827 // -> 6828 // concat(VZIP(v1, v2):0, :1) 6829 // 6830 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6831 SDValue SubV1 = V1->getOperand(0); 6832 SDValue SubV2 = V1->getOperand(1); 6833 EVT SubVT = SubV1.getValueType(); 6834 6835 // We expect these to have been canonicalized to -1. 6836 assert(llvm::all_of(ShuffleMask, [&](int i) { 6837 return i < (int)VT.getVectorNumElements(); 6838 }) && "Unexpected shuffle index into UNDEF operand!"); 6839 6840 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6841 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6842 if (isV_UNDEF) 6843 SubV2 = SubV1; 6844 assert((WhichResult == 0) && 6845 "In-place shuffle of concat can only have one result!"); 6846 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6847 SubV1, SubV2); 6848 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6849 Res.getValue(1)); 6850 } 6851 } 6852 } 6853 6854 // If the shuffle is not directly supported and it has 4 elements, use 6855 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6856 unsigned NumElts = VT.getVectorNumElements(); 6857 if (NumElts == 4) { 6858 unsigned PFIndexes[4]; 6859 for (unsigned i = 0; i != 4; ++i) { 6860 if (ShuffleMask[i] < 0) 6861 PFIndexes[i] = 8; 6862 else 6863 PFIndexes[i] = ShuffleMask[i]; 6864 } 6865 6866 // Compute the index in the perfect shuffle table. 6867 unsigned PFTableIndex = 6868 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6869 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6870 unsigned Cost = (PFEntry >> 30); 6871 6872 if (Cost <= 4) 6873 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6874 } 6875 6876 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6877 if (EltSize >= 32) { 6878 // Do the expansion with floating-point types, since that is what the VFP 6879 // registers are defined to use, and since i64 is not legal. 6880 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6881 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6882 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6883 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6884 SmallVector<SDValue, 8> Ops; 6885 for (unsigned i = 0; i < NumElts; ++i) { 6886 if (ShuffleMask[i] < 0) 6887 Ops.push_back(DAG.getUNDEF(EltVT)); 6888 else 6889 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6890 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6891 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6892 dl, MVT::i32))); 6893 } 6894 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6895 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6896 } 6897 6898 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6899 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6900 6901 if (VT == MVT::v8i8) 6902 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6903 return NewOp; 6904 6905 return SDValue(); 6906 } 6907 6908 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6909 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6910 SDValue Lane = Op.getOperand(2); 6911 if (!isa<ConstantSDNode>(Lane)) 6912 return SDValue(); 6913 6914 return Op; 6915 } 6916 6917 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6918 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6919 SDValue Lane = Op.getOperand(1); 6920 if (!isa<ConstantSDNode>(Lane)) 6921 return SDValue(); 6922 6923 SDValue Vec = Op.getOperand(0); 6924 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 6925 SDLoc dl(Op); 6926 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6927 } 6928 6929 return Op; 6930 } 6931 6932 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6933 // The only time a CONCAT_VECTORS operation can have legal types is when 6934 // two 64-bit vectors are concatenated to a 128-bit vector. 6935 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6936 "unexpected CONCAT_VECTORS"); 6937 SDLoc dl(Op); 6938 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6939 SDValue Op0 = Op.getOperand(0); 6940 SDValue Op1 = Op.getOperand(1); 6941 if (!Op0.isUndef()) 6942 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6943 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6944 DAG.getIntPtrConstant(0, dl)); 6945 if (!Op1.isUndef()) 6946 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6947 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6948 DAG.getIntPtrConstant(1, dl)); 6949 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6950 } 6951 6952 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6953 /// element has been zero/sign-extended, depending on the isSigned parameter, 6954 /// from an integer type half its size. 6955 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6956 bool isSigned) { 6957 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6958 EVT VT = N->getValueType(0); 6959 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6960 SDNode *BVN = N->getOperand(0).getNode(); 6961 if (BVN->getValueType(0) != MVT::v4i32 || 6962 BVN->getOpcode() != ISD::BUILD_VECTOR) 6963 return false; 6964 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6965 unsigned HiElt = 1 - LoElt; 6966 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6967 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6968 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6969 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6970 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6971 return false; 6972 if (isSigned) { 6973 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6974 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6975 return true; 6976 } else { 6977 if (Hi0->isNullValue() && Hi1->isNullValue()) 6978 return true; 6979 } 6980 return false; 6981 } 6982 6983 if (N->getOpcode() != ISD::BUILD_VECTOR) 6984 return false; 6985 6986 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6987 SDNode *Elt = N->getOperand(i).getNode(); 6988 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6989 unsigned EltSize = VT.getScalarSizeInBits(); 6990 unsigned HalfSize = EltSize / 2; 6991 if (isSigned) { 6992 if (!isIntN(HalfSize, C->getSExtValue())) 6993 return false; 6994 } else { 6995 if (!isUIntN(HalfSize, C->getZExtValue())) 6996 return false; 6997 } 6998 continue; 6999 } 7000 return false; 7001 } 7002 7003 return true; 7004 } 7005 7006 /// isSignExtended - Check if a node is a vector value that is sign-extended 7007 /// or a constant BUILD_VECTOR with sign-extended elements. 7008 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7009 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7010 return true; 7011 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7012 return true; 7013 return false; 7014 } 7015 7016 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7017 /// or a constant BUILD_VECTOR with zero-extended elements. 7018 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7019 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7020 return true; 7021 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7022 return true; 7023 return false; 7024 } 7025 7026 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7027 if (OrigVT.getSizeInBits() >= 64) 7028 return OrigVT; 7029 7030 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7031 7032 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7033 switch (OrigSimpleTy) { 7034 default: llvm_unreachable("Unexpected Vector Type"); 7035 case MVT::v2i8: 7036 case MVT::v2i16: 7037 return MVT::v2i32; 7038 case MVT::v4i8: 7039 return MVT::v4i16; 7040 } 7041 } 7042 7043 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7044 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7045 /// We insert the required extension here to get the vector to fill a D register. 7046 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7047 const EVT &OrigTy, 7048 const EVT &ExtTy, 7049 unsigned ExtOpcode) { 7050 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7051 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7052 // 64-bits we need to insert a new extension so that it will be 64-bits. 7053 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7054 if (OrigTy.getSizeInBits() >= 64) 7055 return N; 7056 7057 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7058 EVT NewVT = getExtensionTo64Bits(OrigTy); 7059 7060 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7061 } 7062 7063 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7064 /// does not do any sign/zero extension. If the original vector is less 7065 /// than 64 bits, an appropriate extension will be added after the load to 7066 /// reach a total size of 64 bits. We have to add the extension separately 7067 /// because ARM does not have a sign/zero extending load for vectors. 7068 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7069 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7070 7071 // The load already has the right type. 7072 if (ExtendedTy == LD->getMemoryVT()) 7073 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7074 LD->getBasePtr(), LD->getPointerInfo(), 7075 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7076 7077 // We need to create a zextload/sextload. We cannot just create a load 7078 // followed by a zext/zext node because LowerMUL is also run during normal 7079 // operation legalization where we can't create illegal types. 7080 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7081 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7082 LD->getMemoryVT(), LD->getAlignment(), 7083 LD->getMemOperand()->getFlags()); 7084 } 7085 7086 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7087 /// extending load, or BUILD_VECTOR with extended elements, return the 7088 /// unextended value. The unextended vector should be 64 bits so that it can 7089 /// be used as an operand to a VMULL instruction. If the original vector size 7090 /// before extension is less than 64 bits we add a an extension to resize 7091 /// the vector to 64 bits. 7092 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7093 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7094 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7095 N->getOperand(0)->getValueType(0), 7096 N->getValueType(0), 7097 N->getOpcode()); 7098 7099 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7100 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7101 "Expected extending load"); 7102 7103 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7104 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7105 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7106 SDValue extLoad = 7107 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7108 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7109 7110 return newLoad; 7111 } 7112 7113 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7114 // have been legalized as a BITCAST from v4i32. 7115 if (N->getOpcode() == ISD::BITCAST) { 7116 SDNode *BVN = N->getOperand(0).getNode(); 7117 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7118 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7119 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7120 return DAG.getBuildVector( 7121 MVT::v2i32, SDLoc(N), 7122 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7123 } 7124 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7125 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7126 EVT VT = N->getValueType(0); 7127 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7128 unsigned NumElts = VT.getVectorNumElements(); 7129 MVT TruncVT = MVT::getIntegerVT(EltSize); 7130 SmallVector<SDValue, 8> Ops; 7131 SDLoc dl(N); 7132 for (unsigned i = 0; i != NumElts; ++i) { 7133 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7134 const APInt &CInt = C->getAPIntValue(); 7135 // Element types smaller than 32 bits are not legal, so use i32 elements. 7136 // The values are implicitly truncated so sext vs. zext doesn't matter. 7137 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7138 } 7139 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7140 } 7141 7142 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7143 unsigned Opcode = N->getOpcode(); 7144 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7145 SDNode *N0 = N->getOperand(0).getNode(); 7146 SDNode *N1 = N->getOperand(1).getNode(); 7147 return N0->hasOneUse() && N1->hasOneUse() && 7148 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7149 } 7150 return false; 7151 } 7152 7153 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7154 unsigned Opcode = N->getOpcode(); 7155 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7156 SDNode *N0 = N->getOperand(0).getNode(); 7157 SDNode *N1 = N->getOperand(1).getNode(); 7158 return N0->hasOneUse() && N1->hasOneUse() && 7159 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7160 } 7161 return false; 7162 } 7163 7164 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7165 // Multiplications are only custom-lowered for 128-bit vectors so that 7166 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7167 EVT VT = Op.getValueType(); 7168 assert(VT.is128BitVector() && VT.isInteger() && 7169 "unexpected type for custom-lowering ISD::MUL"); 7170 SDNode *N0 = Op.getOperand(0).getNode(); 7171 SDNode *N1 = Op.getOperand(1).getNode(); 7172 unsigned NewOpc = 0; 7173 bool isMLA = false; 7174 bool isN0SExt = isSignExtended(N0, DAG); 7175 bool isN1SExt = isSignExtended(N1, DAG); 7176 if (isN0SExt && isN1SExt) 7177 NewOpc = ARMISD::VMULLs; 7178 else { 7179 bool isN0ZExt = isZeroExtended(N0, DAG); 7180 bool isN1ZExt = isZeroExtended(N1, DAG); 7181 if (isN0ZExt && isN1ZExt) 7182 NewOpc = ARMISD::VMULLu; 7183 else if (isN1SExt || isN1ZExt) { 7184 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7185 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7186 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7187 NewOpc = ARMISD::VMULLs; 7188 isMLA = true; 7189 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7190 NewOpc = ARMISD::VMULLu; 7191 isMLA = true; 7192 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7193 std::swap(N0, N1); 7194 NewOpc = ARMISD::VMULLu; 7195 isMLA = true; 7196 } 7197 } 7198 7199 if (!NewOpc) { 7200 if (VT == MVT::v2i64) 7201 // Fall through to expand this. It is not legal. 7202 return SDValue(); 7203 else 7204 // Other vector multiplications are legal. 7205 return Op; 7206 } 7207 } 7208 7209 // Legalize to a VMULL instruction. 7210 SDLoc DL(Op); 7211 SDValue Op0; 7212 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7213 if (!isMLA) { 7214 Op0 = SkipExtensionForVMULL(N0, DAG); 7215 assert(Op0.getValueType().is64BitVector() && 7216 Op1.getValueType().is64BitVector() && 7217 "unexpected types for extended operands to VMULL"); 7218 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7219 } 7220 7221 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7222 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7223 // vmull q0, d4, d6 7224 // vmlal q0, d5, d6 7225 // is faster than 7226 // vaddl q0, d4, d5 7227 // vmovl q1, d6 7228 // vmul q0, q0, q1 7229 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7230 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7231 EVT Op1VT = Op1.getValueType(); 7232 return DAG.getNode(N0->getOpcode(), DL, VT, 7233 DAG.getNode(NewOpc, DL, VT, 7234 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7235 DAG.getNode(NewOpc, DL, VT, 7236 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7237 } 7238 7239 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7240 SelectionDAG &DAG) { 7241 // TODO: Should this propagate fast-math-flags? 7242 7243 // Convert to float 7244 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7245 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7246 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7247 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7248 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7249 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7250 // Get reciprocal estimate. 7251 // float4 recip = vrecpeq_f32(yf); 7252 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7253 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7254 Y); 7255 // Because char has a smaller range than uchar, we can actually get away 7256 // without any newton steps. This requires that we use a weird bias 7257 // of 0xb000, however (again, this has been exhaustively tested). 7258 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7259 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7260 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7261 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7262 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7263 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7264 // Convert back to short. 7265 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7266 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7267 return X; 7268 } 7269 7270 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7271 SelectionDAG &DAG) { 7272 // TODO: Should this propagate fast-math-flags? 7273 7274 SDValue N2; 7275 // Convert to float. 7276 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7277 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7278 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7279 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7280 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7281 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7282 7283 // Use reciprocal estimate and one refinement step. 7284 // float4 recip = vrecpeq_f32(yf); 7285 // recip *= vrecpsq_f32(yf, recip); 7286 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7287 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7288 N1); 7289 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7290 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7291 N1, N2); 7292 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7293 // Because short has a smaller range than ushort, we can actually get away 7294 // with only a single newton step. This requires that we use a weird bias 7295 // of 89, however (again, this has been exhaustively tested). 7296 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7297 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7298 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7299 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7300 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7301 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7302 // Convert back to integer and return. 7303 // return vmovn_s32(vcvt_s32_f32(result)); 7304 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7305 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7306 return N0; 7307 } 7308 7309 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7310 EVT VT = Op.getValueType(); 7311 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7312 "unexpected type for custom-lowering ISD::SDIV"); 7313 7314 SDLoc dl(Op); 7315 SDValue N0 = Op.getOperand(0); 7316 SDValue N1 = Op.getOperand(1); 7317 SDValue N2, N3; 7318 7319 if (VT == MVT::v8i8) { 7320 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7321 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7322 7323 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7324 DAG.getIntPtrConstant(4, dl)); 7325 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7326 DAG.getIntPtrConstant(4, dl)); 7327 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7328 DAG.getIntPtrConstant(0, dl)); 7329 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7330 DAG.getIntPtrConstant(0, dl)); 7331 7332 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7333 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7334 7335 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7336 N0 = LowerCONCAT_VECTORS(N0, DAG); 7337 7338 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7339 return N0; 7340 } 7341 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7342 } 7343 7344 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7345 // TODO: Should this propagate fast-math-flags? 7346 EVT VT = Op.getValueType(); 7347 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7348 "unexpected type for custom-lowering ISD::UDIV"); 7349 7350 SDLoc dl(Op); 7351 SDValue N0 = Op.getOperand(0); 7352 SDValue N1 = Op.getOperand(1); 7353 SDValue N2, N3; 7354 7355 if (VT == MVT::v8i8) { 7356 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7357 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7358 7359 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7360 DAG.getIntPtrConstant(4, dl)); 7361 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7362 DAG.getIntPtrConstant(4, dl)); 7363 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7364 DAG.getIntPtrConstant(0, dl)); 7365 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7366 DAG.getIntPtrConstant(0, dl)); 7367 7368 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7369 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7370 7371 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7372 N0 = LowerCONCAT_VECTORS(N0, DAG); 7373 7374 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7375 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7376 MVT::i32), 7377 N0); 7378 return N0; 7379 } 7380 7381 // v4i16 sdiv ... Convert to float. 7382 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7383 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7384 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7385 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7386 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7387 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7388 7389 // Use reciprocal estimate and two refinement steps. 7390 // float4 recip = vrecpeq_f32(yf); 7391 // recip *= vrecpsq_f32(yf, recip); 7392 // recip *= vrecpsq_f32(yf, recip); 7393 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7394 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7395 BN1); 7396 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7397 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7398 BN1, N2); 7399 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7400 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7401 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7402 BN1, N2); 7403 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7404 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7405 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7406 // and that it will never cause us to return an answer too large). 7407 // float4 result = as_float4(as_int4(xf*recip) + 2); 7408 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7409 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7410 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7411 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7412 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7413 // Convert back to integer and return. 7414 // return vmovn_u32(vcvt_s32_f32(result)); 7415 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7416 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7417 return N0; 7418 } 7419 7420 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7421 EVT VT = Op.getNode()->getValueType(0); 7422 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7423 7424 unsigned Opc; 7425 bool ExtraOp = false; 7426 switch (Op.getOpcode()) { 7427 default: llvm_unreachable("Invalid code"); 7428 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7429 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7430 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7431 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7432 } 7433 7434 if (!ExtraOp) 7435 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7436 Op.getOperand(1)); 7437 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7438 Op.getOperand(1), Op.getOperand(2)); 7439 } 7440 7441 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7442 SDNode *N = Op.getNode(); 7443 EVT VT = N->getValueType(0); 7444 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7445 7446 SDValue Carry = Op.getOperand(2); 7447 EVT CarryVT = Carry.getValueType(); 7448 7449 SDLoc DL(Op); 7450 7451 APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits()); 7452 7453 SDValue Result; 7454 if (Op.getOpcode() == ISD::ADDCARRY) { 7455 // This converts the boolean value carry into the carry flag. 7456 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7457 7458 // Do the addition proper using the carry flag we wanted. 7459 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7460 Op.getOperand(1), Carry.getValue(1)); 7461 7462 // Now convert the carry flag into a boolean value. 7463 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7464 } else { 7465 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7466 // have to invert the carry first. 7467 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7468 DAG.getConstant(1, DL, MVT::i32), Carry); 7469 // This converts the boolean value carry into the carry flag. 7470 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7471 7472 // Do the subtraction proper using the carry flag we wanted. 7473 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7474 Op.getOperand(1), Carry.getValue(1)); 7475 7476 // Now convert the carry flag into a boolean value. 7477 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7478 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7479 // by ISD::SUBCARRY, so compute 1 - C. 7480 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7481 DAG.getConstant(1, DL, MVT::i32), Carry); 7482 } 7483 7484 // Return both values. 7485 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7486 } 7487 7488 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7489 assert(Subtarget->isTargetDarwin()); 7490 7491 // For iOS, we want to call an alternative entry point: __sincos_stret, 7492 // return values are passed via sret. 7493 SDLoc dl(Op); 7494 SDValue Arg = Op.getOperand(0); 7495 EVT ArgVT = Arg.getValueType(); 7496 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7497 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7498 7499 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7500 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7501 7502 // Pair of floats / doubles used to pass the result. 7503 Type *RetTy = StructType::get(ArgTy, ArgTy); 7504 auto &DL = DAG.getDataLayout(); 7505 7506 ArgListTy Args; 7507 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7508 SDValue SRet; 7509 if (ShouldUseSRet) { 7510 // Create stack object for sret. 7511 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7512 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7513 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7514 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7515 7516 ArgListEntry Entry; 7517 Entry.Node = SRet; 7518 Entry.Ty = RetTy->getPointerTo(); 7519 Entry.IsSExt = false; 7520 Entry.IsZExt = false; 7521 Entry.IsSRet = true; 7522 Args.push_back(Entry); 7523 RetTy = Type::getVoidTy(*DAG.getContext()); 7524 } 7525 7526 ArgListEntry Entry; 7527 Entry.Node = Arg; 7528 Entry.Ty = ArgTy; 7529 Entry.IsSExt = false; 7530 Entry.IsZExt = false; 7531 Args.push_back(Entry); 7532 7533 const char *LibcallName = 7534 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 7535 RTLIB::Libcall LC = 7536 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 7537 CallingConv::ID CC = getLibcallCallingConv(LC); 7538 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7539 7540 TargetLowering::CallLoweringInfo CLI(DAG); 7541 CLI.setDebugLoc(dl) 7542 .setChain(DAG.getEntryNode()) 7543 .setCallee(CC, RetTy, Callee, std::move(Args)) 7544 .setDiscardResult(ShouldUseSRet); 7545 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7546 7547 if (!ShouldUseSRet) 7548 return CallResult.first; 7549 7550 SDValue LoadSin = 7551 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7552 7553 // Address of cos field. 7554 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7555 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7556 SDValue LoadCos = 7557 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7558 7559 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7560 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7561 LoadSin.getValue(0), LoadCos.getValue(0)); 7562 } 7563 7564 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7565 bool Signed, 7566 SDValue &Chain) const { 7567 EVT VT = Op.getValueType(); 7568 assert((VT == MVT::i32 || VT == MVT::i64) && 7569 "unexpected type for custom lowering DIV"); 7570 SDLoc dl(Op); 7571 7572 const auto &DL = DAG.getDataLayout(); 7573 const auto &TLI = DAG.getTargetLoweringInfo(); 7574 7575 const char *Name = nullptr; 7576 if (Signed) 7577 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7578 else 7579 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7580 7581 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7582 7583 ARMTargetLowering::ArgListTy Args; 7584 7585 for (auto AI : {1, 0}) { 7586 ArgListEntry Arg; 7587 Arg.Node = Op.getOperand(AI); 7588 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7589 Args.push_back(Arg); 7590 } 7591 7592 CallLoweringInfo CLI(DAG); 7593 CLI.setDebugLoc(dl) 7594 .setChain(Chain) 7595 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7596 ES, std::move(Args)); 7597 7598 return LowerCallTo(CLI).first; 7599 } 7600 7601 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7602 bool Signed) const { 7603 assert(Op.getValueType() == MVT::i32 && 7604 "unexpected type for custom lowering DIV"); 7605 SDLoc dl(Op); 7606 7607 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7608 DAG.getEntryNode(), Op.getOperand(1)); 7609 7610 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7611 } 7612 7613 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7614 SDLoc DL(N); 7615 SDValue Op = N->getOperand(1); 7616 if (N->getValueType(0) == MVT::i32) 7617 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7618 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7619 DAG.getConstant(0, DL, MVT::i32)); 7620 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7621 DAG.getConstant(1, DL, MVT::i32)); 7622 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7623 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7624 } 7625 7626 void ARMTargetLowering::ExpandDIV_Windows( 7627 SDValue Op, SelectionDAG &DAG, bool Signed, 7628 SmallVectorImpl<SDValue> &Results) const { 7629 const auto &DL = DAG.getDataLayout(); 7630 const auto &TLI = DAG.getTargetLoweringInfo(); 7631 7632 assert(Op.getValueType() == MVT::i64 && 7633 "unexpected type for custom lowering DIV"); 7634 SDLoc dl(Op); 7635 7636 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7637 7638 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7639 7640 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7641 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7642 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7643 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7644 7645 Results.push_back(Lower); 7646 Results.push_back(Upper); 7647 } 7648 7649 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7650 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7651 // Acquire/Release load/store is not legal for targets without a dmb or 7652 // equivalent available. 7653 return SDValue(); 7654 7655 // Monotonic load/store is legal for all targets. 7656 return Op; 7657 } 7658 7659 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7660 SmallVectorImpl<SDValue> &Results, 7661 SelectionDAG &DAG, 7662 const ARMSubtarget *Subtarget) { 7663 SDLoc DL(N); 7664 // Under Power Management extensions, the cycle-count is: 7665 // mrc p15, #0, <Rt>, c9, c13, #0 7666 SDValue Ops[] = { N->getOperand(0), // Chain 7667 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7668 DAG.getConstant(15, DL, MVT::i32), 7669 DAG.getConstant(0, DL, MVT::i32), 7670 DAG.getConstant(9, DL, MVT::i32), 7671 DAG.getConstant(13, DL, MVT::i32), 7672 DAG.getConstant(0, DL, MVT::i32) 7673 }; 7674 7675 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7676 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7677 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7678 DAG.getConstant(0, DL, MVT::i32))); 7679 Results.push_back(Cycles32.getValue(1)); 7680 } 7681 7682 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7683 SDLoc dl(V.getNode()); 7684 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7685 SDValue VHi = DAG.getAnyExtOrTrunc( 7686 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7687 dl, MVT::i32); 7688 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7689 if (isBigEndian) 7690 std::swap (VLo, VHi); 7691 SDValue RegClass = 7692 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7693 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7694 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7695 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7696 return SDValue( 7697 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7698 } 7699 7700 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7701 SmallVectorImpl<SDValue> & Results, 7702 SelectionDAG &DAG) { 7703 assert(N->getValueType(0) == MVT::i64 && 7704 "AtomicCmpSwap on types less than 64 should be legal"); 7705 SDValue Ops[] = {N->getOperand(1), 7706 createGPRPairNode(DAG, N->getOperand(2)), 7707 createGPRPairNode(DAG, N->getOperand(3)), 7708 N->getOperand(0)}; 7709 SDNode *CmpSwap = DAG.getMachineNode( 7710 ARM::CMP_SWAP_64, SDLoc(N), 7711 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7712 7713 MachineFunction &MF = DAG.getMachineFunction(); 7714 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7715 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7716 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7717 7718 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7719 7720 Results.push_back( 7721 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 7722 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7723 Results.push_back( 7724 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 7725 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7726 Results.push_back(SDValue(CmpSwap, 2)); 7727 } 7728 7729 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7730 SelectionDAG &DAG) { 7731 const auto &TLI = DAG.getTargetLoweringInfo(); 7732 7733 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7734 "Custom lowering is MSVCRT specific!"); 7735 7736 SDLoc dl(Op); 7737 SDValue Val = Op.getOperand(0); 7738 MVT Ty = Val->getSimpleValueType(0); 7739 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7740 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7741 TLI.getPointerTy(DAG.getDataLayout())); 7742 7743 TargetLowering::ArgListTy Args; 7744 TargetLowering::ArgListEntry Entry; 7745 7746 Entry.Node = Val; 7747 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7748 Entry.IsZExt = true; 7749 Args.push_back(Entry); 7750 7751 Entry.Node = Exponent; 7752 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7753 Entry.IsZExt = true; 7754 Args.push_back(Entry); 7755 7756 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7757 7758 // In the in-chain to the call is the entry node If we are emitting a 7759 // tailcall, the chain will be mutated if the node has a non-entry input 7760 // chain. 7761 SDValue InChain = DAG.getEntryNode(); 7762 SDValue TCChain = InChain; 7763 7764 const auto *F = DAG.getMachineFunction().getFunction(); 7765 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 7766 F->getReturnType() == LCRTy; 7767 if (IsTC) 7768 InChain = TCChain; 7769 7770 TargetLowering::CallLoweringInfo CLI(DAG); 7771 CLI.setDebugLoc(dl) 7772 .setChain(InChain) 7773 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 7774 .setTailCall(IsTC); 7775 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 7776 7777 // Return the chain (the DAG root) if it is a tail call 7778 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 7779 } 7780 7781 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7782 DEBUG(dbgs() << "Lowering node: "; Op.dump()); 7783 switch (Op.getOpcode()) { 7784 default: llvm_unreachable("Don't know how to custom lower this!"); 7785 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7786 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7787 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7788 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 7789 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7790 case ISD::SELECT: return LowerSELECT(Op, DAG); 7791 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7792 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7793 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7794 case ISD::VASTART: return LowerVASTART(Op, DAG); 7795 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7796 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7797 case ISD::SINT_TO_FP: 7798 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7799 case ISD::FP_TO_SINT: 7800 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7801 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7802 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7803 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7804 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7805 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7806 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7807 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7808 Subtarget); 7809 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7810 case ISD::SHL: 7811 case ISD::SRL: 7812 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7813 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7814 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7815 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7816 case ISD::SRL_PARTS: 7817 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7818 case ISD::CTTZ: 7819 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7820 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7821 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7822 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7823 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7824 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7825 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7826 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7827 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7828 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7829 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7830 case ISD::MUL: return LowerMUL(Op, DAG); 7831 case ISD::SDIV: 7832 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7833 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7834 return LowerSDIV(Op, DAG); 7835 case ISD::UDIV: 7836 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7837 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7838 return LowerUDIV(Op, DAG); 7839 case ISD::ADDC: 7840 case ISD::ADDE: 7841 case ISD::SUBC: 7842 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7843 case ISD::ADDCARRY: 7844 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 7845 case ISD::SADDO: 7846 case ISD::SSUBO: 7847 return LowerSignedALUO(Op, DAG); 7848 case ISD::UADDO: 7849 case ISD::USUBO: 7850 return LowerUnsignedALUO(Op, DAG); 7851 case ISD::ATOMIC_LOAD: 7852 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7853 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7854 case ISD::SDIVREM: 7855 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7856 case ISD::DYNAMIC_STACKALLOC: 7857 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7858 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7859 llvm_unreachable("Don't know how to custom lower this!"); 7860 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7861 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7862 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 7863 case ARMISD::WIN__DBZCHK: return SDValue(); 7864 } 7865 } 7866 7867 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 7868 SelectionDAG &DAG) { 7869 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7870 unsigned Opc = 0; 7871 if (IntNo == Intrinsic::arm_smlald) 7872 Opc = ARMISD::SMLALD; 7873 else if (IntNo == Intrinsic::arm_smlaldx) 7874 Opc = ARMISD::SMLALDX; 7875 else if (IntNo == Intrinsic::arm_smlsld) 7876 Opc = ARMISD::SMLSLD; 7877 else if (IntNo == Intrinsic::arm_smlsldx) 7878 Opc = ARMISD::SMLSLDX; 7879 else 7880 return; 7881 7882 SDLoc dl(N); 7883 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7884 N->getOperand(3), 7885 DAG.getConstant(0, dl, MVT::i32)); 7886 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7887 N->getOperand(3), 7888 DAG.getConstant(1, dl, MVT::i32)); 7889 7890 SDValue LongMul = DAG.getNode(Opc, dl, 7891 DAG.getVTList(MVT::i32, MVT::i32), 7892 N->getOperand(1), N->getOperand(2), 7893 Lo, Hi); 7894 Results.push_back(LongMul.getValue(0)); 7895 Results.push_back(LongMul.getValue(1)); 7896 } 7897 7898 /// ReplaceNodeResults - Replace the results of node with an illegal result 7899 /// type with new values built out of custom code. 7900 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7901 SmallVectorImpl<SDValue> &Results, 7902 SelectionDAG &DAG) const { 7903 SDValue Res; 7904 switch (N->getOpcode()) { 7905 default: 7906 llvm_unreachable("Don't know how to custom expand this!"); 7907 case ISD::READ_REGISTER: 7908 ExpandREAD_REGISTER(N, Results, DAG); 7909 break; 7910 case ISD::BITCAST: 7911 Res = ExpandBITCAST(N, DAG); 7912 break; 7913 case ISD::SRL: 7914 case ISD::SRA: 7915 Res = Expand64BitShift(N, DAG, Subtarget); 7916 break; 7917 case ISD::SREM: 7918 case ISD::UREM: 7919 Res = LowerREM(N, DAG); 7920 break; 7921 case ISD::SDIVREM: 7922 case ISD::UDIVREM: 7923 Res = LowerDivRem(SDValue(N, 0), DAG); 7924 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7925 Results.push_back(Res.getValue(0)); 7926 Results.push_back(Res.getValue(1)); 7927 return; 7928 case ISD::READCYCLECOUNTER: 7929 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7930 return; 7931 case ISD::UDIV: 7932 case ISD::SDIV: 7933 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7934 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7935 Results); 7936 case ISD::ATOMIC_CMP_SWAP: 7937 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7938 return; 7939 case ISD::INTRINSIC_WO_CHAIN: 7940 return ReplaceLongIntrinsic(N, Results, DAG); 7941 } 7942 if (Res.getNode()) 7943 Results.push_back(Res); 7944 } 7945 7946 //===----------------------------------------------------------------------===// 7947 // ARM Scheduler Hooks 7948 //===----------------------------------------------------------------------===// 7949 7950 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7951 /// registers the function context. 7952 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 7953 MachineBasicBlock *MBB, 7954 MachineBasicBlock *DispatchBB, 7955 int FI) const { 7956 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 7957 "ROPI/RWPI not currently supported with SjLj"); 7958 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7959 DebugLoc dl = MI.getDebugLoc(); 7960 MachineFunction *MF = MBB->getParent(); 7961 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7962 MachineConstantPool *MCP = MF->getConstantPool(); 7963 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7964 const Function *F = MF->getFunction(); 7965 7966 bool isThumb = Subtarget->isThumb(); 7967 bool isThumb2 = Subtarget->isThumb2(); 7968 7969 unsigned PCLabelId = AFI->createPICLabelUId(); 7970 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7971 ARMConstantPoolValue *CPV = 7972 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7973 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7974 7975 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7976 : &ARM::GPRRegClass; 7977 7978 // Grab constant pool and fixed stack memory operands. 7979 MachineMemOperand *CPMMO = 7980 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7981 MachineMemOperand::MOLoad, 4, 4); 7982 7983 MachineMemOperand *FIMMOSt = 7984 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7985 MachineMemOperand::MOStore, 4, 4); 7986 7987 // Load the address of the dispatch MBB into the jump buffer. 7988 if (isThumb2) { 7989 // Incoming value: jbuf 7990 // ldr.n r5, LCPI1_1 7991 // orr r5, r5, #1 7992 // add r5, pc 7993 // str r5, [$jbuf, #+4] ; &jbuf[1] 7994 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7995 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7996 .addConstantPoolIndex(CPI) 7997 .addMemOperand(CPMMO) 7998 .add(predOps(ARMCC::AL)); 7999 // Set the low bit because of thumb mode. 8000 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8001 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8002 .addReg(NewVReg1, RegState::Kill) 8003 .addImm(0x01) 8004 .add(predOps(ARMCC::AL)) 8005 .add(condCodeOp()); 8006 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8007 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8008 .addReg(NewVReg2, RegState::Kill) 8009 .addImm(PCLabelId); 8010 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8011 .addReg(NewVReg3, RegState::Kill) 8012 .addFrameIndex(FI) 8013 .addImm(36) // &jbuf[1] :: pc 8014 .addMemOperand(FIMMOSt) 8015 .add(predOps(ARMCC::AL)); 8016 } else if (isThumb) { 8017 // Incoming value: jbuf 8018 // ldr.n r1, LCPI1_4 8019 // add r1, pc 8020 // mov r2, #1 8021 // orrs r1, r2 8022 // add r2, $jbuf, #+4 ; &jbuf[1] 8023 // str r1, [r2] 8024 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8025 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8026 .addConstantPoolIndex(CPI) 8027 .addMemOperand(CPMMO) 8028 .add(predOps(ARMCC::AL)); 8029 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8030 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8031 .addReg(NewVReg1, RegState::Kill) 8032 .addImm(PCLabelId); 8033 // Set the low bit because of thumb mode. 8034 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8035 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8036 .addReg(ARM::CPSR, RegState::Define) 8037 .addImm(1) 8038 .add(predOps(ARMCC::AL)); 8039 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8040 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8041 .addReg(ARM::CPSR, RegState::Define) 8042 .addReg(NewVReg2, RegState::Kill) 8043 .addReg(NewVReg3, RegState::Kill) 8044 .add(predOps(ARMCC::AL)); 8045 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8046 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8047 .addFrameIndex(FI) 8048 .addImm(36); // &jbuf[1] :: pc 8049 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8050 .addReg(NewVReg4, RegState::Kill) 8051 .addReg(NewVReg5, RegState::Kill) 8052 .addImm(0) 8053 .addMemOperand(FIMMOSt) 8054 .add(predOps(ARMCC::AL)); 8055 } else { 8056 // Incoming value: jbuf 8057 // ldr r1, LCPI1_1 8058 // add r1, pc, r1 8059 // str r1, [$jbuf, #+4] ; &jbuf[1] 8060 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8061 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8062 .addConstantPoolIndex(CPI) 8063 .addImm(0) 8064 .addMemOperand(CPMMO) 8065 .add(predOps(ARMCC::AL)); 8066 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8067 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8068 .addReg(NewVReg1, RegState::Kill) 8069 .addImm(PCLabelId) 8070 .add(predOps(ARMCC::AL)); 8071 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8072 .addReg(NewVReg2, RegState::Kill) 8073 .addFrameIndex(FI) 8074 .addImm(36) // &jbuf[1] :: pc 8075 .addMemOperand(FIMMOSt) 8076 .add(predOps(ARMCC::AL)); 8077 } 8078 } 8079 8080 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8081 MachineBasicBlock *MBB) const { 8082 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8083 DebugLoc dl = MI.getDebugLoc(); 8084 MachineFunction *MF = MBB->getParent(); 8085 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8086 MachineFrameInfo &MFI = MF->getFrameInfo(); 8087 int FI = MFI.getFunctionContextIndex(); 8088 8089 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8090 : &ARM::GPRnopcRegClass; 8091 8092 // Get a mapping of the call site numbers to all of the landing pads they're 8093 // associated with. 8094 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8095 unsigned MaxCSNum = 0; 8096 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8097 ++BB) { 8098 if (!BB->isEHPad()) continue; 8099 8100 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8101 // pad. 8102 for (MachineBasicBlock::iterator 8103 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8104 if (!II->isEHLabel()) continue; 8105 8106 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8107 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8108 8109 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8110 for (SmallVectorImpl<unsigned>::iterator 8111 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8112 CSI != CSE; ++CSI) { 8113 CallSiteNumToLPad[*CSI].push_back(&*BB); 8114 MaxCSNum = std::max(MaxCSNum, *CSI); 8115 } 8116 break; 8117 } 8118 } 8119 8120 // Get an ordered list of the machine basic blocks for the jump table. 8121 std::vector<MachineBasicBlock*> LPadList; 8122 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8123 LPadList.reserve(CallSiteNumToLPad.size()); 8124 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8125 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8126 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8127 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8128 LPadList.push_back(*II); 8129 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8130 } 8131 } 8132 8133 assert(!LPadList.empty() && 8134 "No landing pad destinations for the dispatch jump table!"); 8135 8136 // Create the jump table and associated information. 8137 MachineJumpTableInfo *JTI = 8138 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8139 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8140 8141 // Create the MBBs for the dispatch code. 8142 8143 // Shove the dispatch's address into the return slot in the function context. 8144 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8145 DispatchBB->setIsEHPad(); 8146 8147 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8148 unsigned trap_opcode; 8149 if (Subtarget->isThumb()) 8150 trap_opcode = ARM::tTRAP; 8151 else 8152 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8153 8154 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8155 DispatchBB->addSuccessor(TrapBB); 8156 8157 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8158 DispatchBB->addSuccessor(DispContBB); 8159 8160 // Insert and MBBs. 8161 MF->insert(MF->end(), DispatchBB); 8162 MF->insert(MF->end(), DispContBB); 8163 MF->insert(MF->end(), TrapBB); 8164 8165 // Insert code into the entry block that creates and registers the function 8166 // context. 8167 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8168 8169 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8170 MachinePointerInfo::getFixedStack(*MF, FI), 8171 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8172 8173 MachineInstrBuilder MIB; 8174 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8175 8176 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8177 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8178 8179 // Add a register mask with no preserved registers. This results in all 8180 // registers being marked as clobbered. This can't work if the dispatch block 8181 // is in a Thumb1 function and is linked with ARM code which uses the FP 8182 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8183 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8184 8185 bool IsPositionIndependent = isPositionIndependent(); 8186 unsigned NumLPads = LPadList.size(); 8187 if (Subtarget->isThumb2()) { 8188 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8189 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8190 .addFrameIndex(FI) 8191 .addImm(4) 8192 .addMemOperand(FIMMOLd) 8193 .add(predOps(ARMCC::AL)); 8194 8195 if (NumLPads < 256) { 8196 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8197 .addReg(NewVReg1) 8198 .addImm(LPadList.size()) 8199 .add(predOps(ARMCC::AL)); 8200 } else { 8201 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8202 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8203 .addImm(NumLPads & 0xFFFF) 8204 .add(predOps(ARMCC::AL)); 8205 8206 unsigned VReg2 = VReg1; 8207 if ((NumLPads & 0xFFFF0000) != 0) { 8208 VReg2 = MRI->createVirtualRegister(TRC); 8209 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8210 .addReg(VReg1) 8211 .addImm(NumLPads >> 16) 8212 .add(predOps(ARMCC::AL)); 8213 } 8214 8215 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8216 .addReg(NewVReg1) 8217 .addReg(VReg2) 8218 .add(predOps(ARMCC::AL)); 8219 } 8220 8221 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8222 .addMBB(TrapBB) 8223 .addImm(ARMCC::HI) 8224 .addReg(ARM::CPSR); 8225 8226 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8227 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8228 .addJumpTableIndex(MJTI) 8229 .add(predOps(ARMCC::AL)); 8230 8231 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8232 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8233 .addReg(NewVReg3, RegState::Kill) 8234 .addReg(NewVReg1) 8235 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8236 .add(predOps(ARMCC::AL)) 8237 .add(condCodeOp()); 8238 8239 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8240 .addReg(NewVReg4, RegState::Kill) 8241 .addReg(NewVReg1) 8242 .addJumpTableIndex(MJTI); 8243 } else if (Subtarget->isThumb()) { 8244 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8245 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8246 .addFrameIndex(FI) 8247 .addImm(1) 8248 .addMemOperand(FIMMOLd) 8249 .add(predOps(ARMCC::AL)); 8250 8251 if (NumLPads < 256) { 8252 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8253 .addReg(NewVReg1) 8254 .addImm(NumLPads) 8255 .add(predOps(ARMCC::AL)); 8256 } else { 8257 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8258 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8259 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8260 8261 // MachineConstantPool wants an explicit alignment. 8262 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8263 if (Align == 0) 8264 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8265 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8266 8267 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8268 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8269 .addReg(VReg1, RegState::Define) 8270 .addConstantPoolIndex(Idx) 8271 .add(predOps(ARMCC::AL)); 8272 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8273 .addReg(NewVReg1) 8274 .addReg(VReg1) 8275 .add(predOps(ARMCC::AL)); 8276 } 8277 8278 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8279 .addMBB(TrapBB) 8280 .addImm(ARMCC::HI) 8281 .addReg(ARM::CPSR); 8282 8283 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8284 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8285 .addReg(ARM::CPSR, RegState::Define) 8286 .addReg(NewVReg1) 8287 .addImm(2) 8288 .add(predOps(ARMCC::AL)); 8289 8290 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8291 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8292 .addJumpTableIndex(MJTI) 8293 .add(predOps(ARMCC::AL)); 8294 8295 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8296 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8297 .addReg(ARM::CPSR, RegState::Define) 8298 .addReg(NewVReg2, RegState::Kill) 8299 .addReg(NewVReg3) 8300 .add(predOps(ARMCC::AL)); 8301 8302 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8303 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8304 8305 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8306 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8307 .addReg(NewVReg4, RegState::Kill) 8308 .addImm(0) 8309 .addMemOperand(JTMMOLd) 8310 .add(predOps(ARMCC::AL)); 8311 8312 unsigned NewVReg6 = NewVReg5; 8313 if (IsPositionIndependent) { 8314 NewVReg6 = MRI->createVirtualRegister(TRC); 8315 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8316 .addReg(ARM::CPSR, RegState::Define) 8317 .addReg(NewVReg5, RegState::Kill) 8318 .addReg(NewVReg3) 8319 .add(predOps(ARMCC::AL)); 8320 } 8321 8322 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8323 .addReg(NewVReg6, RegState::Kill) 8324 .addJumpTableIndex(MJTI); 8325 } else { 8326 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8327 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8328 .addFrameIndex(FI) 8329 .addImm(4) 8330 .addMemOperand(FIMMOLd) 8331 .add(predOps(ARMCC::AL)); 8332 8333 if (NumLPads < 256) { 8334 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8335 .addReg(NewVReg1) 8336 .addImm(NumLPads) 8337 .add(predOps(ARMCC::AL)); 8338 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8339 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8340 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8341 .addImm(NumLPads & 0xFFFF) 8342 .add(predOps(ARMCC::AL)); 8343 8344 unsigned VReg2 = VReg1; 8345 if ((NumLPads & 0xFFFF0000) != 0) { 8346 VReg2 = MRI->createVirtualRegister(TRC); 8347 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8348 .addReg(VReg1) 8349 .addImm(NumLPads >> 16) 8350 .add(predOps(ARMCC::AL)); 8351 } 8352 8353 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8354 .addReg(NewVReg1) 8355 .addReg(VReg2) 8356 .add(predOps(ARMCC::AL)); 8357 } else { 8358 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8359 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8360 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8361 8362 // MachineConstantPool wants an explicit alignment. 8363 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8364 if (Align == 0) 8365 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8366 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8367 8368 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8369 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8370 .addReg(VReg1, RegState::Define) 8371 .addConstantPoolIndex(Idx) 8372 .addImm(0) 8373 .add(predOps(ARMCC::AL)); 8374 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8375 .addReg(NewVReg1) 8376 .addReg(VReg1, RegState::Kill) 8377 .add(predOps(ARMCC::AL)); 8378 } 8379 8380 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8381 .addMBB(TrapBB) 8382 .addImm(ARMCC::HI) 8383 .addReg(ARM::CPSR); 8384 8385 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8386 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8387 .addReg(NewVReg1) 8388 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8389 .add(predOps(ARMCC::AL)) 8390 .add(condCodeOp()); 8391 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8392 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8393 .addJumpTableIndex(MJTI) 8394 .add(predOps(ARMCC::AL)); 8395 8396 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8397 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8398 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8399 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8400 .addReg(NewVReg3, RegState::Kill) 8401 .addReg(NewVReg4) 8402 .addImm(0) 8403 .addMemOperand(JTMMOLd) 8404 .add(predOps(ARMCC::AL)); 8405 8406 if (IsPositionIndependent) { 8407 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8408 .addReg(NewVReg5, RegState::Kill) 8409 .addReg(NewVReg4) 8410 .addJumpTableIndex(MJTI); 8411 } else { 8412 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8413 .addReg(NewVReg5, RegState::Kill) 8414 .addJumpTableIndex(MJTI); 8415 } 8416 } 8417 8418 // Add the jump table entries as successors to the MBB. 8419 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8420 for (std::vector<MachineBasicBlock*>::iterator 8421 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8422 MachineBasicBlock *CurMBB = *I; 8423 if (SeenMBBs.insert(CurMBB).second) 8424 DispContBB->addSuccessor(CurMBB); 8425 } 8426 8427 // N.B. the order the invoke BBs are processed in doesn't matter here. 8428 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8429 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8430 for (MachineBasicBlock *BB : InvokeBBs) { 8431 8432 // Remove the landing pad successor from the invoke block and replace it 8433 // with the new dispatch block. 8434 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8435 BB->succ_end()); 8436 while (!Successors.empty()) { 8437 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8438 if (SMBB->isEHPad()) { 8439 BB->removeSuccessor(SMBB); 8440 MBBLPads.push_back(SMBB); 8441 } 8442 } 8443 8444 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8445 BB->normalizeSuccProbs(); 8446 8447 // Find the invoke call and mark all of the callee-saved registers as 8448 // 'implicit defined' so that they're spilled. This prevents code from 8449 // moving instructions to before the EH block, where they will never be 8450 // executed. 8451 for (MachineBasicBlock::reverse_iterator 8452 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8453 if (!II->isCall()) continue; 8454 8455 DenseMap<unsigned, bool> DefRegs; 8456 for (MachineInstr::mop_iterator 8457 OI = II->operands_begin(), OE = II->operands_end(); 8458 OI != OE; ++OI) { 8459 if (!OI->isReg()) continue; 8460 DefRegs[OI->getReg()] = true; 8461 } 8462 8463 MachineInstrBuilder MIB(*MF, &*II); 8464 8465 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8466 unsigned Reg = SavedRegs[i]; 8467 if (Subtarget->isThumb2() && 8468 !ARM::tGPRRegClass.contains(Reg) && 8469 !ARM::hGPRRegClass.contains(Reg)) 8470 continue; 8471 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8472 continue; 8473 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8474 continue; 8475 if (!DefRegs[Reg]) 8476 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8477 } 8478 8479 break; 8480 } 8481 } 8482 8483 // Mark all former landing pads as non-landing pads. The dispatch is the only 8484 // landing pad now. 8485 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8486 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8487 (*I)->setIsEHPad(false); 8488 8489 // The instruction is gone now. 8490 MI.eraseFromParent(); 8491 } 8492 8493 static 8494 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8495 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8496 E = MBB->succ_end(); I != E; ++I) 8497 if (*I != Succ) 8498 return *I; 8499 llvm_unreachable("Expecting a BB with two successors!"); 8500 } 8501 8502 /// Return the load opcode for a given load size. If load size >= 8, 8503 /// neon opcode will be returned. 8504 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8505 if (LdSize >= 8) 8506 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8507 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8508 if (IsThumb1) 8509 return LdSize == 4 ? ARM::tLDRi 8510 : LdSize == 2 ? ARM::tLDRHi 8511 : LdSize == 1 ? ARM::tLDRBi : 0; 8512 if (IsThumb2) 8513 return LdSize == 4 ? ARM::t2LDR_POST 8514 : LdSize == 2 ? ARM::t2LDRH_POST 8515 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8516 return LdSize == 4 ? ARM::LDR_POST_IMM 8517 : LdSize == 2 ? ARM::LDRH_POST 8518 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8519 } 8520 8521 /// Return the store opcode for a given store size. If store size >= 8, 8522 /// neon opcode will be returned. 8523 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8524 if (StSize >= 8) 8525 return StSize == 16 ? ARM::VST1q32wb_fixed 8526 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8527 if (IsThumb1) 8528 return StSize == 4 ? ARM::tSTRi 8529 : StSize == 2 ? ARM::tSTRHi 8530 : StSize == 1 ? ARM::tSTRBi : 0; 8531 if (IsThumb2) 8532 return StSize == 4 ? ARM::t2STR_POST 8533 : StSize == 2 ? ARM::t2STRH_POST 8534 : StSize == 1 ? ARM::t2STRB_POST : 0; 8535 return StSize == 4 ? ARM::STR_POST_IMM 8536 : StSize == 2 ? ARM::STRH_POST 8537 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8538 } 8539 8540 /// Emit a post-increment load operation with given size. The instructions 8541 /// will be added to BB at Pos. 8542 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8543 const TargetInstrInfo *TII, const DebugLoc &dl, 8544 unsigned LdSize, unsigned Data, unsigned AddrIn, 8545 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8546 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8547 assert(LdOpc != 0 && "Should have a load opcode"); 8548 if (LdSize >= 8) { 8549 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8550 .addReg(AddrOut, RegState::Define) 8551 .addReg(AddrIn) 8552 .addImm(0) 8553 .add(predOps(ARMCC::AL)); 8554 } else if (IsThumb1) { 8555 // load + update AddrIn 8556 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8557 .addReg(AddrIn) 8558 .addImm(0) 8559 .add(predOps(ARMCC::AL)); 8560 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8561 .add(t1CondCodeOp()) 8562 .addReg(AddrIn) 8563 .addImm(LdSize) 8564 .add(predOps(ARMCC::AL)); 8565 } else if (IsThumb2) { 8566 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8567 .addReg(AddrOut, RegState::Define) 8568 .addReg(AddrIn) 8569 .addImm(LdSize) 8570 .add(predOps(ARMCC::AL)); 8571 } else { // arm 8572 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8573 .addReg(AddrOut, RegState::Define) 8574 .addReg(AddrIn) 8575 .addReg(0) 8576 .addImm(LdSize) 8577 .add(predOps(ARMCC::AL)); 8578 } 8579 } 8580 8581 /// Emit a post-increment store operation with given size. The instructions 8582 /// will be added to BB at Pos. 8583 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8584 const TargetInstrInfo *TII, const DebugLoc &dl, 8585 unsigned StSize, unsigned Data, unsigned AddrIn, 8586 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8587 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8588 assert(StOpc != 0 && "Should have a store opcode"); 8589 if (StSize >= 8) { 8590 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8591 .addReg(AddrIn) 8592 .addImm(0) 8593 .addReg(Data) 8594 .add(predOps(ARMCC::AL)); 8595 } else if (IsThumb1) { 8596 // store + update AddrIn 8597 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8598 .addReg(Data) 8599 .addReg(AddrIn) 8600 .addImm(0) 8601 .add(predOps(ARMCC::AL)); 8602 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8603 .add(t1CondCodeOp()) 8604 .addReg(AddrIn) 8605 .addImm(StSize) 8606 .add(predOps(ARMCC::AL)); 8607 } else if (IsThumb2) { 8608 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8609 .addReg(Data) 8610 .addReg(AddrIn) 8611 .addImm(StSize) 8612 .add(predOps(ARMCC::AL)); 8613 } else { // arm 8614 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8615 .addReg(Data) 8616 .addReg(AddrIn) 8617 .addReg(0) 8618 .addImm(StSize) 8619 .add(predOps(ARMCC::AL)); 8620 } 8621 } 8622 8623 MachineBasicBlock * 8624 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8625 MachineBasicBlock *BB) const { 8626 // This pseudo instruction has 3 operands: dst, src, size 8627 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8628 // Otherwise, we will generate unrolled scalar copies. 8629 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8630 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8631 MachineFunction::iterator It = ++BB->getIterator(); 8632 8633 unsigned dest = MI.getOperand(0).getReg(); 8634 unsigned src = MI.getOperand(1).getReg(); 8635 unsigned SizeVal = MI.getOperand(2).getImm(); 8636 unsigned Align = MI.getOperand(3).getImm(); 8637 DebugLoc dl = MI.getDebugLoc(); 8638 8639 MachineFunction *MF = BB->getParent(); 8640 MachineRegisterInfo &MRI = MF->getRegInfo(); 8641 unsigned UnitSize = 0; 8642 const TargetRegisterClass *TRC = nullptr; 8643 const TargetRegisterClass *VecTRC = nullptr; 8644 8645 bool IsThumb1 = Subtarget->isThumb1Only(); 8646 bool IsThumb2 = Subtarget->isThumb2(); 8647 bool IsThumb = Subtarget->isThumb(); 8648 8649 if (Align & 1) { 8650 UnitSize = 1; 8651 } else if (Align & 2) { 8652 UnitSize = 2; 8653 } else { 8654 // Check whether we can use NEON instructions. 8655 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 8656 Subtarget->hasNEON()) { 8657 if ((Align % 16 == 0) && SizeVal >= 16) 8658 UnitSize = 16; 8659 else if ((Align % 8 == 0) && SizeVal >= 8) 8660 UnitSize = 8; 8661 } 8662 // Can't use NEON instructions. 8663 if (UnitSize == 0) 8664 UnitSize = 4; 8665 } 8666 8667 // Select the correct opcode and register class for unit size load/store 8668 bool IsNeon = UnitSize >= 8; 8669 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8670 if (IsNeon) 8671 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8672 : UnitSize == 8 ? &ARM::DPRRegClass 8673 : nullptr; 8674 8675 unsigned BytesLeft = SizeVal % UnitSize; 8676 unsigned LoopSize = SizeVal - BytesLeft; 8677 8678 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8679 // Use LDR and STR to copy. 8680 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8681 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8682 unsigned srcIn = src; 8683 unsigned destIn = dest; 8684 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8685 unsigned srcOut = MRI.createVirtualRegister(TRC); 8686 unsigned destOut = MRI.createVirtualRegister(TRC); 8687 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8688 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8689 IsThumb1, IsThumb2); 8690 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8691 IsThumb1, IsThumb2); 8692 srcIn = srcOut; 8693 destIn = destOut; 8694 } 8695 8696 // Handle the leftover bytes with LDRB and STRB. 8697 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8698 // [destOut] = STRB_POST(scratch, destIn, 1) 8699 for (unsigned i = 0; i < BytesLeft; i++) { 8700 unsigned srcOut = MRI.createVirtualRegister(TRC); 8701 unsigned destOut = MRI.createVirtualRegister(TRC); 8702 unsigned scratch = MRI.createVirtualRegister(TRC); 8703 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8704 IsThumb1, IsThumb2); 8705 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8706 IsThumb1, IsThumb2); 8707 srcIn = srcOut; 8708 destIn = destOut; 8709 } 8710 MI.eraseFromParent(); // The instruction is gone now. 8711 return BB; 8712 } 8713 8714 // Expand the pseudo op to a loop. 8715 // thisMBB: 8716 // ... 8717 // movw varEnd, # --> with thumb2 8718 // movt varEnd, # 8719 // ldrcp varEnd, idx --> without thumb2 8720 // fallthrough --> loopMBB 8721 // loopMBB: 8722 // PHI varPhi, varEnd, varLoop 8723 // PHI srcPhi, src, srcLoop 8724 // PHI destPhi, dst, destLoop 8725 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8726 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8727 // subs varLoop, varPhi, #UnitSize 8728 // bne loopMBB 8729 // fallthrough --> exitMBB 8730 // exitMBB: 8731 // epilogue to handle left-over bytes 8732 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8733 // [destOut] = STRB_POST(scratch, destLoop, 1) 8734 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8735 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8736 MF->insert(It, loopMBB); 8737 MF->insert(It, exitMBB); 8738 8739 // Transfer the remainder of BB and its successor edges to exitMBB. 8740 exitMBB->splice(exitMBB->begin(), BB, 8741 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8742 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8743 8744 // Load an immediate to varEnd. 8745 unsigned varEnd = MRI.createVirtualRegister(TRC); 8746 if (Subtarget->useMovt(*MF)) { 8747 unsigned Vtmp = varEnd; 8748 if ((LoopSize & 0xFFFF0000) != 0) 8749 Vtmp = MRI.createVirtualRegister(TRC); 8750 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8751 .addImm(LoopSize & 0xFFFF) 8752 .add(predOps(ARMCC::AL)); 8753 8754 if ((LoopSize & 0xFFFF0000) != 0) 8755 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 8756 .addReg(Vtmp) 8757 .addImm(LoopSize >> 16) 8758 .add(predOps(ARMCC::AL)); 8759 } else { 8760 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8761 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8762 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8763 8764 // MachineConstantPool wants an explicit alignment. 8765 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8766 if (Align == 0) 8767 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8768 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8769 8770 if (IsThumb) 8771 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 8772 .addReg(varEnd, RegState::Define) 8773 .addConstantPoolIndex(Idx) 8774 .add(predOps(ARMCC::AL)); 8775 else 8776 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 8777 .addReg(varEnd, RegState::Define) 8778 .addConstantPoolIndex(Idx) 8779 .addImm(0) 8780 .add(predOps(ARMCC::AL)); 8781 } 8782 BB->addSuccessor(loopMBB); 8783 8784 // Generate the loop body: 8785 // varPhi = PHI(varLoop, varEnd) 8786 // srcPhi = PHI(srcLoop, src) 8787 // destPhi = PHI(destLoop, dst) 8788 MachineBasicBlock *entryBB = BB; 8789 BB = loopMBB; 8790 unsigned varLoop = MRI.createVirtualRegister(TRC); 8791 unsigned varPhi = MRI.createVirtualRegister(TRC); 8792 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8793 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8794 unsigned destLoop = MRI.createVirtualRegister(TRC); 8795 unsigned destPhi = MRI.createVirtualRegister(TRC); 8796 8797 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8798 .addReg(varLoop).addMBB(loopMBB) 8799 .addReg(varEnd).addMBB(entryBB); 8800 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8801 .addReg(srcLoop).addMBB(loopMBB) 8802 .addReg(src).addMBB(entryBB); 8803 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8804 .addReg(destLoop).addMBB(loopMBB) 8805 .addReg(dest).addMBB(entryBB); 8806 8807 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8808 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8809 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8810 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8811 IsThumb1, IsThumb2); 8812 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8813 IsThumb1, IsThumb2); 8814 8815 // Decrement loop variable by UnitSize. 8816 if (IsThumb1) { 8817 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 8818 .add(t1CondCodeOp()) 8819 .addReg(varPhi) 8820 .addImm(UnitSize) 8821 .add(predOps(ARMCC::AL)); 8822 } else { 8823 MachineInstrBuilder MIB = 8824 BuildMI(*BB, BB->end(), dl, 8825 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8826 MIB.addReg(varPhi) 8827 .addImm(UnitSize) 8828 .add(predOps(ARMCC::AL)) 8829 .add(condCodeOp()); 8830 MIB->getOperand(5).setReg(ARM::CPSR); 8831 MIB->getOperand(5).setIsDef(true); 8832 } 8833 BuildMI(*BB, BB->end(), dl, 8834 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8835 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8836 8837 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8838 BB->addSuccessor(loopMBB); 8839 BB->addSuccessor(exitMBB); 8840 8841 // Add epilogue to handle BytesLeft. 8842 BB = exitMBB; 8843 auto StartOfExit = exitMBB->begin(); 8844 8845 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8846 // [destOut] = STRB_POST(scratch, destLoop, 1) 8847 unsigned srcIn = srcLoop; 8848 unsigned destIn = destLoop; 8849 for (unsigned i = 0; i < BytesLeft; i++) { 8850 unsigned srcOut = MRI.createVirtualRegister(TRC); 8851 unsigned destOut = MRI.createVirtualRegister(TRC); 8852 unsigned scratch = MRI.createVirtualRegister(TRC); 8853 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8854 IsThumb1, IsThumb2); 8855 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8856 IsThumb1, IsThumb2); 8857 srcIn = srcOut; 8858 destIn = destOut; 8859 } 8860 8861 MI.eraseFromParent(); // The instruction is gone now. 8862 return BB; 8863 } 8864 8865 MachineBasicBlock * 8866 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8867 MachineBasicBlock *MBB) const { 8868 const TargetMachine &TM = getTargetMachine(); 8869 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8870 DebugLoc DL = MI.getDebugLoc(); 8871 8872 assert(Subtarget->isTargetWindows() && 8873 "__chkstk is only supported on Windows"); 8874 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8875 8876 // __chkstk takes the number of words to allocate on the stack in R4, and 8877 // returns the stack adjustment in number of bytes in R4. This will not 8878 // clober any other registers (other than the obvious lr). 8879 // 8880 // Although, technically, IP should be considered a register which may be 8881 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8882 // thumb-2 environment, so there is no interworking required. As a result, we 8883 // do not expect a veneer to be emitted by the linker, clobbering IP. 8884 // 8885 // Each module receives its own copy of __chkstk, so no import thunk is 8886 // required, again, ensuring that IP is not clobbered. 8887 // 8888 // Finally, although some linkers may theoretically provide a trampoline for 8889 // out of range calls (which is quite common due to a 32M range limitation of 8890 // branches for Thumb), we can generate the long-call version via 8891 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8892 // IP. 8893 8894 switch (TM.getCodeModel()) { 8895 case CodeModel::Small: 8896 case CodeModel::Medium: 8897 case CodeModel::Kernel: 8898 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8899 .add(predOps(ARMCC::AL)) 8900 .addExternalSymbol("__chkstk") 8901 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8902 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8903 .addReg(ARM::R12, 8904 RegState::Implicit | RegState::Define | RegState::Dead) 8905 .addReg(ARM::CPSR, 8906 RegState::Implicit | RegState::Define | RegState::Dead); 8907 break; 8908 case CodeModel::Large: { 8909 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8910 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8911 8912 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8913 .addExternalSymbol("__chkstk"); 8914 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8915 .add(predOps(ARMCC::AL)) 8916 .addReg(Reg, RegState::Kill) 8917 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8918 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8919 .addReg(ARM::R12, 8920 RegState::Implicit | RegState::Define | RegState::Dead) 8921 .addReg(ARM::CPSR, 8922 RegState::Implicit | RegState::Define | RegState::Dead); 8923 break; 8924 } 8925 } 8926 8927 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 8928 .addReg(ARM::SP, RegState::Kill) 8929 .addReg(ARM::R4, RegState::Kill) 8930 .setMIFlags(MachineInstr::FrameSetup) 8931 .add(predOps(ARMCC::AL)) 8932 .add(condCodeOp()); 8933 8934 MI.eraseFromParent(); 8935 return MBB; 8936 } 8937 8938 MachineBasicBlock * 8939 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 8940 MachineBasicBlock *MBB) const { 8941 DebugLoc DL = MI.getDebugLoc(); 8942 MachineFunction *MF = MBB->getParent(); 8943 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8944 8945 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8946 MF->insert(++MBB->getIterator(), ContBB); 8947 ContBB->splice(ContBB->begin(), MBB, 8948 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8949 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8950 MBB->addSuccessor(ContBB); 8951 8952 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8953 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 8954 MF->push_back(TrapBB); 8955 MBB->addSuccessor(TrapBB); 8956 8957 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 8958 .addReg(MI.getOperand(0).getReg()) 8959 .addImm(0) 8960 .add(predOps(ARMCC::AL)); 8961 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 8962 .addMBB(TrapBB) 8963 .addImm(ARMCC::EQ) 8964 .addReg(ARM::CPSR); 8965 8966 MI.eraseFromParent(); 8967 return ContBB; 8968 } 8969 8970 MachineBasicBlock * 8971 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8972 MachineBasicBlock *BB) const { 8973 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8974 DebugLoc dl = MI.getDebugLoc(); 8975 bool isThumb2 = Subtarget->isThumb2(); 8976 switch (MI.getOpcode()) { 8977 default: { 8978 MI.print(errs()); 8979 llvm_unreachable("Unexpected instr type to insert"); 8980 } 8981 8982 // Thumb1 post-indexed loads are really just single-register LDMs. 8983 case ARM::tLDR_postidx: { 8984 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 8985 .add(MI.getOperand(1)) // Rn_wb 8986 .add(MI.getOperand(2)) // Rn 8987 .add(MI.getOperand(3)) // PredImm 8988 .add(MI.getOperand(4)) // PredReg 8989 .add(MI.getOperand(0)); // Rt 8990 MI.eraseFromParent(); 8991 return BB; 8992 } 8993 8994 // The Thumb2 pre-indexed stores have the same MI operands, they just 8995 // define them differently in the .td files from the isel patterns, so 8996 // they need pseudos. 8997 case ARM::t2STR_preidx: 8998 MI.setDesc(TII->get(ARM::t2STR_PRE)); 8999 return BB; 9000 case ARM::t2STRB_preidx: 9001 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9002 return BB; 9003 case ARM::t2STRH_preidx: 9004 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9005 return BB; 9006 9007 case ARM::STRi_preidx: 9008 case ARM::STRBi_preidx: { 9009 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9010 : ARM::STRB_PRE_IMM; 9011 // Decode the offset. 9012 unsigned Offset = MI.getOperand(4).getImm(); 9013 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9014 Offset = ARM_AM::getAM2Offset(Offset); 9015 if (isSub) 9016 Offset = -Offset; 9017 9018 MachineMemOperand *MMO = *MI.memoperands_begin(); 9019 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9020 .add(MI.getOperand(0)) // Rn_wb 9021 .add(MI.getOperand(1)) // Rt 9022 .add(MI.getOperand(2)) // Rn 9023 .addImm(Offset) // offset (skip GPR==zero_reg) 9024 .add(MI.getOperand(5)) // pred 9025 .add(MI.getOperand(6)) 9026 .addMemOperand(MMO); 9027 MI.eraseFromParent(); 9028 return BB; 9029 } 9030 case ARM::STRr_preidx: 9031 case ARM::STRBr_preidx: 9032 case ARM::STRH_preidx: { 9033 unsigned NewOpc; 9034 switch (MI.getOpcode()) { 9035 default: llvm_unreachable("unexpected opcode!"); 9036 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9037 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9038 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9039 } 9040 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9041 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9042 MIB.add(MI.getOperand(i)); 9043 MI.eraseFromParent(); 9044 return BB; 9045 } 9046 9047 case ARM::tMOVCCr_pseudo: { 9048 // To "insert" a SELECT_CC instruction, we actually have to insert the 9049 // diamond control-flow pattern. The incoming instruction knows the 9050 // destination vreg to set, the condition code register to branch on, the 9051 // true/false values to select between, and a branch opcode to use. 9052 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9053 MachineFunction::iterator It = ++BB->getIterator(); 9054 9055 // thisMBB: 9056 // ... 9057 // TrueVal = ... 9058 // cmpTY ccX, r1, r2 9059 // bCC copy1MBB 9060 // fallthrough --> copy0MBB 9061 MachineBasicBlock *thisMBB = BB; 9062 MachineFunction *F = BB->getParent(); 9063 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9064 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9065 F->insert(It, copy0MBB); 9066 F->insert(It, sinkMBB); 9067 9068 // Transfer the remainder of BB and its successor edges to sinkMBB. 9069 sinkMBB->splice(sinkMBB->begin(), BB, 9070 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9071 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9072 9073 BB->addSuccessor(copy0MBB); 9074 BB->addSuccessor(sinkMBB); 9075 9076 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9077 .addMBB(sinkMBB) 9078 .addImm(MI.getOperand(3).getImm()) 9079 .addReg(MI.getOperand(4).getReg()); 9080 9081 // copy0MBB: 9082 // %FalseValue = ... 9083 // # fallthrough to sinkMBB 9084 BB = copy0MBB; 9085 9086 // Update machine-CFG edges 9087 BB->addSuccessor(sinkMBB); 9088 9089 // sinkMBB: 9090 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9091 // ... 9092 BB = sinkMBB; 9093 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9094 .addReg(MI.getOperand(1).getReg()) 9095 .addMBB(copy0MBB) 9096 .addReg(MI.getOperand(2).getReg()) 9097 .addMBB(thisMBB); 9098 9099 MI.eraseFromParent(); // The pseudo instruction is gone now. 9100 return BB; 9101 } 9102 9103 case ARM::BCCi64: 9104 case ARM::BCCZi64: { 9105 // If there is an unconditional branch to the other successor, remove it. 9106 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9107 9108 // Compare both parts that make up the double comparison separately for 9109 // equality. 9110 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9111 9112 unsigned LHS1 = MI.getOperand(1).getReg(); 9113 unsigned LHS2 = MI.getOperand(2).getReg(); 9114 if (RHSisZero) { 9115 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9116 .addReg(LHS1) 9117 .addImm(0) 9118 .add(predOps(ARMCC::AL)); 9119 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9120 .addReg(LHS2).addImm(0) 9121 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9122 } else { 9123 unsigned RHS1 = MI.getOperand(3).getReg(); 9124 unsigned RHS2 = MI.getOperand(4).getReg(); 9125 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9126 .addReg(LHS1) 9127 .addReg(RHS1) 9128 .add(predOps(ARMCC::AL)); 9129 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9130 .addReg(LHS2).addReg(RHS2) 9131 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9132 } 9133 9134 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9135 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9136 if (MI.getOperand(0).getImm() == ARMCC::NE) 9137 std::swap(destMBB, exitMBB); 9138 9139 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9140 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9141 if (isThumb2) 9142 BuildMI(BB, dl, TII->get(ARM::t2B)) 9143 .addMBB(exitMBB) 9144 .add(predOps(ARMCC::AL)); 9145 else 9146 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9147 9148 MI.eraseFromParent(); // The pseudo instruction is gone now. 9149 return BB; 9150 } 9151 9152 case ARM::Int_eh_sjlj_setjmp: 9153 case ARM::Int_eh_sjlj_setjmp_nofp: 9154 case ARM::tInt_eh_sjlj_setjmp: 9155 case ARM::t2Int_eh_sjlj_setjmp: 9156 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9157 return BB; 9158 9159 case ARM::Int_eh_sjlj_setup_dispatch: 9160 EmitSjLjDispatchBlock(MI, BB); 9161 return BB; 9162 9163 case ARM::ABS: 9164 case ARM::t2ABS: { 9165 // To insert an ABS instruction, we have to insert the 9166 // diamond control-flow pattern. The incoming instruction knows the 9167 // source vreg to test against 0, the destination vreg to set, 9168 // the condition code register to branch on, the 9169 // true/false values to select between, and a branch opcode to use. 9170 // It transforms 9171 // V1 = ABS V0 9172 // into 9173 // V2 = MOVS V0 9174 // BCC (branch to SinkBB if V0 >= 0) 9175 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9176 // SinkBB: V1 = PHI(V2, V3) 9177 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9178 MachineFunction::iterator BBI = ++BB->getIterator(); 9179 MachineFunction *Fn = BB->getParent(); 9180 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9181 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9182 Fn->insert(BBI, RSBBB); 9183 Fn->insert(BBI, SinkBB); 9184 9185 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9186 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9187 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9188 bool isThumb2 = Subtarget->isThumb2(); 9189 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9190 // In Thumb mode S must not be specified if source register is the SP or 9191 // PC and if destination register is the SP, so restrict register class 9192 unsigned NewRsbDstReg = 9193 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9194 9195 // Transfer the remainder of BB and its successor edges to sinkMBB. 9196 SinkBB->splice(SinkBB->begin(), BB, 9197 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9198 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9199 9200 BB->addSuccessor(RSBBB); 9201 BB->addSuccessor(SinkBB); 9202 9203 // fall through to SinkMBB 9204 RSBBB->addSuccessor(SinkBB); 9205 9206 // insert a cmp at the end of BB 9207 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9208 .addReg(ABSSrcReg) 9209 .addImm(0) 9210 .add(predOps(ARMCC::AL)); 9211 9212 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9213 BuildMI(BB, dl, 9214 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9215 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9216 9217 // insert rsbri in RSBBB 9218 // Note: BCC and rsbri will be converted into predicated rsbmi 9219 // by if-conversion pass 9220 BuildMI(*RSBBB, RSBBB->begin(), dl, 9221 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9222 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9223 .addImm(0) 9224 .add(predOps(ARMCC::AL)) 9225 .add(condCodeOp()); 9226 9227 // insert PHI in SinkBB, 9228 // reuse ABSDstReg to not change uses of ABS instruction 9229 BuildMI(*SinkBB, SinkBB->begin(), dl, 9230 TII->get(ARM::PHI), ABSDstReg) 9231 .addReg(NewRsbDstReg).addMBB(RSBBB) 9232 .addReg(ABSSrcReg).addMBB(BB); 9233 9234 // remove ABS instruction 9235 MI.eraseFromParent(); 9236 9237 // return last added BB 9238 return SinkBB; 9239 } 9240 case ARM::COPY_STRUCT_BYVAL_I32: 9241 ++NumLoopByVals; 9242 return EmitStructByval(MI, BB); 9243 case ARM::WIN__CHKSTK: 9244 return EmitLowered__chkstk(MI, BB); 9245 case ARM::WIN__DBZCHK: 9246 return EmitLowered__dbzchk(MI, BB); 9247 } 9248 } 9249 9250 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 9251 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9252 /// instead of as a custom inserter because we need the use list from the SDNode. 9253 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9254 MachineInstr &MI, const SDNode *Node) { 9255 bool isThumb1 = Subtarget->isThumb1Only(); 9256 9257 DebugLoc DL = MI.getDebugLoc(); 9258 MachineFunction *MF = MI.getParent()->getParent(); 9259 MachineRegisterInfo &MRI = MF->getRegInfo(); 9260 MachineInstrBuilder MIB(*MF, MI); 9261 9262 // If the new dst/src is unused mark it as dead. 9263 if (!Node->hasAnyUseOfValue(0)) { 9264 MI.getOperand(0).setIsDead(true); 9265 } 9266 if (!Node->hasAnyUseOfValue(1)) { 9267 MI.getOperand(1).setIsDead(true); 9268 } 9269 9270 // The MEMCPY both defines and kills the scratch registers. 9271 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9272 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9273 : &ARM::GPRRegClass); 9274 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9275 } 9276 } 9277 9278 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9279 SDNode *Node) const { 9280 if (MI.getOpcode() == ARM::MEMCPY) { 9281 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9282 return; 9283 } 9284 9285 const MCInstrDesc *MCID = &MI.getDesc(); 9286 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9287 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9288 // operand is still set to noreg. If needed, set the optional operand's 9289 // register to CPSR, and remove the redundant implicit def. 9290 // 9291 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 9292 9293 // Rename pseudo opcodes. 9294 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9295 unsigned ccOutIdx; 9296 if (NewOpc) { 9297 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9298 MCID = &TII->get(NewOpc); 9299 9300 assert(MCID->getNumOperands() == 9301 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9302 && "converted opcode should be the same except for cc_out" 9303 " (and, on Thumb1, pred)"); 9304 9305 MI.setDesc(*MCID); 9306 9307 // Add the optional cc_out operand 9308 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9309 9310 // On Thumb1, move all input operands to the end, then add the predicate 9311 if (Subtarget->isThumb1Only()) { 9312 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9313 MI.addOperand(MI.getOperand(1)); 9314 MI.RemoveOperand(1); 9315 } 9316 9317 // Restore the ties 9318 for (unsigned i = MI.getNumOperands(); i--;) { 9319 const MachineOperand& op = MI.getOperand(i); 9320 if (op.isReg() && op.isUse()) { 9321 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9322 if (DefIdx != -1) 9323 MI.tieOperands(DefIdx, i); 9324 } 9325 } 9326 9327 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9328 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9329 ccOutIdx = 1; 9330 } else 9331 ccOutIdx = MCID->getNumOperands() - 1; 9332 } else 9333 ccOutIdx = MCID->getNumOperands() - 1; 9334 9335 // Any ARM instruction that sets the 's' bit should specify an optional 9336 // "cc_out" operand in the last operand position. 9337 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9338 assert(!NewOpc && "Optional cc_out operand required"); 9339 return; 9340 } 9341 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9342 // since we already have an optional CPSR def. 9343 bool definesCPSR = false; 9344 bool deadCPSR = false; 9345 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9346 ++i) { 9347 const MachineOperand &MO = MI.getOperand(i); 9348 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9349 definesCPSR = true; 9350 if (MO.isDead()) 9351 deadCPSR = true; 9352 MI.RemoveOperand(i); 9353 break; 9354 } 9355 } 9356 if (!definesCPSR) { 9357 assert(!NewOpc && "Optional cc_out operand required"); 9358 return; 9359 } 9360 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9361 if (deadCPSR) { 9362 assert(!MI.getOperand(ccOutIdx).getReg() && 9363 "expect uninitialized optional cc_out operand"); 9364 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9365 if (!Subtarget->isThumb1Only()) 9366 return; 9367 } 9368 9369 // If this instruction was defined with an optional CPSR def and its dag node 9370 // had a live implicit CPSR def, then activate the optional CPSR def. 9371 MachineOperand &MO = MI.getOperand(ccOutIdx); 9372 MO.setReg(ARM::CPSR); 9373 MO.setIsDef(true); 9374 } 9375 9376 //===----------------------------------------------------------------------===// 9377 // ARM Optimization Hooks 9378 //===----------------------------------------------------------------------===// 9379 9380 // Helper function that checks if N is a null or all ones constant. 9381 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9382 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9383 } 9384 9385 // Return true if N is conditionally 0 or all ones. 9386 // Detects these expressions where cc is an i1 value: 9387 // 9388 // (select cc 0, y) [AllOnes=0] 9389 // (select cc y, 0) [AllOnes=0] 9390 // (zext cc) [AllOnes=0] 9391 // (sext cc) [AllOnes=0/1] 9392 // (select cc -1, y) [AllOnes=1] 9393 // (select cc y, -1) [AllOnes=1] 9394 // 9395 // Invert is set when N is the null/all ones constant when CC is false. 9396 // OtherOp is set to the alternative value of N. 9397 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9398 SDValue &CC, bool &Invert, 9399 SDValue &OtherOp, 9400 SelectionDAG &DAG) { 9401 switch (N->getOpcode()) { 9402 default: return false; 9403 case ISD::SELECT: { 9404 CC = N->getOperand(0); 9405 SDValue N1 = N->getOperand(1); 9406 SDValue N2 = N->getOperand(2); 9407 if (isZeroOrAllOnes(N1, AllOnes)) { 9408 Invert = false; 9409 OtherOp = N2; 9410 return true; 9411 } 9412 if (isZeroOrAllOnes(N2, AllOnes)) { 9413 Invert = true; 9414 OtherOp = N1; 9415 return true; 9416 } 9417 return false; 9418 } 9419 case ISD::ZERO_EXTEND: 9420 // (zext cc) can never be the all ones value. 9421 if (AllOnes) 9422 return false; 9423 LLVM_FALLTHROUGH; 9424 case ISD::SIGN_EXTEND: { 9425 SDLoc dl(N); 9426 EVT VT = N->getValueType(0); 9427 CC = N->getOperand(0); 9428 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9429 return false; 9430 Invert = !AllOnes; 9431 if (AllOnes) 9432 // When looking for an AllOnes constant, N is an sext, and the 'other' 9433 // value is 0. 9434 OtherOp = DAG.getConstant(0, dl, VT); 9435 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9436 // When looking for a 0 constant, N can be zext or sext. 9437 OtherOp = DAG.getConstant(1, dl, VT); 9438 else 9439 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9440 VT); 9441 return true; 9442 } 9443 } 9444 } 9445 9446 // Combine a constant select operand into its use: 9447 // 9448 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9449 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9450 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9451 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9452 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9453 // 9454 // The transform is rejected if the select doesn't have a constant operand that 9455 // is null, or all ones when AllOnes is set. 9456 // 9457 // Also recognize sext/zext from i1: 9458 // 9459 // (add (zext cc), x) -> (select cc (add x, 1), x) 9460 // (add (sext cc), x) -> (select cc (add x, -1), x) 9461 // 9462 // These transformations eventually create predicated instructions. 9463 // 9464 // @param N The node to transform. 9465 // @param Slct The N operand that is a select. 9466 // @param OtherOp The other N operand (x above). 9467 // @param DCI Context. 9468 // @param AllOnes Require the select constant to be all ones instead of null. 9469 // @returns The new node, or SDValue() on failure. 9470 static 9471 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9472 TargetLowering::DAGCombinerInfo &DCI, 9473 bool AllOnes = false) { 9474 SelectionDAG &DAG = DCI.DAG; 9475 EVT VT = N->getValueType(0); 9476 SDValue NonConstantVal; 9477 SDValue CCOp; 9478 bool SwapSelectOps; 9479 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9480 NonConstantVal, DAG)) 9481 return SDValue(); 9482 9483 // Slct is now know to be the desired identity constant when CC is true. 9484 SDValue TrueVal = OtherOp; 9485 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9486 OtherOp, NonConstantVal); 9487 // Unless SwapSelectOps says CC should be false. 9488 if (SwapSelectOps) 9489 std::swap(TrueVal, FalseVal); 9490 9491 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9492 CCOp, TrueVal, FalseVal); 9493 } 9494 9495 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9496 static 9497 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9498 TargetLowering::DAGCombinerInfo &DCI) { 9499 SDValue N0 = N->getOperand(0); 9500 SDValue N1 = N->getOperand(1); 9501 if (N0.getNode()->hasOneUse()) 9502 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9503 return Result; 9504 if (N1.getNode()->hasOneUse()) 9505 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9506 return Result; 9507 return SDValue(); 9508 } 9509 9510 static bool IsVUZPShuffleNode(SDNode *N) { 9511 // VUZP shuffle node. 9512 if (N->getOpcode() == ARMISD::VUZP) 9513 return true; 9514 9515 // "VUZP" on i32 is an alias for VTRN. 9516 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9517 return true; 9518 9519 return false; 9520 } 9521 9522 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9523 TargetLowering::DAGCombinerInfo &DCI, 9524 const ARMSubtarget *Subtarget) { 9525 // Look for ADD(VUZP.0, VUZP.1). 9526 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9527 N0 == N1) 9528 return SDValue(); 9529 9530 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9531 if (!N->getValueType(0).is64BitVector()) 9532 return SDValue(); 9533 9534 // Generate vpadd. 9535 SelectionDAG &DAG = DCI.DAG; 9536 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9537 SDLoc dl(N); 9538 SDNode *Unzip = N0.getNode(); 9539 EVT VT = N->getValueType(0); 9540 9541 SmallVector<SDValue, 8> Ops; 9542 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9543 TLI.getPointerTy(DAG.getDataLayout()))); 9544 Ops.push_back(Unzip->getOperand(0)); 9545 Ops.push_back(Unzip->getOperand(1)); 9546 9547 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9548 } 9549 9550 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9551 TargetLowering::DAGCombinerInfo &DCI, 9552 const ARMSubtarget *Subtarget) { 9553 // Check for two extended operands. 9554 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9555 N1.getOpcode() == ISD::SIGN_EXTEND) && 9556 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9557 N1.getOpcode() == ISD::ZERO_EXTEND)) 9558 return SDValue(); 9559 9560 SDValue N00 = N0.getOperand(0); 9561 SDValue N10 = N1.getOperand(0); 9562 9563 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9564 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9565 N00 == N10) 9566 return SDValue(); 9567 9568 // We only recognize Q register paddl here; this can't be reached until 9569 // after type legalization. 9570 if (!N00.getValueType().is64BitVector() || 9571 !N0.getValueType().is128BitVector()) 9572 return SDValue(); 9573 9574 // Generate vpaddl. 9575 SelectionDAG &DAG = DCI.DAG; 9576 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9577 SDLoc dl(N); 9578 EVT VT = N->getValueType(0); 9579 9580 SmallVector<SDValue, 8> Ops; 9581 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9582 unsigned Opcode; 9583 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9584 Opcode = Intrinsic::arm_neon_vpaddls; 9585 else 9586 Opcode = Intrinsic::arm_neon_vpaddlu; 9587 Ops.push_back(DAG.getConstant(Opcode, dl, 9588 TLI.getPointerTy(DAG.getDataLayout()))); 9589 EVT ElemTy = N00.getValueType().getVectorElementType(); 9590 unsigned NumElts = VT.getVectorNumElements(); 9591 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9592 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9593 N00.getOperand(0), N00.getOperand(1)); 9594 Ops.push_back(Concat); 9595 9596 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9597 } 9598 9599 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9600 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9601 // much easier to match. 9602 static SDValue 9603 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9604 TargetLowering::DAGCombinerInfo &DCI, 9605 const ARMSubtarget *Subtarget) { 9606 // Only perform optimization if after legalize, and if NEON is available. We 9607 // also expected both operands to be BUILD_VECTORs. 9608 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9609 || N0.getOpcode() != ISD::BUILD_VECTOR 9610 || N1.getOpcode() != ISD::BUILD_VECTOR) 9611 return SDValue(); 9612 9613 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9614 EVT VT = N->getValueType(0); 9615 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9616 return SDValue(); 9617 9618 // Check that the vector operands are of the right form. 9619 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9620 // operands, where N is the size of the formed vector. 9621 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9622 // index such that we have a pair wise add pattern. 9623 9624 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9625 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9626 return SDValue(); 9627 SDValue Vec = N0->getOperand(0)->getOperand(0); 9628 SDNode *V = Vec.getNode(); 9629 unsigned nextIndex = 0; 9630 9631 // For each operands to the ADD which are BUILD_VECTORs, 9632 // check to see if each of their operands are an EXTRACT_VECTOR with 9633 // the same vector and appropriate index. 9634 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9635 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9636 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9637 9638 SDValue ExtVec0 = N0->getOperand(i); 9639 SDValue ExtVec1 = N1->getOperand(i); 9640 9641 // First operand is the vector, verify its the same. 9642 if (V != ExtVec0->getOperand(0).getNode() || 9643 V != ExtVec1->getOperand(0).getNode()) 9644 return SDValue(); 9645 9646 // Second is the constant, verify its correct. 9647 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9648 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9649 9650 // For the constant, we want to see all the even or all the odd. 9651 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9652 || C1->getZExtValue() != nextIndex+1) 9653 return SDValue(); 9654 9655 // Increment index. 9656 nextIndex+=2; 9657 } else 9658 return SDValue(); 9659 } 9660 9661 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9662 // we're using the entire input vector, otherwise there's a size/legality 9663 // mismatch somewhere. 9664 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9665 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9666 return SDValue(); 9667 9668 // Create VPADDL node. 9669 SelectionDAG &DAG = DCI.DAG; 9670 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9671 9672 SDLoc dl(N); 9673 9674 // Build operand list. 9675 SmallVector<SDValue, 8> Ops; 9676 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9677 TLI.getPointerTy(DAG.getDataLayout()))); 9678 9679 // Input is the vector. 9680 Ops.push_back(Vec); 9681 9682 // Get widened type and narrowed type. 9683 MVT widenType; 9684 unsigned numElem = VT.getVectorNumElements(); 9685 9686 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9687 switch (inputLaneType.getSimpleVT().SimpleTy) { 9688 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9689 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9690 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9691 default: 9692 llvm_unreachable("Invalid vector element type for padd optimization."); 9693 } 9694 9695 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9696 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9697 return DAG.getNode(ExtOp, dl, VT, tmp); 9698 } 9699 9700 static SDValue findMUL_LOHI(SDValue V) { 9701 if (V->getOpcode() == ISD::UMUL_LOHI || 9702 V->getOpcode() == ISD::SMUL_LOHI) 9703 return V; 9704 return SDValue(); 9705 } 9706 9707 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 9708 TargetLowering::DAGCombinerInfo &DCI, 9709 const ARMSubtarget *Subtarget) { 9710 if (Subtarget->isThumb()) { 9711 if (!Subtarget->hasDSP()) 9712 return SDValue(); 9713 } else if (!Subtarget->hasV5TEOps()) 9714 return SDValue(); 9715 9716 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 9717 // accumulates the product into a 64-bit value. The 16-bit values will 9718 // be sign extended somehow or SRA'd into 32-bit values 9719 // (addc (adde (mul 16bit, 16bit), lo), hi) 9720 SDValue Mul = AddcNode->getOperand(0); 9721 SDValue Lo = AddcNode->getOperand(1); 9722 if (Mul.getOpcode() != ISD::MUL) { 9723 Lo = AddcNode->getOperand(0); 9724 Mul = AddcNode->getOperand(1); 9725 if (Mul.getOpcode() != ISD::MUL) 9726 return SDValue(); 9727 } 9728 9729 SDValue SRA = AddeNode->getOperand(0); 9730 SDValue Hi = AddeNode->getOperand(1); 9731 if (SRA.getOpcode() != ISD::SRA) { 9732 SRA = AddeNode->getOperand(1); 9733 Hi = AddeNode->getOperand(0); 9734 if (SRA.getOpcode() != ISD::SRA) 9735 return SDValue(); 9736 } 9737 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 9738 if (Const->getZExtValue() != 31) 9739 return SDValue(); 9740 } else 9741 return SDValue(); 9742 9743 if (SRA.getOperand(0) != Mul) 9744 return SDValue(); 9745 9746 SelectionDAG &DAG = DCI.DAG; 9747 SDLoc dl(AddcNode); 9748 unsigned Opcode = 0; 9749 SDValue Op0; 9750 SDValue Op1; 9751 9752 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 9753 Opcode = ARMISD::SMLALBB; 9754 Op0 = Mul.getOperand(0); 9755 Op1 = Mul.getOperand(1); 9756 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 9757 Opcode = ARMISD::SMLALBT; 9758 Op0 = Mul.getOperand(0); 9759 Op1 = Mul.getOperand(1).getOperand(0); 9760 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 9761 Opcode = ARMISD::SMLALTB; 9762 Op0 = Mul.getOperand(0).getOperand(0); 9763 Op1 = Mul.getOperand(1); 9764 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 9765 Opcode = ARMISD::SMLALTT; 9766 Op0 = Mul->getOperand(0).getOperand(0); 9767 Op1 = Mul->getOperand(1).getOperand(0); 9768 } 9769 9770 if (!Op0 || !Op1) 9771 return SDValue(); 9772 9773 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 9774 Op0, Op1, Lo, Hi); 9775 // Replace the ADDs' nodes uses by the MLA node's values. 9776 SDValue HiMLALResult(SMLAL.getNode(), 1); 9777 SDValue LoMLALResult(SMLAL.getNode(), 0); 9778 9779 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9780 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9781 9782 // Return original node to notify the driver to stop replacing. 9783 SDValue resNode(AddcNode, 0); 9784 return resNode; 9785 } 9786 9787 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode, 9788 TargetLowering::DAGCombinerInfo &DCI, 9789 const ARMSubtarget *Subtarget) { 9790 // Look for multiply add opportunities. 9791 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 9792 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 9793 // a glue link from the first add to the second add. 9794 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 9795 // a S/UMLAL instruction. 9796 // UMUL_LOHI 9797 // / :lo \ :hi 9798 // V \ [no multiline comment] 9799 // loAdd -> ADDC | 9800 // \ :carry / 9801 // V V 9802 // ADDE <- hiAdd 9803 // 9804 assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE"); 9805 9806 assert(AddeNode->getNumOperands() == 3 && 9807 AddeNode->getOperand(2).getValueType() == MVT::i32 && 9808 "ADDE node has the wrong inputs"); 9809 9810 // Check that we are chained to the right ADDC node. 9811 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9812 if (AddcNode->getOpcode() != ARMISD::ADDC) 9813 return SDValue(); 9814 9815 SDValue AddcOp0 = AddcNode->getOperand(0); 9816 SDValue AddcOp1 = AddcNode->getOperand(1); 9817 9818 // Check if the two operands are from the same mul_lohi node. 9819 if (AddcOp0.getNode() == AddcOp1.getNode()) 9820 return SDValue(); 9821 9822 assert(AddcNode->getNumValues() == 2 && 9823 AddcNode->getValueType(0) == MVT::i32 && 9824 "Expect ADDC with two result values. First: i32"); 9825 9826 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 9827 // maybe a SMLAL which multiplies two 16-bit values. 9828 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 9829 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 9830 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 9831 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 9832 return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget); 9833 9834 // Check for the triangle shape. 9835 SDValue AddeOp0 = AddeNode->getOperand(0); 9836 SDValue AddeOp1 = AddeNode->getOperand(1); 9837 9838 // Make sure that the ADDE operands are not coming from the same node. 9839 if (AddeOp0.getNode() == AddeOp1.getNode()) 9840 return SDValue(); 9841 9842 // Find the MUL_LOHI node walking up ADDE's operands. 9843 bool IsLeftOperandMUL = false; 9844 SDValue MULOp = findMUL_LOHI(AddeOp0); 9845 if (MULOp == SDValue()) 9846 MULOp = findMUL_LOHI(AddeOp1); 9847 else 9848 IsLeftOperandMUL = true; 9849 if (MULOp == SDValue()) 9850 return SDValue(); 9851 9852 // Figure out the right opcode. 9853 unsigned Opc = MULOp->getOpcode(); 9854 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 9855 9856 // Figure out the high and low input values to the MLAL node. 9857 SDValue* HiAdd = nullptr; 9858 SDValue* LoMul = nullptr; 9859 SDValue* LowAdd = nullptr; 9860 9861 // Ensure that ADDE is from high result of ISD::xMUL_LOHI. 9862 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 9863 return SDValue(); 9864 9865 if (IsLeftOperandMUL) 9866 HiAdd = &AddeOp1; 9867 else 9868 HiAdd = &AddeOp0; 9869 9870 9871 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 9872 // whose low result is fed to the ADDC we are checking. 9873 9874 if (AddcOp0 == MULOp.getValue(0)) { 9875 LoMul = &AddcOp0; 9876 LowAdd = &AddcOp1; 9877 } 9878 if (AddcOp1 == MULOp.getValue(0)) { 9879 LoMul = &AddcOp1; 9880 LowAdd = &AddcOp0; 9881 } 9882 9883 if (!LoMul) 9884 return SDValue(); 9885 9886 // If HiAdd is the same node as ADDC or is a predecessor of ADDC the 9887 // replacement below will create a cycle. 9888 if (AddcNode == HiAdd->getNode() || 9889 AddcNode->isPredecessorOf(HiAdd->getNode())) 9890 return SDValue(); 9891 9892 // Create the merged node. 9893 SelectionDAG &DAG = DCI.DAG; 9894 9895 // Build operand list. 9896 SmallVector<SDValue, 8> Ops; 9897 Ops.push_back(LoMul->getOperand(0)); 9898 Ops.push_back(LoMul->getOperand(1)); 9899 Ops.push_back(*LowAdd); 9900 Ops.push_back(*HiAdd); 9901 9902 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 9903 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9904 9905 // Replace the ADDs' nodes uses by the MLA node's values. 9906 SDValue HiMLALResult(MLALNode.getNode(), 1); 9907 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9908 9909 SDValue LoMLALResult(MLALNode.getNode(), 0); 9910 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9911 9912 // Return original node to notify the driver to stop replacing. 9913 return SDValue(AddeNode, 0); 9914 } 9915 9916 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 9917 TargetLowering::DAGCombinerInfo &DCI, 9918 const ARMSubtarget *Subtarget) { 9919 // UMAAL is similar to UMLAL except that it adds two unsigned values. 9920 // While trying to combine for the other MLAL nodes, first search for the 9921 // chance to use UMAAL. Check if Addc uses a node which has already 9922 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 9923 // as the addend, and it's handled in PerformUMLALCombine. 9924 9925 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 9926 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 9927 9928 // Check that we have a glued ADDC node. 9929 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9930 if (AddcNode->getOpcode() != ARMISD::ADDC) 9931 return SDValue(); 9932 9933 // Find the converted UMAAL or quit if it doesn't exist. 9934 SDNode *UmlalNode = nullptr; 9935 SDValue AddHi; 9936 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 9937 UmlalNode = AddcNode->getOperand(0).getNode(); 9938 AddHi = AddcNode->getOperand(1); 9939 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 9940 UmlalNode = AddcNode->getOperand(1).getNode(); 9941 AddHi = AddcNode->getOperand(0); 9942 } else { 9943 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 9944 } 9945 9946 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 9947 // the ADDC as well as Zero. 9948 if (!isNullConstant(UmlalNode->getOperand(3))) 9949 return SDValue(); 9950 9951 if ((isNullConstant(AddeNode->getOperand(0)) && 9952 AddeNode->getOperand(1).getNode() == UmlalNode) || 9953 (AddeNode->getOperand(0).getNode() == UmlalNode && 9954 isNullConstant(AddeNode->getOperand(1)))) { 9955 SelectionDAG &DAG = DCI.DAG; 9956 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9957 UmlalNode->getOperand(2), AddHi }; 9958 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9959 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9960 9961 // Replace the ADDs' nodes uses by the UMAAL node's values. 9962 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9963 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9964 9965 // Return original node to notify the driver to stop replacing. 9966 return SDValue(AddeNode, 0); 9967 } 9968 return SDValue(); 9969 } 9970 9971 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 9972 const ARMSubtarget *Subtarget) { 9973 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 9974 return SDValue(); 9975 9976 // Check that we have a pair of ADDC and ADDE as operands. 9977 // Both addends of the ADDE must be zero. 9978 SDNode* AddcNode = N->getOperand(2).getNode(); 9979 SDNode* AddeNode = N->getOperand(3).getNode(); 9980 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 9981 (AddeNode->getOpcode() == ARMISD::ADDE) && 9982 isNullConstant(AddeNode->getOperand(0)) && 9983 isNullConstant(AddeNode->getOperand(1)) && 9984 (AddeNode->getOperand(2).getNode() == AddcNode)) 9985 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 9986 DAG.getVTList(MVT::i32, MVT::i32), 9987 {N->getOperand(0), N->getOperand(1), 9988 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 9989 else 9990 return SDValue(); 9991 } 9992 9993 static SDValue PerformAddcSubcCombine(SDNode *N, 9994 TargetLowering::DAGCombinerInfo &DCI, 9995 const ARMSubtarget *Subtarget) { 9996 SelectionDAG &DAG(DCI.DAG); 9997 9998 if (N->getOpcode() == ARMISD::ADDC) { 9999 // (ADDC (ADDE 0, 0, C), -1) -> C 10000 SDValue LHS = N->getOperand(0); 10001 SDValue RHS = N->getOperand(1); 10002 if (LHS->getOpcode() == ARMISD::ADDE && 10003 isNullConstant(LHS->getOperand(0)) && 10004 isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) { 10005 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10006 } 10007 } 10008 10009 if (Subtarget->isThumb1Only()) { 10010 SDValue RHS = N->getOperand(1); 10011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10012 int32_t imm = C->getSExtValue(); 10013 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10014 SDLoc DL(N); 10015 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10016 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10017 : ARMISD::ADDC; 10018 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10019 } 10020 } 10021 } 10022 return SDValue(); 10023 } 10024 10025 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG, 10026 const ARMSubtarget *Subtarget) { 10027 if (Subtarget->isThumb1Only()) { 10028 SDValue RHS = N->getOperand(1); 10029 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10030 int64_t imm = C->getSExtValue(); 10031 if (imm < 0) { 10032 SDLoc DL(N); 10033 10034 // The with-carry-in form matches bitwise not instead of the negation. 10035 // Effectively, the inverse interpretation of the carry flag already 10036 // accounts for part of the negation. 10037 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10038 10039 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10040 : ARMISD::ADDE; 10041 return DAG.getNode(Opcode, DL, N->getVTList(), 10042 N->getOperand(0), RHS, N->getOperand(2)); 10043 } 10044 } 10045 } 10046 return SDValue(); 10047 } 10048 10049 /// PerformADDECombine - Target-specific dag combine transform from 10050 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10051 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10052 static SDValue PerformADDECombine(SDNode *N, 10053 TargetLowering::DAGCombinerInfo &DCI, 10054 const ARMSubtarget *Subtarget) { 10055 // Only ARM and Thumb2 support UMLAL/SMLAL. 10056 if (Subtarget->isThumb1Only()) 10057 return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 10058 10059 // Only perform the checks after legalize when the pattern is available. 10060 if (DCI.isBeforeLegalize()) return SDValue(); 10061 10062 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10063 } 10064 10065 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10066 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10067 /// called with the default operands, and if that fails, with commuted 10068 /// operands. 10069 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10070 TargetLowering::DAGCombinerInfo &DCI, 10071 const ARMSubtarget *Subtarget){ 10072 // Attempt to create vpadd for this add. 10073 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10074 return Result; 10075 10076 // Attempt to create vpaddl for this add. 10077 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10078 return Result; 10079 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10080 Subtarget)) 10081 return Result; 10082 10083 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10084 if (N0.getNode()->hasOneUse()) 10085 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10086 return Result; 10087 return SDValue(); 10088 } 10089 10090 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10091 /// 10092 static SDValue PerformADDCombine(SDNode *N, 10093 TargetLowering::DAGCombinerInfo &DCI, 10094 const ARMSubtarget *Subtarget) { 10095 SDValue N0 = N->getOperand(0); 10096 SDValue N1 = N->getOperand(1); 10097 10098 // First try with the default operand order. 10099 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10100 return Result; 10101 10102 // If that didn't work, try again with the operands commuted. 10103 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10104 } 10105 10106 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10107 /// 10108 static SDValue PerformSUBCombine(SDNode *N, 10109 TargetLowering::DAGCombinerInfo &DCI) { 10110 SDValue N0 = N->getOperand(0); 10111 SDValue N1 = N->getOperand(1); 10112 10113 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10114 if (N1.getNode()->hasOneUse()) 10115 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10116 return Result; 10117 10118 return SDValue(); 10119 } 10120 10121 /// PerformVMULCombine 10122 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10123 /// special multiplier accumulator forwarding. 10124 /// vmul d3, d0, d2 10125 /// vmla d3, d1, d2 10126 /// is faster than 10127 /// vadd d3, d0, d1 10128 /// vmul d3, d3, d2 10129 // However, for (A + B) * (A + B), 10130 // vadd d2, d0, d1 10131 // vmul d3, d0, d2 10132 // vmla d3, d1, d2 10133 // is slower than 10134 // vadd d2, d0, d1 10135 // vmul d3, d2, d2 10136 static SDValue PerformVMULCombine(SDNode *N, 10137 TargetLowering::DAGCombinerInfo &DCI, 10138 const ARMSubtarget *Subtarget) { 10139 if (!Subtarget->hasVMLxForwarding()) 10140 return SDValue(); 10141 10142 SelectionDAG &DAG = DCI.DAG; 10143 SDValue N0 = N->getOperand(0); 10144 SDValue N1 = N->getOperand(1); 10145 unsigned Opcode = N0.getOpcode(); 10146 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10147 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10148 Opcode = N1.getOpcode(); 10149 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10150 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10151 return SDValue(); 10152 std::swap(N0, N1); 10153 } 10154 10155 if (N0 == N1) 10156 return SDValue(); 10157 10158 EVT VT = N->getValueType(0); 10159 SDLoc DL(N); 10160 SDValue N00 = N0->getOperand(0); 10161 SDValue N01 = N0->getOperand(1); 10162 return DAG.getNode(Opcode, DL, VT, 10163 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10164 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10165 } 10166 10167 static SDValue PerformMULCombine(SDNode *N, 10168 TargetLowering::DAGCombinerInfo &DCI, 10169 const ARMSubtarget *Subtarget) { 10170 SelectionDAG &DAG = DCI.DAG; 10171 10172 if (Subtarget->isThumb1Only()) 10173 return SDValue(); 10174 10175 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10176 return SDValue(); 10177 10178 EVT VT = N->getValueType(0); 10179 if (VT.is64BitVector() || VT.is128BitVector()) 10180 return PerformVMULCombine(N, DCI, Subtarget); 10181 if (VT != MVT::i32) 10182 return SDValue(); 10183 10184 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10185 if (!C) 10186 return SDValue(); 10187 10188 int64_t MulAmt = C->getSExtValue(); 10189 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10190 10191 ShiftAmt = ShiftAmt & (32 - 1); 10192 SDValue V = N->getOperand(0); 10193 SDLoc DL(N); 10194 10195 SDValue Res; 10196 MulAmt >>= ShiftAmt; 10197 10198 if (MulAmt >= 0) { 10199 if (isPowerOf2_32(MulAmt - 1)) { 10200 // (mul x, 2^N + 1) => (add (shl x, N), x) 10201 Res = DAG.getNode(ISD::ADD, DL, VT, 10202 V, 10203 DAG.getNode(ISD::SHL, DL, VT, 10204 V, 10205 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10206 MVT::i32))); 10207 } else if (isPowerOf2_32(MulAmt + 1)) { 10208 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10209 Res = DAG.getNode(ISD::SUB, DL, VT, 10210 DAG.getNode(ISD::SHL, DL, VT, 10211 V, 10212 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10213 MVT::i32)), 10214 V); 10215 } else 10216 return SDValue(); 10217 } else { 10218 uint64_t MulAmtAbs = -MulAmt; 10219 if (isPowerOf2_32(MulAmtAbs + 1)) { 10220 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10221 Res = DAG.getNode(ISD::SUB, DL, VT, 10222 V, 10223 DAG.getNode(ISD::SHL, DL, VT, 10224 V, 10225 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10226 MVT::i32))); 10227 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10228 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10229 Res = DAG.getNode(ISD::ADD, DL, VT, 10230 V, 10231 DAG.getNode(ISD::SHL, DL, VT, 10232 V, 10233 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10234 MVT::i32))); 10235 Res = DAG.getNode(ISD::SUB, DL, VT, 10236 DAG.getConstant(0, DL, MVT::i32), Res); 10237 } else 10238 return SDValue(); 10239 } 10240 10241 if (ShiftAmt != 0) 10242 Res = DAG.getNode(ISD::SHL, DL, VT, 10243 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10244 10245 // Do not add new nodes to DAG combiner worklist. 10246 DCI.CombineTo(N, Res, false); 10247 return SDValue(); 10248 } 10249 10250 static SDValue PerformANDCombine(SDNode *N, 10251 TargetLowering::DAGCombinerInfo &DCI, 10252 const ARMSubtarget *Subtarget) { 10253 // Attempt to use immediate-form VBIC 10254 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10255 SDLoc dl(N); 10256 EVT VT = N->getValueType(0); 10257 SelectionDAG &DAG = DCI.DAG; 10258 10259 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10260 return SDValue(); 10261 10262 APInt SplatBits, SplatUndef; 10263 unsigned SplatBitSize; 10264 bool HasAnyUndefs; 10265 if (BVN && 10266 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10267 if (SplatBitSize <= 64) { 10268 EVT VbicVT; 10269 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10270 SplatUndef.getZExtValue(), SplatBitSize, 10271 DAG, dl, VbicVT, VT.is128BitVector(), 10272 OtherModImm); 10273 if (Val.getNode()) { 10274 SDValue Input = 10275 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10276 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10277 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10278 } 10279 } 10280 } 10281 10282 if (!Subtarget->isThumb1Only()) { 10283 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10284 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10285 return Result; 10286 } 10287 10288 return SDValue(); 10289 } 10290 10291 // Try combining OR nodes to SMULWB, SMULWT. 10292 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10293 TargetLowering::DAGCombinerInfo &DCI, 10294 const ARMSubtarget *Subtarget) { 10295 if (!Subtarget->hasV6Ops() || 10296 (Subtarget->isThumb() && 10297 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10298 return SDValue(); 10299 10300 SDValue SRL = OR->getOperand(0); 10301 SDValue SHL = OR->getOperand(1); 10302 10303 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10304 SRL = OR->getOperand(1); 10305 SHL = OR->getOperand(0); 10306 } 10307 if (!isSRL16(SRL) || !isSHL16(SHL)) 10308 return SDValue(); 10309 10310 // The first operands to the shifts need to be the two results from the 10311 // same smul_lohi node. 10312 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10313 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10314 return SDValue(); 10315 10316 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10317 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10318 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10319 return SDValue(); 10320 10321 // Now we have: 10322 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10323 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10324 // For SMUWB the 16-bit value will signed extended somehow. 10325 // For SMULWT only the SRA is required. 10326 // Check both sides of SMUL_LOHI 10327 SDValue OpS16 = SMULLOHI->getOperand(0); 10328 SDValue OpS32 = SMULLOHI->getOperand(1); 10329 10330 SelectionDAG &DAG = DCI.DAG; 10331 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10332 OpS16 = OpS32; 10333 OpS32 = SMULLOHI->getOperand(0); 10334 } 10335 10336 SDLoc dl(OR); 10337 unsigned Opcode = 0; 10338 if (isS16(OpS16, DAG)) 10339 Opcode = ARMISD::SMULWB; 10340 else if (isSRA16(OpS16)) { 10341 Opcode = ARMISD::SMULWT; 10342 OpS16 = OpS16->getOperand(0); 10343 } 10344 else 10345 return SDValue(); 10346 10347 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10348 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10349 return SDValue(OR, 0); 10350 } 10351 10352 static SDValue PerformORCombineToBFI(SDNode *N, 10353 TargetLowering::DAGCombinerInfo &DCI, 10354 const ARMSubtarget *Subtarget) { 10355 // BFI is only available on V6T2+ 10356 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10357 return SDValue(); 10358 10359 EVT VT = N->getValueType(0); 10360 SDValue N0 = N->getOperand(0); 10361 SDValue N1 = N->getOperand(1); 10362 SelectionDAG &DAG = DCI.DAG; 10363 SDLoc DL(N); 10364 // 1) or (and A, mask), val => ARMbfi A, val, mask 10365 // iff (val & mask) == val 10366 // 10367 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10368 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10369 // && mask == ~mask2 10370 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10371 // && ~mask == mask2 10372 // (i.e., copy a bitfield value into another bitfield of the same width) 10373 10374 if (VT != MVT::i32) 10375 return SDValue(); 10376 10377 SDValue N00 = N0.getOperand(0); 10378 10379 // The value and the mask need to be constants so we can verify this is 10380 // actually a bitfield set. If the mask is 0xffff, we can do better 10381 // via a movt instruction, so don't use BFI in that case. 10382 SDValue MaskOp = N0.getOperand(1); 10383 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10384 if (!MaskC) 10385 return SDValue(); 10386 unsigned Mask = MaskC->getZExtValue(); 10387 if (Mask == 0xffff) 10388 return SDValue(); 10389 SDValue Res; 10390 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10391 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10392 if (N1C) { 10393 unsigned Val = N1C->getZExtValue(); 10394 if ((Val & ~Mask) != Val) 10395 return SDValue(); 10396 10397 if (ARM::isBitFieldInvertedMask(Mask)) { 10398 Val >>= countTrailingZeros(~Mask); 10399 10400 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10401 DAG.getConstant(Val, DL, MVT::i32), 10402 DAG.getConstant(Mask, DL, MVT::i32)); 10403 10404 DCI.CombineTo(N, Res, false); 10405 // Return value from the original node to inform the combiner than N is 10406 // now dead. 10407 return SDValue(N, 0); 10408 } 10409 } else if (N1.getOpcode() == ISD::AND) { 10410 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10411 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10412 if (!N11C) 10413 return SDValue(); 10414 unsigned Mask2 = N11C->getZExtValue(); 10415 10416 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10417 // as is to match. 10418 if (ARM::isBitFieldInvertedMask(Mask) && 10419 (Mask == ~Mask2)) { 10420 // The pack halfword instruction works better for masks that fit it, 10421 // so use that when it's available. 10422 if (Subtarget->hasDSP() && 10423 (Mask == 0xffff || Mask == 0xffff0000)) 10424 return SDValue(); 10425 // 2a 10426 unsigned amt = countTrailingZeros(Mask2); 10427 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10428 DAG.getConstant(amt, DL, MVT::i32)); 10429 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10430 DAG.getConstant(Mask, DL, MVT::i32)); 10431 DCI.CombineTo(N, Res, false); 10432 // Return value from the original node to inform the combiner than N is 10433 // now dead. 10434 return SDValue(N, 0); 10435 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10436 (~Mask == Mask2)) { 10437 // The pack halfword instruction works better for masks that fit it, 10438 // so use that when it's available. 10439 if (Subtarget->hasDSP() && 10440 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10441 return SDValue(); 10442 // 2b 10443 unsigned lsb = countTrailingZeros(Mask); 10444 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10445 DAG.getConstant(lsb, DL, MVT::i32)); 10446 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10447 DAG.getConstant(Mask2, DL, MVT::i32)); 10448 DCI.CombineTo(N, Res, false); 10449 // Return value from the original node to inform the combiner than N is 10450 // now dead. 10451 return SDValue(N, 0); 10452 } 10453 } 10454 10455 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10456 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10457 ARM::isBitFieldInvertedMask(~Mask)) { 10458 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10459 // where lsb(mask) == #shamt and masked bits of B are known zero. 10460 SDValue ShAmt = N00.getOperand(1); 10461 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10462 unsigned LSB = countTrailingZeros(Mask); 10463 if (ShAmtC != LSB) 10464 return SDValue(); 10465 10466 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10467 DAG.getConstant(~Mask, DL, MVT::i32)); 10468 10469 DCI.CombineTo(N, Res, false); 10470 // Return value from the original node to inform the combiner than N is 10471 // now dead. 10472 return SDValue(N, 0); 10473 } 10474 10475 return SDValue(); 10476 } 10477 10478 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10479 static SDValue PerformORCombine(SDNode *N, 10480 TargetLowering::DAGCombinerInfo &DCI, 10481 const ARMSubtarget *Subtarget) { 10482 // Attempt to use immediate-form VORR 10483 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10484 SDLoc dl(N); 10485 EVT VT = N->getValueType(0); 10486 SelectionDAG &DAG = DCI.DAG; 10487 10488 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10489 return SDValue(); 10490 10491 APInt SplatBits, SplatUndef; 10492 unsigned SplatBitSize; 10493 bool HasAnyUndefs; 10494 if (BVN && Subtarget->hasNEON() && 10495 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10496 if (SplatBitSize <= 64) { 10497 EVT VorrVT; 10498 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10499 SplatUndef.getZExtValue(), SplatBitSize, 10500 DAG, dl, VorrVT, VT.is128BitVector(), 10501 OtherModImm); 10502 if (Val.getNode()) { 10503 SDValue Input = 10504 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10505 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10506 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10507 } 10508 } 10509 } 10510 10511 if (!Subtarget->isThumb1Only()) { 10512 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10513 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10514 return Result; 10515 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10516 return Result; 10517 } 10518 10519 // The code below optimizes (or (and X, Y), Z). 10520 // The AND operand needs to have a single user to make these optimizations 10521 // profitable. 10522 SDValue N0 = N->getOperand(0); 10523 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10524 return SDValue(); 10525 SDValue N1 = N->getOperand(1); 10526 10527 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10528 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10529 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10530 APInt SplatUndef; 10531 unsigned SplatBitSize; 10532 bool HasAnyUndefs; 10533 10534 APInt SplatBits0, SplatBits1; 10535 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 10536 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 10537 // Ensure that the second operand of both ands are constants 10538 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 10539 HasAnyUndefs) && !HasAnyUndefs) { 10540 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 10541 HasAnyUndefs) && !HasAnyUndefs) { 10542 // Ensure that the bit width of the constants are the same and that 10543 // the splat arguments are logical inverses as per the pattern we 10544 // are trying to simplify. 10545 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 10546 SplatBits0 == ~SplatBits1) { 10547 // Canonicalize the vector type to make instruction selection 10548 // simpler. 10549 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 10550 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 10551 N0->getOperand(1), 10552 N0->getOperand(0), 10553 N1->getOperand(0)); 10554 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 10555 } 10556 } 10557 } 10558 } 10559 10560 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 10561 // reasonable. 10562 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 10563 return Res; 10564 10565 return SDValue(); 10566 } 10567 10568 static SDValue PerformXORCombine(SDNode *N, 10569 TargetLowering::DAGCombinerInfo &DCI, 10570 const ARMSubtarget *Subtarget) { 10571 EVT VT = N->getValueType(0); 10572 SelectionDAG &DAG = DCI.DAG; 10573 10574 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10575 return SDValue(); 10576 10577 if (!Subtarget->isThumb1Only()) { 10578 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10579 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10580 return Result; 10581 } 10582 10583 return SDValue(); 10584 } 10585 10586 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 10587 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 10588 // their position in "to" (Rd). 10589 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 10590 assert(N->getOpcode() == ARMISD::BFI); 10591 10592 SDValue From = N->getOperand(1); 10593 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 10594 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 10595 10596 // If the Base came from a SHR #C, we can deduce that it is really testing bit 10597 // #C in the base of the SHR. 10598 if (From->getOpcode() == ISD::SRL && 10599 isa<ConstantSDNode>(From->getOperand(1))) { 10600 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 10601 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 10602 FromMask <<= Shift.getLimitedValue(31); 10603 From = From->getOperand(0); 10604 } 10605 10606 return From; 10607 } 10608 10609 // If A and B contain one contiguous set of bits, does A | B == A . B? 10610 // 10611 // Neither A nor B must be zero. 10612 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 10613 unsigned LastActiveBitInA = A.countTrailingZeros(); 10614 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 10615 return LastActiveBitInA - 1 == FirstActiveBitInB; 10616 } 10617 10618 static SDValue FindBFIToCombineWith(SDNode *N) { 10619 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 10620 // if one exists. 10621 APInt ToMask, FromMask; 10622 SDValue From = ParseBFI(N, ToMask, FromMask); 10623 SDValue To = N->getOperand(0); 10624 10625 // Now check for a compatible BFI to merge with. We can pass through BFIs that 10626 // aren't compatible, but not if they set the same bit in their destination as 10627 // we do (or that of any BFI we're going to combine with). 10628 SDValue V = To; 10629 APInt CombinedToMask = ToMask; 10630 while (V.getOpcode() == ARMISD::BFI) { 10631 APInt NewToMask, NewFromMask; 10632 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 10633 if (NewFrom != From) { 10634 // This BFI has a different base. Keep going. 10635 CombinedToMask |= NewToMask; 10636 V = V.getOperand(0); 10637 continue; 10638 } 10639 10640 // Do the written bits conflict with any we've seen so far? 10641 if ((NewToMask & CombinedToMask).getBoolValue()) 10642 // Conflicting bits - bail out because going further is unsafe. 10643 return SDValue(); 10644 10645 // Are the new bits contiguous when combined with the old bits? 10646 if (BitsProperlyConcatenate(ToMask, NewToMask) && 10647 BitsProperlyConcatenate(FromMask, NewFromMask)) 10648 return V; 10649 if (BitsProperlyConcatenate(NewToMask, ToMask) && 10650 BitsProperlyConcatenate(NewFromMask, FromMask)) 10651 return V; 10652 10653 // We've seen a write to some bits, so track it. 10654 CombinedToMask |= NewToMask; 10655 // Keep going... 10656 V = V.getOperand(0); 10657 } 10658 10659 return SDValue(); 10660 } 10661 10662 static SDValue PerformBFICombine(SDNode *N, 10663 TargetLowering::DAGCombinerInfo &DCI) { 10664 SDValue N1 = N->getOperand(1); 10665 if (N1.getOpcode() == ISD::AND) { 10666 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 10667 // the bits being cleared by the AND are not demanded by the BFI. 10668 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10669 if (!N11C) 10670 return SDValue(); 10671 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10672 unsigned LSB = countTrailingZeros(~InvMask); 10673 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 10674 assert(Width < 10675 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 10676 "undefined behavior"); 10677 unsigned Mask = (1u << Width) - 1; 10678 unsigned Mask2 = N11C->getZExtValue(); 10679 if ((Mask & (~Mask2)) == 0) 10680 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 10681 N->getOperand(0), N1.getOperand(0), 10682 N->getOperand(2)); 10683 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 10684 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 10685 // Keep track of any consecutive bits set that all come from the same base 10686 // value. We can combine these together into a single BFI. 10687 SDValue CombineBFI = FindBFIToCombineWith(N); 10688 if (CombineBFI == SDValue()) 10689 return SDValue(); 10690 10691 // We've found a BFI. 10692 APInt ToMask1, FromMask1; 10693 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 10694 10695 APInt ToMask2, FromMask2; 10696 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 10697 assert(From1 == From2); 10698 (void)From2; 10699 10700 // First, unlink CombineBFI. 10701 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 10702 // Then create a new BFI, combining the two together. 10703 APInt NewFromMask = FromMask1 | FromMask2; 10704 APInt NewToMask = ToMask1 | ToMask2; 10705 10706 EVT VT = N->getValueType(0); 10707 SDLoc dl(N); 10708 10709 if (NewFromMask[0] == 0) 10710 From1 = DCI.DAG.getNode( 10711 ISD::SRL, dl, VT, From1, 10712 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 10713 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 10714 DCI.DAG.getConstant(~NewToMask, dl, VT)); 10715 } 10716 return SDValue(); 10717 } 10718 10719 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 10720 /// ARMISD::VMOVRRD. 10721 static SDValue PerformVMOVRRDCombine(SDNode *N, 10722 TargetLowering::DAGCombinerInfo &DCI, 10723 const ARMSubtarget *Subtarget) { 10724 // vmovrrd(vmovdrr x, y) -> x,y 10725 SDValue InDouble = N->getOperand(0); 10726 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 10727 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 10728 10729 // vmovrrd(load f64) -> (load i32), (load i32) 10730 SDNode *InNode = InDouble.getNode(); 10731 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 10732 InNode->getValueType(0) == MVT::f64 && 10733 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 10734 !cast<LoadSDNode>(InNode)->isVolatile()) { 10735 // TODO: Should this be done for non-FrameIndex operands? 10736 LoadSDNode *LD = cast<LoadSDNode>(InNode); 10737 10738 SelectionDAG &DAG = DCI.DAG; 10739 SDLoc DL(LD); 10740 SDValue BasePtr = LD->getBasePtr(); 10741 SDValue NewLD1 = 10742 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 10743 LD->getAlignment(), LD->getMemOperand()->getFlags()); 10744 10745 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10746 DAG.getConstant(4, DL, MVT::i32)); 10747 SDValue NewLD2 = DAG.getLoad( 10748 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 10749 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 10750 10751 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 10752 if (DCI.DAG.getDataLayout().isBigEndian()) 10753 std::swap (NewLD1, NewLD2); 10754 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 10755 return Result; 10756 } 10757 10758 return SDValue(); 10759 } 10760 10761 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 10762 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 10763 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 10764 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 10765 SDValue Op0 = N->getOperand(0); 10766 SDValue Op1 = N->getOperand(1); 10767 if (Op0.getOpcode() == ISD::BITCAST) 10768 Op0 = Op0.getOperand(0); 10769 if (Op1.getOpcode() == ISD::BITCAST) 10770 Op1 = Op1.getOperand(0); 10771 if (Op0.getOpcode() == ARMISD::VMOVRRD && 10772 Op0.getNode() == Op1.getNode() && 10773 Op0.getResNo() == 0 && Op1.getResNo() == 1) 10774 return DAG.getNode(ISD::BITCAST, SDLoc(N), 10775 N->getValueType(0), Op0.getOperand(0)); 10776 return SDValue(); 10777 } 10778 10779 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 10780 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 10781 /// i64 vector to have f64 elements, since the value can then be loaded 10782 /// directly into a VFP register. 10783 static bool hasNormalLoadOperand(SDNode *N) { 10784 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 10785 for (unsigned i = 0; i < NumElts; ++i) { 10786 SDNode *Elt = N->getOperand(i).getNode(); 10787 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 10788 return true; 10789 } 10790 return false; 10791 } 10792 10793 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 10794 /// ISD::BUILD_VECTOR. 10795 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 10796 TargetLowering::DAGCombinerInfo &DCI, 10797 const ARMSubtarget *Subtarget) { 10798 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 10799 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 10800 // into a pair of GPRs, which is fine when the value is used as a scalar, 10801 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 10802 SelectionDAG &DAG = DCI.DAG; 10803 if (N->getNumOperands() == 2) 10804 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 10805 return RV; 10806 10807 // Load i64 elements as f64 values so that type legalization does not split 10808 // them up into i32 values. 10809 EVT VT = N->getValueType(0); 10810 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 10811 return SDValue(); 10812 SDLoc dl(N); 10813 SmallVector<SDValue, 8> Ops; 10814 unsigned NumElts = VT.getVectorNumElements(); 10815 for (unsigned i = 0; i < NumElts; ++i) { 10816 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 10817 Ops.push_back(V); 10818 // Make the DAGCombiner fold the bitcast. 10819 DCI.AddToWorklist(V.getNode()); 10820 } 10821 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 10822 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 10823 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10824 } 10825 10826 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 10827 static SDValue 10828 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10829 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 10830 // At that time, we may have inserted bitcasts from integer to float. 10831 // If these bitcasts have survived DAGCombine, change the lowering of this 10832 // BUILD_VECTOR in something more vector friendly, i.e., that does not 10833 // force to use floating point types. 10834 10835 // Make sure we can change the type of the vector. 10836 // This is possible iff: 10837 // 1. The vector is only used in a bitcast to a integer type. I.e., 10838 // 1.1. Vector is used only once. 10839 // 1.2. Use is a bit convert to an integer type. 10840 // 2. The size of its operands are 32-bits (64-bits are not legal). 10841 EVT VT = N->getValueType(0); 10842 EVT EltVT = VT.getVectorElementType(); 10843 10844 // Check 1.1. and 2. 10845 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 10846 return SDValue(); 10847 10848 // By construction, the input type must be float. 10849 assert(EltVT == MVT::f32 && "Unexpected type!"); 10850 10851 // Check 1.2. 10852 SDNode *Use = *N->use_begin(); 10853 if (Use->getOpcode() != ISD::BITCAST || 10854 Use->getValueType(0).isFloatingPoint()) 10855 return SDValue(); 10856 10857 // Check profitability. 10858 // Model is, if more than half of the relevant operands are bitcast from 10859 // i32, turn the build_vector into a sequence of insert_vector_elt. 10860 // Relevant operands are everything that is not statically 10861 // (i.e., at compile time) bitcasted. 10862 unsigned NumOfBitCastedElts = 0; 10863 unsigned NumElts = VT.getVectorNumElements(); 10864 unsigned NumOfRelevantElts = NumElts; 10865 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 10866 SDValue Elt = N->getOperand(Idx); 10867 if (Elt->getOpcode() == ISD::BITCAST) { 10868 // Assume only bit cast to i32 will go away. 10869 if (Elt->getOperand(0).getValueType() == MVT::i32) 10870 ++NumOfBitCastedElts; 10871 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 10872 // Constants are statically casted, thus do not count them as 10873 // relevant operands. 10874 --NumOfRelevantElts; 10875 } 10876 10877 // Check if more than half of the elements require a non-free bitcast. 10878 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 10879 return SDValue(); 10880 10881 SelectionDAG &DAG = DCI.DAG; 10882 // Create the new vector type. 10883 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 10884 // Check if the type is legal. 10885 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10886 if (!TLI.isTypeLegal(VecVT)) 10887 return SDValue(); 10888 10889 // Combine: 10890 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 10891 // => BITCAST INSERT_VECTOR_ELT 10892 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 10893 // (BITCAST EN), N. 10894 SDValue Vec = DAG.getUNDEF(VecVT); 10895 SDLoc dl(N); 10896 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 10897 SDValue V = N->getOperand(Idx); 10898 if (V.isUndef()) 10899 continue; 10900 if (V.getOpcode() == ISD::BITCAST && 10901 V->getOperand(0).getValueType() == MVT::i32) 10902 // Fold obvious case. 10903 V = V.getOperand(0); 10904 else { 10905 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 10906 // Make the DAGCombiner fold the bitcasts. 10907 DCI.AddToWorklist(V.getNode()); 10908 } 10909 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 10910 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 10911 } 10912 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 10913 // Make the DAGCombiner fold the bitcasts. 10914 DCI.AddToWorklist(Vec.getNode()); 10915 return Vec; 10916 } 10917 10918 /// PerformInsertEltCombine - Target-specific dag combine xforms for 10919 /// ISD::INSERT_VECTOR_ELT. 10920 static SDValue PerformInsertEltCombine(SDNode *N, 10921 TargetLowering::DAGCombinerInfo &DCI) { 10922 // Bitcast an i64 load inserted into a vector to f64. 10923 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10924 EVT VT = N->getValueType(0); 10925 SDNode *Elt = N->getOperand(1).getNode(); 10926 if (VT.getVectorElementType() != MVT::i64 || 10927 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 10928 return SDValue(); 10929 10930 SelectionDAG &DAG = DCI.DAG; 10931 SDLoc dl(N); 10932 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10933 VT.getVectorNumElements()); 10934 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 10935 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 10936 // Make the DAGCombiner fold the bitcasts. 10937 DCI.AddToWorklist(Vec.getNode()); 10938 DCI.AddToWorklist(V.getNode()); 10939 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 10940 Vec, V, N->getOperand(2)); 10941 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 10942 } 10943 10944 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 10945 /// ISD::VECTOR_SHUFFLE. 10946 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 10947 // The LLVM shufflevector instruction does not require the shuffle mask 10948 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 10949 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 10950 // operands do not match the mask length, they are extended by concatenating 10951 // them with undef vectors. That is probably the right thing for other 10952 // targets, but for NEON it is better to concatenate two double-register 10953 // size vector operands into a single quad-register size vector. Do that 10954 // transformation here: 10955 // shuffle(concat(v1, undef), concat(v2, undef)) -> 10956 // shuffle(concat(v1, v2), undef) 10957 SDValue Op0 = N->getOperand(0); 10958 SDValue Op1 = N->getOperand(1); 10959 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 10960 Op1.getOpcode() != ISD::CONCAT_VECTORS || 10961 Op0.getNumOperands() != 2 || 10962 Op1.getNumOperands() != 2) 10963 return SDValue(); 10964 SDValue Concat0Op1 = Op0.getOperand(1); 10965 SDValue Concat1Op1 = Op1.getOperand(1); 10966 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 10967 return SDValue(); 10968 // Skip the transformation if any of the types are illegal. 10969 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10970 EVT VT = N->getValueType(0); 10971 if (!TLI.isTypeLegal(VT) || 10972 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 10973 !TLI.isTypeLegal(Concat1Op1.getValueType())) 10974 return SDValue(); 10975 10976 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10977 Op0.getOperand(0), Op1.getOperand(0)); 10978 // Translate the shuffle mask. 10979 SmallVector<int, 16> NewMask; 10980 unsigned NumElts = VT.getVectorNumElements(); 10981 unsigned HalfElts = NumElts/2; 10982 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10983 for (unsigned n = 0; n < NumElts; ++n) { 10984 int MaskElt = SVN->getMaskElt(n); 10985 int NewElt = -1; 10986 if (MaskElt < (int)HalfElts) 10987 NewElt = MaskElt; 10988 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 10989 NewElt = HalfElts + MaskElt - NumElts; 10990 NewMask.push_back(NewElt); 10991 } 10992 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 10993 DAG.getUNDEF(VT), NewMask); 10994 } 10995 10996 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 10997 /// NEON load/store intrinsics, and generic vector load/stores, to merge 10998 /// base address updates. 10999 /// For generic load/stores, the memory type is assumed to be a vector. 11000 /// The caller is assumed to have checked legality. 11001 static SDValue CombineBaseUpdate(SDNode *N, 11002 TargetLowering::DAGCombinerInfo &DCI) { 11003 SelectionDAG &DAG = DCI.DAG; 11004 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11005 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11006 const bool isStore = N->getOpcode() == ISD::STORE; 11007 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11008 SDValue Addr = N->getOperand(AddrOpIdx); 11009 MemSDNode *MemN = cast<MemSDNode>(N); 11010 SDLoc dl(N); 11011 11012 // Search for a use of the address operand that is an increment. 11013 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11014 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11015 SDNode *User = *UI; 11016 if (User->getOpcode() != ISD::ADD || 11017 UI.getUse().getResNo() != Addr.getResNo()) 11018 continue; 11019 11020 // Check that the add is independent of the load/store. Otherwise, folding 11021 // it would create a cycle. 11022 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 11023 continue; 11024 11025 // Find the new opcode for the updating load/store. 11026 bool isLoadOp = true; 11027 bool isLaneOp = false; 11028 unsigned NewOpc = 0; 11029 unsigned NumVecs = 0; 11030 if (isIntrinsic) { 11031 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11032 switch (IntNo) { 11033 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11034 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11035 NumVecs = 1; break; 11036 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11037 NumVecs = 2; break; 11038 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11039 NumVecs = 3; break; 11040 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11041 NumVecs = 4; break; 11042 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11043 NumVecs = 2; isLaneOp = true; break; 11044 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11045 NumVecs = 3; isLaneOp = true; break; 11046 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11047 NumVecs = 4; isLaneOp = true; break; 11048 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11049 NumVecs = 1; isLoadOp = false; break; 11050 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11051 NumVecs = 2; isLoadOp = false; break; 11052 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11053 NumVecs = 3; isLoadOp = false; break; 11054 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11055 NumVecs = 4; isLoadOp = false; break; 11056 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11057 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11058 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11059 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11060 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11061 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11062 } 11063 } else { 11064 isLaneOp = true; 11065 switch (N->getOpcode()) { 11066 default: llvm_unreachable("unexpected opcode for Neon base update"); 11067 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11068 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11069 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11070 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11071 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11072 NumVecs = 1; isLaneOp = false; break; 11073 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11074 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11075 } 11076 } 11077 11078 // Find the size of memory referenced by the load/store. 11079 EVT VecTy; 11080 if (isLoadOp) { 11081 VecTy = N->getValueType(0); 11082 } else if (isIntrinsic) { 11083 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11084 } else { 11085 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11086 VecTy = N->getOperand(1).getValueType(); 11087 } 11088 11089 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11090 if (isLaneOp) 11091 NumBytes /= VecTy.getVectorNumElements(); 11092 11093 // If the increment is a constant, it must match the memory ref size. 11094 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11095 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11096 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11097 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11098 // separate instructions that make it harder to use a non-constant update. 11099 continue; 11100 } 11101 11102 // OK, we found an ADD we can fold into the base update. 11103 // Now, create a _UPD node, taking care of not breaking alignment. 11104 11105 EVT AlignedVecTy = VecTy; 11106 unsigned Alignment = MemN->getAlignment(); 11107 11108 // If this is a less-than-standard-aligned load/store, change the type to 11109 // match the standard alignment. 11110 // The alignment is overlooked when selecting _UPD variants; and it's 11111 // easier to introduce bitcasts here than fix that. 11112 // There are 3 ways to get to this base-update combine: 11113 // - intrinsics: they are assumed to be properly aligned (to the standard 11114 // alignment of the memory type), so we don't need to do anything. 11115 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11116 // intrinsics, so, likewise, there's nothing to do. 11117 // - generic load/store instructions: the alignment is specified as an 11118 // explicit operand, rather than implicitly as the standard alignment 11119 // of the memory type (like the intrisics). We need to change the 11120 // memory type to match the explicit alignment. That way, we don't 11121 // generate non-standard-aligned ARMISD::VLDx nodes. 11122 if (isa<LSBaseSDNode>(N)) { 11123 if (Alignment == 0) 11124 Alignment = 1; 11125 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11126 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11127 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11128 assert(!isLaneOp && "Unexpected generic load/store lane."); 11129 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11130 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11131 } 11132 // Don't set an explicit alignment on regular load/stores that we want 11133 // to transform to VLD/VST 1_UPD nodes. 11134 // This matches the behavior of regular load/stores, which only get an 11135 // explicit alignment if the MMO alignment is larger than the standard 11136 // alignment of the memory type. 11137 // Intrinsics, however, always get an explicit alignment, set to the 11138 // alignment of the MMO. 11139 Alignment = 1; 11140 } 11141 11142 // Create the new updating load/store node. 11143 // First, create an SDVTList for the new updating node's results. 11144 EVT Tys[6]; 11145 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11146 unsigned n; 11147 for (n = 0; n < NumResultVecs; ++n) 11148 Tys[n] = AlignedVecTy; 11149 Tys[n++] = MVT::i32; 11150 Tys[n] = MVT::Other; 11151 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11152 11153 // Then, gather the new node's operands. 11154 SmallVector<SDValue, 8> Ops; 11155 Ops.push_back(N->getOperand(0)); // incoming chain 11156 Ops.push_back(N->getOperand(AddrOpIdx)); 11157 Ops.push_back(Inc); 11158 11159 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11160 // Try to match the intrinsic's signature 11161 Ops.push_back(StN->getValue()); 11162 } else { 11163 // Loads (and of course intrinsics) match the intrinsics' signature, 11164 // so just add all but the alignment operand. 11165 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11166 Ops.push_back(N->getOperand(i)); 11167 } 11168 11169 // For all node types, the alignment operand is always the last one. 11170 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11171 11172 // If this is a non-standard-aligned STORE, the penultimate operand is the 11173 // stored value. Bitcast it to the aligned type. 11174 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11175 SDValue &StVal = Ops[Ops.size()-2]; 11176 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11177 } 11178 11179 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11180 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11181 MemN->getMemOperand()); 11182 11183 // Update the uses. 11184 SmallVector<SDValue, 5> NewResults; 11185 for (unsigned i = 0; i < NumResultVecs; ++i) 11186 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11187 11188 // If this is an non-standard-aligned LOAD, the first result is the loaded 11189 // value. Bitcast it to the expected result type. 11190 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11191 SDValue &LdVal = NewResults[0]; 11192 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11193 } 11194 11195 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11196 DCI.CombineTo(N, NewResults); 11197 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11198 11199 break; 11200 } 11201 return SDValue(); 11202 } 11203 11204 static SDValue PerformVLDCombine(SDNode *N, 11205 TargetLowering::DAGCombinerInfo &DCI) { 11206 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11207 return SDValue(); 11208 11209 return CombineBaseUpdate(N, DCI); 11210 } 11211 11212 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11213 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11214 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11215 /// return true. 11216 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11217 SelectionDAG &DAG = DCI.DAG; 11218 EVT VT = N->getValueType(0); 11219 // vldN-dup instructions only support 64-bit vectors for N > 1. 11220 if (!VT.is64BitVector()) 11221 return false; 11222 11223 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11224 SDNode *VLD = N->getOperand(0).getNode(); 11225 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11226 return false; 11227 unsigned NumVecs = 0; 11228 unsigned NewOpc = 0; 11229 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11230 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11231 NumVecs = 2; 11232 NewOpc = ARMISD::VLD2DUP; 11233 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11234 NumVecs = 3; 11235 NewOpc = ARMISD::VLD3DUP; 11236 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11237 NumVecs = 4; 11238 NewOpc = ARMISD::VLD4DUP; 11239 } else { 11240 return false; 11241 } 11242 11243 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11244 // numbers match the load. 11245 unsigned VLDLaneNo = 11246 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11247 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11248 UI != UE; ++UI) { 11249 // Ignore uses of the chain result. 11250 if (UI.getUse().getResNo() == NumVecs) 11251 continue; 11252 SDNode *User = *UI; 11253 if (User->getOpcode() != ARMISD::VDUPLANE || 11254 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11255 return false; 11256 } 11257 11258 // Create the vldN-dup node. 11259 EVT Tys[5]; 11260 unsigned n; 11261 for (n = 0; n < NumVecs; ++n) 11262 Tys[n] = VT; 11263 Tys[n] = MVT::Other; 11264 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11265 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11266 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11267 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11268 Ops, VLDMemInt->getMemoryVT(), 11269 VLDMemInt->getMemOperand()); 11270 11271 // Update the uses. 11272 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11273 UI != UE; ++UI) { 11274 unsigned ResNo = UI.getUse().getResNo(); 11275 // Ignore uses of the chain result. 11276 if (ResNo == NumVecs) 11277 continue; 11278 SDNode *User = *UI; 11279 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11280 } 11281 11282 // Now the vldN-lane intrinsic is dead except for its chain result. 11283 // Update uses of the chain. 11284 std::vector<SDValue> VLDDupResults; 11285 for (unsigned n = 0; n < NumVecs; ++n) 11286 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11287 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11288 DCI.CombineTo(VLD, VLDDupResults); 11289 11290 return true; 11291 } 11292 11293 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11294 /// ARMISD::VDUPLANE. 11295 static SDValue PerformVDUPLANECombine(SDNode *N, 11296 TargetLowering::DAGCombinerInfo &DCI) { 11297 SDValue Op = N->getOperand(0); 11298 11299 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11300 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11301 if (CombineVLDDUP(N, DCI)) 11302 return SDValue(N, 0); 11303 11304 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11305 // redundant. Ignore bit_converts for now; element sizes are checked below. 11306 while (Op.getOpcode() == ISD::BITCAST) 11307 Op = Op.getOperand(0); 11308 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11309 return SDValue(); 11310 11311 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11312 unsigned EltSize = Op.getScalarValueSizeInBits(); 11313 // The canonical VMOV for a zero vector uses a 32-bit element size. 11314 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11315 unsigned EltBits; 11316 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11317 EltSize = 8; 11318 EVT VT = N->getValueType(0); 11319 if (EltSize > VT.getScalarSizeInBits()) 11320 return SDValue(); 11321 11322 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11323 } 11324 11325 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11326 static SDValue PerformVDUPCombine(SDNode *N, 11327 TargetLowering::DAGCombinerInfo &DCI) { 11328 SelectionDAG &DAG = DCI.DAG; 11329 SDValue Op = N->getOperand(0); 11330 11331 // Match VDUP(LOAD) -> VLD1DUP. 11332 // We match this pattern here rather than waiting for isel because the 11333 // transform is only legal for unindexed loads. 11334 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11335 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11336 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11337 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11338 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11339 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11340 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11341 Ops, LD->getMemoryVT(), 11342 LD->getMemOperand()); 11343 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11344 return VLDDup; 11345 } 11346 11347 return SDValue(); 11348 } 11349 11350 static SDValue PerformLOADCombine(SDNode *N, 11351 TargetLowering::DAGCombinerInfo &DCI) { 11352 EVT VT = N->getValueType(0); 11353 11354 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11355 if (ISD::isNormalLoad(N) && VT.isVector() && 11356 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11357 return CombineBaseUpdate(N, DCI); 11358 11359 return SDValue(); 11360 } 11361 11362 /// PerformSTORECombine - Target-specific dag combine xforms for 11363 /// ISD::STORE. 11364 static SDValue PerformSTORECombine(SDNode *N, 11365 TargetLowering::DAGCombinerInfo &DCI) { 11366 StoreSDNode *St = cast<StoreSDNode>(N); 11367 if (St->isVolatile()) 11368 return SDValue(); 11369 11370 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11371 // pack all of the elements in one place. Next, store to memory in fewer 11372 // chunks. 11373 SDValue StVal = St->getValue(); 11374 EVT VT = StVal.getValueType(); 11375 if (St->isTruncatingStore() && VT.isVector()) { 11376 SelectionDAG &DAG = DCI.DAG; 11377 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11378 EVT StVT = St->getMemoryVT(); 11379 unsigned NumElems = VT.getVectorNumElements(); 11380 assert(StVT != VT && "Cannot truncate to the same type"); 11381 unsigned FromEltSz = VT.getScalarSizeInBits(); 11382 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11383 11384 // From, To sizes and ElemCount must be pow of two 11385 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11386 11387 // We are going to use the original vector elt for storing. 11388 // Accumulated smaller vector elements must be a multiple of the store size. 11389 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11390 11391 unsigned SizeRatio = FromEltSz / ToEltSz; 11392 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11393 11394 // Create a type on which we perform the shuffle. 11395 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11396 NumElems*SizeRatio); 11397 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11398 11399 SDLoc DL(St); 11400 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11401 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11402 for (unsigned i = 0; i < NumElems; ++i) 11403 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11404 ? (i + 1) * SizeRatio - 1 11405 : i * SizeRatio; 11406 11407 // Can't shuffle using an illegal type. 11408 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11409 11410 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11411 DAG.getUNDEF(WideVec.getValueType()), 11412 ShuffleVec); 11413 // At this point all of the data is stored at the bottom of the 11414 // register. We now need to save it to mem. 11415 11416 // Find the largest store unit 11417 MVT StoreType = MVT::i8; 11418 for (MVT Tp : MVT::integer_valuetypes()) { 11419 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11420 StoreType = Tp; 11421 } 11422 // Didn't find a legal store type. 11423 if (!TLI.isTypeLegal(StoreType)) 11424 return SDValue(); 11425 11426 // Bitcast the original vector into a vector of store-size units 11427 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11428 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11429 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11430 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11431 SmallVector<SDValue, 8> Chains; 11432 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11433 TLI.getPointerTy(DAG.getDataLayout())); 11434 SDValue BasePtr = St->getBasePtr(); 11435 11436 // Perform one or more big stores into memory. 11437 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11438 for (unsigned I = 0; I < E; I++) { 11439 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11440 StoreType, ShuffWide, 11441 DAG.getIntPtrConstant(I, DL)); 11442 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11443 St->getPointerInfo(), St->getAlignment(), 11444 St->getMemOperand()->getFlags()); 11445 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11446 Increment); 11447 Chains.push_back(Ch); 11448 } 11449 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11450 } 11451 11452 if (!ISD::isNormalStore(St)) 11453 return SDValue(); 11454 11455 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11456 // ARM stores of arguments in the same cache line. 11457 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11458 StVal.getNode()->hasOneUse()) { 11459 SelectionDAG &DAG = DCI.DAG; 11460 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11461 SDLoc DL(St); 11462 SDValue BasePtr = St->getBasePtr(); 11463 SDValue NewST1 = DAG.getStore( 11464 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11465 BasePtr, St->getPointerInfo(), St->getAlignment(), 11466 St->getMemOperand()->getFlags()); 11467 11468 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11469 DAG.getConstant(4, DL, MVT::i32)); 11470 return DAG.getStore(NewST1.getValue(0), DL, 11471 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11472 OffsetPtr, St->getPointerInfo(), 11473 std::min(4U, St->getAlignment() / 2), 11474 St->getMemOperand()->getFlags()); 11475 } 11476 11477 if (StVal.getValueType() == MVT::i64 && 11478 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11479 11480 // Bitcast an i64 store extracted from a vector to f64. 11481 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11482 SelectionDAG &DAG = DCI.DAG; 11483 SDLoc dl(StVal); 11484 SDValue IntVec = StVal.getOperand(0); 11485 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11486 IntVec.getValueType().getVectorNumElements()); 11487 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11488 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11489 Vec, StVal.getOperand(1)); 11490 dl = SDLoc(N); 11491 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11492 // Make the DAGCombiner fold the bitcasts. 11493 DCI.AddToWorklist(Vec.getNode()); 11494 DCI.AddToWorklist(ExtElt.getNode()); 11495 DCI.AddToWorklist(V.getNode()); 11496 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11497 St->getPointerInfo(), St->getAlignment(), 11498 St->getMemOperand()->getFlags(), St->getAAInfo()); 11499 } 11500 11501 // If this is a legal vector store, try to combine it into a VST1_UPD. 11502 if (ISD::isNormalStore(N) && VT.isVector() && 11503 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11504 return CombineBaseUpdate(N, DCI); 11505 11506 return SDValue(); 11507 } 11508 11509 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11510 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11511 /// when the VMUL has a constant operand that is a power of 2. 11512 /// 11513 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11514 /// vmul.f32 d16, d17, d16 11515 /// vcvt.s32.f32 d16, d16 11516 /// becomes: 11517 /// vcvt.s32.f32 d16, d16, #3 11518 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11519 const ARMSubtarget *Subtarget) { 11520 if (!Subtarget->hasNEON()) 11521 return SDValue(); 11522 11523 SDValue Op = N->getOperand(0); 11524 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11525 Op.getOpcode() != ISD::FMUL) 11526 return SDValue(); 11527 11528 SDValue ConstVec = Op->getOperand(1); 11529 if (!isa<BuildVectorSDNode>(ConstVec)) 11530 return SDValue(); 11531 11532 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11533 uint32_t FloatBits = FloatTy.getSizeInBits(); 11534 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11535 uint32_t IntBits = IntTy.getSizeInBits(); 11536 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11537 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11538 // These instructions only exist converting from f32 to i32. We can handle 11539 // smaller integers by generating an extra truncate, but larger ones would 11540 // be lossy. We also can't handle more then 4 lanes, since these intructions 11541 // only support v2i32/v4i32 types. 11542 return SDValue(); 11543 } 11544 11545 BitVector UndefElements; 11546 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11547 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11548 if (C == -1 || C == 0 || C > 32) 11549 return SDValue(); 11550 11551 SDLoc dl(N); 11552 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11553 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11554 Intrinsic::arm_neon_vcvtfp2fxu; 11555 SDValue FixConv = DAG.getNode( 11556 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11557 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 11558 DAG.getConstant(C, dl, MVT::i32)); 11559 11560 if (IntBits < FloatBits) 11561 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 11562 11563 return FixConv; 11564 } 11565 11566 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 11567 /// can replace combinations of VCVT (integer to floating-point) and VDIV 11568 /// when the VDIV has a constant operand that is a power of 2. 11569 /// 11570 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11571 /// vcvt.f32.s32 d16, d16 11572 /// vdiv.f32 d16, d17, d16 11573 /// becomes: 11574 /// vcvt.f32.s32 d16, d16, #3 11575 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 11576 const ARMSubtarget *Subtarget) { 11577 if (!Subtarget->hasNEON()) 11578 return SDValue(); 11579 11580 SDValue Op = N->getOperand(0); 11581 unsigned OpOpcode = Op.getNode()->getOpcode(); 11582 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 11583 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 11584 return SDValue(); 11585 11586 SDValue ConstVec = N->getOperand(1); 11587 if (!isa<BuildVectorSDNode>(ConstVec)) 11588 return SDValue(); 11589 11590 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 11591 uint32_t FloatBits = FloatTy.getSizeInBits(); 11592 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 11593 uint32_t IntBits = IntTy.getSizeInBits(); 11594 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11595 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11596 // These instructions only exist converting from i32 to f32. We can handle 11597 // smaller integers by generating an extra extend, but larger ones would 11598 // be lossy. We also can't handle more then 4 lanes, since these intructions 11599 // only support v2i32/v4i32 types. 11600 return SDValue(); 11601 } 11602 11603 BitVector UndefElements; 11604 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11605 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11606 if (C == -1 || C == 0 || C > 32) 11607 return SDValue(); 11608 11609 SDLoc dl(N); 11610 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 11611 SDValue ConvInput = Op.getOperand(0); 11612 if (IntBits < FloatBits) 11613 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 11614 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11615 ConvInput); 11616 11617 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 11618 Intrinsic::arm_neon_vcvtfxu2fp; 11619 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 11620 Op.getValueType(), 11621 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 11622 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 11623 } 11624 11625 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 11626 /// operand of a vector shift operation, where all the elements of the 11627 /// build_vector must have the same constant integer value. 11628 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 11629 // Ignore bit_converts. 11630 while (Op.getOpcode() == ISD::BITCAST) 11631 Op = Op.getOperand(0); 11632 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 11633 APInt SplatBits, SplatUndef; 11634 unsigned SplatBitSize; 11635 bool HasAnyUndefs; 11636 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 11637 HasAnyUndefs, ElementBits) || 11638 SplatBitSize > ElementBits) 11639 return false; 11640 Cnt = SplatBits.getSExtValue(); 11641 return true; 11642 } 11643 11644 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 11645 /// operand of a vector shift left operation. That value must be in the range: 11646 /// 0 <= Value < ElementBits for a left shift; or 11647 /// 0 <= Value <= ElementBits for a long left shift. 11648 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 11649 assert(VT.isVector() && "vector shift count is not a vector type"); 11650 int64_t ElementBits = VT.getScalarSizeInBits(); 11651 if (! getVShiftImm(Op, ElementBits, Cnt)) 11652 return false; 11653 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 11654 } 11655 11656 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 11657 /// operand of a vector shift right operation. For a shift opcode, the value 11658 /// is positive, but for an intrinsic the value count must be negative. The 11659 /// absolute value must be in the range: 11660 /// 1 <= |Value| <= ElementBits for a right shift; or 11661 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 11662 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 11663 int64_t &Cnt) { 11664 assert(VT.isVector() && "vector shift count is not a vector type"); 11665 int64_t ElementBits = VT.getScalarSizeInBits(); 11666 if (! getVShiftImm(Op, ElementBits, Cnt)) 11667 return false; 11668 if (!isIntrinsic) 11669 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 11670 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 11671 Cnt = -Cnt; 11672 return true; 11673 } 11674 return false; 11675 } 11676 11677 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 11678 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 11679 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 11680 switch (IntNo) { 11681 default: 11682 // Don't do anything for most intrinsics. 11683 break; 11684 11685 // Vector shifts: check for immediate versions and lower them. 11686 // Note: This is done during DAG combining instead of DAG legalizing because 11687 // the build_vectors for 64-bit vector element shift counts are generally 11688 // not legal, and it is hard to see their values after they get legalized to 11689 // loads from a constant pool. 11690 case Intrinsic::arm_neon_vshifts: 11691 case Intrinsic::arm_neon_vshiftu: 11692 case Intrinsic::arm_neon_vrshifts: 11693 case Intrinsic::arm_neon_vrshiftu: 11694 case Intrinsic::arm_neon_vrshiftn: 11695 case Intrinsic::arm_neon_vqshifts: 11696 case Intrinsic::arm_neon_vqshiftu: 11697 case Intrinsic::arm_neon_vqshiftsu: 11698 case Intrinsic::arm_neon_vqshiftns: 11699 case Intrinsic::arm_neon_vqshiftnu: 11700 case Intrinsic::arm_neon_vqshiftnsu: 11701 case Intrinsic::arm_neon_vqrshiftns: 11702 case Intrinsic::arm_neon_vqrshiftnu: 11703 case Intrinsic::arm_neon_vqrshiftnsu: { 11704 EVT VT = N->getOperand(1).getValueType(); 11705 int64_t Cnt; 11706 unsigned VShiftOpc = 0; 11707 11708 switch (IntNo) { 11709 case Intrinsic::arm_neon_vshifts: 11710 case Intrinsic::arm_neon_vshiftu: 11711 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 11712 VShiftOpc = ARMISD::VSHL; 11713 break; 11714 } 11715 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 11716 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 11717 ARMISD::VSHRs : ARMISD::VSHRu); 11718 break; 11719 } 11720 return SDValue(); 11721 11722 case Intrinsic::arm_neon_vrshifts: 11723 case Intrinsic::arm_neon_vrshiftu: 11724 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 11725 break; 11726 return SDValue(); 11727 11728 case Intrinsic::arm_neon_vqshifts: 11729 case Intrinsic::arm_neon_vqshiftu: 11730 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11731 break; 11732 return SDValue(); 11733 11734 case Intrinsic::arm_neon_vqshiftsu: 11735 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11736 break; 11737 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 11738 11739 case Intrinsic::arm_neon_vrshiftn: 11740 case Intrinsic::arm_neon_vqshiftns: 11741 case Intrinsic::arm_neon_vqshiftnu: 11742 case Intrinsic::arm_neon_vqshiftnsu: 11743 case Intrinsic::arm_neon_vqrshiftns: 11744 case Intrinsic::arm_neon_vqrshiftnu: 11745 case Intrinsic::arm_neon_vqrshiftnsu: 11746 // Narrowing shifts require an immediate right shift. 11747 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 11748 break; 11749 llvm_unreachable("invalid shift count for narrowing vector shift " 11750 "intrinsic"); 11751 11752 default: 11753 llvm_unreachable("unhandled vector shift"); 11754 } 11755 11756 switch (IntNo) { 11757 case Intrinsic::arm_neon_vshifts: 11758 case Intrinsic::arm_neon_vshiftu: 11759 // Opcode already set above. 11760 break; 11761 case Intrinsic::arm_neon_vrshifts: 11762 VShiftOpc = ARMISD::VRSHRs; break; 11763 case Intrinsic::arm_neon_vrshiftu: 11764 VShiftOpc = ARMISD::VRSHRu; break; 11765 case Intrinsic::arm_neon_vrshiftn: 11766 VShiftOpc = ARMISD::VRSHRN; break; 11767 case Intrinsic::arm_neon_vqshifts: 11768 VShiftOpc = ARMISD::VQSHLs; break; 11769 case Intrinsic::arm_neon_vqshiftu: 11770 VShiftOpc = ARMISD::VQSHLu; break; 11771 case Intrinsic::arm_neon_vqshiftsu: 11772 VShiftOpc = ARMISD::VQSHLsu; break; 11773 case Intrinsic::arm_neon_vqshiftns: 11774 VShiftOpc = ARMISD::VQSHRNs; break; 11775 case Intrinsic::arm_neon_vqshiftnu: 11776 VShiftOpc = ARMISD::VQSHRNu; break; 11777 case Intrinsic::arm_neon_vqshiftnsu: 11778 VShiftOpc = ARMISD::VQSHRNsu; break; 11779 case Intrinsic::arm_neon_vqrshiftns: 11780 VShiftOpc = ARMISD::VQRSHRNs; break; 11781 case Intrinsic::arm_neon_vqrshiftnu: 11782 VShiftOpc = ARMISD::VQRSHRNu; break; 11783 case Intrinsic::arm_neon_vqrshiftnsu: 11784 VShiftOpc = ARMISD::VQRSHRNsu; break; 11785 } 11786 11787 SDLoc dl(N); 11788 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11789 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 11790 } 11791 11792 case Intrinsic::arm_neon_vshiftins: { 11793 EVT VT = N->getOperand(1).getValueType(); 11794 int64_t Cnt; 11795 unsigned VShiftOpc = 0; 11796 11797 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 11798 VShiftOpc = ARMISD::VSLI; 11799 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 11800 VShiftOpc = ARMISD::VSRI; 11801 else { 11802 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 11803 } 11804 11805 SDLoc dl(N); 11806 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11807 N->getOperand(1), N->getOperand(2), 11808 DAG.getConstant(Cnt, dl, MVT::i32)); 11809 } 11810 11811 case Intrinsic::arm_neon_vqrshifts: 11812 case Intrinsic::arm_neon_vqrshiftu: 11813 // No immediate versions of these to check for. 11814 break; 11815 } 11816 11817 return SDValue(); 11818 } 11819 11820 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 11821 /// lowers them. As with the vector shift intrinsics, this is done during DAG 11822 /// combining instead of DAG legalizing because the build_vectors for 64-bit 11823 /// vector element shift counts are generally not legal, and it is hard to see 11824 /// their values after they get legalized to loads from a constant pool. 11825 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 11826 const ARMSubtarget *ST) { 11827 EVT VT = N->getValueType(0); 11828 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 11829 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 11830 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 11831 SDValue N1 = N->getOperand(1); 11832 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 11833 SDValue N0 = N->getOperand(0); 11834 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 11835 DAG.MaskedValueIsZero(N0.getOperand(0), 11836 APInt::getHighBitsSet(32, 16))) 11837 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 11838 } 11839 } 11840 11841 // Nothing to be done for scalar shifts. 11842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11843 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 11844 return SDValue(); 11845 11846 assert(ST->hasNEON() && "unexpected vector shift"); 11847 int64_t Cnt; 11848 11849 switch (N->getOpcode()) { 11850 default: llvm_unreachable("unexpected shift opcode"); 11851 11852 case ISD::SHL: 11853 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 11854 SDLoc dl(N); 11855 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 11856 DAG.getConstant(Cnt, dl, MVT::i32)); 11857 } 11858 break; 11859 11860 case ISD::SRA: 11861 case ISD::SRL: 11862 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 11863 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 11864 ARMISD::VSHRs : ARMISD::VSHRu); 11865 SDLoc dl(N); 11866 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 11867 DAG.getConstant(Cnt, dl, MVT::i32)); 11868 } 11869 } 11870 return SDValue(); 11871 } 11872 11873 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 11874 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 11875 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 11876 const ARMSubtarget *ST) { 11877 SDValue N0 = N->getOperand(0); 11878 11879 // Check for sign- and zero-extensions of vector extract operations of 8- 11880 // and 16-bit vector elements. NEON supports these directly. They are 11881 // handled during DAG combining because type legalization will promote them 11882 // to 32-bit types and it is messy to recognize the operations after that. 11883 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11884 SDValue Vec = N0.getOperand(0); 11885 SDValue Lane = N0.getOperand(1); 11886 EVT VT = N->getValueType(0); 11887 EVT EltVT = N0.getValueType(); 11888 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11889 11890 if (VT == MVT::i32 && 11891 (EltVT == MVT::i8 || EltVT == MVT::i16) && 11892 TLI.isTypeLegal(Vec.getValueType()) && 11893 isa<ConstantSDNode>(Lane)) { 11894 11895 unsigned Opc = 0; 11896 switch (N->getOpcode()) { 11897 default: llvm_unreachable("unexpected opcode"); 11898 case ISD::SIGN_EXTEND: 11899 Opc = ARMISD::VGETLANEs; 11900 break; 11901 case ISD::ZERO_EXTEND: 11902 case ISD::ANY_EXTEND: 11903 Opc = ARMISD::VGETLANEu; 11904 break; 11905 } 11906 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 11907 } 11908 } 11909 11910 return SDValue(); 11911 } 11912 11913 static const APInt *isPowerOf2Constant(SDValue V) { 11914 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 11915 if (!C) 11916 return nullptr; 11917 const APInt *CV = &C->getAPIntValue(); 11918 return CV->isPowerOf2() ? CV : nullptr; 11919 } 11920 11921 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 11922 // If we have a CMOV, OR and AND combination such as: 11923 // if (x & CN) 11924 // y |= CM; 11925 // 11926 // And: 11927 // * CN is a single bit; 11928 // * All bits covered by CM are known zero in y 11929 // 11930 // Then we can convert this into a sequence of BFI instructions. This will 11931 // always be a win if CM is a single bit, will always be no worse than the 11932 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 11933 // three bits (due to the extra IT instruction). 11934 11935 SDValue Op0 = CMOV->getOperand(0); 11936 SDValue Op1 = CMOV->getOperand(1); 11937 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 11938 auto CC = CCNode->getAPIntValue().getLimitedValue(); 11939 SDValue CmpZ = CMOV->getOperand(4); 11940 11941 // The compare must be against zero. 11942 if (!isNullConstant(CmpZ->getOperand(1))) 11943 return SDValue(); 11944 11945 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 11946 SDValue And = CmpZ->getOperand(0); 11947 if (And->getOpcode() != ISD::AND) 11948 return SDValue(); 11949 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 11950 if (!AndC) 11951 return SDValue(); 11952 SDValue X = And->getOperand(0); 11953 11954 if (CC == ARMCC::EQ) { 11955 // We're performing an "equal to zero" compare. Swap the operands so we 11956 // canonicalize on a "not equal to zero" compare. 11957 std::swap(Op0, Op1); 11958 } else { 11959 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 11960 } 11961 11962 if (Op1->getOpcode() != ISD::OR) 11963 return SDValue(); 11964 11965 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 11966 if (!OrC) 11967 return SDValue(); 11968 SDValue Y = Op1->getOperand(0); 11969 11970 if (Op0 != Y) 11971 return SDValue(); 11972 11973 // Now, is it profitable to continue? 11974 APInt OrCI = OrC->getAPIntValue(); 11975 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 11976 if (OrCI.countPopulation() > Heuristic) 11977 return SDValue(); 11978 11979 // Lastly, can we determine that the bits defined by OrCI 11980 // are zero in Y? 11981 KnownBits Known; 11982 DAG.computeKnownBits(Y, Known); 11983 if ((OrCI & Known.Zero) != OrCI) 11984 return SDValue(); 11985 11986 // OK, we can do the combine. 11987 SDValue V = Y; 11988 SDLoc dl(X); 11989 EVT VT = X.getValueType(); 11990 unsigned BitInX = AndC->logBase2(); 11991 11992 if (BitInX != 0) { 11993 // We must shift X first. 11994 X = DAG.getNode(ISD::SRL, dl, VT, X, 11995 DAG.getConstant(BitInX, dl, VT)); 11996 } 11997 11998 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 11999 BitInY < NumActiveBits; ++BitInY) { 12000 if (OrCI[BitInY] == 0) 12001 continue; 12002 APInt Mask(VT.getSizeInBits(), 0); 12003 Mask.setBit(BitInY); 12004 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12005 // Confusingly, the operand is an *inverted* mask. 12006 DAG.getConstant(~Mask, dl, VT)); 12007 } 12008 12009 return V; 12010 } 12011 12012 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12013 SDValue 12014 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12015 SDValue Cmp = N->getOperand(4); 12016 if (Cmp.getOpcode() != ARMISD::CMPZ) 12017 // Only looking at NE cases. 12018 return SDValue(); 12019 12020 EVT VT = N->getValueType(0); 12021 SDLoc dl(N); 12022 SDValue LHS = Cmp.getOperand(0); 12023 SDValue RHS = Cmp.getOperand(1); 12024 SDValue Chain = N->getOperand(0); 12025 SDValue BB = N->getOperand(1); 12026 SDValue ARMcc = N->getOperand(2); 12027 ARMCC::CondCodes CC = 12028 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12029 12030 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12031 // -> (brcond Chain BB CC CPSR Cmp) 12032 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12033 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12034 LHS->getOperand(0)->hasOneUse()) { 12035 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12036 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12037 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12038 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12039 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12040 (LHS01C && LHS01C->getZExtValue() == 1) && 12041 (LHS1C && LHS1C->getZExtValue() == 1) && 12042 (RHSC && RHSC->getZExtValue() == 0)) { 12043 return DAG.getNode( 12044 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12045 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12046 } 12047 } 12048 12049 return SDValue(); 12050 } 12051 12052 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12053 SDValue 12054 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12055 SDValue Cmp = N->getOperand(4); 12056 if (Cmp.getOpcode() != ARMISD::CMPZ) 12057 // Only looking at EQ and NE cases. 12058 return SDValue(); 12059 12060 EVT VT = N->getValueType(0); 12061 SDLoc dl(N); 12062 SDValue LHS = Cmp.getOperand(0); 12063 SDValue RHS = Cmp.getOperand(1); 12064 SDValue FalseVal = N->getOperand(0); 12065 SDValue TrueVal = N->getOperand(1); 12066 SDValue ARMcc = N->getOperand(2); 12067 ARMCC::CondCodes CC = 12068 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12069 12070 // BFI is only available on V6T2+. 12071 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12072 SDValue R = PerformCMOVToBFICombine(N, DAG); 12073 if (R) 12074 return R; 12075 } 12076 12077 // Simplify 12078 // mov r1, r0 12079 // cmp r1, x 12080 // mov r0, y 12081 // moveq r0, x 12082 // to 12083 // cmp r0, x 12084 // movne r0, y 12085 // 12086 // mov r1, r0 12087 // cmp r1, x 12088 // mov r0, x 12089 // movne r0, y 12090 // to 12091 // cmp r0, x 12092 // movne r0, y 12093 /// FIXME: Turn this into a target neutral optimization? 12094 SDValue Res; 12095 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12096 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12097 N->getOperand(3), Cmp); 12098 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12099 SDValue ARMcc; 12100 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12101 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12102 N->getOperand(3), NewCmp); 12103 } 12104 12105 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12106 // -> (cmov F T CC CPSR Cmp) 12107 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12108 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12109 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12110 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12111 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12112 (LHS1C && LHS1C->getZExtValue() == 1) && 12113 (RHSC && RHSC->getZExtValue() == 0)) { 12114 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12115 LHS->getOperand(2), LHS->getOperand(3), 12116 LHS->getOperand(4)); 12117 } 12118 } 12119 12120 if (Res.getNode()) { 12121 KnownBits Known; 12122 DAG.computeKnownBits(SDValue(N,0), Known); 12123 // Capture demanded bits information that would be otherwise lost. 12124 if (Known.Zero == 0xfffffffe) 12125 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12126 DAG.getValueType(MVT::i1)); 12127 else if (Known.Zero == 0xffffff00) 12128 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12129 DAG.getValueType(MVT::i8)); 12130 else if (Known.Zero == 0xffff0000) 12131 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12132 DAG.getValueType(MVT::i16)); 12133 } 12134 12135 return Res; 12136 } 12137 12138 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12139 DAGCombinerInfo &DCI) const { 12140 switch (N->getOpcode()) { 12141 default: break; 12142 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12143 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12144 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12145 case ISD::SUB: return PerformSUBCombine(N, DCI); 12146 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12147 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12148 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12149 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12150 case ARMISD::ADDC: 12151 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12152 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 12153 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12154 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12155 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12156 case ISD::STORE: return PerformSTORECombine(N, DCI); 12157 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12158 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12159 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12160 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12161 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12162 case ISD::FP_TO_SINT: 12163 case ISD::FP_TO_UINT: 12164 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12165 case ISD::FDIV: 12166 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12167 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12168 case ISD::SHL: 12169 case ISD::SRA: 12170 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 12171 case ISD::SIGN_EXTEND: 12172 case ISD::ZERO_EXTEND: 12173 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12174 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12175 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12176 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12177 case ARMISD::VLD1DUP: 12178 case ARMISD::VLD2DUP: 12179 case ARMISD::VLD3DUP: 12180 case ARMISD::VLD4DUP: 12181 return PerformVLDCombine(N, DCI); 12182 case ARMISD::BUILD_VECTOR: 12183 return PerformARMBUILD_VECTORCombine(N, DCI); 12184 case ARMISD::SMULWB: { 12185 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12186 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12187 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12188 return SDValue(); 12189 break; 12190 } 12191 case ARMISD::SMULWT: { 12192 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12193 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12194 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12195 return SDValue(); 12196 break; 12197 } 12198 case ARMISD::SMLALBB: { 12199 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12200 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12201 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12202 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12203 return SDValue(); 12204 break; 12205 } 12206 case ARMISD::SMLALBT: { 12207 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12208 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12209 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12210 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12211 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12212 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12213 return SDValue(); 12214 break; 12215 } 12216 case ARMISD::SMLALTB: { 12217 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12218 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12219 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12220 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12221 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12222 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12223 return SDValue(); 12224 break; 12225 } 12226 case ARMISD::SMLALTT: { 12227 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12228 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12229 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12230 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12231 return SDValue(); 12232 break; 12233 } 12234 case ISD::INTRINSIC_VOID: 12235 case ISD::INTRINSIC_W_CHAIN: 12236 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12237 case Intrinsic::arm_neon_vld1: 12238 case Intrinsic::arm_neon_vld2: 12239 case Intrinsic::arm_neon_vld3: 12240 case Intrinsic::arm_neon_vld4: 12241 case Intrinsic::arm_neon_vld2lane: 12242 case Intrinsic::arm_neon_vld3lane: 12243 case Intrinsic::arm_neon_vld4lane: 12244 case Intrinsic::arm_neon_vst1: 12245 case Intrinsic::arm_neon_vst2: 12246 case Intrinsic::arm_neon_vst3: 12247 case Intrinsic::arm_neon_vst4: 12248 case Intrinsic::arm_neon_vst2lane: 12249 case Intrinsic::arm_neon_vst3lane: 12250 case Intrinsic::arm_neon_vst4lane: 12251 return PerformVLDCombine(N, DCI); 12252 default: break; 12253 } 12254 break; 12255 } 12256 return SDValue(); 12257 } 12258 12259 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12260 EVT VT) const { 12261 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12262 } 12263 12264 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12265 unsigned, 12266 unsigned, 12267 bool *Fast) const { 12268 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12269 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12270 12271 switch (VT.getSimpleVT().SimpleTy) { 12272 default: 12273 return false; 12274 case MVT::i8: 12275 case MVT::i16: 12276 case MVT::i32: { 12277 // Unaligned access can use (for example) LRDB, LRDH, LDR 12278 if (AllowsUnaligned) { 12279 if (Fast) 12280 *Fast = Subtarget->hasV7Ops(); 12281 return true; 12282 } 12283 return false; 12284 } 12285 case MVT::f64: 12286 case MVT::v2f64: { 12287 // For any little-endian targets with neon, we can support unaligned ld/st 12288 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12289 // A big-endian target may also explicitly support unaligned accesses 12290 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12291 if (Fast) 12292 *Fast = true; 12293 return true; 12294 } 12295 return false; 12296 } 12297 } 12298 } 12299 12300 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12301 unsigned AlignCheck) { 12302 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12303 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12304 } 12305 12306 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12307 unsigned DstAlign, unsigned SrcAlign, 12308 bool IsMemset, bool ZeroMemset, 12309 bool MemcpyStrSrc, 12310 MachineFunction &MF) const { 12311 const Function *F = MF.getFunction(); 12312 12313 // See if we can use NEON instructions for this... 12314 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12315 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 12316 bool Fast; 12317 if (Size >= 16 && 12318 (memOpAlign(SrcAlign, DstAlign, 16) || 12319 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12320 return MVT::v2f64; 12321 } else if (Size >= 8 && 12322 (memOpAlign(SrcAlign, DstAlign, 8) || 12323 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12324 Fast))) { 12325 return MVT::f64; 12326 } 12327 } 12328 12329 // Let the target-independent logic figure it out. 12330 return MVT::Other; 12331 } 12332 12333 // 64-bit integers are split into their high and low parts and held in two 12334 // different registers, so the trunc is free since the low register can just 12335 // be used. 12336 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 12337 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 12338 return false; 12339 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 12340 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 12341 return (SrcBits == 64 && DestBits == 32); 12342 } 12343 12344 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 12345 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 12346 !DstVT.isInteger()) 12347 return false; 12348 unsigned SrcBits = SrcVT.getSizeInBits(); 12349 unsigned DestBits = DstVT.getSizeInBits(); 12350 return (SrcBits == 64 && DestBits == 32); 12351 } 12352 12353 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12354 if (Val.getOpcode() != ISD::LOAD) 12355 return false; 12356 12357 EVT VT1 = Val.getValueType(); 12358 if (!VT1.isSimple() || !VT1.isInteger() || 12359 !VT2.isSimple() || !VT2.isInteger()) 12360 return false; 12361 12362 switch (VT1.getSimpleVT().SimpleTy) { 12363 default: break; 12364 case MVT::i1: 12365 case MVT::i8: 12366 case MVT::i16: 12367 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12368 return true; 12369 } 12370 12371 return false; 12372 } 12373 12374 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12375 EVT VT = ExtVal.getValueType(); 12376 12377 if (!isTypeLegal(VT)) 12378 return false; 12379 12380 // Don't create a loadext if we can fold the extension into a wide/long 12381 // instruction. 12382 // If there's more than one user instruction, the loadext is desirable no 12383 // matter what. There can be two uses by the same instruction. 12384 if (ExtVal->use_empty() || 12385 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12386 return true; 12387 12388 SDNode *U = *ExtVal->use_begin(); 12389 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12390 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12391 return false; 12392 12393 return true; 12394 } 12395 12396 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12397 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12398 return false; 12399 12400 if (!isTypeLegal(EVT::getEVT(Ty1))) 12401 return false; 12402 12403 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12404 12405 // Assuming the caller doesn't have a zeroext or signext return parameter, 12406 // truncation all the way down to i1 is valid. 12407 return true; 12408 } 12409 12410 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12411 const AddrMode &AM, Type *Ty, 12412 unsigned AS) const { 12413 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12414 if (Subtarget->hasFPAO()) 12415 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12416 return 0; 12417 } 12418 return -1; 12419 } 12420 12421 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 12422 if (V < 0) 12423 return false; 12424 12425 unsigned Scale = 1; 12426 switch (VT.getSimpleVT().SimpleTy) { 12427 default: return false; 12428 case MVT::i1: 12429 case MVT::i8: 12430 // Scale == 1; 12431 break; 12432 case MVT::i16: 12433 // Scale == 2; 12434 Scale = 2; 12435 break; 12436 case MVT::i32: 12437 // Scale == 4; 12438 Scale = 4; 12439 break; 12440 } 12441 12442 if ((V & (Scale - 1)) != 0) 12443 return false; 12444 V /= Scale; 12445 return V == (V & ((1LL << 5) - 1)); 12446 } 12447 12448 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 12449 const ARMSubtarget *Subtarget) { 12450 bool isNeg = false; 12451 if (V < 0) { 12452 isNeg = true; 12453 V = - V; 12454 } 12455 12456 switch (VT.getSimpleVT().SimpleTy) { 12457 default: return false; 12458 case MVT::i1: 12459 case MVT::i8: 12460 case MVT::i16: 12461 case MVT::i32: 12462 // + imm12 or - imm8 12463 if (isNeg) 12464 return V == (V & ((1LL << 8) - 1)); 12465 return V == (V & ((1LL << 12) - 1)); 12466 case MVT::f32: 12467 case MVT::f64: 12468 // Same as ARM mode. FIXME: NEON? 12469 if (!Subtarget->hasVFP2()) 12470 return false; 12471 if ((V & 3) != 0) 12472 return false; 12473 V >>= 2; 12474 return V == (V & ((1LL << 8) - 1)); 12475 } 12476 } 12477 12478 /// isLegalAddressImmediate - Return true if the integer value can be used 12479 /// as the offset of the target addressing mode for load / store of the 12480 /// given type. 12481 static bool isLegalAddressImmediate(int64_t V, EVT VT, 12482 const ARMSubtarget *Subtarget) { 12483 if (V == 0) 12484 return true; 12485 12486 if (!VT.isSimple()) 12487 return false; 12488 12489 if (Subtarget->isThumb1Only()) 12490 return isLegalT1AddressImmediate(V, VT); 12491 else if (Subtarget->isThumb2()) 12492 return isLegalT2AddressImmediate(V, VT, Subtarget); 12493 12494 // ARM mode. 12495 if (V < 0) 12496 V = - V; 12497 switch (VT.getSimpleVT().SimpleTy) { 12498 default: return false; 12499 case MVT::i1: 12500 case MVT::i8: 12501 case MVT::i32: 12502 // +- imm12 12503 return V == (V & ((1LL << 12) - 1)); 12504 case MVT::i16: 12505 // +- imm8 12506 return V == (V & ((1LL << 8) - 1)); 12507 case MVT::f32: 12508 case MVT::f64: 12509 if (!Subtarget->hasVFP2()) // FIXME: NEON? 12510 return false; 12511 if ((V & 3) != 0) 12512 return false; 12513 V >>= 2; 12514 return V == (V & ((1LL << 8) - 1)); 12515 } 12516 } 12517 12518 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 12519 EVT VT) const { 12520 int Scale = AM.Scale; 12521 if (Scale < 0) 12522 return false; 12523 12524 switch (VT.getSimpleVT().SimpleTy) { 12525 default: return false; 12526 case MVT::i1: 12527 case MVT::i8: 12528 case MVT::i16: 12529 case MVT::i32: 12530 if (Scale == 1) 12531 return true; 12532 // r + r << imm 12533 Scale = Scale & ~1; 12534 return Scale == 2 || Scale == 4 || Scale == 8; 12535 case MVT::i64: 12536 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 12537 // version in Thumb mode. 12538 // r + r 12539 if (Scale == 1) 12540 return true; 12541 // r * 2 (this can be lowered to r + r). 12542 if (!AM.HasBaseReg && Scale == 2) 12543 return true; 12544 return false; 12545 case MVT::isVoid: 12546 // Note, we allow "void" uses (basically, uses that aren't loads or 12547 // stores), because arm allows folding a scale into many arithmetic 12548 // operations. This should be made more precise and revisited later. 12549 12550 // Allow r << imm, but the imm has to be a multiple of two. 12551 if (Scale & 1) return false; 12552 return isPowerOf2_32(Scale); 12553 } 12554 } 12555 12556 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 12557 EVT VT) const { 12558 const int Scale = AM.Scale; 12559 12560 // Negative scales are not supported in Thumb1. 12561 if (Scale < 0) 12562 return false; 12563 12564 // Thumb1 addressing modes do not support register scaling excepting the 12565 // following cases: 12566 // 1. Scale == 1 means no scaling. 12567 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 12568 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 12569 } 12570 12571 /// isLegalAddressingMode - Return true if the addressing mode represented 12572 /// by AM is legal for this target, for a load/store of the specified type. 12573 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12574 const AddrMode &AM, Type *Ty, 12575 unsigned AS, Instruction *I) const { 12576 EVT VT = getValueType(DL, Ty, true); 12577 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 12578 return false; 12579 12580 // Can never fold addr of global into load/store. 12581 if (AM.BaseGV) 12582 return false; 12583 12584 switch (AM.Scale) { 12585 case 0: // no scale reg, must be "r+i" or "r", or "i". 12586 break; 12587 default: 12588 // ARM doesn't support any R+R*scale+imm addr modes. 12589 if (AM.BaseOffs) 12590 return false; 12591 12592 if (!VT.isSimple()) 12593 return false; 12594 12595 if (Subtarget->isThumb1Only()) 12596 return isLegalT1ScaledAddressingMode(AM, VT); 12597 12598 if (Subtarget->isThumb2()) 12599 return isLegalT2ScaledAddressingMode(AM, VT); 12600 12601 int Scale = AM.Scale; 12602 switch (VT.getSimpleVT().SimpleTy) { 12603 default: return false; 12604 case MVT::i1: 12605 case MVT::i8: 12606 case MVT::i32: 12607 if (Scale < 0) Scale = -Scale; 12608 if (Scale == 1) 12609 return true; 12610 // r + r << imm 12611 return isPowerOf2_32(Scale & ~1); 12612 case MVT::i16: 12613 case MVT::i64: 12614 // r +/- r 12615 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 12616 return true; 12617 // r * 2 (this can be lowered to r + r). 12618 if (!AM.HasBaseReg && Scale == 2) 12619 return true; 12620 return false; 12621 12622 case MVT::isVoid: 12623 // Note, we allow "void" uses (basically, uses that aren't loads or 12624 // stores), because arm allows folding a scale into many arithmetic 12625 // operations. This should be made more precise and revisited later. 12626 12627 // Allow r << imm, but the imm has to be a multiple of two. 12628 if (Scale & 1) return false; 12629 return isPowerOf2_32(Scale); 12630 } 12631 } 12632 return true; 12633 } 12634 12635 /// isLegalICmpImmediate - Return true if the specified immediate is legal 12636 /// icmp immediate, that is the target has icmp instructions which can compare 12637 /// a register against the immediate without having to materialize the 12638 /// immediate into a register. 12639 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12640 // Thumb2 and ARM modes can use cmn for negative immediates. 12641 if (!Subtarget->isThumb()) 12642 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 12643 if (Subtarget->isThumb2()) 12644 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 12645 // Thumb1 doesn't have cmn, and only 8-bit immediates. 12646 return Imm >= 0 && Imm <= 255; 12647 } 12648 12649 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 12650 /// *or sub* immediate, that is the target has add or sub instructions which can 12651 /// add a register with the immediate without having to materialize the 12652 /// immediate into a register. 12653 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 12654 // Same encoding for add/sub, just flip the sign. 12655 int64_t AbsImm = std::abs(Imm); 12656 if (!Subtarget->isThumb()) 12657 return ARM_AM::getSOImmVal(AbsImm) != -1; 12658 if (Subtarget->isThumb2()) 12659 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 12660 // Thumb1 only has 8-bit unsigned immediate. 12661 return AbsImm >= 0 && AbsImm <= 255; 12662 } 12663 12664 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 12665 bool isSEXTLoad, SDValue &Base, 12666 SDValue &Offset, bool &isInc, 12667 SelectionDAG &DAG) { 12668 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12669 return false; 12670 12671 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 12672 // AddressingMode 3 12673 Base = Ptr->getOperand(0); 12674 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12675 int RHSC = (int)RHS->getZExtValue(); 12676 if (RHSC < 0 && RHSC > -256) { 12677 assert(Ptr->getOpcode() == ISD::ADD); 12678 isInc = false; 12679 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12680 return true; 12681 } 12682 } 12683 isInc = (Ptr->getOpcode() == ISD::ADD); 12684 Offset = Ptr->getOperand(1); 12685 return true; 12686 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 12687 // AddressingMode 2 12688 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12689 int RHSC = (int)RHS->getZExtValue(); 12690 if (RHSC < 0 && RHSC > -0x1000) { 12691 assert(Ptr->getOpcode() == ISD::ADD); 12692 isInc = false; 12693 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12694 Base = Ptr->getOperand(0); 12695 return true; 12696 } 12697 } 12698 12699 if (Ptr->getOpcode() == ISD::ADD) { 12700 isInc = true; 12701 ARM_AM::ShiftOpc ShOpcVal= 12702 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 12703 if (ShOpcVal != ARM_AM::no_shift) { 12704 Base = Ptr->getOperand(1); 12705 Offset = Ptr->getOperand(0); 12706 } else { 12707 Base = Ptr->getOperand(0); 12708 Offset = Ptr->getOperand(1); 12709 } 12710 return true; 12711 } 12712 12713 isInc = (Ptr->getOpcode() == ISD::ADD); 12714 Base = Ptr->getOperand(0); 12715 Offset = Ptr->getOperand(1); 12716 return true; 12717 } 12718 12719 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 12720 return false; 12721 } 12722 12723 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 12724 bool isSEXTLoad, SDValue &Base, 12725 SDValue &Offset, bool &isInc, 12726 SelectionDAG &DAG) { 12727 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12728 return false; 12729 12730 Base = Ptr->getOperand(0); 12731 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12732 int RHSC = (int)RHS->getZExtValue(); 12733 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 12734 assert(Ptr->getOpcode() == ISD::ADD); 12735 isInc = false; 12736 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12737 return true; 12738 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 12739 isInc = Ptr->getOpcode() == ISD::ADD; 12740 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12741 return true; 12742 } 12743 } 12744 12745 return false; 12746 } 12747 12748 /// getPreIndexedAddressParts - returns true by value, base pointer and 12749 /// offset pointer and addressing mode by reference if the node's address 12750 /// can be legally represented as pre-indexed load / store address. 12751 bool 12752 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 12753 SDValue &Offset, 12754 ISD::MemIndexedMode &AM, 12755 SelectionDAG &DAG) const { 12756 if (Subtarget->isThumb1Only()) 12757 return false; 12758 12759 EVT VT; 12760 SDValue Ptr; 12761 bool isSEXTLoad = false; 12762 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12763 Ptr = LD->getBasePtr(); 12764 VT = LD->getMemoryVT(); 12765 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12766 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12767 Ptr = ST->getBasePtr(); 12768 VT = ST->getMemoryVT(); 12769 } else 12770 return false; 12771 12772 bool isInc; 12773 bool isLegal = false; 12774 if (Subtarget->isThumb2()) 12775 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12776 Offset, isInc, DAG); 12777 else 12778 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12779 Offset, isInc, DAG); 12780 if (!isLegal) 12781 return false; 12782 12783 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 12784 return true; 12785 } 12786 12787 /// getPostIndexedAddressParts - returns true by value, base pointer and 12788 /// offset pointer and addressing mode by reference if this node can be 12789 /// combined with a load / store to form a post-indexed load / store. 12790 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 12791 SDValue &Base, 12792 SDValue &Offset, 12793 ISD::MemIndexedMode &AM, 12794 SelectionDAG &DAG) const { 12795 EVT VT; 12796 SDValue Ptr; 12797 bool isSEXTLoad = false, isNonExt; 12798 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12799 VT = LD->getMemoryVT(); 12800 Ptr = LD->getBasePtr(); 12801 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12802 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 12803 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12804 VT = ST->getMemoryVT(); 12805 Ptr = ST->getBasePtr(); 12806 isNonExt = !ST->isTruncatingStore(); 12807 } else 12808 return false; 12809 12810 if (Subtarget->isThumb1Only()) { 12811 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 12812 // must be non-extending/truncating, i32, with an offset of 4. 12813 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 12814 if (Op->getOpcode() != ISD::ADD || !isNonExt) 12815 return false; 12816 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 12817 if (!RHS || RHS->getZExtValue() != 4) 12818 return false; 12819 12820 Offset = Op->getOperand(1); 12821 Base = Op->getOperand(0); 12822 AM = ISD::POST_INC; 12823 return true; 12824 } 12825 12826 bool isInc; 12827 bool isLegal = false; 12828 if (Subtarget->isThumb2()) 12829 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12830 isInc, DAG); 12831 else 12832 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12833 isInc, DAG); 12834 if (!isLegal) 12835 return false; 12836 12837 if (Ptr != Base) { 12838 // Swap base ptr and offset to catch more post-index load / store when 12839 // it's legal. In Thumb2 mode, offset must be an immediate. 12840 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 12841 !Subtarget->isThumb2()) 12842 std::swap(Base, Offset); 12843 12844 // Post-indexed load / store update the base pointer. 12845 if (Ptr != Base) 12846 return false; 12847 } 12848 12849 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 12850 return true; 12851 } 12852 12853 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12854 KnownBits &Known, 12855 const APInt &DemandedElts, 12856 const SelectionDAG &DAG, 12857 unsigned Depth) const { 12858 unsigned BitWidth = Known.getBitWidth(); 12859 Known.resetAll(); 12860 switch (Op.getOpcode()) { 12861 default: break; 12862 case ARMISD::ADDC: 12863 case ARMISD::ADDE: 12864 case ARMISD::SUBC: 12865 case ARMISD::SUBE: 12866 // Special cases when we convert a carry to a boolean. 12867 if (Op.getResNo() == 0) { 12868 SDValue LHS = Op.getOperand(0); 12869 SDValue RHS = Op.getOperand(1); 12870 // (ADDE 0, 0, C) will give us a single bit. 12871 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 12872 isNullConstant(RHS)) { 12873 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 12874 return; 12875 } 12876 } 12877 break; 12878 case ARMISD::CMOV: { 12879 // Bits are known zero/one if known on the LHS and RHS. 12880 DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1); 12881 if (Known.isUnknown()) 12882 return; 12883 12884 KnownBits KnownRHS; 12885 DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1); 12886 Known.Zero &= KnownRHS.Zero; 12887 Known.One &= KnownRHS.One; 12888 return; 12889 } 12890 case ISD::INTRINSIC_W_CHAIN: { 12891 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 12892 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 12893 switch (IntID) { 12894 default: return; 12895 case Intrinsic::arm_ldaex: 12896 case Intrinsic::arm_ldrex: { 12897 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 12898 unsigned MemBits = VT.getScalarSizeInBits(); 12899 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 12900 return; 12901 } 12902 } 12903 } 12904 case ARMISD::BFI: { 12905 // Conservatively, we can recurse down the first operand 12906 // and just mask out all affected bits. 12907 DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1); 12908 12909 // The operand to BFI is already a mask suitable for removing the bits it 12910 // sets. 12911 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 12912 const APInt &Mask = CI->getAPIntValue(); 12913 Known.Zero &= Mask; 12914 Known.One &= Mask; 12915 return; 12916 } 12917 } 12918 } 12919 12920 //===----------------------------------------------------------------------===// 12921 // ARM Inline Assembly Support 12922 //===----------------------------------------------------------------------===// 12923 12924 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 12925 // Looking for "rev" which is V6+. 12926 if (!Subtarget->hasV6Ops()) 12927 return false; 12928 12929 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 12930 std::string AsmStr = IA->getAsmString(); 12931 SmallVector<StringRef, 4> AsmPieces; 12932 SplitString(AsmStr, AsmPieces, ";\n"); 12933 12934 switch (AsmPieces.size()) { 12935 default: return false; 12936 case 1: 12937 AsmStr = AsmPieces[0]; 12938 AsmPieces.clear(); 12939 SplitString(AsmStr, AsmPieces, " \t,"); 12940 12941 // rev $0, $1 12942 if (AsmPieces.size() == 3 && 12943 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 12944 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 12945 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12946 if (Ty && Ty->getBitWidth() == 32) 12947 return IntrinsicLowering::LowerToByteSwap(CI); 12948 } 12949 break; 12950 } 12951 12952 return false; 12953 } 12954 12955 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 12956 // At this point, we have to lower this constraint to something else, so we 12957 // lower it to an "r" or "w". However, by doing this we will force the result 12958 // to be in register, while the X constraint is much more permissive. 12959 // 12960 // Although we are correct (we are free to emit anything, without 12961 // constraints), we might break use cases that would expect us to be more 12962 // efficient and emit something else. 12963 if (!Subtarget->hasVFP2()) 12964 return "r"; 12965 if (ConstraintVT.isFloatingPoint()) 12966 return "w"; 12967 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 12968 (ConstraintVT.getSizeInBits() == 64 || 12969 ConstraintVT.getSizeInBits() == 128)) 12970 return "w"; 12971 12972 return "r"; 12973 } 12974 12975 /// getConstraintType - Given a constraint letter, return the type of 12976 /// constraint it is for this target. 12977 ARMTargetLowering::ConstraintType 12978 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 12979 if (Constraint.size() == 1) { 12980 switch (Constraint[0]) { 12981 default: break; 12982 case 'l': return C_RegisterClass; 12983 case 'w': return C_RegisterClass; 12984 case 'h': return C_RegisterClass; 12985 case 'x': return C_RegisterClass; 12986 case 't': return C_RegisterClass; 12987 case 'j': return C_Other; // Constant for movw. 12988 // An address with a single base register. Due to the way we 12989 // currently handle addresses it is the same as an 'r' memory constraint. 12990 case 'Q': return C_Memory; 12991 } 12992 } else if (Constraint.size() == 2) { 12993 switch (Constraint[0]) { 12994 default: break; 12995 // All 'U+' constraints are addresses. 12996 case 'U': return C_Memory; 12997 } 12998 } 12999 return TargetLowering::getConstraintType(Constraint); 13000 } 13001 13002 /// Examine constraint type and operand type and determine a weight value. 13003 /// This object must already have been set up with the operand type 13004 /// and the current alternative constraint selected. 13005 TargetLowering::ConstraintWeight 13006 ARMTargetLowering::getSingleConstraintMatchWeight( 13007 AsmOperandInfo &info, const char *constraint) const { 13008 ConstraintWeight weight = CW_Invalid; 13009 Value *CallOperandVal = info.CallOperandVal; 13010 // If we don't have a value, we can't do a match, 13011 // but allow it at the lowest weight. 13012 if (!CallOperandVal) 13013 return CW_Default; 13014 Type *type = CallOperandVal->getType(); 13015 // Look at the constraint type. 13016 switch (*constraint) { 13017 default: 13018 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13019 break; 13020 case 'l': 13021 if (type->isIntegerTy()) { 13022 if (Subtarget->isThumb()) 13023 weight = CW_SpecificReg; 13024 else 13025 weight = CW_Register; 13026 } 13027 break; 13028 case 'w': 13029 if (type->isFloatingPointTy()) 13030 weight = CW_Register; 13031 break; 13032 } 13033 return weight; 13034 } 13035 13036 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13037 13038 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13039 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13040 if (Constraint.size() == 1) { 13041 // GCC ARM Constraint Letters 13042 switch (Constraint[0]) { 13043 case 'l': // Low regs or general regs. 13044 if (Subtarget->isThumb()) 13045 return RCPair(0U, &ARM::tGPRRegClass); 13046 return RCPair(0U, &ARM::GPRRegClass); 13047 case 'h': // High regs or no regs. 13048 if (Subtarget->isThumb()) 13049 return RCPair(0U, &ARM::hGPRRegClass); 13050 break; 13051 case 'r': 13052 if (Subtarget->isThumb1Only()) 13053 return RCPair(0U, &ARM::tGPRRegClass); 13054 return RCPair(0U, &ARM::GPRRegClass); 13055 case 'w': 13056 if (VT == MVT::Other) 13057 break; 13058 if (VT == MVT::f32) 13059 return RCPair(0U, &ARM::SPRRegClass); 13060 if (VT.getSizeInBits() == 64) 13061 return RCPair(0U, &ARM::DPRRegClass); 13062 if (VT.getSizeInBits() == 128) 13063 return RCPair(0U, &ARM::QPRRegClass); 13064 break; 13065 case 'x': 13066 if (VT == MVT::Other) 13067 break; 13068 if (VT == MVT::f32) 13069 return RCPair(0U, &ARM::SPR_8RegClass); 13070 if (VT.getSizeInBits() == 64) 13071 return RCPair(0U, &ARM::DPR_8RegClass); 13072 if (VT.getSizeInBits() == 128) 13073 return RCPair(0U, &ARM::QPR_8RegClass); 13074 break; 13075 case 't': 13076 if (VT == MVT::f32) 13077 return RCPair(0U, &ARM::SPRRegClass); 13078 break; 13079 } 13080 } 13081 if (StringRef("{cc}").equals_lower(Constraint)) 13082 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 13083 13084 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13085 } 13086 13087 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13088 /// vector. If it is invalid, don't add anything to Ops. 13089 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13090 std::string &Constraint, 13091 std::vector<SDValue>&Ops, 13092 SelectionDAG &DAG) const { 13093 SDValue Result; 13094 13095 // Currently only support length 1 constraints. 13096 if (Constraint.length() != 1) return; 13097 13098 char ConstraintLetter = Constraint[0]; 13099 switch (ConstraintLetter) { 13100 default: break; 13101 case 'j': 13102 case 'I': case 'J': case 'K': case 'L': 13103 case 'M': case 'N': case 'O': 13104 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 13105 if (!C) 13106 return; 13107 13108 int64_t CVal64 = C->getSExtValue(); 13109 int CVal = (int) CVal64; 13110 // None of these constraints allow values larger than 32 bits. Check 13111 // that the value fits in an int. 13112 if (CVal != CVal64) 13113 return; 13114 13115 switch (ConstraintLetter) { 13116 case 'j': 13117 // Constant suitable for movw, must be between 0 and 13118 // 65535. 13119 if (Subtarget->hasV6T2Ops()) 13120 if (CVal >= 0 && CVal <= 65535) 13121 break; 13122 return; 13123 case 'I': 13124 if (Subtarget->isThumb1Only()) { 13125 // This must be a constant between 0 and 255, for ADD 13126 // immediates. 13127 if (CVal >= 0 && CVal <= 255) 13128 break; 13129 } else if (Subtarget->isThumb2()) { 13130 // A constant that can be used as an immediate value in a 13131 // data-processing instruction. 13132 if (ARM_AM::getT2SOImmVal(CVal) != -1) 13133 break; 13134 } else { 13135 // A constant that can be used as an immediate value in a 13136 // data-processing instruction. 13137 if (ARM_AM::getSOImmVal(CVal) != -1) 13138 break; 13139 } 13140 return; 13141 13142 case 'J': 13143 if (Subtarget->isThumb1Only()) { 13144 // This must be a constant between -255 and -1, for negated ADD 13145 // immediates. This can be used in GCC with an "n" modifier that 13146 // prints the negated value, for use with SUB instructions. It is 13147 // not useful otherwise but is implemented for compatibility. 13148 if (CVal >= -255 && CVal <= -1) 13149 break; 13150 } else { 13151 // This must be a constant between -4095 and 4095. It is not clear 13152 // what this constraint is intended for. Implemented for 13153 // compatibility with GCC. 13154 if (CVal >= -4095 && CVal <= 4095) 13155 break; 13156 } 13157 return; 13158 13159 case 'K': 13160 if (Subtarget->isThumb1Only()) { 13161 // A 32-bit value where only one byte has a nonzero value. Exclude 13162 // zero to match GCC. This constraint is used by GCC internally for 13163 // constants that can be loaded with a move/shift combination. 13164 // It is not useful otherwise but is implemented for compatibility. 13165 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 13166 break; 13167 } else if (Subtarget->isThumb2()) { 13168 // A constant whose bitwise inverse can be used as an immediate 13169 // value in a data-processing instruction. This can be used in GCC 13170 // with a "B" modifier that prints the inverted value, for use with 13171 // BIC and MVN instructions. It is not useful otherwise but is 13172 // implemented for compatibility. 13173 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 13174 break; 13175 } else { 13176 // A constant whose bitwise inverse can be used as an immediate 13177 // value in a data-processing instruction. This can be used in GCC 13178 // with a "B" modifier that prints the inverted value, for use with 13179 // BIC and MVN instructions. It is not useful otherwise but is 13180 // implemented for compatibility. 13181 if (ARM_AM::getSOImmVal(~CVal) != -1) 13182 break; 13183 } 13184 return; 13185 13186 case 'L': 13187 if (Subtarget->isThumb1Only()) { 13188 // This must be a constant between -7 and 7, 13189 // for 3-operand ADD/SUB immediate instructions. 13190 if (CVal >= -7 && CVal < 7) 13191 break; 13192 } else if (Subtarget->isThumb2()) { 13193 // A constant whose negation can be used as an immediate value in a 13194 // data-processing instruction. This can be used in GCC with an "n" 13195 // modifier that prints the negated value, for use with SUB 13196 // instructions. It is not useful otherwise but is implemented for 13197 // compatibility. 13198 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 13199 break; 13200 } else { 13201 // A constant whose negation can be used as an immediate value in a 13202 // data-processing instruction. This can be used in GCC with an "n" 13203 // modifier that prints the negated value, for use with SUB 13204 // instructions. It is not useful otherwise but is implemented for 13205 // compatibility. 13206 if (ARM_AM::getSOImmVal(-CVal) != -1) 13207 break; 13208 } 13209 return; 13210 13211 case 'M': 13212 if (Subtarget->isThumb1Only()) { 13213 // This must be a multiple of 4 between 0 and 1020, for 13214 // ADD sp + immediate. 13215 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 13216 break; 13217 } else { 13218 // A power of two or a constant between 0 and 32. This is used in 13219 // GCC for the shift amount on shifted register operands, but it is 13220 // useful in general for any shift amounts. 13221 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 13222 break; 13223 } 13224 return; 13225 13226 case 'N': 13227 if (Subtarget->isThumb()) { // FIXME thumb2 13228 // This must be a constant between 0 and 31, for shift amounts. 13229 if (CVal >= 0 && CVal <= 31) 13230 break; 13231 } 13232 return; 13233 13234 case 'O': 13235 if (Subtarget->isThumb()) { // FIXME thumb2 13236 // This must be a multiple of 4 between -508 and 508, for 13237 // ADD/SUB sp = sp + immediate. 13238 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 13239 break; 13240 } 13241 return; 13242 } 13243 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 13244 break; 13245 } 13246 13247 if (Result.getNode()) { 13248 Ops.push_back(Result); 13249 return; 13250 } 13251 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13252 } 13253 13254 static RTLIB::Libcall getDivRemLibcall( 13255 const SDNode *N, MVT::SimpleValueType SVT) { 13256 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13257 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13258 "Unhandled Opcode in getDivRemLibcall"); 13259 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13260 N->getOpcode() == ISD::SREM; 13261 RTLIB::Libcall LC; 13262 switch (SVT) { 13263 default: llvm_unreachable("Unexpected request for libcall!"); 13264 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 13265 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 13266 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 13267 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 13268 } 13269 return LC; 13270 } 13271 13272 static TargetLowering::ArgListTy getDivRemArgList( 13273 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13274 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13275 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13276 "Unhandled Opcode in getDivRemArgList"); 13277 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13278 N->getOpcode() == ISD::SREM; 13279 TargetLowering::ArgListTy Args; 13280 TargetLowering::ArgListEntry Entry; 13281 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13282 EVT ArgVT = N->getOperand(i).getValueType(); 13283 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13284 Entry.Node = N->getOperand(i); 13285 Entry.Ty = ArgTy; 13286 Entry.IsSExt = isSigned; 13287 Entry.IsZExt = !isSigned; 13288 Args.push_back(Entry); 13289 } 13290 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13291 std::swap(Args[0], Args[1]); 13292 return Args; 13293 } 13294 13295 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13296 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13297 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13298 Subtarget->isTargetWindows()) && 13299 "Register-based DivRem lowering only"); 13300 unsigned Opcode = Op->getOpcode(); 13301 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13302 "Invalid opcode for Div/Rem lowering"); 13303 bool isSigned = (Opcode == ISD::SDIVREM); 13304 EVT VT = Op->getValueType(0); 13305 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13306 SDLoc dl(Op); 13307 13308 // If the target has hardware divide, use divide + multiply + subtract: 13309 // div = a / b 13310 // rem = a - b * div 13311 // return {div, rem} 13312 // This should be lowered into UDIV/SDIV + MLS later on. 13313 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 13314 : Subtarget->hasDivideInARMMode(); 13315 if (hasDivide && Op->getValueType(0).isSimple() && 13316 Op->getSimpleValueType(0) == MVT::i32) { 13317 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13318 const SDValue Dividend = Op->getOperand(0); 13319 const SDValue Divisor = Op->getOperand(1); 13320 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13321 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13322 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13323 13324 SDValue Values[2] = {Div, Rem}; 13325 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13326 } 13327 13328 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13329 VT.getSimpleVT().SimpleTy); 13330 SDValue InChain = DAG.getEntryNode(); 13331 13332 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13333 DAG.getContext(), 13334 Subtarget); 13335 13336 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13337 getPointerTy(DAG.getDataLayout())); 13338 13339 Type *RetTy = StructType::get(Ty, Ty); 13340 13341 if (Subtarget->isTargetWindows()) 13342 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13343 13344 TargetLowering::CallLoweringInfo CLI(DAG); 13345 CLI.setDebugLoc(dl).setChain(InChain) 13346 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13347 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13348 13349 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13350 return CallInfo.first; 13351 } 13352 13353 // Lowers REM using divmod helpers 13354 // see RTABI section 4.2/4.3 13355 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13356 // Build return types (div and rem) 13357 std::vector<Type*> RetTyParams; 13358 Type *RetTyElement; 13359 13360 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13361 default: llvm_unreachable("Unexpected request for libcall!"); 13362 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13363 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13364 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13365 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13366 } 13367 13368 RetTyParams.push_back(RetTyElement); 13369 RetTyParams.push_back(RetTyElement); 13370 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13371 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13372 13373 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13374 SimpleTy); 13375 SDValue InChain = DAG.getEntryNode(); 13376 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13377 Subtarget); 13378 bool isSigned = N->getOpcode() == ISD::SREM; 13379 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13380 getPointerTy(DAG.getDataLayout())); 13381 13382 if (Subtarget->isTargetWindows()) 13383 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13384 13385 // Lower call 13386 CallLoweringInfo CLI(DAG); 13387 CLI.setChain(InChain) 13388 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13389 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13390 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13391 13392 // Return second (rem) result operand (first contains div) 13393 SDNode *ResNode = CallResult.first.getNode(); 13394 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13395 return ResNode->getOperand(1); 13396 } 13397 13398 SDValue 13399 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13400 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13401 SDLoc DL(Op); 13402 13403 // Get the inputs. 13404 SDValue Chain = Op.getOperand(0); 13405 SDValue Size = Op.getOperand(1); 13406 13407 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 13408 DAG.getConstant(2, DL, MVT::i32)); 13409 13410 SDValue Flag; 13411 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 13412 Flag = Chain.getValue(1); 13413 13414 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 13415 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 13416 13417 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13418 Chain = NewSP.getValue(1); 13419 13420 SDValue Ops[2] = { NewSP, Chain }; 13421 return DAG.getMergeValues(Ops, DL); 13422 } 13423 13424 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 13425 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 13426 "Unexpected type for custom-lowering FP_EXTEND"); 13427 13428 RTLIB::Libcall LC; 13429 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 13430 13431 SDValue SrcVal = Op.getOperand(0); 13432 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13433 SDLoc(Op)).first; 13434 } 13435 13436 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 13437 assert(Op.getOperand(0).getValueType() == MVT::f64 && 13438 Subtarget->isFPOnlySP() && 13439 "Unexpected type for custom-lowering FP_ROUND"); 13440 13441 RTLIB::Libcall LC; 13442 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 13443 13444 SDValue SrcVal = Op.getOperand(0); 13445 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13446 SDLoc(Op)).first; 13447 } 13448 13449 bool 13450 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13451 // The ARM target isn't yet aware of offsets. 13452 return false; 13453 } 13454 13455 bool ARM::isBitFieldInvertedMask(unsigned v) { 13456 if (v == 0xffffffff) 13457 return false; 13458 13459 // there can be 1's on either or both "outsides", all the "inside" 13460 // bits must be 0's 13461 return isShiftedMask_32(~v); 13462 } 13463 13464 /// isFPImmLegal - Returns true if the target can instruction select the 13465 /// specified FP immediate natively. If false, the legalizer will 13466 /// materialize the FP immediate as a load from a constant pool. 13467 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13468 if (!Subtarget->hasVFP3()) 13469 return false; 13470 if (VT == MVT::f32) 13471 return ARM_AM::getFP32Imm(Imm) != -1; 13472 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 13473 return ARM_AM::getFP64Imm(Imm) != -1; 13474 return false; 13475 } 13476 13477 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 13478 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 13479 /// specified in the intrinsic calls. 13480 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13481 const CallInst &I, 13482 unsigned Intrinsic) const { 13483 switch (Intrinsic) { 13484 case Intrinsic::arm_neon_vld1: 13485 case Intrinsic::arm_neon_vld2: 13486 case Intrinsic::arm_neon_vld3: 13487 case Intrinsic::arm_neon_vld4: 13488 case Intrinsic::arm_neon_vld2lane: 13489 case Intrinsic::arm_neon_vld3lane: 13490 case Intrinsic::arm_neon_vld4lane: { 13491 Info.opc = ISD::INTRINSIC_W_CHAIN; 13492 // Conservatively set memVT to the entire set of vectors loaded. 13493 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13494 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 13495 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13496 Info.ptrVal = I.getArgOperand(0); 13497 Info.offset = 0; 13498 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13499 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13500 Info.vol = false; // volatile loads with NEON intrinsics not supported 13501 Info.readMem = true; 13502 Info.writeMem = false; 13503 return true; 13504 } 13505 case Intrinsic::arm_neon_vst1: 13506 case Intrinsic::arm_neon_vst2: 13507 case Intrinsic::arm_neon_vst3: 13508 case Intrinsic::arm_neon_vst4: 13509 case Intrinsic::arm_neon_vst2lane: 13510 case Intrinsic::arm_neon_vst3lane: 13511 case Intrinsic::arm_neon_vst4lane: { 13512 Info.opc = ISD::INTRINSIC_VOID; 13513 // Conservatively set memVT to the entire set of vectors stored. 13514 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13515 unsigned NumElts = 0; 13516 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 13517 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 13518 if (!ArgTy->isVectorTy()) 13519 break; 13520 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 13521 } 13522 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13523 Info.ptrVal = I.getArgOperand(0); 13524 Info.offset = 0; 13525 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13526 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13527 Info.vol = false; // volatile stores with NEON intrinsics not supported 13528 Info.readMem = false; 13529 Info.writeMem = true; 13530 return true; 13531 } 13532 case Intrinsic::arm_ldaex: 13533 case Intrinsic::arm_ldrex: { 13534 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13535 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 13536 Info.opc = ISD::INTRINSIC_W_CHAIN; 13537 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13538 Info.ptrVal = I.getArgOperand(0); 13539 Info.offset = 0; 13540 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13541 Info.vol = true; 13542 Info.readMem = true; 13543 Info.writeMem = false; 13544 return true; 13545 } 13546 case Intrinsic::arm_stlex: 13547 case Intrinsic::arm_strex: { 13548 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13549 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 13550 Info.opc = ISD::INTRINSIC_W_CHAIN; 13551 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13552 Info.ptrVal = I.getArgOperand(1); 13553 Info.offset = 0; 13554 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13555 Info.vol = true; 13556 Info.readMem = false; 13557 Info.writeMem = true; 13558 return true; 13559 } 13560 case Intrinsic::arm_stlexd: 13561 case Intrinsic::arm_strexd: 13562 Info.opc = ISD::INTRINSIC_W_CHAIN; 13563 Info.memVT = MVT::i64; 13564 Info.ptrVal = I.getArgOperand(2); 13565 Info.offset = 0; 13566 Info.align = 8; 13567 Info.vol = true; 13568 Info.readMem = false; 13569 Info.writeMem = true; 13570 return true; 13571 13572 case Intrinsic::arm_ldaexd: 13573 case Intrinsic::arm_ldrexd: 13574 Info.opc = ISD::INTRINSIC_W_CHAIN; 13575 Info.memVT = MVT::i64; 13576 Info.ptrVal = I.getArgOperand(0); 13577 Info.offset = 0; 13578 Info.align = 8; 13579 Info.vol = true; 13580 Info.readMem = true; 13581 Info.writeMem = false; 13582 return true; 13583 13584 default: 13585 break; 13586 } 13587 13588 return false; 13589 } 13590 13591 /// \brief Returns true if it is beneficial to convert a load of a constant 13592 /// to just the constant itself. 13593 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13594 Type *Ty) const { 13595 assert(Ty->isIntegerTy()); 13596 13597 unsigned Bits = Ty->getPrimitiveSizeInBits(); 13598 if (Bits == 0 || Bits > 32) 13599 return false; 13600 return true; 13601 } 13602 13603 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 13604 unsigned Index) const { 13605 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 13606 return false; 13607 13608 return (Index == 0 || Index == ResVT.getVectorNumElements()); 13609 } 13610 13611 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 13612 ARM_MB::MemBOpt Domain) const { 13613 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13614 13615 // First, if the target has no DMB, see what fallback we can use. 13616 if (!Subtarget->hasDataBarrier()) { 13617 // Some ARMv6 cpus can support data barriers with an mcr instruction. 13618 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 13619 // here. 13620 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 13621 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 13622 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 13623 Builder.getInt32(0), Builder.getInt32(7), 13624 Builder.getInt32(10), Builder.getInt32(5)}; 13625 return Builder.CreateCall(MCR, args); 13626 } else { 13627 // Instead of using barriers, atomic accesses on these subtargets use 13628 // libcalls. 13629 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 13630 } 13631 } else { 13632 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 13633 // Only a full system barrier exists in the M-class architectures. 13634 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 13635 Constant *CDomain = Builder.getInt32(Domain); 13636 return Builder.CreateCall(DMB, CDomain); 13637 } 13638 } 13639 13640 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 13641 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 13642 Instruction *Inst, 13643 AtomicOrdering Ord) const { 13644 switch (Ord) { 13645 case AtomicOrdering::NotAtomic: 13646 case AtomicOrdering::Unordered: 13647 llvm_unreachable("Invalid fence: unordered/non-atomic"); 13648 case AtomicOrdering::Monotonic: 13649 case AtomicOrdering::Acquire: 13650 return nullptr; // Nothing to do 13651 case AtomicOrdering::SequentiallyConsistent: 13652 if (!Inst->hasAtomicStore()) 13653 return nullptr; // Nothing to do 13654 /*FALLTHROUGH*/ 13655 case AtomicOrdering::Release: 13656 case AtomicOrdering::AcquireRelease: 13657 if (Subtarget->preferISHSTBarriers()) 13658 return makeDMB(Builder, ARM_MB::ISHST); 13659 // FIXME: add a comment with a link to documentation justifying this. 13660 else 13661 return makeDMB(Builder, ARM_MB::ISH); 13662 } 13663 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 13664 } 13665 13666 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 13667 Instruction *Inst, 13668 AtomicOrdering Ord) const { 13669 switch (Ord) { 13670 case AtomicOrdering::NotAtomic: 13671 case AtomicOrdering::Unordered: 13672 llvm_unreachable("Invalid fence: unordered/not-atomic"); 13673 case AtomicOrdering::Monotonic: 13674 case AtomicOrdering::Release: 13675 return nullptr; // Nothing to do 13676 case AtomicOrdering::Acquire: 13677 case AtomicOrdering::AcquireRelease: 13678 case AtomicOrdering::SequentiallyConsistent: 13679 return makeDMB(Builder, ARM_MB::ISH); 13680 } 13681 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 13682 } 13683 13684 // Loads and stores less than 64-bits are already atomic; ones above that 13685 // are doomed anyway, so defer to the default libcall and blame the OS when 13686 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13687 // anything for those. 13688 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 13689 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 13690 return (Size == 64) && !Subtarget->isMClass(); 13691 } 13692 13693 // Loads and stores less than 64-bits are already atomic; ones above that 13694 // are doomed anyway, so defer to the default libcall and blame the OS when 13695 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13696 // anything for those. 13697 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 13698 // guarantee, see DDI0406C ARM architecture reference manual, 13699 // sections A8.8.72-74 LDRD) 13700 TargetLowering::AtomicExpansionKind 13701 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 13702 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 13703 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 13704 : AtomicExpansionKind::None; 13705 } 13706 13707 // For the real atomic operations, we have ldrex/strex up to 32 bits, 13708 // and up to 64 bits on the non-M profiles 13709 TargetLowering::AtomicExpansionKind 13710 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13711 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13712 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13713 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 13714 ? AtomicExpansionKind::LLSC 13715 : AtomicExpansionKind::None; 13716 } 13717 13718 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 13719 AtomicCmpXchgInst *AI) const { 13720 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 13721 // implement cmpxchg without spilling. If the address being exchanged is also 13722 // on the stack and close enough to the spill slot, this can lead to a 13723 // situation where the monitor always gets cleared and the atomic operation 13724 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 13725 bool hasAtomicCmpXchg = 13726 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13727 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 13728 } 13729 13730 bool ARMTargetLowering::shouldInsertFencesForAtomic( 13731 const Instruction *I) const { 13732 return InsertFencesForAtomic; 13733 } 13734 13735 // This has so far only been implemented for MachO. 13736 bool ARMTargetLowering::useLoadStackGuardNode() const { 13737 return Subtarget->isTargetMachO(); 13738 } 13739 13740 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 13741 unsigned &Cost) const { 13742 // If we do not have NEON, vector types are not natively supported. 13743 if (!Subtarget->hasNEON()) 13744 return false; 13745 13746 // Floating point values and vector values map to the same register file. 13747 // Therefore, although we could do a store extract of a vector type, this is 13748 // better to leave at float as we have more freedom in the addressing mode for 13749 // those. 13750 if (VectorTy->isFPOrFPVectorTy()) 13751 return false; 13752 13753 // If the index is unknown at compile time, this is very expensive to lower 13754 // and it is not possible to combine the store with the extract. 13755 if (!isa<ConstantInt>(Idx)) 13756 return false; 13757 13758 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 13759 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 13760 // We can do a store + vector extract on any vector that fits perfectly in a D 13761 // or Q register. 13762 if (BitWidth == 64 || BitWidth == 128) { 13763 Cost = 0; 13764 return true; 13765 } 13766 return false; 13767 } 13768 13769 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 13770 return Subtarget->hasV6T2Ops(); 13771 } 13772 13773 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 13774 return Subtarget->hasV6T2Ops(); 13775 } 13776 13777 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 13778 AtomicOrdering Ord) const { 13779 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13780 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 13781 bool IsAcquire = isAcquireOrStronger(Ord); 13782 13783 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 13784 // intrinsic must return {i32, i32} and we have to recombine them into a 13785 // single i64 here. 13786 if (ValTy->getPrimitiveSizeInBits() == 64) { 13787 Intrinsic::ID Int = 13788 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 13789 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 13790 13791 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13792 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 13793 13794 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 13795 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 13796 if (!Subtarget->isLittle()) 13797 std::swap (Lo, Hi); 13798 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 13799 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 13800 return Builder.CreateOr( 13801 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 13802 } 13803 13804 Type *Tys[] = { Addr->getType() }; 13805 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 13806 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 13807 13808 return Builder.CreateTruncOrBitCast( 13809 Builder.CreateCall(Ldrex, Addr), 13810 cast<PointerType>(Addr->getType())->getElementType()); 13811 } 13812 13813 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 13814 IRBuilder<> &Builder) const { 13815 if (!Subtarget->hasV7Ops()) 13816 return; 13817 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13818 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 13819 } 13820 13821 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 13822 Value *Addr, 13823 AtomicOrdering Ord) const { 13824 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13825 bool IsRelease = isReleaseOrStronger(Ord); 13826 13827 // Since the intrinsics must have legal type, the i64 intrinsics take two 13828 // parameters: "i32, i32". We must marshal Val into the appropriate form 13829 // before the call. 13830 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 13831 Intrinsic::ID Int = 13832 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 13833 Function *Strex = Intrinsic::getDeclaration(M, Int); 13834 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 13835 13836 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 13837 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 13838 if (!Subtarget->isLittle()) 13839 std::swap(Lo, Hi); 13840 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13841 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 13842 } 13843 13844 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 13845 Type *Tys[] = { Addr->getType() }; 13846 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 13847 13848 return Builder.CreateCall( 13849 Strex, {Builder.CreateZExtOrBitCast( 13850 Val, Strex->getFunctionType()->getParamType(0)), 13851 Addr}); 13852 } 13853 13854 /// A helper function for determining the number of interleaved accesses we 13855 /// will generate when lowering accesses of the given type. 13856 unsigned 13857 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 13858 const DataLayout &DL) const { 13859 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 13860 } 13861 13862 bool ARMTargetLowering::isLegalInterleavedAccessType( 13863 VectorType *VecTy, const DataLayout &DL) const { 13864 13865 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 13866 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 13867 13868 // Ensure the vector doesn't have f16 elements. Even though we could do an 13869 // i16 vldN, we can't hold the f16 vectors and will end up converting via 13870 // f32. 13871 if (VecTy->getElementType()->isHalfTy()) 13872 return false; 13873 13874 // Ensure the number of vector elements is greater than 1. 13875 if (VecTy->getNumElements() < 2) 13876 return false; 13877 13878 // Ensure the element type is legal. 13879 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 13880 return false; 13881 13882 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 13883 // 128 will be split into multiple interleaved accesses. 13884 return VecSize == 64 || VecSize % 128 == 0; 13885 } 13886 13887 /// \brief Lower an interleaved load into a vldN intrinsic. 13888 /// 13889 /// E.g. Lower an interleaved load (Factor = 2): 13890 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 13891 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 13892 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 13893 /// 13894 /// Into: 13895 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 13896 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 13897 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 13898 bool ARMTargetLowering::lowerInterleavedLoad( 13899 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 13900 ArrayRef<unsigned> Indices, unsigned Factor) const { 13901 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13902 "Invalid interleave factor"); 13903 assert(!Shuffles.empty() && "Empty shufflevector input"); 13904 assert(Shuffles.size() == Indices.size() && 13905 "Unmatched number of shufflevectors and indices"); 13906 13907 VectorType *VecTy = Shuffles[0]->getType(); 13908 Type *EltTy = VecTy->getVectorElementType(); 13909 13910 const DataLayout &DL = LI->getModule()->getDataLayout(); 13911 13912 // Skip if we do not have NEON and skip illegal vector types. We can 13913 // "legalize" wide vector types into multiple interleaved accesses as long as 13914 // the vector types are divisible by 128. 13915 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 13916 return false; 13917 13918 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 13919 13920 // A pointer vector can not be the return type of the ldN intrinsics. Need to 13921 // load integer vectors first and then convert to pointer vectors. 13922 if (EltTy->isPointerTy()) 13923 VecTy = 13924 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 13925 13926 IRBuilder<> Builder(LI); 13927 13928 // The base address of the load. 13929 Value *BaseAddr = LI->getPointerOperand(); 13930 13931 if (NumLoads > 1) { 13932 // If we're going to generate more than one load, reset the sub-vector type 13933 // to something legal. 13934 VecTy = VectorType::get(VecTy->getVectorElementType(), 13935 VecTy->getVectorNumElements() / NumLoads); 13936 13937 // We will compute the pointer operand of each load from the original base 13938 // address using GEPs. Cast the base address to a pointer to the scalar 13939 // element type. 13940 BaseAddr = Builder.CreateBitCast( 13941 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 13942 LI->getPointerAddressSpace())); 13943 } 13944 13945 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 13946 13947 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 13948 Type *Tys[] = {VecTy, Int8Ptr}; 13949 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 13950 Intrinsic::arm_neon_vld3, 13951 Intrinsic::arm_neon_vld4}; 13952 Function *VldnFunc = 13953 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 13954 13955 // Holds sub-vectors extracted from the load intrinsic return values. The 13956 // sub-vectors are associated with the shufflevector instructions they will 13957 // replace. 13958 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 13959 13960 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 13961 // If we're generating more than one load, compute the base address of 13962 // subsequent loads as an offset from the previous. 13963 if (LoadCount > 0) 13964 BaseAddr = Builder.CreateConstGEP1_32( 13965 BaseAddr, VecTy->getVectorNumElements() * Factor); 13966 13967 SmallVector<Value *, 2> Ops; 13968 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 13969 Ops.push_back(Builder.getInt32(LI->getAlignment())); 13970 13971 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 13972 13973 // Replace uses of each shufflevector with the corresponding vector loaded 13974 // by ldN. 13975 for (unsigned i = 0; i < Shuffles.size(); i++) { 13976 ShuffleVectorInst *SV = Shuffles[i]; 13977 unsigned Index = Indices[i]; 13978 13979 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 13980 13981 // Convert the integer vector to pointer vector if the element is pointer. 13982 if (EltTy->isPointerTy()) 13983 SubVec = Builder.CreateIntToPtr( 13984 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 13985 VecTy->getVectorNumElements())); 13986 13987 SubVecs[SV].push_back(SubVec); 13988 } 13989 } 13990 13991 // Replace uses of the shufflevector instructions with the sub-vectors 13992 // returned by the load intrinsic. If a shufflevector instruction is 13993 // associated with more than one sub-vector, those sub-vectors will be 13994 // concatenated into a single wide vector. 13995 for (ShuffleVectorInst *SVI : Shuffles) { 13996 auto &SubVec = SubVecs[SVI]; 13997 auto *WideVec = 13998 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 13999 SVI->replaceAllUsesWith(WideVec); 14000 } 14001 14002 return true; 14003 } 14004 14005 /// \brief Lower an interleaved store into a vstN intrinsic. 14006 /// 14007 /// E.g. Lower an interleaved store (Factor = 3): 14008 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 14009 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 14010 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 14011 /// 14012 /// Into: 14013 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 14014 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 14015 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 14016 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14017 /// 14018 /// Note that the new shufflevectors will be removed and we'll only generate one 14019 /// vst3 instruction in CodeGen. 14020 /// 14021 /// Example for a more general valid mask (Factor 3). Lower: 14022 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 14023 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 14024 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 14025 /// 14026 /// Into: 14027 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 14028 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 14029 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 14030 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14031 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 14032 ShuffleVectorInst *SVI, 14033 unsigned Factor) const { 14034 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14035 "Invalid interleave factor"); 14036 14037 VectorType *VecTy = SVI->getType(); 14038 assert(VecTy->getVectorNumElements() % Factor == 0 && 14039 "Invalid interleaved store"); 14040 14041 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 14042 Type *EltTy = VecTy->getVectorElementType(); 14043 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 14044 14045 const DataLayout &DL = SI->getModule()->getDataLayout(); 14046 14047 // Skip if we do not have NEON and skip illegal vector types. We can 14048 // "legalize" wide vector types into multiple interleaved accesses as long as 14049 // the vector types are divisible by 128. 14050 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 14051 return false; 14052 14053 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 14054 14055 Value *Op0 = SVI->getOperand(0); 14056 Value *Op1 = SVI->getOperand(1); 14057 IRBuilder<> Builder(SI); 14058 14059 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 14060 // vectors to integer vectors. 14061 if (EltTy->isPointerTy()) { 14062 Type *IntTy = DL.getIntPtrType(EltTy); 14063 14064 // Convert to the corresponding integer vector. 14065 Type *IntVecTy = 14066 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 14067 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 14068 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 14069 14070 SubVecTy = VectorType::get(IntTy, LaneLen); 14071 } 14072 14073 // The base address of the store. 14074 Value *BaseAddr = SI->getPointerOperand(); 14075 14076 if (NumStores > 1) { 14077 // If we're going to generate more than one store, reset the lane length 14078 // and sub-vector type to something legal. 14079 LaneLen /= NumStores; 14080 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 14081 14082 // We will compute the pointer operand of each store from the original base 14083 // address using GEPs. Cast the base address to a pointer to the scalar 14084 // element type. 14085 BaseAddr = Builder.CreateBitCast( 14086 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 14087 SI->getPointerAddressSpace())); 14088 } 14089 14090 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 14091 14092 auto Mask = SVI->getShuffleMask(); 14093 14094 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 14095 Type *Tys[] = {Int8Ptr, SubVecTy}; 14096 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 14097 Intrinsic::arm_neon_vst3, 14098 Intrinsic::arm_neon_vst4}; 14099 14100 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 14101 // If we generating more than one store, we compute the base address of 14102 // subsequent stores as an offset from the previous. 14103 if (StoreCount > 0) 14104 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 14105 14106 SmallVector<Value *, 6> Ops; 14107 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14108 14109 Function *VstNFunc = 14110 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 14111 14112 // Split the shufflevector operands into sub vectors for the new vstN call. 14113 for (unsigned i = 0; i < Factor; i++) { 14114 unsigned IdxI = StoreCount * LaneLen * Factor + i; 14115 if (Mask[IdxI] >= 0) { 14116 Ops.push_back(Builder.CreateShuffleVector( 14117 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 14118 } else { 14119 unsigned StartMask = 0; 14120 for (unsigned j = 1; j < LaneLen; j++) { 14121 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 14122 if (Mask[IdxJ * Factor + IdxI] >= 0) { 14123 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 14124 break; 14125 } 14126 } 14127 // Note: If all elements in a chunk are undefs, StartMask=0! 14128 // Note: Filling undef gaps with random elements is ok, since 14129 // those elements were being written anyway (with undefs). 14130 // In the case of all undefs we're defaulting to using elems from 0 14131 // Note: StartMask cannot be negative, it's checked in 14132 // isReInterleaveMask 14133 Ops.push_back(Builder.CreateShuffleVector( 14134 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 14135 } 14136 } 14137 14138 Ops.push_back(Builder.getInt32(SI->getAlignment())); 14139 Builder.CreateCall(VstNFunc, Ops); 14140 } 14141 return true; 14142 } 14143 14144 enum HABaseType { 14145 HA_UNKNOWN = 0, 14146 HA_FLOAT, 14147 HA_DOUBLE, 14148 HA_VECT64, 14149 HA_VECT128 14150 }; 14151 14152 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 14153 uint64_t &Members) { 14154 if (auto *ST = dyn_cast<StructType>(Ty)) { 14155 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 14156 uint64_t SubMembers = 0; 14157 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 14158 return false; 14159 Members += SubMembers; 14160 } 14161 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 14162 uint64_t SubMembers = 0; 14163 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 14164 return false; 14165 Members += SubMembers * AT->getNumElements(); 14166 } else if (Ty->isFloatTy()) { 14167 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 14168 return false; 14169 Members = 1; 14170 Base = HA_FLOAT; 14171 } else if (Ty->isDoubleTy()) { 14172 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 14173 return false; 14174 Members = 1; 14175 Base = HA_DOUBLE; 14176 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 14177 Members = 1; 14178 switch (Base) { 14179 case HA_FLOAT: 14180 case HA_DOUBLE: 14181 return false; 14182 case HA_VECT64: 14183 return VT->getBitWidth() == 64; 14184 case HA_VECT128: 14185 return VT->getBitWidth() == 128; 14186 case HA_UNKNOWN: 14187 switch (VT->getBitWidth()) { 14188 case 64: 14189 Base = HA_VECT64; 14190 return true; 14191 case 128: 14192 Base = HA_VECT128; 14193 return true; 14194 default: 14195 return false; 14196 } 14197 } 14198 } 14199 14200 return (Members > 0 && Members <= 4); 14201 } 14202 14203 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 14204 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 14205 /// passing according to AAPCS rules. 14206 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 14207 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 14208 if (getEffectiveCallingConv(CallConv, isVarArg) != 14209 CallingConv::ARM_AAPCS_VFP) 14210 return false; 14211 14212 HABaseType Base = HA_UNKNOWN; 14213 uint64_t Members = 0; 14214 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 14215 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 14216 14217 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 14218 return IsHA || IsIntArray; 14219 } 14220 14221 unsigned ARMTargetLowering::getExceptionPointerRegister( 14222 const Constant *PersonalityFn) const { 14223 // Platforms which do not use SjLj EH may return values in these registers 14224 // via the personality function. 14225 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 14226 } 14227 14228 unsigned ARMTargetLowering::getExceptionSelectorRegister( 14229 const Constant *PersonalityFn) const { 14230 // Platforms which do not use SjLj EH may return values in these registers 14231 // via the personality function. 14232 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 14233 } 14234 14235 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14236 // Update IsSplitCSR in ARMFunctionInfo. 14237 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 14238 AFI->setIsSplitCSR(true); 14239 } 14240 14241 void ARMTargetLowering::insertCopiesSplitCSR( 14242 MachineBasicBlock *Entry, 14243 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14244 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 14245 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14246 if (!IStart) 14247 return; 14248 14249 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 14250 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14251 MachineBasicBlock::iterator MBBI = Entry->begin(); 14252 for (const MCPhysReg *I = IStart; *I; ++I) { 14253 const TargetRegisterClass *RC = nullptr; 14254 if (ARM::GPRRegClass.contains(*I)) 14255 RC = &ARM::GPRRegClass; 14256 else if (ARM::DPRRegClass.contains(*I)) 14257 RC = &ARM::DPRRegClass; 14258 else 14259 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14260 14261 unsigned NewVR = MRI->createVirtualRegister(RC); 14262 // Create copy from CSR to a virtual register. 14263 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14264 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14265 // nounwind. If we want to generalize this later, we may need to emit 14266 // CFI pseudo-instructions. 14267 assert(Entry->getParent()->getFunction()->hasFnAttribute( 14268 Attribute::NoUnwind) && 14269 "Function should be nounwind in insertCopiesSplitCSR!"); 14270 Entry->addLiveIn(*I); 14271 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14272 .addReg(*I); 14273 14274 // Insert the copy-back instructions right before the terminator. 14275 for (auto *Exit : Exits) 14276 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14277 TII->get(TargetOpcode::COPY), *I) 14278 .addReg(NewVR); 14279 } 14280 } 14281 14282 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 14283 MF.getFrameInfo().computeMaxCallFrameSize(MF); 14284 TargetLoweringBase::finalizeLowering(MF); 14285 } 14286