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/RuntimeLibcalls.h" 57 #include "llvm/CodeGen/SelectionDAG.h" 58 #include "llvm/CodeGen/SelectionDAGNodes.h" 59 #include "llvm/CodeGen/TargetInstrInfo.h" 60 #include "llvm/CodeGen/TargetLowering.h" 61 #include "llvm/CodeGen/TargetOpcodes.h" 62 #include "llvm/CodeGen/TargetRegisterInfo.h" 63 #include "llvm/CodeGen/TargetSubtargetInfo.h" 64 #include "llvm/CodeGen/ValueTypes.h" 65 #include "llvm/IR/Attributes.h" 66 #include "llvm/IR/CallingConv.h" 67 #include "llvm/IR/Constant.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugLoc.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GlobalAlias.h" 74 #include "llvm/IR/GlobalValue.h" 75 #include "llvm/IR/GlobalVariable.h" 76 #include "llvm/IR/IRBuilder.h" 77 #include "llvm/IR/InlineAsm.h" 78 #include "llvm/IR/Instruction.h" 79 #include "llvm/IR/Instructions.h" 80 #include "llvm/IR/IntrinsicInst.h" 81 #include "llvm/IR/Intrinsics.h" 82 #include "llvm/IR/Module.h" 83 #include "llvm/IR/Type.h" 84 #include "llvm/IR/User.h" 85 #include "llvm/IR/Value.h" 86 #include "llvm/MC/MCInstrDesc.h" 87 #include "llvm/MC/MCInstrItineraries.h" 88 #include "llvm/MC/MCRegisterInfo.h" 89 #include "llvm/MC/MCSchedule.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/BranchProbability.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CodeGen.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/ErrorHandling.h" 98 #include "llvm/Support/KnownBits.h" 99 #include "llvm/Support/MachineValueType.h" 100 #include "llvm/Support/MathExtras.h" 101 #include "llvm/Support/raw_ostream.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.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 if (Subtarget->hasFullFP16()) { 526 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 527 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 528 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 529 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 530 531 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 532 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 533 } 534 535 for (MVT VT : MVT::vector_valuetypes()) { 536 for (MVT InnerVT : MVT::vector_valuetypes()) { 537 setTruncStoreAction(VT, InnerVT, Expand); 538 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 539 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 540 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 541 } 542 543 setOperationAction(ISD::MULHS, VT, Expand); 544 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 545 setOperationAction(ISD::MULHU, VT, Expand); 546 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 547 548 setOperationAction(ISD::BSWAP, VT, Expand); 549 } 550 551 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 552 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 553 554 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 555 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 556 557 if (Subtarget->hasNEON()) { 558 addDRTypeForNEON(MVT::v2f32); 559 addDRTypeForNEON(MVT::v8i8); 560 addDRTypeForNEON(MVT::v4i16); 561 addDRTypeForNEON(MVT::v2i32); 562 addDRTypeForNEON(MVT::v1i64); 563 564 addQRTypeForNEON(MVT::v4f32); 565 addQRTypeForNEON(MVT::v2f64); 566 addQRTypeForNEON(MVT::v16i8); 567 addQRTypeForNEON(MVT::v8i16); 568 addQRTypeForNEON(MVT::v4i32); 569 addQRTypeForNEON(MVT::v2i64); 570 571 if (Subtarget->hasFullFP16()) { 572 addQRTypeForNEON(MVT::v8f16); 573 addDRTypeForNEON(MVT::v4f16); 574 } 575 576 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 577 // neither Neon nor VFP support any arithmetic operations on it. 578 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 579 // supported for v4f32. 580 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 581 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 582 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 583 // FIXME: Code duplication: FDIV and FREM are expanded always, see 584 // ARMTargetLowering::addTypeForNEON method for details. 585 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 586 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 587 // FIXME: Create unittest. 588 // In another words, find a way when "copysign" appears in DAG with vector 589 // operands. 590 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 591 // FIXME: Code duplication: SETCC has custom operation action, see 592 // ARMTargetLowering::addTypeForNEON method for details. 593 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 594 // FIXME: Create unittest for FNEG and for FABS. 595 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 596 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 597 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 598 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 599 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 600 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 601 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 602 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 603 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 604 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 605 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 606 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 607 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 608 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 609 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 610 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 611 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 612 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 613 614 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 615 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 616 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 617 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 618 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 619 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 620 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 621 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 622 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 623 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 624 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 625 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 626 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 627 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 628 629 // Mark v2f32 intrinsics. 630 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 631 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 632 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 633 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 634 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 635 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 636 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 637 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 638 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 639 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 640 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 641 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 642 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 643 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 644 645 // Neon does not support some operations on v1i64 and v2i64 types. 646 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 647 // Custom handling for some quad-vector types to detect VMULL. 648 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 649 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 650 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 651 // Custom handling for some vector types to avoid expensive expansions 652 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 653 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 654 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 655 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 656 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 657 // a destination type that is wider than the source, and nor does 658 // it have a FP_TO_[SU]INT instruction with a narrower destination than 659 // source. 660 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 661 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 662 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 663 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 664 665 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 666 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 667 668 // NEON does not have single instruction CTPOP for vectors with element 669 // types wider than 8-bits. However, custom lowering can leverage the 670 // v8i8/v16i8 vcnt instruction. 671 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 672 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 673 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 674 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 675 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 676 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 677 678 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 679 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 680 681 // NEON does not have single instruction CTTZ for vectors. 682 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 683 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 684 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 685 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 686 687 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 688 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 689 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 690 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 691 692 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 693 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 694 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 695 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 696 697 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 698 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 699 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 700 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 701 702 // NEON only has FMA instructions as of VFP4. 703 if (!Subtarget->hasVFP4()) { 704 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 705 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 706 } 707 708 setTargetDAGCombine(ISD::INTRINSIC_VOID); 709 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 710 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 711 setTargetDAGCombine(ISD::SHL); 712 setTargetDAGCombine(ISD::SRL); 713 setTargetDAGCombine(ISD::SRA); 714 setTargetDAGCombine(ISD::SIGN_EXTEND); 715 setTargetDAGCombine(ISD::ZERO_EXTEND); 716 setTargetDAGCombine(ISD::ANY_EXTEND); 717 setTargetDAGCombine(ISD::BUILD_VECTOR); 718 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 719 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 720 setTargetDAGCombine(ISD::STORE); 721 setTargetDAGCombine(ISD::FP_TO_SINT); 722 setTargetDAGCombine(ISD::FP_TO_UINT); 723 setTargetDAGCombine(ISD::FDIV); 724 setTargetDAGCombine(ISD::LOAD); 725 726 // It is legal to extload from v4i8 to v4i16 or v4i32. 727 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 728 MVT::v2i32}) { 729 for (MVT VT : MVT::integer_vector_valuetypes()) { 730 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 731 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 732 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 733 } 734 } 735 } 736 737 if (Subtarget->isFPOnlySP()) { 738 // When targeting a floating-point unit with only single-precision 739 // operations, f64 is legal for the few double-precision instructions which 740 // are present However, no double-precision operations other than moves, 741 // loads and stores are provided by the hardware. 742 setOperationAction(ISD::FADD, MVT::f64, Expand); 743 setOperationAction(ISD::FSUB, MVT::f64, Expand); 744 setOperationAction(ISD::FMUL, MVT::f64, Expand); 745 setOperationAction(ISD::FMA, MVT::f64, Expand); 746 setOperationAction(ISD::FDIV, MVT::f64, Expand); 747 setOperationAction(ISD::FREM, MVT::f64, Expand); 748 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 749 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 750 setOperationAction(ISD::FNEG, MVT::f64, Expand); 751 setOperationAction(ISD::FABS, MVT::f64, Expand); 752 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 753 setOperationAction(ISD::FSIN, MVT::f64, Expand); 754 setOperationAction(ISD::FCOS, MVT::f64, Expand); 755 setOperationAction(ISD::FPOW, MVT::f64, Expand); 756 setOperationAction(ISD::FLOG, MVT::f64, Expand); 757 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 758 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 759 setOperationAction(ISD::FEXP, MVT::f64, Expand); 760 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 761 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 762 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 763 setOperationAction(ISD::FRINT, MVT::f64, Expand); 764 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 765 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 766 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 767 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 768 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 769 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 770 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 771 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 772 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 773 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 774 } 775 776 computeRegisterProperties(Subtarget->getRegisterInfo()); 777 778 // ARM does not have floating-point extending loads. 779 for (MVT VT : MVT::fp_valuetypes()) { 780 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 781 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 782 } 783 784 // ... or truncating stores 785 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 786 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 787 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 788 789 // ARM does not have i1 sign extending load. 790 for (MVT VT : MVT::integer_valuetypes()) 791 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 792 793 // ARM supports all 4 flavors of integer indexed load / store. 794 if (!Subtarget->isThumb1Only()) { 795 for (unsigned im = (unsigned)ISD::PRE_INC; 796 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 797 setIndexedLoadAction(im, MVT::i1, Legal); 798 setIndexedLoadAction(im, MVT::i8, Legal); 799 setIndexedLoadAction(im, MVT::i16, Legal); 800 setIndexedLoadAction(im, MVT::i32, Legal); 801 setIndexedStoreAction(im, MVT::i1, Legal); 802 setIndexedStoreAction(im, MVT::i8, Legal); 803 setIndexedStoreAction(im, MVT::i16, Legal); 804 setIndexedStoreAction(im, MVT::i32, Legal); 805 } 806 } else { 807 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 808 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 809 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 810 } 811 812 setOperationAction(ISD::SADDO, MVT::i32, Custom); 813 setOperationAction(ISD::UADDO, MVT::i32, Custom); 814 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 815 setOperationAction(ISD::USUBO, MVT::i32, Custom); 816 817 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 818 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 819 820 // i64 operation support. 821 setOperationAction(ISD::MUL, MVT::i64, Expand); 822 setOperationAction(ISD::MULHU, MVT::i32, Expand); 823 if (Subtarget->isThumb1Only()) { 824 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 825 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 826 } 827 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 828 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 829 setOperationAction(ISD::MULHS, MVT::i32, Expand); 830 831 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 832 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 833 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 834 setOperationAction(ISD::SRL, MVT::i64, Custom); 835 setOperationAction(ISD::SRA, MVT::i64, Custom); 836 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 837 838 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 839 if (Subtarget->isThumb1Only()) { 840 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 841 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 842 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 843 } 844 845 setOperationAction(ISD::ADDC, MVT::i32, Custom); 846 setOperationAction(ISD::ADDE, MVT::i32, Custom); 847 setOperationAction(ISD::SUBC, MVT::i32, Custom); 848 setOperationAction(ISD::SUBE, MVT::i32, Custom); 849 850 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 851 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 852 853 // ARM does not have ROTL. 854 setOperationAction(ISD::ROTL, MVT::i32, Expand); 855 for (MVT VT : MVT::vector_valuetypes()) { 856 setOperationAction(ISD::ROTL, VT, Expand); 857 setOperationAction(ISD::ROTR, VT, Expand); 858 } 859 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 860 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 861 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 862 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 863 864 // @llvm.readcyclecounter requires the Performance Monitors extension. 865 // Default to the 0 expansion on unsupported platforms. 866 // FIXME: Technically there are older ARM CPUs that have 867 // implementation-specific ways of obtaining this information. 868 if (Subtarget->hasPerfMon()) 869 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 870 871 // Only ARMv6 has BSWAP. 872 if (!Subtarget->hasV6Ops()) 873 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 874 875 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 876 : Subtarget->hasDivideInARMMode(); 877 if (!hasDivide) { 878 // These are expanded into libcalls if the cpu doesn't have HW divider. 879 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 880 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 881 } 882 883 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 884 setOperationAction(ISD::SDIV, MVT::i32, Custom); 885 setOperationAction(ISD::UDIV, MVT::i32, Custom); 886 887 setOperationAction(ISD::SDIV, MVT::i64, Custom); 888 setOperationAction(ISD::UDIV, MVT::i64, Custom); 889 } 890 891 setOperationAction(ISD::SREM, MVT::i32, Expand); 892 setOperationAction(ISD::UREM, MVT::i32, Expand); 893 894 // Register based DivRem for AEABI (RTABI 4.2) 895 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 896 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 897 Subtarget->isTargetWindows()) { 898 setOperationAction(ISD::SREM, MVT::i64, Custom); 899 setOperationAction(ISD::UREM, MVT::i64, Custom); 900 HasStandaloneRem = false; 901 902 if (Subtarget->isTargetWindows()) { 903 const struct { 904 const RTLIB::Libcall Op; 905 const char * const Name; 906 const CallingConv::ID CC; 907 } LibraryCalls[] = { 908 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 909 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 910 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 911 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 912 913 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 914 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 915 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 916 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 917 }; 918 919 for (const auto &LC : LibraryCalls) { 920 setLibcallName(LC.Op, LC.Name); 921 setLibcallCallingConv(LC.Op, LC.CC); 922 } 923 } else { 924 const struct { 925 const RTLIB::Libcall Op; 926 const char * const Name; 927 const CallingConv::ID CC; 928 } LibraryCalls[] = { 929 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 930 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 931 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 932 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 933 934 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 935 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 936 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 937 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 938 }; 939 940 for (const auto &LC : LibraryCalls) { 941 setLibcallName(LC.Op, LC.Name); 942 setLibcallCallingConv(LC.Op, LC.CC); 943 } 944 } 945 946 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 947 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 948 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 949 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 950 } else { 951 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 952 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 953 } 954 955 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 956 for (auto &VT : {MVT::f32, MVT::f64}) 957 setOperationAction(ISD::FPOWI, VT, Custom); 958 959 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 960 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 961 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 962 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 963 964 setOperationAction(ISD::TRAP, MVT::Other, Legal); 965 966 // Use the default implementation. 967 setOperationAction(ISD::VASTART, MVT::Other, Custom); 968 setOperationAction(ISD::VAARG, MVT::Other, Expand); 969 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 970 setOperationAction(ISD::VAEND, MVT::Other, Expand); 971 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 972 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 973 974 if (Subtarget->isTargetWindows()) 975 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 976 else 977 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 978 979 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 980 // the default expansion. 981 InsertFencesForAtomic = false; 982 if (Subtarget->hasAnyDataBarrier() && 983 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 984 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 985 // to ldrex/strex loops already. 986 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 987 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 988 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 989 990 // On v8, we have particularly efficient implementations of atomic fences 991 // if they can be combined with nearby atomic loads and stores. 992 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 993 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 994 InsertFencesForAtomic = true; 995 } 996 } else { 997 // If there's anything we can use as a barrier, go through custom lowering 998 // for ATOMIC_FENCE. 999 // If target has DMB in thumb, Fences can be inserted. 1000 if (Subtarget->hasDataBarrier()) 1001 InsertFencesForAtomic = true; 1002 1003 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1004 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1005 1006 // Set them all for expansion, which will force libcalls. 1007 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1008 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1009 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1010 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1011 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1012 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1013 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1014 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1015 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1016 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1017 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1018 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1019 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1020 // Unordered/Monotonic case. 1021 if (!InsertFencesForAtomic) { 1022 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1023 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1024 } 1025 } 1026 1027 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1028 1029 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1030 if (!Subtarget->hasV6Ops()) { 1031 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1032 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1033 } 1034 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1035 1036 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1037 !Subtarget->isThumb1Only()) { 1038 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1039 // iff target supports vfp2. 1040 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1041 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1042 } 1043 1044 // We want to custom lower some of our intrinsics. 1045 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1046 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1047 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1048 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1049 if (Subtarget->useSjLjEH()) 1050 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1051 1052 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1053 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1054 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1055 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1056 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1057 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1058 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1059 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1060 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1061 if (Subtarget->hasFullFP16()) { 1062 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1063 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1064 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1065 } 1066 1067 // Thumb-1 cannot currently select ARMISD::SUBE. 1068 if (!Subtarget->isThumb1Only()) 1069 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1070 1071 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1072 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1073 if (Subtarget->hasFullFP16()) 1074 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1075 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1076 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1077 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1078 1079 // We don't support sin/cos/fmod/copysign/pow 1080 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1081 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1082 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1083 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1084 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1085 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1086 setOperationAction(ISD::FREM, MVT::f64, Expand); 1087 setOperationAction(ISD::FREM, MVT::f32, Expand); 1088 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1089 !Subtarget->isThumb1Only()) { 1090 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1091 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1092 } 1093 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1094 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1095 1096 if (!Subtarget->hasVFP4()) { 1097 setOperationAction(ISD::FMA, MVT::f64, Expand); 1098 setOperationAction(ISD::FMA, MVT::f32, Expand); 1099 } 1100 1101 // Various VFP goodness 1102 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1103 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1104 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1105 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1106 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1107 } 1108 1109 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1110 if (!Subtarget->hasFP16()) { 1111 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1112 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1113 } 1114 } 1115 1116 // Use __sincos_stret if available. 1117 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1118 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1119 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1120 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1121 } 1122 1123 // FP-ARMv8 implements a lot of rounding-like FP operations. 1124 if (Subtarget->hasFPARMv8()) { 1125 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1126 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1127 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1128 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1129 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1130 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1131 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1132 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1133 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1134 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1135 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1136 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1137 1138 if (!Subtarget->isFPOnlySP()) { 1139 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1140 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1141 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1142 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1143 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1144 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1145 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1146 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1147 } 1148 } 1149 1150 if (Subtarget->hasNEON()) { 1151 // vmin and vmax aren't available in a scalar form, so we use 1152 // a NEON instruction with an undef lane instead. 1153 setOperationAction(ISD::FMINNAN, MVT::f16, Legal); 1154 setOperationAction(ISD::FMAXNAN, MVT::f16, Legal); 1155 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1156 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1157 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1158 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1159 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1160 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1161 } 1162 1163 // We have target-specific dag combine patterns for the following nodes: 1164 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1165 setTargetDAGCombine(ISD::ADD); 1166 setTargetDAGCombine(ISD::SUB); 1167 setTargetDAGCombine(ISD::MUL); 1168 setTargetDAGCombine(ISD::AND); 1169 setTargetDAGCombine(ISD::OR); 1170 setTargetDAGCombine(ISD::XOR); 1171 1172 if (Subtarget->hasV6Ops()) 1173 setTargetDAGCombine(ISD::SRL); 1174 1175 setStackPointerRegisterToSaveRestore(ARM::SP); 1176 1177 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1178 !Subtarget->hasVFP2()) 1179 setSchedulingPreference(Sched::RegPressure); 1180 else 1181 setSchedulingPreference(Sched::Hybrid); 1182 1183 //// temporary - rewrite interface to use type 1184 MaxStoresPerMemset = 8; 1185 MaxStoresPerMemsetOptSize = 4; 1186 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1187 MaxStoresPerMemcpyOptSize = 2; 1188 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1189 MaxStoresPerMemmoveOptSize = 2; 1190 1191 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1192 // are at least 4 bytes aligned. 1193 setMinStackArgumentAlignment(4); 1194 1195 // Prefer likely predicted branches to selects on out-of-order cores. 1196 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1197 1198 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1199 } 1200 1201 bool ARMTargetLowering::useSoftFloat() const { 1202 return Subtarget->useSoftFloat(); 1203 } 1204 1205 // FIXME: It might make sense to define the representative register class as the 1206 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1207 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1208 // SPR's representative would be DPR_VFP2. This should work well if register 1209 // pressure tracking were modified such that a register use would increment the 1210 // pressure of the register class's representative and all of it's super 1211 // classes' representatives transitively. We have not implemented this because 1212 // of the difficulty prior to coalescing of modeling operand register classes 1213 // due to the common occurrence of cross class copies and subregister insertions 1214 // and extractions. 1215 std::pair<const TargetRegisterClass *, uint8_t> 1216 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1217 MVT VT) const { 1218 const TargetRegisterClass *RRC = nullptr; 1219 uint8_t Cost = 1; 1220 switch (VT.SimpleTy) { 1221 default: 1222 return TargetLowering::findRepresentativeClass(TRI, VT); 1223 // Use DPR as representative register class for all floating point 1224 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1225 // the cost is 1 for both f32 and f64. 1226 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1227 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1228 RRC = &ARM::DPRRegClass; 1229 // When NEON is used for SP, only half of the register file is available 1230 // because operations that define both SP and DP results will be constrained 1231 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1232 // coalescing by double-counting the SP regs. See the FIXME above. 1233 if (Subtarget->useNEONForSinglePrecisionFP()) 1234 Cost = 2; 1235 break; 1236 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1237 case MVT::v4f32: case MVT::v2f64: 1238 RRC = &ARM::DPRRegClass; 1239 Cost = 2; 1240 break; 1241 case MVT::v4i64: 1242 RRC = &ARM::DPRRegClass; 1243 Cost = 4; 1244 break; 1245 case MVT::v8i64: 1246 RRC = &ARM::DPRRegClass; 1247 Cost = 8; 1248 break; 1249 } 1250 return std::make_pair(RRC, Cost); 1251 } 1252 1253 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1254 switch ((ARMISD::NodeType)Opcode) { 1255 case ARMISD::FIRST_NUMBER: break; 1256 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1257 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1258 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1259 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1260 case ARMISD::CALL: return "ARMISD::CALL"; 1261 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1262 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1263 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1264 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1265 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1266 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1267 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1268 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1269 case ARMISD::CMP: return "ARMISD::CMP"; 1270 case ARMISD::CMN: return "ARMISD::CMN"; 1271 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1272 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1273 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1274 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1275 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1276 1277 case ARMISD::CMOV: return "ARMISD::CMOV"; 1278 1279 case ARMISD::SSAT: return "ARMISD::SSAT"; 1280 case ARMISD::USAT: return "ARMISD::USAT"; 1281 1282 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1283 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1284 case ARMISD::RRX: return "ARMISD::RRX"; 1285 1286 case ARMISD::ADDC: return "ARMISD::ADDC"; 1287 case ARMISD::ADDE: return "ARMISD::ADDE"; 1288 case ARMISD::SUBC: return "ARMISD::SUBC"; 1289 case ARMISD::SUBE: return "ARMISD::SUBE"; 1290 1291 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1292 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1293 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1294 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1295 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1296 1297 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1298 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1299 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1300 1301 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1302 1303 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1304 1305 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1306 1307 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1308 1309 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1310 1311 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1312 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1313 1314 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1315 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1316 case ARMISD::VCGE: return "ARMISD::VCGE"; 1317 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1318 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1319 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1320 case ARMISD::VCGT: return "ARMISD::VCGT"; 1321 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1322 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1323 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1324 case ARMISD::VTST: return "ARMISD::VTST"; 1325 1326 case ARMISD::VSHL: return "ARMISD::VSHL"; 1327 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1328 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1329 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1330 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1331 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1332 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1333 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1334 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1335 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1336 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1337 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1338 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1339 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1340 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1341 case ARMISD::VSLI: return "ARMISD::VSLI"; 1342 case ARMISD::VSRI: return "ARMISD::VSRI"; 1343 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1344 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1345 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1346 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1347 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1348 case ARMISD::VDUP: return "ARMISD::VDUP"; 1349 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1350 case ARMISD::VEXT: return "ARMISD::VEXT"; 1351 case ARMISD::VREV64: return "ARMISD::VREV64"; 1352 case ARMISD::VREV32: return "ARMISD::VREV32"; 1353 case ARMISD::VREV16: return "ARMISD::VREV16"; 1354 case ARMISD::VZIP: return "ARMISD::VZIP"; 1355 case ARMISD::VUZP: return "ARMISD::VUZP"; 1356 case ARMISD::VTRN: return "ARMISD::VTRN"; 1357 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1358 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1359 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1360 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1361 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1362 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1363 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1364 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1365 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1366 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1367 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1368 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1369 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1370 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1371 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1372 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1373 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1374 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1375 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1376 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1377 case ARMISD::BFI: return "ARMISD::BFI"; 1378 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1379 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1380 case ARMISD::VBSL: return "ARMISD::VBSL"; 1381 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1382 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1383 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1384 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1385 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1386 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1387 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1388 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1389 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1390 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1391 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1392 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1393 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1394 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1395 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1396 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1397 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1398 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1399 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1400 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1401 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1402 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1403 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1404 } 1405 return nullptr; 1406 } 1407 1408 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1409 EVT VT) const { 1410 if (!VT.isVector()) 1411 return getPointerTy(DL); 1412 return VT.changeVectorElementTypeToInteger(); 1413 } 1414 1415 /// getRegClassFor - Return the register class that should be used for the 1416 /// specified value type. 1417 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1418 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1419 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1420 // load / store 4 to 8 consecutive D registers. 1421 if (Subtarget->hasNEON()) { 1422 if (VT == MVT::v4i64) 1423 return &ARM::QQPRRegClass; 1424 if (VT == MVT::v8i64) 1425 return &ARM::QQQQPRRegClass; 1426 } 1427 return TargetLowering::getRegClassFor(VT); 1428 } 1429 1430 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1431 // source/dest is aligned and the copy size is large enough. We therefore want 1432 // to align such objects passed to memory intrinsics. 1433 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1434 unsigned &PrefAlign) const { 1435 if (!isa<MemIntrinsic>(CI)) 1436 return false; 1437 MinSize = 8; 1438 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1439 // cycle faster than 4-byte aligned LDM. 1440 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1441 return true; 1442 } 1443 1444 // Create a fast isel object. 1445 FastISel * 1446 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1447 const TargetLibraryInfo *libInfo) const { 1448 return ARM::createFastISel(funcInfo, libInfo); 1449 } 1450 1451 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1452 unsigned NumVals = N->getNumValues(); 1453 if (!NumVals) 1454 return Sched::RegPressure; 1455 1456 for (unsigned i = 0; i != NumVals; ++i) { 1457 EVT VT = N->getValueType(i); 1458 if (VT == MVT::Glue || VT == MVT::Other) 1459 continue; 1460 if (VT.isFloatingPoint() || VT.isVector()) 1461 return Sched::ILP; 1462 } 1463 1464 if (!N->isMachineOpcode()) 1465 return Sched::RegPressure; 1466 1467 // Load are scheduled for latency even if there instruction itinerary 1468 // is not available. 1469 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1470 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1471 1472 if (MCID.getNumDefs() == 0) 1473 return Sched::RegPressure; 1474 if (!Itins->isEmpty() && 1475 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1476 return Sched::ILP; 1477 1478 return Sched::RegPressure; 1479 } 1480 1481 //===----------------------------------------------------------------------===// 1482 // Lowering Code 1483 //===----------------------------------------------------------------------===// 1484 1485 static bool isSRL16(const SDValue &Op) { 1486 if (Op.getOpcode() != ISD::SRL) 1487 return false; 1488 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1489 return Const->getZExtValue() == 16; 1490 return false; 1491 } 1492 1493 static bool isSRA16(const SDValue &Op) { 1494 if (Op.getOpcode() != ISD::SRA) 1495 return false; 1496 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1497 return Const->getZExtValue() == 16; 1498 return false; 1499 } 1500 1501 static bool isSHL16(const SDValue &Op) { 1502 if (Op.getOpcode() != ISD::SHL) 1503 return false; 1504 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1505 return Const->getZExtValue() == 16; 1506 return false; 1507 } 1508 1509 // Check for a signed 16-bit value. We special case SRA because it makes it 1510 // more simple when also looking for SRAs that aren't sign extending a 1511 // smaller value. Without the check, we'd need to take extra care with 1512 // checking order for some operations. 1513 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1514 if (isSRA16(Op)) 1515 return isSHL16(Op.getOperand(0)); 1516 return DAG.ComputeNumSignBits(Op) == 17; 1517 } 1518 1519 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1520 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1521 switch (CC) { 1522 default: llvm_unreachable("Unknown condition code!"); 1523 case ISD::SETNE: return ARMCC::NE; 1524 case ISD::SETEQ: return ARMCC::EQ; 1525 case ISD::SETGT: return ARMCC::GT; 1526 case ISD::SETGE: return ARMCC::GE; 1527 case ISD::SETLT: return ARMCC::LT; 1528 case ISD::SETLE: return ARMCC::LE; 1529 case ISD::SETUGT: return ARMCC::HI; 1530 case ISD::SETUGE: return ARMCC::HS; 1531 case ISD::SETULT: return ARMCC::LO; 1532 case ISD::SETULE: return ARMCC::LS; 1533 } 1534 } 1535 1536 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1537 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1538 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1539 CondCode2 = ARMCC::AL; 1540 InvalidOnQNaN = true; 1541 switch (CC) { 1542 default: llvm_unreachable("Unknown FP condition!"); 1543 case ISD::SETEQ: 1544 case ISD::SETOEQ: 1545 CondCode = ARMCC::EQ; 1546 InvalidOnQNaN = false; 1547 break; 1548 case ISD::SETGT: 1549 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1550 case ISD::SETGE: 1551 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1552 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1553 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1554 case ISD::SETONE: 1555 CondCode = ARMCC::MI; 1556 CondCode2 = ARMCC::GT; 1557 InvalidOnQNaN = false; 1558 break; 1559 case ISD::SETO: CondCode = ARMCC::VC; break; 1560 case ISD::SETUO: CondCode = ARMCC::VS; break; 1561 case ISD::SETUEQ: 1562 CondCode = ARMCC::EQ; 1563 CondCode2 = ARMCC::VS; 1564 InvalidOnQNaN = false; 1565 break; 1566 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1567 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1568 case ISD::SETLT: 1569 case ISD::SETULT: CondCode = ARMCC::LT; break; 1570 case ISD::SETLE: 1571 case ISD::SETULE: CondCode = ARMCC::LE; break; 1572 case ISD::SETNE: 1573 case ISD::SETUNE: 1574 CondCode = ARMCC::NE; 1575 InvalidOnQNaN = false; 1576 break; 1577 } 1578 } 1579 1580 //===----------------------------------------------------------------------===// 1581 // Calling Convention Implementation 1582 //===----------------------------------------------------------------------===// 1583 1584 #include "ARMGenCallingConv.inc" 1585 1586 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1587 /// account presence of floating point hardware and calling convention 1588 /// limitations, such as support for variadic functions. 1589 CallingConv::ID 1590 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1591 bool isVarArg) const { 1592 switch (CC) { 1593 default: 1594 report_fatal_error("Unsupported calling convention"); 1595 case CallingConv::ARM_AAPCS: 1596 case CallingConv::ARM_APCS: 1597 case CallingConv::GHC: 1598 return CC; 1599 case CallingConv::PreserveMost: 1600 return CallingConv::PreserveMost; 1601 case CallingConv::ARM_AAPCS_VFP: 1602 case CallingConv::Swift: 1603 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1604 case CallingConv::C: 1605 if (!Subtarget->isAAPCS_ABI()) 1606 return CallingConv::ARM_APCS; 1607 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1608 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1609 !isVarArg) 1610 return CallingConv::ARM_AAPCS_VFP; 1611 else 1612 return CallingConv::ARM_AAPCS; 1613 case CallingConv::Fast: 1614 case CallingConv::CXX_FAST_TLS: 1615 if (!Subtarget->isAAPCS_ABI()) { 1616 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1617 return CallingConv::Fast; 1618 return CallingConv::ARM_APCS; 1619 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1620 return CallingConv::ARM_AAPCS_VFP; 1621 else 1622 return CallingConv::ARM_AAPCS; 1623 } 1624 } 1625 1626 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1627 bool isVarArg) const { 1628 return CCAssignFnForNode(CC, false, isVarArg); 1629 } 1630 1631 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1632 bool isVarArg) const { 1633 return CCAssignFnForNode(CC, true, isVarArg); 1634 } 1635 1636 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1637 /// CallingConvention. 1638 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1639 bool Return, 1640 bool isVarArg) const { 1641 switch (getEffectiveCallingConv(CC, isVarArg)) { 1642 default: 1643 report_fatal_error("Unsupported calling convention"); 1644 case CallingConv::ARM_APCS: 1645 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1646 case CallingConv::ARM_AAPCS: 1647 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1648 case CallingConv::ARM_AAPCS_VFP: 1649 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1650 case CallingConv::Fast: 1651 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1652 case CallingConv::GHC: 1653 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1654 case CallingConv::PreserveMost: 1655 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1656 } 1657 } 1658 1659 /// LowerCallResult - Lower the result values of a call into the 1660 /// appropriate copies out of appropriate physical registers. 1661 SDValue ARMTargetLowering::LowerCallResult( 1662 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1663 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1664 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1665 SDValue ThisVal) const { 1666 // Assign locations to each value returned by this call. 1667 SmallVector<CCValAssign, 16> RVLocs; 1668 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1669 *DAG.getContext()); 1670 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1671 1672 // Copy all of the result registers out of their specified physreg. 1673 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1674 CCValAssign VA = RVLocs[i]; 1675 1676 // Pass 'this' value directly from the argument to return value, to avoid 1677 // reg unit interference 1678 if (i == 0 && isThisReturn) { 1679 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1680 "unexpected return calling convention register assignment"); 1681 InVals.push_back(ThisVal); 1682 continue; 1683 } 1684 1685 SDValue Val; 1686 if (VA.needsCustom()) { 1687 // Handle f64 or half of a v2f64. 1688 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1689 InFlag); 1690 Chain = Lo.getValue(1); 1691 InFlag = Lo.getValue(2); 1692 VA = RVLocs[++i]; // skip ahead to next loc 1693 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1694 InFlag); 1695 Chain = Hi.getValue(1); 1696 InFlag = Hi.getValue(2); 1697 if (!Subtarget->isLittle()) 1698 std::swap (Lo, Hi); 1699 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1700 1701 if (VA.getLocVT() == MVT::v2f64) { 1702 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1703 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1704 DAG.getConstant(0, dl, MVT::i32)); 1705 1706 VA = RVLocs[++i]; // skip ahead to next loc 1707 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1708 Chain = Lo.getValue(1); 1709 InFlag = Lo.getValue(2); 1710 VA = RVLocs[++i]; // skip ahead to next loc 1711 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1712 Chain = Hi.getValue(1); 1713 InFlag = Hi.getValue(2); 1714 if (!Subtarget->isLittle()) 1715 std::swap (Lo, Hi); 1716 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1717 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1718 DAG.getConstant(1, dl, MVT::i32)); 1719 } 1720 } else { 1721 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1722 InFlag); 1723 Chain = Val.getValue(1); 1724 InFlag = Val.getValue(2); 1725 } 1726 1727 switch (VA.getLocInfo()) { 1728 default: llvm_unreachable("Unknown loc info!"); 1729 case CCValAssign::Full: break; 1730 case CCValAssign::BCvt: 1731 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1732 break; 1733 } 1734 1735 InVals.push_back(Val); 1736 } 1737 1738 return Chain; 1739 } 1740 1741 /// LowerMemOpCallTo - Store the argument to the stack. 1742 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1743 SDValue Arg, const SDLoc &dl, 1744 SelectionDAG &DAG, 1745 const CCValAssign &VA, 1746 ISD::ArgFlagsTy Flags) const { 1747 unsigned LocMemOffset = VA.getLocMemOffset(); 1748 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1749 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1750 StackPtr, PtrOff); 1751 return DAG.getStore( 1752 Chain, dl, Arg, PtrOff, 1753 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1754 } 1755 1756 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1757 SDValue Chain, SDValue &Arg, 1758 RegsToPassVector &RegsToPass, 1759 CCValAssign &VA, CCValAssign &NextVA, 1760 SDValue &StackPtr, 1761 SmallVectorImpl<SDValue> &MemOpChains, 1762 ISD::ArgFlagsTy Flags) const { 1763 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1764 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1765 unsigned id = Subtarget->isLittle() ? 0 : 1; 1766 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1767 1768 if (NextVA.isRegLoc()) 1769 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1770 else { 1771 assert(NextVA.isMemLoc()); 1772 if (!StackPtr.getNode()) 1773 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1774 getPointerTy(DAG.getDataLayout())); 1775 1776 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1777 dl, DAG, NextVA, 1778 Flags)); 1779 } 1780 } 1781 1782 /// LowerCall - Lowering a call into a callseq_start <- 1783 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1784 /// nodes. 1785 SDValue 1786 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1787 SmallVectorImpl<SDValue> &InVals) const { 1788 SelectionDAG &DAG = CLI.DAG; 1789 SDLoc &dl = CLI.DL; 1790 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1791 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1792 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1793 SDValue Chain = CLI.Chain; 1794 SDValue Callee = CLI.Callee; 1795 bool &isTailCall = CLI.IsTailCall; 1796 CallingConv::ID CallConv = CLI.CallConv; 1797 bool doesNotRet = CLI.DoesNotReturn; 1798 bool isVarArg = CLI.IsVarArg; 1799 1800 MachineFunction &MF = DAG.getMachineFunction(); 1801 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1802 bool isThisReturn = false; 1803 bool isSibCall = false; 1804 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1805 1806 // Disable tail calls if they're not supported. 1807 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1808 isTailCall = false; 1809 1810 if (isTailCall) { 1811 // Check if it's really possible to do a tail call. 1812 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1813 isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(), 1814 Outs, OutVals, Ins, DAG); 1815 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1816 report_fatal_error("failed to perform tail call elimination on a call " 1817 "site marked musttail"); 1818 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1819 // detected sibcalls. 1820 if (isTailCall) { 1821 ++NumTailCalls; 1822 isSibCall = true; 1823 } 1824 } 1825 1826 // Analyze operands of the call, assigning locations to each operand. 1827 SmallVector<CCValAssign, 16> ArgLocs; 1828 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1829 *DAG.getContext()); 1830 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1831 1832 // Get a count of how many bytes are to be pushed on the stack. 1833 unsigned NumBytes = CCInfo.getNextStackOffset(); 1834 1835 // For tail calls, memory operands are available in our caller's stack. 1836 if (isSibCall) 1837 NumBytes = 0; 1838 1839 // Adjust the stack pointer for the new arguments... 1840 // These operations are automatically eliminated by the prolog/epilog pass 1841 if (!isSibCall) 1842 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1843 1844 SDValue StackPtr = 1845 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1846 1847 RegsToPassVector RegsToPass; 1848 SmallVector<SDValue, 8> MemOpChains; 1849 1850 // Walk the register/memloc assignments, inserting copies/loads. In the case 1851 // of tail call optimization, arguments are handled later. 1852 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1853 i != e; 1854 ++i, ++realArgIdx) { 1855 CCValAssign &VA = ArgLocs[i]; 1856 SDValue Arg = OutVals[realArgIdx]; 1857 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1858 bool isByVal = Flags.isByVal(); 1859 1860 // Promote the value if needed. 1861 switch (VA.getLocInfo()) { 1862 default: llvm_unreachable("Unknown loc info!"); 1863 case CCValAssign::Full: break; 1864 case CCValAssign::SExt: 1865 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1866 break; 1867 case CCValAssign::ZExt: 1868 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1869 break; 1870 case CCValAssign::AExt: 1871 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1872 break; 1873 case CCValAssign::BCvt: 1874 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1875 break; 1876 } 1877 1878 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1879 if (VA.needsCustom()) { 1880 if (VA.getLocVT() == MVT::v2f64) { 1881 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1882 DAG.getConstant(0, dl, MVT::i32)); 1883 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1884 DAG.getConstant(1, dl, MVT::i32)); 1885 1886 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1887 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1888 1889 VA = ArgLocs[++i]; // skip ahead to next loc 1890 if (VA.isRegLoc()) { 1891 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1892 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1893 } else { 1894 assert(VA.isMemLoc()); 1895 1896 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1897 dl, DAG, VA, Flags)); 1898 } 1899 } else { 1900 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1901 StackPtr, MemOpChains, Flags); 1902 } 1903 } else if (VA.isRegLoc()) { 1904 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1905 Outs[0].VT == MVT::i32) { 1906 assert(VA.getLocVT() == MVT::i32 && 1907 "unexpected calling convention register assignment"); 1908 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1909 "unexpected use of 'returned'"); 1910 isThisReturn = true; 1911 } 1912 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1913 } else if (isByVal) { 1914 assert(VA.isMemLoc()); 1915 unsigned offset = 0; 1916 1917 // True if this byval aggregate will be split between registers 1918 // and memory. 1919 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1920 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1921 1922 if (CurByValIdx < ByValArgsCount) { 1923 1924 unsigned RegBegin, RegEnd; 1925 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1926 1927 EVT PtrVT = 1928 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1929 unsigned int i, j; 1930 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1931 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1932 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1933 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1934 MachinePointerInfo(), 1935 DAG.InferPtrAlignment(AddArg)); 1936 MemOpChains.push_back(Load.getValue(1)); 1937 RegsToPass.push_back(std::make_pair(j, Load)); 1938 } 1939 1940 // If parameter size outsides register area, "offset" value 1941 // helps us to calculate stack slot for remained part properly. 1942 offset = RegEnd - RegBegin; 1943 1944 CCInfo.nextInRegsParam(); 1945 } 1946 1947 if (Flags.getByValSize() > 4*offset) { 1948 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1949 unsigned LocMemOffset = VA.getLocMemOffset(); 1950 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1951 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1952 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1953 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1954 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1955 MVT::i32); 1956 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1957 MVT::i32); 1958 1959 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1960 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1961 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1962 Ops)); 1963 } 1964 } else if (!isSibCall) { 1965 assert(VA.isMemLoc()); 1966 1967 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1968 dl, DAG, VA, Flags)); 1969 } 1970 } 1971 1972 if (!MemOpChains.empty()) 1973 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1974 1975 // Build a sequence of copy-to-reg nodes chained together with token chain 1976 // and flag operands which copy the outgoing args into the appropriate regs. 1977 SDValue InFlag; 1978 // Tail call byval lowering might overwrite argument registers so in case of 1979 // tail call optimization the copies to registers are lowered later. 1980 if (!isTailCall) 1981 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1982 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1983 RegsToPass[i].second, InFlag); 1984 InFlag = Chain.getValue(1); 1985 } 1986 1987 // For tail calls lower the arguments to the 'real' stack slot. 1988 if (isTailCall) { 1989 // Force all the incoming stack arguments to be loaded from the stack 1990 // before any new outgoing arguments are stored to the stack, because the 1991 // outgoing stack slots may alias the incoming argument stack slots, and 1992 // the alias isn't otherwise explicit. This is slightly more conservative 1993 // than necessary, because it means that each store effectively depends 1994 // on every argument instead of just those arguments it would clobber. 1995 1996 // Do not flag preceding copytoreg stuff together with the following stuff. 1997 InFlag = SDValue(); 1998 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1999 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2000 RegsToPass[i].second, InFlag); 2001 InFlag = Chain.getValue(1); 2002 } 2003 InFlag = SDValue(); 2004 } 2005 2006 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2007 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2008 // node so that legalize doesn't hack it. 2009 bool isDirect = false; 2010 2011 const TargetMachine &TM = getTargetMachine(); 2012 const Module *Mod = MF.getFunction().getParent(); 2013 const GlobalValue *GV = nullptr; 2014 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2015 GV = G->getGlobal(); 2016 bool isStub = 2017 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2018 2019 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2020 bool isLocalARMFunc = false; 2021 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2022 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2023 2024 if (Subtarget->genLongCalls()) { 2025 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2026 "long-calls codegen is not position independent!"); 2027 // Handle a global address or an external symbol. If it's not one of 2028 // those, the target's already in a register, so we don't need to do 2029 // anything extra. 2030 if (isa<GlobalAddressSDNode>(Callee)) { 2031 // Create a constant pool entry for the callee address 2032 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2033 ARMConstantPoolValue *CPV = 2034 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2035 2036 // Get the address of the callee into a register 2037 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2038 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2039 Callee = DAG.getLoad( 2040 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2041 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2042 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2043 const char *Sym = S->getSymbol(); 2044 2045 // Create a constant pool entry for the callee address 2046 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2047 ARMConstantPoolValue *CPV = 2048 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2049 ARMPCLabelIndex, 0); 2050 // Get the address of the callee into a register 2051 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2052 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2053 Callee = DAG.getLoad( 2054 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2055 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2056 } 2057 } else if (isa<GlobalAddressSDNode>(Callee)) { 2058 // If we're optimizing for minimum size and the function is called three or 2059 // more times in this block, we can improve codesize by calling indirectly 2060 // as BLXr has a 16-bit encoding. 2061 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2062 auto *BB = CLI.CS.getParent(); 2063 bool PreferIndirect = 2064 Subtarget->isThumb() && MF.getFunction().optForMinSize() && 2065 count_if(GV->users(), [&BB](const User *U) { 2066 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2067 }) > 2; 2068 2069 if (!PreferIndirect) { 2070 isDirect = true; 2071 bool isDef = GV->isStrongDefinitionForLinker(); 2072 2073 // ARM call to a local ARM function is predicable. 2074 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2075 // tBX takes a register source operand. 2076 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2077 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2078 Callee = DAG.getNode( 2079 ARMISD::WrapperPIC, dl, PtrVt, 2080 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2081 Callee = DAG.getLoad( 2082 PtrVt, dl, DAG.getEntryNode(), Callee, 2083 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2084 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2085 MachineMemOperand::MOInvariant); 2086 } else if (Subtarget->isTargetCOFF()) { 2087 assert(Subtarget->isTargetWindows() && 2088 "Windows is the only supported COFF target"); 2089 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2090 ? ARMII::MO_DLLIMPORT 2091 : ARMII::MO_NO_FLAG; 2092 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2093 TargetFlags); 2094 if (GV->hasDLLImportStorageClass()) 2095 Callee = 2096 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2097 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2098 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2099 } else { 2100 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2101 } 2102 } 2103 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2104 isDirect = true; 2105 // tBX takes a register source operand. 2106 const char *Sym = S->getSymbol(); 2107 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2108 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2109 ARMConstantPoolValue *CPV = 2110 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2111 ARMPCLabelIndex, 4); 2112 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2113 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2114 Callee = DAG.getLoad( 2115 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2116 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2117 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2118 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2119 } else { 2120 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2121 } 2122 } 2123 2124 // FIXME: handle tail calls differently. 2125 unsigned CallOpc; 2126 if (Subtarget->isThumb()) { 2127 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2128 CallOpc = ARMISD::CALL_NOLINK; 2129 else 2130 CallOpc = ARMISD::CALL; 2131 } else { 2132 if (!isDirect && !Subtarget->hasV5TOps()) 2133 CallOpc = ARMISD::CALL_NOLINK; 2134 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2135 // Emit regular call when code size is the priority 2136 !MF.getFunction().optForMinSize()) 2137 // "mov lr, pc; b _foo" to avoid confusing the RSP 2138 CallOpc = ARMISD::CALL_NOLINK; 2139 else 2140 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2141 } 2142 2143 std::vector<SDValue> Ops; 2144 Ops.push_back(Chain); 2145 Ops.push_back(Callee); 2146 2147 // Add argument registers to the end of the list so that they are known live 2148 // into the call. 2149 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2150 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2151 RegsToPass[i].second.getValueType())); 2152 2153 // Add a register mask operand representing the call-preserved registers. 2154 if (!isTailCall) { 2155 const uint32_t *Mask; 2156 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2157 if (isThisReturn) { 2158 // For 'this' returns, use the R0-preserving mask if applicable 2159 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2160 if (!Mask) { 2161 // Set isThisReturn to false if the calling convention is not one that 2162 // allows 'returned' to be modeled in this way, so LowerCallResult does 2163 // not try to pass 'this' straight through 2164 isThisReturn = false; 2165 Mask = ARI->getCallPreservedMask(MF, CallConv); 2166 } 2167 } else 2168 Mask = ARI->getCallPreservedMask(MF, CallConv); 2169 2170 assert(Mask && "Missing call preserved mask for calling convention"); 2171 Ops.push_back(DAG.getRegisterMask(Mask)); 2172 } 2173 2174 if (InFlag.getNode()) 2175 Ops.push_back(InFlag); 2176 2177 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2178 if (isTailCall) { 2179 MF.getFrameInfo().setHasTailCall(); 2180 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2181 } 2182 2183 // Returns a chain and a flag for retval copy to use. 2184 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2185 InFlag = Chain.getValue(1); 2186 2187 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2188 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2189 if (!Ins.empty()) 2190 InFlag = Chain.getValue(1); 2191 2192 // Handle result values, copying them out of physregs into vregs that we 2193 // return. 2194 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2195 InVals, isThisReturn, 2196 isThisReturn ? OutVals[0] : SDValue()); 2197 } 2198 2199 /// HandleByVal - Every parameter *after* a byval parameter is passed 2200 /// on the stack. Remember the next parameter register to allocate, 2201 /// and then confiscate the rest of the parameter registers to insure 2202 /// this. 2203 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2204 unsigned Align) const { 2205 // Byval (as with any stack) slots are always at least 4 byte aligned. 2206 Align = std::max(Align, 4U); 2207 2208 unsigned Reg = State->AllocateReg(GPRArgRegs); 2209 if (!Reg) 2210 return; 2211 2212 unsigned AlignInRegs = Align / 4; 2213 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2214 for (unsigned i = 0; i < Waste; ++i) 2215 Reg = State->AllocateReg(GPRArgRegs); 2216 2217 if (!Reg) 2218 return; 2219 2220 unsigned Excess = 4 * (ARM::R4 - Reg); 2221 2222 // Special case when NSAA != SP and parameter size greater than size of 2223 // all remained GPR regs. In that case we can't split parameter, we must 2224 // send it to stack. We also must set NCRN to R4, so waste all 2225 // remained registers. 2226 const unsigned NSAAOffset = State->getNextStackOffset(); 2227 if (NSAAOffset != 0 && Size > Excess) { 2228 while (State->AllocateReg(GPRArgRegs)) 2229 ; 2230 return; 2231 } 2232 2233 // First register for byval parameter is the first register that wasn't 2234 // allocated before this method call, so it would be "reg". 2235 // If parameter is small enough to be saved in range [reg, r4), then 2236 // the end (first after last) register would be reg + param-size-in-regs, 2237 // else parameter would be splitted between registers and stack, 2238 // end register would be r4 in this case. 2239 unsigned ByValRegBegin = Reg; 2240 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2241 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2242 // Note, first register is allocated in the beginning of function already, 2243 // allocate remained amount of registers we need. 2244 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2245 State->AllocateReg(GPRArgRegs); 2246 // A byval parameter that is split between registers and memory needs its 2247 // size truncated here. 2248 // In the case where the entire structure fits in registers, we set the 2249 // size in memory to zero. 2250 Size = std::max<int>(Size - Excess, 0); 2251 } 2252 2253 /// MatchingStackOffset - Return true if the given stack call argument is 2254 /// already available in the same position (relatively) of the caller's 2255 /// incoming argument stack. 2256 static 2257 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2258 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2259 const TargetInstrInfo *TII) { 2260 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2261 int FI = std::numeric_limits<int>::max(); 2262 if (Arg.getOpcode() == ISD::CopyFromReg) { 2263 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2264 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2265 return false; 2266 MachineInstr *Def = MRI->getVRegDef(VR); 2267 if (!Def) 2268 return false; 2269 if (!Flags.isByVal()) { 2270 if (!TII->isLoadFromStackSlot(*Def, FI)) 2271 return false; 2272 } else { 2273 return false; 2274 } 2275 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2276 if (Flags.isByVal()) 2277 // ByVal argument is passed in as a pointer but it's now being 2278 // dereferenced. e.g. 2279 // define @foo(%struct.X* %A) { 2280 // tail call @bar(%struct.X* byval %A) 2281 // } 2282 return false; 2283 SDValue Ptr = Ld->getBasePtr(); 2284 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2285 if (!FINode) 2286 return false; 2287 FI = FINode->getIndex(); 2288 } else 2289 return false; 2290 2291 assert(FI != std::numeric_limits<int>::max()); 2292 if (!MFI.isFixedObjectIndex(FI)) 2293 return false; 2294 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2295 } 2296 2297 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2298 /// for tail call optimization. Targets which want to do tail call 2299 /// optimization should implement this function. 2300 bool 2301 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2302 CallingConv::ID CalleeCC, 2303 bool isVarArg, 2304 bool isCalleeStructRet, 2305 bool isCallerStructRet, 2306 const SmallVectorImpl<ISD::OutputArg> &Outs, 2307 const SmallVectorImpl<SDValue> &OutVals, 2308 const SmallVectorImpl<ISD::InputArg> &Ins, 2309 SelectionDAG& DAG) const { 2310 MachineFunction &MF = DAG.getMachineFunction(); 2311 const Function &CallerF = MF.getFunction(); 2312 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2313 2314 assert(Subtarget->supportsTailCall()); 2315 2316 // Tail calls to function pointers cannot be optimized for Thumb1 if the args 2317 // to the call take up r0-r3. The reason is that there are no legal registers 2318 // left to hold the pointer to the function to be called. 2319 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2320 !isa<GlobalAddressSDNode>(Callee.getNode())) 2321 return false; 2322 2323 // Look for obvious safe cases to perform tail call optimization that do not 2324 // require ABI changes. This is what gcc calls sibcall. 2325 2326 // Exception-handling functions need a special set of instructions to indicate 2327 // a return to the hardware. Tail-calling another function would probably 2328 // break this. 2329 if (CallerF.hasFnAttribute("interrupt")) 2330 return false; 2331 2332 // Also avoid sibcall optimization if either caller or callee uses struct 2333 // return semantics. 2334 if (isCalleeStructRet || isCallerStructRet) 2335 return false; 2336 2337 // Externally-defined functions with weak linkage should not be 2338 // tail-called on ARM when the OS does not support dynamic 2339 // pre-emption of symbols, as the AAELF spec requires normal calls 2340 // to undefined weak functions to be replaced with a NOP or jump to the 2341 // next instruction. The behaviour of branch instructions in this 2342 // situation (as used for tail calls) is implementation-defined, so we 2343 // cannot rely on the linker replacing the tail call with a return. 2344 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2345 const GlobalValue *GV = G->getGlobal(); 2346 const Triple &TT = getTargetMachine().getTargetTriple(); 2347 if (GV->hasExternalWeakLinkage() && 2348 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2349 return false; 2350 } 2351 2352 // Check that the call results are passed in the same way. 2353 LLVMContext &C = *DAG.getContext(); 2354 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2355 CCAssignFnForReturn(CalleeCC, isVarArg), 2356 CCAssignFnForReturn(CallerCC, isVarArg))) 2357 return false; 2358 // The callee has to preserve all registers the caller needs to preserve. 2359 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2360 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2361 if (CalleeCC != CallerCC) { 2362 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2363 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2364 return false; 2365 } 2366 2367 // If Caller's vararg or byval argument has been split between registers and 2368 // stack, do not perform tail call, since part of the argument is in caller's 2369 // local frame. 2370 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2371 if (AFI_Caller->getArgRegsSaveSize()) 2372 return false; 2373 2374 // If the callee takes no arguments then go on to check the results of the 2375 // call. 2376 if (!Outs.empty()) { 2377 // Check if stack adjustment is needed. For now, do not do this if any 2378 // argument is passed on the stack. 2379 SmallVector<CCValAssign, 16> ArgLocs; 2380 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2381 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2382 if (CCInfo.getNextStackOffset()) { 2383 // Check if the arguments are already laid out in the right way as 2384 // the caller's fixed stack objects. 2385 MachineFrameInfo &MFI = MF.getFrameInfo(); 2386 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2387 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2388 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2389 i != e; 2390 ++i, ++realArgIdx) { 2391 CCValAssign &VA = ArgLocs[i]; 2392 EVT RegVT = VA.getLocVT(); 2393 SDValue Arg = OutVals[realArgIdx]; 2394 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2395 if (VA.getLocInfo() == CCValAssign::Indirect) 2396 return false; 2397 if (VA.needsCustom()) { 2398 // f64 and vector types are split into multiple registers or 2399 // register/stack-slot combinations. The types will not match 2400 // the registers; give up on memory f64 refs until we figure 2401 // out what to do about this. 2402 if (!VA.isRegLoc()) 2403 return false; 2404 if (!ArgLocs[++i].isRegLoc()) 2405 return false; 2406 if (RegVT == MVT::v2f64) { 2407 if (!ArgLocs[++i].isRegLoc()) 2408 return false; 2409 if (!ArgLocs[++i].isRegLoc()) 2410 return false; 2411 } 2412 } else if (!VA.isRegLoc()) { 2413 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2414 MFI, MRI, TII)) 2415 return false; 2416 } 2417 } 2418 } 2419 2420 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2421 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2422 return false; 2423 } 2424 2425 return true; 2426 } 2427 2428 bool 2429 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2430 MachineFunction &MF, bool isVarArg, 2431 const SmallVectorImpl<ISD::OutputArg> &Outs, 2432 LLVMContext &Context) const { 2433 SmallVector<CCValAssign, 16> RVLocs; 2434 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2435 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2436 } 2437 2438 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2439 const SDLoc &DL, SelectionDAG &DAG) { 2440 const MachineFunction &MF = DAG.getMachineFunction(); 2441 const Function &F = MF.getFunction(); 2442 2443 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2444 2445 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2446 // version of the "preferred return address". These offsets affect the return 2447 // instruction if this is a return from PL1 without hypervisor extensions. 2448 // IRQ/FIQ: +4 "subs pc, lr, #4" 2449 // SWI: 0 "subs pc, lr, #0" 2450 // ABORT: +4 "subs pc, lr, #4" 2451 // UNDEF: +4/+2 "subs pc, lr, #0" 2452 // UNDEF varies depending on where the exception came from ARM or Thumb 2453 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2454 2455 int64_t LROffset; 2456 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2457 IntKind == "ABORT") 2458 LROffset = 4; 2459 else if (IntKind == "SWI" || IntKind == "UNDEF") 2460 LROffset = 0; 2461 else 2462 report_fatal_error("Unsupported interrupt attribute. If present, value " 2463 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2464 2465 RetOps.insert(RetOps.begin() + 1, 2466 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2467 2468 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2469 } 2470 2471 SDValue 2472 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2473 bool isVarArg, 2474 const SmallVectorImpl<ISD::OutputArg> &Outs, 2475 const SmallVectorImpl<SDValue> &OutVals, 2476 const SDLoc &dl, SelectionDAG &DAG) const { 2477 // CCValAssign - represent the assignment of the return value to a location. 2478 SmallVector<CCValAssign, 16> RVLocs; 2479 2480 // CCState - Info about the registers and stack slots. 2481 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2482 *DAG.getContext()); 2483 2484 // Analyze outgoing return values. 2485 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2486 2487 SDValue Flag; 2488 SmallVector<SDValue, 4> RetOps; 2489 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2490 bool isLittleEndian = Subtarget->isLittle(); 2491 2492 MachineFunction &MF = DAG.getMachineFunction(); 2493 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2494 AFI->setReturnRegsCount(RVLocs.size()); 2495 2496 // Copy the result values into the output registers. 2497 for (unsigned i = 0, realRVLocIdx = 0; 2498 i != RVLocs.size(); 2499 ++i, ++realRVLocIdx) { 2500 CCValAssign &VA = RVLocs[i]; 2501 assert(VA.isRegLoc() && "Can only return in registers!"); 2502 2503 SDValue Arg = OutVals[realRVLocIdx]; 2504 bool ReturnF16 = false; 2505 2506 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2507 // Half-precision return values can be returned like this: 2508 // 2509 // t11 f16 = fadd ... 2510 // t12: i16 = bitcast t11 2511 // t13: i32 = zero_extend t12 2512 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2513 // 2514 // to avoid code generation for bitcasts, we simply set Arg to the node 2515 // that produces the f16 value, t11 in this case. 2516 // 2517 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2518 SDValue ZE = Arg.getOperand(0); 2519 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2520 SDValue BC = ZE.getOperand(0); 2521 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2522 Arg = BC.getOperand(0); 2523 ReturnF16 = true; 2524 } 2525 } 2526 } 2527 } 2528 2529 switch (VA.getLocInfo()) { 2530 default: llvm_unreachable("Unknown loc info!"); 2531 case CCValAssign::Full: break; 2532 case CCValAssign::BCvt: 2533 if (!ReturnF16) 2534 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2535 break; 2536 } 2537 2538 if (VA.needsCustom()) { 2539 if (VA.getLocVT() == MVT::v2f64) { 2540 // Extract the first half and return it in two registers. 2541 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2542 DAG.getConstant(0, dl, MVT::i32)); 2543 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2544 DAG.getVTList(MVT::i32, MVT::i32), Half); 2545 2546 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2547 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2548 Flag); 2549 Flag = Chain.getValue(1); 2550 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2551 VA = RVLocs[++i]; // skip ahead to next loc 2552 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2553 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2554 Flag); 2555 Flag = Chain.getValue(1); 2556 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2557 VA = RVLocs[++i]; // skip ahead to next loc 2558 2559 // Extract the 2nd half and fall through to handle it as an f64 value. 2560 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2561 DAG.getConstant(1, dl, MVT::i32)); 2562 } 2563 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2564 // available. 2565 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2566 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2567 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2568 fmrrd.getValue(isLittleEndian ? 0 : 1), 2569 Flag); 2570 Flag = Chain.getValue(1); 2571 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2572 VA = RVLocs[++i]; // skip ahead to next loc 2573 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2574 fmrrd.getValue(isLittleEndian ? 1 : 0), 2575 Flag); 2576 } else 2577 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2578 2579 // Guarantee that all emitted copies are 2580 // stuck together, avoiding something bad. 2581 Flag = Chain.getValue(1); 2582 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2583 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2584 } 2585 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2586 const MCPhysReg *I = 2587 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2588 if (I) { 2589 for (; *I; ++I) { 2590 if (ARM::GPRRegClass.contains(*I)) 2591 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2592 else if (ARM::DPRRegClass.contains(*I)) 2593 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2594 else 2595 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2596 } 2597 } 2598 2599 // Update chain and glue. 2600 RetOps[0] = Chain; 2601 if (Flag.getNode()) 2602 RetOps.push_back(Flag); 2603 2604 // CPUs which aren't M-class use a special sequence to return from 2605 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2606 // though we use "subs pc, lr, #N"). 2607 // 2608 // M-class CPUs actually use a normal return sequence with a special 2609 // (hardware-provided) value in LR, so the normal code path works. 2610 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2611 !Subtarget->isMClass()) { 2612 if (Subtarget->isThumb1Only()) 2613 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2614 return LowerInterruptReturn(RetOps, dl, DAG); 2615 } 2616 2617 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2618 } 2619 2620 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2621 if (N->getNumValues() != 1) 2622 return false; 2623 if (!N->hasNUsesOfValue(1, 0)) 2624 return false; 2625 2626 SDValue TCChain = Chain; 2627 SDNode *Copy = *N->use_begin(); 2628 if (Copy->getOpcode() == ISD::CopyToReg) { 2629 // If the copy has a glue operand, we conservatively assume it isn't safe to 2630 // perform a tail call. 2631 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2632 return false; 2633 TCChain = Copy->getOperand(0); 2634 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2635 SDNode *VMov = Copy; 2636 // f64 returned in a pair of GPRs. 2637 SmallPtrSet<SDNode*, 2> Copies; 2638 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2639 UI != UE; ++UI) { 2640 if (UI->getOpcode() != ISD::CopyToReg) 2641 return false; 2642 Copies.insert(*UI); 2643 } 2644 if (Copies.size() > 2) 2645 return false; 2646 2647 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2648 UI != UE; ++UI) { 2649 SDValue UseChain = UI->getOperand(0); 2650 if (Copies.count(UseChain.getNode())) 2651 // Second CopyToReg 2652 Copy = *UI; 2653 else { 2654 // We are at the top of this chain. 2655 // If the copy has a glue operand, we conservatively assume it 2656 // isn't safe to perform a tail call. 2657 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2658 return false; 2659 // First CopyToReg 2660 TCChain = UseChain; 2661 } 2662 } 2663 } else if (Copy->getOpcode() == ISD::BITCAST) { 2664 // f32 returned in a single GPR. 2665 if (!Copy->hasOneUse()) 2666 return false; 2667 Copy = *Copy->use_begin(); 2668 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2669 return false; 2670 // If the copy has a glue operand, we conservatively assume it isn't safe to 2671 // perform a tail call. 2672 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2673 return false; 2674 TCChain = Copy->getOperand(0); 2675 } else { 2676 return false; 2677 } 2678 2679 bool HasRet = false; 2680 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2681 UI != UE; ++UI) { 2682 if (UI->getOpcode() != ARMISD::RET_FLAG && 2683 UI->getOpcode() != ARMISD::INTRET_FLAG) 2684 return false; 2685 HasRet = true; 2686 } 2687 2688 if (!HasRet) 2689 return false; 2690 2691 Chain = TCChain; 2692 return true; 2693 } 2694 2695 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2696 if (!Subtarget->supportsTailCall()) 2697 return false; 2698 2699 auto Attr = 2700 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2701 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2702 return false; 2703 2704 return true; 2705 } 2706 2707 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2708 // and pass the lower and high parts through. 2709 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2710 SDLoc DL(Op); 2711 SDValue WriteValue = Op->getOperand(2); 2712 2713 // This function is only supposed to be called for i64 type argument. 2714 assert(WriteValue.getValueType() == MVT::i64 2715 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2716 2717 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2718 DAG.getConstant(0, DL, MVT::i32)); 2719 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2720 DAG.getConstant(1, DL, MVT::i32)); 2721 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2722 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2723 } 2724 2725 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2726 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2727 // one of the above mentioned nodes. It has to be wrapped because otherwise 2728 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2729 // be used to form addressing mode. These wrapped nodes will be selected 2730 // into MOVi. 2731 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2732 SelectionDAG &DAG) const { 2733 EVT PtrVT = Op.getValueType(); 2734 // FIXME there is no actual debug info here 2735 SDLoc dl(Op); 2736 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2737 SDValue Res; 2738 2739 // When generating execute-only code Constant Pools must be promoted to the 2740 // global data section. It's a bit ugly that we can't share them across basic 2741 // blocks, but this way we guarantee that execute-only behaves correct with 2742 // position-independent addressing modes. 2743 if (Subtarget->genExecuteOnly()) { 2744 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2745 auto T = const_cast<Type*>(CP->getType()); 2746 auto C = const_cast<Constant*>(CP->getConstVal()); 2747 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2748 getFunction().getParent()); 2749 auto GV = new GlobalVariable( 2750 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2751 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2752 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2753 Twine(AFI->createPICLabelUId()) 2754 ); 2755 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2756 dl, PtrVT); 2757 return LowerGlobalAddress(GA, DAG); 2758 } 2759 2760 if (CP->isMachineConstantPoolEntry()) 2761 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2762 CP->getAlignment()); 2763 else 2764 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2765 CP->getAlignment()); 2766 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2767 } 2768 2769 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2770 return MachineJumpTableInfo::EK_Inline; 2771 } 2772 2773 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2774 SelectionDAG &DAG) const { 2775 MachineFunction &MF = DAG.getMachineFunction(); 2776 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2777 unsigned ARMPCLabelIndex = 0; 2778 SDLoc DL(Op); 2779 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2780 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2781 SDValue CPAddr; 2782 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2783 if (!IsPositionIndependent) { 2784 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2785 } else { 2786 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2787 ARMPCLabelIndex = AFI->createPICLabelUId(); 2788 ARMConstantPoolValue *CPV = 2789 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2790 ARMCP::CPBlockAddress, PCAdj); 2791 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2792 } 2793 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2794 SDValue Result = DAG.getLoad( 2795 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2796 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2797 if (!IsPositionIndependent) 2798 return Result; 2799 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2800 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2801 } 2802 2803 /// Convert a TLS address reference into the correct sequence of loads 2804 /// and calls to compute the variable's address for Darwin, and return an 2805 /// SDValue containing the final node. 2806 2807 /// Darwin only has one TLS scheme which must be capable of dealing with the 2808 /// fully general situation, in the worst case. This means: 2809 /// + "extern __thread" declaration. 2810 /// + Defined in a possibly unknown dynamic library. 2811 /// 2812 /// The general system is that each __thread variable has a [3 x i32] descriptor 2813 /// which contains information used by the runtime to calculate the address. The 2814 /// only part of this the compiler needs to know about is the first word, which 2815 /// contains a function pointer that must be called with the address of the 2816 /// entire descriptor in "r0". 2817 /// 2818 /// Since this descriptor may be in a different unit, in general access must 2819 /// proceed along the usual ARM rules. A common sequence to produce is: 2820 /// 2821 /// movw rT1, :lower16:_var$non_lazy_ptr 2822 /// movt rT1, :upper16:_var$non_lazy_ptr 2823 /// ldr r0, [rT1] 2824 /// ldr rT2, [r0] 2825 /// blx rT2 2826 /// [...address now in r0...] 2827 SDValue 2828 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2829 SelectionDAG &DAG) const { 2830 assert(Subtarget->isTargetDarwin() && 2831 "This function expects a Darwin target"); 2832 SDLoc DL(Op); 2833 2834 // First step is to get the address of the actua global symbol. This is where 2835 // the TLS descriptor lives. 2836 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2837 2838 // The first entry in the descriptor is a function pointer that we must call 2839 // to obtain the address of the variable. 2840 SDValue Chain = DAG.getEntryNode(); 2841 SDValue FuncTLVGet = DAG.getLoad( 2842 MVT::i32, DL, Chain, DescAddr, 2843 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2844 /* Alignment = */ 4, 2845 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2846 MachineMemOperand::MOInvariant); 2847 Chain = FuncTLVGet.getValue(1); 2848 2849 MachineFunction &F = DAG.getMachineFunction(); 2850 MachineFrameInfo &MFI = F.getFrameInfo(); 2851 MFI.setAdjustsStack(true); 2852 2853 // TLS calls preserve all registers except those that absolutely must be 2854 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2855 // silly). 2856 auto TRI = 2857 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2858 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2859 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2860 2861 // Finally, we can make the call. This is just a degenerate version of a 2862 // normal AArch64 call node: r0 takes the address of the descriptor, and 2863 // returns the address of the variable in this thread. 2864 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2865 Chain = 2866 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2867 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2868 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2869 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2870 } 2871 2872 SDValue 2873 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2874 SelectionDAG &DAG) const { 2875 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2876 2877 SDValue Chain = DAG.getEntryNode(); 2878 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2879 SDLoc DL(Op); 2880 2881 // Load the current TEB (thread environment block) 2882 SDValue Ops[] = {Chain, 2883 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2884 DAG.getConstant(15, DL, MVT::i32), 2885 DAG.getConstant(0, DL, MVT::i32), 2886 DAG.getConstant(13, DL, MVT::i32), 2887 DAG.getConstant(0, DL, MVT::i32), 2888 DAG.getConstant(2, DL, MVT::i32)}; 2889 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2890 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2891 2892 SDValue TEB = CurrentTEB.getValue(0); 2893 Chain = CurrentTEB.getValue(1); 2894 2895 // Load the ThreadLocalStoragePointer from the TEB 2896 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2897 SDValue TLSArray = 2898 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2899 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2900 2901 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2902 // offset into the TLSArray. 2903 2904 // Load the TLS index from the C runtime 2905 SDValue TLSIndex = 2906 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2907 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2908 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2909 2910 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2911 DAG.getConstant(2, DL, MVT::i32)); 2912 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2913 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2914 MachinePointerInfo()); 2915 2916 // Get the offset of the start of the .tls section (section base) 2917 const auto *GA = cast<GlobalAddressSDNode>(Op); 2918 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2919 SDValue Offset = DAG.getLoad( 2920 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2921 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2922 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2923 2924 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2925 } 2926 2927 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2928 SDValue 2929 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2930 SelectionDAG &DAG) const { 2931 SDLoc dl(GA); 2932 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2933 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2934 MachineFunction &MF = DAG.getMachineFunction(); 2935 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2936 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2937 ARMConstantPoolValue *CPV = 2938 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2939 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2940 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2941 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2942 Argument = DAG.getLoad( 2943 PtrVT, dl, DAG.getEntryNode(), Argument, 2944 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2945 SDValue Chain = Argument.getValue(1); 2946 2947 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2948 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2949 2950 // call __tls_get_addr. 2951 ArgListTy Args; 2952 ArgListEntry Entry; 2953 Entry.Node = Argument; 2954 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2955 Args.push_back(Entry); 2956 2957 // FIXME: is there useful debug info available here? 2958 TargetLowering::CallLoweringInfo CLI(DAG); 2959 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2960 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2961 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2962 2963 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2964 return CallResult.first; 2965 } 2966 2967 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2968 // "local exec" model. 2969 SDValue 2970 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2971 SelectionDAG &DAG, 2972 TLSModel::Model model) const { 2973 const GlobalValue *GV = GA->getGlobal(); 2974 SDLoc dl(GA); 2975 SDValue Offset; 2976 SDValue Chain = DAG.getEntryNode(); 2977 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2978 // Get the Thread Pointer 2979 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2980 2981 if (model == TLSModel::InitialExec) { 2982 MachineFunction &MF = DAG.getMachineFunction(); 2983 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2984 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2985 // Initial exec model. 2986 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2987 ARMConstantPoolValue *CPV = 2988 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2989 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2990 true); 2991 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2992 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2993 Offset = DAG.getLoad( 2994 PtrVT, dl, Chain, Offset, 2995 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2996 Chain = Offset.getValue(1); 2997 2998 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2999 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3000 3001 Offset = DAG.getLoad( 3002 PtrVT, dl, Chain, Offset, 3003 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3004 } else { 3005 // local exec model 3006 assert(model == TLSModel::LocalExec); 3007 ARMConstantPoolValue *CPV = 3008 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3009 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3010 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3011 Offset = DAG.getLoad( 3012 PtrVT, dl, Chain, Offset, 3013 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3014 } 3015 3016 // The address of the thread local variable is the add of the thread 3017 // pointer with the offset of the variable. 3018 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3019 } 3020 3021 SDValue 3022 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3023 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3024 if (DAG.getTarget().useEmulatedTLS()) 3025 return LowerToTLSEmulatedModel(GA, DAG); 3026 3027 if (Subtarget->isTargetDarwin()) 3028 return LowerGlobalTLSAddressDarwin(Op, DAG); 3029 3030 if (Subtarget->isTargetWindows()) 3031 return LowerGlobalTLSAddressWindows(Op, DAG); 3032 3033 // TODO: implement the "local dynamic" model 3034 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3035 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3036 3037 switch (model) { 3038 case TLSModel::GeneralDynamic: 3039 case TLSModel::LocalDynamic: 3040 return LowerToTLSGeneralDynamicModel(GA, DAG); 3041 case TLSModel::InitialExec: 3042 case TLSModel::LocalExec: 3043 return LowerToTLSExecModels(GA, DAG, model); 3044 } 3045 llvm_unreachable("bogus TLS model"); 3046 } 3047 3048 /// Return true if all users of V are within function F, looking through 3049 /// ConstantExprs. 3050 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3051 SmallVector<const User*,4> Worklist; 3052 for (auto *U : V->users()) 3053 Worklist.push_back(U); 3054 while (!Worklist.empty()) { 3055 auto *U = Worklist.pop_back_val(); 3056 if (isa<ConstantExpr>(U)) { 3057 for (auto *UU : U->users()) 3058 Worklist.push_back(UU); 3059 continue; 3060 } 3061 3062 auto *I = dyn_cast<Instruction>(U); 3063 if (!I || I->getParent()->getParent() != F) 3064 return false; 3065 } 3066 return true; 3067 } 3068 3069 /// Return true if all users of V are within some (any) function, looking through 3070 /// ConstantExprs. In other words, are there any global constant users? 3071 static bool allUsersAreInFunctions(const Value *V) { 3072 SmallVector<const User*,4> Worklist; 3073 for (auto *U : V->users()) 3074 Worklist.push_back(U); 3075 while (!Worklist.empty()) { 3076 auto *U = Worklist.pop_back_val(); 3077 if (isa<ConstantExpr>(U)) { 3078 for (auto *UU : U->users()) 3079 Worklist.push_back(UU); 3080 continue; 3081 } 3082 3083 if (!isa<Instruction>(U)) 3084 return false; 3085 } 3086 return true; 3087 } 3088 3089 // Return true if T is an integer, float or an array/vector of either. 3090 static bool isSimpleType(Type *T) { 3091 if (T->isIntegerTy() || T->isFloatingPointTy()) 3092 return true; 3093 Type *SubT = nullptr; 3094 if (T->isArrayTy()) 3095 SubT = T->getArrayElementType(); 3096 else if (T->isVectorTy()) 3097 SubT = T->getVectorElementType(); 3098 else 3099 return false; 3100 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3101 } 3102 3103 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3104 EVT PtrVT, const SDLoc &dl) { 3105 // If we're creating a pool entry for a constant global with unnamed address, 3106 // and the global is small enough, we can emit it inline into the constant pool 3107 // to save ourselves an indirection. 3108 // 3109 // This is a win if the constant is only used in one function (so it doesn't 3110 // need to be duplicated) or duplicating the constant wouldn't increase code 3111 // size (implying the constant is no larger than 4 bytes). 3112 const Function &F = DAG.getMachineFunction().getFunction(); 3113 3114 // We rely on this decision to inline being idemopotent and unrelated to the 3115 // use-site. We know that if we inline a variable at one use site, we'll 3116 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3117 // doesn't know about this optimization, so bail out if it's enabled else 3118 // we could decide to inline here (and thus never emit the GV) but require 3119 // the GV from fast-isel generated code. 3120 if (!EnableConstpoolPromotion || 3121 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3122 return SDValue(); 3123 3124 auto *GVar = dyn_cast<GlobalVariable>(GV); 3125 if (!GVar || !GVar->hasInitializer() || 3126 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3127 !GVar->hasLocalLinkage()) 3128 return SDValue(); 3129 3130 // Ensure that we don't try and inline any type that contains pointers. If 3131 // we inline a value that contains relocations, we move the relocations from 3132 // .data to .text which is not ideal. 3133 auto *Init = GVar->getInitializer(); 3134 if (!isSimpleType(Init->getType())) 3135 return SDValue(); 3136 3137 // The constant islands pass can only really deal with alignment requests 3138 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3139 // any type wanting greater alignment requirements than 4 bytes. We also 3140 // can only promote constants that are multiples of 4 bytes in size or 3141 // are paddable to a multiple of 4. Currently we only try and pad constants 3142 // that are strings for simplicity. 3143 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3144 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3145 unsigned Align = GVar->getAlignment(); 3146 unsigned RequiredPadding = 4 - (Size % 4); 3147 bool PaddingPossible = 3148 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3149 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3150 Size == 0) 3151 return SDValue(); 3152 3153 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3154 MachineFunction &MF = DAG.getMachineFunction(); 3155 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3156 3157 // We can't bloat the constant pool too much, else the ConstantIslands pass 3158 // may fail to converge. If we haven't promoted this global yet (it may have 3159 // multiple uses), and promoting it would increase the constant pool size (Sz 3160 // > 4), ensure we have space to do so up to MaxTotal. 3161 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3162 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3163 ConstpoolPromotionMaxTotal) 3164 return SDValue(); 3165 3166 // This is only valid if all users are in a single function OR it has users 3167 // in multiple functions but it no larger than a pointer. We also check if 3168 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3169 // address taken. 3170 if (!allUsersAreInFunction(GVar, &F) && 3171 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3172 return SDValue(); 3173 3174 // We're going to inline this global. Pad it out if needed. 3175 if (RequiredPadding != 4) { 3176 StringRef S = CDAInit->getAsString(); 3177 3178 SmallVector<uint8_t,16> V(S.size()); 3179 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3180 while (RequiredPadding--) 3181 V.push_back(0); 3182 Init = ConstantDataArray::get(*DAG.getContext(), V); 3183 } 3184 3185 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3186 SDValue CPAddr = 3187 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3188 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3189 AFI->markGlobalAsPromotedToConstantPool(GVar); 3190 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3191 PaddedSize - 4); 3192 } 3193 ++NumConstpoolPromoted; 3194 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3195 } 3196 3197 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3198 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3199 GV = GA->getBaseObject(); 3200 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3201 isa<Function>(GV); 3202 } 3203 3204 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3205 SelectionDAG &DAG) const { 3206 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3207 default: llvm_unreachable("unknown object format"); 3208 case Triple::COFF: 3209 return LowerGlobalAddressWindows(Op, DAG); 3210 case Triple::ELF: 3211 return LowerGlobalAddressELF(Op, DAG); 3212 case Triple::MachO: 3213 return LowerGlobalAddressDarwin(Op, DAG); 3214 } 3215 } 3216 3217 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3218 SelectionDAG &DAG) const { 3219 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3220 SDLoc dl(Op); 3221 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3222 const TargetMachine &TM = getTargetMachine(); 3223 bool IsRO = isReadOnly(GV); 3224 3225 // promoteToConstantPool only if not generating XO text section 3226 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3227 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3228 return V; 3229 3230 if (isPositionIndependent()) { 3231 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3232 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3233 UseGOT_PREL ? ARMII::MO_GOT : 0); 3234 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3235 if (UseGOT_PREL) 3236 Result = 3237 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3238 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3239 return Result; 3240 } else if (Subtarget->isROPI() && IsRO) { 3241 // PC-relative. 3242 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3243 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3244 return Result; 3245 } else if (Subtarget->isRWPI() && !IsRO) { 3246 // SB-relative. 3247 SDValue RelAddr; 3248 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3249 ++NumMovwMovt; 3250 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3251 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3252 } else { // use literal pool for address constant 3253 ARMConstantPoolValue *CPV = 3254 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3255 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3256 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3257 RelAddr = DAG.getLoad( 3258 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3259 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3260 } 3261 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3262 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3263 return Result; 3264 } 3265 3266 // If we have T2 ops, we can materialize the address directly via movt/movw 3267 // pair. This is always cheaper. 3268 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3269 ++NumMovwMovt; 3270 // FIXME: Once remat is capable of dealing with instructions with register 3271 // operands, expand this into two nodes. 3272 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3273 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3274 } else { 3275 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3276 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3277 return DAG.getLoad( 3278 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3279 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3280 } 3281 } 3282 3283 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3284 SelectionDAG &DAG) const { 3285 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3286 "ROPI/RWPI not currently supported for Darwin"); 3287 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3288 SDLoc dl(Op); 3289 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3290 3291 if (Subtarget->useMovt(DAG.getMachineFunction())) 3292 ++NumMovwMovt; 3293 3294 // FIXME: Once remat is capable of dealing with instructions with register 3295 // operands, expand this into multiple nodes 3296 unsigned Wrapper = 3297 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3298 3299 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3300 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3301 3302 if (Subtarget->isGVIndirectSymbol(GV)) 3303 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3304 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3305 return Result; 3306 } 3307 3308 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3309 SelectionDAG &DAG) const { 3310 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3311 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3312 "Windows on ARM expects to use movw/movt"); 3313 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3314 "ROPI/RWPI not currently supported for Windows"); 3315 3316 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3317 const ARMII::TOF TargetFlags = 3318 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3319 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3320 SDValue Result; 3321 SDLoc DL(Op); 3322 3323 ++NumMovwMovt; 3324 3325 // FIXME: Once remat is capable of dealing with instructions with register 3326 // operands, expand this into two nodes. 3327 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3328 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3329 TargetFlags)); 3330 if (GV->hasDLLImportStorageClass()) 3331 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3332 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3333 return Result; 3334 } 3335 3336 SDValue 3337 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3338 SDLoc dl(Op); 3339 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3340 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3341 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3342 Op.getOperand(1), Val); 3343 } 3344 3345 SDValue 3346 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3347 SDLoc dl(Op); 3348 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3349 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3350 } 3351 3352 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3353 SelectionDAG &DAG) const { 3354 SDLoc dl(Op); 3355 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3356 Op.getOperand(0)); 3357 } 3358 3359 SDValue 3360 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3361 const ARMSubtarget *Subtarget) const { 3362 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3363 SDLoc dl(Op); 3364 switch (IntNo) { 3365 default: return SDValue(); // Don't custom lower most intrinsics. 3366 case Intrinsic::thread_pointer: { 3367 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3368 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3369 } 3370 case Intrinsic::eh_sjlj_lsda: { 3371 MachineFunction &MF = DAG.getMachineFunction(); 3372 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3373 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3374 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3375 SDValue CPAddr; 3376 bool IsPositionIndependent = isPositionIndependent(); 3377 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3378 ARMConstantPoolValue *CPV = 3379 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3380 ARMCP::CPLSDA, PCAdj); 3381 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3382 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3383 SDValue Result = DAG.getLoad( 3384 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3385 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3386 3387 if (IsPositionIndependent) { 3388 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3389 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3390 } 3391 return Result; 3392 } 3393 case Intrinsic::arm_neon_vabs: 3394 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3395 Op.getOperand(1)); 3396 case Intrinsic::arm_neon_vmulls: 3397 case Intrinsic::arm_neon_vmullu: { 3398 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3399 ? ARMISD::VMULLs : ARMISD::VMULLu; 3400 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3401 Op.getOperand(1), Op.getOperand(2)); 3402 } 3403 case Intrinsic::arm_neon_vminnm: 3404 case Intrinsic::arm_neon_vmaxnm: { 3405 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3406 ? ISD::FMINNUM : ISD::FMAXNUM; 3407 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3408 Op.getOperand(1), Op.getOperand(2)); 3409 } 3410 case Intrinsic::arm_neon_vminu: 3411 case Intrinsic::arm_neon_vmaxu: { 3412 if (Op.getValueType().isFloatingPoint()) 3413 return SDValue(); 3414 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3415 ? ISD::UMIN : ISD::UMAX; 3416 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3417 Op.getOperand(1), Op.getOperand(2)); 3418 } 3419 case Intrinsic::arm_neon_vmins: 3420 case Intrinsic::arm_neon_vmaxs: { 3421 // v{min,max}s is overloaded between signed integers and floats. 3422 if (!Op.getValueType().isFloatingPoint()) { 3423 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3424 ? ISD::SMIN : ISD::SMAX; 3425 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3426 Op.getOperand(1), Op.getOperand(2)); 3427 } 3428 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3429 ? ISD::FMINNAN : ISD::FMAXNAN; 3430 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3431 Op.getOperand(1), Op.getOperand(2)); 3432 } 3433 case Intrinsic::arm_neon_vtbl1: 3434 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3435 Op.getOperand(1), Op.getOperand(2)); 3436 case Intrinsic::arm_neon_vtbl2: 3437 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3438 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3439 } 3440 } 3441 3442 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3443 const ARMSubtarget *Subtarget) { 3444 SDLoc dl(Op); 3445 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3446 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3447 if (SSID == SyncScope::SingleThread) 3448 return Op; 3449 3450 if (!Subtarget->hasDataBarrier()) { 3451 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3452 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3453 // here. 3454 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3455 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3456 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3457 DAG.getConstant(0, dl, MVT::i32)); 3458 } 3459 3460 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3461 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3462 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3463 if (Subtarget->isMClass()) { 3464 // Only a full system barrier exists in the M-class architectures. 3465 Domain = ARM_MB::SY; 3466 } else if (Subtarget->preferISHSTBarriers() && 3467 Ord == AtomicOrdering::Release) { 3468 // Swift happens to implement ISHST barriers in a way that's compatible with 3469 // Release semantics but weaker than ISH so we'd be fools not to use 3470 // it. Beware: other processors probably don't! 3471 Domain = ARM_MB::ISHST; 3472 } 3473 3474 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3475 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3476 DAG.getConstant(Domain, dl, MVT::i32)); 3477 } 3478 3479 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3480 const ARMSubtarget *Subtarget) { 3481 // ARM pre v5TE and Thumb1 does not have preload instructions. 3482 if (!(Subtarget->isThumb2() || 3483 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3484 // Just preserve the chain. 3485 return Op.getOperand(0); 3486 3487 SDLoc dl(Op); 3488 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3489 if (!isRead && 3490 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3491 // ARMv7 with MP extension has PLDW. 3492 return Op.getOperand(0); 3493 3494 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3495 if (Subtarget->isThumb()) { 3496 // Invert the bits. 3497 isRead = ~isRead & 1; 3498 isData = ~isData & 1; 3499 } 3500 3501 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3502 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3503 DAG.getConstant(isData, dl, MVT::i32)); 3504 } 3505 3506 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3507 MachineFunction &MF = DAG.getMachineFunction(); 3508 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3509 3510 // vastart just stores the address of the VarArgsFrameIndex slot into the 3511 // memory location argument. 3512 SDLoc dl(Op); 3513 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3514 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3515 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3516 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3517 MachinePointerInfo(SV)); 3518 } 3519 3520 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3521 CCValAssign &NextVA, 3522 SDValue &Root, 3523 SelectionDAG &DAG, 3524 const SDLoc &dl) const { 3525 MachineFunction &MF = DAG.getMachineFunction(); 3526 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3527 3528 const TargetRegisterClass *RC; 3529 if (AFI->isThumb1OnlyFunction()) 3530 RC = &ARM::tGPRRegClass; 3531 else 3532 RC = &ARM::GPRRegClass; 3533 3534 // Transform the arguments stored in physical registers into virtual ones. 3535 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3536 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3537 3538 SDValue ArgValue2; 3539 if (NextVA.isMemLoc()) { 3540 MachineFrameInfo &MFI = MF.getFrameInfo(); 3541 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3542 3543 // Create load node to retrieve arguments from the stack. 3544 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3545 ArgValue2 = DAG.getLoad( 3546 MVT::i32, dl, Root, FIN, 3547 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3548 } else { 3549 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3550 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3551 } 3552 if (!Subtarget->isLittle()) 3553 std::swap (ArgValue, ArgValue2); 3554 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3555 } 3556 3557 // The remaining GPRs hold either the beginning of variable-argument 3558 // data, or the beginning of an aggregate passed by value (usually 3559 // byval). Either way, we allocate stack slots adjacent to the data 3560 // provided by our caller, and store the unallocated registers there. 3561 // If this is a variadic function, the va_list pointer will begin with 3562 // these values; otherwise, this reassembles a (byval) structure that 3563 // was split between registers and memory. 3564 // Return: The frame index registers were stored into. 3565 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3566 const SDLoc &dl, SDValue &Chain, 3567 const Value *OrigArg, 3568 unsigned InRegsParamRecordIdx, 3569 int ArgOffset, unsigned ArgSize) const { 3570 // Currently, two use-cases possible: 3571 // Case #1. Non-var-args function, and we meet first byval parameter. 3572 // Setup first unallocated register as first byval register; 3573 // eat all remained registers 3574 // (these two actions are performed by HandleByVal method). 3575 // Then, here, we initialize stack frame with 3576 // "store-reg" instructions. 3577 // Case #2. Var-args function, that doesn't contain byval parameters. 3578 // The same: eat all remained unallocated registers, 3579 // initialize stack frame. 3580 3581 MachineFunction &MF = DAG.getMachineFunction(); 3582 MachineFrameInfo &MFI = MF.getFrameInfo(); 3583 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3584 unsigned RBegin, REnd; 3585 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3586 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3587 } else { 3588 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3589 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3590 REnd = ARM::R4; 3591 } 3592 3593 if (REnd != RBegin) 3594 ArgOffset = -4 * (ARM::R4 - RBegin); 3595 3596 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3597 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3598 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3599 3600 SmallVector<SDValue, 4> MemOps; 3601 const TargetRegisterClass *RC = 3602 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3603 3604 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3605 unsigned VReg = MF.addLiveIn(Reg, RC); 3606 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3607 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3608 MachinePointerInfo(OrigArg, 4 * i)); 3609 MemOps.push_back(Store); 3610 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3611 } 3612 3613 if (!MemOps.empty()) 3614 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3615 return FrameIndex; 3616 } 3617 3618 // Setup stack frame, the va_list pointer will start from. 3619 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3620 const SDLoc &dl, SDValue &Chain, 3621 unsigned ArgOffset, 3622 unsigned TotalArgRegsSaveSize, 3623 bool ForceMutable) const { 3624 MachineFunction &MF = DAG.getMachineFunction(); 3625 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3626 3627 // Try to store any remaining integer argument regs 3628 // to their spots on the stack so that they may be loaded by dereferencing 3629 // the result of va_next. 3630 // If there is no regs to be stored, just point address after last 3631 // argument passed via stack. 3632 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3633 CCInfo.getInRegsParamsCount(), 3634 CCInfo.getNextStackOffset(), 4); 3635 AFI->setVarArgsFrameIndex(FrameIndex); 3636 } 3637 3638 SDValue ARMTargetLowering::LowerFormalArguments( 3639 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3640 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3641 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3642 MachineFunction &MF = DAG.getMachineFunction(); 3643 MachineFrameInfo &MFI = MF.getFrameInfo(); 3644 3645 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3646 3647 // Assign locations to all of the incoming arguments. 3648 SmallVector<CCValAssign, 16> ArgLocs; 3649 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3650 *DAG.getContext()); 3651 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3652 3653 SmallVector<SDValue, 16> ArgValues; 3654 SDValue ArgValue; 3655 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3656 unsigned CurArgIdx = 0; 3657 3658 // Initially ArgRegsSaveSize is zero. 3659 // Then we increase this value each time we meet byval parameter. 3660 // We also increase this value in case of varargs function. 3661 AFI->setArgRegsSaveSize(0); 3662 3663 // Calculate the amount of stack space that we need to allocate to store 3664 // byval and variadic arguments that are passed in registers. 3665 // We need to know this before we allocate the first byval or variadic 3666 // argument, as they will be allocated a stack slot below the CFA (Canonical 3667 // Frame Address, the stack pointer at entry to the function). 3668 unsigned ArgRegBegin = ARM::R4; 3669 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3670 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3671 break; 3672 3673 CCValAssign &VA = ArgLocs[i]; 3674 unsigned Index = VA.getValNo(); 3675 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3676 if (!Flags.isByVal()) 3677 continue; 3678 3679 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3680 unsigned RBegin, REnd; 3681 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3682 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3683 3684 CCInfo.nextInRegsParam(); 3685 } 3686 CCInfo.rewindByValRegsInfo(); 3687 3688 int lastInsIndex = -1; 3689 if (isVarArg && MFI.hasVAStart()) { 3690 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3691 if (RegIdx != array_lengthof(GPRArgRegs)) 3692 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3693 } 3694 3695 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3696 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3697 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3698 3699 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3700 CCValAssign &VA = ArgLocs[i]; 3701 if (Ins[VA.getValNo()].isOrigArg()) { 3702 std::advance(CurOrigArg, 3703 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3704 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3705 } 3706 // Arguments stored in registers. 3707 if (VA.isRegLoc()) { 3708 EVT RegVT = VA.getLocVT(); 3709 3710 if (VA.needsCustom()) { 3711 // f64 and vector types are split up into multiple registers or 3712 // combinations of registers and stack slots. 3713 if (VA.getLocVT() == MVT::v2f64) { 3714 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3715 Chain, DAG, dl); 3716 VA = ArgLocs[++i]; // skip ahead to next loc 3717 SDValue ArgValue2; 3718 if (VA.isMemLoc()) { 3719 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3720 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3721 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3722 MachinePointerInfo::getFixedStack( 3723 DAG.getMachineFunction(), FI)); 3724 } else { 3725 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3726 Chain, DAG, dl); 3727 } 3728 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3729 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3730 ArgValue, ArgValue1, 3731 DAG.getIntPtrConstant(0, dl)); 3732 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3733 ArgValue, ArgValue2, 3734 DAG.getIntPtrConstant(1, dl)); 3735 } else 3736 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3737 } else { 3738 const TargetRegisterClass *RC; 3739 3740 3741 if (RegVT == MVT::f16) 3742 RC = &ARM::HPRRegClass; 3743 else if (RegVT == MVT::f32) 3744 RC = &ARM::SPRRegClass; 3745 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3746 RC = &ARM::DPRRegClass; 3747 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3748 RC = &ARM::QPRRegClass; 3749 else if (RegVT == MVT::i32) 3750 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3751 : &ARM::GPRRegClass; 3752 else 3753 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3754 3755 // Transform the arguments in physical registers into virtual ones. 3756 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3757 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3758 } 3759 3760 // If this is an 8 or 16-bit value, it is really passed promoted 3761 // to 32 bits. Insert an assert[sz]ext to capture this, then 3762 // truncate to the right size. 3763 switch (VA.getLocInfo()) { 3764 default: llvm_unreachable("Unknown loc info!"); 3765 case CCValAssign::Full: break; 3766 case CCValAssign::BCvt: 3767 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3768 break; 3769 case CCValAssign::SExt: 3770 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3771 DAG.getValueType(VA.getValVT())); 3772 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3773 break; 3774 case CCValAssign::ZExt: 3775 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3776 DAG.getValueType(VA.getValVT())); 3777 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3778 break; 3779 } 3780 3781 InVals.push_back(ArgValue); 3782 } else { // VA.isRegLoc() 3783 // sanity check 3784 assert(VA.isMemLoc()); 3785 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3786 3787 int index = VA.getValNo(); 3788 3789 // Some Ins[] entries become multiple ArgLoc[] entries. 3790 // Process them only once. 3791 if (index != lastInsIndex) 3792 { 3793 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3794 // FIXME: For now, all byval parameter objects are marked mutable. 3795 // This can be changed with more analysis. 3796 // In case of tail call optimization mark all arguments mutable. 3797 // Since they could be overwritten by lowering of arguments in case of 3798 // a tail call. 3799 if (Flags.isByVal()) { 3800 assert(Ins[index].isOrigArg() && 3801 "Byval arguments cannot be implicit"); 3802 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3803 3804 int FrameIndex = StoreByValRegs( 3805 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3806 VA.getLocMemOffset(), Flags.getByValSize()); 3807 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3808 CCInfo.nextInRegsParam(); 3809 } else { 3810 unsigned FIOffset = VA.getLocMemOffset(); 3811 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3812 FIOffset, true); 3813 3814 // Create load nodes to retrieve arguments from the stack. 3815 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3816 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3817 MachinePointerInfo::getFixedStack( 3818 DAG.getMachineFunction(), FI))); 3819 } 3820 lastInsIndex = index; 3821 } 3822 } 3823 } 3824 3825 // varargs 3826 if (isVarArg && MFI.hasVAStart()) 3827 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3828 CCInfo.getNextStackOffset(), 3829 TotalArgRegsSaveSize); 3830 3831 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3832 3833 return Chain; 3834 } 3835 3836 /// isFloatingPointZero - Return true if this is +0.0. 3837 static bool isFloatingPointZero(SDValue Op) { 3838 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3839 return CFP->getValueAPF().isPosZero(); 3840 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3841 // Maybe this has already been legalized into the constant pool? 3842 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3843 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3844 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3845 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3846 return CFP->getValueAPF().isPosZero(); 3847 } 3848 } else if (Op->getOpcode() == ISD::BITCAST && 3849 Op->getValueType(0) == MVT::f64) { 3850 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3851 // created by LowerConstantFP(). 3852 SDValue BitcastOp = Op->getOperand(0); 3853 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3854 isNullConstant(BitcastOp->getOperand(0))) 3855 return true; 3856 } 3857 return false; 3858 } 3859 3860 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3861 /// the given operands. 3862 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3863 SDValue &ARMcc, SelectionDAG &DAG, 3864 const SDLoc &dl) const { 3865 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3866 unsigned C = RHSC->getZExtValue(); 3867 if (!isLegalICmpImmediate(C)) { 3868 // Constant does not fit, try adjusting it by one? 3869 switch (CC) { 3870 default: break; 3871 case ISD::SETLT: 3872 case ISD::SETGE: 3873 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3874 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3875 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3876 } 3877 break; 3878 case ISD::SETULT: 3879 case ISD::SETUGE: 3880 if (C != 0 && isLegalICmpImmediate(C-1)) { 3881 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3882 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3883 } 3884 break; 3885 case ISD::SETLE: 3886 case ISD::SETGT: 3887 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3888 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3889 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3890 } 3891 break; 3892 case ISD::SETULE: 3893 case ISD::SETUGT: 3894 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3895 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3896 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3897 } 3898 break; 3899 } 3900 } 3901 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3902 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3903 // In ARM and Thumb-2, the compare instructions can shift their second 3904 // operand. 3905 CC = ISD::getSetCCSwappedOperands(CC); 3906 std::swap(LHS, RHS); 3907 } 3908 3909 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3910 ARMISD::NodeType CompareType; 3911 switch (CondCode) { 3912 default: 3913 CompareType = ARMISD::CMP; 3914 break; 3915 case ARMCC::EQ: 3916 case ARMCC::NE: 3917 // Uses only Z Flag 3918 CompareType = ARMISD::CMPZ; 3919 break; 3920 } 3921 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3922 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3923 } 3924 3925 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3926 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3927 SelectionDAG &DAG, const SDLoc &dl, 3928 bool InvalidOnQNaN) const { 3929 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3930 SDValue Cmp; 3931 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3932 if (!isFloatingPointZero(RHS)) 3933 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3934 else 3935 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3936 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3937 } 3938 3939 /// duplicateCmp - Glue values can have only one use, so this function 3940 /// duplicates a comparison node. 3941 SDValue 3942 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3943 unsigned Opc = Cmp.getOpcode(); 3944 SDLoc DL(Cmp); 3945 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3946 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3947 3948 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3949 Cmp = Cmp.getOperand(0); 3950 Opc = Cmp.getOpcode(); 3951 if (Opc == ARMISD::CMPFP) 3952 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3953 Cmp.getOperand(1), Cmp.getOperand(2)); 3954 else { 3955 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3956 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3957 Cmp.getOperand(1)); 3958 } 3959 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3960 } 3961 3962 // This function returns three things: the arithmetic computation itself 3963 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 3964 // comparison and the condition code define the case in which the arithmetic 3965 // computation *does not* overflow. 3966 std::pair<SDValue, SDValue> 3967 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3968 SDValue &ARMcc) const { 3969 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3970 3971 SDValue Value, OverflowCmp; 3972 SDValue LHS = Op.getOperand(0); 3973 SDValue RHS = Op.getOperand(1); 3974 SDLoc dl(Op); 3975 3976 // FIXME: We are currently always generating CMPs because we don't support 3977 // generating CMN through the backend. This is not as good as the natural 3978 // CMP case because it causes a register dependency and cannot be folded 3979 // later. 3980 3981 switch (Op.getOpcode()) { 3982 default: 3983 llvm_unreachable("Unknown overflow instruction!"); 3984 case ISD::SADDO: 3985 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3986 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3987 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3988 break; 3989 case ISD::UADDO: 3990 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3991 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 3992 // We do not use it in the USUBO case as Value may not be used. 3993 Value = DAG.getNode(ARMISD::ADDC, dl, 3994 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 3995 .getValue(0); 3996 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3997 break; 3998 case ISD::SSUBO: 3999 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4000 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4001 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4002 break; 4003 case ISD::USUBO: 4004 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4005 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4006 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4007 break; 4008 case ISD::UMULO: 4009 // We generate a UMUL_LOHI and then check if the high word is 0. 4010 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4011 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4012 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4013 LHS, RHS); 4014 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4015 DAG.getConstant(0, dl, MVT::i32)); 4016 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4017 break; 4018 case ISD::SMULO: 4019 // We generate a SMUL_LOHI and then check if all the bits of the high word 4020 // are the same as the sign bit of the low word. 4021 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4022 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4023 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4024 LHS, RHS); 4025 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4026 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4027 Value.getValue(0), 4028 DAG.getConstant(31, dl, MVT::i32))); 4029 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4030 break; 4031 } // switch (...) 4032 4033 return std::make_pair(Value, OverflowCmp); 4034 } 4035 4036 SDValue 4037 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4038 // Let legalize expand this if it isn't a legal type yet. 4039 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4040 return SDValue(); 4041 4042 SDValue Value, OverflowCmp; 4043 SDValue ARMcc; 4044 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4045 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4046 SDLoc dl(Op); 4047 // We use 0 and 1 as false and true values. 4048 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4049 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4050 EVT VT = Op.getValueType(); 4051 4052 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4053 ARMcc, CCR, OverflowCmp); 4054 4055 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4056 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4057 } 4058 4059 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4060 SelectionDAG &DAG) { 4061 SDLoc DL(BoolCarry); 4062 EVT CarryVT = BoolCarry.getValueType(); 4063 4064 // This converts the boolean value carry into the carry flag by doing 4065 // ARMISD::SUBC Carry, 1 4066 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4067 DAG.getVTList(CarryVT, MVT::i32), 4068 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4069 return Carry.getValue(1); 4070 } 4071 4072 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4073 SelectionDAG &DAG) { 4074 SDLoc DL(Flags); 4075 4076 // Now convert the carry flag into a boolean carry. We do this 4077 // using ARMISD:ADDE 0, 0, Carry 4078 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4079 DAG.getConstant(0, DL, MVT::i32), 4080 DAG.getConstant(0, DL, MVT::i32), Flags); 4081 } 4082 4083 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4084 SelectionDAG &DAG) const { 4085 // Let legalize expand this if it isn't a legal type yet. 4086 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4087 return SDValue(); 4088 4089 SDValue LHS = Op.getOperand(0); 4090 SDValue RHS = Op.getOperand(1); 4091 SDLoc dl(Op); 4092 4093 EVT VT = Op.getValueType(); 4094 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4095 SDValue Value; 4096 SDValue Overflow; 4097 switch (Op.getOpcode()) { 4098 default: 4099 llvm_unreachable("Unknown overflow instruction!"); 4100 case ISD::UADDO: 4101 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4102 // Convert the carry flag into a boolean value. 4103 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4104 break; 4105 case ISD::USUBO: { 4106 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4107 // Convert the carry flag into a boolean value. 4108 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4109 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4110 // value. So compute 1 - C. 4111 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4112 DAG.getConstant(1, dl, MVT::i32), Overflow); 4113 break; 4114 } 4115 } 4116 4117 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4118 } 4119 4120 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4121 SDValue Cond = Op.getOperand(0); 4122 SDValue SelectTrue = Op.getOperand(1); 4123 SDValue SelectFalse = Op.getOperand(2); 4124 SDLoc dl(Op); 4125 unsigned Opc = Cond.getOpcode(); 4126 4127 if (Cond.getResNo() == 1 && 4128 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4129 Opc == ISD::USUBO)) { 4130 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4131 return SDValue(); 4132 4133 SDValue Value, OverflowCmp; 4134 SDValue ARMcc; 4135 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4136 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4137 EVT VT = Op.getValueType(); 4138 4139 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4140 OverflowCmp, DAG); 4141 } 4142 4143 // Convert: 4144 // 4145 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4146 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4147 // 4148 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4149 const ConstantSDNode *CMOVTrue = 4150 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4151 const ConstantSDNode *CMOVFalse = 4152 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4153 4154 if (CMOVTrue && CMOVFalse) { 4155 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4156 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4157 4158 SDValue True; 4159 SDValue False; 4160 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4161 True = SelectTrue; 4162 False = SelectFalse; 4163 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4164 True = SelectFalse; 4165 False = SelectTrue; 4166 } 4167 4168 if (True.getNode() && False.getNode()) { 4169 EVT VT = Op.getValueType(); 4170 SDValue ARMcc = Cond.getOperand(2); 4171 SDValue CCR = Cond.getOperand(3); 4172 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4173 assert(True.getValueType() == VT); 4174 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4175 } 4176 } 4177 } 4178 4179 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4180 // undefined bits before doing a full-word comparison with zero. 4181 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4182 DAG.getConstant(1, dl, Cond.getValueType())); 4183 4184 return DAG.getSelectCC(dl, Cond, 4185 DAG.getConstant(0, dl, Cond.getValueType()), 4186 SelectTrue, SelectFalse, ISD::SETNE); 4187 } 4188 4189 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4190 bool &swpCmpOps, bool &swpVselOps) { 4191 // Start by selecting the GE condition code for opcodes that return true for 4192 // 'equality' 4193 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4194 CC == ISD::SETULE) 4195 CondCode = ARMCC::GE; 4196 4197 // and GT for opcodes that return false for 'equality'. 4198 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4199 CC == ISD::SETULT) 4200 CondCode = ARMCC::GT; 4201 4202 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4203 // to swap the compare operands. 4204 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4205 CC == ISD::SETULT) 4206 swpCmpOps = true; 4207 4208 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4209 // If we have an unordered opcode, we need to swap the operands to the VSEL 4210 // instruction (effectively negating the condition). 4211 // 4212 // This also has the effect of swapping which one of 'less' or 'greater' 4213 // returns true, so we also swap the compare operands. It also switches 4214 // whether we return true for 'equality', so we compensate by picking the 4215 // opposite condition code to our original choice. 4216 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4217 CC == ISD::SETUGT) { 4218 swpCmpOps = !swpCmpOps; 4219 swpVselOps = !swpVselOps; 4220 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4221 } 4222 4223 // 'ordered' is 'anything but unordered', so use the VS condition code and 4224 // swap the VSEL operands. 4225 if (CC == ISD::SETO) { 4226 CondCode = ARMCC::VS; 4227 swpVselOps = true; 4228 } 4229 4230 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4231 // code and swap the VSEL operands. 4232 if (CC == ISD::SETUNE) { 4233 CondCode = ARMCC::EQ; 4234 swpVselOps = true; 4235 } 4236 } 4237 4238 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4239 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4240 SDValue Cmp, SelectionDAG &DAG) const { 4241 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4242 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4243 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4244 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4245 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4246 4247 SDValue TrueLow = TrueVal.getValue(0); 4248 SDValue TrueHigh = TrueVal.getValue(1); 4249 SDValue FalseLow = FalseVal.getValue(0); 4250 SDValue FalseHigh = FalseVal.getValue(1); 4251 4252 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4253 ARMcc, CCR, Cmp); 4254 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4255 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4256 4257 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4258 } else { 4259 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4260 Cmp); 4261 } 4262 } 4263 4264 static bool isGTorGE(ISD::CondCode CC) { 4265 return CC == ISD::SETGT || CC == ISD::SETGE; 4266 } 4267 4268 static bool isLTorLE(ISD::CondCode CC) { 4269 return CC == ISD::SETLT || CC == ISD::SETLE; 4270 } 4271 4272 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4273 // All of these conditions (and their <= and >= counterparts) will do: 4274 // x < k ? k : x 4275 // x > k ? x : k 4276 // k < x ? x : k 4277 // k > x ? k : x 4278 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4279 const SDValue TrueVal, const SDValue FalseVal, 4280 const ISD::CondCode CC, const SDValue K) { 4281 return (isGTorGE(CC) && 4282 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4283 (isLTorLE(CC) && 4284 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4285 } 4286 4287 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4288 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4289 const SDValue TrueVal, const SDValue FalseVal, 4290 const ISD::CondCode CC, const SDValue K) { 4291 return (isGTorGE(CC) && 4292 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4293 (isLTorLE(CC) && 4294 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4295 } 4296 4297 // Check if two chained conditionals could be converted into SSAT or USAT. 4298 // 4299 // SSAT can replace a set of two conditional selectors that bound a number to an 4300 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4301 // 4302 // x < -k ? -k : (x > k ? k : x) 4303 // x < -k ? -k : (x < k ? x : k) 4304 // x > -k ? (x > k ? k : x) : -k 4305 // x < k ? (x < -k ? -k : x) : k 4306 // etc. 4307 // 4308 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4309 // a power of 2. 4310 // 4311 // It returns true if the conversion can be done, false otherwise. 4312 // Additionally, the variable is returned in parameter V, the constant in K and 4313 // usat is set to true if the conditional represents an unsigned saturation 4314 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4315 uint64_t &K, bool &usat) { 4316 SDValue LHS1 = Op.getOperand(0); 4317 SDValue RHS1 = Op.getOperand(1); 4318 SDValue TrueVal1 = Op.getOperand(2); 4319 SDValue FalseVal1 = Op.getOperand(3); 4320 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4321 4322 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4323 if (Op2.getOpcode() != ISD::SELECT_CC) 4324 return false; 4325 4326 SDValue LHS2 = Op2.getOperand(0); 4327 SDValue RHS2 = Op2.getOperand(1); 4328 SDValue TrueVal2 = Op2.getOperand(2); 4329 SDValue FalseVal2 = Op2.getOperand(3); 4330 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4331 4332 // Find out which are the constants and which are the variables 4333 // in each conditional 4334 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4335 ? &RHS1 4336 : nullptr; 4337 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4338 ? &RHS2 4339 : nullptr; 4340 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4341 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4342 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4343 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4344 4345 // We must detect cases where the original operations worked with 16- or 4346 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4347 // must work with sign-extended values but the select operations return 4348 // the original non-extended value. 4349 SDValue V2TmpReg = V2Tmp; 4350 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4351 V2TmpReg = V2Tmp->getOperand(0); 4352 4353 // Check that the registers and the constants have the correct values 4354 // in both conditionals 4355 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4356 V2TmpReg != V2) 4357 return false; 4358 4359 // Figure out which conditional is saturating the lower/upper bound. 4360 const SDValue *LowerCheckOp = 4361 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4362 ? &Op 4363 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4364 ? &Op2 4365 : nullptr; 4366 const SDValue *UpperCheckOp = 4367 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4368 ? &Op 4369 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4370 ? &Op2 4371 : nullptr; 4372 4373 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4374 return false; 4375 4376 // Check that the constant in the lower-bound check is 4377 // the opposite of the constant in the upper-bound check 4378 // in 1's complement. 4379 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4380 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4381 int64_t PosVal = std::max(Val1, Val2); 4382 int64_t NegVal = std::min(Val1, Val2); 4383 4384 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4385 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4386 isPowerOf2_64(PosVal + 1)) { 4387 4388 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4389 if (Val1 == ~Val2) 4390 usat = false; 4391 else if (NegVal == 0) 4392 usat = true; 4393 else 4394 return false; 4395 4396 V = V2; 4397 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4398 4399 return true; 4400 } 4401 4402 return false; 4403 } 4404 4405 // Check if a condition of the type x < k ? k : x can be converted into a 4406 // bit operation instead of conditional moves. 4407 // Currently this is allowed given: 4408 // - The conditions and values match up 4409 // - k is 0 or -1 (all ones) 4410 // This function will not check the last condition, thats up to the caller 4411 // It returns true if the transformation can be made, and in such case 4412 // returns x in V, and k in SatK. 4413 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4414 SDValue &SatK) 4415 { 4416 SDValue LHS = Op.getOperand(0); 4417 SDValue RHS = Op.getOperand(1); 4418 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4419 SDValue TrueVal = Op.getOperand(2); 4420 SDValue FalseVal = Op.getOperand(3); 4421 4422 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4423 ? &RHS 4424 : nullptr; 4425 4426 // No constant operation in comparison, early out 4427 if (!K) 4428 return false; 4429 4430 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4431 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4432 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4433 4434 // If the constant on left and right side, or variable on left and right, 4435 // does not match, early out 4436 if (*K != KTmp || V != VTmp) 4437 return false; 4438 4439 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4440 SatK = *K; 4441 return true; 4442 } 4443 4444 return false; 4445 } 4446 4447 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4448 EVT VT = Op.getValueType(); 4449 SDLoc dl(Op); 4450 4451 // Try to convert two saturating conditional selects into a single SSAT 4452 SDValue SatValue; 4453 uint64_t SatConstant; 4454 bool SatUSat; 4455 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4456 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4457 if (SatUSat) 4458 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4459 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4460 else 4461 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4462 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4463 } 4464 4465 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4466 // into more efficient bit operations, which is possible when k is 0 or -1 4467 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4468 // single instructions. On Thumb the shift and the bit operation will be two 4469 // instructions. 4470 // Only allow this transformation on full-width (32-bit) operations 4471 SDValue LowerSatConstant; 4472 if (VT == MVT::i32 && 4473 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4474 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4475 DAG.getConstant(31, dl, VT)); 4476 if (isNullConstant(LowerSatConstant)) { 4477 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4478 DAG.getAllOnesConstant(dl, VT)); 4479 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4480 } else if (isAllOnesConstant(LowerSatConstant)) 4481 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4482 } 4483 4484 SDValue LHS = Op.getOperand(0); 4485 SDValue RHS = Op.getOperand(1); 4486 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4487 SDValue TrueVal = Op.getOperand(2); 4488 SDValue FalseVal = Op.getOperand(3); 4489 4490 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4491 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4492 dl); 4493 4494 // If softenSetCCOperands only returned one value, we should compare it to 4495 // zero. 4496 if (!RHS.getNode()) { 4497 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4498 CC = ISD::SETNE; 4499 } 4500 } 4501 4502 if (LHS.getValueType() == MVT::i32) { 4503 // Try to generate VSEL on ARMv8. 4504 // The VSEL instruction can't use all the usual ARM condition 4505 // codes: it only has two bits to select the condition code, so it's 4506 // constrained to use only GE, GT, VS and EQ. 4507 // 4508 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4509 // swap the operands of the previous compare instruction (effectively 4510 // inverting the compare condition, swapping 'less' and 'greater') and 4511 // sometimes need to swap the operands to the VSEL (which inverts the 4512 // condition in the sense of firing whenever the previous condition didn't) 4513 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4514 TrueVal.getValueType() == MVT::f64)) { 4515 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4516 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4517 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4518 CC = ISD::getSetCCInverse(CC, true); 4519 std::swap(TrueVal, FalseVal); 4520 } 4521 } 4522 4523 SDValue ARMcc; 4524 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4525 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4526 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4527 } 4528 4529 ARMCC::CondCodes CondCode, CondCode2; 4530 bool InvalidOnQNaN; 4531 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4532 4533 // Normalize the fp compare. If RHS is zero we keep it there so we match 4534 // CMPFPw0 instead of CMPFP. 4535 if (Subtarget->hasFPARMv8() && !isFloatingPointZero(RHS) && 4536 (TrueVal.getValueType() == MVT::f16 || 4537 TrueVal.getValueType() == MVT::f32 || 4538 TrueVal.getValueType() == MVT::f64)) { 4539 bool swpCmpOps = false; 4540 bool swpVselOps = false; 4541 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4542 4543 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4544 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4545 if (swpCmpOps) 4546 std::swap(LHS, RHS); 4547 if (swpVselOps) 4548 std::swap(TrueVal, FalseVal); 4549 } 4550 } 4551 4552 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4553 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4554 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4555 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4556 if (CondCode2 != ARMCC::AL) { 4557 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4558 // FIXME: Needs another CMP because flag can have but one use. 4559 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4560 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4561 } 4562 return Result; 4563 } 4564 4565 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4566 /// to morph to an integer compare sequence. 4567 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4568 const ARMSubtarget *Subtarget) { 4569 SDNode *N = Op.getNode(); 4570 if (!N->hasOneUse()) 4571 // Otherwise it requires moving the value from fp to integer registers. 4572 return false; 4573 if (!N->getNumValues()) 4574 return false; 4575 EVT VT = Op.getValueType(); 4576 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4577 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4578 // vmrs are very slow, e.g. cortex-a8. 4579 return false; 4580 4581 if (isFloatingPointZero(Op)) { 4582 SeenZero = true; 4583 return true; 4584 } 4585 return ISD::isNormalLoad(N); 4586 } 4587 4588 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4589 if (isFloatingPointZero(Op)) 4590 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4591 4592 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4593 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4594 Ld->getPointerInfo(), Ld->getAlignment(), 4595 Ld->getMemOperand()->getFlags()); 4596 4597 llvm_unreachable("Unknown VFP cmp argument!"); 4598 } 4599 4600 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4601 SDValue &RetVal1, SDValue &RetVal2) { 4602 SDLoc dl(Op); 4603 4604 if (isFloatingPointZero(Op)) { 4605 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4606 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4607 return; 4608 } 4609 4610 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4611 SDValue Ptr = Ld->getBasePtr(); 4612 RetVal1 = 4613 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4614 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4615 4616 EVT PtrType = Ptr.getValueType(); 4617 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4618 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4619 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4620 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4621 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4622 Ld->getMemOperand()->getFlags()); 4623 return; 4624 } 4625 4626 llvm_unreachable("Unknown VFP cmp argument!"); 4627 } 4628 4629 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4630 /// f32 and even f64 comparisons to integer ones. 4631 SDValue 4632 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4633 SDValue Chain = Op.getOperand(0); 4634 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4635 SDValue LHS = Op.getOperand(2); 4636 SDValue RHS = Op.getOperand(3); 4637 SDValue Dest = Op.getOperand(4); 4638 SDLoc dl(Op); 4639 4640 bool LHSSeenZero = false; 4641 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4642 bool RHSSeenZero = false; 4643 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4644 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4645 // If unsafe fp math optimization is enabled and there are no other uses of 4646 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4647 // to an integer comparison. 4648 if (CC == ISD::SETOEQ) 4649 CC = ISD::SETEQ; 4650 else if (CC == ISD::SETUNE) 4651 CC = ISD::SETNE; 4652 4653 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4654 SDValue ARMcc; 4655 if (LHS.getValueType() == MVT::f32) { 4656 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4657 bitcastf32Toi32(LHS, DAG), Mask); 4658 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4659 bitcastf32Toi32(RHS, DAG), Mask); 4660 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4661 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4662 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4663 Chain, Dest, ARMcc, CCR, Cmp); 4664 } 4665 4666 SDValue LHS1, LHS2; 4667 SDValue RHS1, RHS2; 4668 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4669 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4670 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4671 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4672 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4673 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4674 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4675 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4676 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4677 } 4678 4679 return SDValue(); 4680 } 4681 4682 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4683 SDValue Chain = Op.getOperand(0); 4684 SDValue Cond = Op.getOperand(1); 4685 SDValue Dest = Op.getOperand(2); 4686 SDLoc dl(Op); 4687 4688 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4689 // instruction. 4690 unsigned Opc = Cond.getOpcode(); 4691 if (Cond.getResNo() == 1 && 4692 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4693 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4694 // Only lower legal XALUO ops. 4695 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4696 return SDValue(); 4697 4698 // The actual operation with overflow check. 4699 SDValue Value, OverflowCmp; 4700 SDValue ARMcc; 4701 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4702 4703 // Reverse the condition code. 4704 ARMCC::CondCodes CondCode = 4705 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4706 CondCode = ARMCC::getOppositeCondition(CondCode); 4707 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4708 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4709 4710 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4711 OverflowCmp); 4712 } 4713 4714 return SDValue(); 4715 } 4716 4717 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4718 SDValue Chain = Op.getOperand(0); 4719 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4720 SDValue LHS = Op.getOperand(2); 4721 SDValue RHS = Op.getOperand(3); 4722 SDValue Dest = Op.getOperand(4); 4723 SDLoc dl(Op); 4724 4725 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4726 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4727 dl); 4728 4729 // If softenSetCCOperands only returned one value, we should compare it to 4730 // zero. 4731 if (!RHS.getNode()) { 4732 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4733 CC = ISD::SETNE; 4734 } 4735 } 4736 4737 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4738 // instruction. 4739 unsigned Opc = LHS.getOpcode(); 4740 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4741 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4742 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO) && 4743 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4744 // Only lower legal XALUO ops. 4745 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4746 return SDValue(); 4747 4748 // The actual operation with overflow check. 4749 SDValue Value, OverflowCmp; 4750 SDValue ARMcc; 4751 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4752 4753 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4754 // Reverse the condition code. 4755 ARMCC::CondCodes CondCode = 4756 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4757 CondCode = ARMCC::getOppositeCondition(CondCode); 4758 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4759 } 4760 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4761 4762 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4763 OverflowCmp); 4764 } 4765 4766 if (LHS.getValueType() == MVT::i32) { 4767 SDValue ARMcc; 4768 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4769 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4770 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4771 Chain, Dest, ARMcc, CCR, Cmp); 4772 } 4773 4774 if (getTargetMachine().Options.UnsafeFPMath && 4775 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4776 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4777 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4778 return Result; 4779 } 4780 4781 ARMCC::CondCodes CondCode, CondCode2; 4782 bool InvalidOnQNaN; 4783 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4784 4785 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4786 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4787 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4788 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4789 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4790 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4791 if (CondCode2 != ARMCC::AL) { 4792 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4793 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4794 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4795 } 4796 return Res; 4797 } 4798 4799 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4800 SDValue Chain = Op.getOperand(0); 4801 SDValue Table = Op.getOperand(1); 4802 SDValue Index = Op.getOperand(2); 4803 SDLoc dl(Op); 4804 4805 EVT PTy = getPointerTy(DAG.getDataLayout()); 4806 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4807 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4808 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4809 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4810 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4811 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4812 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4813 // which does another jump to the destination. This also makes it easier 4814 // to translate it to TBB / TBH later (Thumb2 only). 4815 // FIXME: This might not work if the function is extremely large. 4816 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4817 Addr, Op.getOperand(2), JTI); 4818 } 4819 if (isPositionIndependent() || Subtarget->isROPI()) { 4820 Addr = 4821 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4822 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4823 Chain = Addr.getValue(1); 4824 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4825 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4826 } else { 4827 Addr = 4828 DAG.getLoad(PTy, dl, Chain, Addr, 4829 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4830 Chain = Addr.getValue(1); 4831 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4832 } 4833 } 4834 4835 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4836 EVT VT = Op.getValueType(); 4837 SDLoc dl(Op); 4838 4839 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4840 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4841 return Op; 4842 return DAG.UnrollVectorOp(Op.getNode()); 4843 } 4844 4845 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4846 "Invalid type for custom lowering!"); 4847 if (VT != MVT::v4i16) 4848 return DAG.UnrollVectorOp(Op.getNode()); 4849 4850 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4851 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4852 } 4853 4854 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4855 EVT VT = Op.getValueType(); 4856 if (VT.isVector()) 4857 return LowerVectorFP_TO_INT(Op, DAG); 4858 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4859 RTLIB::Libcall LC; 4860 if (Op.getOpcode() == ISD::FP_TO_SINT) 4861 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4862 Op.getValueType()); 4863 else 4864 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4865 Op.getValueType()); 4866 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4867 /*isSigned*/ false, SDLoc(Op)).first; 4868 } 4869 4870 return Op; 4871 } 4872 4873 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4874 EVT VT = Op.getValueType(); 4875 SDLoc dl(Op); 4876 4877 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4878 if (VT.getVectorElementType() == MVT::f32) 4879 return Op; 4880 return DAG.UnrollVectorOp(Op.getNode()); 4881 } 4882 4883 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4884 "Invalid type for custom lowering!"); 4885 if (VT != MVT::v4f32) 4886 return DAG.UnrollVectorOp(Op.getNode()); 4887 4888 unsigned CastOpc; 4889 unsigned Opc; 4890 switch (Op.getOpcode()) { 4891 default: llvm_unreachable("Invalid opcode!"); 4892 case ISD::SINT_TO_FP: 4893 CastOpc = ISD::SIGN_EXTEND; 4894 Opc = ISD::SINT_TO_FP; 4895 break; 4896 case ISD::UINT_TO_FP: 4897 CastOpc = ISD::ZERO_EXTEND; 4898 Opc = ISD::UINT_TO_FP; 4899 break; 4900 } 4901 4902 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4903 return DAG.getNode(Opc, dl, VT, Op); 4904 } 4905 4906 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4907 EVT VT = Op.getValueType(); 4908 if (VT.isVector()) 4909 return LowerVectorINT_TO_FP(Op, DAG); 4910 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4911 RTLIB::Libcall LC; 4912 if (Op.getOpcode() == ISD::SINT_TO_FP) 4913 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4914 Op.getValueType()); 4915 else 4916 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4917 Op.getValueType()); 4918 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4919 /*isSigned*/ false, SDLoc(Op)).first; 4920 } 4921 4922 return Op; 4923 } 4924 4925 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4926 // Implement fcopysign with a fabs and a conditional fneg. 4927 SDValue Tmp0 = Op.getOperand(0); 4928 SDValue Tmp1 = Op.getOperand(1); 4929 SDLoc dl(Op); 4930 EVT VT = Op.getValueType(); 4931 EVT SrcVT = Tmp1.getValueType(); 4932 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4933 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4934 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4935 4936 if (UseNEON) { 4937 // Use VBSL to copy the sign bit. 4938 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4939 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4940 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4941 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4942 if (VT == MVT::f64) 4943 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4944 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4945 DAG.getConstant(32, dl, MVT::i32)); 4946 else /*if (VT == MVT::f32)*/ 4947 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4948 if (SrcVT == MVT::f32) { 4949 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4950 if (VT == MVT::f64) 4951 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4952 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4953 DAG.getConstant(32, dl, MVT::i32)); 4954 } else if (VT == MVT::f32) 4955 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4956 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4957 DAG.getConstant(32, dl, MVT::i32)); 4958 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4959 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4960 4961 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4962 dl, MVT::i32); 4963 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4964 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4965 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4966 4967 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4968 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4969 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4970 if (VT == MVT::f32) { 4971 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4972 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4973 DAG.getConstant(0, dl, MVT::i32)); 4974 } else { 4975 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4976 } 4977 4978 return Res; 4979 } 4980 4981 // Bitcast operand 1 to i32. 4982 if (SrcVT == MVT::f64) 4983 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4984 Tmp1).getValue(1); 4985 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4986 4987 // Or in the signbit with integer operations. 4988 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4989 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4990 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4991 if (VT == MVT::f32) { 4992 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4993 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4994 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4995 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4996 } 4997 4998 // f64: Or the high part with signbit and then combine two parts. 4999 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5000 Tmp0); 5001 SDValue Lo = Tmp0.getValue(0); 5002 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5003 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5004 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5005 } 5006 5007 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5008 MachineFunction &MF = DAG.getMachineFunction(); 5009 MachineFrameInfo &MFI = MF.getFrameInfo(); 5010 MFI.setReturnAddressIsTaken(true); 5011 5012 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5013 return SDValue(); 5014 5015 EVT VT = Op.getValueType(); 5016 SDLoc dl(Op); 5017 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5018 if (Depth) { 5019 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5020 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5021 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5022 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5023 MachinePointerInfo()); 5024 } 5025 5026 // Return LR, which contains the return address. Mark it an implicit live-in. 5027 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5028 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5029 } 5030 5031 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5032 const ARMBaseRegisterInfo &ARI = 5033 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5034 MachineFunction &MF = DAG.getMachineFunction(); 5035 MachineFrameInfo &MFI = MF.getFrameInfo(); 5036 MFI.setFrameAddressIsTaken(true); 5037 5038 EVT VT = Op.getValueType(); 5039 SDLoc dl(Op); // FIXME probably not meaningful 5040 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5041 unsigned FrameReg = ARI.getFrameRegister(MF); 5042 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5043 while (Depth--) 5044 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5045 MachinePointerInfo()); 5046 return FrameAddr; 5047 } 5048 5049 // FIXME? Maybe this could be a TableGen attribute on some registers and 5050 // this table could be generated automatically from RegInfo. 5051 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5052 SelectionDAG &DAG) const { 5053 unsigned Reg = StringSwitch<unsigned>(RegName) 5054 .Case("sp", ARM::SP) 5055 .Default(0); 5056 if (Reg) 5057 return Reg; 5058 report_fatal_error(Twine("Invalid register name \"" 5059 + StringRef(RegName) + "\".")); 5060 } 5061 5062 // Result is 64 bit value so split into two 32 bit values and return as a 5063 // pair of values. 5064 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5065 SelectionDAG &DAG) { 5066 SDLoc DL(N); 5067 5068 // This function is only supposed to be called for i64 type destination. 5069 assert(N->getValueType(0) == MVT::i64 5070 && "ExpandREAD_REGISTER called for non-i64 type result."); 5071 5072 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5073 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5074 N->getOperand(0), 5075 N->getOperand(1)); 5076 5077 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5078 Read.getValue(1))); 5079 Results.push_back(Read.getOperand(0)); 5080 } 5081 5082 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5083 /// When \p DstVT, the destination type of \p BC, is on the vector 5084 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5085 /// it might be possible to combine them, such that everything stays on the 5086 /// vector register bank. 5087 /// \p return The node that would replace \p BT, if the combine 5088 /// is possible. 5089 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5090 SelectionDAG &DAG) { 5091 SDValue Op = BC->getOperand(0); 5092 EVT DstVT = BC->getValueType(0); 5093 5094 // The only vector instruction that can produce a scalar (remember, 5095 // since the bitcast was about to be turned into VMOVDRR, the source 5096 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5097 // Moreover, we can do this combine only if there is one use. 5098 // Finally, if the destination type is not a vector, there is not 5099 // much point on forcing everything on the vector bank. 5100 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5101 !Op.hasOneUse()) 5102 return SDValue(); 5103 5104 // If the index is not constant, we will introduce an additional 5105 // multiply that will stick. 5106 // Give up in that case. 5107 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5108 if (!Index) 5109 return SDValue(); 5110 unsigned DstNumElt = DstVT.getVectorNumElements(); 5111 5112 // Compute the new index. 5113 const APInt &APIntIndex = Index->getAPIntValue(); 5114 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5115 NewIndex *= APIntIndex; 5116 // Check if the new constant index fits into i32. 5117 if (NewIndex.getBitWidth() > 32) 5118 return SDValue(); 5119 5120 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5121 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5122 SDLoc dl(Op); 5123 SDValue ExtractSrc = Op.getOperand(0); 5124 EVT VecVT = EVT::getVectorVT( 5125 *DAG.getContext(), DstVT.getScalarType(), 5126 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5127 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5128 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5129 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5130 } 5131 5132 /// ExpandBITCAST - If the target supports VFP, this function is called to 5133 /// expand a bit convert where either the source or destination type is i64 to 5134 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5135 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5136 /// vectors), since the legalizer won't know what to do with that. 5137 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5138 const ARMSubtarget *Subtarget) { 5139 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5140 SDLoc dl(N); 5141 SDValue Op = N->getOperand(0); 5142 5143 // This function is only supposed to be called for i64 types, either as the 5144 // source or destination of the bit convert. 5145 EVT SrcVT = Op.getValueType(); 5146 EVT DstVT = N->getValueType(0); 5147 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5148 5149 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5150 // FullFP16: half values are passed in S-registers, and we don't 5151 // need any of the bitcast and moves: 5152 // 5153 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5154 // t5: i32 = bitcast t2 5155 // t18: f16 = ARMISD::VMOVhr t5 5156 if (Op.getOpcode() != ISD::CopyFromReg || 5157 Op.getValueType() != MVT::f32) 5158 return SDValue(); 5159 5160 auto Move = N->use_begin(); 5161 if (Move->getOpcode() != ARMISD::VMOVhr) 5162 return SDValue(); 5163 5164 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5165 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5166 DAG.ReplaceAllUsesWith(*Move, &Copy); 5167 return Copy; 5168 } 5169 5170 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5171 if (!HasFullFP16) 5172 return SDValue(); 5173 // SoftFP: read half-precision arguments: 5174 // 5175 // t2: i32,ch = ... 5176 // t7: i16 = truncate t2 <~~~~ Op 5177 // t8: f16 = bitcast t7 <~~~~ N 5178 // 5179 if (Op.getOperand(0).getValueType() == MVT::i32) 5180 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5181 MVT::f16, Op.getOperand(0)); 5182 5183 return SDValue(); 5184 } 5185 5186 // Half-precision return values 5187 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5188 if (!HasFullFP16) 5189 return SDValue(); 5190 // 5191 // t11: f16 = fadd t8, t10 5192 // t12: i16 = bitcast t11 <~~~ SDNode N 5193 // t13: i32 = zero_extend t12 5194 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5195 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5196 // 5197 // transform this into: 5198 // 5199 // t20: i32 = ARMISD::VMOVrh t11 5200 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5201 // 5202 auto ZeroExtend = N->use_begin(); 5203 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5204 ZeroExtend->getValueType(0) != MVT::i32) 5205 return SDValue(); 5206 5207 auto Copy = ZeroExtend->use_begin(); 5208 if (Copy->getOpcode() == ISD::CopyToReg && 5209 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5210 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5211 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5212 return Cvt; 5213 } 5214 return SDValue(); 5215 } 5216 5217 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5218 return SDValue(); 5219 5220 // Turn i64->f64 into VMOVDRR. 5221 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5222 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5223 // if we can combine the bitcast with its source. 5224 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5225 return Val; 5226 5227 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5228 DAG.getConstant(0, dl, MVT::i32)); 5229 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5230 DAG.getConstant(1, dl, MVT::i32)); 5231 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5232 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5233 } 5234 5235 // Turn f64->i64 into VMOVRRD. 5236 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5237 SDValue Cvt; 5238 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5239 SrcVT.getVectorNumElements() > 1) 5240 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5241 DAG.getVTList(MVT::i32, MVT::i32), 5242 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5243 else 5244 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5245 DAG.getVTList(MVT::i32, MVT::i32), Op); 5246 // Merge the pieces into a single i64 value. 5247 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5248 } 5249 5250 return SDValue(); 5251 } 5252 5253 /// getZeroVector - Returns a vector of specified type with all zero elements. 5254 /// Zero vectors are used to represent vector negation and in those cases 5255 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5256 /// not support i64 elements, so sometimes the zero vectors will need to be 5257 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5258 /// zero vector. 5259 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5260 assert(VT.isVector() && "Expected a vector type"); 5261 // The canonical modified immediate encoding of a zero vector is....0! 5262 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5263 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5264 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5265 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5266 } 5267 5268 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5269 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5270 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5271 SelectionDAG &DAG) const { 5272 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5273 EVT VT = Op.getValueType(); 5274 unsigned VTBits = VT.getSizeInBits(); 5275 SDLoc dl(Op); 5276 SDValue ShOpLo = Op.getOperand(0); 5277 SDValue ShOpHi = Op.getOperand(1); 5278 SDValue ShAmt = Op.getOperand(2); 5279 SDValue ARMcc; 5280 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5281 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5282 5283 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5284 5285 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5286 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5287 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5288 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5289 DAG.getConstant(VTBits, dl, MVT::i32)); 5290 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5291 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5292 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5293 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5294 ISD::SETGE, ARMcc, DAG, dl); 5295 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5296 ARMcc, CCR, CmpLo); 5297 5298 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5299 SDValue HiBigShift = Opc == ISD::SRA 5300 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5301 DAG.getConstant(VTBits - 1, dl, VT)) 5302 : DAG.getConstant(0, dl, VT); 5303 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5304 ISD::SETGE, ARMcc, DAG, dl); 5305 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5306 ARMcc, CCR, CmpHi); 5307 5308 SDValue Ops[2] = { Lo, Hi }; 5309 return DAG.getMergeValues(Ops, dl); 5310 } 5311 5312 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5313 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5314 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5315 SelectionDAG &DAG) const { 5316 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5317 EVT VT = Op.getValueType(); 5318 unsigned VTBits = VT.getSizeInBits(); 5319 SDLoc dl(Op); 5320 SDValue ShOpLo = Op.getOperand(0); 5321 SDValue ShOpHi = Op.getOperand(1); 5322 SDValue ShAmt = Op.getOperand(2); 5323 SDValue ARMcc; 5324 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5325 5326 assert(Op.getOpcode() == ISD::SHL_PARTS); 5327 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5328 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5329 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5330 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5331 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5332 5333 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5334 DAG.getConstant(VTBits, dl, MVT::i32)); 5335 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5336 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5337 ISD::SETGE, ARMcc, DAG, dl); 5338 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5339 ARMcc, CCR, CmpHi); 5340 5341 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5342 ISD::SETGE, ARMcc, DAG, dl); 5343 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5344 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5345 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5346 5347 SDValue Ops[2] = { Lo, Hi }; 5348 return DAG.getMergeValues(Ops, dl); 5349 } 5350 5351 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5352 SelectionDAG &DAG) const { 5353 // The rounding mode is in bits 23:22 of the FPSCR. 5354 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5355 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5356 // so that the shift + and get folded into a bitfield extract. 5357 SDLoc dl(Op); 5358 SDValue Ops[] = { DAG.getEntryNode(), 5359 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5360 5361 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5362 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5363 DAG.getConstant(1U << 22, dl, MVT::i32)); 5364 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5365 DAG.getConstant(22, dl, MVT::i32)); 5366 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5367 DAG.getConstant(3, dl, MVT::i32)); 5368 } 5369 5370 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5371 const ARMSubtarget *ST) { 5372 SDLoc dl(N); 5373 EVT VT = N->getValueType(0); 5374 if (VT.isVector()) { 5375 assert(ST->hasNEON()); 5376 5377 // Compute the least significant set bit: LSB = X & -X 5378 SDValue X = N->getOperand(0); 5379 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5380 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5381 5382 EVT ElemTy = VT.getVectorElementType(); 5383 5384 if (ElemTy == MVT::i8) { 5385 // Compute with: cttz(x) = ctpop(lsb - 1) 5386 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5387 DAG.getTargetConstant(1, dl, ElemTy)); 5388 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5389 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5390 } 5391 5392 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5393 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5394 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5395 unsigned NumBits = ElemTy.getSizeInBits(); 5396 SDValue WidthMinus1 = 5397 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5398 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5399 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5400 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5401 } 5402 5403 // Compute with: cttz(x) = ctpop(lsb - 1) 5404 5405 // Since we can only compute the number of bits in a byte with vcnt.8, we 5406 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 5407 // and i64. 5408 5409 // Compute LSB - 1. 5410 SDValue Bits; 5411 if (ElemTy == MVT::i64) { 5412 // Load constant 0xffff'ffff'ffff'ffff to register. 5413 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5414 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5415 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5416 } else { 5417 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5418 DAG.getTargetConstant(1, dl, ElemTy)); 5419 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5420 } 5421 5422 // Count #bits with vcnt.8. 5423 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5424 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5425 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5426 5427 // Gather the #bits with vpaddl (pairwise add.) 5428 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5429 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5430 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5431 Cnt8); 5432 if (ElemTy == MVT::i16) 5433 return Cnt16; 5434 5435 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5436 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5437 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5438 Cnt16); 5439 if (ElemTy == MVT::i32) 5440 return Cnt32; 5441 5442 assert(ElemTy == MVT::i64); 5443 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5444 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5445 Cnt32); 5446 return Cnt64; 5447 } 5448 5449 if (!ST->hasV6T2Ops()) 5450 return SDValue(); 5451 5452 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5453 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5454 } 5455 5456 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5457 /// for each 16-bit element from operand, repeated. The basic idea is to 5458 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5459 /// 5460 /// Trace for v4i16: 5461 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5462 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5463 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5464 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5465 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5466 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5467 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5468 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5469 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5470 EVT VT = N->getValueType(0); 5471 SDLoc DL(N); 5472 5473 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5474 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5475 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5476 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5477 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5478 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5479 } 5480 5481 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5482 /// bit-count for each 16-bit element from the operand. We need slightly 5483 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5484 /// 64/128-bit registers. 5485 /// 5486 /// Trace for v4i16: 5487 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5488 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5489 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5490 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5491 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5492 EVT VT = N->getValueType(0); 5493 SDLoc DL(N); 5494 5495 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5496 if (VT.is64BitVector()) { 5497 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5498 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5499 DAG.getIntPtrConstant(0, DL)); 5500 } else { 5501 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5502 BitCounts, DAG.getIntPtrConstant(0, DL)); 5503 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5504 } 5505 } 5506 5507 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5508 /// bit-count for each 32-bit element from the operand. The idea here is 5509 /// to split the vector into 16-bit elements, leverage the 16-bit count 5510 /// routine, and then combine the results. 5511 /// 5512 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5513 /// input = [v0 v1 ] (vi: 32-bit elements) 5514 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5515 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5516 /// vrev: N0 = [k1 k0 k3 k2 ] 5517 /// [k0 k1 k2 k3 ] 5518 /// N1 =+[k1 k0 k3 k2 ] 5519 /// [k0 k2 k1 k3 ] 5520 /// N2 =+[k1 k3 k0 k2 ] 5521 /// [k0 k2 k1 k3 ] 5522 /// Extended =+[k1 k3 k0 k2 ] 5523 /// [k0 k2 ] 5524 /// Extracted=+[k1 k3 ] 5525 /// 5526 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5527 EVT VT = N->getValueType(0); 5528 SDLoc DL(N); 5529 5530 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5531 5532 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5533 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5534 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5535 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5536 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5537 5538 if (VT.is64BitVector()) { 5539 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5540 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5541 DAG.getIntPtrConstant(0, DL)); 5542 } else { 5543 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5544 DAG.getIntPtrConstant(0, DL)); 5545 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5546 } 5547 } 5548 5549 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5550 const ARMSubtarget *ST) { 5551 EVT VT = N->getValueType(0); 5552 5553 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5554 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5555 VT == MVT::v4i16 || VT == MVT::v8i16) && 5556 "Unexpected type for custom ctpop lowering"); 5557 5558 if (VT.getVectorElementType() == MVT::i32) 5559 return lowerCTPOP32BitElements(N, DAG); 5560 else 5561 return lowerCTPOP16BitElements(N, DAG); 5562 } 5563 5564 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5565 const ARMSubtarget *ST) { 5566 EVT VT = N->getValueType(0); 5567 SDLoc dl(N); 5568 5569 if (!VT.isVector()) 5570 return SDValue(); 5571 5572 // Lower vector shifts on NEON to use VSHL. 5573 assert(ST->hasNEON() && "unexpected vector shift"); 5574 5575 // Left shifts translate directly to the vshiftu intrinsic. 5576 if (N->getOpcode() == ISD::SHL) 5577 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5578 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5579 MVT::i32), 5580 N->getOperand(0), N->getOperand(1)); 5581 5582 assert((N->getOpcode() == ISD::SRA || 5583 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5584 5585 // NEON uses the same intrinsics for both left and right shifts. For 5586 // right shifts, the shift amounts are negative, so negate the vector of 5587 // shift amounts. 5588 EVT ShiftVT = N->getOperand(1).getValueType(); 5589 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5590 getZeroVector(ShiftVT, DAG, dl), 5591 N->getOperand(1)); 5592 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5593 Intrinsic::arm_neon_vshifts : 5594 Intrinsic::arm_neon_vshiftu); 5595 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5596 DAG.getConstant(vshiftInt, dl, MVT::i32), 5597 N->getOperand(0), NegatedCount); 5598 } 5599 5600 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5601 const ARMSubtarget *ST) { 5602 EVT VT = N->getValueType(0); 5603 SDLoc dl(N); 5604 5605 // We can get here for a node like i32 = ISD::SHL i32, i64 5606 if (VT != MVT::i64) 5607 return SDValue(); 5608 5609 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5610 "Unknown shift to lower!"); 5611 5612 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5613 if (!isOneConstant(N->getOperand(1))) 5614 return SDValue(); 5615 5616 // If we are in thumb mode, we don't have RRX. 5617 if (ST->isThumb1Only()) return SDValue(); 5618 5619 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5620 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5621 DAG.getConstant(0, dl, MVT::i32)); 5622 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5623 DAG.getConstant(1, dl, MVT::i32)); 5624 5625 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5626 // captures the result into a carry flag. 5627 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5628 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5629 5630 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5631 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5632 5633 // Merge the pieces into a single i64 value. 5634 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5635 } 5636 5637 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5638 SDValue TmpOp0, TmpOp1; 5639 bool Invert = false; 5640 bool Swap = false; 5641 unsigned Opc = 0; 5642 5643 SDValue Op0 = Op.getOperand(0); 5644 SDValue Op1 = Op.getOperand(1); 5645 SDValue CC = Op.getOperand(2); 5646 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5647 EVT VT = Op.getValueType(); 5648 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5649 SDLoc dl(Op); 5650 5651 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5652 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5653 // Special-case integer 64-bit equality comparisons. They aren't legal, 5654 // but they can be lowered with a few vector instructions. 5655 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5656 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5657 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5658 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5659 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5660 DAG.getCondCode(ISD::SETEQ)); 5661 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5662 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5663 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5664 if (SetCCOpcode == ISD::SETNE) 5665 Merged = DAG.getNOT(dl, Merged, CmpVT); 5666 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5667 return Merged; 5668 } 5669 5670 if (CmpVT.getVectorElementType() == MVT::i64) 5671 // 64-bit comparisons are not legal in general. 5672 return SDValue(); 5673 5674 if (Op1.getValueType().isFloatingPoint()) { 5675 switch (SetCCOpcode) { 5676 default: llvm_unreachable("Illegal FP comparison"); 5677 case ISD::SETUNE: 5678 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5679 case ISD::SETOEQ: 5680 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5681 case ISD::SETOLT: 5682 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5683 case ISD::SETOGT: 5684 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5685 case ISD::SETOLE: 5686 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5687 case ISD::SETOGE: 5688 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5689 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5690 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5691 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5692 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5693 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5694 case ISD::SETONE: 5695 // Expand this to (OLT | OGT). 5696 TmpOp0 = Op0; 5697 TmpOp1 = Op1; 5698 Opc = ISD::OR; 5699 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5700 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5701 break; 5702 case ISD::SETUO: 5703 Invert = true; 5704 LLVM_FALLTHROUGH; 5705 case ISD::SETO: 5706 // Expand this to (OLT | OGE). 5707 TmpOp0 = Op0; 5708 TmpOp1 = Op1; 5709 Opc = ISD::OR; 5710 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5711 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5712 break; 5713 } 5714 } else { 5715 // Integer comparisons. 5716 switch (SetCCOpcode) { 5717 default: llvm_unreachable("Illegal integer comparison"); 5718 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5719 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5720 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5721 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5722 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5723 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5724 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5725 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5726 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5727 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5728 } 5729 5730 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5731 if (Opc == ARMISD::VCEQ) { 5732 SDValue AndOp; 5733 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5734 AndOp = Op0; 5735 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5736 AndOp = Op1; 5737 5738 // Ignore bitconvert. 5739 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5740 AndOp = AndOp.getOperand(0); 5741 5742 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5743 Opc = ARMISD::VTST; 5744 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5745 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5746 Invert = !Invert; 5747 } 5748 } 5749 } 5750 5751 if (Swap) 5752 std::swap(Op0, Op1); 5753 5754 // If one of the operands is a constant vector zero, attempt to fold the 5755 // comparison to a specialized compare-against-zero form. 5756 SDValue SingleOp; 5757 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5758 SingleOp = Op0; 5759 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5760 if (Opc == ARMISD::VCGE) 5761 Opc = ARMISD::VCLEZ; 5762 else if (Opc == ARMISD::VCGT) 5763 Opc = ARMISD::VCLTZ; 5764 SingleOp = Op1; 5765 } 5766 5767 SDValue Result; 5768 if (SingleOp.getNode()) { 5769 switch (Opc) { 5770 case ARMISD::VCEQ: 5771 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5772 case ARMISD::VCGE: 5773 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5774 case ARMISD::VCLEZ: 5775 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5776 case ARMISD::VCGT: 5777 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5778 case ARMISD::VCLTZ: 5779 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5780 default: 5781 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5782 } 5783 } else { 5784 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5785 } 5786 5787 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5788 5789 if (Invert) 5790 Result = DAG.getNOT(dl, Result, VT); 5791 5792 return Result; 5793 } 5794 5795 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 5796 SDValue LHS = Op.getOperand(0); 5797 SDValue RHS = Op.getOperand(1); 5798 SDValue Carry = Op.getOperand(2); 5799 SDValue Cond = Op.getOperand(3); 5800 SDLoc DL(Op); 5801 5802 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 5803 5804 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 5805 // have to invert the carry first. 5806 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 5807 DAG.getConstant(1, DL, MVT::i32), Carry); 5808 // This converts the boolean value carry into the carry flag. 5809 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 5810 5811 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5812 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5813 5814 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5815 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5816 SDValue ARMcc = DAG.getConstant( 5817 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5818 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5819 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5820 Cmp.getValue(1), SDValue()); 5821 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5822 CCR, Chain.getValue(1)); 5823 } 5824 5825 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5826 /// valid vector constant for a NEON instruction with a "modified immediate" 5827 /// operand (e.g., VMOV). If so, return the encoded value. 5828 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5829 unsigned SplatBitSize, SelectionDAG &DAG, 5830 const SDLoc &dl, EVT &VT, bool is128Bits, 5831 NEONModImmType type) { 5832 unsigned OpCmode, Imm; 5833 5834 // SplatBitSize is set to the smallest size that splats the vector, so a 5835 // zero vector will always have SplatBitSize == 8. However, NEON modified 5836 // immediate instructions others than VMOV do not support the 8-bit encoding 5837 // of a zero vector, and the default encoding of zero is supposed to be the 5838 // 32-bit version. 5839 if (SplatBits == 0) 5840 SplatBitSize = 32; 5841 5842 switch (SplatBitSize) { 5843 case 8: 5844 if (type != VMOVModImm) 5845 return SDValue(); 5846 // Any 1-byte value is OK. Op=0, Cmode=1110. 5847 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5848 OpCmode = 0xe; 5849 Imm = SplatBits; 5850 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5851 break; 5852 5853 case 16: 5854 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5855 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5856 if ((SplatBits & ~0xff) == 0) { 5857 // Value = 0x00nn: Op=x, Cmode=100x. 5858 OpCmode = 0x8; 5859 Imm = SplatBits; 5860 break; 5861 } 5862 if ((SplatBits & ~0xff00) == 0) { 5863 // Value = 0xnn00: Op=x, Cmode=101x. 5864 OpCmode = 0xa; 5865 Imm = SplatBits >> 8; 5866 break; 5867 } 5868 return SDValue(); 5869 5870 case 32: 5871 // NEON's 32-bit VMOV supports splat values where: 5872 // * only one byte is nonzero, or 5873 // * the least significant byte is 0xff and the second byte is nonzero, or 5874 // * the least significant 2 bytes are 0xff and the third is nonzero. 5875 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5876 if ((SplatBits & ~0xff) == 0) { 5877 // Value = 0x000000nn: Op=x, Cmode=000x. 5878 OpCmode = 0; 5879 Imm = SplatBits; 5880 break; 5881 } 5882 if ((SplatBits & ~0xff00) == 0) { 5883 // Value = 0x0000nn00: Op=x, Cmode=001x. 5884 OpCmode = 0x2; 5885 Imm = SplatBits >> 8; 5886 break; 5887 } 5888 if ((SplatBits & ~0xff0000) == 0) { 5889 // Value = 0x00nn0000: Op=x, Cmode=010x. 5890 OpCmode = 0x4; 5891 Imm = SplatBits >> 16; 5892 break; 5893 } 5894 if ((SplatBits & ~0xff000000) == 0) { 5895 // Value = 0xnn000000: Op=x, Cmode=011x. 5896 OpCmode = 0x6; 5897 Imm = SplatBits >> 24; 5898 break; 5899 } 5900 5901 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5902 if (type == OtherModImm) return SDValue(); 5903 5904 if ((SplatBits & ~0xffff) == 0 && 5905 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5906 // Value = 0x0000nnff: Op=x, Cmode=1100. 5907 OpCmode = 0xc; 5908 Imm = SplatBits >> 8; 5909 break; 5910 } 5911 5912 if ((SplatBits & ~0xffffff) == 0 && 5913 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5914 // Value = 0x00nnffff: Op=x, Cmode=1101. 5915 OpCmode = 0xd; 5916 Imm = SplatBits >> 16; 5917 break; 5918 } 5919 5920 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5921 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5922 // VMOV.I32. A (very) minor optimization would be to replicate the value 5923 // and fall through here to test for a valid 64-bit splat. But, then the 5924 // caller would also need to check and handle the change in size. 5925 return SDValue(); 5926 5927 case 64: { 5928 if (type != VMOVModImm) 5929 return SDValue(); 5930 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5931 uint64_t BitMask = 0xff; 5932 uint64_t Val = 0; 5933 unsigned ImmMask = 1; 5934 Imm = 0; 5935 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5936 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5937 Val |= BitMask; 5938 Imm |= ImmMask; 5939 } else if ((SplatBits & BitMask) != 0) { 5940 return SDValue(); 5941 } 5942 BitMask <<= 8; 5943 ImmMask <<= 1; 5944 } 5945 5946 if (DAG.getDataLayout().isBigEndian()) 5947 // swap higher and lower 32 bit word 5948 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5949 5950 // Op=1, Cmode=1110. 5951 OpCmode = 0x1e; 5952 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5953 break; 5954 } 5955 5956 default: 5957 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5958 } 5959 5960 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5961 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5962 } 5963 5964 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5965 const ARMSubtarget *ST) const { 5966 EVT VT = Op.getValueType(); 5967 bool IsDouble = (VT == MVT::f64); 5968 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5969 const APFloat &FPVal = CFP->getValueAPF(); 5970 5971 // Prevent floating-point constants from using literal loads 5972 // when execute-only is enabled. 5973 if (ST->genExecuteOnly()) { 5974 // If we can represent the constant as an immediate, don't lower it 5975 if (isFPImmLegal(FPVal, VT)) 5976 return Op; 5977 // Otherwise, construct as integer, and move to float register 5978 APInt INTVal = FPVal.bitcastToAPInt(); 5979 SDLoc DL(CFP); 5980 switch (VT.getSimpleVT().SimpleTy) { 5981 default: 5982 llvm_unreachable("Unknown floating point type!"); 5983 break; 5984 case MVT::f64: { 5985 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5986 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5987 if (!ST->isLittle()) 5988 std::swap(Lo, Hi); 5989 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5990 } 5991 case MVT::f32: 5992 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 5993 DAG.getConstant(INTVal, DL, MVT::i32)); 5994 } 5995 } 5996 5997 if (!ST->hasVFP3()) 5998 return SDValue(); 5999 6000 // Use the default (constant pool) lowering for double constants when we have 6001 // an SP-only FPU 6002 if (IsDouble && Subtarget->isFPOnlySP()) 6003 return SDValue(); 6004 6005 // Try splatting with a VMOV.f32... 6006 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6007 6008 if (ImmVal != -1) { 6009 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6010 // We have code in place to select a valid ConstantFP already, no need to 6011 // do any mangling. 6012 return Op; 6013 } 6014 6015 // It's a float and we are trying to use NEON operations where 6016 // possible. Lower it to a splat followed by an extract. 6017 SDLoc DL(Op); 6018 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6019 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6020 NewVal); 6021 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6022 DAG.getConstant(0, DL, MVT::i32)); 6023 } 6024 6025 // The rest of our options are NEON only, make sure that's allowed before 6026 // proceeding.. 6027 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6028 return SDValue(); 6029 6030 EVT VMovVT; 6031 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6032 6033 // It wouldn't really be worth bothering for doubles except for one very 6034 // important value, which does happen to match: 0.0. So make sure we don't do 6035 // anything stupid. 6036 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6037 return SDValue(); 6038 6039 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6040 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6041 VMovVT, false, VMOVModImm); 6042 if (NewVal != SDValue()) { 6043 SDLoc DL(Op); 6044 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6045 NewVal); 6046 if (IsDouble) 6047 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6048 6049 // It's a float: cast and extract a vector element. 6050 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6051 VecConstant); 6052 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6053 DAG.getConstant(0, DL, MVT::i32)); 6054 } 6055 6056 // Finally, try a VMVN.i32 6057 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6058 false, VMVNModImm); 6059 if (NewVal != SDValue()) { 6060 SDLoc DL(Op); 6061 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6062 6063 if (IsDouble) 6064 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6065 6066 // It's a float: cast and extract a vector element. 6067 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6068 VecConstant); 6069 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6070 DAG.getConstant(0, DL, MVT::i32)); 6071 } 6072 6073 return SDValue(); 6074 } 6075 6076 // check if an VEXT instruction can handle the shuffle mask when the 6077 // vector sources of the shuffle are the same. 6078 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6079 unsigned NumElts = VT.getVectorNumElements(); 6080 6081 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6082 if (M[0] < 0) 6083 return false; 6084 6085 Imm = M[0]; 6086 6087 // If this is a VEXT shuffle, the immediate value is the index of the first 6088 // element. The other shuffle indices must be the successive elements after 6089 // the first one. 6090 unsigned ExpectedElt = Imm; 6091 for (unsigned i = 1; i < NumElts; ++i) { 6092 // Increment the expected index. If it wraps around, just follow it 6093 // back to index zero and keep going. 6094 ++ExpectedElt; 6095 if (ExpectedElt == NumElts) 6096 ExpectedElt = 0; 6097 6098 if (M[i] < 0) continue; // ignore UNDEF indices 6099 if (ExpectedElt != static_cast<unsigned>(M[i])) 6100 return false; 6101 } 6102 6103 return true; 6104 } 6105 6106 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6107 bool &ReverseVEXT, unsigned &Imm) { 6108 unsigned NumElts = VT.getVectorNumElements(); 6109 ReverseVEXT = false; 6110 6111 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6112 if (M[0] < 0) 6113 return false; 6114 6115 Imm = M[0]; 6116 6117 // If this is a VEXT shuffle, the immediate value is the index of the first 6118 // element. The other shuffle indices must be the successive elements after 6119 // the first one. 6120 unsigned ExpectedElt = Imm; 6121 for (unsigned i = 1; i < NumElts; ++i) { 6122 // Increment the expected index. If it wraps around, it may still be 6123 // a VEXT but the source vectors must be swapped. 6124 ExpectedElt += 1; 6125 if (ExpectedElt == NumElts * 2) { 6126 ExpectedElt = 0; 6127 ReverseVEXT = true; 6128 } 6129 6130 if (M[i] < 0) continue; // ignore UNDEF indices 6131 if (ExpectedElt != static_cast<unsigned>(M[i])) 6132 return false; 6133 } 6134 6135 // Adjust the index value if the source operands will be swapped. 6136 if (ReverseVEXT) 6137 Imm -= NumElts; 6138 6139 return true; 6140 } 6141 6142 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6143 /// instruction with the specified blocksize. (The order of the elements 6144 /// within each block of the vector is reversed.) 6145 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6146 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6147 "Only possible block sizes for VREV are: 16, 32, 64"); 6148 6149 unsigned EltSz = VT.getScalarSizeInBits(); 6150 if (EltSz == 64) 6151 return false; 6152 6153 unsigned NumElts = VT.getVectorNumElements(); 6154 unsigned BlockElts = M[0] + 1; 6155 // If the first shuffle index is UNDEF, be optimistic. 6156 if (M[0] < 0) 6157 BlockElts = BlockSize / EltSz; 6158 6159 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6160 return false; 6161 6162 for (unsigned i = 0; i < NumElts; ++i) { 6163 if (M[i] < 0) continue; // ignore UNDEF indices 6164 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6165 return false; 6166 } 6167 6168 return true; 6169 } 6170 6171 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6172 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6173 // range, then 0 is placed into the resulting vector. So pretty much any mask 6174 // of 8 elements can work here. 6175 return VT == MVT::v8i8 && M.size() == 8; 6176 } 6177 6178 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6179 unsigned Index) { 6180 if (Mask.size() == Elements * 2) 6181 return Index / Elements; 6182 return Mask[Index] == 0 ? 0 : 1; 6183 } 6184 6185 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6186 // checking that pairs of elements in the shuffle mask represent the same index 6187 // in each vector, incrementing the expected index by 2 at each step. 6188 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6189 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6190 // v2={e,f,g,h} 6191 // WhichResult gives the offset for each element in the mask based on which 6192 // of the two results it belongs to. 6193 // 6194 // The transpose can be represented either as: 6195 // result1 = shufflevector v1, v2, result1_shuffle_mask 6196 // result2 = shufflevector v1, v2, result2_shuffle_mask 6197 // where v1/v2 and the shuffle masks have the same number of elements 6198 // (here WhichResult (see below) indicates which result is being checked) 6199 // 6200 // or as: 6201 // results = shufflevector v1, v2, shuffle_mask 6202 // where both results are returned in one vector and the shuffle mask has twice 6203 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6204 // want to check the low half and high half of the shuffle mask as if it were 6205 // the other case 6206 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6207 unsigned EltSz = VT.getScalarSizeInBits(); 6208 if (EltSz == 64) 6209 return false; 6210 6211 unsigned NumElts = VT.getVectorNumElements(); 6212 if (M.size() != NumElts && M.size() != NumElts*2) 6213 return false; 6214 6215 // If the mask is twice as long as the input vector then we need to check the 6216 // upper and lower parts of the mask with a matching value for WhichResult 6217 // FIXME: A mask with only even values will be rejected in case the first 6218 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6219 // M[0] is used to determine WhichResult 6220 for (unsigned i = 0; i < M.size(); i += NumElts) { 6221 WhichResult = SelectPairHalf(NumElts, M, i); 6222 for (unsigned j = 0; j < NumElts; j += 2) { 6223 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6224 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6225 return false; 6226 } 6227 } 6228 6229 if (M.size() == NumElts*2) 6230 WhichResult = 0; 6231 6232 return true; 6233 } 6234 6235 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6236 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6237 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6238 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6239 unsigned EltSz = VT.getScalarSizeInBits(); 6240 if (EltSz == 64) 6241 return false; 6242 6243 unsigned NumElts = VT.getVectorNumElements(); 6244 if (M.size() != NumElts && M.size() != NumElts*2) 6245 return false; 6246 6247 for (unsigned i = 0; i < M.size(); i += NumElts) { 6248 WhichResult = SelectPairHalf(NumElts, M, i); 6249 for (unsigned j = 0; j < NumElts; j += 2) { 6250 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6251 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6252 return false; 6253 } 6254 } 6255 6256 if (M.size() == NumElts*2) 6257 WhichResult = 0; 6258 6259 return true; 6260 } 6261 6262 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6263 // that the mask elements are either all even and in steps of size 2 or all odd 6264 // and in steps of size 2. 6265 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6266 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6267 // v2={e,f,g,h} 6268 // Requires similar checks to that of isVTRNMask with 6269 // respect the how results are returned. 6270 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6271 unsigned EltSz = VT.getScalarSizeInBits(); 6272 if (EltSz == 64) 6273 return false; 6274 6275 unsigned NumElts = VT.getVectorNumElements(); 6276 if (M.size() != NumElts && M.size() != NumElts*2) 6277 return false; 6278 6279 for (unsigned i = 0; i < M.size(); i += NumElts) { 6280 WhichResult = SelectPairHalf(NumElts, M, i); 6281 for (unsigned j = 0; j < NumElts; ++j) { 6282 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6283 return false; 6284 } 6285 } 6286 6287 if (M.size() == NumElts*2) 6288 WhichResult = 0; 6289 6290 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6291 if (VT.is64BitVector() && EltSz == 32) 6292 return false; 6293 6294 return true; 6295 } 6296 6297 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6298 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6299 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6300 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6301 unsigned EltSz = VT.getScalarSizeInBits(); 6302 if (EltSz == 64) 6303 return false; 6304 6305 unsigned NumElts = VT.getVectorNumElements(); 6306 if (M.size() != NumElts && M.size() != NumElts*2) 6307 return false; 6308 6309 unsigned Half = NumElts / 2; 6310 for (unsigned i = 0; i < M.size(); i += NumElts) { 6311 WhichResult = SelectPairHalf(NumElts, M, i); 6312 for (unsigned j = 0; j < NumElts; j += Half) { 6313 unsigned Idx = WhichResult; 6314 for (unsigned k = 0; k < Half; ++k) { 6315 int MIdx = M[i + j + k]; 6316 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6317 return false; 6318 Idx += 2; 6319 } 6320 } 6321 } 6322 6323 if (M.size() == NumElts*2) 6324 WhichResult = 0; 6325 6326 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6327 if (VT.is64BitVector() && EltSz == 32) 6328 return false; 6329 6330 return true; 6331 } 6332 6333 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6334 // that pairs of elements of the shufflemask represent the same index in each 6335 // vector incrementing sequentially through the vectors. 6336 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6337 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6338 // v2={e,f,g,h} 6339 // Requires similar checks to that of isVTRNMask with respect the how results 6340 // are returned. 6341 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6342 unsigned EltSz = VT.getScalarSizeInBits(); 6343 if (EltSz == 64) 6344 return false; 6345 6346 unsigned NumElts = VT.getVectorNumElements(); 6347 if (M.size() != NumElts && M.size() != NumElts*2) 6348 return false; 6349 6350 for (unsigned i = 0; i < M.size(); i += NumElts) { 6351 WhichResult = SelectPairHalf(NumElts, M, i); 6352 unsigned Idx = WhichResult * NumElts / 2; 6353 for (unsigned j = 0; j < NumElts; j += 2) { 6354 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6355 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6356 return false; 6357 Idx += 1; 6358 } 6359 } 6360 6361 if (M.size() == NumElts*2) 6362 WhichResult = 0; 6363 6364 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6365 if (VT.is64BitVector() && EltSz == 32) 6366 return false; 6367 6368 return true; 6369 } 6370 6371 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6372 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6373 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6374 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6375 unsigned EltSz = VT.getScalarSizeInBits(); 6376 if (EltSz == 64) 6377 return false; 6378 6379 unsigned NumElts = VT.getVectorNumElements(); 6380 if (M.size() != NumElts && M.size() != NumElts*2) 6381 return false; 6382 6383 for (unsigned i = 0; i < M.size(); i += NumElts) { 6384 WhichResult = SelectPairHalf(NumElts, M, i); 6385 unsigned Idx = WhichResult * NumElts / 2; 6386 for (unsigned j = 0; j < NumElts; j += 2) { 6387 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6388 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6389 return false; 6390 Idx += 1; 6391 } 6392 } 6393 6394 if (M.size() == NumElts*2) 6395 WhichResult = 0; 6396 6397 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6398 if (VT.is64BitVector() && EltSz == 32) 6399 return false; 6400 6401 return true; 6402 } 6403 6404 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6405 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6406 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6407 unsigned &WhichResult, 6408 bool &isV_UNDEF) { 6409 isV_UNDEF = false; 6410 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6411 return ARMISD::VTRN; 6412 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6413 return ARMISD::VUZP; 6414 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6415 return ARMISD::VZIP; 6416 6417 isV_UNDEF = true; 6418 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6419 return ARMISD::VTRN; 6420 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6421 return ARMISD::VUZP; 6422 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6423 return ARMISD::VZIP; 6424 6425 return 0; 6426 } 6427 6428 /// \return true if this is a reverse operation on an vector. 6429 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6430 unsigned NumElts = VT.getVectorNumElements(); 6431 // Make sure the mask has the right size. 6432 if (NumElts != M.size()) 6433 return false; 6434 6435 // Look for <15, ..., 3, -1, 1, 0>. 6436 for (unsigned i = 0; i != NumElts; ++i) 6437 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6438 return false; 6439 6440 return true; 6441 } 6442 6443 // If N is an integer constant that can be moved into a register in one 6444 // instruction, return an SDValue of such a constant (will become a MOV 6445 // instruction). Otherwise return null. 6446 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6447 const ARMSubtarget *ST, const SDLoc &dl) { 6448 uint64_t Val; 6449 if (!isa<ConstantSDNode>(N)) 6450 return SDValue(); 6451 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6452 6453 if (ST->isThumb1Only()) { 6454 if (Val <= 255 || ~Val <= 255) 6455 return DAG.getConstant(Val, dl, MVT::i32); 6456 } else { 6457 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6458 return DAG.getConstant(Val, dl, MVT::i32); 6459 } 6460 return SDValue(); 6461 } 6462 6463 // If this is a case we can't handle, return null and let the default 6464 // expansion code take care of it. 6465 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6466 const ARMSubtarget *ST) const { 6467 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6468 SDLoc dl(Op); 6469 EVT VT = Op.getValueType(); 6470 6471 APInt SplatBits, SplatUndef; 6472 unsigned SplatBitSize; 6473 bool HasAnyUndefs; 6474 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6475 if (SplatUndef.isAllOnesValue()) 6476 return DAG.getUNDEF(VT); 6477 6478 if (SplatBitSize <= 64) { 6479 // Check if an immediate VMOV works. 6480 EVT VmovVT; 6481 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6482 SplatUndef.getZExtValue(), SplatBitSize, 6483 DAG, dl, VmovVT, VT.is128BitVector(), 6484 VMOVModImm); 6485 if (Val.getNode()) { 6486 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6487 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6488 } 6489 6490 // Try an immediate VMVN. 6491 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6492 Val = isNEONModifiedImm(NegatedImm, 6493 SplatUndef.getZExtValue(), SplatBitSize, 6494 DAG, dl, VmovVT, VT.is128BitVector(), 6495 VMVNModImm); 6496 if (Val.getNode()) { 6497 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6498 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6499 } 6500 6501 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6502 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6503 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6504 if (ImmVal != -1) { 6505 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6506 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6507 } 6508 } 6509 } 6510 } 6511 6512 // Scan through the operands to see if only one value is used. 6513 // 6514 // As an optimisation, even if more than one value is used it may be more 6515 // profitable to splat with one value then change some lanes. 6516 // 6517 // Heuristically we decide to do this if the vector has a "dominant" value, 6518 // defined as splatted to more than half of the lanes. 6519 unsigned NumElts = VT.getVectorNumElements(); 6520 bool isOnlyLowElement = true; 6521 bool usesOnlyOneValue = true; 6522 bool hasDominantValue = false; 6523 bool isConstant = true; 6524 6525 // Map of the number of times a particular SDValue appears in the 6526 // element list. 6527 DenseMap<SDValue, unsigned> ValueCounts; 6528 SDValue Value; 6529 for (unsigned i = 0; i < NumElts; ++i) { 6530 SDValue V = Op.getOperand(i); 6531 if (V.isUndef()) 6532 continue; 6533 if (i > 0) 6534 isOnlyLowElement = false; 6535 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6536 isConstant = false; 6537 6538 ValueCounts.insert(std::make_pair(V, 0)); 6539 unsigned &Count = ValueCounts[V]; 6540 6541 // Is this value dominant? (takes up more than half of the lanes) 6542 if (++Count > (NumElts / 2)) { 6543 hasDominantValue = true; 6544 Value = V; 6545 } 6546 } 6547 if (ValueCounts.size() != 1) 6548 usesOnlyOneValue = false; 6549 if (!Value.getNode() && !ValueCounts.empty()) 6550 Value = ValueCounts.begin()->first; 6551 6552 if (ValueCounts.empty()) 6553 return DAG.getUNDEF(VT); 6554 6555 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6556 // Keep going if we are hitting this case. 6557 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6558 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6559 6560 unsigned EltSize = VT.getScalarSizeInBits(); 6561 6562 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6563 // i32 and try again. 6564 if (hasDominantValue && EltSize <= 32) { 6565 if (!isConstant) { 6566 SDValue N; 6567 6568 // If we are VDUPing a value that comes directly from a vector, that will 6569 // cause an unnecessary move to and from a GPR, where instead we could 6570 // just use VDUPLANE. We can only do this if the lane being extracted 6571 // is at a constant index, as the VDUP from lane instructions only have 6572 // constant-index forms. 6573 ConstantSDNode *constIndex; 6574 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6575 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6576 // We need to create a new undef vector to use for the VDUPLANE if the 6577 // size of the vector from which we get the value is different than the 6578 // size of the vector that we need to create. We will insert the element 6579 // such that the register coalescer will remove unnecessary copies. 6580 if (VT != Value->getOperand(0).getValueType()) { 6581 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6582 VT.getVectorNumElements(); 6583 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6584 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6585 Value, DAG.getConstant(index, dl, MVT::i32)), 6586 DAG.getConstant(index, dl, MVT::i32)); 6587 } else 6588 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6589 Value->getOperand(0), Value->getOperand(1)); 6590 } else 6591 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6592 6593 if (!usesOnlyOneValue) { 6594 // The dominant value was splatted as 'N', but we now have to insert 6595 // all differing elements. 6596 for (unsigned I = 0; I < NumElts; ++I) { 6597 if (Op.getOperand(I) == Value) 6598 continue; 6599 SmallVector<SDValue, 3> Ops; 6600 Ops.push_back(N); 6601 Ops.push_back(Op.getOperand(I)); 6602 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6603 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6604 } 6605 } 6606 return N; 6607 } 6608 if (VT.getVectorElementType().isFloatingPoint()) { 6609 SmallVector<SDValue, 8> Ops; 6610 for (unsigned i = 0; i < NumElts; ++i) 6611 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6612 Op.getOperand(i))); 6613 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6614 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6615 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6616 if (Val.getNode()) 6617 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6618 } 6619 if (usesOnlyOneValue) { 6620 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6621 if (isConstant && Val.getNode()) 6622 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6623 } 6624 } 6625 6626 // If all elements are constants and the case above didn't get hit, fall back 6627 // to the default expansion, which will generate a load from the constant 6628 // pool. 6629 if (isConstant) 6630 return SDValue(); 6631 6632 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6633 if (NumElts >= 4) { 6634 SDValue shuffle = ReconstructShuffle(Op, DAG); 6635 if (shuffle != SDValue()) 6636 return shuffle; 6637 } 6638 6639 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6640 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6641 // into two 64-bit vectors; we might discover a better way to lower it. 6642 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6643 EVT ExtVT = VT.getVectorElementType(); 6644 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6645 SDValue Lower = 6646 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6647 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6648 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6649 SDValue Upper = DAG.getBuildVector( 6650 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6651 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6652 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6653 if (Lower && Upper) 6654 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6655 } 6656 6657 // Vectors with 32- or 64-bit elements can be built by directly assigning 6658 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6659 // will be legalized. 6660 if (EltSize >= 32) { 6661 // Do the expansion with floating-point types, since that is what the VFP 6662 // registers are defined to use, and since i64 is not legal. 6663 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6664 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6665 SmallVector<SDValue, 8> Ops; 6666 for (unsigned i = 0; i < NumElts; ++i) 6667 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6668 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6669 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6670 } 6671 6672 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6673 // know the default expansion would otherwise fall back on something even 6674 // worse. For a vector with one or two non-undef values, that's 6675 // scalar_to_vector for the elements followed by a shuffle (provided the 6676 // shuffle is valid for the target) and materialization element by element 6677 // on the stack followed by a load for everything else. 6678 if (!isConstant && !usesOnlyOneValue) { 6679 SDValue Vec = DAG.getUNDEF(VT); 6680 for (unsigned i = 0 ; i < NumElts; ++i) { 6681 SDValue V = Op.getOperand(i); 6682 if (V.isUndef()) 6683 continue; 6684 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6685 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6686 } 6687 return Vec; 6688 } 6689 6690 return SDValue(); 6691 } 6692 6693 // Gather data to see if the operation can be modelled as a 6694 // shuffle in combination with VEXTs. 6695 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6696 SelectionDAG &DAG) const { 6697 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6698 SDLoc dl(Op); 6699 EVT VT = Op.getValueType(); 6700 unsigned NumElts = VT.getVectorNumElements(); 6701 6702 struct ShuffleSourceInfo { 6703 SDValue Vec; 6704 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6705 unsigned MaxElt = 0; 6706 6707 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6708 // be compatible with the shuffle we intend to construct. As a result 6709 // ShuffleVec will be some sliding window into the original Vec. 6710 SDValue ShuffleVec; 6711 6712 // Code should guarantee that element i in Vec starts at element "WindowBase 6713 // + i * WindowScale in ShuffleVec". 6714 int WindowBase = 0; 6715 int WindowScale = 1; 6716 6717 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6718 6719 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6720 }; 6721 6722 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6723 // node. 6724 SmallVector<ShuffleSourceInfo, 2> Sources; 6725 for (unsigned i = 0; i < NumElts; ++i) { 6726 SDValue V = Op.getOperand(i); 6727 if (V.isUndef()) 6728 continue; 6729 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6730 // A shuffle can only come from building a vector from various 6731 // elements of other vectors. 6732 return SDValue(); 6733 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6734 // Furthermore, shuffles require a constant mask, whereas extractelts 6735 // accept variable indices. 6736 return SDValue(); 6737 } 6738 6739 // Add this element source to the list if it's not already there. 6740 SDValue SourceVec = V.getOperand(0); 6741 auto Source = llvm::find(Sources, SourceVec); 6742 if (Source == Sources.end()) 6743 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6744 6745 // Update the minimum and maximum lane number seen. 6746 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6747 Source->MinElt = std::min(Source->MinElt, EltNo); 6748 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6749 } 6750 6751 // Currently only do something sane when at most two source vectors 6752 // are involved. 6753 if (Sources.size() > 2) 6754 return SDValue(); 6755 6756 // Find out the smallest element size among result and two sources, and use 6757 // it as element size to build the shuffle_vector. 6758 EVT SmallestEltTy = VT.getVectorElementType(); 6759 for (auto &Source : Sources) { 6760 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6761 if (SrcEltTy.bitsLT(SmallestEltTy)) 6762 SmallestEltTy = SrcEltTy; 6763 } 6764 unsigned ResMultiplier = 6765 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6766 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6767 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6768 6769 // If the source vector is too wide or too narrow, we may nevertheless be able 6770 // to construct a compatible shuffle either by concatenating it with UNDEF or 6771 // extracting a suitable range of elements. 6772 for (auto &Src : Sources) { 6773 EVT SrcVT = Src.ShuffleVec.getValueType(); 6774 6775 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6776 continue; 6777 6778 // This stage of the search produces a source with the same element type as 6779 // the original, but with a total width matching the BUILD_VECTOR output. 6780 EVT EltVT = SrcVT.getVectorElementType(); 6781 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6782 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6783 6784 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6785 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6786 return SDValue(); 6787 // We can pad out the smaller vector for free, so if it's part of a 6788 // shuffle... 6789 Src.ShuffleVec = 6790 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6791 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6792 continue; 6793 } 6794 6795 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6796 return SDValue(); 6797 6798 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6799 // Span too large for a VEXT to cope 6800 return SDValue(); 6801 } 6802 6803 if (Src.MinElt >= NumSrcElts) { 6804 // The extraction can just take the second half 6805 Src.ShuffleVec = 6806 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6807 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6808 Src.WindowBase = -NumSrcElts; 6809 } else if (Src.MaxElt < NumSrcElts) { 6810 // The extraction can just take the first half 6811 Src.ShuffleVec = 6812 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6813 DAG.getConstant(0, dl, MVT::i32)); 6814 } else { 6815 // An actual VEXT is needed 6816 SDValue VEXTSrc1 = 6817 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6818 DAG.getConstant(0, dl, MVT::i32)); 6819 SDValue VEXTSrc2 = 6820 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6821 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6822 6823 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6824 VEXTSrc2, 6825 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6826 Src.WindowBase = -Src.MinElt; 6827 } 6828 } 6829 6830 // Another possible incompatibility occurs from the vector element types. We 6831 // can fix this by bitcasting the source vectors to the same type we intend 6832 // for the shuffle. 6833 for (auto &Src : Sources) { 6834 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6835 if (SrcEltTy == SmallestEltTy) 6836 continue; 6837 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6838 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6839 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6840 Src.WindowBase *= Src.WindowScale; 6841 } 6842 6843 // Final sanity check before we try to actually produce a shuffle. 6844 LLVM_DEBUG(for (auto Src 6845 : Sources) 6846 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6847 6848 // The stars all align, our next step is to produce the mask for the shuffle. 6849 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6850 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6851 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6852 SDValue Entry = Op.getOperand(i); 6853 if (Entry.isUndef()) 6854 continue; 6855 6856 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6857 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6858 6859 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6860 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6861 // segment. 6862 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6863 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6864 VT.getScalarSizeInBits()); 6865 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6866 6867 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6868 // starting at the appropriate offset. 6869 int *LaneMask = &Mask[i * ResMultiplier]; 6870 6871 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6872 ExtractBase += NumElts * (Src - Sources.begin()); 6873 for (int j = 0; j < LanesDefined; ++j) 6874 LaneMask[j] = ExtractBase + j; 6875 } 6876 6877 // Final check before we try to produce nonsense... 6878 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6879 return SDValue(); 6880 6881 // We can't handle more than two sources. This should have already 6882 // been checked before this point. 6883 assert(Sources.size() <= 2 && "Too many sources!"); 6884 6885 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6886 for (unsigned i = 0; i < Sources.size(); ++i) 6887 ShuffleOps[i] = Sources[i].ShuffleVec; 6888 6889 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6890 ShuffleOps[1], Mask); 6891 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6892 } 6893 6894 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6895 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6896 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6897 /// are assumed to be legal. 6898 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6899 if (VT.getVectorNumElements() == 4 && 6900 (VT.is128BitVector() || VT.is64BitVector())) { 6901 unsigned PFIndexes[4]; 6902 for (unsigned i = 0; i != 4; ++i) { 6903 if (M[i] < 0) 6904 PFIndexes[i] = 8; 6905 else 6906 PFIndexes[i] = M[i]; 6907 } 6908 6909 // Compute the index in the perfect shuffle table. 6910 unsigned PFTableIndex = 6911 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6912 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6913 unsigned Cost = (PFEntry >> 30); 6914 6915 if (Cost <= 4) 6916 return true; 6917 } 6918 6919 bool ReverseVEXT, isV_UNDEF; 6920 unsigned Imm, WhichResult; 6921 6922 unsigned EltSize = VT.getScalarSizeInBits(); 6923 return (EltSize >= 32 || 6924 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6925 isVREVMask(M, VT, 64) || 6926 isVREVMask(M, VT, 32) || 6927 isVREVMask(M, VT, 16) || 6928 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6929 isVTBLMask(M, VT) || 6930 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6931 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6932 } 6933 6934 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6935 /// the specified operations to build the shuffle. 6936 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6937 SDValue RHS, SelectionDAG &DAG, 6938 const SDLoc &dl) { 6939 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6940 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6941 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6942 6943 enum { 6944 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6945 OP_VREV, 6946 OP_VDUP0, 6947 OP_VDUP1, 6948 OP_VDUP2, 6949 OP_VDUP3, 6950 OP_VEXT1, 6951 OP_VEXT2, 6952 OP_VEXT3, 6953 OP_VUZPL, // VUZP, left result 6954 OP_VUZPR, // VUZP, right result 6955 OP_VZIPL, // VZIP, left result 6956 OP_VZIPR, // VZIP, right result 6957 OP_VTRNL, // VTRN, left result 6958 OP_VTRNR // VTRN, right result 6959 }; 6960 6961 if (OpNum == OP_COPY) { 6962 if (LHSID == (1*9+2)*9+3) return LHS; 6963 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6964 return RHS; 6965 } 6966 6967 SDValue OpLHS, OpRHS; 6968 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6969 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6970 EVT VT = OpLHS.getValueType(); 6971 6972 switch (OpNum) { 6973 default: llvm_unreachable("Unknown shuffle opcode!"); 6974 case OP_VREV: 6975 // VREV divides the vector in half and swaps within the half. 6976 if (VT.getVectorElementType() == MVT::i32 || 6977 VT.getVectorElementType() == MVT::f32) 6978 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6979 // vrev <4 x i16> -> VREV32 6980 if (VT.getVectorElementType() == MVT::i16) 6981 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6982 // vrev <4 x i8> -> VREV16 6983 assert(VT.getVectorElementType() == MVT::i8); 6984 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6985 case OP_VDUP0: 6986 case OP_VDUP1: 6987 case OP_VDUP2: 6988 case OP_VDUP3: 6989 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6990 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6991 case OP_VEXT1: 6992 case OP_VEXT2: 6993 case OP_VEXT3: 6994 return DAG.getNode(ARMISD::VEXT, dl, VT, 6995 OpLHS, OpRHS, 6996 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6997 case OP_VUZPL: 6998 case OP_VUZPR: 6999 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 7000 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 7001 case OP_VZIPL: 7002 case OP_VZIPR: 7003 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 7004 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 7005 case OP_VTRNL: 7006 case OP_VTRNR: 7007 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7008 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7009 } 7010 } 7011 7012 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7013 ArrayRef<int> ShuffleMask, 7014 SelectionDAG &DAG) { 7015 // Check to see if we can use the VTBL instruction. 7016 SDValue V1 = Op.getOperand(0); 7017 SDValue V2 = Op.getOperand(1); 7018 SDLoc DL(Op); 7019 7020 SmallVector<SDValue, 8> VTBLMask; 7021 for (ArrayRef<int>::iterator 7022 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7023 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7024 7025 if (V2.getNode()->isUndef()) 7026 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7027 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7028 7029 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7030 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7031 } 7032 7033 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7034 SelectionDAG &DAG) { 7035 SDLoc DL(Op); 7036 SDValue OpLHS = Op.getOperand(0); 7037 EVT VT = OpLHS.getValueType(); 7038 7039 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7040 "Expect an v8i16/v16i8 type"); 7041 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7042 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7043 // extract the first 8 bytes into the top double word and the last 8 bytes 7044 // into the bottom double word. The v8i16 case is similar. 7045 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7046 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7047 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7048 } 7049 7050 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 7051 SDValue V1 = Op.getOperand(0); 7052 SDValue V2 = Op.getOperand(1); 7053 SDLoc dl(Op); 7054 EVT VT = Op.getValueType(); 7055 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7056 7057 // Convert shuffles that are directly supported on NEON to target-specific 7058 // DAG nodes, instead of keeping them as shuffles and matching them again 7059 // during code selection. This is more efficient and avoids the possibility 7060 // of inconsistencies between legalization and selection. 7061 // FIXME: floating-point vectors should be canonicalized to integer vectors 7062 // of the same time so that they get CSEd properly. 7063 ArrayRef<int> ShuffleMask = SVN->getMask(); 7064 7065 unsigned EltSize = VT.getScalarSizeInBits(); 7066 if (EltSize <= 32) { 7067 if (SVN->isSplat()) { 7068 int Lane = SVN->getSplatIndex(); 7069 // If this is undef splat, generate it via "just" vdup, if possible. 7070 if (Lane == -1) Lane = 0; 7071 7072 // Test if V1 is a SCALAR_TO_VECTOR. 7073 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7074 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7075 } 7076 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7077 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7078 // reaches it). 7079 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7080 !isa<ConstantSDNode>(V1.getOperand(0))) { 7081 bool IsScalarToVector = true; 7082 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7083 if (!V1.getOperand(i).isUndef()) { 7084 IsScalarToVector = false; 7085 break; 7086 } 7087 if (IsScalarToVector) 7088 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7089 } 7090 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7091 DAG.getConstant(Lane, dl, MVT::i32)); 7092 } 7093 7094 bool ReverseVEXT; 7095 unsigned Imm; 7096 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7097 if (ReverseVEXT) 7098 std::swap(V1, V2); 7099 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7100 DAG.getConstant(Imm, dl, MVT::i32)); 7101 } 7102 7103 if (isVREVMask(ShuffleMask, VT, 64)) 7104 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7105 if (isVREVMask(ShuffleMask, VT, 32)) 7106 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7107 if (isVREVMask(ShuffleMask, VT, 16)) 7108 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7109 7110 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7111 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7112 DAG.getConstant(Imm, dl, MVT::i32)); 7113 } 7114 7115 // Check for Neon shuffles that modify both input vectors in place. 7116 // If both results are used, i.e., if there are two shuffles with the same 7117 // source operands and with masks corresponding to both results of one of 7118 // these operations, DAG memoization will ensure that a single node is 7119 // used for both shuffles. 7120 unsigned WhichResult; 7121 bool isV_UNDEF; 7122 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7123 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7124 if (isV_UNDEF) 7125 V2 = V1; 7126 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7127 .getValue(WhichResult); 7128 } 7129 7130 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7131 // shuffles that produce a result larger than their operands with: 7132 // shuffle(concat(v1, undef), concat(v2, undef)) 7133 // -> 7134 // shuffle(concat(v1, v2), undef) 7135 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7136 // 7137 // This is useful in the general case, but there are special cases where 7138 // native shuffles produce larger results: the two-result ops. 7139 // 7140 // Look through the concat when lowering them: 7141 // shuffle(concat(v1, v2), undef) 7142 // -> 7143 // concat(VZIP(v1, v2):0, :1) 7144 // 7145 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7146 SDValue SubV1 = V1->getOperand(0); 7147 SDValue SubV2 = V1->getOperand(1); 7148 EVT SubVT = SubV1.getValueType(); 7149 7150 // We expect these to have been canonicalized to -1. 7151 assert(llvm::all_of(ShuffleMask, [&](int i) { 7152 return i < (int)VT.getVectorNumElements(); 7153 }) && "Unexpected shuffle index into UNDEF operand!"); 7154 7155 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7156 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7157 if (isV_UNDEF) 7158 SubV2 = SubV1; 7159 assert((WhichResult == 0) && 7160 "In-place shuffle of concat can only have one result!"); 7161 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7162 SubV1, SubV2); 7163 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7164 Res.getValue(1)); 7165 } 7166 } 7167 } 7168 7169 // If the shuffle is not directly supported and it has 4 elements, use 7170 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7171 unsigned NumElts = VT.getVectorNumElements(); 7172 if (NumElts == 4) { 7173 unsigned PFIndexes[4]; 7174 for (unsigned i = 0; i != 4; ++i) { 7175 if (ShuffleMask[i] < 0) 7176 PFIndexes[i] = 8; 7177 else 7178 PFIndexes[i] = ShuffleMask[i]; 7179 } 7180 7181 // Compute the index in the perfect shuffle table. 7182 unsigned PFTableIndex = 7183 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7184 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7185 unsigned Cost = (PFEntry >> 30); 7186 7187 if (Cost <= 4) 7188 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7189 } 7190 7191 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7192 if (EltSize >= 32) { 7193 // Do the expansion with floating-point types, since that is what the VFP 7194 // registers are defined to use, and since i64 is not legal. 7195 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7196 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7197 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7198 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7199 SmallVector<SDValue, 8> Ops; 7200 for (unsigned i = 0; i < NumElts; ++i) { 7201 if (ShuffleMask[i] < 0) 7202 Ops.push_back(DAG.getUNDEF(EltVT)); 7203 else 7204 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7205 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7206 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7207 dl, MVT::i32))); 7208 } 7209 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7210 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7211 } 7212 7213 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7214 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7215 7216 if (VT == MVT::v8i8) 7217 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7218 return NewOp; 7219 7220 return SDValue(); 7221 } 7222 7223 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7224 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7225 SDValue Lane = Op.getOperand(2); 7226 if (!isa<ConstantSDNode>(Lane)) 7227 return SDValue(); 7228 7229 return Op; 7230 } 7231 7232 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7233 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7234 SDValue Lane = Op.getOperand(1); 7235 if (!isa<ConstantSDNode>(Lane)) 7236 return SDValue(); 7237 7238 SDValue Vec = Op.getOperand(0); 7239 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7240 SDLoc dl(Op); 7241 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7242 } 7243 7244 return Op; 7245 } 7246 7247 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7248 // The only time a CONCAT_VECTORS operation can have legal types is when 7249 // two 64-bit vectors are concatenated to a 128-bit vector. 7250 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7251 "unexpected CONCAT_VECTORS"); 7252 SDLoc dl(Op); 7253 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7254 SDValue Op0 = Op.getOperand(0); 7255 SDValue Op1 = Op.getOperand(1); 7256 if (!Op0.isUndef()) 7257 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7258 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7259 DAG.getIntPtrConstant(0, dl)); 7260 if (!Op1.isUndef()) 7261 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7262 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7263 DAG.getIntPtrConstant(1, dl)); 7264 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7265 } 7266 7267 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7268 /// element has been zero/sign-extended, depending on the isSigned parameter, 7269 /// from an integer type half its size. 7270 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7271 bool isSigned) { 7272 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7273 EVT VT = N->getValueType(0); 7274 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7275 SDNode *BVN = N->getOperand(0).getNode(); 7276 if (BVN->getValueType(0) != MVT::v4i32 || 7277 BVN->getOpcode() != ISD::BUILD_VECTOR) 7278 return false; 7279 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7280 unsigned HiElt = 1 - LoElt; 7281 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7282 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7283 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7284 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7285 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7286 return false; 7287 if (isSigned) { 7288 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7289 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7290 return true; 7291 } else { 7292 if (Hi0->isNullValue() && Hi1->isNullValue()) 7293 return true; 7294 } 7295 return false; 7296 } 7297 7298 if (N->getOpcode() != ISD::BUILD_VECTOR) 7299 return false; 7300 7301 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7302 SDNode *Elt = N->getOperand(i).getNode(); 7303 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7304 unsigned EltSize = VT.getScalarSizeInBits(); 7305 unsigned HalfSize = EltSize / 2; 7306 if (isSigned) { 7307 if (!isIntN(HalfSize, C->getSExtValue())) 7308 return false; 7309 } else { 7310 if (!isUIntN(HalfSize, C->getZExtValue())) 7311 return false; 7312 } 7313 continue; 7314 } 7315 return false; 7316 } 7317 7318 return true; 7319 } 7320 7321 /// isSignExtended - Check if a node is a vector value that is sign-extended 7322 /// or a constant BUILD_VECTOR with sign-extended elements. 7323 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7324 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7325 return true; 7326 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7327 return true; 7328 return false; 7329 } 7330 7331 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7332 /// or a constant BUILD_VECTOR with zero-extended elements. 7333 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7334 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7335 return true; 7336 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7337 return true; 7338 return false; 7339 } 7340 7341 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7342 if (OrigVT.getSizeInBits() >= 64) 7343 return OrigVT; 7344 7345 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7346 7347 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7348 switch (OrigSimpleTy) { 7349 default: llvm_unreachable("Unexpected Vector Type"); 7350 case MVT::v2i8: 7351 case MVT::v2i16: 7352 return MVT::v2i32; 7353 case MVT::v4i8: 7354 return MVT::v4i16; 7355 } 7356 } 7357 7358 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7359 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7360 /// We insert the required extension here to get the vector to fill a D register. 7361 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7362 const EVT &OrigTy, 7363 const EVT &ExtTy, 7364 unsigned ExtOpcode) { 7365 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7366 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7367 // 64-bits we need to insert a new extension so that it will be 64-bits. 7368 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7369 if (OrigTy.getSizeInBits() >= 64) 7370 return N; 7371 7372 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7373 EVT NewVT = getExtensionTo64Bits(OrigTy); 7374 7375 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7376 } 7377 7378 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7379 /// does not do any sign/zero extension. If the original vector is less 7380 /// than 64 bits, an appropriate extension will be added after the load to 7381 /// reach a total size of 64 bits. We have to add the extension separately 7382 /// because ARM does not have a sign/zero extending load for vectors. 7383 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7384 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7385 7386 // The load already has the right type. 7387 if (ExtendedTy == LD->getMemoryVT()) 7388 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7389 LD->getBasePtr(), LD->getPointerInfo(), 7390 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7391 7392 // We need to create a zextload/sextload. We cannot just create a load 7393 // followed by a zext/zext node because LowerMUL is also run during normal 7394 // operation legalization where we can't create illegal types. 7395 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7396 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7397 LD->getMemoryVT(), LD->getAlignment(), 7398 LD->getMemOperand()->getFlags()); 7399 } 7400 7401 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7402 /// extending load, or BUILD_VECTOR with extended elements, return the 7403 /// unextended value. The unextended vector should be 64 bits so that it can 7404 /// be used as an operand to a VMULL instruction. If the original vector size 7405 /// before extension is less than 64 bits we add a an extension to resize 7406 /// the vector to 64 bits. 7407 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7408 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7409 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7410 N->getOperand(0)->getValueType(0), 7411 N->getValueType(0), 7412 N->getOpcode()); 7413 7414 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7415 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7416 "Expected extending load"); 7417 7418 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7419 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7420 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7421 SDValue extLoad = 7422 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7423 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7424 7425 return newLoad; 7426 } 7427 7428 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7429 // have been legalized as a BITCAST from v4i32. 7430 if (N->getOpcode() == ISD::BITCAST) { 7431 SDNode *BVN = N->getOperand(0).getNode(); 7432 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7433 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7434 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7435 return DAG.getBuildVector( 7436 MVT::v2i32, SDLoc(N), 7437 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7438 } 7439 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7440 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7441 EVT VT = N->getValueType(0); 7442 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7443 unsigned NumElts = VT.getVectorNumElements(); 7444 MVT TruncVT = MVT::getIntegerVT(EltSize); 7445 SmallVector<SDValue, 8> Ops; 7446 SDLoc dl(N); 7447 for (unsigned i = 0; i != NumElts; ++i) { 7448 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7449 const APInt &CInt = C->getAPIntValue(); 7450 // Element types smaller than 32 bits are not legal, so use i32 elements. 7451 // The values are implicitly truncated so sext vs. zext doesn't matter. 7452 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7453 } 7454 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7455 } 7456 7457 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7458 unsigned Opcode = N->getOpcode(); 7459 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7460 SDNode *N0 = N->getOperand(0).getNode(); 7461 SDNode *N1 = N->getOperand(1).getNode(); 7462 return N0->hasOneUse() && N1->hasOneUse() && 7463 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7464 } 7465 return false; 7466 } 7467 7468 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7469 unsigned Opcode = N->getOpcode(); 7470 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7471 SDNode *N0 = N->getOperand(0).getNode(); 7472 SDNode *N1 = N->getOperand(1).getNode(); 7473 return N0->hasOneUse() && N1->hasOneUse() && 7474 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7475 } 7476 return false; 7477 } 7478 7479 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7480 // Multiplications are only custom-lowered for 128-bit vectors so that 7481 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7482 EVT VT = Op.getValueType(); 7483 assert(VT.is128BitVector() && VT.isInteger() && 7484 "unexpected type for custom-lowering ISD::MUL"); 7485 SDNode *N0 = Op.getOperand(0).getNode(); 7486 SDNode *N1 = Op.getOperand(1).getNode(); 7487 unsigned NewOpc = 0; 7488 bool isMLA = false; 7489 bool isN0SExt = isSignExtended(N0, DAG); 7490 bool isN1SExt = isSignExtended(N1, DAG); 7491 if (isN0SExt && isN1SExt) 7492 NewOpc = ARMISD::VMULLs; 7493 else { 7494 bool isN0ZExt = isZeroExtended(N0, DAG); 7495 bool isN1ZExt = isZeroExtended(N1, DAG); 7496 if (isN0ZExt && isN1ZExt) 7497 NewOpc = ARMISD::VMULLu; 7498 else if (isN1SExt || isN1ZExt) { 7499 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7500 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7501 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7502 NewOpc = ARMISD::VMULLs; 7503 isMLA = true; 7504 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7505 NewOpc = ARMISD::VMULLu; 7506 isMLA = true; 7507 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7508 std::swap(N0, N1); 7509 NewOpc = ARMISD::VMULLu; 7510 isMLA = true; 7511 } 7512 } 7513 7514 if (!NewOpc) { 7515 if (VT == MVT::v2i64) 7516 // Fall through to expand this. It is not legal. 7517 return SDValue(); 7518 else 7519 // Other vector multiplications are legal. 7520 return Op; 7521 } 7522 } 7523 7524 // Legalize to a VMULL instruction. 7525 SDLoc DL(Op); 7526 SDValue Op0; 7527 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7528 if (!isMLA) { 7529 Op0 = SkipExtensionForVMULL(N0, DAG); 7530 assert(Op0.getValueType().is64BitVector() && 7531 Op1.getValueType().is64BitVector() && 7532 "unexpected types for extended operands to VMULL"); 7533 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7534 } 7535 7536 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7537 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7538 // vmull q0, d4, d6 7539 // vmlal q0, d5, d6 7540 // is faster than 7541 // vaddl q0, d4, d5 7542 // vmovl q1, d6 7543 // vmul q0, q0, q1 7544 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7545 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7546 EVT Op1VT = Op1.getValueType(); 7547 return DAG.getNode(N0->getOpcode(), DL, VT, 7548 DAG.getNode(NewOpc, DL, VT, 7549 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7550 DAG.getNode(NewOpc, DL, VT, 7551 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7552 } 7553 7554 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7555 SelectionDAG &DAG) { 7556 // TODO: Should this propagate fast-math-flags? 7557 7558 // Convert to float 7559 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7560 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7561 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7562 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7563 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7564 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7565 // Get reciprocal estimate. 7566 // float4 recip = vrecpeq_f32(yf); 7567 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7568 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7569 Y); 7570 // Because char has a smaller range than uchar, we can actually get away 7571 // without any newton steps. This requires that we use a weird bias 7572 // of 0xb000, however (again, this has been exhaustively tested). 7573 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7574 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7575 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7576 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7577 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7578 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7579 // Convert back to short. 7580 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7581 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7582 return X; 7583 } 7584 7585 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7586 SelectionDAG &DAG) { 7587 // TODO: Should this propagate fast-math-flags? 7588 7589 SDValue N2; 7590 // Convert to float. 7591 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7592 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7593 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7594 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7595 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7596 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7597 7598 // Use reciprocal estimate and one refinement step. 7599 // float4 recip = vrecpeq_f32(yf); 7600 // recip *= vrecpsq_f32(yf, recip); 7601 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7602 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7603 N1); 7604 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7605 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7606 N1, N2); 7607 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7608 // Because short has a smaller range than ushort, we can actually get away 7609 // with only a single newton step. This requires that we use a weird bias 7610 // of 89, however (again, this has been exhaustively tested). 7611 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7612 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7613 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7614 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7615 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7616 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7617 // Convert back to integer and return. 7618 // return vmovn_s32(vcvt_s32_f32(result)); 7619 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7620 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7621 return N0; 7622 } 7623 7624 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7625 EVT VT = Op.getValueType(); 7626 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7627 "unexpected type for custom-lowering ISD::SDIV"); 7628 7629 SDLoc dl(Op); 7630 SDValue N0 = Op.getOperand(0); 7631 SDValue N1 = Op.getOperand(1); 7632 SDValue N2, N3; 7633 7634 if (VT == MVT::v8i8) { 7635 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7636 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7637 7638 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7639 DAG.getIntPtrConstant(4, dl)); 7640 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7641 DAG.getIntPtrConstant(4, dl)); 7642 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7643 DAG.getIntPtrConstant(0, dl)); 7644 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7645 DAG.getIntPtrConstant(0, dl)); 7646 7647 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7648 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7649 7650 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7651 N0 = LowerCONCAT_VECTORS(N0, DAG); 7652 7653 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7654 return N0; 7655 } 7656 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7657 } 7658 7659 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7660 // TODO: Should this propagate fast-math-flags? 7661 EVT VT = Op.getValueType(); 7662 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7663 "unexpected type for custom-lowering ISD::UDIV"); 7664 7665 SDLoc dl(Op); 7666 SDValue N0 = Op.getOperand(0); 7667 SDValue N1 = Op.getOperand(1); 7668 SDValue N2, N3; 7669 7670 if (VT == MVT::v8i8) { 7671 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7672 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7673 7674 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7675 DAG.getIntPtrConstant(4, dl)); 7676 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7677 DAG.getIntPtrConstant(4, dl)); 7678 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7679 DAG.getIntPtrConstant(0, dl)); 7680 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7681 DAG.getIntPtrConstant(0, dl)); 7682 7683 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7684 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7685 7686 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7687 N0 = LowerCONCAT_VECTORS(N0, DAG); 7688 7689 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7690 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7691 MVT::i32), 7692 N0); 7693 return N0; 7694 } 7695 7696 // v4i16 sdiv ... Convert to float. 7697 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7698 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7699 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7700 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7701 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7702 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7703 7704 // Use reciprocal estimate and two refinement steps. 7705 // float4 recip = vrecpeq_f32(yf); 7706 // recip *= vrecpsq_f32(yf, recip); 7707 // recip *= vrecpsq_f32(yf, recip); 7708 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7709 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7710 BN1); 7711 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7712 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7713 BN1, N2); 7714 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7715 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7716 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7717 BN1, N2); 7718 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7719 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7720 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7721 // and that it will never cause us to return an answer too large). 7722 // float4 result = as_float4(as_int4(xf*recip) + 2); 7723 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7724 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7725 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7726 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7727 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7728 // Convert back to integer and return. 7729 // return vmovn_u32(vcvt_s32_f32(result)); 7730 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7731 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7732 return N0; 7733 } 7734 7735 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7736 EVT VT = Op.getNode()->getValueType(0); 7737 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7738 7739 unsigned Opc; 7740 bool ExtraOp = false; 7741 switch (Op.getOpcode()) { 7742 default: llvm_unreachable("Invalid code"); 7743 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7744 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7745 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7746 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7747 } 7748 7749 if (!ExtraOp) 7750 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7751 Op.getOperand(1)); 7752 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7753 Op.getOperand(1), Op.getOperand(2)); 7754 } 7755 7756 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7757 SDNode *N = Op.getNode(); 7758 EVT VT = N->getValueType(0); 7759 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7760 7761 SDValue Carry = Op.getOperand(2); 7762 7763 SDLoc DL(Op); 7764 7765 SDValue Result; 7766 if (Op.getOpcode() == ISD::ADDCARRY) { 7767 // This converts the boolean value carry into the carry flag. 7768 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7769 7770 // Do the addition proper using the carry flag we wanted. 7771 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7772 Op.getOperand(1), Carry); 7773 7774 // Now convert the carry flag into a boolean value. 7775 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7776 } else { 7777 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7778 // have to invert the carry first. 7779 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7780 DAG.getConstant(1, DL, MVT::i32), Carry); 7781 // This converts the boolean value carry into the carry flag. 7782 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7783 7784 // Do the subtraction proper using the carry flag we wanted. 7785 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7786 Op.getOperand(1), Carry); 7787 7788 // Now convert the carry flag into a boolean value. 7789 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7790 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7791 // by ISD::SUBCARRY, so compute 1 - C. 7792 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7793 DAG.getConstant(1, DL, MVT::i32), Carry); 7794 } 7795 7796 // Return both values. 7797 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7798 } 7799 7800 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7801 assert(Subtarget->isTargetDarwin()); 7802 7803 // For iOS, we want to call an alternative entry point: __sincos_stret, 7804 // return values are passed via sret. 7805 SDLoc dl(Op); 7806 SDValue Arg = Op.getOperand(0); 7807 EVT ArgVT = Arg.getValueType(); 7808 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7809 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7810 7811 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7812 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7813 7814 // Pair of floats / doubles used to pass the result. 7815 Type *RetTy = StructType::get(ArgTy, ArgTy); 7816 auto &DL = DAG.getDataLayout(); 7817 7818 ArgListTy Args; 7819 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7820 SDValue SRet; 7821 if (ShouldUseSRet) { 7822 // Create stack object for sret. 7823 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7824 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7825 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7826 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7827 7828 ArgListEntry Entry; 7829 Entry.Node = SRet; 7830 Entry.Ty = RetTy->getPointerTo(); 7831 Entry.IsSExt = false; 7832 Entry.IsZExt = false; 7833 Entry.IsSRet = true; 7834 Args.push_back(Entry); 7835 RetTy = Type::getVoidTy(*DAG.getContext()); 7836 } 7837 7838 ArgListEntry Entry; 7839 Entry.Node = Arg; 7840 Entry.Ty = ArgTy; 7841 Entry.IsSExt = false; 7842 Entry.IsZExt = false; 7843 Args.push_back(Entry); 7844 7845 RTLIB::Libcall LC = 7846 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 7847 const char *LibcallName = getLibcallName(LC); 7848 CallingConv::ID CC = getLibcallCallingConv(LC); 7849 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7850 7851 TargetLowering::CallLoweringInfo CLI(DAG); 7852 CLI.setDebugLoc(dl) 7853 .setChain(DAG.getEntryNode()) 7854 .setCallee(CC, RetTy, Callee, std::move(Args)) 7855 .setDiscardResult(ShouldUseSRet); 7856 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7857 7858 if (!ShouldUseSRet) 7859 return CallResult.first; 7860 7861 SDValue LoadSin = 7862 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7863 7864 // Address of cos field. 7865 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7866 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7867 SDValue LoadCos = 7868 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7869 7870 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7871 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7872 LoadSin.getValue(0), LoadCos.getValue(0)); 7873 } 7874 7875 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7876 bool Signed, 7877 SDValue &Chain) const { 7878 EVT VT = Op.getValueType(); 7879 assert((VT == MVT::i32 || VT == MVT::i64) && 7880 "unexpected type for custom lowering DIV"); 7881 SDLoc dl(Op); 7882 7883 const auto &DL = DAG.getDataLayout(); 7884 const auto &TLI = DAG.getTargetLoweringInfo(); 7885 7886 const char *Name = nullptr; 7887 if (Signed) 7888 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7889 else 7890 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7891 7892 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7893 7894 ARMTargetLowering::ArgListTy Args; 7895 7896 for (auto AI : {1, 0}) { 7897 ArgListEntry Arg; 7898 Arg.Node = Op.getOperand(AI); 7899 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7900 Args.push_back(Arg); 7901 } 7902 7903 CallLoweringInfo CLI(DAG); 7904 CLI.setDebugLoc(dl) 7905 .setChain(Chain) 7906 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7907 ES, std::move(Args)); 7908 7909 return LowerCallTo(CLI).first; 7910 } 7911 7912 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7913 bool Signed) const { 7914 assert(Op.getValueType() == MVT::i32 && 7915 "unexpected type for custom lowering DIV"); 7916 SDLoc dl(Op); 7917 7918 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7919 DAG.getEntryNode(), Op.getOperand(1)); 7920 7921 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7922 } 7923 7924 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7925 SDLoc DL(N); 7926 SDValue Op = N->getOperand(1); 7927 if (N->getValueType(0) == MVT::i32) 7928 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7929 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7930 DAG.getConstant(0, DL, MVT::i32)); 7931 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7932 DAG.getConstant(1, DL, MVT::i32)); 7933 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7934 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7935 } 7936 7937 void ARMTargetLowering::ExpandDIV_Windows( 7938 SDValue Op, SelectionDAG &DAG, bool Signed, 7939 SmallVectorImpl<SDValue> &Results) const { 7940 const auto &DL = DAG.getDataLayout(); 7941 const auto &TLI = DAG.getTargetLoweringInfo(); 7942 7943 assert(Op.getValueType() == MVT::i64 && 7944 "unexpected type for custom lowering DIV"); 7945 SDLoc dl(Op); 7946 7947 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7948 7949 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7950 7951 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7952 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7953 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7954 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7955 7956 Results.push_back(Lower); 7957 Results.push_back(Upper); 7958 } 7959 7960 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7961 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7962 // Acquire/Release load/store is not legal for targets without a dmb or 7963 // equivalent available. 7964 return SDValue(); 7965 7966 // Monotonic load/store is legal for all targets. 7967 return Op; 7968 } 7969 7970 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7971 SmallVectorImpl<SDValue> &Results, 7972 SelectionDAG &DAG, 7973 const ARMSubtarget *Subtarget) { 7974 SDLoc DL(N); 7975 // Under Power Management extensions, the cycle-count is: 7976 // mrc p15, #0, <Rt>, c9, c13, #0 7977 SDValue Ops[] = { N->getOperand(0), // Chain 7978 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7979 DAG.getConstant(15, DL, MVT::i32), 7980 DAG.getConstant(0, DL, MVT::i32), 7981 DAG.getConstant(9, DL, MVT::i32), 7982 DAG.getConstant(13, DL, MVT::i32), 7983 DAG.getConstant(0, DL, MVT::i32) 7984 }; 7985 7986 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7987 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7988 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7989 DAG.getConstant(0, DL, MVT::i32))); 7990 Results.push_back(Cycles32.getValue(1)); 7991 } 7992 7993 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7994 SDLoc dl(V.getNode()); 7995 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7996 SDValue VHi = DAG.getAnyExtOrTrunc( 7997 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7998 dl, MVT::i32); 7999 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8000 if (isBigEndian) 8001 std::swap (VLo, VHi); 8002 SDValue RegClass = 8003 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 8004 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 8005 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 8006 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 8007 return SDValue( 8008 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 8009 } 8010 8011 static void ReplaceCMP_SWAP_64Results(SDNode *N, 8012 SmallVectorImpl<SDValue> & Results, 8013 SelectionDAG &DAG) { 8014 assert(N->getValueType(0) == MVT::i64 && 8015 "AtomicCmpSwap on types less than 64 should be legal"); 8016 SDValue Ops[] = {N->getOperand(1), 8017 createGPRPairNode(DAG, N->getOperand(2)), 8018 createGPRPairNode(DAG, N->getOperand(3)), 8019 N->getOperand(0)}; 8020 SDNode *CmpSwap = DAG.getMachineNode( 8021 ARM::CMP_SWAP_64, SDLoc(N), 8022 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 8023 8024 MachineFunction &MF = DAG.getMachineFunction(); 8025 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 8026 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 8027 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 8028 8029 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8030 8031 Results.push_back( 8032 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 8033 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8034 Results.push_back( 8035 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 8036 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8037 Results.push_back(SDValue(CmpSwap, 2)); 8038 } 8039 8040 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 8041 SelectionDAG &DAG) { 8042 const auto &TLI = DAG.getTargetLoweringInfo(); 8043 8044 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 8045 "Custom lowering is MSVCRT specific!"); 8046 8047 SDLoc dl(Op); 8048 SDValue Val = Op.getOperand(0); 8049 MVT Ty = Val->getSimpleValueType(0); 8050 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 8051 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 8052 TLI.getPointerTy(DAG.getDataLayout())); 8053 8054 TargetLowering::ArgListTy Args; 8055 TargetLowering::ArgListEntry Entry; 8056 8057 Entry.Node = Val; 8058 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8059 Entry.IsZExt = true; 8060 Args.push_back(Entry); 8061 8062 Entry.Node = Exponent; 8063 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 8064 Entry.IsZExt = true; 8065 Args.push_back(Entry); 8066 8067 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8068 8069 // In the in-chain to the call is the entry node If we are emitting a 8070 // tailcall, the chain will be mutated if the node has a non-entry input 8071 // chain. 8072 SDValue InChain = DAG.getEntryNode(); 8073 SDValue TCChain = InChain; 8074 8075 const Function &F = DAG.getMachineFunction().getFunction(); 8076 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8077 F.getReturnType() == LCRTy; 8078 if (IsTC) 8079 InChain = TCChain; 8080 8081 TargetLowering::CallLoweringInfo CLI(DAG); 8082 CLI.setDebugLoc(dl) 8083 .setChain(InChain) 8084 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8085 .setTailCall(IsTC); 8086 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8087 8088 // Return the chain (the DAG root) if it is a tail call 8089 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8090 } 8091 8092 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8093 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8094 switch (Op.getOpcode()) { 8095 default: llvm_unreachable("Don't know how to custom lower this!"); 8096 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8097 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8098 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8099 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8100 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8101 case ISD::SELECT: return LowerSELECT(Op, DAG); 8102 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8103 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8104 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8105 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8106 case ISD::VASTART: return LowerVASTART(Op, DAG); 8107 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8108 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8109 case ISD::SINT_TO_FP: 8110 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8111 case ISD::FP_TO_SINT: 8112 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8113 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8114 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8115 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8116 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8117 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8118 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8119 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8120 Subtarget); 8121 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8122 case ISD::SHL: 8123 case ISD::SRL: 8124 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8125 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8126 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8127 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8128 case ISD::SRL_PARTS: 8129 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8130 case ISD::CTTZ: 8131 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8132 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8133 case ISD::SETCC: return LowerVSETCC(Op, DAG); 8134 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8135 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8136 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8137 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 8138 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8139 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8140 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 8141 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8142 case ISD::MUL: return LowerMUL(Op, DAG); 8143 case ISD::SDIV: 8144 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8145 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8146 return LowerSDIV(Op, DAG); 8147 case ISD::UDIV: 8148 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8149 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8150 return LowerUDIV(Op, DAG); 8151 case ISD::ADDC: 8152 case ISD::ADDE: 8153 case ISD::SUBC: 8154 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 8155 case ISD::ADDCARRY: 8156 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8157 case ISD::SADDO: 8158 case ISD::SSUBO: 8159 return LowerSignedALUO(Op, DAG); 8160 case ISD::UADDO: 8161 case ISD::USUBO: 8162 return LowerUnsignedALUO(Op, DAG); 8163 case ISD::ATOMIC_LOAD: 8164 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8165 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8166 case ISD::SDIVREM: 8167 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8168 case ISD::DYNAMIC_STACKALLOC: 8169 if (Subtarget->isTargetWindows()) 8170 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8171 llvm_unreachable("Don't know how to custom lower this!"); 8172 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8173 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8174 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8175 case ARMISD::WIN__DBZCHK: return SDValue(); 8176 } 8177 } 8178 8179 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8180 SelectionDAG &DAG) { 8181 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8182 unsigned Opc = 0; 8183 if (IntNo == Intrinsic::arm_smlald) 8184 Opc = ARMISD::SMLALD; 8185 else if (IntNo == Intrinsic::arm_smlaldx) 8186 Opc = ARMISD::SMLALDX; 8187 else if (IntNo == Intrinsic::arm_smlsld) 8188 Opc = ARMISD::SMLSLD; 8189 else if (IntNo == Intrinsic::arm_smlsldx) 8190 Opc = ARMISD::SMLSLDX; 8191 else 8192 return; 8193 8194 SDLoc dl(N); 8195 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8196 N->getOperand(3), 8197 DAG.getConstant(0, dl, MVT::i32)); 8198 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8199 N->getOperand(3), 8200 DAG.getConstant(1, dl, MVT::i32)); 8201 8202 SDValue LongMul = DAG.getNode(Opc, dl, 8203 DAG.getVTList(MVT::i32, MVT::i32), 8204 N->getOperand(1), N->getOperand(2), 8205 Lo, Hi); 8206 Results.push_back(LongMul.getValue(0)); 8207 Results.push_back(LongMul.getValue(1)); 8208 } 8209 8210 /// ReplaceNodeResults - Replace the results of node with an illegal result 8211 /// type with new values built out of custom code. 8212 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8213 SmallVectorImpl<SDValue> &Results, 8214 SelectionDAG &DAG) const { 8215 SDValue Res; 8216 switch (N->getOpcode()) { 8217 default: 8218 llvm_unreachable("Don't know how to custom expand this!"); 8219 case ISD::READ_REGISTER: 8220 ExpandREAD_REGISTER(N, Results, DAG); 8221 break; 8222 case ISD::BITCAST: 8223 Res = ExpandBITCAST(N, DAG, Subtarget); 8224 break; 8225 case ISD::SRL: 8226 case ISD::SRA: 8227 Res = Expand64BitShift(N, DAG, Subtarget); 8228 break; 8229 case ISD::SREM: 8230 case ISD::UREM: 8231 Res = LowerREM(N, DAG); 8232 break; 8233 case ISD::SDIVREM: 8234 case ISD::UDIVREM: 8235 Res = LowerDivRem(SDValue(N, 0), DAG); 8236 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8237 Results.push_back(Res.getValue(0)); 8238 Results.push_back(Res.getValue(1)); 8239 return; 8240 case ISD::READCYCLECOUNTER: 8241 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8242 return; 8243 case ISD::UDIV: 8244 case ISD::SDIV: 8245 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8246 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8247 Results); 8248 case ISD::ATOMIC_CMP_SWAP: 8249 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8250 return; 8251 case ISD::INTRINSIC_WO_CHAIN: 8252 return ReplaceLongIntrinsic(N, Results, DAG); 8253 } 8254 if (Res.getNode()) 8255 Results.push_back(Res); 8256 } 8257 8258 //===----------------------------------------------------------------------===// 8259 // ARM Scheduler Hooks 8260 //===----------------------------------------------------------------------===// 8261 8262 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8263 /// registers the function context. 8264 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8265 MachineBasicBlock *MBB, 8266 MachineBasicBlock *DispatchBB, 8267 int FI) const { 8268 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8269 "ROPI/RWPI not currently supported with SjLj"); 8270 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8271 DebugLoc dl = MI.getDebugLoc(); 8272 MachineFunction *MF = MBB->getParent(); 8273 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8274 MachineConstantPool *MCP = MF->getConstantPool(); 8275 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8276 const Function &F = MF->getFunction(); 8277 8278 bool isThumb = Subtarget->isThumb(); 8279 bool isThumb2 = Subtarget->isThumb2(); 8280 8281 unsigned PCLabelId = AFI->createPICLabelUId(); 8282 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8283 ARMConstantPoolValue *CPV = 8284 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8285 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8286 8287 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8288 : &ARM::GPRRegClass; 8289 8290 // Grab constant pool and fixed stack memory operands. 8291 MachineMemOperand *CPMMO = 8292 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8293 MachineMemOperand::MOLoad, 4, 4); 8294 8295 MachineMemOperand *FIMMOSt = 8296 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8297 MachineMemOperand::MOStore, 4, 4); 8298 8299 // Load the address of the dispatch MBB into the jump buffer. 8300 if (isThumb2) { 8301 // Incoming value: jbuf 8302 // ldr.n r5, LCPI1_1 8303 // orr r5, r5, #1 8304 // add r5, pc 8305 // str r5, [$jbuf, #+4] ; &jbuf[1] 8306 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8307 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8308 .addConstantPoolIndex(CPI) 8309 .addMemOperand(CPMMO) 8310 .add(predOps(ARMCC::AL)); 8311 // Set the low bit because of thumb mode. 8312 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8313 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8314 .addReg(NewVReg1, RegState::Kill) 8315 .addImm(0x01) 8316 .add(predOps(ARMCC::AL)) 8317 .add(condCodeOp()); 8318 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8319 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8320 .addReg(NewVReg2, RegState::Kill) 8321 .addImm(PCLabelId); 8322 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8323 .addReg(NewVReg3, RegState::Kill) 8324 .addFrameIndex(FI) 8325 .addImm(36) // &jbuf[1] :: pc 8326 .addMemOperand(FIMMOSt) 8327 .add(predOps(ARMCC::AL)); 8328 } else if (isThumb) { 8329 // Incoming value: jbuf 8330 // ldr.n r1, LCPI1_4 8331 // add r1, pc 8332 // mov r2, #1 8333 // orrs r1, r2 8334 // add r2, $jbuf, #+4 ; &jbuf[1] 8335 // str r1, [r2] 8336 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8337 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8338 .addConstantPoolIndex(CPI) 8339 .addMemOperand(CPMMO) 8340 .add(predOps(ARMCC::AL)); 8341 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8342 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8343 .addReg(NewVReg1, RegState::Kill) 8344 .addImm(PCLabelId); 8345 // Set the low bit because of thumb mode. 8346 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8347 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8348 .addReg(ARM::CPSR, RegState::Define) 8349 .addImm(1) 8350 .add(predOps(ARMCC::AL)); 8351 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8352 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8353 .addReg(ARM::CPSR, RegState::Define) 8354 .addReg(NewVReg2, RegState::Kill) 8355 .addReg(NewVReg3, RegState::Kill) 8356 .add(predOps(ARMCC::AL)); 8357 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8358 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8359 .addFrameIndex(FI) 8360 .addImm(36); // &jbuf[1] :: pc 8361 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8362 .addReg(NewVReg4, RegState::Kill) 8363 .addReg(NewVReg5, RegState::Kill) 8364 .addImm(0) 8365 .addMemOperand(FIMMOSt) 8366 .add(predOps(ARMCC::AL)); 8367 } else { 8368 // Incoming value: jbuf 8369 // ldr r1, LCPI1_1 8370 // add r1, pc, r1 8371 // str r1, [$jbuf, #+4] ; &jbuf[1] 8372 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8373 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8374 .addConstantPoolIndex(CPI) 8375 .addImm(0) 8376 .addMemOperand(CPMMO) 8377 .add(predOps(ARMCC::AL)); 8378 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8379 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8380 .addReg(NewVReg1, RegState::Kill) 8381 .addImm(PCLabelId) 8382 .add(predOps(ARMCC::AL)); 8383 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8384 .addReg(NewVReg2, RegState::Kill) 8385 .addFrameIndex(FI) 8386 .addImm(36) // &jbuf[1] :: pc 8387 .addMemOperand(FIMMOSt) 8388 .add(predOps(ARMCC::AL)); 8389 } 8390 } 8391 8392 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8393 MachineBasicBlock *MBB) const { 8394 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8395 DebugLoc dl = MI.getDebugLoc(); 8396 MachineFunction *MF = MBB->getParent(); 8397 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8398 MachineFrameInfo &MFI = MF->getFrameInfo(); 8399 int FI = MFI.getFunctionContextIndex(); 8400 8401 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8402 : &ARM::GPRnopcRegClass; 8403 8404 // Get a mapping of the call site numbers to all of the landing pads they're 8405 // associated with. 8406 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8407 unsigned MaxCSNum = 0; 8408 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8409 ++BB) { 8410 if (!BB->isEHPad()) continue; 8411 8412 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8413 // pad. 8414 for (MachineBasicBlock::iterator 8415 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8416 if (!II->isEHLabel()) continue; 8417 8418 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8419 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8420 8421 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8422 for (SmallVectorImpl<unsigned>::iterator 8423 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8424 CSI != CSE; ++CSI) { 8425 CallSiteNumToLPad[*CSI].push_back(&*BB); 8426 MaxCSNum = std::max(MaxCSNum, *CSI); 8427 } 8428 break; 8429 } 8430 } 8431 8432 // Get an ordered list of the machine basic blocks for the jump table. 8433 std::vector<MachineBasicBlock*> LPadList; 8434 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8435 LPadList.reserve(CallSiteNumToLPad.size()); 8436 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8437 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8438 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8439 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8440 LPadList.push_back(*II); 8441 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8442 } 8443 } 8444 8445 assert(!LPadList.empty() && 8446 "No landing pad destinations for the dispatch jump table!"); 8447 8448 // Create the jump table and associated information. 8449 MachineJumpTableInfo *JTI = 8450 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8451 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8452 8453 // Create the MBBs for the dispatch code. 8454 8455 // Shove the dispatch's address into the return slot in the function context. 8456 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8457 DispatchBB->setIsEHPad(); 8458 8459 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8460 unsigned trap_opcode; 8461 if (Subtarget->isThumb()) 8462 trap_opcode = ARM::tTRAP; 8463 else 8464 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8465 8466 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8467 DispatchBB->addSuccessor(TrapBB); 8468 8469 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8470 DispatchBB->addSuccessor(DispContBB); 8471 8472 // Insert and MBBs. 8473 MF->insert(MF->end(), DispatchBB); 8474 MF->insert(MF->end(), DispContBB); 8475 MF->insert(MF->end(), TrapBB); 8476 8477 // Insert code into the entry block that creates and registers the function 8478 // context. 8479 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8480 8481 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8482 MachinePointerInfo::getFixedStack(*MF, FI), 8483 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8484 8485 MachineInstrBuilder MIB; 8486 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8487 8488 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8489 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8490 8491 // Add a register mask with no preserved registers. This results in all 8492 // registers being marked as clobbered. This can't work if the dispatch block 8493 // is in a Thumb1 function and is linked with ARM code which uses the FP 8494 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8495 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8496 8497 bool IsPositionIndependent = isPositionIndependent(); 8498 unsigned NumLPads = LPadList.size(); 8499 if (Subtarget->isThumb2()) { 8500 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8501 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8502 .addFrameIndex(FI) 8503 .addImm(4) 8504 .addMemOperand(FIMMOLd) 8505 .add(predOps(ARMCC::AL)); 8506 8507 if (NumLPads < 256) { 8508 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8509 .addReg(NewVReg1) 8510 .addImm(LPadList.size()) 8511 .add(predOps(ARMCC::AL)); 8512 } else { 8513 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8514 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8515 .addImm(NumLPads & 0xFFFF) 8516 .add(predOps(ARMCC::AL)); 8517 8518 unsigned VReg2 = VReg1; 8519 if ((NumLPads & 0xFFFF0000) != 0) { 8520 VReg2 = MRI->createVirtualRegister(TRC); 8521 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8522 .addReg(VReg1) 8523 .addImm(NumLPads >> 16) 8524 .add(predOps(ARMCC::AL)); 8525 } 8526 8527 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8528 .addReg(NewVReg1) 8529 .addReg(VReg2) 8530 .add(predOps(ARMCC::AL)); 8531 } 8532 8533 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8534 .addMBB(TrapBB) 8535 .addImm(ARMCC::HI) 8536 .addReg(ARM::CPSR); 8537 8538 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8539 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8540 .addJumpTableIndex(MJTI) 8541 .add(predOps(ARMCC::AL)); 8542 8543 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8544 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8545 .addReg(NewVReg3, RegState::Kill) 8546 .addReg(NewVReg1) 8547 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8548 .add(predOps(ARMCC::AL)) 8549 .add(condCodeOp()); 8550 8551 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8552 .addReg(NewVReg4, RegState::Kill) 8553 .addReg(NewVReg1) 8554 .addJumpTableIndex(MJTI); 8555 } else if (Subtarget->isThumb()) { 8556 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8557 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8558 .addFrameIndex(FI) 8559 .addImm(1) 8560 .addMemOperand(FIMMOLd) 8561 .add(predOps(ARMCC::AL)); 8562 8563 if (NumLPads < 256) { 8564 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8565 .addReg(NewVReg1) 8566 .addImm(NumLPads) 8567 .add(predOps(ARMCC::AL)); 8568 } else { 8569 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8570 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8571 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8572 8573 // MachineConstantPool wants an explicit alignment. 8574 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8575 if (Align == 0) 8576 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8577 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8578 8579 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8580 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8581 .addReg(VReg1, RegState::Define) 8582 .addConstantPoolIndex(Idx) 8583 .add(predOps(ARMCC::AL)); 8584 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8585 .addReg(NewVReg1) 8586 .addReg(VReg1) 8587 .add(predOps(ARMCC::AL)); 8588 } 8589 8590 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8591 .addMBB(TrapBB) 8592 .addImm(ARMCC::HI) 8593 .addReg(ARM::CPSR); 8594 8595 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8596 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8597 .addReg(ARM::CPSR, RegState::Define) 8598 .addReg(NewVReg1) 8599 .addImm(2) 8600 .add(predOps(ARMCC::AL)); 8601 8602 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8603 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8604 .addJumpTableIndex(MJTI) 8605 .add(predOps(ARMCC::AL)); 8606 8607 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8608 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8609 .addReg(ARM::CPSR, RegState::Define) 8610 .addReg(NewVReg2, RegState::Kill) 8611 .addReg(NewVReg3) 8612 .add(predOps(ARMCC::AL)); 8613 8614 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8615 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8616 8617 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8618 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8619 .addReg(NewVReg4, RegState::Kill) 8620 .addImm(0) 8621 .addMemOperand(JTMMOLd) 8622 .add(predOps(ARMCC::AL)); 8623 8624 unsigned NewVReg6 = NewVReg5; 8625 if (IsPositionIndependent) { 8626 NewVReg6 = MRI->createVirtualRegister(TRC); 8627 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8628 .addReg(ARM::CPSR, RegState::Define) 8629 .addReg(NewVReg5, RegState::Kill) 8630 .addReg(NewVReg3) 8631 .add(predOps(ARMCC::AL)); 8632 } 8633 8634 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8635 .addReg(NewVReg6, RegState::Kill) 8636 .addJumpTableIndex(MJTI); 8637 } else { 8638 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8639 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8640 .addFrameIndex(FI) 8641 .addImm(4) 8642 .addMemOperand(FIMMOLd) 8643 .add(predOps(ARMCC::AL)); 8644 8645 if (NumLPads < 256) { 8646 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8647 .addReg(NewVReg1) 8648 .addImm(NumLPads) 8649 .add(predOps(ARMCC::AL)); 8650 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8651 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8652 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8653 .addImm(NumLPads & 0xFFFF) 8654 .add(predOps(ARMCC::AL)); 8655 8656 unsigned VReg2 = VReg1; 8657 if ((NumLPads & 0xFFFF0000) != 0) { 8658 VReg2 = MRI->createVirtualRegister(TRC); 8659 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8660 .addReg(VReg1) 8661 .addImm(NumLPads >> 16) 8662 .add(predOps(ARMCC::AL)); 8663 } 8664 8665 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8666 .addReg(NewVReg1) 8667 .addReg(VReg2) 8668 .add(predOps(ARMCC::AL)); 8669 } else { 8670 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8671 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8672 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8673 8674 // MachineConstantPool wants an explicit alignment. 8675 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8676 if (Align == 0) 8677 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8678 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8679 8680 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8681 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8682 .addReg(VReg1, RegState::Define) 8683 .addConstantPoolIndex(Idx) 8684 .addImm(0) 8685 .add(predOps(ARMCC::AL)); 8686 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8687 .addReg(NewVReg1) 8688 .addReg(VReg1, RegState::Kill) 8689 .add(predOps(ARMCC::AL)); 8690 } 8691 8692 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8693 .addMBB(TrapBB) 8694 .addImm(ARMCC::HI) 8695 .addReg(ARM::CPSR); 8696 8697 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8698 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8699 .addReg(NewVReg1) 8700 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8701 .add(predOps(ARMCC::AL)) 8702 .add(condCodeOp()); 8703 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8704 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8705 .addJumpTableIndex(MJTI) 8706 .add(predOps(ARMCC::AL)); 8707 8708 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8709 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8710 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8711 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8712 .addReg(NewVReg3, RegState::Kill) 8713 .addReg(NewVReg4) 8714 .addImm(0) 8715 .addMemOperand(JTMMOLd) 8716 .add(predOps(ARMCC::AL)); 8717 8718 if (IsPositionIndependent) { 8719 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8720 .addReg(NewVReg5, RegState::Kill) 8721 .addReg(NewVReg4) 8722 .addJumpTableIndex(MJTI); 8723 } else { 8724 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8725 .addReg(NewVReg5, RegState::Kill) 8726 .addJumpTableIndex(MJTI); 8727 } 8728 } 8729 8730 // Add the jump table entries as successors to the MBB. 8731 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8732 for (std::vector<MachineBasicBlock*>::iterator 8733 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8734 MachineBasicBlock *CurMBB = *I; 8735 if (SeenMBBs.insert(CurMBB).second) 8736 DispContBB->addSuccessor(CurMBB); 8737 } 8738 8739 // N.B. the order the invoke BBs are processed in doesn't matter here. 8740 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8741 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8742 for (MachineBasicBlock *BB : InvokeBBs) { 8743 8744 // Remove the landing pad successor from the invoke block and replace it 8745 // with the new dispatch block. 8746 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8747 BB->succ_end()); 8748 while (!Successors.empty()) { 8749 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8750 if (SMBB->isEHPad()) { 8751 BB->removeSuccessor(SMBB); 8752 MBBLPads.push_back(SMBB); 8753 } 8754 } 8755 8756 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8757 BB->normalizeSuccProbs(); 8758 8759 // Find the invoke call and mark all of the callee-saved registers as 8760 // 'implicit defined' so that they're spilled. This prevents code from 8761 // moving instructions to before the EH block, where they will never be 8762 // executed. 8763 for (MachineBasicBlock::reverse_iterator 8764 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8765 if (!II->isCall()) continue; 8766 8767 DenseMap<unsigned, bool> DefRegs; 8768 for (MachineInstr::mop_iterator 8769 OI = II->operands_begin(), OE = II->operands_end(); 8770 OI != OE; ++OI) { 8771 if (!OI->isReg()) continue; 8772 DefRegs[OI->getReg()] = true; 8773 } 8774 8775 MachineInstrBuilder MIB(*MF, &*II); 8776 8777 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8778 unsigned Reg = SavedRegs[i]; 8779 if (Subtarget->isThumb2() && 8780 !ARM::tGPRRegClass.contains(Reg) && 8781 !ARM::hGPRRegClass.contains(Reg)) 8782 continue; 8783 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8784 continue; 8785 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8786 continue; 8787 if (!DefRegs[Reg]) 8788 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8789 } 8790 8791 break; 8792 } 8793 } 8794 8795 // Mark all former landing pads as non-landing pads. The dispatch is the only 8796 // landing pad now. 8797 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8798 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8799 (*I)->setIsEHPad(false); 8800 8801 // The instruction is gone now. 8802 MI.eraseFromParent(); 8803 } 8804 8805 static 8806 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8807 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8808 E = MBB->succ_end(); I != E; ++I) 8809 if (*I != Succ) 8810 return *I; 8811 llvm_unreachable("Expecting a BB with two successors!"); 8812 } 8813 8814 /// Return the load opcode for a given load size. If load size >= 8, 8815 /// neon opcode will be returned. 8816 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8817 if (LdSize >= 8) 8818 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8819 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8820 if (IsThumb1) 8821 return LdSize == 4 ? ARM::tLDRi 8822 : LdSize == 2 ? ARM::tLDRHi 8823 : LdSize == 1 ? ARM::tLDRBi : 0; 8824 if (IsThumb2) 8825 return LdSize == 4 ? ARM::t2LDR_POST 8826 : LdSize == 2 ? ARM::t2LDRH_POST 8827 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8828 return LdSize == 4 ? ARM::LDR_POST_IMM 8829 : LdSize == 2 ? ARM::LDRH_POST 8830 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8831 } 8832 8833 /// Return the store opcode for a given store size. If store size >= 8, 8834 /// neon opcode will be returned. 8835 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8836 if (StSize >= 8) 8837 return StSize == 16 ? ARM::VST1q32wb_fixed 8838 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8839 if (IsThumb1) 8840 return StSize == 4 ? ARM::tSTRi 8841 : StSize == 2 ? ARM::tSTRHi 8842 : StSize == 1 ? ARM::tSTRBi : 0; 8843 if (IsThumb2) 8844 return StSize == 4 ? ARM::t2STR_POST 8845 : StSize == 2 ? ARM::t2STRH_POST 8846 : StSize == 1 ? ARM::t2STRB_POST : 0; 8847 return StSize == 4 ? ARM::STR_POST_IMM 8848 : StSize == 2 ? ARM::STRH_POST 8849 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8850 } 8851 8852 /// Emit a post-increment load operation with given size. The instructions 8853 /// will be added to BB at Pos. 8854 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8855 const TargetInstrInfo *TII, const DebugLoc &dl, 8856 unsigned LdSize, unsigned Data, unsigned AddrIn, 8857 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8858 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8859 assert(LdOpc != 0 && "Should have a load opcode"); 8860 if (LdSize >= 8) { 8861 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8862 .addReg(AddrOut, RegState::Define) 8863 .addReg(AddrIn) 8864 .addImm(0) 8865 .add(predOps(ARMCC::AL)); 8866 } else if (IsThumb1) { 8867 // load + update AddrIn 8868 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8869 .addReg(AddrIn) 8870 .addImm(0) 8871 .add(predOps(ARMCC::AL)); 8872 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8873 .add(t1CondCodeOp()) 8874 .addReg(AddrIn) 8875 .addImm(LdSize) 8876 .add(predOps(ARMCC::AL)); 8877 } else if (IsThumb2) { 8878 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8879 .addReg(AddrOut, RegState::Define) 8880 .addReg(AddrIn) 8881 .addImm(LdSize) 8882 .add(predOps(ARMCC::AL)); 8883 } else { // arm 8884 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8885 .addReg(AddrOut, RegState::Define) 8886 .addReg(AddrIn) 8887 .addReg(0) 8888 .addImm(LdSize) 8889 .add(predOps(ARMCC::AL)); 8890 } 8891 } 8892 8893 /// Emit a post-increment store operation with given size. The instructions 8894 /// will be added to BB at Pos. 8895 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8896 const TargetInstrInfo *TII, const DebugLoc &dl, 8897 unsigned StSize, unsigned Data, unsigned AddrIn, 8898 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8899 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8900 assert(StOpc != 0 && "Should have a store opcode"); 8901 if (StSize >= 8) { 8902 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8903 .addReg(AddrIn) 8904 .addImm(0) 8905 .addReg(Data) 8906 .add(predOps(ARMCC::AL)); 8907 } else if (IsThumb1) { 8908 // store + update AddrIn 8909 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8910 .addReg(Data) 8911 .addReg(AddrIn) 8912 .addImm(0) 8913 .add(predOps(ARMCC::AL)); 8914 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8915 .add(t1CondCodeOp()) 8916 .addReg(AddrIn) 8917 .addImm(StSize) 8918 .add(predOps(ARMCC::AL)); 8919 } else if (IsThumb2) { 8920 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8921 .addReg(Data) 8922 .addReg(AddrIn) 8923 .addImm(StSize) 8924 .add(predOps(ARMCC::AL)); 8925 } else { // arm 8926 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8927 .addReg(Data) 8928 .addReg(AddrIn) 8929 .addReg(0) 8930 .addImm(StSize) 8931 .add(predOps(ARMCC::AL)); 8932 } 8933 } 8934 8935 MachineBasicBlock * 8936 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8937 MachineBasicBlock *BB) const { 8938 // This pseudo instruction has 3 operands: dst, src, size 8939 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8940 // Otherwise, we will generate unrolled scalar copies. 8941 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8942 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8943 MachineFunction::iterator It = ++BB->getIterator(); 8944 8945 unsigned dest = MI.getOperand(0).getReg(); 8946 unsigned src = MI.getOperand(1).getReg(); 8947 unsigned SizeVal = MI.getOperand(2).getImm(); 8948 unsigned Align = MI.getOperand(3).getImm(); 8949 DebugLoc dl = MI.getDebugLoc(); 8950 8951 MachineFunction *MF = BB->getParent(); 8952 MachineRegisterInfo &MRI = MF->getRegInfo(); 8953 unsigned UnitSize = 0; 8954 const TargetRegisterClass *TRC = nullptr; 8955 const TargetRegisterClass *VecTRC = nullptr; 8956 8957 bool IsThumb1 = Subtarget->isThumb1Only(); 8958 bool IsThumb2 = Subtarget->isThumb2(); 8959 bool IsThumb = Subtarget->isThumb(); 8960 8961 if (Align & 1) { 8962 UnitSize = 1; 8963 } else if (Align & 2) { 8964 UnitSize = 2; 8965 } else { 8966 // Check whether we can use NEON instructions. 8967 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 8968 Subtarget->hasNEON()) { 8969 if ((Align % 16 == 0) && SizeVal >= 16) 8970 UnitSize = 16; 8971 else if ((Align % 8 == 0) && SizeVal >= 8) 8972 UnitSize = 8; 8973 } 8974 // Can't use NEON instructions. 8975 if (UnitSize == 0) 8976 UnitSize = 4; 8977 } 8978 8979 // Select the correct opcode and register class for unit size load/store 8980 bool IsNeon = UnitSize >= 8; 8981 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8982 if (IsNeon) 8983 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8984 : UnitSize == 8 ? &ARM::DPRRegClass 8985 : nullptr; 8986 8987 unsigned BytesLeft = SizeVal % UnitSize; 8988 unsigned LoopSize = SizeVal - BytesLeft; 8989 8990 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8991 // Use LDR and STR to copy. 8992 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8993 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8994 unsigned srcIn = src; 8995 unsigned destIn = dest; 8996 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8997 unsigned srcOut = MRI.createVirtualRegister(TRC); 8998 unsigned destOut = MRI.createVirtualRegister(TRC); 8999 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9000 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 9001 IsThumb1, IsThumb2); 9002 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 9003 IsThumb1, IsThumb2); 9004 srcIn = srcOut; 9005 destIn = destOut; 9006 } 9007 9008 // Handle the leftover bytes with LDRB and STRB. 9009 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 9010 // [destOut] = STRB_POST(scratch, destIn, 1) 9011 for (unsigned i = 0; i < BytesLeft; i++) { 9012 unsigned srcOut = MRI.createVirtualRegister(TRC); 9013 unsigned destOut = MRI.createVirtualRegister(TRC); 9014 unsigned scratch = MRI.createVirtualRegister(TRC); 9015 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 9016 IsThumb1, IsThumb2); 9017 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 9018 IsThumb1, IsThumb2); 9019 srcIn = srcOut; 9020 destIn = destOut; 9021 } 9022 MI.eraseFromParent(); // The instruction is gone now. 9023 return BB; 9024 } 9025 9026 // Expand the pseudo op to a loop. 9027 // thisMBB: 9028 // ... 9029 // movw varEnd, # --> with thumb2 9030 // movt varEnd, # 9031 // ldrcp varEnd, idx --> without thumb2 9032 // fallthrough --> loopMBB 9033 // loopMBB: 9034 // PHI varPhi, varEnd, varLoop 9035 // PHI srcPhi, src, srcLoop 9036 // PHI destPhi, dst, destLoop 9037 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9038 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 9039 // subs varLoop, varPhi, #UnitSize 9040 // bne loopMBB 9041 // fallthrough --> exitMBB 9042 // exitMBB: 9043 // epilogue to handle left-over bytes 9044 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9045 // [destOut] = STRB_POST(scratch, destLoop, 1) 9046 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9047 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9048 MF->insert(It, loopMBB); 9049 MF->insert(It, exitMBB); 9050 9051 // Transfer the remainder of BB and its successor edges to exitMBB. 9052 exitMBB->splice(exitMBB->begin(), BB, 9053 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9054 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9055 9056 // Load an immediate to varEnd. 9057 unsigned varEnd = MRI.createVirtualRegister(TRC); 9058 if (Subtarget->useMovt(*MF)) { 9059 unsigned Vtmp = varEnd; 9060 if ((LoopSize & 0xFFFF0000) != 0) 9061 Vtmp = MRI.createVirtualRegister(TRC); 9062 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 9063 .addImm(LoopSize & 0xFFFF) 9064 .add(predOps(ARMCC::AL)); 9065 9066 if ((LoopSize & 0xFFFF0000) != 0) 9067 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9068 .addReg(Vtmp) 9069 .addImm(LoopSize >> 16) 9070 .add(predOps(ARMCC::AL)); 9071 } else { 9072 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9073 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9074 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9075 9076 // MachineConstantPool wants an explicit alignment. 9077 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9078 if (Align == 0) 9079 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9080 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9081 9082 if (IsThumb) 9083 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9084 .addReg(varEnd, RegState::Define) 9085 .addConstantPoolIndex(Idx) 9086 .add(predOps(ARMCC::AL)); 9087 else 9088 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9089 .addReg(varEnd, RegState::Define) 9090 .addConstantPoolIndex(Idx) 9091 .addImm(0) 9092 .add(predOps(ARMCC::AL)); 9093 } 9094 BB->addSuccessor(loopMBB); 9095 9096 // Generate the loop body: 9097 // varPhi = PHI(varLoop, varEnd) 9098 // srcPhi = PHI(srcLoop, src) 9099 // destPhi = PHI(destLoop, dst) 9100 MachineBasicBlock *entryBB = BB; 9101 BB = loopMBB; 9102 unsigned varLoop = MRI.createVirtualRegister(TRC); 9103 unsigned varPhi = MRI.createVirtualRegister(TRC); 9104 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9105 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9106 unsigned destLoop = MRI.createVirtualRegister(TRC); 9107 unsigned destPhi = MRI.createVirtualRegister(TRC); 9108 9109 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9110 .addReg(varLoop).addMBB(loopMBB) 9111 .addReg(varEnd).addMBB(entryBB); 9112 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9113 .addReg(srcLoop).addMBB(loopMBB) 9114 .addReg(src).addMBB(entryBB); 9115 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9116 .addReg(destLoop).addMBB(loopMBB) 9117 .addReg(dest).addMBB(entryBB); 9118 9119 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9120 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9121 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9122 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9123 IsThumb1, IsThumb2); 9124 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9125 IsThumb1, IsThumb2); 9126 9127 // Decrement loop variable by UnitSize. 9128 if (IsThumb1) { 9129 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9130 .add(t1CondCodeOp()) 9131 .addReg(varPhi) 9132 .addImm(UnitSize) 9133 .add(predOps(ARMCC::AL)); 9134 } else { 9135 MachineInstrBuilder MIB = 9136 BuildMI(*BB, BB->end(), dl, 9137 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9138 MIB.addReg(varPhi) 9139 .addImm(UnitSize) 9140 .add(predOps(ARMCC::AL)) 9141 .add(condCodeOp()); 9142 MIB->getOperand(5).setReg(ARM::CPSR); 9143 MIB->getOperand(5).setIsDef(true); 9144 } 9145 BuildMI(*BB, BB->end(), dl, 9146 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9147 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9148 9149 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9150 BB->addSuccessor(loopMBB); 9151 BB->addSuccessor(exitMBB); 9152 9153 // Add epilogue to handle BytesLeft. 9154 BB = exitMBB; 9155 auto StartOfExit = exitMBB->begin(); 9156 9157 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9158 // [destOut] = STRB_POST(scratch, destLoop, 1) 9159 unsigned srcIn = srcLoop; 9160 unsigned destIn = destLoop; 9161 for (unsigned i = 0; i < BytesLeft; i++) { 9162 unsigned srcOut = MRI.createVirtualRegister(TRC); 9163 unsigned destOut = MRI.createVirtualRegister(TRC); 9164 unsigned scratch = MRI.createVirtualRegister(TRC); 9165 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9166 IsThumb1, IsThumb2); 9167 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9168 IsThumb1, IsThumb2); 9169 srcIn = srcOut; 9170 destIn = destOut; 9171 } 9172 9173 MI.eraseFromParent(); // The instruction is gone now. 9174 return BB; 9175 } 9176 9177 MachineBasicBlock * 9178 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9179 MachineBasicBlock *MBB) const { 9180 const TargetMachine &TM = getTargetMachine(); 9181 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9182 DebugLoc DL = MI.getDebugLoc(); 9183 9184 assert(Subtarget->isTargetWindows() && 9185 "__chkstk is only supported on Windows"); 9186 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9187 9188 // __chkstk takes the number of words to allocate on the stack in R4, and 9189 // returns the stack adjustment in number of bytes in R4. This will not 9190 // clober any other registers (other than the obvious lr). 9191 // 9192 // Although, technically, IP should be considered a register which may be 9193 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9194 // thumb-2 environment, so there is no interworking required. As a result, we 9195 // do not expect a veneer to be emitted by the linker, clobbering IP. 9196 // 9197 // Each module receives its own copy of __chkstk, so no import thunk is 9198 // required, again, ensuring that IP is not clobbered. 9199 // 9200 // Finally, although some linkers may theoretically provide a trampoline for 9201 // out of range calls (which is quite common due to a 32M range limitation of 9202 // branches for Thumb), we can generate the long-call version via 9203 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9204 // IP. 9205 9206 switch (TM.getCodeModel()) { 9207 case CodeModel::Small: 9208 case CodeModel::Medium: 9209 case CodeModel::Kernel: 9210 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9211 .add(predOps(ARMCC::AL)) 9212 .addExternalSymbol("__chkstk") 9213 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9214 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9215 .addReg(ARM::R12, 9216 RegState::Implicit | RegState::Define | RegState::Dead) 9217 .addReg(ARM::CPSR, 9218 RegState::Implicit | RegState::Define | RegState::Dead); 9219 break; 9220 case CodeModel::Large: { 9221 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9222 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9223 9224 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9225 .addExternalSymbol("__chkstk"); 9226 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9227 .add(predOps(ARMCC::AL)) 9228 .addReg(Reg, RegState::Kill) 9229 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9230 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9231 .addReg(ARM::R12, 9232 RegState::Implicit | RegState::Define | RegState::Dead) 9233 .addReg(ARM::CPSR, 9234 RegState::Implicit | RegState::Define | RegState::Dead); 9235 break; 9236 } 9237 } 9238 9239 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9240 .addReg(ARM::SP, RegState::Kill) 9241 .addReg(ARM::R4, RegState::Kill) 9242 .setMIFlags(MachineInstr::FrameSetup) 9243 .add(predOps(ARMCC::AL)) 9244 .add(condCodeOp()); 9245 9246 MI.eraseFromParent(); 9247 return MBB; 9248 } 9249 9250 MachineBasicBlock * 9251 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9252 MachineBasicBlock *MBB) const { 9253 DebugLoc DL = MI.getDebugLoc(); 9254 MachineFunction *MF = MBB->getParent(); 9255 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9256 9257 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9258 MF->insert(++MBB->getIterator(), ContBB); 9259 ContBB->splice(ContBB->begin(), MBB, 9260 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9261 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9262 MBB->addSuccessor(ContBB); 9263 9264 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9265 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9266 MF->push_back(TrapBB); 9267 MBB->addSuccessor(TrapBB); 9268 9269 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9270 .addReg(MI.getOperand(0).getReg()) 9271 .addImm(0) 9272 .add(predOps(ARMCC::AL)); 9273 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9274 .addMBB(TrapBB) 9275 .addImm(ARMCC::EQ) 9276 .addReg(ARM::CPSR); 9277 9278 MI.eraseFromParent(); 9279 return ContBB; 9280 } 9281 9282 MachineBasicBlock * 9283 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9284 MachineBasicBlock *BB) const { 9285 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9286 DebugLoc dl = MI.getDebugLoc(); 9287 bool isThumb2 = Subtarget->isThumb2(); 9288 switch (MI.getOpcode()) { 9289 default: { 9290 MI.print(errs()); 9291 llvm_unreachable("Unexpected instr type to insert"); 9292 } 9293 9294 // Thumb1 post-indexed loads are really just single-register LDMs. 9295 case ARM::tLDR_postidx: { 9296 MachineOperand Def(MI.getOperand(1)); 9297 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9298 .add(Def) // Rn_wb 9299 .add(MI.getOperand(2)) // Rn 9300 .add(MI.getOperand(3)) // PredImm 9301 .add(MI.getOperand(4)) // PredReg 9302 .add(MI.getOperand(0)); // Rt 9303 MI.eraseFromParent(); 9304 return BB; 9305 } 9306 9307 // The Thumb2 pre-indexed stores have the same MI operands, they just 9308 // define them differently in the .td files from the isel patterns, so 9309 // they need pseudos. 9310 case ARM::t2STR_preidx: 9311 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9312 return BB; 9313 case ARM::t2STRB_preidx: 9314 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9315 return BB; 9316 case ARM::t2STRH_preidx: 9317 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9318 return BB; 9319 9320 case ARM::STRi_preidx: 9321 case ARM::STRBi_preidx: { 9322 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9323 : ARM::STRB_PRE_IMM; 9324 // Decode the offset. 9325 unsigned Offset = MI.getOperand(4).getImm(); 9326 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9327 Offset = ARM_AM::getAM2Offset(Offset); 9328 if (isSub) 9329 Offset = -Offset; 9330 9331 MachineMemOperand *MMO = *MI.memoperands_begin(); 9332 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9333 .add(MI.getOperand(0)) // Rn_wb 9334 .add(MI.getOperand(1)) // Rt 9335 .add(MI.getOperand(2)) // Rn 9336 .addImm(Offset) // offset (skip GPR==zero_reg) 9337 .add(MI.getOperand(5)) // pred 9338 .add(MI.getOperand(6)) 9339 .addMemOperand(MMO); 9340 MI.eraseFromParent(); 9341 return BB; 9342 } 9343 case ARM::STRr_preidx: 9344 case ARM::STRBr_preidx: 9345 case ARM::STRH_preidx: { 9346 unsigned NewOpc; 9347 switch (MI.getOpcode()) { 9348 default: llvm_unreachable("unexpected opcode!"); 9349 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9350 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9351 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9352 } 9353 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9354 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9355 MIB.add(MI.getOperand(i)); 9356 MI.eraseFromParent(); 9357 return BB; 9358 } 9359 9360 case ARM::tMOVCCr_pseudo: { 9361 // To "insert" a SELECT_CC instruction, we actually have to insert the 9362 // diamond control-flow pattern. The incoming instruction knows the 9363 // destination vreg to set, the condition code register to branch on, the 9364 // true/false values to select between, and a branch opcode to use. 9365 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9366 MachineFunction::iterator It = ++BB->getIterator(); 9367 9368 // thisMBB: 9369 // ... 9370 // TrueVal = ... 9371 // cmpTY ccX, r1, r2 9372 // bCC copy1MBB 9373 // fallthrough --> copy0MBB 9374 MachineBasicBlock *thisMBB = BB; 9375 MachineFunction *F = BB->getParent(); 9376 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9377 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9378 F->insert(It, copy0MBB); 9379 F->insert(It, sinkMBB); 9380 9381 // Transfer the remainder of BB and its successor edges to sinkMBB. 9382 sinkMBB->splice(sinkMBB->begin(), BB, 9383 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9384 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9385 9386 BB->addSuccessor(copy0MBB); 9387 BB->addSuccessor(sinkMBB); 9388 9389 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9390 .addMBB(sinkMBB) 9391 .addImm(MI.getOperand(3).getImm()) 9392 .addReg(MI.getOperand(4).getReg()); 9393 9394 // copy0MBB: 9395 // %FalseValue = ... 9396 // # fallthrough to sinkMBB 9397 BB = copy0MBB; 9398 9399 // Update machine-CFG edges 9400 BB->addSuccessor(sinkMBB); 9401 9402 // sinkMBB: 9403 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9404 // ... 9405 BB = sinkMBB; 9406 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9407 .addReg(MI.getOperand(1).getReg()) 9408 .addMBB(copy0MBB) 9409 .addReg(MI.getOperand(2).getReg()) 9410 .addMBB(thisMBB); 9411 9412 MI.eraseFromParent(); // The pseudo instruction is gone now. 9413 return BB; 9414 } 9415 9416 case ARM::BCCi64: 9417 case ARM::BCCZi64: { 9418 // If there is an unconditional branch to the other successor, remove it. 9419 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9420 9421 // Compare both parts that make up the double comparison separately for 9422 // equality. 9423 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9424 9425 unsigned LHS1 = MI.getOperand(1).getReg(); 9426 unsigned LHS2 = MI.getOperand(2).getReg(); 9427 if (RHSisZero) { 9428 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9429 .addReg(LHS1) 9430 .addImm(0) 9431 .add(predOps(ARMCC::AL)); 9432 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9433 .addReg(LHS2).addImm(0) 9434 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9435 } else { 9436 unsigned RHS1 = MI.getOperand(3).getReg(); 9437 unsigned RHS2 = MI.getOperand(4).getReg(); 9438 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9439 .addReg(LHS1) 9440 .addReg(RHS1) 9441 .add(predOps(ARMCC::AL)); 9442 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9443 .addReg(LHS2).addReg(RHS2) 9444 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9445 } 9446 9447 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9448 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9449 if (MI.getOperand(0).getImm() == ARMCC::NE) 9450 std::swap(destMBB, exitMBB); 9451 9452 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9453 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9454 if (isThumb2) 9455 BuildMI(BB, dl, TII->get(ARM::t2B)) 9456 .addMBB(exitMBB) 9457 .add(predOps(ARMCC::AL)); 9458 else 9459 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9460 9461 MI.eraseFromParent(); // The pseudo instruction is gone now. 9462 return BB; 9463 } 9464 9465 case ARM::Int_eh_sjlj_setjmp: 9466 case ARM::Int_eh_sjlj_setjmp_nofp: 9467 case ARM::tInt_eh_sjlj_setjmp: 9468 case ARM::t2Int_eh_sjlj_setjmp: 9469 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9470 return BB; 9471 9472 case ARM::Int_eh_sjlj_setup_dispatch: 9473 EmitSjLjDispatchBlock(MI, BB); 9474 return BB; 9475 9476 case ARM::ABS: 9477 case ARM::t2ABS: { 9478 // To insert an ABS instruction, we have to insert the 9479 // diamond control-flow pattern. The incoming instruction knows the 9480 // source vreg to test against 0, the destination vreg to set, 9481 // the condition code register to branch on, the 9482 // true/false values to select between, and a branch opcode to use. 9483 // It transforms 9484 // V1 = ABS V0 9485 // into 9486 // V2 = MOVS V0 9487 // BCC (branch to SinkBB if V0 >= 0) 9488 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9489 // SinkBB: V1 = PHI(V2, V3) 9490 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9491 MachineFunction::iterator BBI = ++BB->getIterator(); 9492 MachineFunction *Fn = BB->getParent(); 9493 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9494 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9495 Fn->insert(BBI, RSBBB); 9496 Fn->insert(BBI, SinkBB); 9497 9498 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9499 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9500 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9501 bool isThumb2 = Subtarget->isThumb2(); 9502 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9503 // In Thumb mode S must not be specified if source register is the SP or 9504 // PC and if destination register is the SP, so restrict register class 9505 unsigned NewRsbDstReg = 9506 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9507 9508 // Transfer the remainder of BB and its successor edges to sinkMBB. 9509 SinkBB->splice(SinkBB->begin(), BB, 9510 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9511 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9512 9513 BB->addSuccessor(RSBBB); 9514 BB->addSuccessor(SinkBB); 9515 9516 // fall through to SinkMBB 9517 RSBBB->addSuccessor(SinkBB); 9518 9519 // insert a cmp at the end of BB 9520 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9521 .addReg(ABSSrcReg) 9522 .addImm(0) 9523 .add(predOps(ARMCC::AL)); 9524 9525 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9526 BuildMI(BB, dl, 9527 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9528 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9529 9530 // insert rsbri in RSBBB 9531 // Note: BCC and rsbri will be converted into predicated rsbmi 9532 // by if-conversion pass 9533 BuildMI(*RSBBB, RSBBB->begin(), dl, 9534 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9535 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9536 .addImm(0) 9537 .add(predOps(ARMCC::AL)) 9538 .add(condCodeOp()); 9539 9540 // insert PHI in SinkBB, 9541 // reuse ABSDstReg to not change uses of ABS instruction 9542 BuildMI(*SinkBB, SinkBB->begin(), dl, 9543 TII->get(ARM::PHI), ABSDstReg) 9544 .addReg(NewRsbDstReg).addMBB(RSBBB) 9545 .addReg(ABSSrcReg).addMBB(BB); 9546 9547 // remove ABS instruction 9548 MI.eraseFromParent(); 9549 9550 // return last added BB 9551 return SinkBB; 9552 } 9553 case ARM::COPY_STRUCT_BYVAL_I32: 9554 ++NumLoopByVals; 9555 return EmitStructByval(MI, BB); 9556 case ARM::WIN__CHKSTK: 9557 return EmitLowered__chkstk(MI, BB); 9558 case ARM::WIN__DBZCHK: 9559 return EmitLowered__dbzchk(MI, BB); 9560 } 9561 } 9562 9563 /// Attaches vregs to MEMCPY that it will use as scratch registers 9564 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9565 /// instead of as a custom inserter because we need the use list from the SDNode. 9566 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9567 MachineInstr &MI, const SDNode *Node) { 9568 bool isThumb1 = Subtarget->isThumb1Only(); 9569 9570 DebugLoc DL = MI.getDebugLoc(); 9571 MachineFunction *MF = MI.getParent()->getParent(); 9572 MachineRegisterInfo &MRI = MF->getRegInfo(); 9573 MachineInstrBuilder MIB(*MF, MI); 9574 9575 // If the new dst/src is unused mark it as dead. 9576 if (!Node->hasAnyUseOfValue(0)) { 9577 MI.getOperand(0).setIsDead(true); 9578 } 9579 if (!Node->hasAnyUseOfValue(1)) { 9580 MI.getOperand(1).setIsDead(true); 9581 } 9582 9583 // The MEMCPY both defines and kills the scratch registers. 9584 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9585 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9586 : &ARM::GPRRegClass); 9587 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9588 } 9589 } 9590 9591 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9592 SDNode *Node) const { 9593 if (MI.getOpcode() == ARM::MEMCPY) { 9594 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9595 return; 9596 } 9597 9598 const MCInstrDesc *MCID = &MI.getDesc(); 9599 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9600 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9601 // operand is still set to noreg. If needed, set the optional operand's 9602 // register to CPSR, and remove the redundant implicit def. 9603 // 9604 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9605 9606 // Rename pseudo opcodes. 9607 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9608 unsigned ccOutIdx; 9609 if (NewOpc) { 9610 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9611 MCID = &TII->get(NewOpc); 9612 9613 assert(MCID->getNumOperands() == 9614 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9615 && "converted opcode should be the same except for cc_out" 9616 " (and, on Thumb1, pred)"); 9617 9618 MI.setDesc(*MCID); 9619 9620 // Add the optional cc_out operand 9621 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9622 9623 // On Thumb1, move all input operands to the end, then add the predicate 9624 if (Subtarget->isThumb1Only()) { 9625 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9626 MI.addOperand(MI.getOperand(1)); 9627 MI.RemoveOperand(1); 9628 } 9629 9630 // Restore the ties 9631 for (unsigned i = MI.getNumOperands(); i--;) { 9632 const MachineOperand& op = MI.getOperand(i); 9633 if (op.isReg() && op.isUse()) { 9634 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9635 if (DefIdx != -1) 9636 MI.tieOperands(DefIdx, i); 9637 } 9638 } 9639 9640 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9641 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9642 ccOutIdx = 1; 9643 } else 9644 ccOutIdx = MCID->getNumOperands() - 1; 9645 } else 9646 ccOutIdx = MCID->getNumOperands() - 1; 9647 9648 // Any ARM instruction that sets the 's' bit should specify an optional 9649 // "cc_out" operand in the last operand position. 9650 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9651 assert(!NewOpc && "Optional cc_out operand required"); 9652 return; 9653 } 9654 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9655 // since we already have an optional CPSR def. 9656 bool definesCPSR = false; 9657 bool deadCPSR = false; 9658 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9659 ++i) { 9660 const MachineOperand &MO = MI.getOperand(i); 9661 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9662 definesCPSR = true; 9663 if (MO.isDead()) 9664 deadCPSR = true; 9665 MI.RemoveOperand(i); 9666 break; 9667 } 9668 } 9669 if (!definesCPSR) { 9670 assert(!NewOpc && "Optional cc_out operand required"); 9671 return; 9672 } 9673 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9674 if (deadCPSR) { 9675 assert(!MI.getOperand(ccOutIdx).getReg() && 9676 "expect uninitialized optional cc_out operand"); 9677 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9678 if (!Subtarget->isThumb1Only()) 9679 return; 9680 } 9681 9682 // If this instruction was defined with an optional CPSR def and its dag node 9683 // had a live implicit CPSR def, then activate the optional CPSR def. 9684 MachineOperand &MO = MI.getOperand(ccOutIdx); 9685 MO.setReg(ARM::CPSR); 9686 MO.setIsDef(true); 9687 } 9688 9689 //===----------------------------------------------------------------------===// 9690 // ARM Optimization Hooks 9691 //===----------------------------------------------------------------------===// 9692 9693 // Helper function that checks if N is a null or all ones constant. 9694 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9695 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9696 } 9697 9698 // Return true if N is conditionally 0 or all ones. 9699 // Detects these expressions where cc is an i1 value: 9700 // 9701 // (select cc 0, y) [AllOnes=0] 9702 // (select cc y, 0) [AllOnes=0] 9703 // (zext cc) [AllOnes=0] 9704 // (sext cc) [AllOnes=0/1] 9705 // (select cc -1, y) [AllOnes=1] 9706 // (select cc y, -1) [AllOnes=1] 9707 // 9708 // Invert is set when N is the null/all ones constant when CC is false. 9709 // OtherOp is set to the alternative value of N. 9710 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9711 SDValue &CC, bool &Invert, 9712 SDValue &OtherOp, 9713 SelectionDAG &DAG) { 9714 switch (N->getOpcode()) { 9715 default: return false; 9716 case ISD::SELECT: { 9717 CC = N->getOperand(0); 9718 SDValue N1 = N->getOperand(1); 9719 SDValue N2 = N->getOperand(2); 9720 if (isZeroOrAllOnes(N1, AllOnes)) { 9721 Invert = false; 9722 OtherOp = N2; 9723 return true; 9724 } 9725 if (isZeroOrAllOnes(N2, AllOnes)) { 9726 Invert = true; 9727 OtherOp = N1; 9728 return true; 9729 } 9730 return false; 9731 } 9732 case ISD::ZERO_EXTEND: 9733 // (zext cc) can never be the all ones value. 9734 if (AllOnes) 9735 return false; 9736 LLVM_FALLTHROUGH; 9737 case ISD::SIGN_EXTEND: { 9738 SDLoc dl(N); 9739 EVT VT = N->getValueType(0); 9740 CC = N->getOperand(0); 9741 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9742 return false; 9743 Invert = !AllOnes; 9744 if (AllOnes) 9745 // When looking for an AllOnes constant, N is an sext, and the 'other' 9746 // value is 0. 9747 OtherOp = DAG.getConstant(0, dl, VT); 9748 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9749 // When looking for a 0 constant, N can be zext or sext. 9750 OtherOp = DAG.getConstant(1, dl, VT); 9751 else 9752 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9753 VT); 9754 return true; 9755 } 9756 } 9757 } 9758 9759 // Combine a constant select operand into its use: 9760 // 9761 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9762 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9763 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9764 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9765 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9766 // 9767 // The transform is rejected if the select doesn't have a constant operand that 9768 // is null, or all ones when AllOnes is set. 9769 // 9770 // Also recognize sext/zext from i1: 9771 // 9772 // (add (zext cc), x) -> (select cc (add x, 1), x) 9773 // (add (sext cc), x) -> (select cc (add x, -1), x) 9774 // 9775 // These transformations eventually create predicated instructions. 9776 // 9777 // @param N The node to transform. 9778 // @param Slct The N operand that is a select. 9779 // @param OtherOp The other N operand (x above). 9780 // @param DCI Context. 9781 // @param AllOnes Require the select constant to be all ones instead of null. 9782 // @returns The new node, or SDValue() on failure. 9783 static 9784 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9785 TargetLowering::DAGCombinerInfo &DCI, 9786 bool AllOnes = false) { 9787 SelectionDAG &DAG = DCI.DAG; 9788 EVT VT = N->getValueType(0); 9789 SDValue NonConstantVal; 9790 SDValue CCOp; 9791 bool SwapSelectOps; 9792 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9793 NonConstantVal, DAG)) 9794 return SDValue(); 9795 9796 // Slct is now know to be the desired identity constant when CC is true. 9797 SDValue TrueVal = OtherOp; 9798 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9799 OtherOp, NonConstantVal); 9800 // Unless SwapSelectOps says CC should be false. 9801 if (SwapSelectOps) 9802 std::swap(TrueVal, FalseVal); 9803 9804 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9805 CCOp, TrueVal, FalseVal); 9806 } 9807 9808 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9809 static 9810 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9811 TargetLowering::DAGCombinerInfo &DCI) { 9812 SDValue N0 = N->getOperand(0); 9813 SDValue N1 = N->getOperand(1); 9814 if (N0.getNode()->hasOneUse()) 9815 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9816 return Result; 9817 if (N1.getNode()->hasOneUse()) 9818 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9819 return Result; 9820 return SDValue(); 9821 } 9822 9823 static bool IsVUZPShuffleNode(SDNode *N) { 9824 // VUZP shuffle node. 9825 if (N->getOpcode() == ARMISD::VUZP) 9826 return true; 9827 9828 // "VUZP" on i32 is an alias for VTRN. 9829 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9830 return true; 9831 9832 return false; 9833 } 9834 9835 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9836 TargetLowering::DAGCombinerInfo &DCI, 9837 const ARMSubtarget *Subtarget) { 9838 // Look for ADD(VUZP.0, VUZP.1). 9839 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9840 N0 == N1) 9841 return SDValue(); 9842 9843 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9844 if (!N->getValueType(0).is64BitVector()) 9845 return SDValue(); 9846 9847 // Generate vpadd. 9848 SelectionDAG &DAG = DCI.DAG; 9849 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9850 SDLoc dl(N); 9851 SDNode *Unzip = N0.getNode(); 9852 EVT VT = N->getValueType(0); 9853 9854 SmallVector<SDValue, 8> Ops; 9855 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9856 TLI.getPointerTy(DAG.getDataLayout()))); 9857 Ops.push_back(Unzip->getOperand(0)); 9858 Ops.push_back(Unzip->getOperand(1)); 9859 9860 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9861 } 9862 9863 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9864 TargetLowering::DAGCombinerInfo &DCI, 9865 const ARMSubtarget *Subtarget) { 9866 // Check for two extended operands. 9867 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9868 N1.getOpcode() == ISD::SIGN_EXTEND) && 9869 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9870 N1.getOpcode() == ISD::ZERO_EXTEND)) 9871 return SDValue(); 9872 9873 SDValue N00 = N0.getOperand(0); 9874 SDValue N10 = N1.getOperand(0); 9875 9876 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9877 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9878 N00 == N10) 9879 return SDValue(); 9880 9881 // We only recognize Q register paddl here; this can't be reached until 9882 // after type legalization. 9883 if (!N00.getValueType().is64BitVector() || 9884 !N0.getValueType().is128BitVector()) 9885 return SDValue(); 9886 9887 // Generate vpaddl. 9888 SelectionDAG &DAG = DCI.DAG; 9889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9890 SDLoc dl(N); 9891 EVT VT = N->getValueType(0); 9892 9893 SmallVector<SDValue, 8> Ops; 9894 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9895 unsigned Opcode; 9896 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9897 Opcode = Intrinsic::arm_neon_vpaddls; 9898 else 9899 Opcode = Intrinsic::arm_neon_vpaddlu; 9900 Ops.push_back(DAG.getConstant(Opcode, dl, 9901 TLI.getPointerTy(DAG.getDataLayout()))); 9902 EVT ElemTy = N00.getValueType().getVectorElementType(); 9903 unsigned NumElts = VT.getVectorNumElements(); 9904 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9905 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9906 N00.getOperand(0), N00.getOperand(1)); 9907 Ops.push_back(Concat); 9908 9909 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9910 } 9911 9912 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9913 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9914 // much easier to match. 9915 static SDValue 9916 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9917 TargetLowering::DAGCombinerInfo &DCI, 9918 const ARMSubtarget *Subtarget) { 9919 // Only perform optimization if after legalize, and if NEON is available. We 9920 // also expected both operands to be BUILD_VECTORs. 9921 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9922 || N0.getOpcode() != ISD::BUILD_VECTOR 9923 || N1.getOpcode() != ISD::BUILD_VECTOR) 9924 return SDValue(); 9925 9926 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9927 EVT VT = N->getValueType(0); 9928 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9929 return SDValue(); 9930 9931 // Check that the vector operands are of the right form. 9932 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9933 // operands, where N is the size of the formed vector. 9934 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9935 // index such that we have a pair wise add pattern. 9936 9937 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9938 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9939 return SDValue(); 9940 SDValue Vec = N0->getOperand(0)->getOperand(0); 9941 SDNode *V = Vec.getNode(); 9942 unsigned nextIndex = 0; 9943 9944 // For each operands to the ADD which are BUILD_VECTORs, 9945 // check to see if each of their operands are an EXTRACT_VECTOR with 9946 // the same vector and appropriate index. 9947 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9948 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9949 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9950 9951 SDValue ExtVec0 = N0->getOperand(i); 9952 SDValue ExtVec1 = N1->getOperand(i); 9953 9954 // First operand is the vector, verify its the same. 9955 if (V != ExtVec0->getOperand(0).getNode() || 9956 V != ExtVec1->getOperand(0).getNode()) 9957 return SDValue(); 9958 9959 // Second is the constant, verify its correct. 9960 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9961 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9962 9963 // For the constant, we want to see all the even or all the odd. 9964 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9965 || C1->getZExtValue() != nextIndex+1) 9966 return SDValue(); 9967 9968 // Increment index. 9969 nextIndex+=2; 9970 } else 9971 return SDValue(); 9972 } 9973 9974 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9975 // we're using the entire input vector, otherwise there's a size/legality 9976 // mismatch somewhere. 9977 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9978 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9979 return SDValue(); 9980 9981 // Create VPADDL node. 9982 SelectionDAG &DAG = DCI.DAG; 9983 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9984 9985 SDLoc dl(N); 9986 9987 // Build operand list. 9988 SmallVector<SDValue, 8> Ops; 9989 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9990 TLI.getPointerTy(DAG.getDataLayout()))); 9991 9992 // Input is the vector. 9993 Ops.push_back(Vec); 9994 9995 // Get widened type and narrowed type. 9996 MVT widenType; 9997 unsigned numElem = VT.getVectorNumElements(); 9998 9999 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 10000 switch (inputLaneType.getSimpleVT().SimpleTy) { 10001 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 10002 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 10003 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 10004 default: 10005 llvm_unreachable("Invalid vector element type for padd optimization."); 10006 } 10007 10008 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 10009 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 10010 return DAG.getNode(ExtOp, dl, VT, tmp); 10011 } 10012 10013 static SDValue findMUL_LOHI(SDValue V) { 10014 if (V->getOpcode() == ISD::UMUL_LOHI || 10015 V->getOpcode() == ISD::SMUL_LOHI) 10016 return V; 10017 return SDValue(); 10018 } 10019 10020 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 10021 TargetLowering::DAGCombinerInfo &DCI, 10022 const ARMSubtarget *Subtarget) { 10023 if (Subtarget->isThumb()) { 10024 if (!Subtarget->hasDSP()) 10025 return SDValue(); 10026 } else if (!Subtarget->hasV5TEOps()) 10027 return SDValue(); 10028 10029 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 10030 // accumulates the product into a 64-bit value. The 16-bit values will 10031 // be sign extended somehow or SRA'd into 32-bit values 10032 // (addc (adde (mul 16bit, 16bit), lo), hi) 10033 SDValue Mul = AddcNode->getOperand(0); 10034 SDValue Lo = AddcNode->getOperand(1); 10035 if (Mul.getOpcode() != ISD::MUL) { 10036 Lo = AddcNode->getOperand(0); 10037 Mul = AddcNode->getOperand(1); 10038 if (Mul.getOpcode() != ISD::MUL) 10039 return SDValue(); 10040 } 10041 10042 SDValue SRA = AddeNode->getOperand(0); 10043 SDValue Hi = AddeNode->getOperand(1); 10044 if (SRA.getOpcode() != ISD::SRA) { 10045 SRA = AddeNode->getOperand(1); 10046 Hi = AddeNode->getOperand(0); 10047 if (SRA.getOpcode() != ISD::SRA) 10048 return SDValue(); 10049 } 10050 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10051 if (Const->getZExtValue() != 31) 10052 return SDValue(); 10053 } else 10054 return SDValue(); 10055 10056 if (SRA.getOperand(0) != Mul) 10057 return SDValue(); 10058 10059 SelectionDAG &DAG = DCI.DAG; 10060 SDLoc dl(AddcNode); 10061 unsigned Opcode = 0; 10062 SDValue Op0; 10063 SDValue Op1; 10064 10065 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10066 Opcode = ARMISD::SMLALBB; 10067 Op0 = Mul.getOperand(0); 10068 Op1 = Mul.getOperand(1); 10069 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10070 Opcode = ARMISD::SMLALBT; 10071 Op0 = Mul.getOperand(0); 10072 Op1 = Mul.getOperand(1).getOperand(0); 10073 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10074 Opcode = ARMISD::SMLALTB; 10075 Op0 = Mul.getOperand(0).getOperand(0); 10076 Op1 = Mul.getOperand(1); 10077 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10078 Opcode = ARMISD::SMLALTT; 10079 Op0 = Mul->getOperand(0).getOperand(0); 10080 Op1 = Mul->getOperand(1).getOperand(0); 10081 } 10082 10083 if (!Op0 || !Op1) 10084 return SDValue(); 10085 10086 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10087 Op0, Op1, Lo, Hi); 10088 // Replace the ADDs' nodes uses by the MLA node's values. 10089 SDValue HiMLALResult(SMLAL.getNode(), 1); 10090 SDValue LoMLALResult(SMLAL.getNode(), 0); 10091 10092 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10093 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10094 10095 // Return original node to notify the driver to stop replacing. 10096 SDValue resNode(AddcNode, 0); 10097 return resNode; 10098 } 10099 10100 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10101 TargetLowering::DAGCombinerInfo &DCI, 10102 const ARMSubtarget *Subtarget) { 10103 // Look for multiply add opportunities. 10104 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10105 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10106 // a glue link from the first add to the second add. 10107 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10108 // a S/UMLAL instruction. 10109 // UMUL_LOHI 10110 // / :lo \ :hi 10111 // V \ [no multiline comment] 10112 // loAdd -> ADDC | 10113 // \ :carry / 10114 // V V 10115 // ADDE <- hiAdd 10116 // 10117 // In the special case where only the higher part of a signed result is used 10118 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10119 // a constant with the exact value of 0x80000000, we recognize we are dealing 10120 // with a "rounded multiply and add" (or subtract) and transform it into 10121 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10122 10123 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10124 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10125 "Expect an ADDE or SUBE"); 10126 10127 assert(AddeSubeNode->getNumOperands() == 3 && 10128 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10129 "ADDE node has the wrong inputs"); 10130 10131 // Check that we are chained to the right ADDC or SUBC node. 10132 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10133 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10134 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10135 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10136 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10137 return SDValue(); 10138 10139 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10140 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10141 10142 // Check if the two operands are from the same mul_lohi node. 10143 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10144 return SDValue(); 10145 10146 assert(AddcSubcNode->getNumValues() == 2 && 10147 AddcSubcNode->getValueType(0) == MVT::i32 && 10148 "Expect ADDC with two result values. First: i32"); 10149 10150 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10151 // maybe a SMLAL which multiplies two 16-bit values. 10152 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10153 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10154 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10155 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10156 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10157 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10158 10159 // Check for the triangle shape. 10160 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10161 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10162 10163 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10164 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10165 return SDValue(); 10166 10167 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10168 bool IsLeftOperandMUL = false; 10169 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10170 if (MULOp == SDValue()) 10171 MULOp = findMUL_LOHI(AddeSubeOp1); 10172 else 10173 IsLeftOperandMUL = true; 10174 if (MULOp == SDValue()) 10175 return SDValue(); 10176 10177 // Figure out the right opcode. 10178 unsigned Opc = MULOp->getOpcode(); 10179 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10180 10181 // Figure out the high and low input values to the MLAL node. 10182 SDValue *HiAddSub = nullptr; 10183 SDValue *LoMul = nullptr; 10184 SDValue *LowAddSub = nullptr; 10185 10186 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10187 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10188 return SDValue(); 10189 10190 if (IsLeftOperandMUL) 10191 HiAddSub = &AddeSubeOp1; 10192 else 10193 HiAddSub = &AddeSubeOp0; 10194 10195 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10196 // whose low result is fed to the ADDC/SUBC we are checking. 10197 10198 if (AddcSubcOp0 == MULOp.getValue(0)) { 10199 LoMul = &AddcSubcOp0; 10200 LowAddSub = &AddcSubcOp1; 10201 } 10202 if (AddcSubcOp1 == MULOp.getValue(0)) { 10203 LoMul = &AddcSubcOp1; 10204 LowAddSub = &AddcSubcOp0; 10205 } 10206 10207 if (!LoMul) 10208 return SDValue(); 10209 10210 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10211 // the replacement below will create a cycle. 10212 if (AddcSubcNode == HiAddSub->getNode() || 10213 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10214 return SDValue(); 10215 10216 // Create the merged node. 10217 SelectionDAG &DAG = DCI.DAG; 10218 10219 // Start building operand list. 10220 SmallVector<SDValue, 8> Ops; 10221 Ops.push_back(LoMul->getOperand(0)); 10222 Ops.push_back(LoMul->getOperand(1)); 10223 10224 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10225 // the case, we must be doing signed multiplication and only use the higher 10226 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10227 // addition or subtraction with the value of 0x800000. 10228 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10229 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10230 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10231 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10232 0x80000000) { 10233 Ops.push_back(*HiAddSub); 10234 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10235 FinalOpc = ARMISD::SMMLSR; 10236 } else { 10237 FinalOpc = ARMISD::SMMLAR; 10238 } 10239 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10240 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10241 10242 return SDValue(AddeSubeNode, 0); 10243 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10244 // SMMLS is generated during instruction selection and the rest of this 10245 // function can not handle the case where AddcSubcNode is a SUBC. 10246 return SDValue(); 10247 10248 // Finish building the operand list for {U/S}MLAL 10249 Ops.push_back(*LowAddSub); 10250 Ops.push_back(*HiAddSub); 10251 10252 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 10253 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10254 10255 // Replace the ADDs' nodes uses by the MLA node's values. 10256 SDValue HiMLALResult(MLALNode.getNode(), 1); 10257 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 10258 10259 SDValue LoMLALResult(MLALNode.getNode(), 0); 10260 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 10261 10262 // Return original node to notify the driver to stop replacing. 10263 return SDValue(AddeSubeNode, 0); 10264 } 10265 10266 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 10267 TargetLowering::DAGCombinerInfo &DCI, 10268 const ARMSubtarget *Subtarget) { 10269 // UMAAL is similar to UMLAL except that it adds two unsigned values. 10270 // While trying to combine for the other MLAL nodes, first search for the 10271 // chance to use UMAAL. Check if Addc uses a node which has already 10272 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 10273 // as the addend, and it's handled in PerformUMLALCombine. 10274 10275 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10276 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10277 10278 // Check that we have a glued ADDC node. 10279 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10280 if (AddcNode->getOpcode() != ARMISD::ADDC) 10281 return SDValue(); 10282 10283 // Find the converted UMAAL or quit if it doesn't exist. 10284 SDNode *UmlalNode = nullptr; 10285 SDValue AddHi; 10286 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10287 UmlalNode = AddcNode->getOperand(0).getNode(); 10288 AddHi = AddcNode->getOperand(1); 10289 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10290 UmlalNode = AddcNode->getOperand(1).getNode(); 10291 AddHi = AddcNode->getOperand(0); 10292 } else { 10293 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10294 } 10295 10296 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10297 // the ADDC as well as Zero. 10298 if (!isNullConstant(UmlalNode->getOperand(3))) 10299 return SDValue(); 10300 10301 if ((isNullConstant(AddeNode->getOperand(0)) && 10302 AddeNode->getOperand(1).getNode() == UmlalNode) || 10303 (AddeNode->getOperand(0).getNode() == UmlalNode && 10304 isNullConstant(AddeNode->getOperand(1)))) { 10305 SelectionDAG &DAG = DCI.DAG; 10306 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10307 UmlalNode->getOperand(2), AddHi }; 10308 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10309 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10310 10311 // Replace the ADDs' nodes uses by the UMAAL node's values. 10312 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10313 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10314 10315 // Return original node to notify the driver to stop replacing. 10316 return SDValue(AddeNode, 0); 10317 } 10318 return SDValue(); 10319 } 10320 10321 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10322 const ARMSubtarget *Subtarget) { 10323 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10324 return SDValue(); 10325 10326 // Check that we have a pair of ADDC and ADDE as operands. 10327 // Both addends of the ADDE must be zero. 10328 SDNode* AddcNode = N->getOperand(2).getNode(); 10329 SDNode* AddeNode = N->getOperand(3).getNode(); 10330 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10331 (AddeNode->getOpcode() == ARMISD::ADDE) && 10332 isNullConstant(AddeNode->getOperand(0)) && 10333 isNullConstant(AddeNode->getOperand(1)) && 10334 (AddeNode->getOperand(2).getNode() == AddcNode)) 10335 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10336 DAG.getVTList(MVT::i32, MVT::i32), 10337 {N->getOperand(0), N->getOperand(1), 10338 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10339 else 10340 return SDValue(); 10341 } 10342 10343 static SDValue PerformAddcSubcCombine(SDNode *N, 10344 TargetLowering::DAGCombinerInfo &DCI, 10345 const ARMSubtarget *Subtarget) { 10346 SelectionDAG &DAG(DCI.DAG); 10347 10348 if (N->getOpcode() == ARMISD::SUBC) { 10349 // (SUBC (ADDE 0, 0, C), 1) -> C 10350 SDValue LHS = N->getOperand(0); 10351 SDValue RHS = N->getOperand(1); 10352 if (LHS->getOpcode() == ARMISD::ADDE && 10353 isNullConstant(LHS->getOperand(0)) && 10354 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 10355 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10356 } 10357 } 10358 10359 if (Subtarget->isThumb1Only()) { 10360 SDValue RHS = N->getOperand(1); 10361 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10362 int32_t imm = C->getSExtValue(); 10363 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10364 SDLoc DL(N); 10365 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10366 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10367 : ARMISD::ADDC; 10368 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10369 } 10370 } 10371 } 10372 10373 return SDValue(); 10374 } 10375 10376 static SDValue PerformAddeSubeCombine(SDNode *N, 10377 TargetLowering::DAGCombinerInfo &DCI, 10378 const ARMSubtarget *Subtarget) { 10379 if (Subtarget->isThumb1Only()) { 10380 SelectionDAG &DAG = DCI.DAG; 10381 SDValue RHS = N->getOperand(1); 10382 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10383 int64_t imm = C->getSExtValue(); 10384 if (imm < 0) { 10385 SDLoc DL(N); 10386 10387 // The with-carry-in form matches bitwise not instead of the negation. 10388 // Effectively, the inverse interpretation of the carry flag already 10389 // accounts for part of the negation. 10390 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10391 10392 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10393 : ARMISD::ADDE; 10394 return DAG.getNode(Opcode, DL, N->getVTList(), 10395 N->getOperand(0), RHS, N->getOperand(2)); 10396 } 10397 } 10398 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 10399 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 10400 } 10401 return SDValue(); 10402 } 10403 10404 /// PerformADDECombine - Target-specific dag combine transform from 10405 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10406 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10407 static SDValue PerformADDECombine(SDNode *N, 10408 TargetLowering::DAGCombinerInfo &DCI, 10409 const ARMSubtarget *Subtarget) { 10410 // Only ARM and Thumb2 support UMLAL/SMLAL. 10411 if (Subtarget->isThumb1Only()) 10412 return PerformAddeSubeCombine(N, DCI, Subtarget); 10413 10414 // Only perform the checks after legalize when the pattern is available. 10415 if (DCI.isBeforeLegalize()) return SDValue(); 10416 10417 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10418 } 10419 10420 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10421 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10422 /// called with the default operands, and if that fails, with commuted 10423 /// operands. 10424 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10425 TargetLowering::DAGCombinerInfo &DCI, 10426 const ARMSubtarget *Subtarget){ 10427 // Attempt to create vpadd for this add. 10428 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10429 return Result; 10430 10431 // Attempt to create vpaddl for this add. 10432 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10433 return Result; 10434 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10435 Subtarget)) 10436 return Result; 10437 10438 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10439 if (N0.getNode()->hasOneUse()) 10440 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10441 return Result; 10442 return SDValue(); 10443 } 10444 10445 static SDValue PerformSHLSimplify(SDNode *N, 10446 TargetLowering::DAGCombinerInfo &DCI, 10447 const ARMSubtarget *ST) { 10448 // Allow the generic combiner to identify potential bswaps. 10449 if (DCI.isBeforeLegalize()) 10450 return SDValue(); 10451 10452 // DAG combiner will fold: 10453 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10454 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10455 // Other code patterns that can be also be modified have the following form: 10456 // b + ((a << 1) | 510) 10457 // b + ((a << 1) & 510) 10458 // b + ((a << 1) ^ 510) 10459 // b + ((a << 1) + 510) 10460 10461 // Many instructions can perform the shift for free, but it requires both 10462 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10463 // instruction will needed. So, unfold back to the original pattern if: 10464 // - if c1 and c2 are small enough that they don't require mov imms. 10465 // - the user(s) of the node can perform an shl 10466 10467 // No shifted operands for 16-bit instructions. 10468 if (ST->isThumb() && ST->isThumb1Only()) 10469 return SDValue(); 10470 10471 // Check that all the users could perform the shl themselves. 10472 for (auto U : N->uses()) { 10473 switch(U->getOpcode()) { 10474 default: 10475 return SDValue(); 10476 case ISD::SUB: 10477 case ISD::ADD: 10478 case ISD::AND: 10479 case ISD::OR: 10480 case ISD::XOR: 10481 case ISD::SETCC: 10482 case ARMISD::CMP: 10483 // Check that the user isn't already using a constant because there 10484 // aren't any instructions that support an immediate operand and a 10485 // shifted operand. 10486 if (isa<ConstantSDNode>(U->getOperand(0)) || 10487 isa<ConstantSDNode>(U->getOperand(1))) 10488 return SDValue(); 10489 10490 // Check that it's not already using a shift. 10491 if (U->getOperand(0).getOpcode() == ISD::SHL || 10492 U->getOperand(1).getOpcode() == ISD::SHL) 10493 return SDValue(); 10494 break; 10495 } 10496 } 10497 10498 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10499 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10500 return SDValue(); 10501 10502 if (N->getOperand(0).getOpcode() != ISD::SHL) 10503 return SDValue(); 10504 10505 SDValue SHL = N->getOperand(0); 10506 10507 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10508 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10509 if (!C1ShlC2 || !C2) 10510 return SDValue(); 10511 10512 APInt C2Int = C2->getAPIntValue(); 10513 APInt C1Int = C1ShlC2->getAPIntValue(); 10514 10515 // Check that performing a lshr will not lose any information. 10516 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10517 C2Int.getBitWidth() - C2->getZExtValue()); 10518 if ((C1Int & Mask) != C1Int) 10519 return SDValue(); 10520 10521 // Shift the first constant. 10522 C1Int.lshrInPlace(C2Int); 10523 10524 // The immediates are encoded as an 8-bit value that can be rotated. 10525 auto LargeImm = [](const APInt &Imm) { 10526 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 10527 return Imm.getBitWidth() - Zeros > 8; 10528 }; 10529 10530 if (LargeImm(C1Int) || LargeImm(C2Int)) 10531 return SDValue(); 10532 10533 SelectionDAG &DAG = DCI.DAG; 10534 SDLoc dl(N); 10535 SDValue X = SHL.getOperand(0); 10536 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10537 DAG.getConstant(C1Int, dl, MVT::i32)); 10538 // Shift left to compensate for the lshr of C1Int. 10539 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10540 10541 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 10542 SHL.dump(); N->dump()); 10543 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 10544 10545 DAG.ReplaceAllUsesWith(SDValue(N, 0), Res); 10546 return SDValue(N, 0); 10547 } 10548 10549 10550 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10551 /// 10552 static SDValue PerformADDCombine(SDNode *N, 10553 TargetLowering::DAGCombinerInfo &DCI, 10554 const ARMSubtarget *Subtarget) { 10555 SDValue N0 = N->getOperand(0); 10556 SDValue N1 = N->getOperand(1); 10557 10558 // Only works one way, because it needs an immediate operand. 10559 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10560 return Result; 10561 10562 // First try with the default operand order. 10563 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10564 return Result; 10565 10566 // If that didn't work, try again with the operands commuted. 10567 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10568 } 10569 10570 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10571 /// 10572 static SDValue PerformSUBCombine(SDNode *N, 10573 TargetLowering::DAGCombinerInfo &DCI) { 10574 SDValue N0 = N->getOperand(0); 10575 SDValue N1 = N->getOperand(1); 10576 10577 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10578 if (N1.getNode()->hasOneUse()) 10579 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10580 return Result; 10581 10582 return SDValue(); 10583 } 10584 10585 /// PerformVMULCombine 10586 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10587 /// special multiplier accumulator forwarding. 10588 /// vmul d3, d0, d2 10589 /// vmla d3, d1, d2 10590 /// is faster than 10591 /// vadd d3, d0, d1 10592 /// vmul d3, d3, d2 10593 // However, for (A + B) * (A + B), 10594 // vadd d2, d0, d1 10595 // vmul d3, d0, d2 10596 // vmla d3, d1, d2 10597 // is slower than 10598 // vadd d2, d0, d1 10599 // vmul d3, d2, d2 10600 static SDValue PerformVMULCombine(SDNode *N, 10601 TargetLowering::DAGCombinerInfo &DCI, 10602 const ARMSubtarget *Subtarget) { 10603 if (!Subtarget->hasVMLxForwarding()) 10604 return SDValue(); 10605 10606 SelectionDAG &DAG = DCI.DAG; 10607 SDValue N0 = N->getOperand(0); 10608 SDValue N1 = N->getOperand(1); 10609 unsigned Opcode = N0.getOpcode(); 10610 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10611 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10612 Opcode = N1.getOpcode(); 10613 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10614 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10615 return SDValue(); 10616 std::swap(N0, N1); 10617 } 10618 10619 if (N0 == N1) 10620 return SDValue(); 10621 10622 EVT VT = N->getValueType(0); 10623 SDLoc DL(N); 10624 SDValue N00 = N0->getOperand(0); 10625 SDValue N01 = N0->getOperand(1); 10626 return DAG.getNode(Opcode, DL, VT, 10627 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10628 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10629 } 10630 10631 static SDValue PerformMULCombine(SDNode *N, 10632 TargetLowering::DAGCombinerInfo &DCI, 10633 const ARMSubtarget *Subtarget) { 10634 SelectionDAG &DAG = DCI.DAG; 10635 10636 if (Subtarget->isThumb1Only()) 10637 return SDValue(); 10638 10639 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10640 return SDValue(); 10641 10642 EVT VT = N->getValueType(0); 10643 if (VT.is64BitVector() || VT.is128BitVector()) 10644 return PerformVMULCombine(N, DCI, Subtarget); 10645 if (VT != MVT::i32) 10646 return SDValue(); 10647 10648 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10649 if (!C) 10650 return SDValue(); 10651 10652 int64_t MulAmt = C->getSExtValue(); 10653 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10654 10655 ShiftAmt = ShiftAmt & (32 - 1); 10656 SDValue V = N->getOperand(0); 10657 SDLoc DL(N); 10658 10659 SDValue Res; 10660 MulAmt >>= ShiftAmt; 10661 10662 if (MulAmt >= 0) { 10663 if (isPowerOf2_32(MulAmt - 1)) { 10664 // (mul x, 2^N + 1) => (add (shl x, N), x) 10665 Res = DAG.getNode(ISD::ADD, DL, VT, 10666 V, 10667 DAG.getNode(ISD::SHL, DL, VT, 10668 V, 10669 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10670 MVT::i32))); 10671 } else if (isPowerOf2_32(MulAmt + 1)) { 10672 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10673 Res = DAG.getNode(ISD::SUB, DL, VT, 10674 DAG.getNode(ISD::SHL, DL, VT, 10675 V, 10676 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10677 MVT::i32)), 10678 V); 10679 } else 10680 return SDValue(); 10681 } else { 10682 uint64_t MulAmtAbs = -MulAmt; 10683 if (isPowerOf2_32(MulAmtAbs + 1)) { 10684 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10685 Res = DAG.getNode(ISD::SUB, DL, VT, 10686 V, 10687 DAG.getNode(ISD::SHL, DL, VT, 10688 V, 10689 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10690 MVT::i32))); 10691 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10692 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10693 Res = DAG.getNode(ISD::ADD, DL, VT, 10694 V, 10695 DAG.getNode(ISD::SHL, DL, VT, 10696 V, 10697 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10698 MVT::i32))); 10699 Res = DAG.getNode(ISD::SUB, DL, VT, 10700 DAG.getConstant(0, DL, MVT::i32), Res); 10701 } else 10702 return SDValue(); 10703 } 10704 10705 if (ShiftAmt != 0) 10706 Res = DAG.getNode(ISD::SHL, DL, VT, 10707 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10708 10709 // Do not add new nodes to DAG combiner worklist. 10710 DCI.CombineTo(N, Res, false); 10711 return SDValue(); 10712 } 10713 10714 static SDValue PerformANDCombine(SDNode *N, 10715 TargetLowering::DAGCombinerInfo &DCI, 10716 const ARMSubtarget *Subtarget) { 10717 // Attempt to use immediate-form VBIC 10718 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10719 SDLoc dl(N); 10720 EVT VT = N->getValueType(0); 10721 SelectionDAG &DAG = DCI.DAG; 10722 10723 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10724 return SDValue(); 10725 10726 APInt SplatBits, SplatUndef; 10727 unsigned SplatBitSize; 10728 bool HasAnyUndefs; 10729 if (BVN && 10730 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10731 if (SplatBitSize <= 64) { 10732 EVT VbicVT; 10733 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10734 SplatUndef.getZExtValue(), SplatBitSize, 10735 DAG, dl, VbicVT, VT.is128BitVector(), 10736 OtherModImm); 10737 if (Val.getNode()) { 10738 SDValue Input = 10739 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10740 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10741 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10742 } 10743 } 10744 } 10745 10746 if (!Subtarget->isThumb1Only()) { 10747 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10748 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10749 return Result; 10750 10751 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10752 return Result; 10753 } 10754 10755 return SDValue(); 10756 } 10757 10758 // Try combining OR nodes to SMULWB, SMULWT. 10759 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10760 TargetLowering::DAGCombinerInfo &DCI, 10761 const ARMSubtarget *Subtarget) { 10762 if (!Subtarget->hasV6Ops() || 10763 (Subtarget->isThumb() && 10764 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10765 return SDValue(); 10766 10767 SDValue SRL = OR->getOperand(0); 10768 SDValue SHL = OR->getOperand(1); 10769 10770 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10771 SRL = OR->getOperand(1); 10772 SHL = OR->getOperand(0); 10773 } 10774 if (!isSRL16(SRL) || !isSHL16(SHL)) 10775 return SDValue(); 10776 10777 // The first operands to the shifts need to be the two results from the 10778 // same smul_lohi node. 10779 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10780 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10781 return SDValue(); 10782 10783 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10784 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10785 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10786 return SDValue(); 10787 10788 // Now we have: 10789 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10790 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10791 // For SMUWB the 16-bit value will signed extended somehow. 10792 // For SMULWT only the SRA is required. 10793 // Check both sides of SMUL_LOHI 10794 SDValue OpS16 = SMULLOHI->getOperand(0); 10795 SDValue OpS32 = SMULLOHI->getOperand(1); 10796 10797 SelectionDAG &DAG = DCI.DAG; 10798 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10799 OpS16 = OpS32; 10800 OpS32 = SMULLOHI->getOperand(0); 10801 } 10802 10803 SDLoc dl(OR); 10804 unsigned Opcode = 0; 10805 if (isS16(OpS16, DAG)) 10806 Opcode = ARMISD::SMULWB; 10807 else if (isSRA16(OpS16)) { 10808 Opcode = ARMISD::SMULWT; 10809 OpS16 = OpS16->getOperand(0); 10810 } 10811 else 10812 return SDValue(); 10813 10814 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10815 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10816 return SDValue(OR, 0); 10817 } 10818 10819 static SDValue PerformORCombineToBFI(SDNode *N, 10820 TargetLowering::DAGCombinerInfo &DCI, 10821 const ARMSubtarget *Subtarget) { 10822 // BFI is only available on V6T2+ 10823 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10824 return SDValue(); 10825 10826 EVT VT = N->getValueType(0); 10827 SDValue N0 = N->getOperand(0); 10828 SDValue N1 = N->getOperand(1); 10829 SelectionDAG &DAG = DCI.DAG; 10830 SDLoc DL(N); 10831 // 1) or (and A, mask), val => ARMbfi A, val, mask 10832 // iff (val & mask) == val 10833 // 10834 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10835 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10836 // && mask == ~mask2 10837 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10838 // && ~mask == mask2 10839 // (i.e., copy a bitfield value into another bitfield of the same width) 10840 10841 if (VT != MVT::i32) 10842 return SDValue(); 10843 10844 SDValue N00 = N0.getOperand(0); 10845 10846 // The value and the mask need to be constants so we can verify this is 10847 // actually a bitfield set. If the mask is 0xffff, we can do better 10848 // via a movt instruction, so don't use BFI in that case. 10849 SDValue MaskOp = N0.getOperand(1); 10850 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10851 if (!MaskC) 10852 return SDValue(); 10853 unsigned Mask = MaskC->getZExtValue(); 10854 if (Mask == 0xffff) 10855 return SDValue(); 10856 SDValue Res; 10857 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10858 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10859 if (N1C) { 10860 unsigned Val = N1C->getZExtValue(); 10861 if ((Val & ~Mask) != Val) 10862 return SDValue(); 10863 10864 if (ARM::isBitFieldInvertedMask(Mask)) { 10865 Val >>= countTrailingZeros(~Mask); 10866 10867 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10868 DAG.getConstant(Val, DL, MVT::i32), 10869 DAG.getConstant(Mask, DL, MVT::i32)); 10870 10871 DCI.CombineTo(N, Res, false); 10872 // Return value from the original node to inform the combiner than N is 10873 // now dead. 10874 return SDValue(N, 0); 10875 } 10876 } else if (N1.getOpcode() == ISD::AND) { 10877 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10878 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10879 if (!N11C) 10880 return SDValue(); 10881 unsigned Mask2 = N11C->getZExtValue(); 10882 10883 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10884 // as is to match. 10885 if (ARM::isBitFieldInvertedMask(Mask) && 10886 (Mask == ~Mask2)) { 10887 // The pack halfword instruction works better for masks that fit it, 10888 // so use that when it's available. 10889 if (Subtarget->hasDSP() && 10890 (Mask == 0xffff || Mask == 0xffff0000)) 10891 return SDValue(); 10892 // 2a 10893 unsigned amt = countTrailingZeros(Mask2); 10894 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10895 DAG.getConstant(amt, DL, MVT::i32)); 10896 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10897 DAG.getConstant(Mask, DL, MVT::i32)); 10898 DCI.CombineTo(N, Res, false); 10899 // Return value from the original node to inform the combiner than N is 10900 // now dead. 10901 return SDValue(N, 0); 10902 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10903 (~Mask == Mask2)) { 10904 // The pack halfword instruction works better for masks that fit it, 10905 // so use that when it's available. 10906 if (Subtarget->hasDSP() && 10907 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10908 return SDValue(); 10909 // 2b 10910 unsigned lsb = countTrailingZeros(Mask); 10911 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10912 DAG.getConstant(lsb, DL, MVT::i32)); 10913 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10914 DAG.getConstant(Mask2, DL, MVT::i32)); 10915 DCI.CombineTo(N, Res, false); 10916 // Return value from the original node to inform the combiner than N is 10917 // now dead. 10918 return SDValue(N, 0); 10919 } 10920 } 10921 10922 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10923 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10924 ARM::isBitFieldInvertedMask(~Mask)) { 10925 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10926 // where lsb(mask) == #shamt and masked bits of B are known zero. 10927 SDValue ShAmt = N00.getOperand(1); 10928 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10929 unsigned LSB = countTrailingZeros(Mask); 10930 if (ShAmtC != LSB) 10931 return SDValue(); 10932 10933 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10934 DAG.getConstant(~Mask, DL, MVT::i32)); 10935 10936 DCI.CombineTo(N, Res, false); 10937 // Return value from the original node to inform the combiner than N is 10938 // now dead. 10939 return SDValue(N, 0); 10940 } 10941 10942 return SDValue(); 10943 } 10944 10945 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10946 static SDValue PerformORCombine(SDNode *N, 10947 TargetLowering::DAGCombinerInfo &DCI, 10948 const ARMSubtarget *Subtarget) { 10949 // Attempt to use immediate-form VORR 10950 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10951 SDLoc dl(N); 10952 EVT VT = N->getValueType(0); 10953 SelectionDAG &DAG = DCI.DAG; 10954 10955 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10956 return SDValue(); 10957 10958 APInt SplatBits, SplatUndef; 10959 unsigned SplatBitSize; 10960 bool HasAnyUndefs; 10961 if (BVN && Subtarget->hasNEON() && 10962 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10963 if (SplatBitSize <= 64) { 10964 EVT VorrVT; 10965 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10966 SplatUndef.getZExtValue(), SplatBitSize, 10967 DAG, dl, VorrVT, VT.is128BitVector(), 10968 OtherModImm); 10969 if (Val.getNode()) { 10970 SDValue Input = 10971 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10972 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10973 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10974 } 10975 } 10976 } 10977 10978 if (!Subtarget->isThumb1Only()) { 10979 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10980 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10981 return Result; 10982 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10983 return Result; 10984 } 10985 10986 SDValue N0 = N->getOperand(0); 10987 SDValue N1 = N->getOperand(1); 10988 10989 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10990 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10991 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10992 10993 // The code below optimizes (or (and X, Y), Z). 10994 // The AND operand needs to have a single user to make these optimizations 10995 // profitable. 10996 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10997 return SDValue(); 10998 10999 APInt SplatUndef; 11000 unsigned SplatBitSize; 11001 bool HasAnyUndefs; 11002 11003 APInt SplatBits0, SplatBits1; 11004 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 11005 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 11006 // Ensure that the second operand of both ands are constants 11007 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 11008 HasAnyUndefs) && !HasAnyUndefs) { 11009 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 11010 HasAnyUndefs) && !HasAnyUndefs) { 11011 // Ensure that the bit width of the constants are the same and that 11012 // the splat arguments are logical inverses as per the pattern we 11013 // are trying to simplify. 11014 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 11015 SplatBits0 == ~SplatBits1) { 11016 // Canonicalize the vector type to make instruction selection 11017 // simpler. 11018 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 11019 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 11020 N0->getOperand(1), 11021 N0->getOperand(0), 11022 N1->getOperand(0)); 11023 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 11024 } 11025 } 11026 } 11027 } 11028 11029 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 11030 // reasonable. 11031 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 11032 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 11033 return Res; 11034 } 11035 11036 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11037 return Result; 11038 11039 return SDValue(); 11040 } 11041 11042 static SDValue PerformXORCombine(SDNode *N, 11043 TargetLowering::DAGCombinerInfo &DCI, 11044 const ARMSubtarget *Subtarget) { 11045 EVT VT = N->getValueType(0); 11046 SelectionDAG &DAG = DCI.DAG; 11047 11048 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11049 return SDValue(); 11050 11051 if (!Subtarget->isThumb1Only()) { 11052 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11053 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11054 return Result; 11055 11056 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11057 return Result; 11058 } 11059 11060 return SDValue(); 11061 } 11062 11063 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 11064 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 11065 // their position in "to" (Rd). 11066 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 11067 assert(N->getOpcode() == ARMISD::BFI); 11068 11069 SDValue From = N->getOperand(1); 11070 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 11071 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 11072 11073 // If the Base came from a SHR #C, we can deduce that it is really testing bit 11074 // #C in the base of the SHR. 11075 if (From->getOpcode() == ISD::SRL && 11076 isa<ConstantSDNode>(From->getOperand(1))) { 11077 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 11078 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 11079 FromMask <<= Shift.getLimitedValue(31); 11080 From = From->getOperand(0); 11081 } 11082 11083 return From; 11084 } 11085 11086 // If A and B contain one contiguous set of bits, does A | B == A . B? 11087 // 11088 // Neither A nor B must be zero. 11089 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 11090 unsigned LastActiveBitInA = A.countTrailingZeros(); 11091 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 11092 return LastActiveBitInA - 1 == FirstActiveBitInB; 11093 } 11094 11095 static SDValue FindBFIToCombineWith(SDNode *N) { 11096 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 11097 // if one exists. 11098 APInt ToMask, FromMask; 11099 SDValue From = ParseBFI(N, ToMask, FromMask); 11100 SDValue To = N->getOperand(0); 11101 11102 // Now check for a compatible BFI to merge with. We can pass through BFIs that 11103 // aren't compatible, but not if they set the same bit in their destination as 11104 // we do (or that of any BFI we're going to combine with). 11105 SDValue V = To; 11106 APInt CombinedToMask = ToMask; 11107 while (V.getOpcode() == ARMISD::BFI) { 11108 APInt NewToMask, NewFromMask; 11109 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 11110 if (NewFrom != From) { 11111 // This BFI has a different base. Keep going. 11112 CombinedToMask |= NewToMask; 11113 V = V.getOperand(0); 11114 continue; 11115 } 11116 11117 // Do the written bits conflict with any we've seen so far? 11118 if ((NewToMask & CombinedToMask).getBoolValue()) 11119 // Conflicting bits - bail out because going further is unsafe. 11120 return SDValue(); 11121 11122 // Are the new bits contiguous when combined with the old bits? 11123 if (BitsProperlyConcatenate(ToMask, NewToMask) && 11124 BitsProperlyConcatenate(FromMask, NewFromMask)) 11125 return V; 11126 if (BitsProperlyConcatenate(NewToMask, ToMask) && 11127 BitsProperlyConcatenate(NewFromMask, FromMask)) 11128 return V; 11129 11130 // We've seen a write to some bits, so track it. 11131 CombinedToMask |= NewToMask; 11132 // Keep going... 11133 V = V.getOperand(0); 11134 } 11135 11136 return SDValue(); 11137 } 11138 11139 static SDValue PerformBFICombine(SDNode *N, 11140 TargetLowering::DAGCombinerInfo &DCI) { 11141 SDValue N1 = N->getOperand(1); 11142 if (N1.getOpcode() == ISD::AND) { 11143 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 11144 // the bits being cleared by the AND are not demanded by the BFI. 11145 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11146 if (!N11C) 11147 return SDValue(); 11148 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11149 unsigned LSB = countTrailingZeros(~InvMask); 11150 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 11151 assert(Width < 11152 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 11153 "undefined behavior"); 11154 unsigned Mask = (1u << Width) - 1; 11155 unsigned Mask2 = N11C->getZExtValue(); 11156 if ((Mask & (~Mask2)) == 0) 11157 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 11158 N->getOperand(0), N1.getOperand(0), 11159 N->getOperand(2)); 11160 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 11161 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 11162 // Keep track of any consecutive bits set that all come from the same base 11163 // value. We can combine these together into a single BFI. 11164 SDValue CombineBFI = FindBFIToCombineWith(N); 11165 if (CombineBFI == SDValue()) 11166 return SDValue(); 11167 11168 // We've found a BFI. 11169 APInt ToMask1, FromMask1; 11170 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 11171 11172 APInt ToMask2, FromMask2; 11173 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 11174 assert(From1 == From2); 11175 (void)From2; 11176 11177 // First, unlink CombineBFI. 11178 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 11179 // Then create a new BFI, combining the two together. 11180 APInt NewFromMask = FromMask1 | FromMask2; 11181 APInt NewToMask = ToMask1 | ToMask2; 11182 11183 EVT VT = N->getValueType(0); 11184 SDLoc dl(N); 11185 11186 if (NewFromMask[0] == 0) 11187 From1 = DCI.DAG.getNode( 11188 ISD::SRL, dl, VT, From1, 11189 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 11190 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 11191 DCI.DAG.getConstant(~NewToMask, dl, VT)); 11192 } 11193 return SDValue(); 11194 } 11195 11196 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 11197 /// ARMISD::VMOVRRD. 11198 static SDValue PerformVMOVRRDCombine(SDNode *N, 11199 TargetLowering::DAGCombinerInfo &DCI, 11200 const ARMSubtarget *Subtarget) { 11201 // vmovrrd(vmovdrr x, y) -> x,y 11202 SDValue InDouble = N->getOperand(0); 11203 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 11204 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 11205 11206 // vmovrrd(load f64) -> (load i32), (load i32) 11207 SDNode *InNode = InDouble.getNode(); 11208 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 11209 InNode->getValueType(0) == MVT::f64 && 11210 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 11211 !cast<LoadSDNode>(InNode)->isVolatile()) { 11212 // TODO: Should this be done for non-FrameIndex operands? 11213 LoadSDNode *LD = cast<LoadSDNode>(InNode); 11214 11215 SelectionDAG &DAG = DCI.DAG; 11216 SDLoc DL(LD); 11217 SDValue BasePtr = LD->getBasePtr(); 11218 SDValue NewLD1 = 11219 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 11220 LD->getAlignment(), LD->getMemOperand()->getFlags()); 11221 11222 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11223 DAG.getConstant(4, DL, MVT::i32)); 11224 SDValue NewLD2 = DAG.getLoad( 11225 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 11226 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 11227 11228 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 11229 if (DCI.DAG.getDataLayout().isBigEndian()) 11230 std::swap (NewLD1, NewLD2); 11231 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 11232 return Result; 11233 } 11234 11235 return SDValue(); 11236 } 11237 11238 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 11239 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 11240 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 11241 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 11242 SDValue Op0 = N->getOperand(0); 11243 SDValue Op1 = N->getOperand(1); 11244 if (Op0.getOpcode() == ISD::BITCAST) 11245 Op0 = Op0.getOperand(0); 11246 if (Op1.getOpcode() == ISD::BITCAST) 11247 Op1 = Op1.getOperand(0); 11248 if (Op0.getOpcode() == ARMISD::VMOVRRD && 11249 Op0.getNode() == Op1.getNode() && 11250 Op0.getResNo() == 0 && Op1.getResNo() == 1) 11251 return DAG.getNode(ISD::BITCAST, SDLoc(N), 11252 N->getValueType(0), Op0.getOperand(0)); 11253 return SDValue(); 11254 } 11255 11256 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 11257 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 11258 /// i64 vector to have f64 elements, since the value can then be loaded 11259 /// directly into a VFP register. 11260 static bool hasNormalLoadOperand(SDNode *N) { 11261 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 11262 for (unsigned i = 0; i < NumElts; ++i) { 11263 SDNode *Elt = N->getOperand(i).getNode(); 11264 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 11265 return true; 11266 } 11267 return false; 11268 } 11269 11270 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 11271 /// ISD::BUILD_VECTOR. 11272 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 11273 TargetLowering::DAGCombinerInfo &DCI, 11274 const ARMSubtarget *Subtarget) { 11275 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 11276 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 11277 // into a pair of GPRs, which is fine when the value is used as a scalar, 11278 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 11279 SelectionDAG &DAG = DCI.DAG; 11280 if (N->getNumOperands() == 2) 11281 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 11282 return RV; 11283 11284 // Load i64 elements as f64 values so that type legalization does not split 11285 // them up into i32 values. 11286 EVT VT = N->getValueType(0); 11287 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11288 return SDValue(); 11289 SDLoc dl(N); 11290 SmallVector<SDValue, 8> Ops; 11291 unsigned NumElts = VT.getVectorNumElements(); 11292 for (unsigned i = 0; i < NumElts; ++i) { 11293 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11294 Ops.push_back(V); 11295 // Make the DAGCombiner fold the bitcast. 11296 DCI.AddToWorklist(V.getNode()); 11297 } 11298 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11299 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11300 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11301 } 11302 11303 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11304 static SDValue 11305 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11306 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11307 // At that time, we may have inserted bitcasts from integer to float. 11308 // If these bitcasts have survived DAGCombine, change the lowering of this 11309 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11310 // force to use floating point types. 11311 11312 // Make sure we can change the type of the vector. 11313 // This is possible iff: 11314 // 1. The vector is only used in a bitcast to a integer type. I.e., 11315 // 1.1. Vector is used only once. 11316 // 1.2. Use is a bit convert to an integer type. 11317 // 2. The size of its operands are 32-bits (64-bits are not legal). 11318 EVT VT = N->getValueType(0); 11319 EVT EltVT = VT.getVectorElementType(); 11320 11321 // Check 1.1. and 2. 11322 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11323 return SDValue(); 11324 11325 // By construction, the input type must be float. 11326 assert(EltVT == MVT::f32 && "Unexpected type!"); 11327 11328 // Check 1.2. 11329 SDNode *Use = *N->use_begin(); 11330 if (Use->getOpcode() != ISD::BITCAST || 11331 Use->getValueType(0).isFloatingPoint()) 11332 return SDValue(); 11333 11334 // Check profitability. 11335 // Model is, if more than half of the relevant operands are bitcast from 11336 // i32, turn the build_vector into a sequence of insert_vector_elt. 11337 // Relevant operands are everything that is not statically 11338 // (i.e., at compile time) bitcasted. 11339 unsigned NumOfBitCastedElts = 0; 11340 unsigned NumElts = VT.getVectorNumElements(); 11341 unsigned NumOfRelevantElts = NumElts; 11342 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11343 SDValue Elt = N->getOperand(Idx); 11344 if (Elt->getOpcode() == ISD::BITCAST) { 11345 // Assume only bit cast to i32 will go away. 11346 if (Elt->getOperand(0).getValueType() == MVT::i32) 11347 ++NumOfBitCastedElts; 11348 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11349 // Constants are statically casted, thus do not count them as 11350 // relevant operands. 11351 --NumOfRelevantElts; 11352 } 11353 11354 // Check if more than half of the elements require a non-free bitcast. 11355 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11356 return SDValue(); 11357 11358 SelectionDAG &DAG = DCI.DAG; 11359 // Create the new vector type. 11360 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11361 // Check if the type is legal. 11362 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11363 if (!TLI.isTypeLegal(VecVT)) 11364 return SDValue(); 11365 11366 // Combine: 11367 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11368 // => BITCAST INSERT_VECTOR_ELT 11369 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11370 // (BITCAST EN), N. 11371 SDValue Vec = DAG.getUNDEF(VecVT); 11372 SDLoc dl(N); 11373 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11374 SDValue V = N->getOperand(Idx); 11375 if (V.isUndef()) 11376 continue; 11377 if (V.getOpcode() == ISD::BITCAST && 11378 V->getOperand(0).getValueType() == MVT::i32) 11379 // Fold obvious case. 11380 V = V.getOperand(0); 11381 else { 11382 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11383 // Make the DAGCombiner fold the bitcasts. 11384 DCI.AddToWorklist(V.getNode()); 11385 } 11386 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11387 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11388 } 11389 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11390 // Make the DAGCombiner fold the bitcasts. 11391 DCI.AddToWorklist(Vec.getNode()); 11392 return Vec; 11393 } 11394 11395 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11396 /// ISD::INSERT_VECTOR_ELT. 11397 static SDValue PerformInsertEltCombine(SDNode *N, 11398 TargetLowering::DAGCombinerInfo &DCI) { 11399 // Bitcast an i64 load inserted into a vector to f64. 11400 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11401 EVT VT = N->getValueType(0); 11402 SDNode *Elt = N->getOperand(1).getNode(); 11403 if (VT.getVectorElementType() != MVT::i64 || 11404 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11405 return SDValue(); 11406 11407 SelectionDAG &DAG = DCI.DAG; 11408 SDLoc dl(N); 11409 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11410 VT.getVectorNumElements()); 11411 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11412 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11413 // Make the DAGCombiner fold the bitcasts. 11414 DCI.AddToWorklist(Vec.getNode()); 11415 DCI.AddToWorklist(V.getNode()); 11416 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11417 Vec, V, N->getOperand(2)); 11418 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11419 } 11420 11421 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11422 /// ISD::VECTOR_SHUFFLE. 11423 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11424 // The LLVM shufflevector instruction does not require the shuffle mask 11425 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11426 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11427 // operands do not match the mask length, they are extended by concatenating 11428 // them with undef vectors. That is probably the right thing for other 11429 // targets, but for NEON it is better to concatenate two double-register 11430 // size vector operands into a single quad-register size vector. Do that 11431 // transformation here: 11432 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11433 // shuffle(concat(v1, v2), undef) 11434 SDValue Op0 = N->getOperand(0); 11435 SDValue Op1 = N->getOperand(1); 11436 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11437 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11438 Op0.getNumOperands() != 2 || 11439 Op1.getNumOperands() != 2) 11440 return SDValue(); 11441 SDValue Concat0Op1 = Op0.getOperand(1); 11442 SDValue Concat1Op1 = Op1.getOperand(1); 11443 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11444 return SDValue(); 11445 // Skip the transformation if any of the types are illegal. 11446 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11447 EVT VT = N->getValueType(0); 11448 if (!TLI.isTypeLegal(VT) || 11449 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11450 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11451 return SDValue(); 11452 11453 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11454 Op0.getOperand(0), Op1.getOperand(0)); 11455 // Translate the shuffle mask. 11456 SmallVector<int, 16> NewMask; 11457 unsigned NumElts = VT.getVectorNumElements(); 11458 unsigned HalfElts = NumElts/2; 11459 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11460 for (unsigned n = 0; n < NumElts; ++n) { 11461 int MaskElt = SVN->getMaskElt(n); 11462 int NewElt = -1; 11463 if (MaskElt < (int)HalfElts) 11464 NewElt = MaskElt; 11465 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11466 NewElt = HalfElts + MaskElt - NumElts; 11467 NewMask.push_back(NewElt); 11468 } 11469 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11470 DAG.getUNDEF(VT), NewMask); 11471 } 11472 11473 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11474 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11475 /// base address updates. 11476 /// For generic load/stores, the memory type is assumed to be a vector. 11477 /// The caller is assumed to have checked legality. 11478 static SDValue CombineBaseUpdate(SDNode *N, 11479 TargetLowering::DAGCombinerInfo &DCI) { 11480 SelectionDAG &DAG = DCI.DAG; 11481 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11482 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11483 const bool isStore = N->getOpcode() == ISD::STORE; 11484 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11485 SDValue Addr = N->getOperand(AddrOpIdx); 11486 MemSDNode *MemN = cast<MemSDNode>(N); 11487 SDLoc dl(N); 11488 11489 // Search for a use of the address operand that is an increment. 11490 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11491 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11492 SDNode *User = *UI; 11493 if (User->getOpcode() != ISD::ADD || 11494 UI.getUse().getResNo() != Addr.getResNo()) 11495 continue; 11496 11497 // Check that the add is independent of the load/store. Otherwise, folding 11498 // it would create a cycle. 11499 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 11500 continue; 11501 11502 // Find the new opcode for the updating load/store. 11503 bool isLoadOp = true; 11504 bool isLaneOp = false; 11505 unsigned NewOpc = 0; 11506 unsigned NumVecs = 0; 11507 if (isIntrinsic) { 11508 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11509 switch (IntNo) { 11510 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11511 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11512 NumVecs = 1; break; 11513 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11514 NumVecs = 2; break; 11515 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11516 NumVecs = 3; break; 11517 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11518 NumVecs = 4; break; 11519 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11520 NumVecs = 2; isLaneOp = true; break; 11521 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11522 NumVecs = 3; isLaneOp = true; break; 11523 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11524 NumVecs = 4; isLaneOp = true; break; 11525 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11526 NumVecs = 1; isLoadOp = false; break; 11527 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11528 NumVecs = 2; isLoadOp = false; break; 11529 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11530 NumVecs = 3; isLoadOp = false; break; 11531 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11532 NumVecs = 4; isLoadOp = false; break; 11533 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11534 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11535 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11536 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11537 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11538 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11539 } 11540 } else { 11541 isLaneOp = true; 11542 switch (N->getOpcode()) { 11543 default: llvm_unreachable("unexpected opcode for Neon base update"); 11544 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11545 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11546 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11547 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11548 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11549 NumVecs = 1; isLaneOp = false; break; 11550 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11551 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11552 } 11553 } 11554 11555 // Find the size of memory referenced by the load/store. 11556 EVT VecTy; 11557 if (isLoadOp) { 11558 VecTy = N->getValueType(0); 11559 } else if (isIntrinsic) { 11560 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11561 } else { 11562 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11563 VecTy = N->getOperand(1).getValueType(); 11564 } 11565 11566 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11567 if (isLaneOp) 11568 NumBytes /= VecTy.getVectorNumElements(); 11569 11570 // If the increment is a constant, it must match the memory ref size. 11571 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11572 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11573 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11574 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11575 // separate instructions that make it harder to use a non-constant update. 11576 continue; 11577 } 11578 11579 // OK, we found an ADD we can fold into the base update. 11580 // Now, create a _UPD node, taking care of not breaking alignment. 11581 11582 EVT AlignedVecTy = VecTy; 11583 unsigned Alignment = MemN->getAlignment(); 11584 11585 // If this is a less-than-standard-aligned load/store, change the type to 11586 // match the standard alignment. 11587 // The alignment is overlooked when selecting _UPD variants; and it's 11588 // easier to introduce bitcasts here than fix that. 11589 // There are 3 ways to get to this base-update combine: 11590 // - intrinsics: they are assumed to be properly aligned (to the standard 11591 // alignment of the memory type), so we don't need to do anything. 11592 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11593 // intrinsics, so, likewise, there's nothing to do. 11594 // - generic load/store instructions: the alignment is specified as an 11595 // explicit operand, rather than implicitly as the standard alignment 11596 // of the memory type (like the intrisics). We need to change the 11597 // memory type to match the explicit alignment. That way, we don't 11598 // generate non-standard-aligned ARMISD::VLDx nodes. 11599 if (isa<LSBaseSDNode>(N)) { 11600 if (Alignment == 0) 11601 Alignment = 1; 11602 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11603 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11604 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11605 assert(!isLaneOp && "Unexpected generic load/store lane."); 11606 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11607 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11608 } 11609 // Don't set an explicit alignment on regular load/stores that we want 11610 // to transform to VLD/VST 1_UPD nodes. 11611 // This matches the behavior of regular load/stores, which only get an 11612 // explicit alignment if the MMO alignment is larger than the standard 11613 // alignment of the memory type. 11614 // Intrinsics, however, always get an explicit alignment, set to the 11615 // alignment of the MMO. 11616 Alignment = 1; 11617 } 11618 11619 // Create the new updating load/store node. 11620 // First, create an SDVTList for the new updating node's results. 11621 EVT Tys[6]; 11622 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11623 unsigned n; 11624 for (n = 0; n < NumResultVecs; ++n) 11625 Tys[n] = AlignedVecTy; 11626 Tys[n++] = MVT::i32; 11627 Tys[n] = MVT::Other; 11628 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11629 11630 // Then, gather the new node's operands. 11631 SmallVector<SDValue, 8> Ops; 11632 Ops.push_back(N->getOperand(0)); // incoming chain 11633 Ops.push_back(N->getOperand(AddrOpIdx)); 11634 Ops.push_back(Inc); 11635 11636 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11637 // Try to match the intrinsic's signature 11638 Ops.push_back(StN->getValue()); 11639 } else { 11640 // Loads (and of course intrinsics) match the intrinsics' signature, 11641 // so just add all but the alignment operand. 11642 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11643 Ops.push_back(N->getOperand(i)); 11644 } 11645 11646 // For all node types, the alignment operand is always the last one. 11647 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11648 11649 // If this is a non-standard-aligned STORE, the penultimate operand is the 11650 // stored value. Bitcast it to the aligned type. 11651 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11652 SDValue &StVal = Ops[Ops.size()-2]; 11653 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11654 } 11655 11656 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11657 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11658 MemN->getMemOperand()); 11659 11660 // Update the uses. 11661 SmallVector<SDValue, 5> NewResults; 11662 for (unsigned i = 0; i < NumResultVecs; ++i) 11663 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11664 11665 // If this is an non-standard-aligned LOAD, the first result is the loaded 11666 // value. Bitcast it to the expected result type. 11667 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11668 SDValue &LdVal = NewResults[0]; 11669 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11670 } 11671 11672 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11673 DCI.CombineTo(N, NewResults); 11674 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11675 11676 break; 11677 } 11678 return SDValue(); 11679 } 11680 11681 static SDValue PerformVLDCombine(SDNode *N, 11682 TargetLowering::DAGCombinerInfo &DCI) { 11683 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11684 return SDValue(); 11685 11686 return CombineBaseUpdate(N, DCI); 11687 } 11688 11689 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11690 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11691 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11692 /// return true. 11693 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11694 SelectionDAG &DAG = DCI.DAG; 11695 EVT VT = N->getValueType(0); 11696 // vldN-dup instructions only support 64-bit vectors for N > 1. 11697 if (!VT.is64BitVector()) 11698 return false; 11699 11700 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11701 SDNode *VLD = N->getOperand(0).getNode(); 11702 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11703 return false; 11704 unsigned NumVecs = 0; 11705 unsigned NewOpc = 0; 11706 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11707 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11708 NumVecs = 2; 11709 NewOpc = ARMISD::VLD2DUP; 11710 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11711 NumVecs = 3; 11712 NewOpc = ARMISD::VLD3DUP; 11713 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11714 NumVecs = 4; 11715 NewOpc = ARMISD::VLD4DUP; 11716 } else { 11717 return false; 11718 } 11719 11720 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11721 // numbers match the load. 11722 unsigned VLDLaneNo = 11723 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11724 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11725 UI != UE; ++UI) { 11726 // Ignore uses of the chain result. 11727 if (UI.getUse().getResNo() == NumVecs) 11728 continue; 11729 SDNode *User = *UI; 11730 if (User->getOpcode() != ARMISD::VDUPLANE || 11731 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11732 return false; 11733 } 11734 11735 // Create the vldN-dup node. 11736 EVT Tys[5]; 11737 unsigned n; 11738 for (n = 0; n < NumVecs; ++n) 11739 Tys[n] = VT; 11740 Tys[n] = MVT::Other; 11741 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11742 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11743 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11744 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11745 Ops, VLDMemInt->getMemoryVT(), 11746 VLDMemInt->getMemOperand()); 11747 11748 // Update the uses. 11749 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11750 UI != UE; ++UI) { 11751 unsigned ResNo = UI.getUse().getResNo(); 11752 // Ignore uses of the chain result. 11753 if (ResNo == NumVecs) 11754 continue; 11755 SDNode *User = *UI; 11756 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11757 } 11758 11759 // Now the vldN-lane intrinsic is dead except for its chain result. 11760 // Update uses of the chain. 11761 std::vector<SDValue> VLDDupResults; 11762 for (unsigned n = 0; n < NumVecs; ++n) 11763 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11764 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11765 DCI.CombineTo(VLD, VLDDupResults); 11766 11767 return true; 11768 } 11769 11770 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11771 /// ARMISD::VDUPLANE. 11772 static SDValue PerformVDUPLANECombine(SDNode *N, 11773 TargetLowering::DAGCombinerInfo &DCI) { 11774 SDValue Op = N->getOperand(0); 11775 11776 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11777 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11778 if (CombineVLDDUP(N, DCI)) 11779 return SDValue(N, 0); 11780 11781 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11782 // redundant. Ignore bit_converts for now; element sizes are checked below. 11783 while (Op.getOpcode() == ISD::BITCAST) 11784 Op = Op.getOperand(0); 11785 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11786 return SDValue(); 11787 11788 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11789 unsigned EltSize = Op.getScalarValueSizeInBits(); 11790 // The canonical VMOV for a zero vector uses a 32-bit element size. 11791 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11792 unsigned EltBits; 11793 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11794 EltSize = 8; 11795 EVT VT = N->getValueType(0); 11796 if (EltSize > VT.getScalarSizeInBits()) 11797 return SDValue(); 11798 11799 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11800 } 11801 11802 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11803 static SDValue PerformVDUPCombine(SDNode *N, 11804 TargetLowering::DAGCombinerInfo &DCI) { 11805 SelectionDAG &DAG = DCI.DAG; 11806 SDValue Op = N->getOperand(0); 11807 11808 // Match VDUP(LOAD) -> VLD1DUP. 11809 // We match this pattern here rather than waiting for isel because the 11810 // transform is only legal for unindexed loads. 11811 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11812 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11813 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11814 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11815 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11816 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11817 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11818 Ops, LD->getMemoryVT(), 11819 LD->getMemOperand()); 11820 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11821 return VLDDup; 11822 } 11823 11824 return SDValue(); 11825 } 11826 11827 static SDValue PerformLOADCombine(SDNode *N, 11828 TargetLowering::DAGCombinerInfo &DCI) { 11829 EVT VT = N->getValueType(0); 11830 11831 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11832 if (ISD::isNormalLoad(N) && VT.isVector() && 11833 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11834 return CombineBaseUpdate(N, DCI); 11835 11836 return SDValue(); 11837 } 11838 11839 /// PerformSTORECombine - Target-specific dag combine xforms for 11840 /// ISD::STORE. 11841 static SDValue PerformSTORECombine(SDNode *N, 11842 TargetLowering::DAGCombinerInfo &DCI) { 11843 StoreSDNode *St = cast<StoreSDNode>(N); 11844 if (St->isVolatile()) 11845 return SDValue(); 11846 11847 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11848 // pack all of the elements in one place. Next, store to memory in fewer 11849 // chunks. 11850 SDValue StVal = St->getValue(); 11851 EVT VT = StVal.getValueType(); 11852 if (St->isTruncatingStore() && VT.isVector()) { 11853 SelectionDAG &DAG = DCI.DAG; 11854 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11855 EVT StVT = St->getMemoryVT(); 11856 unsigned NumElems = VT.getVectorNumElements(); 11857 assert(StVT != VT && "Cannot truncate to the same type"); 11858 unsigned FromEltSz = VT.getScalarSizeInBits(); 11859 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11860 11861 // From, To sizes and ElemCount must be pow of two 11862 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11863 11864 // We are going to use the original vector elt for storing. 11865 // Accumulated smaller vector elements must be a multiple of the store size. 11866 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11867 11868 unsigned SizeRatio = FromEltSz / ToEltSz; 11869 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11870 11871 // Create a type on which we perform the shuffle. 11872 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11873 NumElems*SizeRatio); 11874 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11875 11876 SDLoc DL(St); 11877 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11878 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11879 for (unsigned i = 0; i < NumElems; ++i) 11880 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11881 ? (i + 1) * SizeRatio - 1 11882 : i * SizeRatio; 11883 11884 // Can't shuffle using an illegal type. 11885 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11886 11887 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11888 DAG.getUNDEF(WideVec.getValueType()), 11889 ShuffleVec); 11890 // At this point all of the data is stored at the bottom of the 11891 // register. We now need to save it to mem. 11892 11893 // Find the largest store unit 11894 MVT StoreType = MVT::i8; 11895 for (MVT Tp : MVT::integer_valuetypes()) { 11896 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11897 StoreType = Tp; 11898 } 11899 // Didn't find a legal store type. 11900 if (!TLI.isTypeLegal(StoreType)) 11901 return SDValue(); 11902 11903 // Bitcast the original vector into a vector of store-size units 11904 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11905 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11906 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11907 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11908 SmallVector<SDValue, 8> Chains; 11909 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11910 TLI.getPointerTy(DAG.getDataLayout())); 11911 SDValue BasePtr = St->getBasePtr(); 11912 11913 // Perform one or more big stores into memory. 11914 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11915 for (unsigned I = 0; I < E; I++) { 11916 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11917 StoreType, ShuffWide, 11918 DAG.getIntPtrConstant(I, DL)); 11919 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11920 St->getPointerInfo(), St->getAlignment(), 11921 St->getMemOperand()->getFlags()); 11922 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11923 Increment); 11924 Chains.push_back(Ch); 11925 } 11926 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11927 } 11928 11929 if (!ISD::isNormalStore(St)) 11930 return SDValue(); 11931 11932 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11933 // ARM stores of arguments in the same cache line. 11934 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11935 StVal.getNode()->hasOneUse()) { 11936 SelectionDAG &DAG = DCI.DAG; 11937 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11938 SDLoc DL(St); 11939 SDValue BasePtr = St->getBasePtr(); 11940 SDValue NewST1 = DAG.getStore( 11941 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11942 BasePtr, St->getPointerInfo(), St->getAlignment(), 11943 St->getMemOperand()->getFlags()); 11944 11945 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11946 DAG.getConstant(4, DL, MVT::i32)); 11947 return DAG.getStore(NewST1.getValue(0), DL, 11948 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11949 OffsetPtr, St->getPointerInfo(), 11950 std::min(4U, St->getAlignment() / 2), 11951 St->getMemOperand()->getFlags()); 11952 } 11953 11954 if (StVal.getValueType() == MVT::i64 && 11955 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11956 11957 // Bitcast an i64 store extracted from a vector to f64. 11958 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11959 SelectionDAG &DAG = DCI.DAG; 11960 SDLoc dl(StVal); 11961 SDValue IntVec = StVal.getOperand(0); 11962 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11963 IntVec.getValueType().getVectorNumElements()); 11964 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11965 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11966 Vec, StVal.getOperand(1)); 11967 dl = SDLoc(N); 11968 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11969 // Make the DAGCombiner fold the bitcasts. 11970 DCI.AddToWorklist(Vec.getNode()); 11971 DCI.AddToWorklist(ExtElt.getNode()); 11972 DCI.AddToWorklist(V.getNode()); 11973 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11974 St->getPointerInfo(), St->getAlignment(), 11975 St->getMemOperand()->getFlags(), St->getAAInfo()); 11976 } 11977 11978 // If this is a legal vector store, try to combine it into a VST1_UPD. 11979 if (ISD::isNormalStore(N) && VT.isVector() && 11980 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11981 return CombineBaseUpdate(N, DCI); 11982 11983 return SDValue(); 11984 } 11985 11986 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11987 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11988 /// when the VMUL has a constant operand that is a power of 2. 11989 /// 11990 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11991 /// vmul.f32 d16, d17, d16 11992 /// vcvt.s32.f32 d16, d16 11993 /// becomes: 11994 /// vcvt.s32.f32 d16, d16, #3 11995 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11996 const ARMSubtarget *Subtarget) { 11997 if (!Subtarget->hasNEON()) 11998 return SDValue(); 11999 12000 SDValue Op = N->getOperand(0); 12001 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12002 Op.getOpcode() != ISD::FMUL) 12003 return SDValue(); 12004 12005 SDValue ConstVec = Op->getOperand(1); 12006 if (!isa<BuildVectorSDNode>(ConstVec)) 12007 return SDValue(); 12008 12009 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 12010 uint32_t FloatBits = FloatTy.getSizeInBits(); 12011 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 12012 uint32_t IntBits = IntTy.getSizeInBits(); 12013 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12014 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 12015 // These instructions only exist converting from f32 to i32. We can handle 12016 // smaller integers by generating an extra truncate, but larger ones would 12017 // be lossy. We also can't handle more then 4 lanes, since these intructions 12018 // only support v2i32/v4i32 types. 12019 return SDValue(); 12020 } 12021 12022 BitVector UndefElements; 12023 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12024 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12025 if (C == -1 || C == 0 || C > 32) 12026 return SDValue(); 12027 12028 SDLoc dl(N); 12029 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 12030 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 12031 Intrinsic::arm_neon_vcvtfp2fxu; 12032 SDValue FixConv = DAG.getNode( 12033 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12034 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 12035 DAG.getConstant(C, dl, MVT::i32)); 12036 12037 if (IntBits < FloatBits) 12038 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 12039 12040 return FixConv; 12041 } 12042 12043 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 12044 /// can replace combinations of VCVT (integer to floating-point) and VDIV 12045 /// when the VDIV has a constant operand that is a power of 2. 12046 /// 12047 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12048 /// vcvt.f32.s32 d16, d16 12049 /// vdiv.f32 d16, d17, d16 12050 /// becomes: 12051 /// vcvt.f32.s32 d16, d16, #3 12052 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 12053 const ARMSubtarget *Subtarget) { 12054 if (!Subtarget->hasNEON()) 12055 return SDValue(); 12056 12057 SDValue Op = N->getOperand(0); 12058 unsigned OpOpcode = Op.getNode()->getOpcode(); 12059 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 12060 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 12061 return SDValue(); 12062 12063 SDValue ConstVec = N->getOperand(1); 12064 if (!isa<BuildVectorSDNode>(ConstVec)) 12065 return SDValue(); 12066 12067 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12068 uint32_t FloatBits = FloatTy.getSizeInBits(); 12069 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12070 uint32_t IntBits = IntTy.getSizeInBits(); 12071 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12072 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 12073 // These instructions only exist converting from i32 to f32. We can handle 12074 // smaller integers by generating an extra extend, but larger ones would 12075 // be lossy. We also can't handle more then 4 lanes, since these intructions 12076 // only support v2i32/v4i32 types. 12077 return SDValue(); 12078 } 12079 12080 BitVector UndefElements; 12081 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12082 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12083 if (C == -1 || C == 0 || C > 32) 12084 return SDValue(); 12085 12086 SDLoc dl(N); 12087 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 12088 SDValue ConvInput = Op.getOperand(0); 12089 if (IntBits < FloatBits) 12090 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12091 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12092 ConvInput); 12093 12094 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 12095 Intrinsic::arm_neon_vcvtfxu2fp; 12096 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 12097 Op.getValueType(), 12098 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 12099 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 12100 } 12101 12102 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 12103 /// operand of a vector shift operation, where all the elements of the 12104 /// build_vector must have the same constant integer value. 12105 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 12106 // Ignore bit_converts. 12107 while (Op.getOpcode() == ISD::BITCAST) 12108 Op = Op.getOperand(0); 12109 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 12110 APInt SplatBits, SplatUndef; 12111 unsigned SplatBitSize; 12112 bool HasAnyUndefs; 12113 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 12114 HasAnyUndefs, ElementBits) || 12115 SplatBitSize > ElementBits) 12116 return false; 12117 Cnt = SplatBits.getSExtValue(); 12118 return true; 12119 } 12120 12121 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 12122 /// operand of a vector shift left operation. That value must be in the range: 12123 /// 0 <= Value < ElementBits for a left shift; or 12124 /// 0 <= Value <= ElementBits for a long left shift. 12125 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 12126 assert(VT.isVector() && "vector shift count is not a vector type"); 12127 int64_t ElementBits = VT.getScalarSizeInBits(); 12128 if (! getVShiftImm(Op, ElementBits, Cnt)) 12129 return false; 12130 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 12131 } 12132 12133 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 12134 /// operand of a vector shift right operation. For a shift opcode, the value 12135 /// is positive, but for an intrinsic the value count must be negative. The 12136 /// absolute value must be in the range: 12137 /// 1 <= |Value| <= ElementBits for a right shift; or 12138 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 12139 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 12140 int64_t &Cnt) { 12141 assert(VT.isVector() && "vector shift count is not a vector type"); 12142 int64_t ElementBits = VT.getScalarSizeInBits(); 12143 if (! getVShiftImm(Op, ElementBits, Cnt)) 12144 return false; 12145 if (!isIntrinsic) 12146 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 12147 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 12148 Cnt = -Cnt; 12149 return true; 12150 } 12151 return false; 12152 } 12153 12154 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 12155 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 12156 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12157 switch (IntNo) { 12158 default: 12159 // Don't do anything for most intrinsics. 12160 break; 12161 12162 // Vector shifts: check for immediate versions and lower them. 12163 // Note: This is done during DAG combining instead of DAG legalizing because 12164 // the build_vectors for 64-bit vector element shift counts are generally 12165 // not legal, and it is hard to see their values after they get legalized to 12166 // loads from a constant pool. 12167 case Intrinsic::arm_neon_vshifts: 12168 case Intrinsic::arm_neon_vshiftu: 12169 case Intrinsic::arm_neon_vrshifts: 12170 case Intrinsic::arm_neon_vrshiftu: 12171 case Intrinsic::arm_neon_vrshiftn: 12172 case Intrinsic::arm_neon_vqshifts: 12173 case Intrinsic::arm_neon_vqshiftu: 12174 case Intrinsic::arm_neon_vqshiftsu: 12175 case Intrinsic::arm_neon_vqshiftns: 12176 case Intrinsic::arm_neon_vqshiftnu: 12177 case Intrinsic::arm_neon_vqshiftnsu: 12178 case Intrinsic::arm_neon_vqrshiftns: 12179 case Intrinsic::arm_neon_vqrshiftnu: 12180 case Intrinsic::arm_neon_vqrshiftnsu: { 12181 EVT VT = N->getOperand(1).getValueType(); 12182 int64_t Cnt; 12183 unsigned VShiftOpc = 0; 12184 12185 switch (IntNo) { 12186 case Intrinsic::arm_neon_vshifts: 12187 case Intrinsic::arm_neon_vshiftu: 12188 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 12189 VShiftOpc = ARMISD::VSHL; 12190 break; 12191 } 12192 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 12193 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 12194 ARMISD::VSHRs : ARMISD::VSHRu); 12195 break; 12196 } 12197 return SDValue(); 12198 12199 case Intrinsic::arm_neon_vrshifts: 12200 case Intrinsic::arm_neon_vrshiftu: 12201 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 12202 break; 12203 return SDValue(); 12204 12205 case Intrinsic::arm_neon_vqshifts: 12206 case Intrinsic::arm_neon_vqshiftu: 12207 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12208 break; 12209 return SDValue(); 12210 12211 case Intrinsic::arm_neon_vqshiftsu: 12212 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12213 break; 12214 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 12215 12216 case Intrinsic::arm_neon_vrshiftn: 12217 case Intrinsic::arm_neon_vqshiftns: 12218 case Intrinsic::arm_neon_vqshiftnu: 12219 case Intrinsic::arm_neon_vqshiftnsu: 12220 case Intrinsic::arm_neon_vqrshiftns: 12221 case Intrinsic::arm_neon_vqrshiftnu: 12222 case Intrinsic::arm_neon_vqrshiftnsu: 12223 // Narrowing shifts require an immediate right shift. 12224 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 12225 break; 12226 llvm_unreachable("invalid shift count for narrowing vector shift " 12227 "intrinsic"); 12228 12229 default: 12230 llvm_unreachable("unhandled vector shift"); 12231 } 12232 12233 switch (IntNo) { 12234 case Intrinsic::arm_neon_vshifts: 12235 case Intrinsic::arm_neon_vshiftu: 12236 // Opcode already set above. 12237 break; 12238 case Intrinsic::arm_neon_vrshifts: 12239 VShiftOpc = ARMISD::VRSHRs; break; 12240 case Intrinsic::arm_neon_vrshiftu: 12241 VShiftOpc = ARMISD::VRSHRu; break; 12242 case Intrinsic::arm_neon_vrshiftn: 12243 VShiftOpc = ARMISD::VRSHRN; break; 12244 case Intrinsic::arm_neon_vqshifts: 12245 VShiftOpc = ARMISD::VQSHLs; break; 12246 case Intrinsic::arm_neon_vqshiftu: 12247 VShiftOpc = ARMISD::VQSHLu; break; 12248 case Intrinsic::arm_neon_vqshiftsu: 12249 VShiftOpc = ARMISD::VQSHLsu; break; 12250 case Intrinsic::arm_neon_vqshiftns: 12251 VShiftOpc = ARMISD::VQSHRNs; break; 12252 case Intrinsic::arm_neon_vqshiftnu: 12253 VShiftOpc = ARMISD::VQSHRNu; break; 12254 case Intrinsic::arm_neon_vqshiftnsu: 12255 VShiftOpc = ARMISD::VQSHRNsu; break; 12256 case Intrinsic::arm_neon_vqrshiftns: 12257 VShiftOpc = ARMISD::VQRSHRNs; break; 12258 case Intrinsic::arm_neon_vqrshiftnu: 12259 VShiftOpc = ARMISD::VQRSHRNu; break; 12260 case Intrinsic::arm_neon_vqrshiftnsu: 12261 VShiftOpc = ARMISD::VQRSHRNsu; break; 12262 } 12263 12264 SDLoc dl(N); 12265 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12266 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 12267 } 12268 12269 case Intrinsic::arm_neon_vshiftins: { 12270 EVT VT = N->getOperand(1).getValueType(); 12271 int64_t Cnt; 12272 unsigned VShiftOpc = 0; 12273 12274 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 12275 VShiftOpc = ARMISD::VSLI; 12276 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 12277 VShiftOpc = ARMISD::VSRI; 12278 else { 12279 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 12280 } 12281 12282 SDLoc dl(N); 12283 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12284 N->getOperand(1), N->getOperand(2), 12285 DAG.getConstant(Cnt, dl, MVT::i32)); 12286 } 12287 12288 case Intrinsic::arm_neon_vqrshifts: 12289 case Intrinsic::arm_neon_vqrshiftu: 12290 // No immediate versions of these to check for. 12291 break; 12292 } 12293 12294 return SDValue(); 12295 } 12296 12297 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12298 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12299 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12300 /// vector element shift counts are generally not legal, and it is hard to see 12301 /// their values after they get legalized to loads from a constant pool. 12302 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 12303 const ARMSubtarget *ST) { 12304 EVT VT = N->getValueType(0); 12305 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12306 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12307 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12308 SDValue N1 = N->getOperand(1); 12309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12310 SDValue N0 = N->getOperand(0); 12311 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12312 DAG.MaskedValueIsZero(N0.getOperand(0), 12313 APInt::getHighBitsSet(32, 16))) 12314 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12315 } 12316 } 12317 12318 // Nothing to be done for scalar shifts. 12319 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12320 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12321 return SDValue(); 12322 12323 assert(ST->hasNEON() && "unexpected vector shift"); 12324 int64_t Cnt; 12325 12326 switch (N->getOpcode()) { 12327 default: llvm_unreachable("unexpected shift opcode"); 12328 12329 case ISD::SHL: 12330 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12331 SDLoc dl(N); 12332 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 12333 DAG.getConstant(Cnt, dl, MVT::i32)); 12334 } 12335 break; 12336 12337 case ISD::SRA: 12338 case ISD::SRL: 12339 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12340 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 12341 ARMISD::VSHRs : ARMISD::VSHRu); 12342 SDLoc dl(N); 12343 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12344 DAG.getConstant(Cnt, dl, MVT::i32)); 12345 } 12346 } 12347 return SDValue(); 12348 } 12349 12350 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12351 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12352 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12353 const ARMSubtarget *ST) { 12354 SDValue N0 = N->getOperand(0); 12355 12356 // Check for sign- and zero-extensions of vector extract operations of 8- 12357 // and 16-bit vector elements. NEON supports these directly. They are 12358 // handled during DAG combining because type legalization will promote them 12359 // to 32-bit types and it is messy to recognize the operations after that. 12360 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12361 SDValue Vec = N0.getOperand(0); 12362 SDValue Lane = N0.getOperand(1); 12363 EVT VT = N->getValueType(0); 12364 EVT EltVT = N0.getValueType(); 12365 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12366 12367 if (VT == MVT::i32 && 12368 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12369 TLI.isTypeLegal(Vec.getValueType()) && 12370 isa<ConstantSDNode>(Lane)) { 12371 12372 unsigned Opc = 0; 12373 switch (N->getOpcode()) { 12374 default: llvm_unreachable("unexpected opcode"); 12375 case ISD::SIGN_EXTEND: 12376 Opc = ARMISD::VGETLANEs; 12377 break; 12378 case ISD::ZERO_EXTEND: 12379 case ISD::ANY_EXTEND: 12380 Opc = ARMISD::VGETLANEu; 12381 break; 12382 } 12383 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12384 } 12385 } 12386 12387 return SDValue(); 12388 } 12389 12390 static const APInt *isPowerOf2Constant(SDValue V) { 12391 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12392 if (!C) 12393 return nullptr; 12394 const APInt *CV = &C->getAPIntValue(); 12395 return CV->isPowerOf2() ? CV : nullptr; 12396 } 12397 12398 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12399 // If we have a CMOV, OR and AND combination such as: 12400 // if (x & CN) 12401 // y |= CM; 12402 // 12403 // And: 12404 // * CN is a single bit; 12405 // * All bits covered by CM are known zero in y 12406 // 12407 // Then we can convert this into a sequence of BFI instructions. This will 12408 // always be a win if CM is a single bit, will always be no worse than the 12409 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12410 // three bits (due to the extra IT instruction). 12411 12412 SDValue Op0 = CMOV->getOperand(0); 12413 SDValue Op1 = CMOV->getOperand(1); 12414 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12415 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12416 SDValue CmpZ = CMOV->getOperand(4); 12417 12418 // The compare must be against zero. 12419 if (!isNullConstant(CmpZ->getOperand(1))) 12420 return SDValue(); 12421 12422 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12423 SDValue And = CmpZ->getOperand(0); 12424 if (And->getOpcode() != ISD::AND) 12425 return SDValue(); 12426 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12427 if (!AndC) 12428 return SDValue(); 12429 SDValue X = And->getOperand(0); 12430 12431 if (CC == ARMCC::EQ) { 12432 // We're performing an "equal to zero" compare. Swap the operands so we 12433 // canonicalize on a "not equal to zero" compare. 12434 std::swap(Op0, Op1); 12435 } else { 12436 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12437 } 12438 12439 if (Op1->getOpcode() != ISD::OR) 12440 return SDValue(); 12441 12442 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12443 if (!OrC) 12444 return SDValue(); 12445 SDValue Y = Op1->getOperand(0); 12446 12447 if (Op0 != Y) 12448 return SDValue(); 12449 12450 // Now, is it profitable to continue? 12451 APInt OrCI = OrC->getAPIntValue(); 12452 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12453 if (OrCI.countPopulation() > Heuristic) 12454 return SDValue(); 12455 12456 // Lastly, can we determine that the bits defined by OrCI 12457 // are zero in Y? 12458 KnownBits Known; 12459 DAG.computeKnownBits(Y, Known); 12460 if ((OrCI & Known.Zero) != OrCI) 12461 return SDValue(); 12462 12463 // OK, we can do the combine. 12464 SDValue V = Y; 12465 SDLoc dl(X); 12466 EVT VT = X.getValueType(); 12467 unsigned BitInX = AndC->logBase2(); 12468 12469 if (BitInX != 0) { 12470 // We must shift X first. 12471 X = DAG.getNode(ISD::SRL, dl, VT, X, 12472 DAG.getConstant(BitInX, dl, VT)); 12473 } 12474 12475 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12476 BitInY < NumActiveBits; ++BitInY) { 12477 if (OrCI[BitInY] == 0) 12478 continue; 12479 APInt Mask(VT.getSizeInBits(), 0); 12480 Mask.setBit(BitInY); 12481 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12482 // Confusingly, the operand is an *inverted* mask. 12483 DAG.getConstant(~Mask, dl, VT)); 12484 } 12485 12486 return V; 12487 } 12488 12489 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12490 SDValue 12491 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12492 SDValue Cmp = N->getOperand(4); 12493 if (Cmp.getOpcode() != ARMISD::CMPZ) 12494 // Only looking at NE cases. 12495 return SDValue(); 12496 12497 EVT VT = N->getValueType(0); 12498 SDLoc dl(N); 12499 SDValue LHS = Cmp.getOperand(0); 12500 SDValue RHS = Cmp.getOperand(1); 12501 SDValue Chain = N->getOperand(0); 12502 SDValue BB = N->getOperand(1); 12503 SDValue ARMcc = N->getOperand(2); 12504 ARMCC::CondCodes CC = 12505 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12506 12507 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12508 // -> (brcond Chain BB CC CPSR Cmp) 12509 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12510 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12511 LHS->getOperand(0)->hasOneUse()) { 12512 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12513 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12514 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12515 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12516 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12517 (LHS01C && LHS01C->getZExtValue() == 1) && 12518 (LHS1C && LHS1C->getZExtValue() == 1) && 12519 (RHSC && RHSC->getZExtValue() == 0)) { 12520 return DAG.getNode( 12521 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12522 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12523 } 12524 } 12525 12526 return SDValue(); 12527 } 12528 12529 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12530 SDValue 12531 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12532 SDValue Cmp = N->getOperand(4); 12533 if (Cmp.getOpcode() != ARMISD::CMPZ) 12534 // Only looking at EQ and NE cases. 12535 return SDValue(); 12536 12537 EVT VT = N->getValueType(0); 12538 SDLoc dl(N); 12539 SDValue LHS = Cmp.getOperand(0); 12540 SDValue RHS = Cmp.getOperand(1); 12541 SDValue FalseVal = N->getOperand(0); 12542 SDValue TrueVal = N->getOperand(1); 12543 SDValue ARMcc = N->getOperand(2); 12544 ARMCC::CondCodes CC = 12545 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12546 12547 // BFI is only available on V6T2+. 12548 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12549 SDValue R = PerformCMOVToBFICombine(N, DAG); 12550 if (R) 12551 return R; 12552 } 12553 12554 // Simplify 12555 // mov r1, r0 12556 // cmp r1, x 12557 // mov r0, y 12558 // moveq r0, x 12559 // to 12560 // cmp r0, x 12561 // movne r0, y 12562 // 12563 // mov r1, r0 12564 // cmp r1, x 12565 // mov r0, x 12566 // movne r0, y 12567 // to 12568 // cmp r0, x 12569 // movne r0, y 12570 /// FIXME: Turn this into a target neutral optimization? 12571 SDValue Res; 12572 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12573 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12574 N->getOperand(3), Cmp); 12575 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12576 SDValue ARMcc; 12577 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12578 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12579 N->getOperand(3), NewCmp); 12580 } 12581 12582 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12583 // -> (cmov F T CC CPSR Cmp) 12584 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12585 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12586 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12587 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12588 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12589 (LHS1C && LHS1C->getZExtValue() == 1) && 12590 (RHSC && RHSC->getZExtValue() == 0)) { 12591 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12592 LHS->getOperand(2), LHS->getOperand(3), 12593 LHS->getOperand(4)); 12594 } 12595 } 12596 12597 if (!VT.isInteger()) 12598 return SDValue(); 12599 12600 // Materialize a boolean comparison for integers so we can avoid branching. 12601 if (isNullConstant(FalseVal)) { 12602 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 12603 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 12604 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 12605 // right 5 bits will make that 32 be 1, otherwise it will be 0. 12606 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 12607 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12608 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 12609 DAG.getConstant(5, dl, MVT::i32)); 12610 } else { 12611 // CMOV 0, 1, ==, (CMPZ x, y) -> 12612 // (ADDCARRY (SUB x, y), t:0, t:1) 12613 // where t = (SUBCARRY 0, (SUB x, y), 0) 12614 // 12615 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 12616 // x != y. In other words, a carry C == 1 when x == y, C == 0 12617 // otherwise. 12618 // The final ADDCARRY computes 12619 // x - y + (0 - (x - y)) + C == C 12620 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12621 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12622 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 12623 // ISD::SUBCARRY returns a borrow but we want the carry here 12624 // actually. 12625 SDValue Carry = 12626 DAG.getNode(ISD::SUB, dl, MVT::i32, 12627 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 12628 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 12629 } 12630 } else if (CC == ARMCC::NE && LHS != RHS && 12631 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 12632 // This seems pointless but will allow us to combine it further below. 12633 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y) 12634 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12635 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 12636 N->getOperand(3), Cmp); 12637 } 12638 } else if (isNullConstant(TrueVal)) { 12639 if (CC == ARMCC::EQ && LHS != RHS && 12640 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 12641 // This seems pointless but will allow us to combine it further below 12642 // Note that we change == for != as this is the dual for the case above. 12643 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y) 12644 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12645 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 12646 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 12647 N->getOperand(3), Cmp); 12648 } 12649 } 12650 12651 // On Thumb1, the DAG above may be further combined if z is a power of 2 12652 // (z == 2 ^ K). 12653 // CMOV (SUB x, y), z, !=, (CMPZ x, y) -> 12654 // merge t3, t4 12655 // where t1 = (SUBCARRY (SUB x, y), z, 0) 12656 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 12657 // t3 = if K != 0 then (SHL t2:0, K) else t2:0 12658 // t4 = (SUB 1, t2:1) [ we want a carry, not a borrow ] 12659 const APInt *TrueConst; 12660 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 12661 (FalseVal.getOpcode() == ISD::SUB) && (FalseVal.getOperand(0) == LHS) && 12662 (FalseVal.getOperand(1) == RHS) && 12663 (TrueConst = isPowerOf2Constant(TrueVal))) { 12664 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12665 unsigned ShiftAmount = TrueConst->logBase2(); 12666 if (ShiftAmount) 12667 TrueVal = DAG.getConstant(1, dl, VT); 12668 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 12669 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 12670 // Make it a carry, not a borrow. 12671 SDValue Carry = DAG.getNode( 12672 ISD::SUB, dl, VT, DAG.getConstant(1, dl, MVT::i32), Res.getValue(1)); 12673 Res = DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Res, Carry); 12674 12675 if (ShiftAmount) 12676 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 12677 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 12678 } 12679 12680 if (Res.getNode()) { 12681 KnownBits Known; 12682 DAG.computeKnownBits(SDValue(N,0), Known); 12683 // Capture demanded bits information that would be otherwise lost. 12684 if (Known.Zero == 0xfffffffe) 12685 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12686 DAG.getValueType(MVT::i1)); 12687 else if (Known.Zero == 0xffffff00) 12688 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12689 DAG.getValueType(MVT::i8)); 12690 else if (Known.Zero == 0xffff0000) 12691 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12692 DAG.getValueType(MVT::i16)); 12693 } 12694 12695 return Res; 12696 } 12697 12698 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12699 DAGCombinerInfo &DCI) const { 12700 switch (N->getOpcode()) { 12701 default: break; 12702 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12703 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12704 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12705 case ISD::SUB: return PerformSUBCombine(N, DCI); 12706 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12707 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12708 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12709 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12710 case ARMISD::ADDC: 12711 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12712 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 12713 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12714 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12715 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12716 case ISD::STORE: return PerformSTORECombine(N, DCI); 12717 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12718 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12719 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12720 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12721 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12722 case ISD::FP_TO_SINT: 12723 case ISD::FP_TO_UINT: 12724 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12725 case ISD::FDIV: 12726 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12727 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12728 case ISD::SHL: 12729 case ISD::SRA: 12730 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 12731 case ISD::SIGN_EXTEND: 12732 case ISD::ZERO_EXTEND: 12733 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12734 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12735 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12736 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12737 case ARMISD::VLD1DUP: 12738 case ARMISD::VLD2DUP: 12739 case ARMISD::VLD3DUP: 12740 case ARMISD::VLD4DUP: 12741 return PerformVLDCombine(N, DCI); 12742 case ARMISD::BUILD_VECTOR: 12743 return PerformARMBUILD_VECTORCombine(N, DCI); 12744 case ARMISD::SMULWB: { 12745 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12746 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12747 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12748 return SDValue(); 12749 break; 12750 } 12751 case ARMISD::SMULWT: { 12752 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12753 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12754 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12755 return SDValue(); 12756 break; 12757 } 12758 case ARMISD::SMLALBB: { 12759 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12760 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12761 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12762 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12763 return SDValue(); 12764 break; 12765 } 12766 case ARMISD::SMLALBT: { 12767 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12768 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12769 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12770 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12771 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12772 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12773 return SDValue(); 12774 break; 12775 } 12776 case ARMISD::SMLALTB: { 12777 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12778 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12779 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12780 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12781 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12782 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12783 return SDValue(); 12784 break; 12785 } 12786 case ARMISD::SMLALTT: { 12787 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12788 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12789 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12790 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12791 return SDValue(); 12792 break; 12793 } 12794 case ISD::INTRINSIC_VOID: 12795 case ISD::INTRINSIC_W_CHAIN: 12796 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12797 case Intrinsic::arm_neon_vld1: 12798 case Intrinsic::arm_neon_vld2: 12799 case Intrinsic::arm_neon_vld3: 12800 case Intrinsic::arm_neon_vld4: 12801 case Intrinsic::arm_neon_vld2lane: 12802 case Intrinsic::arm_neon_vld3lane: 12803 case Intrinsic::arm_neon_vld4lane: 12804 case Intrinsic::arm_neon_vst1: 12805 case Intrinsic::arm_neon_vst2: 12806 case Intrinsic::arm_neon_vst3: 12807 case Intrinsic::arm_neon_vst4: 12808 case Intrinsic::arm_neon_vst2lane: 12809 case Intrinsic::arm_neon_vst3lane: 12810 case Intrinsic::arm_neon_vst4lane: 12811 return PerformVLDCombine(N, DCI); 12812 default: break; 12813 } 12814 break; 12815 } 12816 return SDValue(); 12817 } 12818 12819 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12820 EVT VT) const { 12821 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12822 } 12823 12824 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12825 unsigned, 12826 unsigned, 12827 bool *Fast) const { 12828 // Depends what it gets converted into if the type is weird. 12829 if (!VT.isSimple()) 12830 return false; 12831 12832 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12833 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12834 12835 switch (VT.getSimpleVT().SimpleTy) { 12836 default: 12837 return false; 12838 case MVT::i8: 12839 case MVT::i16: 12840 case MVT::i32: { 12841 // Unaligned access can use (for example) LRDB, LRDH, LDR 12842 if (AllowsUnaligned) { 12843 if (Fast) 12844 *Fast = Subtarget->hasV7Ops(); 12845 return true; 12846 } 12847 return false; 12848 } 12849 case MVT::f64: 12850 case MVT::v2f64: { 12851 // For any little-endian targets with neon, we can support unaligned ld/st 12852 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12853 // A big-endian target may also explicitly support unaligned accesses 12854 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12855 if (Fast) 12856 *Fast = true; 12857 return true; 12858 } 12859 return false; 12860 } 12861 } 12862 } 12863 12864 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12865 unsigned AlignCheck) { 12866 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12867 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12868 } 12869 12870 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12871 unsigned DstAlign, unsigned SrcAlign, 12872 bool IsMemset, bool ZeroMemset, 12873 bool MemcpyStrSrc, 12874 MachineFunction &MF) const { 12875 const Function &F = MF.getFunction(); 12876 12877 // See if we can use NEON instructions for this... 12878 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12879 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 12880 bool Fast; 12881 if (Size >= 16 && 12882 (memOpAlign(SrcAlign, DstAlign, 16) || 12883 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12884 return MVT::v2f64; 12885 } else if (Size >= 8 && 12886 (memOpAlign(SrcAlign, DstAlign, 8) || 12887 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12888 Fast))) { 12889 return MVT::f64; 12890 } 12891 } 12892 12893 // Let the target-independent logic figure it out. 12894 return MVT::Other; 12895 } 12896 12897 // 64-bit integers are split into their high and low parts and held in two 12898 // different registers, so the trunc is free since the low register can just 12899 // be used. 12900 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 12901 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 12902 return false; 12903 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 12904 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 12905 return (SrcBits == 64 && DestBits == 32); 12906 } 12907 12908 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 12909 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 12910 !DstVT.isInteger()) 12911 return false; 12912 unsigned SrcBits = SrcVT.getSizeInBits(); 12913 unsigned DestBits = DstVT.getSizeInBits(); 12914 return (SrcBits == 64 && DestBits == 32); 12915 } 12916 12917 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12918 if (Val.getOpcode() != ISD::LOAD) 12919 return false; 12920 12921 EVT VT1 = Val.getValueType(); 12922 if (!VT1.isSimple() || !VT1.isInteger() || 12923 !VT2.isSimple() || !VT2.isInteger()) 12924 return false; 12925 12926 switch (VT1.getSimpleVT().SimpleTy) { 12927 default: break; 12928 case MVT::i1: 12929 case MVT::i8: 12930 case MVT::i16: 12931 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12932 return true; 12933 } 12934 12935 return false; 12936 } 12937 12938 bool ARMTargetLowering::isFNegFree(EVT VT) const { 12939 if (!VT.isSimple()) 12940 return false; 12941 12942 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 12943 // negate values directly (fneg is free). So, we don't want to let the DAG 12944 // combiner rewrite fneg into xors and some other instructions. For f16 and 12945 // FullFP16 argument passing, some bitcast nodes may be introduced, 12946 // triggering this DAG combine rewrite, so we are avoiding that with this. 12947 switch (VT.getSimpleVT().SimpleTy) { 12948 default: break; 12949 case MVT::f16: 12950 return Subtarget->hasFullFP16(); 12951 } 12952 12953 return false; 12954 } 12955 12956 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12957 EVT VT = ExtVal.getValueType(); 12958 12959 if (!isTypeLegal(VT)) 12960 return false; 12961 12962 // Don't create a loadext if we can fold the extension into a wide/long 12963 // instruction. 12964 // If there's more than one user instruction, the loadext is desirable no 12965 // matter what. There can be two uses by the same instruction. 12966 if (ExtVal->use_empty() || 12967 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12968 return true; 12969 12970 SDNode *U = *ExtVal->use_begin(); 12971 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12972 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12973 return false; 12974 12975 return true; 12976 } 12977 12978 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12979 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12980 return false; 12981 12982 if (!isTypeLegal(EVT::getEVT(Ty1))) 12983 return false; 12984 12985 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12986 12987 // Assuming the caller doesn't have a zeroext or signext return parameter, 12988 // truncation all the way down to i1 is valid. 12989 return true; 12990 } 12991 12992 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12993 const AddrMode &AM, Type *Ty, 12994 unsigned AS) const { 12995 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12996 if (Subtarget->hasFPAO()) 12997 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12998 return 0; 12999 } 13000 return -1; 13001 } 13002 13003 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 13004 if (V < 0) 13005 return false; 13006 13007 unsigned Scale = 1; 13008 switch (VT.getSimpleVT().SimpleTy) { 13009 default: return false; 13010 case MVT::i1: 13011 case MVT::i8: 13012 // Scale == 1; 13013 break; 13014 case MVT::i16: 13015 // Scale == 2; 13016 Scale = 2; 13017 break; 13018 case MVT::i32: 13019 // Scale == 4; 13020 Scale = 4; 13021 break; 13022 } 13023 13024 if ((V & (Scale - 1)) != 0) 13025 return false; 13026 V /= Scale; 13027 return V == (V & ((1LL << 5) - 1)); 13028 } 13029 13030 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 13031 const ARMSubtarget *Subtarget) { 13032 bool isNeg = false; 13033 if (V < 0) { 13034 isNeg = true; 13035 V = - V; 13036 } 13037 13038 switch (VT.getSimpleVT().SimpleTy) { 13039 default: return false; 13040 case MVT::i1: 13041 case MVT::i8: 13042 case MVT::i16: 13043 case MVT::i32: 13044 // + imm12 or - imm8 13045 if (isNeg) 13046 return V == (V & ((1LL << 8) - 1)); 13047 return V == (V & ((1LL << 12) - 1)); 13048 case MVT::f32: 13049 case MVT::f64: 13050 // Same as ARM mode. FIXME: NEON? 13051 if (!Subtarget->hasVFP2()) 13052 return false; 13053 if ((V & 3) != 0) 13054 return false; 13055 V >>= 2; 13056 return V == (V & ((1LL << 8) - 1)); 13057 } 13058 } 13059 13060 /// isLegalAddressImmediate - Return true if the integer value can be used 13061 /// as the offset of the target addressing mode for load / store of the 13062 /// given type. 13063 static bool isLegalAddressImmediate(int64_t V, EVT VT, 13064 const ARMSubtarget *Subtarget) { 13065 if (V == 0) 13066 return true; 13067 13068 if (!VT.isSimple()) 13069 return false; 13070 13071 if (Subtarget->isThumb1Only()) 13072 return isLegalT1AddressImmediate(V, VT); 13073 else if (Subtarget->isThumb2()) 13074 return isLegalT2AddressImmediate(V, VT, Subtarget); 13075 13076 // ARM mode. 13077 if (V < 0) 13078 V = - V; 13079 switch (VT.getSimpleVT().SimpleTy) { 13080 default: return false; 13081 case MVT::i1: 13082 case MVT::i8: 13083 case MVT::i32: 13084 // +- imm12 13085 return V == (V & ((1LL << 12) - 1)); 13086 case MVT::i16: 13087 // +- imm8 13088 return V == (V & ((1LL << 8) - 1)); 13089 case MVT::f32: 13090 case MVT::f64: 13091 if (!Subtarget->hasVFP2()) // FIXME: NEON? 13092 return false; 13093 if ((V & 3) != 0) 13094 return false; 13095 V >>= 2; 13096 return V == (V & ((1LL << 8) - 1)); 13097 } 13098 } 13099 13100 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 13101 EVT VT) const { 13102 int Scale = AM.Scale; 13103 if (Scale < 0) 13104 return false; 13105 13106 switch (VT.getSimpleVT().SimpleTy) { 13107 default: return false; 13108 case MVT::i1: 13109 case MVT::i8: 13110 case MVT::i16: 13111 case MVT::i32: 13112 if (Scale == 1) 13113 return true; 13114 // r + r << imm 13115 Scale = Scale & ~1; 13116 return Scale == 2 || Scale == 4 || Scale == 8; 13117 case MVT::i64: 13118 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 13119 // version in Thumb mode. 13120 // r + r 13121 if (Scale == 1) 13122 return true; 13123 // r * 2 (this can be lowered to r + r). 13124 if (!AM.HasBaseReg && Scale == 2) 13125 return true; 13126 return false; 13127 case MVT::isVoid: 13128 // Note, we allow "void" uses (basically, uses that aren't loads or 13129 // stores), because arm allows folding a scale into many arithmetic 13130 // operations. This should be made more precise and revisited later. 13131 13132 // Allow r << imm, but the imm has to be a multiple of two. 13133 if (Scale & 1) return false; 13134 return isPowerOf2_32(Scale); 13135 } 13136 } 13137 13138 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 13139 EVT VT) const { 13140 const int Scale = AM.Scale; 13141 13142 // Negative scales are not supported in Thumb1. 13143 if (Scale < 0) 13144 return false; 13145 13146 // Thumb1 addressing modes do not support register scaling excepting the 13147 // following cases: 13148 // 1. Scale == 1 means no scaling. 13149 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 13150 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 13151 } 13152 13153 /// isLegalAddressingMode - Return true if the addressing mode represented 13154 /// by AM is legal for this target, for a load/store of the specified type. 13155 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13156 const AddrMode &AM, Type *Ty, 13157 unsigned AS, Instruction *I) const { 13158 EVT VT = getValueType(DL, Ty, true); 13159 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 13160 return false; 13161 13162 // Can never fold addr of global into load/store. 13163 if (AM.BaseGV) 13164 return false; 13165 13166 switch (AM.Scale) { 13167 case 0: // no scale reg, must be "r+i" or "r", or "i". 13168 break; 13169 default: 13170 // ARM doesn't support any R+R*scale+imm addr modes. 13171 if (AM.BaseOffs) 13172 return false; 13173 13174 if (!VT.isSimple()) 13175 return false; 13176 13177 if (Subtarget->isThumb1Only()) 13178 return isLegalT1ScaledAddressingMode(AM, VT); 13179 13180 if (Subtarget->isThumb2()) 13181 return isLegalT2ScaledAddressingMode(AM, VT); 13182 13183 int Scale = AM.Scale; 13184 switch (VT.getSimpleVT().SimpleTy) { 13185 default: return false; 13186 case MVT::i1: 13187 case MVT::i8: 13188 case MVT::i32: 13189 if (Scale < 0) Scale = -Scale; 13190 if (Scale == 1) 13191 return true; 13192 // r + r << imm 13193 return isPowerOf2_32(Scale & ~1); 13194 case MVT::i16: 13195 case MVT::i64: 13196 // r +/- r 13197 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 13198 return true; 13199 // r * 2 (this can be lowered to r + r). 13200 if (!AM.HasBaseReg && Scale == 2) 13201 return true; 13202 return false; 13203 13204 case MVT::isVoid: 13205 // Note, we allow "void" uses (basically, uses that aren't loads or 13206 // stores), because arm allows folding a scale into many arithmetic 13207 // operations. This should be made more precise and revisited later. 13208 13209 // Allow r << imm, but the imm has to be a multiple of two. 13210 if (Scale & 1) return false; 13211 return isPowerOf2_32(Scale); 13212 } 13213 } 13214 return true; 13215 } 13216 13217 /// isLegalICmpImmediate - Return true if the specified immediate is legal 13218 /// icmp immediate, that is the target has icmp instructions which can compare 13219 /// a register against the immediate without having to materialize the 13220 /// immediate into a register. 13221 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13222 // Thumb2 and ARM modes can use cmn for negative immediates. 13223 if (!Subtarget->isThumb()) 13224 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 13225 if (Subtarget->isThumb2()) 13226 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 13227 // Thumb1 doesn't have cmn, and only 8-bit immediates. 13228 return Imm >= 0 && Imm <= 255; 13229 } 13230 13231 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 13232 /// *or sub* immediate, that is the target has add or sub instructions which can 13233 /// add a register with the immediate without having to materialize the 13234 /// immediate into a register. 13235 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13236 // Same encoding for add/sub, just flip the sign. 13237 int64_t AbsImm = std::abs(Imm); 13238 if (!Subtarget->isThumb()) 13239 return ARM_AM::getSOImmVal(AbsImm) != -1; 13240 if (Subtarget->isThumb2()) 13241 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 13242 // Thumb1 only has 8-bit unsigned immediate. 13243 return AbsImm >= 0 && AbsImm <= 255; 13244 } 13245 13246 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 13247 bool isSEXTLoad, SDValue &Base, 13248 SDValue &Offset, bool &isInc, 13249 SelectionDAG &DAG) { 13250 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13251 return false; 13252 13253 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 13254 // AddressingMode 3 13255 Base = Ptr->getOperand(0); 13256 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13257 int RHSC = (int)RHS->getZExtValue(); 13258 if (RHSC < 0 && RHSC > -256) { 13259 assert(Ptr->getOpcode() == ISD::ADD); 13260 isInc = false; 13261 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13262 return true; 13263 } 13264 } 13265 isInc = (Ptr->getOpcode() == ISD::ADD); 13266 Offset = Ptr->getOperand(1); 13267 return true; 13268 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 13269 // AddressingMode 2 13270 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13271 int RHSC = (int)RHS->getZExtValue(); 13272 if (RHSC < 0 && RHSC > -0x1000) { 13273 assert(Ptr->getOpcode() == ISD::ADD); 13274 isInc = false; 13275 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13276 Base = Ptr->getOperand(0); 13277 return true; 13278 } 13279 } 13280 13281 if (Ptr->getOpcode() == ISD::ADD) { 13282 isInc = true; 13283 ARM_AM::ShiftOpc ShOpcVal= 13284 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 13285 if (ShOpcVal != ARM_AM::no_shift) { 13286 Base = Ptr->getOperand(1); 13287 Offset = Ptr->getOperand(0); 13288 } else { 13289 Base = Ptr->getOperand(0); 13290 Offset = Ptr->getOperand(1); 13291 } 13292 return true; 13293 } 13294 13295 isInc = (Ptr->getOpcode() == ISD::ADD); 13296 Base = Ptr->getOperand(0); 13297 Offset = Ptr->getOperand(1); 13298 return true; 13299 } 13300 13301 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 13302 return false; 13303 } 13304 13305 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 13306 bool isSEXTLoad, SDValue &Base, 13307 SDValue &Offset, bool &isInc, 13308 SelectionDAG &DAG) { 13309 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13310 return false; 13311 13312 Base = Ptr->getOperand(0); 13313 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13314 int RHSC = (int)RHS->getZExtValue(); 13315 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 13316 assert(Ptr->getOpcode() == ISD::ADD); 13317 isInc = false; 13318 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13319 return true; 13320 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 13321 isInc = Ptr->getOpcode() == ISD::ADD; 13322 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13323 return true; 13324 } 13325 } 13326 13327 return false; 13328 } 13329 13330 /// getPreIndexedAddressParts - returns true by value, base pointer and 13331 /// offset pointer and addressing mode by reference if the node's address 13332 /// can be legally represented as pre-indexed load / store address. 13333 bool 13334 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13335 SDValue &Offset, 13336 ISD::MemIndexedMode &AM, 13337 SelectionDAG &DAG) const { 13338 if (Subtarget->isThumb1Only()) 13339 return false; 13340 13341 EVT VT; 13342 SDValue Ptr; 13343 bool isSEXTLoad = false; 13344 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13345 Ptr = LD->getBasePtr(); 13346 VT = LD->getMemoryVT(); 13347 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13348 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13349 Ptr = ST->getBasePtr(); 13350 VT = ST->getMemoryVT(); 13351 } else 13352 return false; 13353 13354 bool isInc; 13355 bool isLegal = false; 13356 if (Subtarget->isThumb2()) 13357 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13358 Offset, isInc, DAG); 13359 else 13360 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13361 Offset, isInc, DAG); 13362 if (!isLegal) 13363 return false; 13364 13365 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 13366 return true; 13367 } 13368 13369 /// getPostIndexedAddressParts - returns true by value, base pointer and 13370 /// offset pointer and addressing mode by reference if this node can be 13371 /// combined with a load / store to form a post-indexed load / store. 13372 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 13373 SDValue &Base, 13374 SDValue &Offset, 13375 ISD::MemIndexedMode &AM, 13376 SelectionDAG &DAG) const { 13377 EVT VT; 13378 SDValue Ptr; 13379 bool isSEXTLoad = false, isNonExt; 13380 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13381 VT = LD->getMemoryVT(); 13382 Ptr = LD->getBasePtr(); 13383 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13384 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 13385 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13386 VT = ST->getMemoryVT(); 13387 Ptr = ST->getBasePtr(); 13388 isNonExt = !ST->isTruncatingStore(); 13389 } else 13390 return false; 13391 13392 if (Subtarget->isThumb1Only()) { 13393 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 13394 // must be non-extending/truncating, i32, with an offset of 4. 13395 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 13396 if (Op->getOpcode() != ISD::ADD || !isNonExt) 13397 return false; 13398 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 13399 if (!RHS || RHS->getZExtValue() != 4) 13400 return false; 13401 13402 Offset = Op->getOperand(1); 13403 Base = Op->getOperand(0); 13404 AM = ISD::POST_INC; 13405 return true; 13406 } 13407 13408 bool isInc; 13409 bool isLegal = false; 13410 if (Subtarget->isThumb2()) 13411 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13412 isInc, DAG); 13413 else 13414 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13415 isInc, DAG); 13416 if (!isLegal) 13417 return false; 13418 13419 if (Ptr != Base) { 13420 // Swap base ptr and offset to catch more post-index load / store when 13421 // it's legal. In Thumb2 mode, offset must be an immediate. 13422 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 13423 !Subtarget->isThumb2()) 13424 std::swap(Base, Offset); 13425 13426 // Post-indexed load / store update the base pointer. 13427 if (Ptr != Base) 13428 return false; 13429 } 13430 13431 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 13432 return true; 13433 } 13434 13435 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13436 KnownBits &Known, 13437 const APInt &DemandedElts, 13438 const SelectionDAG &DAG, 13439 unsigned Depth) const { 13440 unsigned BitWidth = Known.getBitWidth(); 13441 Known.resetAll(); 13442 switch (Op.getOpcode()) { 13443 default: break; 13444 case ARMISD::ADDC: 13445 case ARMISD::ADDE: 13446 case ARMISD::SUBC: 13447 case ARMISD::SUBE: 13448 // Special cases when we convert a carry to a boolean. 13449 if (Op.getResNo() == 0) { 13450 SDValue LHS = Op.getOperand(0); 13451 SDValue RHS = Op.getOperand(1); 13452 // (ADDE 0, 0, C) will give us a single bit. 13453 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 13454 isNullConstant(RHS)) { 13455 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 13456 return; 13457 } 13458 } 13459 break; 13460 case ARMISD::CMOV: { 13461 // Bits are known zero/one if known on the LHS and RHS. 13462 DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1); 13463 if (Known.isUnknown()) 13464 return; 13465 13466 KnownBits KnownRHS; 13467 DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1); 13468 Known.Zero &= KnownRHS.Zero; 13469 Known.One &= KnownRHS.One; 13470 return; 13471 } 13472 case ISD::INTRINSIC_W_CHAIN: { 13473 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 13474 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13475 switch (IntID) { 13476 default: return; 13477 case Intrinsic::arm_ldaex: 13478 case Intrinsic::arm_ldrex: { 13479 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 13480 unsigned MemBits = VT.getScalarSizeInBits(); 13481 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 13482 return; 13483 } 13484 } 13485 } 13486 case ARMISD::BFI: { 13487 // Conservatively, we can recurse down the first operand 13488 // and just mask out all affected bits. 13489 DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1); 13490 13491 // The operand to BFI is already a mask suitable for removing the bits it 13492 // sets. 13493 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 13494 const APInt &Mask = CI->getAPIntValue(); 13495 Known.Zero &= Mask; 13496 Known.One &= Mask; 13497 return; 13498 } 13499 } 13500 } 13501 13502 //===----------------------------------------------------------------------===// 13503 // ARM Inline Assembly Support 13504 //===----------------------------------------------------------------------===// 13505 13506 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 13507 // Looking for "rev" which is V6+. 13508 if (!Subtarget->hasV6Ops()) 13509 return false; 13510 13511 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 13512 std::string AsmStr = IA->getAsmString(); 13513 SmallVector<StringRef, 4> AsmPieces; 13514 SplitString(AsmStr, AsmPieces, ";\n"); 13515 13516 switch (AsmPieces.size()) { 13517 default: return false; 13518 case 1: 13519 AsmStr = AsmPieces[0]; 13520 AsmPieces.clear(); 13521 SplitString(AsmStr, AsmPieces, " \t,"); 13522 13523 // rev $0, $1 13524 if (AsmPieces.size() == 3 && 13525 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 13526 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 13527 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 13528 if (Ty && Ty->getBitWidth() == 32) 13529 return IntrinsicLowering::LowerToByteSwap(CI); 13530 } 13531 break; 13532 } 13533 13534 return false; 13535 } 13536 13537 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 13538 // At this point, we have to lower this constraint to something else, so we 13539 // lower it to an "r" or "w". However, by doing this we will force the result 13540 // to be in register, while the X constraint is much more permissive. 13541 // 13542 // Although we are correct (we are free to emit anything, without 13543 // constraints), we might break use cases that would expect us to be more 13544 // efficient and emit something else. 13545 if (!Subtarget->hasVFP2()) 13546 return "r"; 13547 if (ConstraintVT.isFloatingPoint()) 13548 return "w"; 13549 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 13550 (ConstraintVT.getSizeInBits() == 64 || 13551 ConstraintVT.getSizeInBits() == 128)) 13552 return "w"; 13553 13554 return "r"; 13555 } 13556 13557 /// getConstraintType - Given a constraint letter, return the type of 13558 /// constraint it is for this target. 13559 ARMTargetLowering::ConstraintType 13560 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 13561 if (Constraint.size() == 1) { 13562 switch (Constraint[0]) { 13563 default: break; 13564 case 'l': return C_RegisterClass; 13565 case 'w': return C_RegisterClass; 13566 case 'h': return C_RegisterClass; 13567 case 'x': return C_RegisterClass; 13568 case 't': return C_RegisterClass; 13569 case 'j': return C_Other; // Constant for movw. 13570 // An address with a single base register. Due to the way we 13571 // currently handle addresses it is the same as an 'r' memory constraint. 13572 case 'Q': return C_Memory; 13573 } 13574 } else if (Constraint.size() == 2) { 13575 switch (Constraint[0]) { 13576 default: break; 13577 // All 'U+' constraints are addresses. 13578 case 'U': return C_Memory; 13579 } 13580 } 13581 return TargetLowering::getConstraintType(Constraint); 13582 } 13583 13584 /// Examine constraint type and operand type and determine a weight value. 13585 /// This object must already have been set up with the operand type 13586 /// and the current alternative constraint selected. 13587 TargetLowering::ConstraintWeight 13588 ARMTargetLowering::getSingleConstraintMatchWeight( 13589 AsmOperandInfo &info, const char *constraint) const { 13590 ConstraintWeight weight = CW_Invalid; 13591 Value *CallOperandVal = info.CallOperandVal; 13592 // If we don't have a value, we can't do a match, 13593 // but allow it at the lowest weight. 13594 if (!CallOperandVal) 13595 return CW_Default; 13596 Type *type = CallOperandVal->getType(); 13597 // Look at the constraint type. 13598 switch (*constraint) { 13599 default: 13600 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13601 break; 13602 case 'l': 13603 if (type->isIntegerTy()) { 13604 if (Subtarget->isThumb()) 13605 weight = CW_SpecificReg; 13606 else 13607 weight = CW_Register; 13608 } 13609 break; 13610 case 'w': 13611 if (type->isFloatingPointTy()) 13612 weight = CW_Register; 13613 break; 13614 } 13615 return weight; 13616 } 13617 13618 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13619 13620 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13621 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13622 if (Constraint.size() == 1) { 13623 // GCC ARM Constraint Letters 13624 switch (Constraint[0]) { 13625 case 'l': // Low regs or general regs. 13626 if (Subtarget->isThumb()) 13627 return RCPair(0U, &ARM::tGPRRegClass); 13628 return RCPair(0U, &ARM::GPRRegClass); 13629 case 'h': // High regs or no regs. 13630 if (Subtarget->isThumb()) 13631 return RCPair(0U, &ARM::hGPRRegClass); 13632 break; 13633 case 'r': 13634 if (Subtarget->isThumb1Only()) 13635 return RCPair(0U, &ARM::tGPRRegClass); 13636 return RCPair(0U, &ARM::GPRRegClass); 13637 case 'w': 13638 if (VT == MVT::Other) 13639 break; 13640 if (VT == MVT::f32) 13641 return RCPair(0U, &ARM::SPRRegClass); 13642 if (VT.getSizeInBits() == 64) 13643 return RCPair(0U, &ARM::DPRRegClass); 13644 if (VT.getSizeInBits() == 128) 13645 return RCPair(0U, &ARM::QPRRegClass); 13646 break; 13647 case 'x': 13648 if (VT == MVT::Other) 13649 break; 13650 if (VT == MVT::f32) 13651 return RCPair(0U, &ARM::SPR_8RegClass); 13652 if (VT.getSizeInBits() == 64) 13653 return RCPair(0U, &ARM::DPR_8RegClass); 13654 if (VT.getSizeInBits() == 128) 13655 return RCPair(0U, &ARM::QPR_8RegClass); 13656 break; 13657 case 't': 13658 if (VT == MVT::Other) 13659 break; 13660 if (VT == MVT::f32 || VT == MVT::i32) 13661 return RCPair(0U, &ARM::SPRRegClass); 13662 if (VT.getSizeInBits() == 64) 13663 return RCPair(0U, &ARM::DPR_VFP2RegClass); 13664 if (VT.getSizeInBits() == 128) 13665 return RCPair(0U, &ARM::QPR_VFP2RegClass); 13666 break; 13667 } 13668 } 13669 if (StringRef("{cc}").equals_lower(Constraint)) 13670 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 13671 13672 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13673 } 13674 13675 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13676 /// vector. If it is invalid, don't add anything to Ops. 13677 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13678 std::string &Constraint, 13679 std::vector<SDValue>&Ops, 13680 SelectionDAG &DAG) const { 13681 SDValue Result; 13682 13683 // Currently only support length 1 constraints. 13684 if (Constraint.length() != 1) return; 13685 13686 char ConstraintLetter = Constraint[0]; 13687 switch (ConstraintLetter) { 13688 default: break; 13689 case 'j': 13690 case 'I': case 'J': case 'K': case 'L': 13691 case 'M': case 'N': case 'O': 13692 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 13693 if (!C) 13694 return; 13695 13696 int64_t CVal64 = C->getSExtValue(); 13697 int CVal = (int) CVal64; 13698 // None of these constraints allow values larger than 32 bits. Check 13699 // that the value fits in an int. 13700 if (CVal != CVal64) 13701 return; 13702 13703 switch (ConstraintLetter) { 13704 case 'j': 13705 // Constant suitable for movw, must be between 0 and 13706 // 65535. 13707 if (Subtarget->hasV6T2Ops()) 13708 if (CVal >= 0 && CVal <= 65535) 13709 break; 13710 return; 13711 case 'I': 13712 if (Subtarget->isThumb1Only()) { 13713 // This must be a constant between 0 and 255, for ADD 13714 // immediates. 13715 if (CVal >= 0 && CVal <= 255) 13716 break; 13717 } else if (Subtarget->isThumb2()) { 13718 // A constant that can be used as an immediate value in a 13719 // data-processing instruction. 13720 if (ARM_AM::getT2SOImmVal(CVal) != -1) 13721 break; 13722 } else { 13723 // A constant that can be used as an immediate value in a 13724 // data-processing instruction. 13725 if (ARM_AM::getSOImmVal(CVal) != -1) 13726 break; 13727 } 13728 return; 13729 13730 case 'J': 13731 if (Subtarget->isThumb1Only()) { 13732 // This must be a constant between -255 and -1, for negated ADD 13733 // immediates. This can be used in GCC with an "n" modifier that 13734 // prints the negated value, for use with SUB instructions. It is 13735 // not useful otherwise but is implemented for compatibility. 13736 if (CVal >= -255 && CVal <= -1) 13737 break; 13738 } else { 13739 // This must be a constant between -4095 and 4095. It is not clear 13740 // what this constraint is intended for. Implemented for 13741 // compatibility with GCC. 13742 if (CVal >= -4095 && CVal <= 4095) 13743 break; 13744 } 13745 return; 13746 13747 case 'K': 13748 if (Subtarget->isThumb1Only()) { 13749 // A 32-bit value where only one byte has a nonzero value. Exclude 13750 // zero to match GCC. This constraint is used by GCC internally for 13751 // constants that can be loaded with a move/shift combination. 13752 // It is not useful otherwise but is implemented for compatibility. 13753 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 13754 break; 13755 } else if (Subtarget->isThumb2()) { 13756 // A constant whose bitwise inverse can be used as an immediate 13757 // value in a data-processing instruction. This can be used in GCC 13758 // with a "B" modifier that prints the inverted value, for use with 13759 // BIC and MVN instructions. It is not useful otherwise but is 13760 // implemented for compatibility. 13761 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 13762 break; 13763 } else { 13764 // A constant whose bitwise inverse can be used as an immediate 13765 // value in a data-processing instruction. This can be used in GCC 13766 // with a "B" modifier that prints the inverted value, for use with 13767 // BIC and MVN instructions. It is not useful otherwise but is 13768 // implemented for compatibility. 13769 if (ARM_AM::getSOImmVal(~CVal) != -1) 13770 break; 13771 } 13772 return; 13773 13774 case 'L': 13775 if (Subtarget->isThumb1Only()) { 13776 // This must be a constant between -7 and 7, 13777 // for 3-operand ADD/SUB immediate instructions. 13778 if (CVal >= -7 && CVal < 7) 13779 break; 13780 } else if (Subtarget->isThumb2()) { 13781 // A constant whose negation can be used as an immediate value in a 13782 // data-processing instruction. This can be used in GCC with an "n" 13783 // modifier that prints the negated value, for use with SUB 13784 // instructions. It is not useful otherwise but is implemented for 13785 // compatibility. 13786 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 13787 break; 13788 } else { 13789 // A constant whose negation can be used as an immediate value in a 13790 // data-processing instruction. This can be used in GCC with an "n" 13791 // modifier that prints the negated value, for use with SUB 13792 // instructions. It is not useful otherwise but is implemented for 13793 // compatibility. 13794 if (ARM_AM::getSOImmVal(-CVal) != -1) 13795 break; 13796 } 13797 return; 13798 13799 case 'M': 13800 if (Subtarget->isThumb1Only()) { 13801 // This must be a multiple of 4 between 0 and 1020, for 13802 // ADD sp + immediate. 13803 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 13804 break; 13805 } else { 13806 // A power of two or a constant between 0 and 32. This is used in 13807 // GCC for the shift amount on shifted register operands, but it is 13808 // useful in general for any shift amounts. 13809 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 13810 break; 13811 } 13812 return; 13813 13814 case 'N': 13815 if (Subtarget->isThumb()) { // FIXME thumb2 13816 // This must be a constant between 0 and 31, for shift amounts. 13817 if (CVal >= 0 && CVal <= 31) 13818 break; 13819 } 13820 return; 13821 13822 case 'O': 13823 if (Subtarget->isThumb()) { // FIXME thumb2 13824 // This must be a multiple of 4 between -508 and 508, for 13825 // ADD/SUB sp = sp + immediate. 13826 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 13827 break; 13828 } 13829 return; 13830 } 13831 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 13832 break; 13833 } 13834 13835 if (Result.getNode()) { 13836 Ops.push_back(Result); 13837 return; 13838 } 13839 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13840 } 13841 13842 static RTLIB::Libcall getDivRemLibcall( 13843 const SDNode *N, MVT::SimpleValueType SVT) { 13844 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13845 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13846 "Unhandled Opcode in getDivRemLibcall"); 13847 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13848 N->getOpcode() == ISD::SREM; 13849 RTLIB::Libcall LC; 13850 switch (SVT) { 13851 default: llvm_unreachable("Unexpected request for libcall!"); 13852 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 13853 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 13854 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 13855 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 13856 } 13857 return LC; 13858 } 13859 13860 static TargetLowering::ArgListTy getDivRemArgList( 13861 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13862 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13863 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13864 "Unhandled Opcode in getDivRemArgList"); 13865 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13866 N->getOpcode() == ISD::SREM; 13867 TargetLowering::ArgListTy Args; 13868 TargetLowering::ArgListEntry Entry; 13869 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13870 EVT ArgVT = N->getOperand(i).getValueType(); 13871 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13872 Entry.Node = N->getOperand(i); 13873 Entry.Ty = ArgTy; 13874 Entry.IsSExt = isSigned; 13875 Entry.IsZExt = !isSigned; 13876 Args.push_back(Entry); 13877 } 13878 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13879 std::swap(Args[0], Args[1]); 13880 return Args; 13881 } 13882 13883 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13884 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13885 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13886 Subtarget->isTargetWindows()) && 13887 "Register-based DivRem lowering only"); 13888 unsigned Opcode = Op->getOpcode(); 13889 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13890 "Invalid opcode for Div/Rem lowering"); 13891 bool isSigned = (Opcode == ISD::SDIVREM); 13892 EVT VT = Op->getValueType(0); 13893 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13894 SDLoc dl(Op); 13895 13896 // If the target has hardware divide, use divide + multiply + subtract: 13897 // div = a / b 13898 // rem = a - b * div 13899 // return {div, rem} 13900 // This should be lowered into UDIV/SDIV + MLS later on. 13901 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 13902 : Subtarget->hasDivideInARMMode(); 13903 if (hasDivide && Op->getValueType(0).isSimple() && 13904 Op->getSimpleValueType(0) == MVT::i32) { 13905 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13906 const SDValue Dividend = Op->getOperand(0); 13907 const SDValue Divisor = Op->getOperand(1); 13908 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13909 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13910 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13911 13912 SDValue Values[2] = {Div, Rem}; 13913 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13914 } 13915 13916 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13917 VT.getSimpleVT().SimpleTy); 13918 SDValue InChain = DAG.getEntryNode(); 13919 13920 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13921 DAG.getContext(), 13922 Subtarget); 13923 13924 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13925 getPointerTy(DAG.getDataLayout())); 13926 13927 Type *RetTy = StructType::get(Ty, Ty); 13928 13929 if (Subtarget->isTargetWindows()) 13930 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13931 13932 TargetLowering::CallLoweringInfo CLI(DAG); 13933 CLI.setDebugLoc(dl).setChain(InChain) 13934 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13935 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13936 13937 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13938 return CallInfo.first; 13939 } 13940 13941 // Lowers REM using divmod helpers 13942 // see RTABI section 4.2/4.3 13943 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13944 // Build return types (div and rem) 13945 std::vector<Type*> RetTyParams; 13946 Type *RetTyElement; 13947 13948 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13949 default: llvm_unreachable("Unexpected request for libcall!"); 13950 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13951 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13952 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13953 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13954 } 13955 13956 RetTyParams.push_back(RetTyElement); 13957 RetTyParams.push_back(RetTyElement); 13958 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13959 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13960 13961 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13962 SimpleTy); 13963 SDValue InChain = DAG.getEntryNode(); 13964 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13965 Subtarget); 13966 bool isSigned = N->getOpcode() == ISD::SREM; 13967 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13968 getPointerTy(DAG.getDataLayout())); 13969 13970 if (Subtarget->isTargetWindows()) 13971 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13972 13973 // Lower call 13974 CallLoweringInfo CLI(DAG); 13975 CLI.setChain(InChain) 13976 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13977 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13978 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13979 13980 // Return second (rem) result operand (first contains div) 13981 SDNode *ResNode = CallResult.first.getNode(); 13982 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13983 return ResNode->getOperand(1); 13984 } 13985 13986 SDValue 13987 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13988 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13989 SDLoc DL(Op); 13990 13991 // Get the inputs. 13992 SDValue Chain = Op.getOperand(0); 13993 SDValue Size = Op.getOperand(1); 13994 13995 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 13996 "no-stack-arg-probe")) { 13997 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 13998 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13999 Chain = SP.getValue(1); 14000 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 14001 if (Align) 14002 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 14003 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 14004 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 14005 SDValue Ops[2] = { SP, Chain }; 14006 return DAG.getMergeValues(Ops, DL); 14007 } 14008 14009 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 14010 DAG.getConstant(2, DL, MVT::i32)); 14011 14012 SDValue Flag; 14013 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 14014 Flag = Chain.getValue(1); 14015 14016 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 14017 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 14018 14019 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14020 Chain = NewSP.getValue(1); 14021 14022 SDValue Ops[2] = { NewSP, Chain }; 14023 return DAG.getMergeValues(Ops, DL); 14024 } 14025 14026 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 14027 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 14028 "Unexpected type for custom-lowering FP_EXTEND"); 14029 14030 RTLIB::Libcall LC; 14031 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 14032 14033 SDValue SrcVal = Op.getOperand(0); 14034 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14035 SDLoc(Op)).first; 14036 } 14037 14038 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 14039 assert(Op.getOperand(0).getValueType() == MVT::f64 && 14040 Subtarget->isFPOnlySP() && 14041 "Unexpected type for custom-lowering FP_ROUND"); 14042 14043 RTLIB::Libcall LC; 14044 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 14045 14046 SDValue SrcVal = Op.getOperand(0); 14047 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14048 SDLoc(Op)).first; 14049 } 14050 14051 bool 14052 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14053 // The ARM target isn't yet aware of offsets. 14054 return false; 14055 } 14056 14057 bool ARM::isBitFieldInvertedMask(unsigned v) { 14058 if (v == 0xffffffff) 14059 return false; 14060 14061 // there can be 1's on either or both "outsides", all the "inside" 14062 // bits must be 0's 14063 return isShiftedMask_32(~v); 14064 } 14065 14066 /// isFPImmLegal - Returns true if the target can instruction select the 14067 /// specified FP immediate natively. If false, the legalizer will 14068 /// materialize the FP immediate as a load from a constant pool. 14069 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 14070 if (!Subtarget->hasVFP3()) 14071 return false; 14072 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 14073 return ARM_AM::getFP16Imm(Imm) != -1; 14074 if (VT == MVT::f32) 14075 return ARM_AM::getFP32Imm(Imm) != -1; 14076 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 14077 return ARM_AM::getFP64Imm(Imm) != -1; 14078 return false; 14079 } 14080 14081 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 14082 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 14083 /// specified in the intrinsic calls. 14084 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14085 const CallInst &I, 14086 MachineFunction &MF, 14087 unsigned Intrinsic) const { 14088 switch (Intrinsic) { 14089 case Intrinsic::arm_neon_vld1: 14090 case Intrinsic::arm_neon_vld2: 14091 case Intrinsic::arm_neon_vld3: 14092 case Intrinsic::arm_neon_vld4: 14093 case Intrinsic::arm_neon_vld2lane: 14094 case Intrinsic::arm_neon_vld3lane: 14095 case Intrinsic::arm_neon_vld4lane: { 14096 Info.opc = ISD::INTRINSIC_W_CHAIN; 14097 // Conservatively set memVT to the entire set of vectors loaded. 14098 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14099 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14100 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14101 Info.ptrVal = I.getArgOperand(0); 14102 Info.offset = 0; 14103 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14104 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14105 // volatile loads with NEON intrinsics not supported 14106 Info.flags = MachineMemOperand::MOLoad; 14107 return true; 14108 } 14109 case Intrinsic::arm_neon_vst1: 14110 case Intrinsic::arm_neon_vst2: 14111 case Intrinsic::arm_neon_vst3: 14112 case Intrinsic::arm_neon_vst4: 14113 case Intrinsic::arm_neon_vst2lane: 14114 case Intrinsic::arm_neon_vst3lane: 14115 case Intrinsic::arm_neon_vst4lane: { 14116 Info.opc = ISD::INTRINSIC_VOID; 14117 // Conservatively set memVT to the entire set of vectors stored. 14118 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14119 unsigned NumElts = 0; 14120 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14121 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14122 if (!ArgTy->isVectorTy()) 14123 break; 14124 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14125 } 14126 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14127 Info.ptrVal = I.getArgOperand(0); 14128 Info.offset = 0; 14129 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14130 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14131 // volatile stores with NEON intrinsics not supported 14132 Info.flags = MachineMemOperand::MOStore; 14133 return true; 14134 } 14135 case Intrinsic::arm_ldaex: 14136 case Intrinsic::arm_ldrex: { 14137 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14138 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 14139 Info.opc = ISD::INTRINSIC_W_CHAIN; 14140 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14141 Info.ptrVal = I.getArgOperand(0); 14142 Info.offset = 0; 14143 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14144 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14145 return true; 14146 } 14147 case Intrinsic::arm_stlex: 14148 case Intrinsic::arm_strex: { 14149 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14150 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 14151 Info.opc = ISD::INTRINSIC_W_CHAIN; 14152 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14153 Info.ptrVal = I.getArgOperand(1); 14154 Info.offset = 0; 14155 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14156 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14157 return true; 14158 } 14159 case Intrinsic::arm_stlexd: 14160 case Intrinsic::arm_strexd: 14161 Info.opc = ISD::INTRINSIC_W_CHAIN; 14162 Info.memVT = MVT::i64; 14163 Info.ptrVal = I.getArgOperand(2); 14164 Info.offset = 0; 14165 Info.align = 8; 14166 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14167 return true; 14168 14169 case Intrinsic::arm_ldaexd: 14170 case Intrinsic::arm_ldrexd: 14171 Info.opc = ISD::INTRINSIC_W_CHAIN; 14172 Info.memVT = MVT::i64; 14173 Info.ptrVal = I.getArgOperand(0); 14174 Info.offset = 0; 14175 Info.align = 8; 14176 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14177 return true; 14178 14179 default: 14180 break; 14181 } 14182 14183 return false; 14184 } 14185 14186 /// Returns true if it is beneficial to convert a load of a constant 14187 /// to just the constant itself. 14188 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14189 Type *Ty) const { 14190 assert(Ty->isIntegerTy()); 14191 14192 unsigned Bits = Ty->getPrimitiveSizeInBits(); 14193 if (Bits == 0 || Bits > 32) 14194 return false; 14195 return true; 14196 } 14197 14198 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 14199 unsigned Index) const { 14200 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 14201 return false; 14202 14203 return (Index == 0 || Index == ResVT.getVectorNumElements()); 14204 } 14205 14206 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 14207 ARM_MB::MemBOpt Domain) const { 14208 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14209 14210 // First, if the target has no DMB, see what fallback we can use. 14211 if (!Subtarget->hasDataBarrier()) { 14212 // Some ARMv6 cpus can support data barriers with an mcr instruction. 14213 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 14214 // here. 14215 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 14216 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 14217 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 14218 Builder.getInt32(0), Builder.getInt32(7), 14219 Builder.getInt32(10), Builder.getInt32(5)}; 14220 return Builder.CreateCall(MCR, args); 14221 } else { 14222 // Instead of using barriers, atomic accesses on these subtargets use 14223 // libcalls. 14224 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 14225 } 14226 } else { 14227 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 14228 // Only a full system barrier exists in the M-class architectures. 14229 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 14230 Constant *CDomain = Builder.getInt32(Domain); 14231 return Builder.CreateCall(DMB, CDomain); 14232 } 14233 } 14234 14235 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 14236 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 14237 Instruction *Inst, 14238 AtomicOrdering Ord) const { 14239 switch (Ord) { 14240 case AtomicOrdering::NotAtomic: 14241 case AtomicOrdering::Unordered: 14242 llvm_unreachable("Invalid fence: unordered/non-atomic"); 14243 case AtomicOrdering::Monotonic: 14244 case AtomicOrdering::Acquire: 14245 return nullptr; // Nothing to do 14246 case AtomicOrdering::SequentiallyConsistent: 14247 if (!Inst->hasAtomicStore()) 14248 return nullptr; // Nothing to do 14249 LLVM_FALLTHROUGH; 14250 case AtomicOrdering::Release: 14251 case AtomicOrdering::AcquireRelease: 14252 if (Subtarget->preferISHSTBarriers()) 14253 return makeDMB(Builder, ARM_MB::ISHST); 14254 // FIXME: add a comment with a link to documentation justifying this. 14255 else 14256 return makeDMB(Builder, ARM_MB::ISH); 14257 } 14258 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 14259 } 14260 14261 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 14262 Instruction *Inst, 14263 AtomicOrdering Ord) const { 14264 switch (Ord) { 14265 case AtomicOrdering::NotAtomic: 14266 case AtomicOrdering::Unordered: 14267 llvm_unreachable("Invalid fence: unordered/not-atomic"); 14268 case AtomicOrdering::Monotonic: 14269 case AtomicOrdering::Release: 14270 return nullptr; // Nothing to do 14271 case AtomicOrdering::Acquire: 14272 case AtomicOrdering::AcquireRelease: 14273 case AtomicOrdering::SequentiallyConsistent: 14274 return makeDMB(Builder, ARM_MB::ISH); 14275 } 14276 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 14277 } 14278 14279 // Loads and stores less than 64-bits are already atomic; ones above that 14280 // are doomed anyway, so defer to the default libcall and blame the OS when 14281 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14282 // anything for those. 14283 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 14284 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 14285 return (Size == 64) && !Subtarget->isMClass(); 14286 } 14287 14288 // Loads and stores less than 64-bits are already atomic; ones above that 14289 // are doomed anyway, so defer to the default libcall and blame the OS when 14290 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14291 // anything for those. 14292 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 14293 // guarantee, see DDI0406C ARM architecture reference manual, 14294 // sections A8.8.72-74 LDRD) 14295 TargetLowering::AtomicExpansionKind 14296 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 14297 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 14298 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 14299 : AtomicExpansionKind::None; 14300 } 14301 14302 // For the real atomic operations, we have ldrex/strex up to 32 bits, 14303 // and up to 64 bits on the non-M profiles 14304 TargetLowering::AtomicExpansionKind 14305 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 14306 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 14307 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14308 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 14309 ? AtomicExpansionKind::LLSC 14310 : AtomicExpansionKind::None; 14311 } 14312 14313 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 14314 AtomicCmpXchgInst *AI) const { 14315 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 14316 // implement cmpxchg without spilling. If the address being exchanged is also 14317 // on the stack and close enough to the spill slot, this can lead to a 14318 // situation where the monitor always gets cleared and the atomic operation 14319 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 14320 bool hasAtomicCmpXchg = 14321 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14322 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 14323 } 14324 14325 bool ARMTargetLowering::shouldInsertFencesForAtomic( 14326 const Instruction *I) const { 14327 return InsertFencesForAtomic; 14328 } 14329 14330 // This has so far only been implemented for MachO. 14331 bool ARMTargetLowering::useLoadStackGuardNode() const { 14332 return Subtarget->isTargetMachO(); 14333 } 14334 14335 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 14336 unsigned &Cost) const { 14337 // If we do not have NEON, vector types are not natively supported. 14338 if (!Subtarget->hasNEON()) 14339 return false; 14340 14341 // Floating point values and vector values map to the same register file. 14342 // Therefore, although we could do a store extract of a vector type, this is 14343 // better to leave at float as we have more freedom in the addressing mode for 14344 // those. 14345 if (VectorTy->isFPOrFPVectorTy()) 14346 return false; 14347 14348 // If the index is unknown at compile time, this is very expensive to lower 14349 // and it is not possible to combine the store with the extract. 14350 if (!isa<ConstantInt>(Idx)) 14351 return false; 14352 14353 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 14354 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 14355 // We can do a store + vector extract on any vector that fits perfectly in a D 14356 // or Q register. 14357 if (BitWidth == 64 || BitWidth == 128) { 14358 Cost = 0; 14359 return true; 14360 } 14361 return false; 14362 } 14363 14364 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 14365 return Subtarget->hasV6T2Ops(); 14366 } 14367 14368 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 14369 return Subtarget->hasV6T2Ops(); 14370 } 14371 14372 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 14373 AtomicOrdering Ord) const { 14374 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14375 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 14376 bool IsAcquire = isAcquireOrStronger(Ord); 14377 14378 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 14379 // intrinsic must return {i32, i32} and we have to recombine them into a 14380 // single i64 here. 14381 if (ValTy->getPrimitiveSizeInBits() == 64) { 14382 Intrinsic::ID Int = 14383 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 14384 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 14385 14386 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14387 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 14388 14389 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 14390 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 14391 if (!Subtarget->isLittle()) 14392 std::swap (Lo, Hi); 14393 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 14394 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 14395 return Builder.CreateOr( 14396 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 14397 } 14398 14399 Type *Tys[] = { Addr->getType() }; 14400 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 14401 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 14402 14403 return Builder.CreateTruncOrBitCast( 14404 Builder.CreateCall(Ldrex, Addr), 14405 cast<PointerType>(Addr->getType())->getElementType()); 14406 } 14407 14408 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 14409 IRBuilder<> &Builder) const { 14410 if (!Subtarget->hasV7Ops()) 14411 return; 14412 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14413 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 14414 } 14415 14416 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 14417 Value *Addr, 14418 AtomicOrdering Ord) const { 14419 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14420 bool IsRelease = isReleaseOrStronger(Ord); 14421 14422 // Since the intrinsics must have legal type, the i64 intrinsics take two 14423 // parameters: "i32, i32". We must marshal Val into the appropriate form 14424 // before the call. 14425 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 14426 Intrinsic::ID Int = 14427 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 14428 Function *Strex = Intrinsic::getDeclaration(M, Int); 14429 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 14430 14431 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 14432 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 14433 if (!Subtarget->isLittle()) 14434 std::swap(Lo, Hi); 14435 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14436 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 14437 } 14438 14439 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 14440 Type *Tys[] = { Addr->getType() }; 14441 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 14442 14443 return Builder.CreateCall( 14444 Strex, {Builder.CreateZExtOrBitCast( 14445 Val, Strex->getFunctionType()->getParamType(0)), 14446 Addr}); 14447 } 14448 14449 /// A helper function for determining the number of interleaved accesses we 14450 /// will generate when lowering accesses of the given type. 14451 unsigned 14452 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 14453 const DataLayout &DL) const { 14454 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 14455 } 14456 14457 bool ARMTargetLowering::isLegalInterleavedAccessType( 14458 VectorType *VecTy, const DataLayout &DL) const { 14459 14460 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 14461 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 14462 14463 // Ensure the vector doesn't have f16 elements. Even though we could do an 14464 // i16 vldN, we can't hold the f16 vectors and will end up converting via 14465 // f32. 14466 if (VecTy->getElementType()->isHalfTy()) 14467 return false; 14468 14469 // Ensure the number of vector elements is greater than 1. 14470 if (VecTy->getNumElements() < 2) 14471 return false; 14472 14473 // Ensure the element type is legal. 14474 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 14475 return false; 14476 14477 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 14478 // 128 will be split into multiple interleaved accesses. 14479 return VecSize == 64 || VecSize % 128 == 0; 14480 } 14481 14482 /// Lower an interleaved load into a vldN intrinsic. 14483 /// 14484 /// E.g. Lower an interleaved load (Factor = 2): 14485 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 14486 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 14487 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 14488 /// 14489 /// Into: 14490 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 14491 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 14492 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 14493 bool ARMTargetLowering::lowerInterleavedLoad( 14494 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 14495 ArrayRef<unsigned> Indices, unsigned Factor) const { 14496 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14497 "Invalid interleave factor"); 14498 assert(!Shuffles.empty() && "Empty shufflevector input"); 14499 assert(Shuffles.size() == Indices.size() && 14500 "Unmatched number of shufflevectors and indices"); 14501 14502 VectorType *VecTy = Shuffles[0]->getType(); 14503 Type *EltTy = VecTy->getVectorElementType(); 14504 14505 const DataLayout &DL = LI->getModule()->getDataLayout(); 14506 14507 // Skip if we do not have NEON and skip illegal vector types. We can 14508 // "legalize" wide vector types into multiple interleaved accesses as long as 14509 // the vector types are divisible by 128. 14510 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 14511 return false; 14512 14513 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 14514 14515 // A pointer vector can not be the return type of the ldN intrinsics. Need to 14516 // load integer vectors first and then convert to pointer vectors. 14517 if (EltTy->isPointerTy()) 14518 VecTy = 14519 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 14520 14521 IRBuilder<> Builder(LI); 14522 14523 // The base address of the load. 14524 Value *BaseAddr = LI->getPointerOperand(); 14525 14526 if (NumLoads > 1) { 14527 // If we're going to generate more than one load, reset the sub-vector type 14528 // to something legal. 14529 VecTy = VectorType::get(VecTy->getVectorElementType(), 14530 VecTy->getVectorNumElements() / NumLoads); 14531 14532 // We will compute the pointer operand of each load from the original base 14533 // address using GEPs. Cast the base address to a pointer to the scalar 14534 // element type. 14535 BaseAddr = Builder.CreateBitCast( 14536 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 14537 LI->getPointerAddressSpace())); 14538 } 14539 14540 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 14541 14542 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 14543 Type *Tys[] = {VecTy, Int8Ptr}; 14544 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 14545 Intrinsic::arm_neon_vld3, 14546 Intrinsic::arm_neon_vld4}; 14547 Function *VldnFunc = 14548 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 14549 14550 // Holds sub-vectors extracted from the load intrinsic return values. The 14551 // sub-vectors are associated with the shufflevector instructions they will 14552 // replace. 14553 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 14554 14555 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 14556 // If we're generating more than one load, compute the base address of 14557 // subsequent loads as an offset from the previous. 14558 if (LoadCount > 0) 14559 BaseAddr = Builder.CreateConstGEP1_32( 14560 BaseAddr, VecTy->getVectorNumElements() * Factor); 14561 14562 SmallVector<Value *, 2> Ops; 14563 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14564 Ops.push_back(Builder.getInt32(LI->getAlignment())); 14565 14566 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 14567 14568 // Replace uses of each shufflevector with the corresponding vector loaded 14569 // by ldN. 14570 for (unsigned i = 0; i < Shuffles.size(); i++) { 14571 ShuffleVectorInst *SV = Shuffles[i]; 14572 unsigned Index = Indices[i]; 14573 14574 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 14575 14576 // Convert the integer vector to pointer vector if the element is pointer. 14577 if (EltTy->isPointerTy()) 14578 SubVec = Builder.CreateIntToPtr( 14579 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 14580 VecTy->getVectorNumElements())); 14581 14582 SubVecs[SV].push_back(SubVec); 14583 } 14584 } 14585 14586 // Replace uses of the shufflevector instructions with the sub-vectors 14587 // returned by the load intrinsic. If a shufflevector instruction is 14588 // associated with more than one sub-vector, those sub-vectors will be 14589 // concatenated into a single wide vector. 14590 for (ShuffleVectorInst *SVI : Shuffles) { 14591 auto &SubVec = SubVecs[SVI]; 14592 auto *WideVec = 14593 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 14594 SVI->replaceAllUsesWith(WideVec); 14595 } 14596 14597 return true; 14598 } 14599 14600 /// Lower an interleaved store into a vstN intrinsic. 14601 /// 14602 /// E.g. Lower an interleaved store (Factor = 3): 14603 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 14604 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 14605 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 14606 /// 14607 /// Into: 14608 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 14609 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 14610 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 14611 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14612 /// 14613 /// Note that the new shufflevectors will be removed and we'll only generate one 14614 /// vst3 instruction in CodeGen. 14615 /// 14616 /// Example for a more general valid mask (Factor 3). Lower: 14617 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 14618 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 14619 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 14620 /// 14621 /// Into: 14622 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 14623 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 14624 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 14625 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14626 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 14627 ShuffleVectorInst *SVI, 14628 unsigned Factor) const { 14629 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14630 "Invalid interleave factor"); 14631 14632 VectorType *VecTy = SVI->getType(); 14633 assert(VecTy->getVectorNumElements() % Factor == 0 && 14634 "Invalid interleaved store"); 14635 14636 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 14637 Type *EltTy = VecTy->getVectorElementType(); 14638 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 14639 14640 const DataLayout &DL = SI->getModule()->getDataLayout(); 14641 14642 // Skip if we do not have NEON and skip illegal vector types. We can 14643 // "legalize" wide vector types into multiple interleaved accesses as long as 14644 // the vector types are divisible by 128. 14645 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 14646 return false; 14647 14648 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 14649 14650 Value *Op0 = SVI->getOperand(0); 14651 Value *Op1 = SVI->getOperand(1); 14652 IRBuilder<> Builder(SI); 14653 14654 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 14655 // vectors to integer vectors. 14656 if (EltTy->isPointerTy()) { 14657 Type *IntTy = DL.getIntPtrType(EltTy); 14658 14659 // Convert to the corresponding integer vector. 14660 Type *IntVecTy = 14661 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 14662 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 14663 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 14664 14665 SubVecTy = VectorType::get(IntTy, LaneLen); 14666 } 14667 14668 // The base address of the store. 14669 Value *BaseAddr = SI->getPointerOperand(); 14670 14671 if (NumStores > 1) { 14672 // If we're going to generate more than one store, reset the lane length 14673 // and sub-vector type to something legal. 14674 LaneLen /= NumStores; 14675 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 14676 14677 // We will compute the pointer operand of each store from the original base 14678 // address using GEPs. Cast the base address to a pointer to the scalar 14679 // element type. 14680 BaseAddr = Builder.CreateBitCast( 14681 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 14682 SI->getPointerAddressSpace())); 14683 } 14684 14685 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 14686 14687 auto Mask = SVI->getShuffleMask(); 14688 14689 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 14690 Type *Tys[] = {Int8Ptr, SubVecTy}; 14691 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 14692 Intrinsic::arm_neon_vst3, 14693 Intrinsic::arm_neon_vst4}; 14694 14695 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 14696 // If we generating more than one store, we compute the base address of 14697 // subsequent stores as an offset from the previous. 14698 if (StoreCount > 0) 14699 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 14700 14701 SmallVector<Value *, 6> Ops; 14702 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14703 14704 Function *VstNFunc = 14705 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 14706 14707 // Split the shufflevector operands into sub vectors for the new vstN call. 14708 for (unsigned i = 0; i < Factor; i++) { 14709 unsigned IdxI = StoreCount * LaneLen * Factor + i; 14710 if (Mask[IdxI] >= 0) { 14711 Ops.push_back(Builder.CreateShuffleVector( 14712 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 14713 } else { 14714 unsigned StartMask = 0; 14715 for (unsigned j = 1; j < LaneLen; j++) { 14716 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 14717 if (Mask[IdxJ * Factor + IdxI] >= 0) { 14718 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 14719 break; 14720 } 14721 } 14722 // Note: If all elements in a chunk are undefs, StartMask=0! 14723 // Note: Filling undef gaps with random elements is ok, since 14724 // those elements were being written anyway (with undefs). 14725 // In the case of all undefs we're defaulting to using elems from 0 14726 // Note: StartMask cannot be negative, it's checked in 14727 // isReInterleaveMask 14728 Ops.push_back(Builder.CreateShuffleVector( 14729 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 14730 } 14731 } 14732 14733 Ops.push_back(Builder.getInt32(SI->getAlignment())); 14734 Builder.CreateCall(VstNFunc, Ops); 14735 } 14736 return true; 14737 } 14738 14739 enum HABaseType { 14740 HA_UNKNOWN = 0, 14741 HA_FLOAT, 14742 HA_DOUBLE, 14743 HA_VECT64, 14744 HA_VECT128 14745 }; 14746 14747 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 14748 uint64_t &Members) { 14749 if (auto *ST = dyn_cast<StructType>(Ty)) { 14750 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 14751 uint64_t SubMembers = 0; 14752 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 14753 return false; 14754 Members += SubMembers; 14755 } 14756 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 14757 uint64_t SubMembers = 0; 14758 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 14759 return false; 14760 Members += SubMembers * AT->getNumElements(); 14761 } else if (Ty->isFloatTy()) { 14762 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 14763 return false; 14764 Members = 1; 14765 Base = HA_FLOAT; 14766 } else if (Ty->isDoubleTy()) { 14767 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 14768 return false; 14769 Members = 1; 14770 Base = HA_DOUBLE; 14771 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 14772 Members = 1; 14773 switch (Base) { 14774 case HA_FLOAT: 14775 case HA_DOUBLE: 14776 return false; 14777 case HA_VECT64: 14778 return VT->getBitWidth() == 64; 14779 case HA_VECT128: 14780 return VT->getBitWidth() == 128; 14781 case HA_UNKNOWN: 14782 switch (VT->getBitWidth()) { 14783 case 64: 14784 Base = HA_VECT64; 14785 return true; 14786 case 128: 14787 Base = HA_VECT128; 14788 return true; 14789 default: 14790 return false; 14791 } 14792 } 14793 } 14794 14795 return (Members > 0 && Members <= 4); 14796 } 14797 14798 /// Return the correct alignment for the current calling convention. 14799 unsigned 14800 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 14801 DataLayout DL) const { 14802 if (!ArgTy->isVectorTy()) 14803 return DL.getABITypeAlignment(ArgTy); 14804 14805 // Avoid over-aligning vector parameters. It would require realigning the 14806 // stack and waste space for no real benefit. 14807 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 14808 } 14809 14810 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 14811 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 14812 /// passing according to AAPCS rules. 14813 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 14814 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 14815 if (getEffectiveCallingConv(CallConv, isVarArg) != 14816 CallingConv::ARM_AAPCS_VFP) 14817 return false; 14818 14819 HABaseType Base = HA_UNKNOWN; 14820 uint64_t Members = 0; 14821 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 14822 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 14823 14824 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 14825 return IsHA || IsIntArray; 14826 } 14827 14828 unsigned ARMTargetLowering::getExceptionPointerRegister( 14829 const Constant *PersonalityFn) const { 14830 // Platforms which do not use SjLj EH may return values in these registers 14831 // via the personality function. 14832 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 14833 } 14834 14835 unsigned ARMTargetLowering::getExceptionSelectorRegister( 14836 const Constant *PersonalityFn) const { 14837 // Platforms which do not use SjLj EH may return values in these registers 14838 // via the personality function. 14839 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 14840 } 14841 14842 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14843 // Update IsSplitCSR in ARMFunctionInfo. 14844 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 14845 AFI->setIsSplitCSR(true); 14846 } 14847 14848 void ARMTargetLowering::insertCopiesSplitCSR( 14849 MachineBasicBlock *Entry, 14850 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14851 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 14852 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14853 if (!IStart) 14854 return; 14855 14856 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 14857 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14858 MachineBasicBlock::iterator MBBI = Entry->begin(); 14859 for (const MCPhysReg *I = IStart; *I; ++I) { 14860 const TargetRegisterClass *RC = nullptr; 14861 if (ARM::GPRRegClass.contains(*I)) 14862 RC = &ARM::GPRRegClass; 14863 else if (ARM::DPRRegClass.contains(*I)) 14864 RC = &ARM::DPRRegClass; 14865 else 14866 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14867 14868 unsigned NewVR = MRI->createVirtualRegister(RC); 14869 // Create copy from CSR to a virtual register. 14870 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14871 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14872 // nounwind. If we want to generalize this later, we may need to emit 14873 // CFI pseudo-instructions. 14874 assert(Entry->getParent()->getFunction().hasFnAttribute( 14875 Attribute::NoUnwind) && 14876 "Function should be nounwind in insertCopiesSplitCSR!"); 14877 Entry->addLiveIn(*I); 14878 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14879 .addReg(*I); 14880 14881 // Insert the copy-back instructions right before the terminator. 14882 for (auto *Exit : Exits) 14883 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14884 TII->get(TargetOpcode::COPY), *I) 14885 .addReg(NewVR); 14886 } 14887 } 14888 14889 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 14890 MF.getFrameInfo().computeMaxCallFrameSize(MF); 14891 TargetLoweringBase::finalizeLowering(MF); 14892 } 14893