1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMBaseInstrInfo.h" 17 #include "ARMBaseRegisterInfo.h" 18 #include "ARMCallingConv.h" 19 #include "ARMConstantPoolValue.h" 20 #include "ARMMachineFunctionInfo.h" 21 #include "ARMPerfectShuffle.h" 22 #include "ARMRegisterInfo.h" 23 #include "ARMSelectionDAGInfo.h" 24 #include "ARMSubtarget.h" 25 #include "MCTargetDesc/ARMAddressingModes.h" 26 #include "MCTargetDesc/ARMBaseInfo.h" 27 #include "Utils/ARMBaseInfo.h" 28 #include "llvm/ADT/APFloat.h" 29 #include "llvm/ADT/APInt.h" 30 #include "llvm/ADT/ArrayRef.h" 31 #include "llvm/ADT/BitVector.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallVector.h" 36 #include "llvm/ADT/Statistic.h" 37 #include "llvm/ADT/StringExtras.h" 38 #include "llvm/ADT/StringRef.h" 39 #include "llvm/ADT/StringSwitch.h" 40 #include "llvm/ADT/Triple.h" 41 #include "llvm/ADT/Twine.h" 42 #include "llvm/Analysis/VectorUtils.h" 43 #include "llvm/CodeGen/CallingConvLower.h" 44 #include "llvm/CodeGen/ISDOpcodes.h" 45 #include "llvm/CodeGen/IntrinsicLowering.h" 46 #include "llvm/CodeGen/MachineBasicBlock.h" 47 #include "llvm/CodeGen/MachineConstantPool.h" 48 #include "llvm/CodeGen/MachineFrameInfo.h" 49 #include "llvm/CodeGen/MachineFunction.h" 50 #include "llvm/CodeGen/MachineInstr.h" 51 #include "llvm/CodeGen/MachineInstrBuilder.h" 52 #include "llvm/CodeGen/MachineJumpTableInfo.h" 53 #include "llvm/CodeGen/MachineMemOperand.h" 54 #include "llvm/CodeGen/MachineOperand.h" 55 #include "llvm/CodeGen/MachineRegisterInfo.h" 56 #include "llvm/CodeGen/MachineValueType.h" 57 #include "llvm/CodeGen/RuntimeLibcalls.h" 58 #include "llvm/CodeGen/SelectionDAG.h" 59 #include "llvm/CodeGen/SelectionDAGNodes.h" 60 #include "llvm/CodeGen/TargetInstrInfo.h" 61 #include "llvm/CodeGen/TargetLowering.h" 62 #include "llvm/CodeGen/TargetOpcodes.h" 63 #include "llvm/CodeGen/TargetRegisterInfo.h" 64 #include "llvm/CodeGen/TargetSubtargetInfo.h" 65 #include "llvm/CodeGen/ValueTypes.h" 66 #include "llvm/IR/Attributes.h" 67 #include "llvm/IR/CallingConv.h" 68 #include "llvm/IR/Constant.h" 69 #include "llvm/IR/Constants.h" 70 #include "llvm/IR/DataLayout.h" 71 #include "llvm/IR/DebugLoc.h" 72 #include "llvm/IR/DerivedTypes.h" 73 #include "llvm/IR/Function.h" 74 #include "llvm/IR/GlobalAlias.h" 75 #include "llvm/IR/GlobalValue.h" 76 #include "llvm/IR/GlobalVariable.h" 77 #include "llvm/IR/IRBuilder.h" 78 #include "llvm/IR/InlineAsm.h" 79 #include "llvm/IR/Instruction.h" 80 #include "llvm/IR/Instructions.h" 81 #include "llvm/IR/IntrinsicInst.h" 82 #include "llvm/IR/Intrinsics.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Type.h" 85 #include "llvm/IR/User.h" 86 #include "llvm/IR/Value.h" 87 #include "llvm/MC/MCInstrDesc.h" 88 #include "llvm/MC/MCInstrItineraries.h" 89 #include "llvm/MC/MCRegisterInfo.h" 90 #include "llvm/MC/MCSchedule.h" 91 #include "llvm/Support/AtomicOrdering.h" 92 #include "llvm/Support/BranchProbability.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CodeGen.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/ErrorHandling.h" 99 #include "llvm/Support/KnownBits.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 for (MVT VT : MVT::vector_valuetypes()) { 526 for (MVT InnerVT : MVT::vector_valuetypes()) { 527 setTruncStoreAction(VT, InnerVT, Expand); 528 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 529 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 530 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 531 } 532 533 setOperationAction(ISD::MULHS, VT, Expand); 534 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 535 setOperationAction(ISD::MULHU, VT, Expand); 536 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 537 538 setOperationAction(ISD::BSWAP, VT, Expand); 539 } 540 541 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 542 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 543 544 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 545 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 546 547 if (Subtarget->hasNEON()) { 548 addDRTypeForNEON(MVT::v2f32); 549 addDRTypeForNEON(MVT::v8i8); 550 addDRTypeForNEON(MVT::v4i16); 551 addDRTypeForNEON(MVT::v2i32); 552 addDRTypeForNEON(MVT::v1i64); 553 554 addQRTypeForNEON(MVT::v4f32); 555 addQRTypeForNEON(MVT::v2f64); 556 addQRTypeForNEON(MVT::v16i8); 557 addQRTypeForNEON(MVT::v8i16); 558 addQRTypeForNEON(MVT::v4i32); 559 addQRTypeForNEON(MVT::v2i64); 560 561 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 562 // neither Neon nor VFP support any arithmetic operations on it. 563 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 564 // supported for v4f32. 565 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 566 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 567 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 568 // FIXME: Code duplication: FDIV and FREM are expanded always, see 569 // ARMTargetLowering::addTypeForNEON method for details. 570 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 571 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 572 // FIXME: Create unittest. 573 // In another words, find a way when "copysign" appears in DAG with vector 574 // operands. 575 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 576 // FIXME: Code duplication: SETCC has custom operation action, see 577 // ARMTargetLowering::addTypeForNEON method for details. 578 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 579 // FIXME: Create unittest for FNEG and for FABS. 580 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 581 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 582 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 583 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 584 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 585 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 586 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 587 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 588 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 589 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 590 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 591 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 592 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 593 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 594 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 595 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 596 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 597 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 598 599 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 600 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 601 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 602 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 603 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 604 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 605 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 606 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 607 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 608 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 609 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 610 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 611 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 612 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 613 614 // Mark v2f32 intrinsics. 615 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 616 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 617 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 618 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 619 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 620 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 621 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 622 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 623 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 624 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 625 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 626 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 627 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 628 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 629 630 // Neon does not support some operations on v1i64 and v2i64 types. 631 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 632 // Custom handling for some quad-vector types to detect VMULL. 633 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 634 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 635 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 636 // Custom handling for some vector types to avoid expensive expansions 637 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 638 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 639 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 640 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 641 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 642 // a destination type that is wider than the source, and nor does 643 // it have a FP_TO_[SU]INT instruction with a narrower destination than 644 // source. 645 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 646 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 647 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 648 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 649 650 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 651 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 652 653 // NEON does not have single instruction CTPOP for vectors with element 654 // types wider than 8-bits. However, custom lowering can leverage the 655 // v8i8/v16i8 vcnt instruction. 656 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 657 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 658 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 659 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 660 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 661 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 662 663 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 664 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 665 666 // NEON does not have single instruction CTTZ for vectors. 667 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 668 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 669 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 670 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 671 672 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 673 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 674 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 675 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 676 677 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 678 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 679 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 680 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 681 682 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 683 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 684 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 686 687 // NEON only has FMA instructions as of VFP4. 688 if (!Subtarget->hasVFP4()) { 689 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 690 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 691 } 692 693 setTargetDAGCombine(ISD::INTRINSIC_VOID); 694 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 695 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 696 setTargetDAGCombine(ISD::SHL); 697 setTargetDAGCombine(ISD::SRL); 698 setTargetDAGCombine(ISD::SRA); 699 setTargetDAGCombine(ISD::SIGN_EXTEND); 700 setTargetDAGCombine(ISD::ZERO_EXTEND); 701 setTargetDAGCombine(ISD::ANY_EXTEND); 702 setTargetDAGCombine(ISD::BUILD_VECTOR); 703 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 704 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 705 setTargetDAGCombine(ISD::STORE); 706 setTargetDAGCombine(ISD::FP_TO_SINT); 707 setTargetDAGCombine(ISD::FP_TO_UINT); 708 setTargetDAGCombine(ISD::FDIV); 709 setTargetDAGCombine(ISD::LOAD); 710 711 // It is legal to extload from v4i8 to v4i16 or v4i32. 712 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 713 MVT::v2i32}) { 714 for (MVT VT : MVT::integer_vector_valuetypes()) { 715 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 716 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 717 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 718 } 719 } 720 } 721 722 if (Subtarget->isFPOnlySP()) { 723 // When targeting a floating-point unit with only single-precision 724 // operations, f64 is legal for the few double-precision instructions which 725 // are present However, no double-precision operations other than moves, 726 // loads and stores are provided by the hardware. 727 setOperationAction(ISD::FADD, MVT::f64, Expand); 728 setOperationAction(ISD::FSUB, MVT::f64, Expand); 729 setOperationAction(ISD::FMUL, MVT::f64, Expand); 730 setOperationAction(ISD::FMA, MVT::f64, Expand); 731 setOperationAction(ISD::FDIV, MVT::f64, Expand); 732 setOperationAction(ISD::FREM, MVT::f64, Expand); 733 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 734 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 735 setOperationAction(ISD::FNEG, MVT::f64, Expand); 736 setOperationAction(ISD::FABS, MVT::f64, Expand); 737 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 738 setOperationAction(ISD::FSIN, MVT::f64, Expand); 739 setOperationAction(ISD::FCOS, MVT::f64, Expand); 740 setOperationAction(ISD::FPOW, MVT::f64, Expand); 741 setOperationAction(ISD::FLOG, MVT::f64, Expand); 742 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 743 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 744 setOperationAction(ISD::FEXP, MVT::f64, Expand); 745 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 746 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 747 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 748 setOperationAction(ISD::FRINT, MVT::f64, Expand); 749 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 750 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 751 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 752 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 753 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 754 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 755 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 756 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 757 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 758 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 759 } 760 761 computeRegisterProperties(Subtarget->getRegisterInfo()); 762 763 // ARM does not have floating-point extending loads. 764 for (MVT VT : MVT::fp_valuetypes()) { 765 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 766 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 767 } 768 769 // ... or truncating stores 770 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 771 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 772 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 773 774 // ARM does not have i1 sign extending load. 775 for (MVT VT : MVT::integer_valuetypes()) 776 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 777 778 // ARM supports all 4 flavors of integer indexed load / store. 779 if (!Subtarget->isThumb1Only()) { 780 for (unsigned im = (unsigned)ISD::PRE_INC; 781 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 782 setIndexedLoadAction(im, MVT::i1, Legal); 783 setIndexedLoadAction(im, MVT::i8, Legal); 784 setIndexedLoadAction(im, MVT::i16, Legal); 785 setIndexedLoadAction(im, MVT::i32, Legal); 786 setIndexedStoreAction(im, MVT::i1, Legal); 787 setIndexedStoreAction(im, MVT::i8, Legal); 788 setIndexedStoreAction(im, MVT::i16, Legal); 789 setIndexedStoreAction(im, MVT::i32, Legal); 790 } 791 } else { 792 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 793 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 794 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 795 } 796 797 setOperationAction(ISD::SADDO, MVT::i32, Custom); 798 setOperationAction(ISD::UADDO, MVT::i32, Custom); 799 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 800 setOperationAction(ISD::USUBO, MVT::i32, Custom); 801 802 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 803 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 804 805 // i64 operation support. 806 setOperationAction(ISD::MUL, MVT::i64, Expand); 807 setOperationAction(ISD::MULHU, MVT::i32, Expand); 808 if (Subtarget->isThumb1Only()) { 809 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 810 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 811 } 812 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 813 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 814 setOperationAction(ISD::MULHS, MVT::i32, Expand); 815 816 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 817 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 818 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 819 setOperationAction(ISD::SRL, MVT::i64, Custom); 820 setOperationAction(ISD::SRA, MVT::i64, Custom); 821 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 822 823 setOperationAction(ISD::ADDC, MVT::i32, Custom); 824 setOperationAction(ISD::ADDE, MVT::i32, Custom); 825 setOperationAction(ISD::SUBC, MVT::i32, Custom); 826 setOperationAction(ISD::SUBE, MVT::i32, Custom); 827 828 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 829 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 830 831 // ARM does not have ROTL. 832 setOperationAction(ISD::ROTL, MVT::i32, Expand); 833 for (MVT VT : MVT::vector_valuetypes()) { 834 setOperationAction(ISD::ROTL, VT, Expand); 835 setOperationAction(ISD::ROTR, VT, Expand); 836 } 837 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 838 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 839 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 840 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 841 842 // @llvm.readcyclecounter requires the Performance Monitors extension. 843 // Default to the 0 expansion on unsupported platforms. 844 // FIXME: Technically there are older ARM CPUs that have 845 // implementation-specific ways of obtaining this information. 846 if (Subtarget->hasPerfMon()) 847 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 848 849 // Only ARMv6 has BSWAP. 850 if (!Subtarget->hasV6Ops()) 851 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 852 853 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 854 : Subtarget->hasDivideInARMMode(); 855 if (!hasDivide) { 856 // These are expanded into libcalls if the cpu doesn't have HW divider. 857 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 858 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 859 } 860 861 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 862 setOperationAction(ISD::SDIV, MVT::i32, Custom); 863 setOperationAction(ISD::UDIV, MVT::i32, Custom); 864 865 setOperationAction(ISD::SDIV, MVT::i64, Custom); 866 setOperationAction(ISD::UDIV, MVT::i64, Custom); 867 } 868 869 setOperationAction(ISD::SREM, MVT::i32, Expand); 870 setOperationAction(ISD::UREM, MVT::i32, Expand); 871 872 // Register based DivRem for AEABI (RTABI 4.2) 873 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 874 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 875 Subtarget->isTargetWindows()) { 876 setOperationAction(ISD::SREM, MVT::i64, Custom); 877 setOperationAction(ISD::UREM, MVT::i64, Custom); 878 HasStandaloneRem = false; 879 880 if (Subtarget->isTargetWindows()) { 881 const struct { 882 const RTLIB::Libcall Op; 883 const char * const Name; 884 const CallingConv::ID CC; 885 } LibraryCalls[] = { 886 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 887 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 888 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 889 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 890 891 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 892 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 893 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 894 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 895 }; 896 897 for (const auto &LC : LibraryCalls) { 898 setLibcallName(LC.Op, LC.Name); 899 setLibcallCallingConv(LC.Op, LC.CC); 900 } 901 } else { 902 const struct { 903 const RTLIB::Libcall Op; 904 const char * const Name; 905 const CallingConv::ID CC; 906 } LibraryCalls[] = { 907 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 908 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 909 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 910 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 911 912 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 913 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 914 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 915 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 916 }; 917 918 for (const auto &LC : LibraryCalls) { 919 setLibcallName(LC.Op, LC.Name); 920 setLibcallCallingConv(LC.Op, LC.CC); 921 } 922 } 923 924 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 925 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 926 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 927 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 928 } else { 929 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 930 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 931 } 932 933 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 934 for (auto &VT : {MVT::f32, MVT::f64}) 935 setOperationAction(ISD::FPOWI, VT, Custom); 936 937 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 938 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 939 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 940 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 941 942 setOperationAction(ISD::TRAP, MVT::Other, Legal); 943 944 // Use the default implementation. 945 setOperationAction(ISD::VASTART, MVT::Other, Custom); 946 setOperationAction(ISD::VAARG, MVT::Other, Expand); 947 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 948 setOperationAction(ISD::VAEND, MVT::Other, Expand); 949 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 950 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 951 952 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 953 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 954 else 955 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 956 957 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 958 // the default expansion. 959 InsertFencesForAtomic = false; 960 if (Subtarget->hasAnyDataBarrier() && 961 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 962 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 963 // to ldrex/strex loops already. 964 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 965 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 966 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 967 968 // On v8, we have particularly efficient implementations of atomic fences 969 // if they can be combined with nearby atomic loads and stores. 970 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 971 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 972 InsertFencesForAtomic = true; 973 } 974 } else { 975 // If there's anything we can use as a barrier, go through custom lowering 976 // for ATOMIC_FENCE. 977 // If target has DMB in thumb, Fences can be inserted. 978 if (Subtarget->hasDataBarrier()) 979 InsertFencesForAtomic = true; 980 981 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 982 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 983 984 // Set them all for expansion, which will force libcalls. 985 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 986 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 987 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 988 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 989 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 990 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 991 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 992 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 993 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 994 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 995 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 996 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 997 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 998 // Unordered/Monotonic case. 999 if (!InsertFencesForAtomic) { 1000 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1001 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1002 } 1003 } 1004 1005 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1006 1007 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1008 if (!Subtarget->hasV6Ops()) { 1009 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1010 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1011 } 1012 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1013 1014 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1015 !Subtarget->isThumb1Only()) { 1016 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1017 // iff target supports vfp2. 1018 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1019 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1020 } 1021 1022 // We want to custom lower some of our intrinsics. 1023 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1024 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1025 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1026 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1027 if (Subtarget->useSjLjEH()) 1028 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1029 1030 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1031 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1032 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1033 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1034 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1035 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1036 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1037 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1038 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1039 1040 // Thumb-1 cannot currently select ARMISD::SUBE. 1041 if (!Subtarget->isThumb1Only()) 1042 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1043 1044 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1045 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1046 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1047 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1048 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1049 1050 // We don't support sin/cos/fmod/copysign/pow 1051 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1052 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1053 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1054 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1055 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1056 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1057 setOperationAction(ISD::FREM, MVT::f64, Expand); 1058 setOperationAction(ISD::FREM, MVT::f32, Expand); 1059 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1060 !Subtarget->isThumb1Only()) { 1061 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1062 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1063 } 1064 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1065 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1066 1067 if (!Subtarget->hasVFP4()) { 1068 setOperationAction(ISD::FMA, MVT::f64, Expand); 1069 setOperationAction(ISD::FMA, MVT::f32, Expand); 1070 } 1071 1072 // Various VFP goodness 1073 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1074 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1075 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1076 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1077 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1078 } 1079 1080 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1081 if (!Subtarget->hasFP16()) { 1082 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1083 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1084 } 1085 } 1086 1087 // Use __sincos_stret if available. 1088 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1089 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1090 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1091 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1092 } 1093 1094 // FP-ARMv8 implements a lot of rounding-like FP operations. 1095 if (Subtarget->hasFPARMv8()) { 1096 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1097 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1098 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1099 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1100 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1101 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1102 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1103 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1104 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1105 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1106 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1107 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1108 1109 if (!Subtarget->isFPOnlySP()) { 1110 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1111 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1112 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1113 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1114 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1115 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1116 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1117 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1118 } 1119 } 1120 1121 if (Subtarget->hasNEON()) { 1122 // vmin and vmax aren't available in a scalar form, so we use 1123 // a NEON instruction with an undef lane instead. 1124 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1125 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1126 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1127 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1128 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1129 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1130 } 1131 1132 // We have target-specific dag combine patterns for the following nodes: 1133 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1134 setTargetDAGCombine(ISD::ADD); 1135 setTargetDAGCombine(ISD::SUB); 1136 setTargetDAGCombine(ISD::MUL); 1137 setTargetDAGCombine(ISD::AND); 1138 setTargetDAGCombine(ISD::OR); 1139 setTargetDAGCombine(ISD::XOR); 1140 1141 if (Subtarget->hasV6Ops()) 1142 setTargetDAGCombine(ISD::SRL); 1143 1144 setStackPointerRegisterToSaveRestore(ARM::SP); 1145 1146 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1147 !Subtarget->hasVFP2()) 1148 setSchedulingPreference(Sched::RegPressure); 1149 else 1150 setSchedulingPreference(Sched::Hybrid); 1151 1152 //// temporary - rewrite interface to use type 1153 MaxStoresPerMemset = 8; 1154 MaxStoresPerMemsetOptSize = 4; 1155 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1156 MaxStoresPerMemcpyOptSize = 2; 1157 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1158 MaxStoresPerMemmoveOptSize = 2; 1159 1160 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1161 // are at least 4 bytes aligned. 1162 setMinStackArgumentAlignment(4); 1163 1164 // Prefer likely predicted branches to selects on out-of-order cores. 1165 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1166 1167 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1168 } 1169 1170 bool ARMTargetLowering::useSoftFloat() const { 1171 return Subtarget->useSoftFloat(); 1172 } 1173 1174 // FIXME: It might make sense to define the representative register class as the 1175 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1176 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1177 // SPR's representative would be DPR_VFP2. This should work well if register 1178 // pressure tracking were modified such that a register use would increment the 1179 // pressure of the register class's representative and all of it's super 1180 // classes' representatives transitively. We have not implemented this because 1181 // of the difficulty prior to coalescing of modeling operand register classes 1182 // due to the common occurrence of cross class copies and subregister insertions 1183 // and extractions. 1184 std::pair<const TargetRegisterClass *, uint8_t> 1185 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1186 MVT VT) const { 1187 const TargetRegisterClass *RRC = nullptr; 1188 uint8_t Cost = 1; 1189 switch (VT.SimpleTy) { 1190 default: 1191 return TargetLowering::findRepresentativeClass(TRI, VT); 1192 // Use DPR as representative register class for all floating point 1193 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1194 // the cost is 1 for both f32 and f64. 1195 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1196 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1197 RRC = &ARM::DPRRegClass; 1198 // When NEON is used for SP, only half of the register file is available 1199 // because operations that define both SP and DP results will be constrained 1200 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1201 // coalescing by double-counting the SP regs. See the FIXME above. 1202 if (Subtarget->useNEONForSinglePrecisionFP()) 1203 Cost = 2; 1204 break; 1205 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1206 case MVT::v4f32: case MVT::v2f64: 1207 RRC = &ARM::DPRRegClass; 1208 Cost = 2; 1209 break; 1210 case MVT::v4i64: 1211 RRC = &ARM::DPRRegClass; 1212 Cost = 4; 1213 break; 1214 case MVT::v8i64: 1215 RRC = &ARM::DPRRegClass; 1216 Cost = 8; 1217 break; 1218 } 1219 return std::make_pair(RRC, Cost); 1220 } 1221 1222 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1223 switch ((ARMISD::NodeType)Opcode) { 1224 case ARMISD::FIRST_NUMBER: break; 1225 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1226 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1227 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1228 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1229 case ARMISD::CALL: return "ARMISD::CALL"; 1230 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1231 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1232 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1233 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1234 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1235 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1236 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1237 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1238 case ARMISD::CMP: return "ARMISD::CMP"; 1239 case ARMISD::CMN: return "ARMISD::CMN"; 1240 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1241 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1242 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1243 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1244 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1245 1246 case ARMISD::CMOV: return "ARMISD::CMOV"; 1247 1248 case ARMISD::SSAT: return "ARMISD::SSAT"; 1249 case ARMISD::USAT: return "ARMISD::USAT"; 1250 1251 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1252 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1253 case ARMISD::RRX: return "ARMISD::RRX"; 1254 1255 case ARMISD::ADDC: return "ARMISD::ADDC"; 1256 case ARMISD::ADDE: return "ARMISD::ADDE"; 1257 case ARMISD::SUBC: return "ARMISD::SUBC"; 1258 case ARMISD::SUBE: return "ARMISD::SUBE"; 1259 1260 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1261 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1262 1263 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1264 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1265 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1266 1267 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1268 1269 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1270 1271 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1272 1273 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1274 1275 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1276 1277 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1278 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1279 1280 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1281 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1282 case ARMISD::VCGE: return "ARMISD::VCGE"; 1283 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1284 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1285 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1286 case ARMISD::VCGT: return "ARMISD::VCGT"; 1287 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1288 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1289 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1290 case ARMISD::VTST: return "ARMISD::VTST"; 1291 1292 case ARMISD::VSHL: return "ARMISD::VSHL"; 1293 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1294 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1295 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1296 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1297 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1298 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1299 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1300 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1301 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1302 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1303 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1304 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1305 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1306 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1307 case ARMISD::VSLI: return "ARMISD::VSLI"; 1308 case ARMISD::VSRI: return "ARMISD::VSRI"; 1309 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1310 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1311 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1312 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1313 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1314 case ARMISD::VDUP: return "ARMISD::VDUP"; 1315 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1316 case ARMISD::VEXT: return "ARMISD::VEXT"; 1317 case ARMISD::VREV64: return "ARMISD::VREV64"; 1318 case ARMISD::VREV32: return "ARMISD::VREV32"; 1319 case ARMISD::VREV16: return "ARMISD::VREV16"; 1320 case ARMISD::VZIP: return "ARMISD::VZIP"; 1321 case ARMISD::VUZP: return "ARMISD::VUZP"; 1322 case ARMISD::VTRN: return "ARMISD::VTRN"; 1323 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1324 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1325 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1326 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1327 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1328 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1329 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1330 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1331 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1332 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1333 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1334 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1335 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1336 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1337 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1338 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1339 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1340 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1341 case ARMISD::BFI: return "ARMISD::BFI"; 1342 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1343 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1344 case ARMISD::VBSL: return "ARMISD::VBSL"; 1345 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1346 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1347 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1348 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1349 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1350 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1351 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1352 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1353 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1354 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1355 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1356 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1357 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1358 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1359 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1360 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1361 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1362 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1363 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1364 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1365 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1366 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1367 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1368 } 1369 return nullptr; 1370 } 1371 1372 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1373 EVT VT) const { 1374 if (!VT.isVector()) 1375 return getPointerTy(DL); 1376 return VT.changeVectorElementTypeToInteger(); 1377 } 1378 1379 /// getRegClassFor - Return the register class that should be used for the 1380 /// specified value type. 1381 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1382 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1383 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1384 // load / store 4 to 8 consecutive D registers. 1385 if (Subtarget->hasNEON()) { 1386 if (VT == MVT::v4i64) 1387 return &ARM::QQPRRegClass; 1388 if (VT == MVT::v8i64) 1389 return &ARM::QQQQPRRegClass; 1390 } 1391 return TargetLowering::getRegClassFor(VT); 1392 } 1393 1394 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1395 // source/dest is aligned and the copy size is large enough. We therefore want 1396 // to align such objects passed to memory intrinsics. 1397 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1398 unsigned &PrefAlign) const { 1399 if (!isa<MemIntrinsic>(CI)) 1400 return false; 1401 MinSize = 8; 1402 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1403 // cycle faster than 4-byte aligned LDM. 1404 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1405 return true; 1406 } 1407 1408 // Create a fast isel object. 1409 FastISel * 1410 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1411 const TargetLibraryInfo *libInfo) const { 1412 return ARM::createFastISel(funcInfo, libInfo); 1413 } 1414 1415 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1416 unsigned NumVals = N->getNumValues(); 1417 if (!NumVals) 1418 return Sched::RegPressure; 1419 1420 for (unsigned i = 0; i != NumVals; ++i) { 1421 EVT VT = N->getValueType(i); 1422 if (VT == MVT::Glue || VT == MVT::Other) 1423 continue; 1424 if (VT.isFloatingPoint() || VT.isVector()) 1425 return Sched::ILP; 1426 } 1427 1428 if (!N->isMachineOpcode()) 1429 return Sched::RegPressure; 1430 1431 // Load are scheduled for latency even if there instruction itinerary 1432 // is not available. 1433 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1434 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1435 1436 if (MCID.getNumDefs() == 0) 1437 return Sched::RegPressure; 1438 if (!Itins->isEmpty() && 1439 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1440 return Sched::ILP; 1441 1442 return Sched::RegPressure; 1443 } 1444 1445 //===----------------------------------------------------------------------===// 1446 // Lowering Code 1447 //===----------------------------------------------------------------------===// 1448 1449 static bool isSRL16(const SDValue &Op) { 1450 if (Op.getOpcode() != ISD::SRL) 1451 return false; 1452 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1453 return Const->getZExtValue() == 16; 1454 return false; 1455 } 1456 1457 static bool isSRA16(const SDValue &Op) { 1458 if (Op.getOpcode() != ISD::SRA) 1459 return false; 1460 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1461 return Const->getZExtValue() == 16; 1462 return false; 1463 } 1464 1465 static bool isSHL16(const SDValue &Op) { 1466 if (Op.getOpcode() != ISD::SHL) 1467 return false; 1468 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1469 return Const->getZExtValue() == 16; 1470 return false; 1471 } 1472 1473 // Check for a signed 16-bit value. We special case SRA because it makes it 1474 // more simple when also looking for SRAs that aren't sign extending a 1475 // smaller value. Without the check, we'd need to take extra care with 1476 // checking order for some operations. 1477 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1478 if (isSRA16(Op)) 1479 return isSHL16(Op.getOperand(0)); 1480 return DAG.ComputeNumSignBits(Op) == 17; 1481 } 1482 1483 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1484 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1485 switch (CC) { 1486 default: llvm_unreachable("Unknown condition code!"); 1487 case ISD::SETNE: return ARMCC::NE; 1488 case ISD::SETEQ: return ARMCC::EQ; 1489 case ISD::SETGT: return ARMCC::GT; 1490 case ISD::SETGE: return ARMCC::GE; 1491 case ISD::SETLT: return ARMCC::LT; 1492 case ISD::SETLE: return ARMCC::LE; 1493 case ISD::SETUGT: return ARMCC::HI; 1494 case ISD::SETUGE: return ARMCC::HS; 1495 case ISD::SETULT: return ARMCC::LO; 1496 case ISD::SETULE: return ARMCC::LS; 1497 } 1498 } 1499 1500 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1501 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1502 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1503 CondCode2 = ARMCC::AL; 1504 InvalidOnQNaN = true; 1505 switch (CC) { 1506 default: llvm_unreachable("Unknown FP condition!"); 1507 case ISD::SETEQ: 1508 case ISD::SETOEQ: 1509 CondCode = ARMCC::EQ; 1510 InvalidOnQNaN = false; 1511 break; 1512 case ISD::SETGT: 1513 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1514 case ISD::SETGE: 1515 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1516 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1517 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1518 case ISD::SETONE: 1519 CondCode = ARMCC::MI; 1520 CondCode2 = ARMCC::GT; 1521 InvalidOnQNaN = false; 1522 break; 1523 case ISD::SETO: CondCode = ARMCC::VC; break; 1524 case ISD::SETUO: CondCode = ARMCC::VS; break; 1525 case ISD::SETUEQ: 1526 CondCode = ARMCC::EQ; 1527 CondCode2 = ARMCC::VS; 1528 InvalidOnQNaN = false; 1529 break; 1530 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1531 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1532 case ISD::SETLT: 1533 case ISD::SETULT: CondCode = ARMCC::LT; break; 1534 case ISD::SETLE: 1535 case ISD::SETULE: CondCode = ARMCC::LE; break; 1536 case ISD::SETNE: 1537 case ISD::SETUNE: 1538 CondCode = ARMCC::NE; 1539 InvalidOnQNaN = false; 1540 break; 1541 } 1542 } 1543 1544 //===----------------------------------------------------------------------===// 1545 // Calling Convention Implementation 1546 //===----------------------------------------------------------------------===// 1547 1548 #include "ARMGenCallingConv.inc" 1549 1550 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1551 /// account presence of floating point hardware and calling convention 1552 /// limitations, such as support for variadic functions. 1553 CallingConv::ID 1554 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1555 bool isVarArg) const { 1556 switch (CC) { 1557 default: 1558 report_fatal_error("Unsupported calling convention"); 1559 case CallingConv::ARM_AAPCS: 1560 case CallingConv::ARM_APCS: 1561 case CallingConv::GHC: 1562 return CC; 1563 case CallingConv::PreserveMost: 1564 return CallingConv::PreserveMost; 1565 case CallingConv::ARM_AAPCS_VFP: 1566 case CallingConv::Swift: 1567 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1568 case CallingConv::C: 1569 if (!Subtarget->isAAPCS_ABI()) 1570 return CallingConv::ARM_APCS; 1571 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1572 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1573 !isVarArg) 1574 return CallingConv::ARM_AAPCS_VFP; 1575 else 1576 return CallingConv::ARM_AAPCS; 1577 case CallingConv::Fast: 1578 case CallingConv::CXX_FAST_TLS: 1579 if (!Subtarget->isAAPCS_ABI()) { 1580 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1581 return CallingConv::Fast; 1582 return CallingConv::ARM_APCS; 1583 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1584 return CallingConv::ARM_AAPCS_VFP; 1585 else 1586 return CallingConv::ARM_AAPCS; 1587 } 1588 } 1589 1590 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1591 bool isVarArg) const { 1592 return CCAssignFnForNode(CC, false, isVarArg); 1593 } 1594 1595 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1596 bool isVarArg) const { 1597 return CCAssignFnForNode(CC, true, isVarArg); 1598 } 1599 1600 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1601 /// CallingConvention. 1602 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1603 bool Return, 1604 bool isVarArg) const { 1605 switch (getEffectiveCallingConv(CC, isVarArg)) { 1606 default: 1607 report_fatal_error("Unsupported calling convention"); 1608 case CallingConv::ARM_APCS: 1609 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1610 case CallingConv::ARM_AAPCS: 1611 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1612 case CallingConv::ARM_AAPCS_VFP: 1613 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1614 case CallingConv::Fast: 1615 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1616 case CallingConv::GHC: 1617 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1618 case CallingConv::PreserveMost: 1619 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1620 } 1621 } 1622 1623 /// LowerCallResult - Lower the result values of a call into the 1624 /// appropriate copies out of appropriate physical registers. 1625 SDValue ARMTargetLowering::LowerCallResult( 1626 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1627 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1628 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1629 SDValue ThisVal) const { 1630 // Assign locations to each value returned by this call. 1631 SmallVector<CCValAssign, 16> RVLocs; 1632 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1633 *DAG.getContext()); 1634 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1635 1636 // Copy all of the result registers out of their specified physreg. 1637 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1638 CCValAssign VA = RVLocs[i]; 1639 1640 // Pass 'this' value directly from the argument to return value, to avoid 1641 // reg unit interference 1642 if (i == 0 && isThisReturn) { 1643 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1644 "unexpected return calling convention register assignment"); 1645 InVals.push_back(ThisVal); 1646 continue; 1647 } 1648 1649 SDValue Val; 1650 if (VA.needsCustom()) { 1651 // Handle f64 or half of a v2f64. 1652 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1653 InFlag); 1654 Chain = Lo.getValue(1); 1655 InFlag = Lo.getValue(2); 1656 VA = RVLocs[++i]; // skip ahead to next loc 1657 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1658 InFlag); 1659 Chain = Hi.getValue(1); 1660 InFlag = Hi.getValue(2); 1661 if (!Subtarget->isLittle()) 1662 std::swap (Lo, Hi); 1663 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1664 1665 if (VA.getLocVT() == MVT::v2f64) { 1666 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1667 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1668 DAG.getConstant(0, dl, MVT::i32)); 1669 1670 VA = RVLocs[++i]; // skip ahead to next loc 1671 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1672 Chain = Lo.getValue(1); 1673 InFlag = Lo.getValue(2); 1674 VA = RVLocs[++i]; // skip ahead to next loc 1675 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1676 Chain = Hi.getValue(1); 1677 InFlag = Hi.getValue(2); 1678 if (!Subtarget->isLittle()) 1679 std::swap (Lo, Hi); 1680 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1681 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1682 DAG.getConstant(1, dl, MVT::i32)); 1683 } 1684 } else { 1685 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1686 InFlag); 1687 Chain = Val.getValue(1); 1688 InFlag = Val.getValue(2); 1689 } 1690 1691 switch (VA.getLocInfo()) { 1692 default: llvm_unreachable("Unknown loc info!"); 1693 case CCValAssign::Full: break; 1694 case CCValAssign::BCvt: 1695 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1696 break; 1697 } 1698 1699 InVals.push_back(Val); 1700 } 1701 1702 return Chain; 1703 } 1704 1705 /// LowerMemOpCallTo - Store the argument to the stack. 1706 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1707 SDValue Arg, const SDLoc &dl, 1708 SelectionDAG &DAG, 1709 const CCValAssign &VA, 1710 ISD::ArgFlagsTy Flags) const { 1711 unsigned LocMemOffset = VA.getLocMemOffset(); 1712 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1713 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1714 StackPtr, PtrOff); 1715 return DAG.getStore( 1716 Chain, dl, Arg, PtrOff, 1717 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1718 } 1719 1720 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1721 SDValue Chain, SDValue &Arg, 1722 RegsToPassVector &RegsToPass, 1723 CCValAssign &VA, CCValAssign &NextVA, 1724 SDValue &StackPtr, 1725 SmallVectorImpl<SDValue> &MemOpChains, 1726 ISD::ArgFlagsTy Flags) const { 1727 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1728 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1729 unsigned id = Subtarget->isLittle() ? 0 : 1; 1730 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1731 1732 if (NextVA.isRegLoc()) 1733 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1734 else { 1735 assert(NextVA.isMemLoc()); 1736 if (!StackPtr.getNode()) 1737 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1738 getPointerTy(DAG.getDataLayout())); 1739 1740 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1741 dl, DAG, NextVA, 1742 Flags)); 1743 } 1744 } 1745 1746 /// LowerCall - Lowering a call into a callseq_start <- 1747 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1748 /// nodes. 1749 SDValue 1750 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1751 SmallVectorImpl<SDValue> &InVals) const { 1752 SelectionDAG &DAG = CLI.DAG; 1753 SDLoc &dl = CLI.DL; 1754 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1755 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1756 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1757 SDValue Chain = CLI.Chain; 1758 SDValue Callee = CLI.Callee; 1759 bool &isTailCall = CLI.IsTailCall; 1760 CallingConv::ID CallConv = CLI.CallConv; 1761 bool doesNotRet = CLI.DoesNotReturn; 1762 bool isVarArg = CLI.IsVarArg; 1763 1764 MachineFunction &MF = DAG.getMachineFunction(); 1765 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1766 bool isThisReturn = false; 1767 bool isSibCall = false; 1768 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1769 1770 // Disable tail calls if they're not supported. 1771 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1772 isTailCall = false; 1773 1774 if (isTailCall) { 1775 // Check if it's really possible to do a tail call. 1776 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1777 isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(), 1778 Outs, OutVals, Ins, DAG); 1779 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1780 report_fatal_error("failed to perform tail call elimination on a call " 1781 "site marked musttail"); 1782 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1783 // detected sibcalls. 1784 if (isTailCall) { 1785 ++NumTailCalls; 1786 isSibCall = true; 1787 } 1788 } 1789 1790 // Analyze operands of the call, assigning locations to each operand. 1791 SmallVector<CCValAssign, 16> ArgLocs; 1792 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1793 *DAG.getContext()); 1794 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1795 1796 // Get a count of how many bytes are to be pushed on the stack. 1797 unsigned NumBytes = CCInfo.getNextStackOffset(); 1798 1799 // For tail calls, memory operands are available in our caller's stack. 1800 if (isSibCall) 1801 NumBytes = 0; 1802 1803 // Adjust the stack pointer for the new arguments... 1804 // These operations are automatically eliminated by the prolog/epilog pass 1805 if (!isSibCall) 1806 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1807 1808 SDValue StackPtr = 1809 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1810 1811 RegsToPassVector RegsToPass; 1812 SmallVector<SDValue, 8> MemOpChains; 1813 1814 // Walk the register/memloc assignments, inserting copies/loads. In the case 1815 // of tail call optimization, arguments are handled later. 1816 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1817 i != e; 1818 ++i, ++realArgIdx) { 1819 CCValAssign &VA = ArgLocs[i]; 1820 SDValue Arg = OutVals[realArgIdx]; 1821 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1822 bool isByVal = Flags.isByVal(); 1823 1824 // Promote the value if needed. 1825 switch (VA.getLocInfo()) { 1826 default: llvm_unreachable("Unknown loc info!"); 1827 case CCValAssign::Full: break; 1828 case CCValAssign::SExt: 1829 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1830 break; 1831 case CCValAssign::ZExt: 1832 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1833 break; 1834 case CCValAssign::AExt: 1835 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1836 break; 1837 case CCValAssign::BCvt: 1838 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1839 break; 1840 } 1841 1842 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1843 if (VA.needsCustom()) { 1844 if (VA.getLocVT() == MVT::v2f64) { 1845 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1846 DAG.getConstant(0, dl, MVT::i32)); 1847 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1848 DAG.getConstant(1, dl, MVT::i32)); 1849 1850 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1851 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1852 1853 VA = ArgLocs[++i]; // skip ahead to next loc 1854 if (VA.isRegLoc()) { 1855 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1856 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1857 } else { 1858 assert(VA.isMemLoc()); 1859 1860 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1861 dl, DAG, VA, Flags)); 1862 } 1863 } else { 1864 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1865 StackPtr, MemOpChains, Flags); 1866 } 1867 } else if (VA.isRegLoc()) { 1868 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1869 Outs[0].VT == MVT::i32) { 1870 assert(VA.getLocVT() == MVT::i32 && 1871 "unexpected calling convention register assignment"); 1872 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1873 "unexpected use of 'returned'"); 1874 isThisReturn = true; 1875 } 1876 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1877 } else if (isByVal) { 1878 assert(VA.isMemLoc()); 1879 unsigned offset = 0; 1880 1881 // True if this byval aggregate will be split between registers 1882 // and memory. 1883 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1884 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1885 1886 if (CurByValIdx < ByValArgsCount) { 1887 1888 unsigned RegBegin, RegEnd; 1889 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1890 1891 EVT PtrVT = 1892 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1893 unsigned int i, j; 1894 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1895 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1896 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1897 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1898 MachinePointerInfo(), 1899 DAG.InferPtrAlignment(AddArg)); 1900 MemOpChains.push_back(Load.getValue(1)); 1901 RegsToPass.push_back(std::make_pair(j, Load)); 1902 } 1903 1904 // If parameter size outsides register area, "offset" value 1905 // helps us to calculate stack slot for remained part properly. 1906 offset = RegEnd - RegBegin; 1907 1908 CCInfo.nextInRegsParam(); 1909 } 1910 1911 if (Flags.getByValSize() > 4*offset) { 1912 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1913 unsigned LocMemOffset = VA.getLocMemOffset(); 1914 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1915 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1916 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1917 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1918 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1919 MVT::i32); 1920 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1921 MVT::i32); 1922 1923 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1924 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1925 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1926 Ops)); 1927 } 1928 } else if (!isSibCall) { 1929 assert(VA.isMemLoc()); 1930 1931 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1932 dl, DAG, VA, Flags)); 1933 } 1934 } 1935 1936 if (!MemOpChains.empty()) 1937 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1938 1939 // Build a sequence of copy-to-reg nodes chained together with token chain 1940 // and flag operands which copy the outgoing args into the appropriate regs. 1941 SDValue InFlag; 1942 // Tail call byval lowering might overwrite argument registers so in case of 1943 // tail call optimization the copies to registers are lowered later. 1944 if (!isTailCall) 1945 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1946 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1947 RegsToPass[i].second, InFlag); 1948 InFlag = Chain.getValue(1); 1949 } 1950 1951 // For tail calls lower the arguments to the 'real' stack slot. 1952 if (isTailCall) { 1953 // Force all the incoming stack arguments to be loaded from the stack 1954 // before any new outgoing arguments are stored to the stack, because the 1955 // outgoing stack slots may alias the incoming argument stack slots, and 1956 // the alias isn't otherwise explicit. This is slightly more conservative 1957 // than necessary, because it means that each store effectively depends 1958 // on every argument instead of just those arguments it would clobber. 1959 1960 // Do not flag preceding copytoreg stuff together with the following stuff. 1961 InFlag = SDValue(); 1962 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1963 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1964 RegsToPass[i].second, InFlag); 1965 InFlag = Chain.getValue(1); 1966 } 1967 InFlag = SDValue(); 1968 } 1969 1970 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1971 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1972 // node so that legalize doesn't hack it. 1973 bool isDirect = false; 1974 1975 const TargetMachine &TM = getTargetMachine(); 1976 const Module *Mod = MF.getFunction().getParent(); 1977 const GlobalValue *GV = nullptr; 1978 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1979 GV = G->getGlobal(); 1980 bool isStub = 1981 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1982 1983 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1984 bool isLocalARMFunc = false; 1985 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1986 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1987 1988 if (Subtarget->genLongCalls()) { 1989 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 1990 "long-calls codegen is not position independent!"); 1991 // Handle a global address or an external symbol. If it's not one of 1992 // those, the target's already in a register, so we don't need to do 1993 // anything extra. 1994 if (isa<GlobalAddressSDNode>(Callee)) { 1995 // Create a constant pool entry for the callee address 1996 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1997 ARMConstantPoolValue *CPV = 1998 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1999 2000 // Get the address of the callee into a register 2001 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2002 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2003 Callee = DAG.getLoad( 2004 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2005 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2006 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2007 const char *Sym = S->getSymbol(); 2008 2009 // Create a constant pool entry for the callee address 2010 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2011 ARMConstantPoolValue *CPV = 2012 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2013 ARMPCLabelIndex, 0); 2014 // Get the address of the callee into a register 2015 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2016 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2017 Callee = DAG.getLoad( 2018 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2019 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2020 } 2021 } else if (isa<GlobalAddressSDNode>(Callee)) { 2022 // If we're optimizing for minimum size and the function is called three or 2023 // more times in this block, we can improve codesize by calling indirectly 2024 // as BLXr has a 16-bit encoding. 2025 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2026 auto *BB = CLI.CS.getParent(); 2027 bool PreferIndirect = 2028 Subtarget->isThumb() && MF.getFunction().optForMinSize() && 2029 count_if(GV->users(), [&BB](const User *U) { 2030 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2031 }) > 2; 2032 2033 if (!PreferIndirect) { 2034 isDirect = true; 2035 bool isDef = GV->isStrongDefinitionForLinker(); 2036 2037 // ARM call to a local ARM function is predicable. 2038 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2039 // tBX takes a register source operand. 2040 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2041 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2042 Callee = DAG.getNode( 2043 ARMISD::WrapperPIC, dl, PtrVt, 2044 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2045 Callee = DAG.getLoad( 2046 PtrVt, dl, DAG.getEntryNode(), Callee, 2047 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2048 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2049 MachineMemOperand::MOInvariant); 2050 } else if (Subtarget->isTargetCOFF()) { 2051 assert(Subtarget->isTargetWindows() && 2052 "Windows is the only supported COFF target"); 2053 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2054 ? ARMII::MO_DLLIMPORT 2055 : ARMII::MO_NO_FLAG; 2056 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2057 TargetFlags); 2058 if (GV->hasDLLImportStorageClass()) 2059 Callee = 2060 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2061 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2062 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2063 } else { 2064 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2065 } 2066 } 2067 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2068 isDirect = true; 2069 // tBX takes a register source operand. 2070 const char *Sym = S->getSymbol(); 2071 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2072 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2073 ARMConstantPoolValue *CPV = 2074 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2075 ARMPCLabelIndex, 4); 2076 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2077 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2078 Callee = DAG.getLoad( 2079 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2080 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2081 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2082 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2083 } else { 2084 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2085 } 2086 } 2087 2088 // FIXME: handle tail calls differently. 2089 unsigned CallOpc; 2090 if (Subtarget->isThumb()) { 2091 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2092 CallOpc = ARMISD::CALL_NOLINK; 2093 else 2094 CallOpc = ARMISD::CALL; 2095 } else { 2096 if (!isDirect && !Subtarget->hasV5TOps()) 2097 CallOpc = ARMISD::CALL_NOLINK; 2098 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2099 // Emit regular call when code size is the priority 2100 !MF.getFunction().optForMinSize()) 2101 // "mov lr, pc; b _foo" to avoid confusing the RSP 2102 CallOpc = ARMISD::CALL_NOLINK; 2103 else 2104 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2105 } 2106 2107 std::vector<SDValue> Ops; 2108 Ops.push_back(Chain); 2109 Ops.push_back(Callee); 2110 2111 // Add argument registers to the end of the list so that they are known live 2112 // into the call. 2113 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2114 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2115 RegsToPass[i].second.getValueType())); 2116 2117 // Add a register mask operand representing the call-preserved registers. 2118 if (!isTailCall) { 2119 const uint32_t *Mask; 2120 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2121 if (isThisReturn) { 2122 // For 'this' returns, use the R0-preserving mask if applicable 2123 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2124 if (!Mask) { 2125 // Set isThisReturn to false if the calling convention is not one that 2126 // allows 'returned' to be modeled in this way, so LowerCallResult does 2127 // not try to pass 'this' straight through 2128 isThisReturn = false; 2129 Mask = ARI->getCallPreservedMask(MF, CallConv); 2130 } 2131 } else 2132 Mask = ARI->getCallPreservedMask(MF, CallConv); 2133 2134 assert(Mask && "Missing call preserved mask for calling convention"); 2135 Ops.push_back(DAG.getRegisterMask(Mask)); 2136 } 2137 2138 if (InFlag.getNode()) 2139 Ops.push_back(InFlag); 2140 2141 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2142 if (isTailCall) { 2143 MF.getFrameInfo().setHasTailCall(); 2144 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2145 } 2146 2147 // Returns a chain and a flag for retval copy to use. 2148 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2149 InFlag = Chain.getValue(1); 2150 2151 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2152 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2153 if (!Ins.empty()) 2154 InFlag = Chain.getValue(1); 2155 2156 // Handle result values, copying them out of physregs into vregs that we 2157 // return. 2158 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2159 InVals, isThisReturn, 2160 isThisReturn ? OutVals[0] : SDValue()); 2161 } 2162 2163 /// HandleByVal - Every parameter *after* a byval parameter is passed 2164 /// on the stack. Remember the next parameter register to allocate, 2165 /// and then confiscate the rest of the parameter registers to insure 2166 /// this. 2167 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2168 unsigned Align) const { 2169 // Byval (as with any stack) slots are always at least 4 byte aligned. 2170 Align = std::max(Align, 4U); 2171 2172 unsigned Reg = State->AllocateReg(GPRArgRegs); 2173 if (!Reg) 2174 return; 2175 2176 unsigned AlignInRegs = Align / 4; 2177 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2178 for (unsigned i = 0; i < Waste; ++i) 2179 Reg = State->AllocateReg(GPRArgRegs); 2180 2181 if (!Reg) 2182 return; 2183 2184 unsigned Excess = 4 * (ARM::R4 - Reg); 2185 2186 // Special case when NSAA != SP and parameter size greater than size of 2187 // all remained GPR regs. In that case we can't split parameter, we must 2188 // send it to stack. We also must set NCRN to R4, so waste all 2189 // remained registers. 2190 const unsigned NSAAOffset = State->getNextStackOffset(); 2191 if (NSAAOffset != 0 && Size > Excess) { 2192 while (State->AllocateReg(GPRArgRegs)) 2193 ; 2194 return; 2195 } 2196 2197 // First register for byval parameter is the first register that wasn't 2198 // allocated before this method call, so it would be "reg". 2199 // If parameter is small enough to be saved in range [reg, r4), then 2200 // the end (first after last) register would be reg + param-size-in-regs, 2201 // else parameter would be splitted between registers and stack, 2202 // end register would be r4 in this case. 2203 unsigned ByValRegBegin = Reg; 2204 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2205 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2206 // Note, first register is allocated in the beginning of function already, 2207 // allocate remained amount of registers we need. 2208 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2209 State->AllocateReg(GPRArgRegs); 2210 // A byval parameter that is split between registers and memory needs its 2211 // size truncated here. 2212 // In the case where the entire structure fits in registers, we set the 2213 // size in memory to zero. 2214 Size = std::max<int>(Size - Excess, 0); 2215 } 2216 2217 /// MatchingStackOffset - Return true if the given stack call argument is 2218 /// already available in the same position (relatively) of the caller's 2219 /// incoming argument stack. 2220 static 2221 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2222 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2223 const TargetInstrInfo *TII) { 2224 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2225 int FI = std::numeric_limits<int>::max(); 2226 if (Arg.getOpcode() == ISD::CopyFromReg) { 2227 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2228 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2229 return false; 2230 MachineInstr *Def = MRI->getVRegDef(VR); 2231 if (!Def) 2232 return false; 2233 if (!Flags.isByVal()) { 2234 if (!TII->isLoadFromStackSlot(*Def, FI)) 2235 return false; 2236 } else { 2237 return false; 2238 } 2239 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2240 if (Flags.isByVal()) 2241 // ByVal argument is passed in as a pointer but it's now being 2242 // dereferenced. e.g. 2243 // define @foo(%struct.X* %A) { 2244 // tail call @bar(%struct.X* byval %A) 2245 // } 2246 return false; 2247 SDValue Ptr = Ld->getBasePtr(); 2248 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2249 if (!FINode) 2250 return false; 2251 FI = FINode->getIndex(); 2252 } else 2253 return false; 2254 2255 assert(FI != std::numeric_limits<int>::max()); 2256 if (!MFI.isFixedObjectIndex(FI)) 2257 return false; 2258 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2259 } 2260 2261 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2262 /// for tail call optimization. Targets which want to do tail call 2263 /// optimization should implement this function. 2264 bool 2265 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2266 CallingConv::ID CalleeCC, 2267 bool isVarArg, 2268 bool isCalleeStructRet, 2269 bool isCallerStructRet, 2270 const SmallVectorImpl<ISD::OutputArg> &Outs, 2271 const SmallVectorImpl<SDValue> &OutVals, 2272 const SmallVectorImpl<ISD::InputArg> &Ins, 2273 SelectionDAG& DAG) const { 2274 MachineFunction &MF = DAG.getMachineFunction(); 2275 const Function &CallerF = MF.getFunction(); 2276 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2277 2278 assert(Subtarget->supportsTailCall()); 2279 2280 // Tail calls to function pointers cannot be optimized for Thumb1 if the args 2281 // to the call take up r0-r3. The reason is that there are no legal registers 2282 // left to hold the pointer to the function to be called. 2283 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2284 !isa<GlobalAddressSDNode>(Callee.getNode())) 2285 return false; 2286 2287 // Look for obvious safe cases to perform tail call optimization that do not 2288 // require ABI changes. This is what gcc calls sibcall. 2289 2290 // Exception-handling functions need a special set of instructions to indicate 2291 // a return to the hardware. Tail-calling another function would probably 2292 // break this. 2293 if (CallerF.hasFnAttribute("interrupt")) 2294 return false; 2295 2296 // Also avoid sibcall optimization if either caller or callee uses struct 2297 // return semantics. 2298 if (isCalleeStructRet || isCallerStructRet) 2299 return false; 2300 2301 // Externally-defined functions with weak linkage should not be 2302 // tail-called on ARM when the OS does not support dynamic 2303 // pre-emption of symbols, as the AAELF spec requires normal calls 2304 // to undefined weak functions to be replaced with a NOP or jump to the 2305 // next instruction. The behaviour of branch instructions in this 2306 // situation (as used for tail calls) is implementation-defined, so we 2307 // cannot rely on the linker replacing the tail call with a return. 2308 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2309 const GlobalValue *GV = G->getGlobal(); 2310 const Triple &TT = getTargetMachine().getTargetTriple(); 2311 if (GV->hasExternalWeakLinkage() && 2312 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2313 return false; 2314 } 2315 2316 // Check that the call results are passed in the same way. 2317 LLVMContext &C = *DAG.getContext(); 2318 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2319 CCAssignFnForReturn(CalleeCC, isVarArg), 2320 CCAssignFnForReturn(CallerCC, isVarArg))) 2321 return false; 2322 // The callee has to preserve all registers the caller needs to preserve. 2323 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2324 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2325 if (CalleeCC != CallerCC) { 2326 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2327 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2328 return false; 2329 } 2330 2331 // If Caller's vararg or byval argument has been split between registers and 2332 // stack, do not perform tail call, since part of the argument is in caller's 2333 // local frame. 2334 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2335 if (AFI_Caller->getArgRegsSaveSize()) 2336 return false; 2337 2338 // If the callee takes no arguments then go on to check the results of the 2339 // call. 2340 if (!Outs.empty()) { 2341 // Check if stack adjustment is needed. For now, do not do this if any 2342 // argument is passed on the stack. 2343 SmallVector<CCValAssign, 16> ArgLocs; 2344 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2345 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2346 if (CCInfo.getNextStackOffset()) { 2347 // Check if the arguments are already laid out in the right way as 2348 // the caller's fixed stack objects. 2349 MachineFrameInfo &MFI = MF.getFrameInfo(); 2350 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2351 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2352 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2353 i != e; 2354 ++i, ++realArgIdx) { 2355 CCValAssign &VA = ArgLocs[i]; 2356 EVT RegVT = VA.getLocVT(); 2357 SDValue Arg = OutVals[realArgIdx]; 2358 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2359 if (VA.getLocInfo() == CCValAssign::Indirect) 2360 return false; 2361 if (VA.needsCustom()) { 2362 // f64 and vector types are split into multiple registers or 2363 // register/stack-slot combinations. The types will not match 2364 // the registers; give up on memory f64 refs until we figure 2365 // out what to do about this. 2366 if (!VA.isRegLoc()) 2367 return false; 2368 if (!ArgLocs[++i].isRegLoc()) 2369 return false; 2370 if (RegVT == MVT::v2f64) { 2371 if (!ArgLocs[++i].isRegLoc()) 2372 return false; 2373 if (!ArgLocs[++i].isRegLoc()) 2374 return false; 2375 } 2376 } else if (!VA.isRegLoc()) { 2377 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2378 MFI, MRI, TII)) 2379 return false; 2380 } 2381 } 2382 } 2383 2384 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2385 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2386 return false; 2387 } 2388 2389 return true; 2390 } 2391 2392 bool 2393 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2394 MachineFunction &MF, bool isVarArg, 2395 const SmallVectorImpl<ISD::OutputArg> &Outs, 2396 LLVMContext &Context) const { 2397 SmallVector<CCValAssign, 16> RVLocs; 2398 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2399 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2400 } 2401 2402 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2403 const SDLoc &DL, SelectionDAG &DAG) { 2404 const MachineFunction &MF = DAG.getMachineFunction(); 2405 const Function &F = MF.getFunction(); 2406 2407 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2408 2409 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2410 // version of the "preferred return address". These offsets affect the return 2411 // instruction if this is a return from PL1 without hypervisor extensions. 2412 // IRQ/FIQ: +4 "subs pc, lr, #4" 2413 // SWI: 0 "subs pc, lr, #0" 2414 // ABORT: +4 "subs pc, lr, #4" 2415 // UNDEF: +4/+2 "subs pc, lr, #0" 2416 // UNDEF varies depending on where the exception came from ARM or Thumb 2417 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2418 2419 int64_t LROffset; 2420 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2421 IntKind == "ABORT") 2422 LROffset = 4; 2423 else if (IntKind == "SWI" || IntKind == "UNDEF") 2424 LROffset = 0; 2425 else 2426 report_fatal_error("Unsupported interrupt attribute. If present, value " 2427 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2428 2429 RetOps.insert(RetOps.begin() + 1, 2430 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2431 2432 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2433 } 2434 2435 SDValue 2436 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2437 bool isVarArg, 2438 const SmallVectorImpl<ISD::OutputArg> &Outs, 2439 const SmallVectorImpl<SDValue> &OutVals, 2440 const SDLoc &dl, SelectionDAG &DAG) const { 2441 // CCValAssign - represent the assignment of the return value to a location. 2442 SmallVector<CCValAssign, 16> RVLocs; 2443 2444 // CCState - Info about the registers and stack slots. 2445 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2446 *DAG.getContext()); 2447 2448 // Analyze outgoing return values. 2449 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2450 2451 SDValue Flag; 2452 SmallVector<SDValue, 4> RetOps; 2453 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2454 bool isLittleEndian = Subtarget->isLittle(); 2455 2456 MachineFunction &MF = DAG.getMachineFunction(); 2457 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2458 AFI->setReturnRegsCount(RVLocs.size()); 2459 2460 // Copy the result values into the output registers. 2461 for (unsigned i = 0, realRVLocIdx = 0; 2462 i != RVLocs.size(); 2463 ++i, ++realRVLocIdx) { 2464 CCValAssign &VA = RVLocs[i]; 2465 assert(VA.isRegLoc() && "Can only return in registers!"); 2466 2467 SDValue Arg = OutVals[realRVLocIdx]; 2468 2469 switch (VA.getLocInfo()) { 2470 default: llvm_unreachable("Unknown loc info!"); 2471 case CCValAssign::Full: break; 2472 case CCValAssign::BCvt: 2473 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2474 break; 2475 } 2476 2477 if (VA.needsCustom()) { 2478 if (VA.getLocVT() == MVT::v2f64) { 2479 // Extract the first half and return it in two registers. 2480 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2481 DAG.getConstant(0, dl, MVT::i32)); 2482 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2483 DAG.getVTList(MVT::i32, MVT::i32), Half); 2484 2485 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2486 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2487 Flag); 2488 Flag = Chain.getValue(1); 2489 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2490 VA = RVLocs[++i]; // skip ahead to next loc 2491 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2492 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2493 Flag); 2494 Flag = Chain.getValue(1); 2495 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2496 VA = RVLocs[++i]; // skip ahead to next loc 2497 2498 // Extract the 2nd half and fall through to handle it as an f64 value. 2499 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2500 DAG.getConstant(1, dl, MVT::i32)); 2501 } 2502 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2503 // available. 2504 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2505 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2506 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2507 fmrrd.getValue(isLittleEndian ? 0 : 1), 2508 Flag); 2509 Flag = Chain.getValue(1); 2510 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2511 VA = RVLocs[++i]; // skip ahead to next loc 2512 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2513 fmrrd.getValue(isLittleEndian ? 1 : 0), 2514 Flag); 2515 } else 2516 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2517 2518 // Guarantee that all emitted copies are 2519 // stuck together, avoiding something bad. 2520 Flag = Chain.getValue(1); 2521 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2522 } 2523 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2524 const MCPhysReg *I = 2525 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2526 if (I) { 2527 for (; *I; ++I) { 2528 if (ARM::GPRRegClass.contains(*I)) 2529 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2530 else if (ARM::DPRRegClass.contains(*I)) 2531 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2532 else 2533 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2534 } 2535 } 2536 2537 // Update chain and glue. 2538 RetOps[0] = Chain; 2539 if (Flag.getNode()) 2540 RetOps.push_back(Flag); 2541 2542 // CPUs which aren't M-class use a special sequence to return from 2543 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2544 // though we use "subs pc, lr, #N"). 2545 // 2546 // M-class CPUs actually use a normal return sequence with a special 2547 // (hardware-provided) value in LR, so the normal code path works. 2548 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2549 !Subtarget->isMClass()) { 2550 if (Subtarget->isThumb1Only()) 2551 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2552 return LowerInterruptReturn(RetOps, dl, DAG); 2553 } 2554 2555 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2556 } 2557 2558 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2559 if (N->getNumValues() != 1) 2560 return false; 2561 if (!N->hasNUsesOfValue(1, 0)) 2562 return false; 2563 2564 SDValue TCChain = Chain; 2565 SDNode *Copy = *N->use_begin(); 2566 if (Copy->getOpcode() == ISD::CopyToReg) { 2567 // If the copy has a glue operand, we conservatively assume it isn't safe to 2568 // perform a tail call. 2569 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2570 return false; 2571 TCChain = Copy->getOperand(0); 2572 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2573 SDNode *VMov = Copy; 2574 // f64 returned in a pair of GPRs. 2575 SmallPtrSet<SDNode*, 2> Copies; 2576 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2577 UI != UE; ++UI) { 2578 if (UI->getOpcode() != ISD::CopyToReg) 2579 return false; 2580 Copies.insert(*UI); 2581 } 2582 if (Copies.size() > 2) 2583 return false; 2584 2585 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2586 UI != UE; ++UI) { 2587 SDValue UseChain = UI->getOperand(0); 2588 if (Copies.count(UseChain.getNode())) 2589 // Second CopyToReg 2590 Copy = *UI; 2591 else { 2592 // We are at the top of this chain. 2593 // If the copy has a glue operand, we conservatively assume it 2594 // isn't safe to perform a tail call. 2595 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2596 return false; 2597 // First CopyToReg 2598 TCChain = UseChain; 2599 } 2600 } 2601 } else if (Copy->getOpcode() == ISD::BITCAST) { 2602 // f32 returned in a single GPR. 2603 if (!Copy->hasOneUse()) 2604 return false; 2605 Copy = *Copy->use_begin(); 2606 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2607 return false; 2608 // If the copy has a glue operand, we conservatively assume it isn't safe to 2609 // perform a tail call. 2610 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2611 return false; 2612 TCChain = Copy->getOperand(0); 2613 } else { 2614 return false; 2615 } 2616 2617 bool HasRet = false; 2618 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2619 UI != UE; ++UI) { 2620 if (UI->getOpcode() != ARMISD::RET_FLAG && 2621 UI->getOpcode() != ARMISD::INTRET_FLAG) 2622 return false; 2623 HasRet = true; 2624 } 2625 2626 if (!HasRet) 2627 return false; 2628 2629 Chain = TCChain; 2630 return true; 2631 } 2632 2633 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2634 if (!Subtarget->supportsTailCall()) 2635 return false; 2636 2637 auto Attr = 2638 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2639 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2640 return false; 2641 2642 return true; 2643 } 2644 2645 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2646 // and pass the lower and high parts through. 2647 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2648 SDLoc DL(Op); 2649 SDValue WriteValue = Op->getOperand(2); 2650 2651 // This function is only supposed to be called for i64 type argument. 2652 assert(WriteValue.getValueType() == MVT::i64 2653 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2654 2655 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2656 DAG.getConstant(0, DL, MVT::i32)); 2657 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2658 DAG.getConstant(1, DL, MVT::i32)); 2659 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2660 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2661 } 2662 2663 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2664 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2665 // one of the above mentioned nodes. It has to be wrapped because otherwise 2666 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2667 // be used to form addressing mode. These wrapped nodes will be selected 2668 // into MOVi. 2669 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2670 SelectionDAG &DAG) const { 2671 EVT PtrVT = Op.getValueType(); 2672 // FIXME there is no actual debug info here 2673 SDLoc dl(Op); 2674 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2675 SDValue Res; 2676 2677 // When generating execute-only code Constant Pools must be promoted to the 2678 // global data section. It's a bit ugly that we can't share them across basic 2679 // blocks, but this way we guarantee that execute-only behaves correct with 2680 // position-independent addressing modes. 2681 if (Subtarget->genExecuteOnly()) { 2682 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2683 auto T = const_cast<Type*>(CP->getType()); 2684 auto C = const_cast<Constant*>(CP->getConstVal()); 2685 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2686 getFunction().getParent()); 2687 auto GV = new GlobalVariable( 2688 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2689 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2690 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2691 Twine(AFI->createPICLabelUId()) 2692 ); 2693 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2694 dl, PtrVT); 2695 return LowerGlobalAddress(GA, DAG); 2696 } 2697 2698 if (CP->isMachineConstantPoolEntry()) 2699 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2700 CP->getAlignment()); 2701 else 2702 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2703 CP->getAlignment()); 2704 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2705 } 2706 2707 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2708 return MachineJumpTableInfo::EK_Inline; 2709 } 2710 2711 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2712 SelectionDAG &DAG) const { 2713 MachineFunction &MF = DAG.getMachineFunction(); 2714 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2715 unsigned ARMPCLabelIndex = 0; 2716 SDLoc DL(Op); 2717 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2718 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2719 SDValue CPAddr; 2720 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2721 if (!IsPositionIndependent) { 2722 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2723 } else { 2724 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2725 ARMPCLabelIndex = AFI->createPICLabelUId(); 2726 ARMConstantPoolValue *CPV = 2727 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2728 ARMCP::CPBlockAddress, PCAdj); 2729 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2730 } 2731 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2732 SDValue Result = DAG.getLoad( 2733 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2734 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2735 if (!IsPositionIndependent) 2736 return Result; 2737 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2738 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2739 } 2740 2741 /// \brief Convert a TLS address reference into the correct sequence of loads 2742 /// and calls to compute the variable's address for Darwin, and return an 2743 /// SDValue containing the final node. 2744 2745 /// Darwin only has one TLS scheme which must be capable of dealing with the 2746 /// fully general situation, in the worst case. This means: 2747 /// + "extern __thread" declaration. 2748 /// + Defined in a possibly unknown dynamic library. 2749 /// 2750 /// The general system is that each __thread variable has a [3 x i32] descriptor 2751 /// which contains information used by the runtime to calculate the address. The 2752 /// only part of this the compiler needs to know about is the first word, which 2753 /// contains a function pointer that must be called with the address of the 2754 /// entire descriptor in "r0". 2755 /// 2756 /// Since this descriptor may be in a different unit, in general access must 2757 /// proceed along the usual ARM rules. A common sequence to produce is: 2758 /// 2759 /// movw rT1, :lower16:_var$non_lazy_ptr 2760 /// movt rT1, :upper16:_var$non_lazy_ptr 2761 /// ldr r0, [rT1] 2762 /// ldr rT2, [r0] 2763 /// blx rT2 2764 /// [...address now in r0...] 2765 SDValue 2766 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2767 SelectionDAG &DAG) const { 2768 assert(Subtarget->isTargetDarwin() && 2769 "This function expects a Darwin target"); 2770 SDLoc DL(Op); 2771 2772 // First step is to get the address of the actua global symbol. This is where 2773 // the TLS descriptor lives. 2774 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2775 2776 // The first entry in the descriptor is a function pointer that we must call 2777 // to obtain the address of the variable. 2778 SDValue Chain = DAG.getEntryNode(); 2779 SDValue FuncTLVGet = DAG.getLoad( 2780 MVT::i32, DL, Chain, DescAddr, 2781 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2782 /* Alignment = */ 4, 2783 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2784 MachineMemOperand::MOInvariant); 2785 Chain = FuncTLVGet.getValue(1); 2786 2787 MachineFunction &F = DAG.getMachineFunction(); 2788 MachineFrameInfo &MFI = F.getFrameInfo(); 2789 MFI.setAdjustsStack(true); 2790 2791 // TLS calls preserve all registers except those that absolutely must be 2792 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2793 // silly). 2794 auto TRI = 2795 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2796 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2797 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2798 2799 // Finally, we can make the call. This is just a degenerate version of a 2800 // normal AArch64 call node: r0 takes the address of the descriptor, and 2801 // returns the address of the variable in this thread. 2802 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2803 Chain = 2804 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2805 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2806 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2807 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2808 } 2809 2810 SDValue 2811 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2812 SelectionDAG &DAG) const { 2813 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2814 2815 SDValue Chain = DAG.getEntryNode(); 2816 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2817 SDLoc DL(Op); 2818 2819 // Load the current TEB (thread environment block) 2820 SDValue Ops[] = {Chain, 2821 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2822 DAG.getConstant(15, DL, MVT::i32), 2823 DAG.getConstant(0, DL, MVT::i32), 2824 DAG.getConstant(13, DL, MVT::i32), 2825 DAG.getConstant(0, DL, MVT::i32), 2826 DAG.getConstant(2, DL, MVT::i32)}; 2827 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2828 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2829 2830 SDValue TEB = CurrentTEB.getValue(0); 2831 Chain = CurrentTEB.getValue(1); 2832 2833 // Load the ThreadLocalStoragePointer from the TEB 2834 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2835 SDValue TLSArray = 2836 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2837 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2838 2839 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2840 // offset into the TLSArray. 2841 2842 // Load the TLS index from the C runtime 2843 SDValue TLSIndex = 2844 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2845 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2846 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2847 2848 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2849 DAG.getConstant(2, DL, MVT::i32)); 2850 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2851 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2852 MachinePointerInfo()); 2853 2854 // Get the offset of the start of the .tls section (section base) 2855 const auto *GA = cast<GlobalAddressSDNode>(Op); 2856 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2857 SDValue Offset = DAG.getLoad( 2858 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2859 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2860 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2861 2862 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2863 } 2864 2865 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2866 SDValue 2867 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2868 SelectionDAG &DAG) const { 2869 SDLoc dl(GA); 2870 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2871 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2872 MachineFunction &MF = DAG.getMachineFunction(); 2873 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2874 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2875 ARMConstantPoolValue *CPV = 2876 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2877 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2878 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2879 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2880 Argument = DAG.getLoad( 2881 PtrVT, dl, DAG.getEntryNode(), Argument, 2882 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2883 SDValue Chain = Argument.getValue(1); 2884 2885 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2886 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2887 2888 // call __tls_get_addr. 2889 ArgListTy Args; 2890 ArgListEntry Entry; 2891 Entry.Node = Argument; 2892 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2893 Args.push_back(Entry); 2894 2895 // FIXME: is there useful debug info available here? 2896 TargetLowering::CallLoweringInfo CLI(DAG); 2897 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2898 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2899 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2900 2901 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2902 return CallResult.first; 2903 } 2904 2905 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2906 // "local exec" model. 2907 SDValue 2908 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2909 SelectionDAG &DAG, 2910 TLSModel::Model model) const { 2911 const GlobalValue *GV = GA->getGlobal(); 2912 SDLoc dl(GA); 2913 SDValue Offset; 2914 SDValue Chain = DAG.getEntryNode(); 2915 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2916 // Get the Thread Pointer 2917 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2918 2919 if (model == TLSModel::InitialExec) { 2920 MachineFunction &MF = DAG.getMachineFunction(); 2921 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2922 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2923 // Initial exec model. 2924 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2925 ARMConstantPoolValue *CPV = 2926 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2927 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2928 true); 2929 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2930 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2931 Offset = DAG.getLoad( 2932 PtrVT, dl, Chain, Offset, 2933 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2934 Chain = Offset.getValue(1); 2935 2936 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2937 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2938 2939 Offset = DAG.getLoad( 2940 PtrVT, dl, Chain, Offset, 2941 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2942 } else { 2943 // local exec model 2944 assert(model == TLSModel::LocalExec); 2945 ARMConstantPoolValue *CPV = 2946 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2947 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2948 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2949 Offset = DAG.getLoad( 2950 PtrVT, dl, Chain, Offset, 2951 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2952 } 2953 2954 // The address of the thread local variable is the add of the thread 2955 // pointer with the offset of the variable. 2956 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2957 } 2958 2959 SDValue 2960 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2961 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2962 if (DAG.getTarget().Options.EmulatedTLS) 2963 return LowerToTLSEmulatedModel(GA, DAG); 2964 2965 if (Subtarget->isTargetDarwin()) 2966 return LowerGlobalTLSAddressDarwin(Op, DAG); 2967 2968 if (Subtarget->isTargetWindows()) 2969 return LowerGlobalTLSAddressWindows(Op, DAG); 2970 2971 // TODO: implement the "local dynamic" model 2972 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2973 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2974 2975 switch (model) { 2976 case TLSModel::GeneralDynamic: 2977 case TLSModel::LocalDynamic: 2978 return LowerToTLSGeneralDynamicModel(GA, DAG); 2979 case TLSModel::InitialExec: 2980 case TLSModel::LocalExec: 2981 return LowerToTLSExecModels(GA, DAG, model); 2982 } 2983 llvm_unreachable("bogus TLS model"); 2984 } 2985 2986 /// Return true if all users of V are within function F, looking through 2987 /// ConstantExprs. 2988 static bool allUsersAreInFunction(const Value *V, const Function *F) { 2989 SmallVector<const User*,4> Worklist; 2990 for (auto *U : V->users()) 2991 Worklist.push_back(U); 2992 while (!Worklist.empty()) { 2993 auto *U = Worklist.pop_back_val(); 2994 if (isa<ConstantExpr>(U)) { 2995 for (auto *UU : U->users()) 2996 Worklist.push_back(UU); 2997 continue; 2998 } 2999 3000 auto *I = dyn_cast<Instruction>(U); 3001 if (!I || I->getParent()->getParent() != F) 3002 return false; 3003 } 3004 return true; 3005 } 3006 3007 /// Return true if all users of V are within some (any) function, looking through 3008 /// ConstantExprs. In other words, are there any global constant users? 3009 static bool allUsersAreInFunctions(const Value *V) { 3010 SmallVector<const User*,4> Worklist; 3011 for (auto *U : V->users()) 3012 Worklist.push_back(U); 3013 while (!Worklist.empty()) { 3014 auto *U = Worklist.pop_back_val(); 3015 if (isa<ConstantExpr>(U)) { 3016 for (auto *UU : U->users()) 3017 Worklist.push_back(UU); 3018 continue; 3019 } 3020 3021 if (!isa<Instruction>(U)) 3022 return false; 3023 } 3024 return true; 3025 } 3026 3027 // Return true if T is an integer, float or an array/vector of either. 3028 static bool isSimpleType(Type *T) { 3029 if (T->isIntegerTy() || T->isFloatingPointTy()) 3030 return true; 3031 Type *SubT = nullptr; 3032 if (T->isArrayTy()) 3033 SubT = T->getArrayElementType(); 3034 else if (T->isVectorTy()) 3035 SubT = T->getVectorElementType(); 3036 else 3037 return false; 3038 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3039 } 3040 3041 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3042 EVT PtrVT, const SDLoc &dl) { 3043 // If we're creating a pool entry for a constant global with unnamed address, 3044 // and the global is small enough, we can emit it inline into the constant pool 3045 // to save ourselves an indirection. 3046 // 3047 // This is a win if the constant is only used in one function (so it doesn't 3048 // need to be duplicated) or duplicating the constant wouldn't increase code 3049 // size (implying the constant is no larger than 4 bytes). 3050 const Function &F = DAG.getMachineFunction().getFunction(); 3051 3052 // We rely on this decision to inline being idemopotent and unrelated to the 3053 // use-site. We know that if we inline a variable at one use site, we'll 3054 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3055 // doesn't know about this optimization, so bail out if it's enabled else 3056 // we could decide to inline here (and thus never emit the GV) but require 3057 // the GV from fast-isel generated code. 3058 if (!EnableConstpoolPromotion || 3059 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3060 return SDValue(); 3061 3062 auto *GVar = dyn_cast<GlobalVariable>(GV); 3063 if (!GVar || !GVar->hasInitializer() || 3064 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3065 !GVar->hasLocalLinkage()) 3066 return SDValue(); 3067 3068 // Ensure that we don't try and inline any type that contains pointers. If 3069 // we inline a value that contains relocations, we move the relocations from 3070 // .data to .text which is not ideal. 3071 auto *Init = GVar->getInitializer(); 3072 if (!isSimpleType(Init->getType())) 3073 return SDValue(); 3074 3075 // The constant islands pass can only really deal with alignment requests 3076 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3077 // any type wanting greater alignment requirements than 4 bytes. We also 3078 // can only promote constants that are multiples of 4 bytes in size or 3079 // are paddable to a multiple of 4. Currently we only try and pad constants 3080 // that are strings for simplicity. 3081 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3082 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3083 unsigned Align = GVar->getAlignment(); 3084 unsigned RequiredPadding = 4 - (Size % 4); 3085 bool PaddingPossible = 3086 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3087 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3088 Size == 0) 3089 return SDValue(); 3090 3091 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3092 MachineFunction &MF = DAG.getMachineFunction(); 3093 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3094 3095 // We can't bloat the constant pool too much, else the ConstantIslands pass 3096 // may fail to converge. If we haven't promoted this global yet (it may have 3097 // multiple uses), and promoting it would increase the constant pool size (Sz 3098 // > 4), ensure we have space to do so up to MaxTotal. 3099 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3100 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3101 ConstpoolPromotionMaxTotal) 3102 return SDValue(); 3103 3104 // This is only valid if all users are in a single function OR it has users 3105 // in multiple functions but it no larger than a pointer. We also check if 3106 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3107 // address taken. 3108 if (!allUsersAreInFunction(GVar, &F) && 3109 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3110 return SDValue(); 3111 3112 // We're going to inline this global. Pad it out if needed. 3113 if (RequiredPadding != 4) { 3114 StringRef S = CDAInit->getAsString(); 3115 3116 SmallVector<uint8_t,16> V(S.size()); 3117 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3118 while (RequiredPadding--) 3119 V.push_back(0); 3120 Init = ConstantDataArray::get(*DAG.getContext(), V); 3121 } 3122 3123 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3124 SDValue CPAddr = 3125 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3126 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3127 AFI->markGlobalAsPromotedToConstantPool(GVar); 3128 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3129 PaddedSize - 4); 3130 } 3131 ++NumConstpoolPromoted; 3132 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3133 } 3134 3135 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3136 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3137 GV = GA->getBaseObject(); 3138 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3139 isa<Function>(GV); 3140 } 3141 3142 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3143 SelectionDAG &DAG) const { 3144 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3145 default: llvm_unreachable("unknown object format"); 3146 case Triple::COFF: 3147 return LowerGlobalAddressWindows(Op, DAG); 3148 case Triple::ELF: 3149 return LowerGlobalAddressELF(Op, DAG); 3150 case Triple::MachO: 3151 return LowerGlobalAddressDarwin(Op, DAG); 3152 } 3153 } 3154 3155 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3156 SelectionDAG &DAG) const { 3157 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3158 SDLoc dl(Op); 3159 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3160 const TargetMachine &TM = getTargetMachine(); 3161 bool IsRO = isReadOnly(GV); 3162 3163 // promoteToConstantPool only if not generating XO text section 3164 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3165 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3166 return V; 3167 3168 if (isPositionIndependent()) { 3169 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3170 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3171 UseGOT_PREL ? ARMII::MO_GOT : 0); 3172 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3173 if (UseGOT_PREL) 3174 Result = 3175 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3176 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3177 return Result; 3178 } else if (Subtarget->isROPI() && IsRO) { 3179 // PC-relative. 3180 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3181 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3182 return Result; 3183 } else if (Subtarget->isRWPI() && !IsRO) { 3184 // SB-relative. 3185 SDValue RelAddr; 3186 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3187 ++NumMovwMovt; 3188 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3189 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3190 } else { // use literal pool for address constant 3191 ARMConstantPoolValue *CPV = 3192 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3193 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3194 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3195 RelAddr = DAG.getLoad( 3196 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3197 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3198 } 3199 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3200 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3201 return Result; 3202 } 3203 3204 // If we have T2 ops, we can materialize the address directly via movt/movw 3205 // pair. This is always cheaper. 3206 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3207 ++NumMovwMovt; 3208 // FIXME: Once remat is capable of dealing with instructions with register 3209 // operands, expand this into two nodes. 3210 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3211 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3212 } else { 3213 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3214 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3215 return DAG.getLoad( 3216 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3217 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3218 } 3219 } 3220 3221 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3222 SelectionDAG &DAG) const { 3223 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3224 "ROPI/RWPI not currently supported for Darwin"); 3225 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3226 SDLoc dl(Op); 3227 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3228 3229 if (Subtarget->useMovt(DAG.getMachineFunction())) 3230 ++NumMovwMovt; 3231 3232 // FIXME: Once remat is capable of dealing with instructions with register 3233 // operands, expand this into multiple nodes 3234 unsigned Wrapper = 3235 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3236 3237 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3238 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3239 3240 if (Subtarget->isGVIndirectSymbol(GV)) 3241 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3242 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3243 return Result; 3244 } 3245 3246 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3247 SelectionDAG &DAG) const { 3248 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3249 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3250 "Windows on ARM expects to use movw/movt"); 3251 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3252 "ROPI/RWPI not currently supported for Windows"); 3253 3254 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3255 const ARMII::TOF TargetFlags = 3256 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3257 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3258 SDValue Result; 3259 SDLoc DL(Op); 3260 3261 ++NumMovwMovt; 3262 3263 // FIXME: Once remat is capable of dealing with instructions with register 3264 // operands, expand this into two nodes. 3265 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3266 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3267 TargetFlags)); 3268 if (GV->hasDLLImportStorageClass()) 3269 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3270 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3271 return Result; 3272 } 3273 3274 SDValue 3275 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3276 SDLoc dl(Op); 3277 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3278 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3279 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3280 Op.getOperand(1), Val); 3281 } 3282 3283 SDValue 3284 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3285 SDLoc dl(Op); 3286 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3287 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3288 } 3289 3290 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3291 SelectionDAG &DAG) const { 3292 SDLoc dl(Op); 3293 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3294 Op.getOperand(0)); 3295 } 3296 3297 SDValue 3298 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3299 const ARMSubtarget *Subtarget) const { 3300 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3301 SDLoc dl(Op); 3302 switch (IntNo) { 3303 default: return SDValue(); // Don't custom lower most intrinsics. 3304 case Intrinsic::thread_pointer: { 3305 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3306 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3307 } 3308 case Intrinsic::eh_sjlj_lsda: { 3309 MachineFunction &MF = DAG.getMachineFunction(); 3310 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3311 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3312 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3313 SDValue CPAddr; 3314 bool IsPositionIndependent = isPositionIndependent(); 3315 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3316 ARMConstantPoolValue *CPV = 3317 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3318 ARMCP::CPLSDA, PCAdj); 3319 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3320 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3321 SDValue Result = DAG.getLoad( 3322 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3323 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3324 3325 if (IsPositionIndependent) { 3326 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3327 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3328 } 3329 return Result; 3330 } 3331 case Intrinsic::arm_neon_vabs: 3332 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3333 Op.getOperand(1)); 3334 case Intrinsic::arm_neon_vmulls: 3335 case Intrinsic::arm_neon_vmullu: { 3336 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3337 ? ARMISD::VMULLs : ARMISD::VMULLu; 3338 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3339 Op.getOperand(1), Op.getOperand(2)); 3340 } 3341 case Intrinsic::arm_neon_vminnm: 3342 case Intrinsic::arm_neon_vmaxnm: { 3343 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3344 ? ISD::FMINNUM : ISD::FMAXNUM; 3345 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3346 Op.getOperand(1), Op.getOperand(2)); 3347 } 3348 case Intrinsic::arm_neon_vminu: 3349 case Intrinsic::arm_neon_vmaxu: { 3350 if (Op.getValueType().isFloatingPoint()) 3351 return SDValue(); 3352 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3353 ? ISD::UMIN : ISD::UMAX; 3354 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3355 Op.getOperand(1), Op.getOperand(2)); 3356 } 3357 case Intrinsic::arm_neon_vmins: 3358 case Intrinsic::arm_neon_vmaxs: { 3359 // v{min,max}s is overloaded between signed integers and floats. 3360 if (!Op.getValueType().isFloatingPoint()) { 3361 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3362 ? ISD::SMIN : ISD::SMAX; 3363 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3364 Op.getOperand(1), Op.getOperand(2)); 3365 } 3366 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3367 ? ISD::FMINNAN : ISD::FMAXNAN; 3368 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3369 Op.getOperand(1), Op.getOperand(2)); 3370 } 3371 case Intrinsic::arm_neon_vtbl1: 3372 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3373 Op.getOperand(1), Op.getOperand(2)); 3374 case Intrinsic::arm_neon_vtbl2: 3375 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3376 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3377 } 3378 } 3379 3380 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3381 const ARMSubtarget *Subtarget) { 3382 SDLoc dl(Op); 3383 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3384 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3385 if (SSID == SyncScope::SingleThread) 3386 return Op; 3387 3388 if (!Subtarget->hasDataBarrier()) { 3389 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3390 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3391 // here. 3392 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3393 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3394 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3395 DAG.getConstant(0, dl, MVT::i32)); 3396 } 3397 3398 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3399 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3400 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3401 if (Subtarget->isMClass()) { 3402 // Only a full system barrier exists in the M-class architectures. 3403 Domain = ARM_MB::SY; 3404 } else if (Subtarget->preferISHSTBarriers() && 3405 Ord == AtomicOrdering::Release) { 3406 // Swift happens to implement ISHST barriers in a way that's compatible with 3407 // Release semantics but weaker than ISH so we'd be fools not to use 3408 // it. Beware: other processors probably don't! 3409 Domain = ARM_MB::ISHST; 3410 } 3411 3412 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3413 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3414 DAG.getConstant(Domain, dl, MVT::i32)); 3415 } 3416 3417 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3418 const ARMSubtarget *Subtarget) { 3419 // ARM pre v5TE and Thumb1 does not have preload instructions. 3420 if (!(Subtarget->isThumb2() || 3421 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3422 // Just preserve the chain. 3423 return Op.getOperand(0); 3424 3425 SDLoc dl(Op); 3426 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3427 if (!isRead && 3428 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3429 // ARMv7 with MP extension has PLDW. 3430 return Op.getOperand(0); 3431 3432 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3433 if (Subtarget->isThumb()) { 3434 // Invert the bits. 3435 isRead = ~isRead & 1; 3436 isData = ~isData & 1; 3437 } 3438 3439 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3440 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3441 DAG.getConstant(isData, dl, MVT::i32)); 3442 } 3443 3444 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3445 MachineFunction &MF = DAG.getMachineFunction(); 3446 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3447 3448 // vastart just stores the address of the VarArgsFrameIndex slot into the 3449 // memory location argument. 3450 SDLoc dl(Op); 3451 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3452 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3453 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3454 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3455 MachinePointerInfo(SV)); 3456 } 3457 3458 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3459 CCValAssign &NextVA, 3460 SDValue &Root, 3461 SelectionDAG &DAG, 3462 const SDLoc &dl) const { 3463 MachineFunction &MF = DAG.getMachineFunction(); 3464 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3465 3466 const TargetRegisterClass *RC; 3467 if (AFI->isThumb1OnlyFunction()) 3468 RC = &ARM::tGPRRegClass; 3469 else 3470 RC = &ARM::GPRRegClass; 3471 3472 // Transform the arguments stored in physical registers into virtual ones. 3473 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3474 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3475 3476 SDValue ArgValue2; 3477 if (NextVA.isMemLoc()) { 3478 MachineFrameInfo &MFI = MF.getFrameInfo(); 3479 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3480 3481 // Create load node to retrieve arguments from the stack. 3482 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3483 ArgValue2 = DAG.getLoad( 3484 MVT::i32, dl, Root, FIN, 3485 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3486 } else { 3487 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3488 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3489 } 3490 if (!Subtarget->isLittle()) 3491 std::swap (ArgValue, ArgValue2); 3492 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3493 } 3494 3495 // The remaining GPRs hold either the beginning of variable-argument 3496 // data, or the beginning of an aggregate passed by value (usually 3497 // byval). Either way, we allocate stack slots adjacent to the data 3498 // provided by our caller, and store the unallocated registers there. 3499 // If this is a variadic function, the va_list pointer will begin with 3500 // these values; otherwise, this reassembles a (byval) structure that 3501 // was split between registers and memory. 3502 // Return: The frame index registers were stored into. 3503 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3504 const SDLoc &dl, SDValue &Chain, 3505 const Value *OrigArg, 3506 unsigned InRegsParamRecordIdx, 3507 int ArgOffset, unsigned ArgSize) const { 3508 // Currently, two use-cases possible: 3509 // Case #1. Non-var-args function, and we meet first byval parameter. 3510 // Setup first unallocated register as first byval register; 3511 // eat all remained registers 3512 // (these two actions are performed by HandleByVal method). 3513 // Then, here, we initialize stack frame with 3514 // "store-reg" instructions. 3515 // Case #2. Var-args function, that doesn't contain byval parameters. 3516 // The same: eat all remained unallocated registers, 3517 // initialize stack frame. 3518 3519 MachineFunction &MF = DAG.getMachineFunction(); 3520 MachineFrameInfo &MFI = MF.getFrameInfo(); 3521 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3522 unsigned RBegin, REnd; 3523 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3524 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3525 } else { 3526 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3527 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3528 REnd = ARM::R4; 3529 } 3530 3531 if (REnd != RBegin) 3532 ArgOffset = -4 * (ARM::R4 - RBegin); 3533 3534 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3535 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3536 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3537 3538 SmallVector<SDValue, 4> MemOps; 3539 const TargetRegisterClass *RC = 3540 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3541 3542 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3543 unsigned VReg = MF.addLiveIn(Reg, RC); 3544 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3545 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3546 MachinePointerInfo(OrigArg, 4 * i)); 3547 MemOps.push_back(Store); 3548 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3549 } 3550 3551 if (!MemOps.empty()) 3552 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3553 return FrameIndex; 3554 } 3555 3556 // Setup stack frame, the va_list pointer will start from. 3557 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3558 const SDLoc &dl, SDValue &Chain, 3559 unsigned ArgOffset, 3560 unsigned TotalArgRegsSaveSize, 3561 bool ForceMutable) const { 3562 MachineFunction &MF = DAG.getMachineFunction(); 3563 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3564 3565 // Try to store any remaining integer argument regs 3566 // to their spots on the stack so that they may be loaded by dereferencing 3567 // the result of va_next. 3568 // If there is no regs to be stored, just point address after last 3569 // argument passed via stack. 3570 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3571 CCInfo.getInRegsParamsCount(), 3572 CCInfo.getNextStackOffset(), 4); 3573 AFI->setVarArgsFrameIndex(FrameIndex); 3574 } 3575 3576 SDValue ARMTargetLowering::LowerFormalArguments( 3577 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3578 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3579 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3580 MachineFunction &MF = DAG.getMachineFunction(); 3581 MachineFrameInfo &MFI = MF.getFrameInfo(); 3582 3583 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3584 3585 // Assign locations to all of the incoming arguments. 3586 SmallVector<CCValAssign, 16> ArgLocs; 3587 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3588 *DAG.getContext()); 3589 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3590 3591 SmallVector<SDValue, 16> ArgValues; 3592 SDValue ArgValue; 3593 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3594 unsigned CurArgIdx = 0; 3595 3596 // Initially ArgRegsSaveSize is zero. 3597 // Then we increase this value each time we meet byval parameter. 3598 // We also increase this value in case of varargs function. 3599 AFI->setArgRegsSaveSize(0); 3600 3601 // Calculate the amount of stack space that we need to allocate to store 3602 // byval and variadic arguments that are passed in registers. 3603 // We need to know this before we allocate the first byval or variadic 3604 // argument, as they will be allocated a stack slot below the CFA (Canonical 3605 // Frame Address, the stack pointer at entry to the function). 3606 unsigned ArgRegBegin = ARM::R4; 3607 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3608 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3609 break; 3610 3611 CCValAssign &VA = ArgLocs[i]; 3612 unsigned Index = VA.getValNo(); 3613 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3614 if (!Flags.isByVal()) 3615 continue; 3616 3617 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3618 unsigned RBegin, REnd; 3619 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3620 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3621 3622 CCInfo.nextInRegsParam(); 3623 } 3624 CCInfo.rewindByValRegsInfo(); 3625 3626 int lastInsIndex = -1; 3627 if (isVarArg && MFI.hasVAStart()) { 3628 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3629 if (RegIdx != array_lengthof(GPRArgRegs)) 3630 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3631 } 3632 3633 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3634 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3635 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3636 3637 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3638 CCValAssign &VA = ArgLocs[i]; 3639 if (Ins[VA.getValNo()].isOrigArg()) { 3640 std::advance(CurOrigArg, 3641 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3642 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3643 } 3644 // Arguments stored in registers. 3645 if (VA.isRegLoc()) { 3646 EVT RegVT = VA.getLocVT(); 3647 3648 if (VA.needsCustom()) { 3649 // f64 and vector types are split up into multiple registers or 3650 // combinations of registers and stack slots. 3651 if (VA.getLocVT() == MVT::v2f64) { 3652 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3653 Chain, DAG, dl); 3654 VA = ArgLocs[++i]; // skip ahead to next loc 3655 SDValue ArgValue2; 3656 if (VA.isMemLoc()) { 3657 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3658 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3659 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3660 MachinePointerInfo::getFixedStack( 3661 DAG.getMachineFunction(), FI)); 3662 } else { 3663 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3664 Chain, DAG, dl); 3665 } 3666 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3667 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3668 ArgValue, ArgValue1, 3669 DAG.getIntPtrConstant(0, dl)); 3670 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3671 ArgValue, ArgValue2, 3672 DAG.getIntPtrConstant(1, dl)); 3673 } else 3674 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3675 } else { 3676 const TargetRegisterClass *RC; 3677 3678 if (RegVT == MVT::f32) 3679 RC = &ARM::SPRRegClass; 3680 else if (RegVT == MVT::f64) 3681 RC = &ARM::DPRRegClass; 3682 else if (RegVT == MVT::v2f64) 3683 RC = &ARM::QPRRegClass; 3684 else if (RegVT == MVT::i32) 3685 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3686 : &ARM::GPRRegClass; 3687 else 3688 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3689 3690 // Transform the arguments in physical registers into virtual ones. 3691 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3692 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3693 } 3694 3695 // If this is an 8 or 16-bit value, it is really passed promoted 3696 // to 32 bits. Insert an assert[sz]ext to capture this, then 3697 // truncate to the right size. 3698 switch (VA.getLocInfo()) { 3699 default: llvm_unreachable("Unknown loc info!"); 3700 case CCValAssign::Full: break; 3701 case CCValAssign::BCvt: 3702 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3703 break; 3704 case CCValAssign::SExt: 3705 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3706 DAG.getValueType(VA.getValVT())); 3707 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3708 break; 3709 case CCValAssign::ZExt: 3710 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3711 DAG.getValueType(VA.getValVT())); 3712 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3713 break; 3714 } 3715 3716 InVals.push_back(ArgValue); 3717 } else { // VA.isRegLoc() 3718 // sanity check 3719 assert(VA.isMemLoc()); 3720 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3721 3722 int index = VA.getValNo(); 3723 3724 // Some Ins[] entries become multiple ArgLoc[] entries. 3725 // Process them only once. 3726 if (index != lastInsIndex) 3727 { 3728 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3729 // FIXME: For now, all byval parameter objects are marked mutable. 3730 // This can be changed with more analysis. 3731 // In case of tail call optimization mark all arguments mutable. 3732 // Since they could be overwritten by lowering of arguments in case of 3733 // a tail call. 3734 if (Flags.isByVal()) { 3735 assert(Ins[index].isOrigArg() && 3736 "Byval arguments cannot be implicit"); 3737 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3738 3739 int FrameIndex = StoreByValRegs( 3740 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3741 VA.getLocMemOffset(), Flags.getByValSize()); 3742 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3743 CCInfo.nextInRegsParam(); 3744 } else { 3745 unsigned FIOffset = VA.getLocMemOffset(); 3746 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3747 FIOffset, true); 3748 3749 // Create load nodes to retrieve arguments from the stack. 3750 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3751 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3752 MachinePointerInfo::getFixedStack( 3753 DAG.getMachineFunction(), FI))); 3754 } 3755 lastInsIndex = index; 3756 } 3757 } 3758 } 3759 3760 // varargs 3761 if (isVarArg && MFI.hasVAStart()) 3762 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3763 CCInfo.getNextStackOffset(), 3764 TotalArgRegsSaveSize); 3765 3766 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3767 3768 return Chain; 3769 } 3770 3771 /// isFloatingPointZero - Return true if this is +0.0. 3772 static bool isFloatingPointZero(SDValue Op) { 3773 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3774 return CFP->getValueAPF().isPosZero(); 3775 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3776 // Maybe this has already been legalized into the constant pool? 3777 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3778 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3779 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3780 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3781 return CFP->getValueAPF().isPosZero(); 3782 } 3783 } else if (Op->getOpcode() == ISD::BITCAST && 3784 Op->getValueType(0) == MVT::f64) { 3785 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3786 // created by LowerConstantFP(). 3787 SDValue BitcastOp = Op->getOperand(0); 3788 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3789 isNullConstant(BitcastOp->getOperand(0))) 3790 return true; 3791 } 3792 return false; 3793 } 3794 3795 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3796 /// the given operands. 3797 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3798 SDValue &ARMcc, SelectionDAG &DAG, 3799 const SDLoc &dl) const { 3800 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3801 unsigned C = RHSC->getZExtValue(); 3802 if (!isLegalICmpImmediate(C)) { 3803 // Constant does not fit, try adjusting it by one? 3804 switch (CC) { 3805 default: break; 3806 case ISD::SETLT: 3807 case ISD::SETGE: 3808 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3809 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3810 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3811 } 3812 break; 3813 case ISD::SETULT: 3814 case ISD::SETUGE: 3815 if (C != 0 && isLegalICmpImmediate(C-1)) { 3816 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3817 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3818 } 3819 break; 3820 case ISD::SETLE: 3821 case ISD::SETGT: 3822 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3823 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3824 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3825 } 3826 break; 3827 case ISD::SETULE: 3828 case ISD::SETUGT: 3829 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3830 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3831 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3832 } 3833 break; 3834 } 3835 } 3836 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3837 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3838 // In ARM and Thumb-2, the compare instructions can shift their second 3839 // operand. 3840 CC = ISD::getSetCCSwappedOperands(CC); 3841 std::swap(LHS, RHS); 3842 } 3843 3844 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3845 ARMISD::NodeType CompareType; 3846 switch (CondCode) { 3847 default: 3848 CompareType = ARMISD::CMP; 3849 break; 3850 case ARMCC::EQ: 3851 case ARMCC::NE: 3852 // Uses only Z Flag 3853 CompareType = ARMISD::CMPZ; 3854 break; 3855 } 3856 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3857 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3858 } 3859 3860 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3861 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3862 SelectionDAG &DAG, const SDLoc &dl, 3863 bool InvalidOnQNaN) const { 3864 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3865 SDValue Cmp; 3866 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3867 if (!isFloatingPointZero(RHS)) 3868 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3869 else 3870 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3871 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3872 } 3873 3874 /// duplicateCmp - Glue values can have only one use, so this function 3875 /// duplicates a comparison node. 3876 SDValue 3877 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3878 unsigned Opc = Cmp.getOpcode(); 3879 SDLoc DL(Cmp); 3880 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3881 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3882 3883 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3884 Cmp = Cmp.getOperand(0); 3885 Opc = Cmp.getOpcode(); 3886 if (Opc == ARMISD::CMPFP) 3887 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3888 Cmp.getOperand(1), Cmp.getOperand(2)); 3889 else { 3890 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3891 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3892 Cmp.getOperand(1)); 3893 } 3894 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3895 } 3896 3897 // This function returns three things: the arithmetic computation itself 3898 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 3899 // comparison and the condition code define the case in which the arithmetic 3900 // computation *does not* overflow. 3901 std::pair<SDValue, SDValue> 3902 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3903 SDValue &ARMcc) const { 3904 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3905 3906 SDValue Value, OverflowCmp; 3907 SDValue LHS = Op.getOperand(0); 3908 SDValue RHS = Op.getOperand(1); 3909 SDLoc dl(Op); 3910 3911 // FIXME: We are currently always generating CMPs because we don't support 3912 // generating CMN through the backend. This is not as good as the natural 3913 // CMP case because it causes a register dependency and cannot be folded 3914 // later. 3915 3916 switch (Op.getOpcode()) { 3917 default: 3918 llvm_unreachable("Unknown overflow instruction!"); 3919 case ISD::SADDO: 3920 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3921 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3922 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3923 break; 3924 case ISD::UADDO: 3925 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3926 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 3927 // We do not use it in the USUBO case as Value may not be used. 3928 Value = DAG.getNode(ARMISD::ADDC, dl, 3929 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 3930 .getValue(0); 3931 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3932 break; 3933 case ISD::SSUBO: 3934 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3935 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3936 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3937 break; 3938 case ISD::USUBO: 3939 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3940 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3941 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3942 break; 3943 } // switch (...) 3944 3945 return std::make_pair(Value, OverflowCmp); 3946 } 3947 3948 SDValue 3949 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 3950 // Let legalize expand this if it isn't a legal type yet. 3951 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3952 return SDValue(); 3953 3954 SDValue Value, OverflowCmp; 3955 SDValue ARMcc; 3956 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3957 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3958 SDLoc dl(Op); 3959 // We use 0 and 1 as false and true values. 3960 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3961 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3962 EVT VT = Op.getValueType(); 3963 3964 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3965 ARMcc, CCR, OverflowCmp); 3966 3967 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3968 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3969 } 3970 3971 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 3972 SelectionDAG &DAG) { 3973 SDLoc DL(BoolCarry); 3974 EVT CarryVT = BoolCarry.getValueType(); 3975 3976 APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits()); 3977 // This converts the boolean value carry into the carry flag by doing 3978 // ARMISD::ADDC Carry, ~0 3979 return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32), 3980 BoolCarry, DAG.getConstant(NegOne, DL, CarryVT)); 3981 } 3982 3983 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 3984 SelectionDAG &DAG) { 3985 SDLoc DL(Flags); 3986 3987 // Now convert the carry flag into a boolean carry. We do this 3988 // using ARMISD:ADDE 0, 0, Carry 3989 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 3990 DAG.getConstant(0, DL, MVT::i32), 3991 DAG.getConstant(0, DL, MVT::i32), Flags); 3992 } 3993 3994 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 3995 SelectionDAG &DAG) const { 3996 // Let legalize expand this if it isn't a legal type yet. 3997 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3998 return SDValue(); 3999 4000 SDValue LHS = Op.getOperand(0); 4001 SDValue RHS = Op.getOperand(1); 4002 SDLoc dl(Op); 4003 4004 EVT VT = Op.getValueType(); 4005 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4006 SDValue Value; 4007 SDValue Overflow; 4008 switch (Op.getOpcode()) { 4009 default: 4010 llvm_unreachable("Unknown overflow instruction!"); 4011 case ISD::UADDO: 4012 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4013 // Convert the carry flag into a boolean value. 4014 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4015 break; 4016 case ISD::USUBO: { 4017 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4018 // Convert the carry flag into a boolean value. 4019 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4020 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4021 // value. So compute 1 - C. 4022 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4023 DAG.getConstant(1, dl, MVT::i32), Overflow); 4024 break; 4025 } 4026 } 4027 4028 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4029 } 4030 4031 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4032 SDValue Cond = Op.getOperand(0); 4033 SDValue SelectTrue = Op.getOperand(1); 4034 SDValue SelectFalse = Op.getOperand(2); 4035 SDLoc dl(Op); 4036 unsigned Opc = Cond.getOpcode(); 4037 4038 if (Cond.getResNo() == 1 && 4039 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4040 Opc == ISD::USUBO)) { 4041 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4042 return SDValue(); 4043 4044 SDValue Value, OverflowCmp; 4045 SDValue ARMcc; 4046 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4047 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4048 EVT VT = Op.getValueType(); 4049 4050 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4051 OverflowCmp, DAG); 4052 } 4053 4054 // Convert: 4055 // 4056 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4057 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4058 // 4059 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4060 const ConstantSDNode *CMOVTrue = 4061 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4062 const ConstantSDNode *CMOVFalse = 4063 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4064 4065 if (CMOVTrue && CMOVFalse) { 4066 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4067 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4068 4069 SDValue True; 4070 SDValue False; 4071 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4072 True = SelectTrue; 4073 False = SelectFalse; 4074 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4075 True = SelectFalse; 4076 False = SelectTrue; 4077 } 4078 4079 if (True.getNode() && False.getNode()) { 4080 EVT VT = Op.getValueType(); 4081 SDValue ARMcc = Cond.getOperand(2); 4082 SDValue CCR = Cond.getOperand(3); 4083 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4084 assert(True.getValueType() == VT); 4085 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4086 } 4087 } 4088 } 4089 4090 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4091 // undefined bits before doing a full-word comparison with zero. 4092 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4093 DAG.getConstant(1, dl, Cond.getValueType())); 4094 4095 return DAG.getSelectCC(dl, Cond, 4096 DAG.getConstant(0, dl, Cond.getValueType()), 4097 SelectTrue, SelectFalse, ISD::SETNE); 4098 } 4099 4100 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4101 bool &swpCmpOps, bool &swpVselOps) { 4102 // Start by selecting the GE condition code for opcodes that return true for 4103 // 'equality' 4104 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4105 CC == ISD::SETULE) 4106 CondCode = ARMCC::GE; 4107 4108 // and GT for opcodes that return false for 'equality'. 4109 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4110 CC == ISD::SETULT) 4111 CondCode = ARMCC::GT; 4112 4113 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4114 // to swap the compare operands. 4115 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4116 CC == ISD::SETULT) 4117 swpCmpOps = true; 4118 4119 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4120 // If we have an unordered opcode, we need to swap the operands to the VSEL 4121 // instruction (effectively negating the condition). 4122 // 4123 // This also has the effect of swapping which one of 'less' or 'greater' 4124 // returns true, so we also swap the compare operands. It also switches 4125 // whether we return true for 'equality', so we compensate by picking the 4126 // opposite condition code to our original choice. 4127 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4128 CC == ISD::SETUGT) { 4129 swpCmpOps = !swpCmpOps; 4130 swpVselOps = !swpVselOps; 4131 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4132 } 4133 4134 // 'ordered' is 'anything but unordered', so use the VS condition code and 4135 // swap the VSEL operands. 4136 if (CC == ISD::SETO) { 4137 CondCode = ARMCC::VS; 4138 swpVselOps = true; 4139 } 4140 4141 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4142 // code and swap the VSEL operands. 4143 if (CC == ISD::SETUNE) { 4144 CondCode = ARMCC::EQ; 4145 swpVselOps = true; 4146 } 4147 } 4148 4149 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4150 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4151 SDValue Cmp, SelectionDAG &DAG) const { 4152 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4153 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4154 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4155 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4156 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4157 4158 SDValue TrueLow = TrueVal.getValue(0); 4159 SDValue TrueHigh = TrueVal.getValue(1); 4160 SDValue FalseLow = FalseVal.getValue(0); 4161 SDValue FalseHigh = FalseVal.getValue(1); 4162 4163 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4164 ARMcc, CCR, Cmp); 4165 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4166 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4167 4168 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4169 } else { 4170 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4171 Cmp); 4172 } 4173 } 4174 4175 static bool isGTorGE(ISD::CondCode CC) { 4176 return CC == ISD::SETGT || CC == ISD::SETGE; 4177 } 4178 4179 static bool isLTorLE(ISD::CondCode CC) { 4180 return CC == ISD::SETLT || CC == ISD::SETLE; 4181 } 4182 4183 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4184 // All of these conditions (and their <= and >= counterparts) will do: 4185 // x < k ? k : x 4186 // x > k ? x : k 4187 // k < x ? x : k 4188 // k > x ? k : x 4189 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4190 const SDValue TrueVal, const SDValue FalseVal, 4191 const ISD::CondCode CC, const SDValue K) { 4192 return (isGTorGE(CC) && 4193 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4194 (isLTorLE(CC) && 4195 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4196 } 4197 4198 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4199 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4200 const SDValue TrueVal, const SDValue FalseVal, 4201 const ISD::CondCode CC, const SDValue K) { 4202 return (isGTorGE(CC) && 4203 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4204 (isLTorLE(CC) && 4205 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4206 } 4207 4208 // Check if two chained conditionals could be converted into SSAT or USAT. 4209 // 4210 // SSAT can replace a set of two conditional selectors that bound a number to an 4211 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4212 // 4213 // x < -k ? -k : (x > k ? k : x) 4214 // x < -k ? -k : (x < k ? x : k) 4215 // x > -k ? (x > k ? k : x) : -k 4216 // x < k ? (x < -k ? -k : x) : k 4217 // etc. 4218 // 4219 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4220 // a power of 2. 4221 // 4222 // It returns true if the conversion can be done, false otherwise. 4223 // Additionally, the variable is returned in parameter V, the constant in K and 4224 // usat is set to true if the conditional represents an unsigned saturation 4225 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4226 uint64_t &K, bool &usat) { 4227 SDValue LHS1 = Op.getOperand(0); 4228 SDValue RHS1 = Op.getOperand(1); 4229 SDValue TrueVal1 = Op.getOperand(2); 4230 SDValue FalseVal1 = Op.getOperand(3); 4231 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4232 4233 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4234 if (Op2.getOpcode() != ISD::SELECT_CC) 4235 return false; 4236 4237 SDValue LHS2 = Op2.getOperand(0); 4238 SDValue RHS2 = Op2.getOperand(1); 4239 SDValue TrueVal2 = Op2.getOperand(2); 4240 SDValue FalseVal2 = Op2.getOperand(3); 4241 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4242 4243 // Find out which are the constants and which are the variables 4244 // in each conditional 4245 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4246 ? &RHS1 4247 : nullptr; 4248 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4249 ? &RHS2 4250 : nullptr; 4251 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4252 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4253 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4254 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4255 4256 // We must detect cases where the original operations worked with 16- or 4257 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4258 // must work with sign-extended values but the select operations return 4259 // the original non-extended value. 4260 SDValue V2TmpReg = V2Tmp; 4261 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4262 V2TmpReg = V2Tmp->getOperand(0); 4263 4264 // Check that the registers and the constants have the correct values 4265 // in both conditionals 4266 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4267 V2TmpReg != V2) 4268 return false; 4269 4270 // Figure out which conditional is saturating the lower/upper bound. 4271 const SDValue *LowerCheckOp = 4272 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4273 ? &Op 4274 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4275 ? &Op2 4276 : nullptr; 4277 const SDValue *UpperCheckOp = 4278 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4279 ? &Op 4280 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4281 ? &Op2 4282 : nullptr; 4283 4284 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4285 return false; 4286 4287 // Check that the constant in the lower-bound check is 4288 // the opposite of the constant in the upper-bound check 4289 // in 1's complement. 4290 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4291 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4292 int64_t PosVal = std::max(Val1, Val2); 4293 int64_t NegVal = std::min(Val1, Val2); 4294 4295 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4296 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4297 isPowerOf2_64(PosVal + 1)) { 4298 4299 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4300 if (Val1 == ~Val2) 4301 usat = false; 4302 else if (NegVal == 0) 4303 usat = true; 4304 else 4305 return false; 4306 4307 V = V2; 4308 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4309 4310 return true; 4311 } 4312 4313 return false; 4314 } 4315 4316 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4317 EVT VT = Op.getValueType(); 4318 SDLoc dl(Op); 4319 4320 // Try to convert two saturating conditional selects into a single SSAT 4321 SDValue SatValue; 4322 uint64_t SatConstant; 4323 bool SatUSat; 4324 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4325 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4326 if (SatUSat) 4327 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4328 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4329 else 4330 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4331 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4332 } 4333 4334 SDValue LHS = Op.getOperand(0); 4335 SDValue RHS = Op.getOperand(1); 4336 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4337 SDValue TrueVal = Op.getOperand(2); 4338 SDValue FalseVal = Op.getOperand(3); 4339 4340 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4341 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4342 dl); 4343 4344 // If softenSetCCOperands only returned one value, we should compare it to 4345 // zero. 4346 if (!RHS.getNode()) { 4347 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4348 CC = ISD::SETNE; 4349 } 4350 } 4351 4352 if (LHS.getValueType() == MVT::i32) { 4353 // Try to generate VSEL on ARMv8. 4354 // The VSEL instruction can't use all the usual ARM condition 4355 // codes: it only has two bits to select the condition code, so it's 4356 // constrained to use only GE, GT, VS and EQ. 4357 // 4358 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4359 // swap the operands of the previous compare instruction (effectively 4360 // inverting the compare condition, swapping 'less' and 'greater') and 4361 // sometimes need to swap the operands to the VSEL (which inverts the 4362 // condition in the sense of firing whenever the previous condition didn't) 4363 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4364 TrueVal.getValueType() == MVT::f64)) { 4365 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4366 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4367 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4368 CC = ISD::getSetCCInverse(CC, true); 4369 std::swap(TrueVal, FalseVal); 4370 } 4371 } 4372 4373 SDValue ARMcc; 4374 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4375 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4376 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4377 } 4378 4379 ARMCC::CondCodes CondCode, CondCode2; 4380 bool InvalidOnQNaN; 4381 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4382 4383 // Try to generate VMAXNM/VMINNM on ARMv8. 4384 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4385 TrueVal.getValueType() == MVT::f64)) { 4386 bool swpCmpOps = false; 4387 bool swpVselOps = false; 4388 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4389 4390 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4391 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4392 if (swpCmpOps) 4393 std::swap(LHS, RHS); 4394 if (swpVselOps) 4395 std::swap(TrueVal, FalseVal); 4396 } 4397 } 4398 4399 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4400 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4401 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4402 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4403 if (CondCode2 != ARMCC::AL) { 4404 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4405 // FIXME: Needs another CMP because flag can have but one use. 4406 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4407 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4408 } 4409 return Result; 4410 } 4411 4412 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4413 /// to morph to an integer compare sequence. 4414 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4415 const ARMSubtarget *Subtarget) { 4416 SDNode *N = Op.getNode(); 4417 if (!N->hasOneUse()) 4418 // Otherwise it requires moving the value from fp to integer registers. 4419 return false; 4420 if (!N->getNumValues()) 4421 return false; 4422 EVT VT = Op.getValueType(); 4423 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4424 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4425 // vmrs are very slow, e.g. cortex-a8. 4426 return false; 4427 4428 if (isFloatingPointZero(Op)) { 4429 SeenZero = true; 4430 return true; 4431 } 4432 return ISD::isNormalLoad(N); 4433 } 4434 4435 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4436 if (isFloatingPointZero(Op)) 4437 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4438 4439 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4440 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4441 Ld->getPointerInfo(), Ld->getAlignment(), 4442 Ld->getMemOperand()->getFlags()); 4443 4444 llvm_unreachable("Unknown VFP cmp argument!"); 4445 } 4446 4447 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4448 SDValue &RetVal1, SDValue &RetVal2) { 4449 SDLoc dl(Op); 4450 4451 if (isFloatingPointZero(Op)) { 4452 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4453 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4454 return; 4455 } 4456 4457 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4458 SDValue Ptr = Ld->getBasePtr(); 4459 RetVal1 = 4460 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4461 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4462 4463 EVT PtrType = Ptr.getValueType(); 4464 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4465 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4466 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4467 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4468 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4469 Ld->getMemOperand()->getFlags()); 4470 return; 4471 } 4472 4473 llvm_unreachable("Unknown VFP cmp argument!"); 4474 } 4475 4476 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4477 /// f32 and even f64 comparisons to integer ones. 4478 SDValue 4479 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4480 SDValue Chain = Op.getOperand(0); 4481 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4482 SDValue LHS = Op.getOperand(2); 4483 SDValue RHS = Op.getOperand(3); 4484 SDValue Dest = Op.getOperand(4); 4485 SDLoc dl(Op); 4486 4487 bool LHSSeenZero = false; 4488 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4489 bool RHSSeenZero = false; 4490 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4491 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4492 // If unsafe fp math optimization is enabled and there are no other uses of 4493 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4494 // to an integer comparison. 4495 if (CC == ISD::SETOEQ) 4496 CC = ISD::SETEQ; 4497 else if (CC == ISD::SETUNE) 4498 CC = ISD::SETNE; 4499 4500 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4501 SDValue ARMcc; 4502 if (LHS.getValueType() == MVT::f32) { 4503 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4504 bitcastf32Toi32(LHS, DAG), Mask); 4505 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4506 bitcastf32Toi32(RHS, DAG), Mask); 4507 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4508 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4509 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4510 Chain, Dest, ARMcc, CCR, Cmp); 4511 } 4512 4513 SDValue LHS1, LHS2; 4514 SDValue RHS1, RHS2; 4515 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4516 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4517 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4518 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4519 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4520 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4521 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4522 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4523 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4524 } 4525 4526 return SDValue(); 4527 } 4528 4529 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4530 SDValue Chain = Op.getOperand(0); 4531 SDValue Cond = Op.getOperand(1); 4532 SDValue Dest = Op.getOperand(2); 4533 SDLoc dl(Op); 4534 4535 // Optimize {s|u}{add|sub}.with.overflow feeding into a branch instruction. 4536 unsigned Opc = Cond.getOpcode(); 4537 if (Cond.getResNo() == 1 && (Opc == ISD::SADDO || Opc == ISD::UADDO || 4538 Opc == ISD::SSUBO || Opc == ISD::USUBO)) { 4539 // Only lower legal XALUO ops. 4540 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4541 return SDValue(); 4542 4543 // The actual operation with overflow check. 4544 SDValue Value, OverflowCmp; 4545 SDValue ARMcc; 4546 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4547 4548 // Reverse the condition code. 4549 ARMCC::CondCodes CondCode = 4550 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4551 CondCode = ARMCC::getOppositeCondition(CondCode); 4552 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4553 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4554 4555 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4556 OverflowCmp); 4557 } 4558 4559 return SDValue(); 4560 } 4561 4562 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4563 SDValue Chain = Op.getOperand(0); 4564 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4565 SDValue LHS = Op.getOperand(2); 4566 SDValue RHS = Op.getOperand(3); 4567 SDValue Dest = Op.getOperand(4); 4568 SDLoc dl(Op); 4569 4570 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4571 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4572 dl); 4573 4574 // If softenSetCCOperands only returned one value, we should compare it to 4575 // zero. 4576 if (!RHS.getNode()) { 4577 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4578 CC = ISD::SETNE; 4579 } 4580 } 4581 4582 // Optimize {s|u}{add|sub}.with.overflow feeding into a branch instruction. 4583 unsigned Opc = LHS.getOpcode(); 4584 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4585 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4586 Opc == ISD::USUBO) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4587 // Only lower legal XALUO ops. 4588 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4589 return SDValue(); 4590 4591 // The actual operation with overflow check. 4592 SDValue Value, OverflowCmp; 4593 SDValue ARMcc; 4594 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4595 4596 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4597 // Reverse the condition code. 4598 ARMCC::CondCodes CondCode = 4599 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4600 CondCode = ARMCC::getOppositeCondition(CondCode); 4601 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4602 } 4603 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4604 4605 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4606 OverflowCmp); 4607 } 4608 4609 if (LHS.getValueType() == MVT::i32) { 4610 SDValue ARMcc; 4611 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4612 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4613 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4614 Chain, Dest, ARMcc, CCR, Cmp); 4615 } 4616 4617 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4618 4619 if (getTargetMachine().Options.UnsafeFPMath && 4620 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4621 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4622 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4623 return Result; 4624 } 4625 4626 ARMCC::CondCodes CondCode, CondCode2; 4627 bool InvalidOnQNaN; 4628 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4629 4630 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4631 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4632 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4633 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4634 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4635 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4636 if (CondCode2 != ARMCC::AL) { 4637 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4638 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4639 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4640 } 4641 return Res; 4642 } 4643 4644 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4645 SDValue Chain = Op.getOperand(0); 4646 SDValue Table = Op.getOperand(1); 4647 SDValue Index = Op.getOperand(2); 4648 SDLoc dl(Op); 4649 4650 EVT PTy = getPointerTy(DAG.getDataLayout()); 4651 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4652 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4653 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4654 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4655 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4656 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4657 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4658 // which does another jump to the destination. This also makes it easier 4659 // to translate it to TBB / TBH later (Thumb2 only). 4660 // FIXME: This might not work if the function is extremely large. 4661 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4662 Addr, Op.getOperand(2), JTI); 4663 } 4664 if (isPositionIndependent() || Subtarget->isROPI()) { 4665 Addr = 4666 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4667 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4668 Chain = Addr.getValue(1); 4669 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4670 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4671 } else { 4672 Addr = 4673 DAG.getLoad(PTy, dl, Chain, Addr, 4674 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4675 Chain = Addr.getValue(1); 4676 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4677 } 4678 } 4679 4680 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4681 EVT VT = Op.getValueType(); 4682 SDLoc dl(Op); 4683 4684 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4685 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4686 return Op; 4687 return DAG.UnrollVectorOp(Op.getNode()); 4688 } 4689 4690 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4691 "Invalid type for custom lowering!"); 4692 if (VT != MVT::v4i16) 4693 return DAG.UnrollVectorOp(Op.getNode()); 4694 4695 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4696 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4697 } 4698 4699 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4700 EVT VT = Op.getValueType(); 4701 if (VT.isVector()) 4702 return LowerVectorFP_TO_INT(Op, DAG); 4703 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4704 RTLIB::Libcall LC; 4705 if (Op.getOpcode() == ISD::FP_TO_SINT) 4706 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4707 Op.getValueType()); 4708 else 4709 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4710 Op.getValueType()); 4711 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4712 /*isSigned*/ false, SDLoc(Op)).first; 4713 } 4714 4715 return Op; 4716 } 4717 4718 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4719 EVT VT = Op.getValueType(); 4720 SDLoc dl(Op); 4721 4722 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4723 if (VT.getVectorElementType() == MVT::f32) 4724 return Op; 4725 return DAG.UnrollVectorOp(Op.getNode()); 4726 } 4727 4728 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4729 "Invalid type for custom lowering!"); 4730 if (VT != MVT::v4f32) 4731 return DAG.UnrollVectorOp(Op.getNode()); 4732 4733 unsigned CastOpc; 4734 unsigned Opc; 4735 switch (Op.getOpcode()) { 4736 default: llvm_unreachable("Invalid opcode!"); 4737 case ISD::SINT_TO_FP: 4738 CastOpc = ISD::SIGN_EXTEND; 4739 Opc = ISD::SINT_TO_FP; 4740 break; 4741 case ISD::UINT_TO_FP: 4742 CastOpc = ISD::ZERO_EXTEND; 4743 Opc = ISD::UINT_TO_FP; 4744 break; 4745 } 4746 4747 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4748 return DAG.getNode(Opc, dl, VT, Op); 4749 } 4750 4751 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4752 EVT VT = Op.getValueType(); 4753 if (VT.isVector()) 4754 return LowerVectorINT_TO_FP(Op, DAG); 4755 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4756 RTLIB::Libcall LC; 4757 if (Op.getOpcode() == ISD::SINT_TO_FP) 4758 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4759 Op.getValueType()); 4760 else 4761 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4762 Op.getValueType()); 4763 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4764 /*isSigned*/ false, SDLoc(Op)).first; 4765 } 4766 4767 return Op; 4768 } 4769 4770 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4771 // Implement fcopysign with a fabs and a conditional fneg. 4772 SDValue Tmp0 = Op.getOperand(0); 4773 SDValue Tmp1 = Op.getOperand(1); 4774 SDLoc dl(Op); 4775 EVT VT = Op.getValueType(); 4776 EVT SrcVT = Tmp1.getValueType(); 4777 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4778 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4779 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4780 4781 if (UseNEON) { 4782 // Use VBSL to copy the sign bit. 4783 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4784 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4785 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4786 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4787 if (VT == MVT::f64) 4788 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4789 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4790 DAG.getConstant(32, dl, MVT::i32)); 4791 else /*if (VT == MVT::f32)*/ 4792 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4793 if (SrcVT == MVT::f32) { 4794 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4795 if (VT == MVT::f64) 4796 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4797 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4798 DAG.getConstant(32, dl, MVT::i32)); 4799 } else if (VT == MVT::f32) 4800 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4801 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4802 DAG.getConstant(32, dl, MVT::i32)); 4803 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4804 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4805 4806 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4807 dl, MVT::i32); 4808 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4809 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4810 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4811 4812 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4813 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4814 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4815 if (VT == MVT::f32) { 4816 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4817 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4818 DAG.getConstant(0, dl, MVT::i32)); 4819 } else { 4820 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4821 } 4822 4823 return Res; 4824 } 4825 4826 // Bitcast operand 1 to i32. 4827 if (SrcVT == MVT::f64) 4828 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4829 Tmp1).getValue(1); 4830 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4831 4832 // Or in the signbit with integer operations. 4833 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4834 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4835 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4836 if (VT == MVT::f32) { 4837 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4838 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4839 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4840 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4841 } 4842 4843 // f64: Or the high part with signbit and then combine two parts. 4844 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4845 Tmp0); 4846 SDValue Lo = Tmp0.getValue(0); 4847 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4848 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4849 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4850 } 4851 4852 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4853 MachineFunction &MF = DAG.getMachineFunction(); 4854 MachineFrameInfo &MFI = MF.getFrameInfo(); 4855 MFI.setReturnAddressIsTaken(true); 4856 4857 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4858 return SDValue(); 4859 4860 EVT VT = Op.getValueType(); 4861 SDLoc dl(Op); 4862 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4863 if (Depth) { 4864 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4865 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4866 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4867 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4868 MachinePointerInfo()); 4869 } 4870 4871 // Return LR, which contains the return address. Mark it an implicit live-in. 4872 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4873 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4874 } 4875 4876 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4877 const ARMBaseRegisterInfo &ARI = 4878 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4879 MachineFunction &MF = DAG.getMachineFunction(); 4880 MachineFrameInfo &MFI = MF.getFrameInfo(); 4881 MFI.setFrameAddressIsTaken(true); 4882 4883 EVT VT = Op.getValueType(); 4884 SDLoc dl(Op); // FIXME probably not meaningful 4885 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4886 unsigned FrameReg = ARI.getFrameRegister(MF); 4887 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4888 while (Depth--) 4889 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4890 MachinePointerInfo()); 4891 return FrameAddr; 4892 } 4893 4894 // FIXME? Maybe this could be a TableGen attribute on some registers and 4895 // this table could be generated automatically from RegInfo. 4896 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4897 SelectionDAG &DAG) const { 4898 unsigned Reg = StringSwitch<unsigned>(RegName) 4899 .Case("sp", ARM::SP) 4900 .Default(0); 4901 if (Reg) 4902 return Reg; 4903 report_fatal_error(Twine("Invalid register name \"" 4904 + StringRef(RegName) + "\".")); 4905 } 4906 4907 // Result is 64 bit value so split into two 32 bit values and return as a 4908 // pair of values. 4909 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4910 SelectionDAG &DAG) { 4911 SDLoc DL(N); 4912 4913 // This function is only supposed to be called for i64 type destination. 4914 assert(N->getValueType(0) == MVT::i64 4915 && "ExpandREAD_REGISTER called for non-i64 type result."); 4916 4917 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4918 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4919 N->getOperand(0), 4920 N->getOperand(1)); 4921 4922 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4923 Read.getValue(1))); 4924 Results.push_back(Read.getOperand(0)); 4925 } 4926 4927 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4928 /// When \p DstVT, the destination type of \p BC, is on the vector 4929 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4930 /// it might be possible to combine them, such that everything stays on the 4931 /// vector register bank. 4932 /// \p return The node that would replace \p BT, if the combine 4933 /// is possible. 4934 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4935 SelectionDAG &DAG) { 4936 SDValue Op = BC->getOperand(0); 4937 EVT DstVT = BC->getValueType(0); 4938 4939 // The only vector instruction that can produce a scalar (remember, 4940 // since the bitcast was about to be turned into VMOVDRR, the source 4941 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4942 // Moreover, we can do this combine only if there is one use. 4943 // Finally, if the destination type is not a vector, there is not 4944 // much point on forcing everything on the vector bank. 4945 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4946 !Op.hasOneUse()) 4947 return SDValue(); 4948 4949 // If the index is not constant, we will introduce an additional 4950 // multiply that will stick. 4951 // Give up in that case. 4952 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4953 if (!Index) 4954 return SDValue(); 4955 unsigned DstNumElt = DstVT.getVectorNumElements(); 4956 4957 // Compute the new index. 4958 const APInt &APIntIndex = Index->getAPIntValue(); 4959 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4960 NewIndex *= APIntIndex; 4961 // Check if the new constant index fits into i32. 4962 if (NewIndex.getBitWidth() > 32) 4963 return SDValue(); 4964 4965 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4966 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4967 SDLoc dl(Op); 4968 SDValue ExtractSrc = Op.getOperand(0); 4969 EVT VecVT = EVT::getVectorVT( 4970 *DAG.getContext(), DstVT.getScalarType(), 4971 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4972 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4973 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4974 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4975 } 4976 4977 /// ExpandBITCAST - If the target supports VFP, this function is called to 4978 /// expand a bit convert where either the source or destination type is i64 to 4979 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4980 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4981 /// vectors), since the legalizer won't know what to do with that. 4982 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4983 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4984 SDLoc dl(N); 4985 SDValue Op = N->getOperand(0); 4986 4987 // This function is only supposed to be called for i64 types, either as the 4988 // source or destination of the bit convert. 4989 EVT SrcVT = Op.getValueType(); 4990 EVT DstVT = N->getValueType(0); 4991 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4992 "ExpandBITCAST called for non-i64 type"); 4993 4994 // Turn i64->f64 into VMOVDRR. 4995 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4996 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4997 // if we can combine the bitcast with its source. 4998 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4999 return Val; 5000 5001 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5002 DAG.getConstant(0, dl, MVT::i32)); 5003 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5004 DAG.getConstant(1, dl, MVT::i32)); 5005 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5006 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5007 } 5008 5009 // Turn f64->i64 into VMOVRRD. 5010 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5011 SDValue Cvt; 5012 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5013 SrcVT.getVectorNumElements() > 1) 5014 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5015 DAG.getVTList(MVT::i32, MVT::i32), 5016 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5017 else 5018 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5019 DAG.getVTList(MVT::i32, MVT::i32), Op); 5020 // Merge the pieces into a single i64 value. 5021 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5022 } 5023 5024 return SDValue(); 5025 } 5026 5027 /// getZeroVector - Returns a vector of specified type with all zero elements. 5028 /// Zero vectors are used to represent vector negation and in those cases 5029 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5030 /// not support i64 elements, so sometimes the zero vectors will need to be 5031 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5032 /// zero vector. 5033 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5034 assert(VT.isVector() && "Expected a vector type"); 5035 // The canonical modified immediate encoding of a zero vector is....0! 5036 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5037 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5038 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5039 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5040 } 5041 5042 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5043 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5044 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5045 SelectionDAG &DAG) const { 5046 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5047 EVT VT = Op.getValueType(); 5048 unsigned VTBits = VT.getSizeInBits(); 5049 SDLoc dl(Op); 5050 SDValue ShOpLo = Op.getOperand(0); 5051 SDValue ShOpHi = Op.getOperand(1); 5052 SDValue ShAmt = Op.getOperand(2); 5053 SDValue ARMcc; 5054 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5055 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5056 5057 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5058 5059 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5060 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5061 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5062 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5063 DAG.getConstant(VTBits, dl, MVT::i32)); 5064 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5065 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5066 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5067 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5068 ISD::SETGE, ARMcc, DAG, dl); 5069 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5070 ARMcc, CCR, CmpLo); 5071 5072 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5073 SDValue HiBigShift = Opc == ISD::SRA 5074 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5075 DAG.getConstant(VTBits - 1, dl, VT)) 5076 : DAG.getConstant(0, dl, VT); 5077 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5078 ISD::SETGE, ARMcc, DAG, dl); 5079 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5080 ARMcc, CCR, CmpHi); 5081 5082 SDValue Ops[2] = { Lo, Hi }; 5083 return DAG.getMergeValues(Ops, dl); 5084 } 5085 5086 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5087 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5088 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5089 SelectionDAG &DAG) const { 5090 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5091 EVT VT = Op.getValueType(); 5092 unsigned VTBits = VT.getSizeInBits(); 5093 SDLoc dl(Op); 5094 SDValue ShOpLo = Op.getOperand(0); 5095 SDValue ShOpHi = Op.getOperand(1); 5096 SDValue ShAmt = Op.getOperand(2); 5097 SDValue ARMcc; 5098 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5099 5100 assert(Op.getOpcode() == ISD::SHL_PARTS); 5101 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5102 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5103 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5104 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5105 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5106 5107 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5108 DAG.getConstant(VTBits, dl, MVT::i32)); 5109 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5110 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5111 ISD::SETGE, ARMcc, DAG, dl); 5112 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5113 ARMcc, CCR, CmpHi); 5114 5115 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5116 ISD::SETGE, ARMcc, DAG, dl); 5117 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5118 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5119 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5120 5121 SDValue Ops[2] = { Lo, Hi }; 5122 return DAG.getMergeValues(Ops, dl); 5123 } 5124 5125 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5126 SelectionDAG &DAG) const { 5127 // The rounding mode is in bits 23:22 of the FPSCR. 5128 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5129 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5130 // so that the shift + and get folded into a bitfield extract. 5131 SDLoc dl(Op); 5132 SDValue Ops[] = { DAG.getEntryNode(), 5133 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5134 5135 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5136 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5137 DAG.getConstant(1U << 22, dl, MVT::i32)); 5138 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5139 DAG.getConstant(22, dl, MVT::i32)); 5140 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5141 DAG.getConstant(3, dl, MVT::i32)); 5142 } 5143 5144 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5145 const ARMSubtarget *ST) { 5146 SDLoc dl(N); 5147 EVT VT = N->getValueType(0); 5148 if (VT.isVector()) { 5149 assert(ST->hasNEON()); 5150 5151 // Compute the least significant set bit: LSB = X & -X 5152 SDValue X = N->getOperand(0); 5153 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5154 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5155 5156 EVT ElemTy = VT.getVectorElementType(); 5157 5158 if (ElemTy == MVT::i8) { 5159 // Compute with: cttz(x) = ctpop(lsb - 1) 5160 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5161 DAG.getTargetConstant(1, dl, ElemTy)); 5162 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5163 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5164 } 5165 5166 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5167 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5168 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5169 unsigned NumBits = ElemTy.getSizeInBits(); 5170 SDValue WidthMinus1 = 5171 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5172 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5173 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5174 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5175 } 5176 5177 // Compute with: cttz(x) = ctpop(lsb - 1) 5178 5179 // Since we can only compute the number of bits in a byte with vcnt.8, we 5180 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 5181 // and i64. 5182 5183 // Compute LSB - 1. 5184 SDValue Bits; 5185 if (ElemTy == MVT::i64) { 5186 // Load constant 0xffff'ffff'ffff'ffff to register. 5187 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5188 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5189 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5190 } else { 5191 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5192 DAG.getTargetConstant(1, dl, ElemTy)); 5193 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5194 } 5195 5196 // Count #bits with vcnt.8. 5197 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5198 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5199 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5200 5201 // Gather the #bits with vpaddl (pairwise add.) 5202 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5203 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5204 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5205 Cnt8); 5206 if (ElemTy == MVT::i16) 5207 return Cnt16; 5208 5209 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5210 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5211 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5212 Cnt16); 5213 if (ElemTy == MVT::i32) 5214 return Cnt32; 5215 5216 assert(ElemTy == MVT::i64); 5217 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5218 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5219 Cnt32); 5220 return Cnt64; 5221 } 5222 5223 if (!ST->hasV6T2Ops()) 5224 return SDValue(); 5225 5226 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5227 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5228 } 5229 5230 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5231 /// for each 16-bit element from operand, repeated. The basic idea is to 5232 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5233 /// 5234 /// Trace for v4i16: 5235 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5236 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5237 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5238 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5239 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5240 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5241 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5242 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5243 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5244 EVT VT = N->getValueType(0); 5245 SDLoc DL(N); 5246 5247 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5248 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5249 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5250 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5251 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5252 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5253 } 5254 5255 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5256 /// bit-count for each 16-bit element from the operand. We need slightly 5257 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5258 /// 64/128-bit registers. 5259 /// 5260 /// Trace for v4i16: 5261 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5262 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5263 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5264 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5265 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5266 EVT VT = N->getValueType(0); 5267 SDLoc DL(N); 5268 5269 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5270 if (VT.is64BitVector()) { 5271 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5272 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5273 DAG.getIntPtrConstant(0, DL)); 5274 } else { 5275 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5276 BitCounts, DAG.getIntPtrConstant(0, DL)); 5277 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5278 } 5279 } 5280 5281 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5282 /// bit-count for each 32-bit element from the operand. The idea here is 5283 /// to split the vector into 16-bit elements, leverage the 16-bit count 5284 /// routine, and then combine the results. 5285 /// 5286 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5287 /// input = [v0 v1 ] (vi: 32-bit elements) 5288 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5289 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5290 /// vrev: N0 = [k1 k0 k3 k2 ] 5291 /// [k0 k1 k2 k3 ] 5292 /// N1 =+[k1 k0 k3 k2 ] 5293 /// [k0 k2 k1 k3 ] 5294 /// N2 =+[k1 k3 k0 k2 ] 5295 /// [k0 k2 k1 k3 ] 5296 /// Extended =+[k1 k3 k0 k2 ] 5297 /// [k0 k2 ] 5298 /// Extracted=+[k1 k3 ] 5299 /// 5300 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5301 EVT VT = N->getValueType(0); 5302 SDLoc DL(N); 5303 5304 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5305 5306 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5307 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5308 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5309 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5310 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5311 5312 if (VT.is64BitVector()) { 5313 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5314 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5315 DAG.getIntPtrConstant(0, DL)); 5316 } else { 5317 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5318 DAG.getIntPtrConstant(0, DL)); 5319 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5320 } 5321 } 5322 5323 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5324 const ARMSubtarget *ST) { 5325 EVT VT = N->getValueType(0); 5326 5327 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5328 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5329 VT == MVT::v4i16 || VT == MVT::v8i16) && 5330 "Unexpected type for custom ctpop lowering"); 5331 5332 if (VT.getVectorElementType() == MVT::i32) 5333 return lowerCTPOP32BitElements(N, DAG); 5334 else 5335 return lowerCTPOP16BitElements(N, DAG); 5336 } 5337 5338 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5339 const ARMSubtarget *ST) { 5340 EVT VT = N->getValueType(0); 5341 SDLoc dl(N); 5342 5343 if (!VT.isVector()) 5344 return SDValue(); 5345 5346 // Lower vector shifts on NEON to use VSHL. 5347 assert(ST->hasNEON() && "unexpected vector shift"); 5348 5349 // Left shifts translate directly to the vshiftu intrinsic. 5350 if (N->getOpcode() == ISD::SHL) 5351 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5352 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5353 MVT::i32), 5354 N->getOperand(0), N->getOperand(1)); 5355 5356 assert((N->getOpcode() == ISD::SRA || 5357 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5358 5359 // NEON uses the same intrinsics for both left and right shifts. For 5360 // right shifts, the shift amounts are negative, so negate the vector of 5361 // shift amounts. 5362 EVT ShiftVT = N->getOperand(1).getValueType(); 5363 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5364 getZeroVector(ShiftVT, DAG, dl), 5365 N->getOperand(1)); 5366 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5367 Intrinsic::arm_neon_vshifts : 5368 Intrinsic::arm_neon_vshiftu); 5369 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5370 DAG.getConstant(vshiftInt, dl, MVT::i32), 5371 N->getOperand(0), NegatedCount); 5372 } 5373 5374 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5375 const ARMSubtarget *ST) { 5376 EVT VT = N->getValueType(0); 5377 SDLoc dl(N); 5378 5379 // We can get here for a node like i32 = ISD::SHL i32, i64 5380 if (VT != MVT::i64) 5381 return SDValue(); 5382 5383 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5384 "Unknown shift to lower!"); 5385 5386 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5387 if (!isOneConstant(N->getOperand(1))) 5388 return SDValue(); 5389 5390 // If we are in thumb mode, we don't have RRX. 5391 if (ST->isThumb1Only()) return SDValue(); 5392 5393 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5394 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5395 DAG.getConstant(0, dl, MVT::i32)); 5396 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5397 DAG.getConstant(1, dl, MVT::i32)); 5398 5399 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5400 // captures the result into a carry flag. 5401 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5402 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5403 5404 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5405 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5406 5407 // Merge the pieces into a single i64 value. 5408 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5409 } 5410 5411 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5412 SDValue TmpOp0, TmpOp1; 5413 bool Invert = false; 5414 bool Swap = false; 5415 unsigned Opc = 0; 5416 5417 SDValue Op0 = Op.getOperand(0); 5418 SDValue Op1 = Op.getOperand(1); 5419 SDValue CC = Op.getOperand(2); 5420 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5421 EVT VT = Op.getValueType(); 5422 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5423 SDLoc dl(Op); 5424 5425 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5426 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5427 // Special-case integer 64-bit equality comparisons. They aren't legal, 5428 // but they can be lowered with a few vector instructions. 5429 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5430 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5431 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5432 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5433 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5434 DAG.getCondCode(ISD::SETEQ)); 5435 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5436 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5437 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5438 if (SetCCOpcode == ISD::SETNE) 5439 Merged = DAG.getNOT(dl, Merged, CmpVT); 5440 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5441 return Merged; 5442 } 5443 5444 if (CmpVT.getVectorElementType() == MVT::i64) 5445 // 64-bit comparisons are not legal in general. 5446 return SDValue(); 5447 5448 if (Op1.getValueType().isFloatingPoint()) { 5449 switch (SetCCOpcode) { 5450 default: llvm_unreachable("Illegal FP comparison"); 5451 case ISD::SETUNE: 5452 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5453 case ISD::SETOEQ: 5454 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5455 case ISD::SETOLT: 5456 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5457 case ISD::SETOGT: 5458 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5459 case ISD::SETOLE: 5460 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5461 case ISD::SETOGE: 5462 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5463 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5464 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5465 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5466 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5467 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5468 case ISD::SETONE: 5469 // Expand this to (OLT | OGT). 5470 TmpOp0 = Op0; 5471 TmpOp1 = Op1; 5472 Opc = ISD::OR; 5473 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5474 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5475 break; 5476 case ISD::SETUO: 5477 Invert = true; 5478 LLVM_FALLTHROUGH; 5479 case ISD::SETO: 5480 // Expand this to (OLT | OGE). 5481 TmpOp0 = Op0; 5482 TmpOp1 = Op1; 5483 Opc = ISD::OR; 5484 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5485 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5486 break; 5487 } 5488 } else { 5489 // Integer comparisons. 5490 switch (SetCCOpcode) { 5491 default: llvm_unreachable("Illegal integer comparison"); 5492 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5493 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5494 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5495 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5496 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5497 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5498 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5499 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5500 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5501 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5502 } 5503 5504 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5505 if (Opc == ARMISD::VCEQ) { 5506 SDValue AndOp; 5507 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5508 AndOp = Op0; 5509 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5510 AndOp = Op1; 5511 5512 // Ignore bitconvert. 5513 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5514 AndOp = AndOp.getOperand(0); 5515 5516 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5517 Opc = ARMISD::VTST; 5518 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5519 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5520 Invert = !Invert; 5521 } 5522 } 5523 } 5524 5525 if (Swap) 5526 std::swap(Op0, Op1); 5527 5528 // If one of the operands is a constant vector zero, attempt to fold the 5529 // comparison to a specialized compare-against-zero form. 5530 SDValue SingleOp; 5531 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5532 SingleOp = Op0; 5533 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5534 if (Opc == ARMISD::VCGE) 5535 Opc = ARMISD::VCLEZ; 5536 else if (Opc == ARMISD::VCGT) 5537 Opc = ARMISD::VCLTZ; 5538 SingleOp = Op1; 5539 } 5540 5541 SDValue Result; 5542 if (SingleOp.getNode()) { 5543 switch (Opc) { 5544 case ARMISD::VCEQ: 5545 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5546 case ARMISD::VCGE: 5547 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5548 case ARMISD::VCLEZ: 5549 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5550 case ARMISD::VCGT: 5551 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5552 case ARMISD::VCLTZ: 5553 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5554 default: 5555 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5556 } 5557 } else { 5558 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5559 } 5560 5561 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5562 5563 if (Invert) 5564 Result = DAG.getNOT(dl, Result, VT); 5565 5566 return Result; 5567 } 5568 5569 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5570 SDValue LHS = Op.getOperand(0); 5571 SDValue RHS = Op.getOperand(1); 5572 SDValue Carry = Op.getOperand(2); 5573 SDValue Cond = Op.getOperand(3); 5574 SDLoc DL(Op); 5575 5576 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5577 5578 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5579 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5580 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5581 5582 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5583 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5584 SDValue ARMcc = DAG.getConstant( 5585 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5586 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5587 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5588 Cmp.getValue(1), SDValue()); 5589 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5590 CCR, Chain.getValue(1)); 5591 } 5592 5593 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5594 /// valid vector constant for a NEON instruction with a "modified immediate" 5595 /// operand (e.g., VMOV). If so, return the encoded value. 5596 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5597 unsigned SplatBitSize, SelectionDAG &DAG, 5598 const SDLoc &dl, EVT &VT, bool is128Bits, 5599 NEONModImmType type) { 5600 unsigned OpCmode, Imm; 5601 5602 // SplatBitSize is set to the smallest size that splats the vector, so a 5603 // zero vector will always have SplatBitSize == 8. However, NEON modified 5604 // immediate instructions others than VMOV do not support the 8-bit encoding 5605 // of a zero vector, and the default encoding of zero is supposed to be the 5606 // 32-bit version. 5607 if (SplatBits == 0) 5608 SplatBitSize = 32; 5609 5610 switch (SplatBitSize) { 5611 case 8: 5612 if (type != VMOVModImm) 5613 return SDValue(); 5614 // Any 1-byte value is OK. Op=0, Cmode=1110. 5615 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5616 OpCmode = 0xe; 5617 Imm = SplatBits; 5618 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5619 break; 5620 5621 case 16: 5622 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5623 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5624 if ((SplatBits & ~0xff) == 0) { 5625 // Value = 0x00nn: Op=x, Cmode=100x. 5626 OpCmode = 0x8; 5627 Imm = SplatBits; 5628 break; 5629 } 5630 if ((SplatBits & ~0xff00) == 0) { 5631 // Value = 0xnn00: Op=x, Cmode=101x. 5632 OpCmode = 0xa; 5633 Imm = SplatBits >> 8; 5634 break; 5635 } 5636 return SDValue(); 5637 5638 case 32: 5639 // NEON's 32-bit VMOV supports splat values where: 5640 // * only one byte is nonzero, or 5641 // * the least significant byte is 0xff and the second byte is nonzero, or 5642 // * the least significant 2 bytes are 0xff and the third is nonzero. 5643 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5644 if ((SplatBits & ~0xff) == 0) { 5645 // Value = 0x000000nn: Op=x, Cmode=000x. 5646 OpCmode = 0; 5647 Imm = SplatBits; 5648 break; 5649 } 5650 if ((SplatBits & ~0xff00) == 0) { 5651 // Value = 0x0000nn00: Op=x, Cmode=001x. 5652 OpCmode = 0x2; 5653 Imm = SplatBits >> 8; 5654 break; 5655 } 5656 if ((SplatBits & ~0xff0000) == 0) { 5657 // Value = 0x00nn0000: Op=x, Cmode=010x. 5658 OpCmode = 0x4; 5659 Imm = SplatBits >> 16; 5660 break; 5661 } 5662 if ((SplatBits & ~0xff000000) == 0) { 5663 // Value = 0xnn000000: Op=x, Cmode=011x. 5664 OpCmode = 0x6; 5665 Imm = SplatBits >> 24; 5666 break; 5667 } 5668 5669 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5670 if (type == OtherModImm) return SDValue(); 5671 5672 if ((SplatBits & ~0xffff) == 0 && 5673 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5674 // Value = 0x0000nnff: Op=x, Cmode=1100. 5675 OpCmode = 0xc; 5676 Imm = SplatBits >> 8; 5677 break; 5678 } 5679 5680 if ((SplatBits & ~0xffffff) == 0 && 5681 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5682 // Value = 0x00nnffff: Op=x, Cmode=1101. 5683 OpCmode = 0xd; 5684 Imm = SplatBits >> 16; 5685 break; 5686 } 5687 5688 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5689 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5690 // VMOV.I32. A (very) minor optimization would be to replicate the value 5691 // and fall through here to test for a valid 64-bit splat. But, then the 5692 // caller would also need to check and handle the change in size. 5693 return SDValue(); 5694 5695 case 64: { 5696 if (type != VMOVModImm) 5697 return SDValue(); 5698 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5699 uint64_t BitMask = 0xff; 5700 uint64_t Val = 0; 5701 unsigned ImmMask = 1; 5702 Imm = 0; 5703 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5704 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5705 Val |= BitMask; 5706 Imm |= ImmMask; 5707 } else if ((SplatBits & BitMask) != 0) { 5708 return SDValue(); 5709 } 5710 BitMask <<= 8; 5711 ImmMask <<= 1; 5712 } 5713 5714 if (DAG.getDataLayout().isBigEndian()) 5715 // swap higher and lower 32 bit word 5716 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5717 5718 // Op=1, Cmode=1110. 5719 OpCmode = 0x1e; 5720 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5721 break; 5722 } 5723 5724 default: 5725 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5726 } 5727 5728 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5729 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5730 } 5731 5732 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5733 const ARMSubtarget *ST) const { 5734 bool IsDouble = Op.getValueType() == MVT::f64; 5735 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5736 const APFloat &FPVal = CFP->getValueAPF(); 5737 5738 // Prevent floating-point constants from using literal loads 5739 // when execute-only is enabled. 5740 if (ST->genExecuteOnly()) { 5741 APInt INTVal = FPVal.bitcastToAPInt(); 5742 SDLoc DL(CFP); 5743 if (IsDouble) { 5744 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5745 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5746 if (!ST->isLittle()) 5747 std::swap(Lo, Hi); 5748 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5749 } else { 5750 return DAG.getConstant(INTVal, DL, MVT::i32); 5751 } 5752 } 5753 5754 if (!ST->hasVFP3()) 5755 return SDValue(); 5756 5757 // Use the default (constant pool) lowering for double constants when we have 5758 // an SP-only FPU 5759 if (IsDouble && Subtarget->isFPOnlySP()) 5760 return SDValue(); 5761 5762 // Try splatting with a VMOV.f32... 5763 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5764 5765 if (ImmVal != -1) { 5766 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5767 // We have code in place to select a valid ConstantFP already, no need to 5768 // do any mangling. 5769 return Op; 5770 } 5771 5772 // It's a float and we are trying to use NEON operations where 5773 // possible. Lower it to a splat followed by an extract. 5774 SDLoc DL(Op); 5775 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5776 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5777 NewVal); 5778 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5779 DAG.getConstant(0, DL, MVT::i32)); 5780 } 5781 5782 // The rest of our options are NEON only, make sure that's allowed before 5783 // proceeding.. 5784 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5785 return SDValue(); 5786 5787 EVT VMovVT; 5788 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5789 5790 // It wouldn't really be worth bothering for doubles except for one very 5791 // important value, which does happen to match: 0.0. So make sure we don't do 5792 // anything stupid. 5793 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5794 return SDValue(); 5795 5796 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5797 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5798 VMovVT, false, VMOVModImm); 5799 if (NewVal != SDValue()) { 5800 SDLoc DL(Op); 5801 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5802 NewVal); 5803 if (IsDouble) 5804 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5805 5806 // It's a float: cast and extract a vector element. 5807 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5808 VecConstant); 5809 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5810 DAG.getConstant(0, DL, MVT::i32)); 5811 } 5812 5813 // Finally, try a VMVN.i32 5814 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5815 false, VMVNModImm); 5816 if (NewVal != SDValue()) { 5817 SDLoc DL(Op); 5818 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5819 5820 if (IsDouble) 5821 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5822 5823 // It's a float: cast and extract a vector element. 5824 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5825 VecConstant); 5826 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5827 DAG.getConstant(0, DL, MVT::i32)); 5828 } 5829 5830 return SDValue(); 5831 } 5832 5833 // check if an VEXT instruction can handle the shuffle mask when the 5834 // vector sources of the shuffle are the same. 5835 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5836 unsigned NumElts = VT.getVectorNumElements(); 5837 5838 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5839 if (M[0] < 0) 5840 return false; 5841 5842 Imm = M[0]; 5843 5844 // If this is a VEXT shuffle, the immediate value is the index of the first 5845 // element. The other shuffle indices must be the successive elements after 5846 // the first one. 5847 unsigned ExpectedElt = Imm; 5848 for (unsigned i = 1; i < NumElts; ++i) { 5849 // Increment the expected index. If it wraps around, just follow it 5850 // back to index zero and keep going. 5851 ++ExpectedElt; 5852 if (ExpectedElt == NumElts) 5853 ExpectedElt = 0; 5854 5855 if (M[i] < 0) continue; // ignore UNDEF indices 5856 if (ExpectedElt != static_cast<unsigned>(M[i])) 5857 return false; 5858 } 5859 5860 return true; 5861 } 5862 5863 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5864 bool &ReverseVEXT, unsigned &Imm) { 5865 unsigned NumElts = VT.getVectorNumElements(); 5866 ReverseVEXT = false; 5867 5868 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5869 if (M[0] < 0) 5870 return false; 5871 5872 Imm = M[0]; 5873 5874 // If this is a VEXT shuffle, the immediate value is the index of the first 5875 // element. The other shuffle indices must be the successive elements after 5876 // the first one. 5877 unsigned ExpectedElt = Imm; 5878 for (unsigned i = 1; i < NumElts; ++i) { 5879 // Increment the expected index. If it wraps around, it may still be 5880 // a VEXT but the source vectors must be swapped. 5881 ExpectedElt += 1; 5882 if (ExpectedElt == NumElts * 2) { 5883 ExpectedElt = 0; 5884 ReverseVEXT = true; 5885 } 5886 5887 if (M[i] < 0) continue; // ignore UNDEF indices 5888 if (ExpectedElt != static_cast<unsigned>(M[i])) 5889 return false; 5890 } 5891 5892 // Adjust the index value if the source operands will be swapped. 5893 if (ReverseVEXT) 5894 Imm -= NumElts; 5895 5896 return true; 5897 } 5898 5899 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5900 /// instruction with the specified blocksize. (The order of the elements 5901 /// within each block of the vector is reversed.) 5902 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5903 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5904 "Only possible block sizes for VREV are: 16, 32, 64"); 5905 5906 unsigned EltSz = VT.getScalarSizeInBits(); 5907 if (EltSz == 64) 5908 return false; 5909 5910 unsigned NumElts = VT.getVectorNumElements(); 5911 unsigned BlockElts = M[0] + 1; 5912 // If the first shuffle index is UNDEF, be optimistic. 5913 if (M[0] < 0) 5914 BlockElts = BlockSize / EltSz; 5915 5916 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5917 return false; 5918 5919 for (unsigned i = 0; i < NumElts; ++i) { 5920 if (M[i] < 0) continue; // ignore UNDEF indices 5921 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5922 return false; 5923 } 5924 5925 return true; 5926 } 5927 5928 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5929 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5930 // range, then 0 is placed into the resulting vector. So pretty much any mask 5931 // of 8 elements can work here. 5932 return VT == MVT::v8i8 && M.size() == 8; 5933 } 5934 5935 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 5936 unsigned Index) { 5937 if (Mask.size() == Elements * 2) 5938 return Index / Elements; 5939 return Mask[Index] == 0 ? 0 : 1; 5940 } 5941 5942 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5943 // checking that pairs of elements in the shuffle mask represent the same index 5944 // in each vector, incrementing the expected index by 2 at each step. 5945 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5946 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5947 // v2={e,f,g,h} 5948 // WhichResult gives the offset for each element in the mask based on which 5949 // of the two results it belongs to. 5950 // 5951 // The transpose can be represented either as: 5952 // result1 = shufflevector v1, v2, result1_shuffle_mask 5953 // result2 = shufflevector v1, v2, result2_shuffle_mask 5954 // where v1/v2 and the shuffle masks have the same number of elements 5955 // (here WhichResult (see below) indicates which result is being checked) 5956 // 5957 // or as: 5958 // results = shufflevector v1, v2, shuffle_mask 5959 // where both results are returned in one vector and the shuffle mask has twice 5960 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5961 // want to check the low half and high half of the shuffle mask as if it were 5962 // the other case 5963 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5964 unsigned EltSz = VT.getScalarSizeInBits(); 5965 if (EltSz == 64) 5966 return false; 5967 5968 unsigned NumElts = VT.getVectorNumElements(); 5969 if (M.size() != NumElts && M.size() != NumElts*2) 5970 return false; 5971 5972 // If the mask is twice as long as the input vector then we need to check the 5973 // upper and lower parts of the mask with a matching value for WhichResult 5974 // FIXME: A mask with only even values will be rejected in case the first 5975 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5976 // M[0] is used to determine WhichResult 5977 for (unsigned i = 0; i < M.size(); i += NumElts) { 5978 WhichResult = SelectPairHalf(NumElts, M, i); 5979 for (unsigned j = 0; j < NumElts; j += 2) { 5980 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5981 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5982 return false; 5983 } 5984 } 5985 5986 if (M.size() == NumElts*2) 5987 WhichResult = 0; 5988 5989 return true; 5990 } 5991 5992 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5993 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5994 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5995 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5996 unsigned EltSz = VT.getScalarSizeInBits(); 5997 if (EltSz == 64) 5998 return false; 5999 6000 unsigned NumElts = VT.getVectorNumElements(); 6001 if (M.size() != NumElts && M.size() != NumElts*2) 6002 return false; 6003 6004 for (unsigned i = 0; i < M.size(); i += NumElts) { 6005 WhichResult = SelectPairHalf(NumElts, M, i); 6006 for (unsigned j = 0; j < NumElts; j += 2) { 6007 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6008 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6009 return false; 6010 } 6011 } 6012 6013 if (M.size() == NumElts*2) 6014 WhichResult = 0; 6015 6016 return true; 6017 } 6018 6019 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6020 // that the mask elements are either all even and in steps of size 2 or all odd 6021 // and in steps of size 2. 6022 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6023 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6024 // v2={e,f,g,h} 6025 // Requires similar checks to that of isVTRNMask with 6026 // respect the how results are returned. 6027 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6028 unsigned EltSz = VT.getScalarSizeInBits(); 6029 if (EltSz == 64) 6030 return false; 6031 6032 unsigned NumElts = VT.getVectorNumElements(); 6033 if (M.size() != NumElts && M.size() != NumElts*2) 6034 return false; 6035 6036 for (unsigned i = 0; i < M.size(); i += NumElts) { 6037 WhichResult = SelectPairHalf(NumElts, M, i); 6038 for (unsigned j = 0; j < NumElts; ++j) { 6039 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6040 return false; 6041 } 6042 } 6043 6044 if (M.size() == NumElts*2) 6045 WhichResult = 0; 6046 6047 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6048 if (VT.is64BitVector() && EltSz == 32) 6049 return false; 6050 6051 return true; 6052 } 6053 6054 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6055 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6056 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6057 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6058 unsigned EltSz = VT.getScalarSizeInBits(); 6059 if (EltSz == 64) 6060 return false; 6061 6062 unsigned NumElts = VT.getVectorNumElements(); 6063 if (M.size() != NumElts && M.size() != NumElts*2) 6064 return false; 6065 6066 unsigned Half = NumElts / 2; 6067 for (unsigned i = 0; i < M.size(); i += NumElts) { 6068 WhichResult = SelectPairHalf(NumElts, M, i); 6069 for (unsigned j = 0; j < NumElts; j += Half) { 6070 unsigned Idx = WhichResult; 6071 for (unsigned k = 0; k < Half; ++k) { 6072 int MIdx = M[i + j + k]; 6073 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6074 return false; 6075 Idx += 2; 6076 } 6077 } 6078 } 6079 6080 if (M.size() == NumElts*2) 6081 WhichResult = 0; 6082 6083 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6084 if (VT.is64BitVector() && EltSz == 32) 6085 return false; 6086 6087 return true; 6088 } 6089 6090 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6091 // that pairs of elements of the shufflemask represent the same index in each 6092 // vector incrementing sequentially through the vectors. 6093 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6094 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6095 // v2={e,f,g,h} 6096 // Requires similar checks to that of isVTRNMask with respect the how results 6097 // are returned. 6098 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6099 unsigned EltSz = VT.getScalarSizeInBits(); 6100 if (EltSz == 64) 6101 return false; 6102 6103 unsigned NumElts = VT.getVectorNumElements(); 6104 if (M.size() != NumElts && M.size() != NumElts*2) 6105 return false; 6106 6107 for (unsigned i = 0; i < M.size(); i += NumElts) { 6108 WhichResult = SelectPairHalf(NumElts, M, i); 6109 unsigned Idx = WhichResult * NumElts / 2; 6110 for (unsigned j = 0; j < NumElts; j += 2) { 6111 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6112 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6113 return false; 6114 Idx += 1; 6115 } 6116 } 6117 6118 if (M.size() == NumElts*2) 6119 WhichResult = 0; 6120 6121 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6122 if (VT.is64BitVector() && EltSz == 32) 6123 return false; 6124 6125 return true; 6126 } 6127 6128 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6129 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6130 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6131 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6132 unsigned EltSz = VT.getScalarSizeInBits(); 6133 if (EltSz == 64) 6134 return false; 6135 6136 unsigned NumElts = VT.getVectorNumElements(); 6137 if (M.size() != NumElts && M.size() != NumElts*2) 6138 return false; 6139 6140 for (unsigned i = 0; i < M.size(); i += NumElts) { 6141 WhichResult = SelectPairHalf(NumElts, M, i); 6142 unsigned Idx = WhichResult * NumElts / 2; 6143 for (unsigned j = 0; j < NumElts; j += 2) { 6144 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6145 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6146 return false; 6147 Idx += 1; 6148 } 6149 } 6150 6151 if (M.size() == NumElts*2) 6152 WhichResult = 0; 6153 6154 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6155 if (VT.is64BitVector() && EltSz == 32) 6156 return false; 6157 6158 return true; 6159 } 6160 6161 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6162 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6163 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6164 unsigned &WhichResult, 6165 bool &isV_UNDEF) { 6166 isV_UNDEF = false; 6167 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6168 return ARMISD::VTRN; 6169 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6170 return ARMISD::VUZP; 6171 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6172 return ARMISD::VZIP; 6173 6174 isV_UNDEF = true; 6175 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6176 return ARMISD::VTRN; 6177 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6178 return ARMISD::VUZP; 6179 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6180 return ARMISD::VZIP; 6181 6182 return 0; 6183 } 6184 6185 /// \return true if this is a reverse operation on an vector. 6186 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6187 unsigned NumElts = VT.getVectorNumElements(); 6188 // Make sure the mask has the right size. 6189 if (NumElts != M.size()) 6190 return false; 6191 6192 // Look for <15, ..., 3, -1, 1, 0>. 6193 for (unsigned i = 0; i != NumElts; ++i) 6194 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6195 return false; 6196 6197 return true; 6198 } 6199 6200 // If N is an integer constant that can be moved into a register in one 6201 // instruction, return an SDValue of such a constant (will become a MOV 6202 // instruction). Otherwise return null. 6203 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6204 const ARMSubtarget *ST, const SDLoc &dl) { 6205 uint64_t Val; 6206 if (!isa<ConstantSDNode>(N)) 6207 return SDValue(); 6208 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6209 6210 if (ST->isThumb1Only()) { 6211 if (Val <= 255 || ~Val <= 255) 6212 return DAG.getConstant(Val, dl, MVT::i32); 6213 } else { 6214 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6215 return DAG.getConstant(Val, dl, MVT::i32); 6216 } 6217 return SDValue(); 6218 } 6219 6220 // If this is a case we can't handle, return null and let the default 6221 // expansion code take care of it. 6222 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6223 const ARMSubtarget *ST) const { 6224 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6225 SDLoc dl(Op); 6226 EVT VT = Op.getValueType(); 6227 6228 APInt SplatBits, SplatUndef; 6229 unsigned SplatBitSize; 6230 bool HasAnyUndefs; 6231 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6232 if (SplatUndef.isAllOnesValue()) 6233 return DAG.getUNDEF(VT); 6234 6235 if (SplatBitSize <= 64) { 6236 // Check if an immediate VMOV works. 6237 EVT VmovVT; 6238 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6239 SplatUndef.getZExtValue(), SplatBitSize, 6240 DAG, dl, VmovVT, VT.is128BitVector(), 6241 VMOVModImm); 6242 if (Val.getNode()) { 6243 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6244 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6245 } 6246 6247 // Try an immediate VMVN. 6248 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6249 Val = isNEONModifiedImm(NegatedImm, 6250 SplatUndef.getZExtValue(), SplatBitSize, 6251 DAG, dl, VmovVT, VT.is128BitVector(), 6252 VMVNModImm); 6253 if (Val.getNode()) { 6254 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6255 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6256 } 6257 6258 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6259 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6260 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6261 if (ImmVal != -1) { 6262 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6263 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6264 } 6265 } 6266 } 6267 } 6268 6269 // Scan through the operands to see if only one value is used. 6270 // 6271 // As an optimisation, even if more than one value is used it may be more 6272 // profitable to splat with one value then change some lanes. 6273 // 6274 // Heuristically we decide to do this if the vector has a "dominant" value, 6275 // defined as splatted to more than half of the lanes. 6276 unsigned NumElts = VT.getVectorNumElements(); 6277 bool isOnlyLowElement = true; 6278 bool usesOnlyOneValue = true; 6279 bool hasDominantValue = false; 6280 bool isConstant = true; 6281 6282 // Map of the number of times a particular SDValue appears in the 6283 // element list. 6284 DenseMap<SDValue, unsigned> ValueCounts; 6285 SDValue Value; 6286 for (unsigned i = 0; i < NumElts; ++i) { 6287 SDValue V = Op.getOperand(i); 6288 if (V.isUndef()) 6289 continue; 6290 if (i > 0) 6291 isOnlyLowElement = false; 6292 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6293 isConstant = false; 6294 6295 ValueCounts.insert(std::make_pair(V, 0)); 6296 unsigned &Count = ValueCounts[V]; 6297 6298 // Is this value dominant? (takes up more than half of the lanes) 6299 if (++Count > (NumElts / 2)) { 6300 hasDominantValue = true; 6301 Value = V; 6302 } 6303 } 6304 if (ValueCounts.size() != 1) 6305 usesOnlyOneValue = false; 6306 if (!Value.getNode() && !ValueCounts.empty()) 6307 Value = ValueCounts.begin()->first; 6308 6309 if (ValueCounts.empty()) 6310 return DAG.getUNDEF(VT); 6311 6312 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6313 // Keep going if we are hitting this case. 6314 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6315 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6316 6317 unsigned EltSize = VT.getScalarSizeInBits(); 6318 6319 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6320 // i32 and try again. 6321 if (hasDominantValue && EltSize <= 32) { 6322 if (!isConstant) { 6323 SDValue N; 6324 6325 // If we are VDUPing a value that comes directly from a vector, that will 6326 // cause an unnecessary move to and from a GPR, where instead we could 6327 // just use VDUPLANE. We can only do this if the lane being extracted 6328 // is at a constant index, as the VDUP from lane instructions only have 6329 // constant-index forms. 6330 ConstantSDNode *constIndex; 6331 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6332 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6333 // We need to create a new undef vector to use for the VDUPLANE if the 6334 // size of the vector from which we get the value is different than the 6335 // size of the vector that we need to create. We will insert the element 6336 // such that the register coalescer will remove unnecessary copies. 6337 if (VT != Value->getOperand(0).getValueType()) { 6338 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6339 VT.getVectorNumElements(); 6340 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6341 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6342 Value, DAG.getConstant(index, dl, MVT::i32)), 6343 DAG.getConstant(index, dl, MVT::i32)); 6344 } else 6345 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6346 Value->getOperand(0), Value->getOperand(1)); 6347 } else 6348 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6349 6350 if (!usesOnlyOneValue) { 6351 // The dominant value was splatted as 'N', but we now have to insert 6352 // all differing elements. 6353 for (unsigned I = 0; I < NumElts; ++I) { 6354 if (Op.getOperand(I) == Value) 6355 continue; 6356 SmallVector<SDValue, 3> Ops; 6357 Ops.push_back(N); 6358 Ops.push_back(Op.getOperand(I)); 6359 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6360 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6361 } 6362 } 6363 return N; 6364 } 6365 if (VT.getVectorElementType().isFloatingPoint()) { 6366 SmallVector<SDValue, 8> Ops; 6367 for (unsigned i = 0; i < NumElts; ++i) 6368 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6369 Op.getOperand(i))); 6370 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6371 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6372 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6373 if (Val.getNode()) 6374 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6375 } 6376 if (usesOnlyOneValue) { 6377 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6378 if (isConstant && Val.getNode()) 6379 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6380 } 6381 } 6382 6383 // If all elements are constants and the case above didn't get hit, fall back 6384 // to the default expansion, which will generate a load from the constant 6385 // pool. 6386 if (isConstant) 6387 return SDValue(); 6388 6389 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6390 if (NumElts >= 4) { 6391 SDValue shuffle = ReconstructShuffle(Op, DAG); 6392 if (shuffle != SDValue()) 6393 return shuffle; 6394 } 6395 6396 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6397 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6398 // into two 64-bit vectors; we might discover a better way to lower it. 6399 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6400 EVT ExtVT = VT.getVectorElementType(); 6401 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6402 SDValue Lower = 6403 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6404 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6405 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6406 SDValue Upper = DAG.getBuildVector( 6407 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6408 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6409 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6410 if (Lower && Upper) 6411 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6412 } 6413 6414 // Vectors with 32- or 64-bit elements can be built by directly assigning 6415 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6416 // will be legalized. 6417 if (EltSize >= 32) { 6418 // Do the expansion with floating-point types, since that is what the VFP 6419 // registers are defined to use, and since i64 is not legal. 6420 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6421 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6422 SmallVector<SDValue, 8> Ops; 6423 for (unsigned i = 0; i < NumElts; ++i) 6424 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6425 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6426 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6427 } 6428 6429 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6430 // know the default expansion would otherwise fall back on something even 6431 // worse. For a vector with one or two non-undef values, that's 6432 // scalar_to_vector for the elements followed by a shuffle (provided the 6433 // shuffle is valid for the target) and materialization element by element 6434 // on the stack followed by a load for everything else. 6435 if (!isConstant && !usesOnlyOneValue) { 6436 SDValue Vec = DAG.getUNDEF(VT); 6437 for (unsigned i = 0 ; i < NumElts; ++i) { 6438 SDValue V = Op.getOperand(i); 6439 if (V.isUndef()) 6440 continue; 6441 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6442 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6443 } 6444 return Vec; 6445 } 6446 6447 return SDValue(); 6448 } 6449 6450 // Gather data to see if the operation can be modelled as a 6451 // shuffle in combination with VEXTs. 6452 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6453 SelectionDAG &DAG) const { 6454 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6455 SDLoc dl(Op); 6456 EVT VT = Op.getValueType(); 6457 unsigned NumElts = VT.getVectorNumElements(); 6458 6459 struct ShuffleSourceInfo { 6460 SDValue Vec; 6461 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6462 unsigned MaxElt = 0; 6463 6464 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6465 // be compatible with the shuffle we intend to construct. As a result 6466 // ShuffleVec will be some sliding window into the original Vec. 6467 SDValue ShuffleVec; 6468 6469 // Code should guarantee that element i in Vec starts at element "WindowBase 6470 // + i * WindowScale in ShuffleVec". 6471 int WindowBase = 0; 6472 int WindowScale = 1; 6473 6474 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6475 6476 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6477 }; 6478 6479 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6480 // node. 6481 SmallVector<ShuffleSourceInfo, 2> Sources; 6482 for (unsigned i = 0; i < NumElts; ++i) { 6483 SDValue V = Op.getOperand(i); 6484 if (V.isUndef()) 6485 continue; 6486 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6487 // A shuffle can only come from building a vector from various 6488 // elements of other vectors. 6489 return SDValue(); 6490 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6491 // Furthermore, shuffles require a constant mask, whereas extractelts 6492 // accept variable indices. 6493 return SDValue(); 6494 } 6495 6496 // Add this element source to the list if it's not already there. 6497 SDValue SourceVec = V.getOperand(0); 6498 auto Source = llvm::find(Sources, SourceVec); 6499 if (Source == Sources.end()) 6500 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6501 6502 // Update the minimum and maximum lane number seen. 6503 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6504 Source->MinElt = std::min(Source->MinElt, EltNo); 6505 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6506 } 6507 6508 // Currently only do something sane when at most two source vectors 6509 // are involved. 6510 if (Sources.size() > 2) 6511 return SDValue(); 6512 6513 // Find out the smallest element size among result and two sources, and use 6514 // it as element size to build the shuffle_vector. 6515 EVT SmallestEltTy = VT.getVectorElementType(); 6516 for (auto &Source : Sources) { 6517 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6518 if (SrcEltTy.bitsLT(SmallestEltTy)) 6519 SmallestEltTy = SrcEltTy; 6520 } 6521 unsigned ResMultiplier = 6522 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6523 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6524 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6525 6526 // If the source vector is too wide or too narrow, we may nevertheless be able 6527 // to construct a compatible shuffle either by concatenating it with UNDEF or 6528 // extracting a suitable range of elements. 6529 for (auto &Src : Sources) { 6530 EVT SrcVT = Src.ShuffleVec.getValueType(); 6531 6532 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6533 continue; 6534 6535 // This stage of the search produces a source with the same element type as 6536 // the original, but with a total width matching the BUILD_VECTOR output. 6537 EVT EltVT = SrcVT.getVectorElementType(); 6538 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6539 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6540 6541 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6542 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6543 return SDValue(); 6544 // We can pad out the smaller vector for free, so if it's part of a 6545 // shuffle... 6546 Src.ShuffleVec = 6547 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6548 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6549 continue; 6550 } 6551 6552 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6553 return SDValue(); 6554 6555 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6556 // Span too large for a VEXT to cope 6557 return SDValue(); 6558 } 6559 6560 if (Src.MinElt >= NumSrcElts) { 6561 // The extraction can just take the second half 6562 Src.ShuffleVec = 6563 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6564 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6565 Src.WindowBase = -NumSrcElts; 6566 } else if (Src.MaxElt < NumSrcElts) { 6567 // The extraction can just take the first half 6568 Src.ShuffleVec = 6569 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6570 DAG.getConstant(0, dl, MVT::i32)); 6571 } else { 6572 // An actual VEXT is needed 6573 SDValue VEXTSrc1 = 6574 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6575 DAG.getConstant(0, dl, MVT::i32)); 6576 SDValue VEXTSrc2 = 6577 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6578 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6579 6580 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6581 VEXTSrc2, 6582 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6583 Src.WindowBase = -Src.MinElt; 6584 } 6585 } 6586 6587 // Another possible incompatibility occurs from the vector element types. We 6588 // can fix this by bitcasting the source vectors to the same type we intend 6589 // for the shuffle. 6590 for (auto &Src : Sources) { 6591 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6592 if (SrcEltTy == SmallestEltTy) 6593 continue; 6594 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6595 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6596 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6597 Src.WindowBase *= Src.WindowScale; 6598 } 6599 6600 // Final sanity check before we try to actually produce a shuffle. 6601 DEBUG( 6602 for (auto Src : Sources) 6603 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6604 ); 6605 6606 // The stars all align, our next step is to produce the mask for the shuffle. 6607 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6608 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6609 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6610 SDValue Entry = Op.getOperand(i); 6611 if (Entry.isUndef()) 6612 continue; 6613 6614 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6615 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6616 6617 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6618 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6619 // segment. 6620 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6621 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6622 VT.getScalarSizeInBits()); 6623 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6624 6625 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6626 // starting at the appropriate offset. 6627 int *LaneMask = &Mask[i * ResMultiplier]; 6628 6629 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6630 ExtractBase += NumElts * (Src - Sources.begin()); 6631 for (int j = 0; j < LanesDefined; ++j) 6632 LaneMask[j] = ExtractBase + j; 6633 } 6634 6635 // Final check before we try to produce nonsense... 6636 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6637 return SDValue(); 6638 6639 // We can't handle more than two sources. This should have already 6640 // been checked before this point. 6641 assert(Sources.size() <= 2 && "Too many sources!"); 6642 6643 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6644 for (unsigned i = 0; i < Sources.size(); ++i) 6645 ShuffleOps[i] = Sources[i].ShuffleVec; 6646 6647 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6648 ShuffleOps[1], Mask); 6649 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6650 } 6651 6652 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6653 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6654 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6655 /// are assumed to be legal. 6656 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6657 if (VT.getVectorNumElements() == 4 && 6658 (VT.is128BitVector() || VT.is64BitVector())) { 6659 unsigned PFIndexes[4]; 6660 for (unsigned i = 0; i != 4; ++i) { 6661 if (M[i] < 0) 6662 PFIndexes[i] = 8; 6663 else 6664 PFIndexes[i] = M[i]; 6665 } 6666 6667 // Compute the index in the perfect shuffle table. 6668 unsigned PFTableIndex = 6669 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6670 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6671 unsigned Cost = (PFEntry >> 30); 6672 6673 if (Cost <= 4) 6674 return true; 6675 } 6676 6677 bool ReverseVEXT, isV_UNDEF; 6678 unsigned Imm, WhichResult; 6679 6680 unsigned EltSize = VT.getScalarSizeInBits(); 6681 return (EltSize >= 32 || 6682 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6683 isVREVMask(M, VT, 64) || 6684 isVREVMask(M, VT, 32) || 6685 isVREVMask(M, VT, 16) || 6686 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6687 isVTBLMask(M, VT) || 6688 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6689 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6690 } 6691 6692 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6693 /// the specified operations to build the shuffle. 6694 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6695 SDValue RHS, SelectionDAG &DAG, 6696 const SDLoc &dl) { 6697 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6698 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6699 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6700 6701 enum { 6702 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6703 OP_VREV, 6704 OP_VDUP0, 6705 OP_VDUP1, 6706 OP_VDUP2, 6707 OP_VDUP3, 6708 OP_VEXT1, 6709 OP_VEXT2, 6710 OP_VEXT3, 6711 OP_VUZPL, // VUZP, left result 6712 OP_VUZPR, // VUZP, right result 6713 OP_VZIPL, // VZIP, left result 6714 OP_VZIPR, // VZIP, right result 6715 OP_VTRNL, // VTRN, left result 6716 OP_VTRNR // VTRN, right result 6717 }; 6718 6719 if (OpNum == OP_COPY) { 6720 if (LHSID == (1*9+2)*9+3) return LHS; 6721 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6722 return RHS; 6723 } 6724 6725 SDValue OpLHS, OpRHS; 6726 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6727 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6728 EVT VT = OpLHS.getValueType(); 6729 6730 switch (OpNum) { 6731 default: llvm_unreachable("Unknown shuffle opcode!"); 6732 case OP_VREV: 6733 // VREV divides the vector in half and swaps within the half. 6734 if (VT.getVectorElementType() == MVT::i32 || 6735 VT.getVectorElementType() == MVT::f32) 6736 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6737 // vrev <4 x i16> -> VREV32 6738 if (VT.getVectorElementType() == MVT::i16) 6739 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6740 // vrev <4 x i8> -> VREV16 6741 assert(VT.getVectorElementType() == MVT::i8); 6742 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6743 case OP_VDUP0: 6744 case OP_VDUP1: 6745 case OP_VDUP2: 6746 case OP_VDUP3: 6747 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6748 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6749 case OP_VEXT1: 6750 case OP_VEXT2: 6751 case OP_VEXT3: 6752 return DAG.getNode(ARMISD::VEXT, dl, VT, 6753 OpLHS, OpRHS, 6754 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6755 case OP_VUZPL: 6756 case OP_VUZPR: 6757 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6758 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6759 case OP_VZIPL: 6760 case OP_VZIPR: 6761 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6762 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6763 case OP_VTRNL: 6764 case OP_VTRNR: 6765 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6766 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6767 } 6768 } 6769 6770 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6771 ArrayRef<int> ShuffleMask, 6772 SelectionDAG &DAG) { 6773 // Check to see if we can use the VTBL instruction. 6774 SDValue V1 = Op.getOperand(0); 6775 SDValue V2 = Op.getOperand(1); 6776 SDLoc DL(Op); 6777 6778 SmallVector<SDValue, 8> VTBLMask; 6779 for (ArrayRef<int>::iterator 6780 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6781 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6782 6783 if (V2.getNode()->isUndef()) 6784 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6785 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6786 6787 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6788 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6789 } 6790 6791 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6792 SelectionDAG &DAG) { 6793 SDLoc DL(Op); 6794 SDValue OpLHS = Op.getOperand(0); 6795 EVT VT = OpLHS.getValueType(); 6796 6797 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6798 "Expect an v8i16/v16i8 type"); 6799 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6800 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6801 // extract the first 8 bytes into the top double word and the last 8 bytes 6802 // into the bottom double word. The v8i16 case is similar. 6803 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6804 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6805 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6806 } 6807 6808 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6809 SDValue V1 = Op.getOperand(0); 6810 SDValue V2 = Op.getOperand(1); 6811 SDLoc dl(Op); 6812 EVT VT = Op.getValueType(); 6813 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6814 6815 // Convert shuffles that are directly supported on NEON to target-specific 6816 // DAG nodes, instead of keeping them as shuffles and matching them again 6817 // during code selection. This is more efficient and avoids the possibility 6818 // of inconsistencies between legalization and selection. 6819 // FIXME: floating-point vectors should be canonicalized to integer vectors 6820 // of the same time so that they get CSEd properly. 6821 ArrayRef<int> ShuffleMask = SVN->getMask(); 6822 6823 unsigned EltSize = VT.getScalarSizeInBits(); 6824 if (EltSize <= 32) { 6825 if (SVN->isSplat()) { 6826 int Lane = SVN->getSplatIndex(); 6827 // If this is undef splat, generate it via "just" vdup, if possible. 6828 if (Lane == -1) Lane = 0; 6829 6830 // Test if V1 is a SCALAR_TO_VECTOR. 6831 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6832 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6833 } 6834 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6835 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6836 // reaches it). 6837 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6838 !isa<ConstantSDNode>(V1.getOperand(0))) { 6839 bool IsScalarToVector = true; 6840 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6841 if (!V1.getOperand(i).isUndef()) { 6842 IsScalarToVector = false; 6843 break; 6844 } 6845 if (IsScalarToVector) 6846 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6847 } 6848 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6849 DAG.getConstant(Lane, dl, MVT::i32)); 6850 } 6851 6852 bool ReverseVEXT; 6853 unsigned Imm; 6854 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6855 if (ReverseVEXT) 6856 std::swap(V1, V2); 6857 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6858 DAG.getConstant(Imm, dl, MVT::i32)); 6859 } 6860 6861 if (isVREVMask(ShuffleMask, VT, 64)) 6862 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6863 if (isVREVMask(ShuffleMask, VT, 32)) 6864 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6865 if (isVREVMask(ShuffleMask, VT, 16)) 6866 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6867 6868 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6869 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6870 DAG.getConstant(Imm, dl, MVT::i32)); 6871 } 6872 6873 // Check for Neon shuffles that modify both input vectors in place. 6874 // If both results are used, i.e., if there are two shuffles with the same 6875 // source operands and with masks corresponding to both results of one of 6876 // these operations, DAG memoization will ensure that a single node is 6877 // used for both shuffles. 6878 unsigned WhichResult; 6879 bool isV_UNDEF; 6880 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6881 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6882 if (isV_UNDEF) 6883 V2 = V1; 6884 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6885 .getValue(WhichResult); 6886 } 6887 6888 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6889 // shuffles that produce a result larger than their operands with: 6890 // shuffle(concat(v1, undef), concat(v2, undef)) 6891 // -> 6892 // shuffle(concat(v1, v2), undef) 6893 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6894 // 6895 // This is useful in the general case, but there are special cases where 6896 // native shuffles produce larger results: the two-result ops. 6897 // 6898 // Look through the concat when lowering them: 6899 // shuffle(concat(v1, v2), undef) 6900 // -> 6901 // concat(VZIP(v1, v2):0, :1) 6902 // 6903 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6904 SDValue SubV1 = V1->getOperand(0); 6905 SDValue SubV2 = V1->getOperand(1); 6906 EVT SubVT = SubV1.getValueType(); 6907 6908 // We expect these to have been canonicalized to -1. 6909 assert(llvm::all_of(ShuffleMask, [&](int i) { 6910 return i < (int)VT.getVectorNumElements(); 6911 }) && "Unexpected shuffle index into UNDEF operand!"); 6912 6913 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6914 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6915 if (isV_UNDEF) 6916 SubV2 = SubV1; 6917 assert((WhichResult == 0) && 6918 "In-place shuffle of concat can only have one result!"); 6919 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6920 SubV1, SubV2); 6921 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6922 Res.getValue(1)); 6923 } 6924 } 6925 } 6926 6927 // If the shuffle is not directly supported and it has 4 elements, use 6928 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6929 unsigned NumElts = VT.getVectorNumElements(); 6930 if (NumElts == 4) { 6931 unsigned PFIndexes[4]; 6932 for (unsigned i = 0; i != 4; ++i) { 6933 if (ShuffleMask[i] < 0) 6934 PFIndexes[i] = 8; 6935 else 6936 PFIndexes[i] = ShuffleMask[i]; 6937 } 6938 6939 // Compute the index in the perfect shuffle table. 6940 unsigned PFTableIndex = 6941 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6942 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6943 unsigned Cost = (PFEntry >> 30); 6944 6945 if (Cost <= 4) 6946 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6947 } 6948 6949 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6950 if (EltSize >= 32) { 6951 // Do the expansion with floating-point types, since that is what the VFP 6952 // registers are defined to use, and since i64 is not legal. 6953 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6954 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6955 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6956 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6957 SmallVector<SDValue, 8> Ops; 6958 for (unsigned i = 0; i < NumElts; ++i) { 6959 if (ShuffleMask[i] < 0) 6960 Ops.push_back(DAG.getUNDEF(EltVT)); 6961 else 6962 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6963 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6964 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6965 dl, MVT::i32))); 6966 } 6967 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6968 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6969 } 6970 6971 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6972 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6973 6974 if (VT == MVT::v8i8) 6975 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6976 return NewOp; 6977 6978 return SDValue(); 6979 } 6980 6981 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6982 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6983 SDValue Lane = Op.getOperand(2); 6984 if (!isa<ConstantSDNode>(Lane)) 6985 return SDValue(); 6986 6987 return Op; 6988 } 6989 6990 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6991 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6992 SDValue Lane = Op.getOperand(1); 6993 if (!isa<ConstantSDNode>(Lane)) 6994 return SDValue(); 6995 6996 SDValue Vec = Op.getOperand(0); 6997 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 6998 SDLoc dl(Op); 6999 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7000 } 7001 7002 return Op; 7003 } 7004 7005 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7006 // The only time a CONCAT_VECTORS operation can have legal types is when 7007 // two 64-bit vectors are concatenated to a 128-bit vector. 7008 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7009 "unexpected CONCAT_VECTORS"); 7010 SDLoc dl(Op); 7011 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7012 SDValue Op0 = Op.getOperand(0); 7013 SDValue Op1 = Op.getOperand(1); 7014 if (!Op0.isUndef()) 7015 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7016 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7017 DAG.getIntPtrConstant(0, dl)); 7018 if (!Op1.isUndef()) 7019 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7020 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7021 DAG.getIntPtrConstant(1, dl)); 7022 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7023 } 7024 7025 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7026 /// element has been zero/sign-extended, depending on the isSigned parameter, 7027 /// from an integer type half its size. 7028 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7029 bool isSigned) { 7030 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7031 EVT VT = N->getValueType(0); 7032 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7033 SDNode *BVN = N->getOperand(0).getNode(); 7034 if (BVN->getValueType(0) != MVT::v4i32 || 7035 BVN->getOpcode() != ISD::BUILD_VECTOR) 7036 return false; 7037 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7038 unsigned HiElt = 1 - LoElt; 7039 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7040 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7041 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7042 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7043 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7044 return false; 7045 if (isSigned) { 7046 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7047 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7048 return true; 7049 } else { 7050 if (Hi0->isNullValue() && Hi1->isNullValue()) 7051 return true; 7052 } 7053 return false; 7054 } 7055 7056 if (N->getOpcode() != ISD::BUILD_VECTOR) 7057 return false; 7058 7059 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7060 SDNode *Elt = N->getOperand(i).getNode(); 7061 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7062 unsigned EltSize = VT.getScalarSizeInBits(); 7063 unsigned HalfSize = EltSize / 2; 7064 if (isSigned) { 7065 if (!isIntN(HalfSize, C->getSExtValue())) 7066 return false; 7067 } else { 7068 if (!isUIntN(HalfSize, C->getZExtValue())) 7069 return false; 7070 } 7071 continue; 7072 } 7073 return false; 7074 } 7075 7076 return true; 7077 } 7078 7079 /// isSignExtended - Check if a node is a vector value that is sign-extended 7080 /// or a constant BUILD_VECTOR with sign-extended elements. 7081 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7082 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7083 return true; 7084 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7085 return true; 7086 return false; 7087 } 7088 7089 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7090 /// or a constant BUILD_VECTOR with zero-extended elements. 7091 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7092 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7093 return true; 7094 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7095 return true; 7096 return false; 7097 } 7098 7099 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7100 if (OrigVT.getSizeInBits() >= 64) 7101 return OrigVT; 7102 7103 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7104 7105 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7106 switch (OrigSimpleTy) { 7107 default: llvm_unreachable("Unexpected Vector Type"); 7108 case MVT::v2i8: 7109 case MVT::v2i16: 7110 return MVT::v2i32; 7111 case MVT::v4i8: 7112 return MVT::v4i16; 7113 } 7114 } 7115 7116 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7117 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7118 /// We insert the required extension here to get the vector to fill a D register. 7119 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7120 const EVT &OrigTy, 7121 const EVT &ExtTy, 7122 unsigned ExtOpcode) { 7123 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7124 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7125 // 64-bits we need to insert a new extension so that it will be 64-bits. 7126 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7127 if (OrigTy.getSizeInBits() >= 64) 7128 return N; 7129 7130 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7131 EVT NewVT = getExtensionTo64Bits(OrigTy); 7132 7133 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7134 } 7135 7136 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7137 /// does not do any sign/zero extension. If the original vector is less 7138 /// than 64 bits, an appropriate extension will be added after the load to 7139 /// reach a total size of 64 bits. We have to add the extension separately 7140 /// because ARM does not have a sign/zero extending load for vectors. 7141 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7142 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7143 7144 // The load already has the right type. 7145 if (ExtendedTy == LD->getMemoryVT()) 7146 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7147 LD->getBasePtr(), LD->getPointerInfo(), 7148 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7149 7150 // We need to create a zextload/sextload. We cannot just create a load 7151 // followed by a zext/zext node because LowerMUL is also run during normal 7152 // operation legalization where we can't create illegal types. 7153 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7154 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7155 LD->getMemoryVT(), LD->getAlignment(), 7156 LD->getMemOperand()->getFlags()); 7157 } 7158 7159 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7160 /// extending load, or BUILD_VECTOR with extended elements, return the 7161 /// unextended value. The unextended vector should be 64 bits so that it can 7162 /// be used as an operand to a VMULL instruction. If the original vector size 7163 /// before extension is less than 64 bits we add a an extension to resize 7164 /// the vector to 64 bits. 7165 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7166 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7167 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7168 N->getOperand(0)->getValueType(0), 7169 N->getValueType(0), 7170 N->getOpcode()); 7171 7172 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7173 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7174 "Expected extending load"); 7175 7176 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7177 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7178 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7179 SDValue extLoad = 7180 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7181 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7182 7183 return newLoad; 7184 } 7185 7186 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7187 // have been legalized as a BITCAST from v4i32. 7188 if (N->getOpcode() == ISD::BITCAST) { 7189 SDNode *BVN = N->getOperand(0).getNode(); 7190 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7191 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7192 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7193 return DAG.getBuildVector( 7194 MVT::v2i32, SDLoc(N), 7195 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7196 } 7197 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7198 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7199 EVT VT = N->getValueType(0); 7200 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7201 unsigned NumElts = VT.getVectorNumElements(); 7202 MVT TruncVT = MVT::getIntegerVT(EltSize); 7203 SmallVector<SDValue, 8> Ops; 7204 SDLoc dl(N); 7205 for (unsigned i = 0; i != NumElts; ++i) { 7206 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7207 const APInt &CInt = C->getAPIntValue(); 7208 // Element types smaller than 32 bits are not legal, so use i32 elements. 7209 // The values are implicitly truncated so sext vs. zext doesn't matter. 7210 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7211 } 7212 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7213 } 7214 7215 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7216 unsigned Opcode = N->getOpcode(); 7217 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7218 SDNode *N0 = N->getOperand(0).getNode(); 7219 SDNode *N1 = N->getOperand(1).getNode(); 7220 return N0->hasOneUse() && N1->hasOneUse() && 7221 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7222 } 7223 return false; 7224 } 7225 7226 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7227 unsigned Opcode = N->getOpcode(); 7228 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7229 SDNode *N0 = N->getOperand(0).getNode(); 7230 SDNode *N1 = N->getOperand(1).getNode(); 7231 return N0->hasOneUse() && N1->hasOneUse() && 7232 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7233 } 7234 return false; 7235 } 7236 7237 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7238 // Multiplications are only custom-lowered for 128-bit vectors so that 7239 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7240 EVT VT = Op.getValueType(); 7241 assert(VT.is128BitVector() && VT.isInteger() && 7242 "unexpected type for custom-lowering ISD::MUL"); 7243 SDNode *N0 = Op.getOperand(0).getNode(); 7244 SDNode *N1 = Op.getOperand(1).getNode(); 7245 unsigned NewOpc = 0; 7246 bool isMLA = false; 7247 bool isN0SExt = isSignExtended(N0, DAG); 7248 bool isN1SExt = isSignExtended(N1, DAG); 7249 if (isN0SExt && isN1SExt) 7250 NewOpc = ARMISD::VMULLs; 7251 else { 7252 bool isN0ZExt = isZeroExtended(N0, DAG); 7253 bool isN1ZExt = isZeroExtended(N1, DAG); 7254 if (isN0ZExt && isN1ZExt) 7255 NewOpc = ARMISD::VMULLu; 7256 else if (isN1SExt || isN1ZExt) { 7257 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7258 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7259 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7260 NewOpc = ARMISD::VMULLs; 7261 isMLA = true; 7262 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7263 NewOpc = ARMISD::VMULLu; 7264 isMLA = true; 7265 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7266 std::swap(N0, N1); 7267 NewOpc = ARMISD::VMULLu; 7268 isMLA = true; 7269 } 7270 } 7271 7272 if (!NewOpc) { 7273 if (VT == MVT::v2i64) 7274 // Fall through to expand this. It is not legal. 7275 return SDValue(); 7276 else 7277 // Other vector multiplications are legal. 7278 return Op; 7279 } 7280 } 7281 7282 // Legalize to a VMULL instruction. 7283 SDLoc DL(Op); 7284 SDValue Op0; 7285 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7286 if (!isMLA) { 7287 Op0 = SkipExtensionForVMULL(N0, DAG); 7288 assert(Op0.getValueType().is64BitVector() && 7289 Op1.getValueType().is64BitVector() && 7290 "unexpected types for extended operands to VMULL"); 7291 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7292 } 7293 7294 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7295 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7296 // vmull q0, d4, d6 7297 // vmlal q0, d5, d6 7298 // is faster than 7299 // vaddl q0, d4, d5 7300 // vmovl q1, d6 7301 // vmul q0, q0, q1 7302 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7303 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7304 EVT Op1VT = Op1.getValueType(); 7305 return DAG.getNode(N0->getOpcode(), DL, VT, 7306 DAG.getNode(NewOpc, DL, VT, 7307 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7308 DAG.getNode(NewOpc, DL, VT, 7309 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7310 } 7311 7312 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7313 SelectionDAG &DAG) { 7314 // TODO: Should this propagate fast-math-flags? 7315 7316 // Convert to float 7317 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7318 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7319 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7320 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7321 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7322 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7323 // Get reciprocal estimate. 7324 // float4 recip = vrecpeq_f32(yf); 7325 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7326 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7327 Y); 7328 // Because char has a smaller range than uchar, we can actually get away 7329 // without any newton steps. This requires that we use a weird bias 7330 // of 0xb000, however (again, this has been exhaustively tested). 7331 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7332 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7333 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7334 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7335 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7336 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7337 // Convert back to short. 7338 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7339 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7340 return X; 7341 } 7342 7343 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7344 SelectionDAG &DAG) { 7345 // TODO: Should this propagate fast-math-flags? 7346 7347 SDValue N2; 7348 // Convert to float. 7349 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7350 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7351 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7352 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7353 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7354 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7355 7356 // Use reciprocal estimate and one refinement step. 7357 // float4 recip = vrecpeq_f32(yf); 7358 // recip *= vrecpsq_f32(yf, recip); 7359 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7360 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7361 N1); 7362 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7363 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7364 N1, N2); 7365 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7366 // Because short has a smaller range than ushort, we can actually get away 7367 // with only a single newton step. This requires that we use a weird bias 7368 // of 89, however (again, this has been exhaustively tested). 7369 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7370 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7371 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7372 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7373 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7374 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7375 // Convert back to integer and return. 7376 // return vmovn_s32(vcvt_s32_f32(result)); 7377 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7378 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7379 return N0; 7380 } 7381 7382 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7383 EVT VT = Op.getValueType(); 7384 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7385 "unexpected type for custom-lowering ISD::SDIV"); 7386 7387 SDLoc dl(Op); 7388 SDValue N0 = Op.getOperand(0); 7389 SDValue N1 = Op.getOperand(1); 7390 SDValue N2, N3; 7391 7392 if (VT == MVT::v8i8) { 7393 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7394 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7395 7396 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7397 DAG.getIntPtrConstant(4, dl)); 7398 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7399 DAG.getIntPtrConstant(4, dl)); 7400 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7401 DAG.getIntPtrConstant(0, dl)); 7402 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7403 DAG.getIntPtrConstant(0, dl)); 7404 7405 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7406 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7407 7408 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7409 N0 = LowerCONCAT_VECTORS(N0, DAG); 7410 7411 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7412 return N0; 7413 } 7414 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7415 } 7416 7417 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7418 // TODO: Should this propagate fast-math-flags? 7419 EVT VT = Op.getValueType(); 7420 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7421 "unexpected type for custom-lowering ISD::UDIV"); 7422 7423 SDLoc dl(Op); 7424 SDValue N0 = Op.getOperand(0); 7425 SDValue N1 = Op.getOperand(1); 7426 SDValue N2, N3; 7427 7428 if (VT == MVT::v8i8) { 7429 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7430 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7431 7432 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7433 DAG.getIntPtrConstant(4, dl)); 7434 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7435 DAG.getIntPtrConstant(4, dl)); 7436 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7437 DAG.getIntPtrConstant(0, dl)); 7438 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7439 DAG.getIntPtrConstant(0, dl)); 7440 7441 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7442 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7443 7444 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7445 N0 = LowerCONCAT_VECTORS(N0, DAG); 7446 7447 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7448 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7449 MVT::i32), 7450 N0); 7451 return N0; 7452 } 7453 7454 // v4i16 sdiv ... Convert to float. 7455 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7456 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7457 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7458 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7459 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7460 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7461 7462 // Use reciprocal estimate and two refinement steps. 7463 // float4 recip = vrecpeq_f32(yf); 7464 // recip *= vrecpsq_f32(yf, recip); 7465 // recip *= vrecpsq_f32(yf, recip); 7466 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7467 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7468 BN1); 7469 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7470 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7471 BN1, N2); 7472 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7473 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7474 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7475 BN1, N2); 7476 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7477 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7478 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7479 // and that it will never cause us to return an answer too large). 7480 // float4 result = as_float4(as_int4(xf*recip) + 2); 7481 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7482 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7483 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7484 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7485 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7486 // Convert back to integer and return. 7487 // return vmovn_u32(vcvt_s32_f32(result)); 7488 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7489 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7490 return N0; 7491 } 7492 7493 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7494 EVT VT = Op.getNode()->getValueType(0); 7495 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7496 7497 unsigned Opc; 7498 bool ExtraOp = false; 7499 switch (Op.getOpcode()) { 7500 default: llvm_unreachable("Invalid code"); 7501 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7502 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7503 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7504 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7505 } 7506 7507 if (!ExtraOp) 7508 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7509 Op.getOperand(1)); 7510 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7511 Op.getOperand(1), Op.getOperand(2)); 7512 } 7513 7514 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7515 SDNode *N = Op.getNode(); 7516 EVT VT = N->getValueType(0); 7517 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7518 7519 SDValue Carry = Op.getOperand(2); 7520 EVT CarryVT = Carry.getValueType(); 7521 7522 SDLoc DL(Op); 7523 7524 APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits()); 7525 7526 SDValue Result; 7527 if (Op.getOpcode() == ISD::ADDCARRY) { 7528 // This converts the boolean value carry into the carry flag. 7529 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7530 7531 // Do the addition proper using the carry flag we wanted. 7532 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7533 Op.getOperand(1), Carry.getValue(1)); 7534 7535 // Now convert the carry flag into a boolean value. 7536 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7537 } else { 7538 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7539 // have to invert the carry first. 7540 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7541 DAG.getConstant(1, DL, MVT::i32), Carry); 7542 // This converts the boolean value carry into the carry flag. 7543 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7544 7545 // Do the subtraction proper using the carry flag we wanted. 7546 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7547 Op.getOperand(1), Carry.getValue(1)); 7548 7549 // Now convert the carry flag into a boolean value. 7550 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7551 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7552 // by ISD::SUBCARRY, so compute 1 - C. 7553 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7554 DAG.getConstant(1, DL, MVT::i32), Carry); 7555 } 7556 7557 // Return both values. 7558 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7559 } 7560 7561 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7562 assert(Subtarget->isTargetDarwin()); 7563 7564 // For iOS, we want to call an alternative entry point: __sincos_stret, 7565 // return values are passed via sret. 7566 SDLoc dl(Op); 7567 SDValue Arg = Op.getOperand(0); 7568 EVT ArgVT = Arg.getValueType(); 7569 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7570 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7571 7572 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7574 7575 // Pair of floats / doubles used to pass the result. 7576 Type *RetTy = StructType::get(ArgTy, ArgTy); 7577 auto &DL = DAG.getDataLayout(); 7578 7579 ArgListTy Args; 7580 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7581 SDValue SRet; 7582 if (ShouldUseSRet) { 7583 // Create stack object for sret. 7584 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7585 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7586 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7587 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7588 7589 ArgListEntry Entry; 7590 Entry.Node = SRet; 7591 Entry.Ty = RetTy->getPointerTo(); 7592 Entry.IsSExt = false; 7593 Entry.IsZExt = false; 7594 Entry.IsSRet = true; 7595 Args.push_back(Entry); 7596 RetTy = Type::getVoidTy(*DAG.getContext()); 7597 } 7598 7599 ArgListEntry Entry; 7600 Entry.Node = Arg; 7601 Entry.Ty = ArgTy; 7602 Entry.IsSExt = false; 7603 Entry.IsZExt = false; 7604 Args.push_back(Entry); 7605 7606 RTLIB::Libcall LC = 7607 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 7608 const char *LibcallName = getLibcallName(LC); 7609 CallingConv::ID CC = getLibcallCallingConv(LC); 7610 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7611 7612 TargetLowering::CallLoweringInfo CLI(DAG); 7613 CLI.setDebugLoc(dl) 7614 .setChain(DAG.getEntryNode()) 7615 .setCallee(CC, RetTy, Callee, std::move(Args)) 7616 .setDiscardResult(ShouldUseSRet); 7617 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7618 7619 if (!ShouldUseSRet) 7620 return CallResult.first; 7621 7622 SDValue LoadSin = 7623 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7624 7625 // Address of cos field. 7626 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7627 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7628 SDValue LoadCos = 7629 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7630 7631 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7632 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7633 LoadSin.getValue(0), LoadCos.getValue(0)); 7634 } 7635 7636 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7637 bool Signed, 7638 SDValue &Chain) const { 7639 EVT VT = Op.getValueType(); 7640 assert((VT == MVT::i32 || VT == MVT::i64) && 7641 "unexpected type for custom lowering DIV"); 7642 SDLoc dl(Op); 7643 7644 const auto &DL = DAG.getDataLayout(); 7645 const auto &TLI = DAG.getTargetLoweringInfo(); 7646 7647 const char *Name = nullptr; 7648 if (Signed) 7649 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7650 else 7651 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7652 7653 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7654 7655 ARMTargetLowering::ArgListTy Args; 7656 7657 for (auto AI : {1, 0}) { 7658 ArgListEntry Arg; 7659 Arg.Node = Op.getOperand(AI); 7660 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7661 Args.push_back(Arg); 7662 } 7663 7664 CallLoweringInfo CLI(DAG); 7665 CLI.setDebugLoc(dl) 7666 .setChain(Chain) 7667 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7668 ES, std::move(Args)); 7669 7670 return LowerCallTo(CLI).first; 7671 } 7672 7673 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7674 bool Signed) const { 7675 assert(Op.getValueType() == MVT::i32 && 7676 "unexpected type for custom lowering DIV"); 7677 SDLoc dl(Op); 7678 7679 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7680 DAG.getEntryNode(), Op.getOperand(1)); 7681 7682 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7683 } 7684 7685 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7686 SDLoc DL(N); 7687 SDValue Op = N->getOperand(1); 7688 if (N->getValueType(0) == MVT::i32) 7689 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7690 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7691 DAG.getConstant(0, DL, MVT::i32)); 7692 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7693 DAG.getConstant(1, DL, MVT::i32)); 7694 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7695 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7696 } 7697 7698 void ARMTargetLowering::ExpandDIV_Windows( 7699 SDValue Op, SelectionDAG &DAG, bool Signed, 7700 SmallVectorImpl<SDValue> &Results) const { 7701 const auto &DL = DAG.getDataLayout(); 7702 const auto &TLI = DAG.getTargetLoweringInfo(); 7703 7704 assert(Op.getValueType() == MVT::i64 && 7705 "unexpected type for custom lowering DIV"); 7706 SDLoc dl(Op); 7707 7708 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7709 7710 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7711 7712 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7713 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7714 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7715 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7716 7717 Results.push_back(Lower); 7718 Results.push_back(Upper); 7719 } 7720 7721 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7722 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7723 // Acquire/Release load/store is not legal for targets without a dmb or 7724 // equivalent available. 7725 return SDValue(); 7726 7727 // Monotonic load/store is legal for all targets. 7728 return Op; 7729 } 7730 7731 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7732 SmallVectorImpl<SDValue> &Results, 7733 SelectionDAG &DAG, 7734 const ARMSubtarget *Subtarget) { 7735 SDLoc DL(N); 7736 // Under Power Management extensions, the cycle-count is: 7737 // mrc p15, #0, <Rt>, c9, c13, #0 7738 SDValue Ops[] = { N->getOperand(0), // Chain 7739 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7740 DAG.getConstant(15, DL, MVT::i32), 7741 DAG.getConstant(0, DL, MVT::i32), 7742 DAG.getConstant(9, DL, MVT::i32), 7743 DAG.getConstant(13, DL, MVT::i32), 7744 DAG.getConstant(0, DL, MVT::i32) 7745 }; 7746 7747 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7748 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7749 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7750 DAG.getConstant(0, DL, MVT::i32))); 7751 Results.push_back(Cycles32.getValue(1)); 7752 } 7753 7754 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7755 SDLoc dl(V.getNode()); 7756 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7757 SDValue VHi = DAG.getAnyExtOrTrunc( 7758 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7759 dl, MVT::i32); 7760 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7761 if (isBigEndian) 7762 std::swap (VLo, VHi); 7763 SDValue RegClass = 7764 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7765 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7766 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7767 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7768 return SDValue( 7769 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7770 } 7771 7772 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7773 SmallVectorImpl<SDValue> & Results, 7774 SelectionDAG &DAG) { 7775 assert(N->getValueType(0) == MVT::i64 && 7776 "AtomicCmpSwap on types less than 64 should be legal"); 7777 SDValue Ops[] = {N->getOperand(1), 7778 createGPRPairNode(DAG, N->getOperand(2)), 7779 createGPRPairNode(DAG, N->getOperand(3)), 7780 N->getOperand(0)}; 7781 SDNode *CmpSwap = DAG.getMachineNode( 7782 ARM::CMP_SWAP_64, SDLoc(N), 7783 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7784 7785 MachineFunction &MF = DAG.getMachineFunction(); 7786 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7787 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7788 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7789 7790 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7791 7792 Results.push_back( 7793 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 7794 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7795 Results.push_back( 7796 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 7797 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7798 Results.push_back(SDValue(CmpSwap, 2)); 7799 } 7800 7801 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7802 SelectionDAG &DAG) { 7803 const auto &TLI = DAG.getTargetLoweringInfo(); 7804 7805 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7806 "Custom lowering is MSVCRT specific!"); 7807 7808 SDLoc dl(Op); 7809 SDValue Val = Op.getOperand(0); 7810 MVT Ty = Val->getSimpleValueType(0); 7811 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7812 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7813 TLI.getPointerTy(DAG.getDataLayout())); 7814 7815 TargetLowering::ArgListTy Args; 7816 TargetLowering::ArgListEntry Entry; 7817 7818 Entry.Node = Val; 7819 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7820 Entry.IsZExt = true; 7821 Args.push_back(Entry); 7822 7823 Entry.Node = Exponent; 7824 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7825 Entry.IsZExt = true; 7826 Args.push_back(Entry); 7827 7828 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7829 7830 // In the in-chain to the call is the entry node If we are emitting a 7831 // tailcall, the chain will be mutated if the node has a non-entry input 7832 // chain. 7833 SDValue InChain = DAG.getEntryNode(); 7834 SDValue TCChain = InChain; 7835 7836 const Function &F = DAG.getMachineFunction().getFunction(); 7837 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 7838 F.getReturnType() == LCRTy; 7839 if (IsTC) 7840 InChain = TCChain; 7841 7842 TargetLowering::CallLoweringInfo CLI(DAG); 7843 CLI.setDebugLoc(dl) 7844 .setChain(InChain) 7845 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 7846 .setTailCall(IsTC); 7847 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 7848 7849 // Return the chain (the DAG root) if it is a tail call 7850 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 7851 } 7852 7853 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7854 DEBUG(dbgs() << "Lowering node: "; Op.dump()); 7855 switch (Op.getOpcode()) { 7856 default: llvm_unreachable("Don't know how to custom lower this!"); 7857 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7858 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7859 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7860 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 7861 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7862 case ISD::SELECT: return LowerSELECT(Op, DAG); 7863 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7864 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 7865 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7866 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7867 case ISD::VASTART: return LowerVASTART(Op, DAG); 7868 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7869 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7870 case ISD::SINT_TO_FP: 7871 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7872 case ISD::FP_TO_SINT: 7873 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7874 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7875 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7876 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7877 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7878 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7879 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7880 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7881 Subtarget); 7882 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7883 case ISD::SHL: 7884 case ISD::SRL: 7885 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7886 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7887 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7888 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7889 case ISD::SRL_PARTS: 7890 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7891 case ISD::CTTZ: 7892 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7893 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7894 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7895 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7896 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7897 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7898 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7899 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7900 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7901 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7902 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7903 case ISD::MUL: return LowerMUL(Op, DAG); 7904 case ISD::SDIV: 7905 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7906 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7907 return LowerSDIV(Op, DAG); 7908 case ISD::UDIV: 7909 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7910 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7911 return LowerUDIV(Op, DAG); 7912 case ISD::ADDC: 7913 case ISD::ADDE: 7914 case ISD::SUBC: 7915 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7916 case ISD::ADDCARRY: 7917 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 7918 case ISD::SADDO: 7919 case ISD::SSUBO: 7920 return LowerSignedALUO(Op, DAG); 7921 case ISD::UADDO: 7922 case ISD::USUBO: 7923 return LowerUnsignedALUO(Op, DAG); 7924 case ISD::ATOMIC_LOAD: 7925 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7926 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7927 case ISD::SDIVREM: 7928 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7929 case ISD::DYNAMIC_STACKALLOC: 7930 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7931 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7932 llvm_unreachable("Don't know how to custom lower this!"); 7933 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7934 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7935 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 7936 case ARMISD::WIN__DBZCHK: return SDValue(); 7937 } 7938 } 7939 7940 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 7941 SelectionDAG &DAG) { 7942 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7943 unsigned Opc = 0; 7944 if (IntNo == Intrinsic::arm_smlald) 7945 Opc = ARMISD::SMLALD; 7946 else if (IntNo == Intrinsic::arm_smlaldx) 7947 Opc = ARMISD::SMLALDX; 7948 else if (IntNo == Intrinsic::arm_smlsld) 7949 Opc = ARMISD::SMLSLD; 7950 else if (IntNo == Intrinsic::arm_smlsldx) 7951 Opc = ARMISD::SMLSLDX; 7952 else 7953 return; 7954 7955 SDLoc dl(N); 7956 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7957 N->getOperand(3), 7958 DAG.getConstant(0, dl, MVT::i32)); 7959 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7960 N->getOperand(3), 7961 DAG.getConstant(1, dl, MVT::i32)); 7962 7963 SDValue LongMul = DAG.getNode(Opc, dl, 7964 DAG.getVTList(MVT::i32, MVT::i32), 7965 N->getOperand(1), N->getOperand(2), 7966 Lo, Hi); 7967 Results.push_back(LongMul.getValue(0)); 7968 Results.push_back(LongMul.getValue(1)); 7969 } 7970 7971 /// ReplaceNodeResults - Replace the results of node with an illegal result 7972 /// type with new values built out of custom code. 7973 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7974 SmallVectorImpl<SDValue> &Results, 7975 SelectionDAG &DAG) const { 7976 SDValue Res; 7977 switch (N->getOpcode()) { 7978 default: 7979 llvm_unreachable("Don't know how to custom expand this!"); 7980 case ISD::READ_REGISTER: 7981 ExpandREAD_REGISTER(N, Results, DAG); 7982 break; 7983 case ISD::BITCAST: 7984 Res = ExpandBITCAST(N, DAG); 7985 break; 7986 case ISD::SRL: 7987 case ISD::SRA: 7988 Res = Expand64BitShift(N, DAG, Subtarget); 7989 break; 7990 case ISD::SREM: 7991 case ISD::UREM: 7992 Res = LowerREM(N, DAG); 7993 break; 7994 case ISD::SDIVREM: 7995 case ISD::UDIVREM: 7996 Res = LowerDivRem(SDValue(N, 0), DAG); 7997 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7998 Results.push_back(Res.getValue(0)); 7999 Results.push_back(Res.getValue(1)); 8000 return; 8001 case ISD::READCYCLECOUNTER: 8002 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8003 return; 8004 case ISD::UDIV: 8005 case ISD::SDIV: 8006 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8007 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8008 Results); 8009 case ISD::ATOMIC_CMP_SWAP: 8010 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8011 return; 8012 case ISD::INTRINSIC_WO_CHAIN: 8013 return ReplaceLongIntrinsic(N, Results, DAG); 8014 } 8015 if (Res.getNode()) 8016 Results.push_back(Res); 8017 } 8018 8019 //===----------------------------------------------------------------------===// 8020 // ARM Scheduler Hooks 8021 //===----------------------------------------------------------------------===// 8022 8023 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8024 /// registers the function context. 8025 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8026 MachineBasicBlock *MBB, 8027 MachineBasicBlock *DispatchBB, 8028 int FI) const { 8029 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8030 "ROPI/RWPI not currently supported with SjLj"); 8031 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8032 DebugLoc dl = MI.getDebugLoc(); 8033 MachineFunction *MF = MBB->getParent(); 8034 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8035 MachineConstantPool *MCP = MF->getConstantPool(); 8036 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8037 const Function &F = MF->getFunction(); 8038 8039 bool isThumb = Subtarget->isThumb(); 8040 bool isThumb2 = Subtarget->isThumb2(); 8041 8042 unsigned PCLabelId = AFI->createPICLabelUId(); 8043 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8044 ARMConstantPoolValue *CPV = 8045 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8046 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8047 8048 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8049 : &ARM::GPRRegClass; 8050 8051 // Grab constant pool and fixed stack memory operands. 8052 MachineMemOperand *CPMMO = 8053 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8054 MachineMemOperand::MOLoad, 4, 4); 8055 8056 MachineMemOperand *FIMMOSt = 8057 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8058 MachineMemOperand::MOStore, 4, 4); 8059 8060 // Load the address of the dispatch MBB into the jump buffer. 8061 if (isThumb2) { 8062 // Incoming value: jbuf 8063 // ldr.n r5, LCPI1_1 8064 // orr r5, r5, #1 8065 // add r5, pc 8066 // str r5, [$jbuf, #+4] ; &jbuf[1] 8067 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8068 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8069 .addConstantPoolIndex(CPI) 8070 .addMemOperand(CPMMO) 8071 .add(predOps(ARMCC::AL)); 8072 // Set the low bit because of thumb mode. 8073 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8074 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8075 .addReg(NewVReg1, RegState::Kill) 8076 .addImm(0x01) 8077 .add(predOps(ARMCC::AL)) 8078 .add(condCodeOp()); 8079 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8080 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8081 .addReg(NewVReg2, RegState::Kill) 8082 .addImm(PCLabelId); 8083 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8084 .addReg(NewVReg3, RegState::Kill) 8085 .addFrameIndex(FI) 8086 .addImm(36) // &jbuf[1] :: pc 8087 .addMemOperand(FIMMOSt) 8088 .add(predOps(ARMCC::AL)); 8089 } else if (isThumb) { 8090 // Incoming value: jbuf 8091 // ldr.n r1, LCPI1_4 8092 // add r1, pc 8093 // mov r2, #1 8094 // orrs r1, r2 8095 // add r2, $jbuf, #+4 ; &jbuf[1] 8096 // str r1, [r2] 8097 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8098 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8099 .addConstantPoolIndex(CPI) 8100 .addMemOperand(CPMMO) 8101 .add(predOps(ARMCC::AL)); 8102 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8103 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8104 .addReg(NewVReg1, RegState::Kill) 8105 .addImm(PCLabelId); 8106 // Set the low bit because of thumb mode. 8107 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8108 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8109 .addReg(ARM::CPSR, RegState::Define) 8110 .addImm(1) 8111 .add(predOps(ARMCC::AL)); 8112 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8113 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8114 .addReg(ARM::CPSR, RegState::Define) 8115 .addReg(NewVReg2, RegState::Kill) 8116 .addReg(NewVReg3, RegState::Kill) 8117 .add(predOps(ARMCC::AL)); 8118 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8119 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8120 .addFrameIndex(FI) 8121 .addImm(36); // &jbuf[1] :: pc 8122 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8123 .addReg(NewVReg4, RegState::Kill) 8124 .addReg(NewVReg5, RegState::Kill) 8125 .addImm(0) 8126 .addMemOperand(FIMMOSt) 8127 .add(predOps(ARMCC::AL)); 8128 } else { 8129 // Incoming value: jbuf 8130 // ldr r1, LCPI1_1 8131 // add r1, pc, r1 8132 // str r1, [$jbuf, #+4] ; &jbuf[1] 8133 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8134 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8135 .addConstantPoolIndex(CPI) 8136 .addImm(0) 8137 .addMemOperand(CPMMO) 8138 .add(predOps(ARMCC::AL)); 8139 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8140 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8141 .addReg(NewVReg1, RegState::Kill) 8142 .addImm(PCLabelId) 8143 .add(predOps(ARMCC::AL)); 8144 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8145 .addReg(NewVReg2, RegState::Kill) 8146 .addFrameIndex(FI) 8147 .addImm(36) // &jbuf[1] :: pc 8148 .addMemOperand(FIMMOSt) 8149 .add(predOps(ARMCC::AL)); 8150 } 8151 } 8152 8153 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8154 MachineBasicBlock *MBB) const { 8155 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8156 DebugLoc dl = MI.getDebugLoc(); 8157 MachineFunction *MF = MBB->getParent(); 8158 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8159 MachineFrameInfo &MFI = MF->getFrameInfo(); 8160 int FI = MFI.getFunctionContextIndex(); 8161 8162 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8163 : &ARM::GPRnopcRegClass; 8164 8165 // Get a mapping of the call site numbers to all of the landing pads they're 8166 // associated with. 8167 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8168 unsigned MaxCSNum = 0; 8169 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8170 ++BB) { 8171 if (!BB->isEHPad()) continue; 8172 8173 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8174 // pad. 8175 for (MachineBasicBlock::iterator 8176 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8177 if (!II->isEHLabel()) continue; 8178 8179 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8180 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8181 8182 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8183 for (SmallVectorImpl<unsigned>::iterator 8184 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8185 CSI != CSE; ++CSI) { 8186 CallSiteNumToLPad[*CSI].push_back(&*BB); 8187 MaxCSNum = std::max(MaxCSNum, *CSI); 8188 } 8189 break; 8190 } 8191 } 8192 8193 // Get an ordered list of the machine basic blocks for the jump table. 8194 std::vector<MachineBasicBlock*> LPadList; 8195 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8196 LPadList.reserve(CallSiteNumToLPad.size()); 8197 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8198 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8199 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8200 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8201 LPadList.push_back(*II); 8202 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8203 } 8204 } 8205 8206 assert(!LPadList.empty() && 8207 "No landing pad destinations for the dispatch jump table!"); 8208 8209 // Create the jump table and associated information. 8210 MachineJumpTableInfo *JTI = 8211 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8212 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8213 8214 // Create the MBBs for the dispatch code. 8215 8216 // Shove the dispatch's address into the return slot in the function context. 8217 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8218 DispatchBB->setIsEHPad(); 8219 8220 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8221 unsigned trap_opcode; 8222 if (Subtarget->isThumb()) 8223 trap_opcode = ARM::tTRAP; 8224 else 8225 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8226 8227 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8228 DispatchBB->addSuccessor(TrapBB); 8229 8230 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8231 DispatchBB->addSuccessor(DispContBB); 8232 8233 // Insert and MBBs. 8234 MF->insert(MF->end(), DispatchBB); 8235 MF->insert(MF->end(), DispContBB); 8236 MF->insert(MF->end(), TrapBB); 8237 8238 // Insert code into the entry block that creates and registers the function 8239 // context. 8240 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8241 8242 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8243 MachinePointerInfo::getFixedStack(*MF, FI), 8244 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8245 8246 MachineInstrBuilder MIB; 8247 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8248 8249 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8250 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8251 8252 // Add a register mask with no preserved registers. This results in all 8253 // registers being marked as clobbered. This can't work if the dispatch block 8254 // is in a Thumb1 function and is linked with ARM code which uses the FP 8255 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8256 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8257 8258 bool IsPositionIndependent = isPositionIndependent(); 8259 unsigned NumLPads = LPadList.size(); 8260 if (Subtarget->isThumb2()) { 8261 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8262 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8263 .addFrameIndex(FI) 8264 .addImm(4) 8265 .addMemOperand(FIMMOLd) 8266 .add(predOps(ARMCC::AL)); 8267 8268 if (NumLPads < 256) { 8269 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8270 .addReg(NewVReg1) 8271 .addImm(LPadList.size()) 8272 .add(predOps(ARMCC::AL)); 8273 } else { 8274 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8275 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8276 .addImm(NumLPads & 0xFFFF) 8277 .add(predOps(ARMCC::AL)); 8278 8279 unsigned VReg2 = VReg1; 8280 if ((NumLPads & 0xFFFF0000) != 0) { 8281 VReg2 = MRI->createVirtualRegister(TRC); 8282 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8283 .addReg(VReg1) 8284 .addImm(NumLPads >> 16) 8285 .add(predOps(ARMCC::AL)); 8286 } 8287 8288 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8289 .addReg(NewVReg1) 8290 .addReg(VReg2) 8291 .add(predOps(ARMCC::AL)); 8292 } 8293 8294 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8295 .addMBB(TrapBB) 8296 .addImm(ARMCC::HI) 8297 .addReg(ARM::CPSR); 8298 8299 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8300 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8301 .addJumpTableIndex(MJTI) 8302 .add(predOps(ARMCC::AL)); 8303 8304 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8305 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8306 .addReg(NewVReg3, RegState::Kill) 8307 .addReg(NewVReg1) 8308 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8309 .add(predOps(ARMCC::AL)) 8310 .add(condCodeOp()); 8311 8312 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8313 .addReg(NewVReg4, RegState::Kill) 8314 .addReg(NewVReg1) 8315 .addJumpTableIndex(MJTI); 8316 } else if (Subtarget->isThumb()) { 8317 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8318 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8319 .addFrameIndex(FI) 8320 .addImm(1) 8321 .addMemOperand(FIMMOLd) 8322 .add(predOps(ARMCC::AL)); 8323 8324 if (NumLPads < 256) { 8325 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8326 .addReg(NewVReg1) 8327 .addImm(NumLPads) 8328 .add(predOps(ARMCC::AL)); 8329 } else { 8330 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8331 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8332 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8333 8334 // MachineConstantPool wants an explicit alignment. 8335 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8336 if (Align == 0) 8337 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8338 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8339 8340 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8341 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8342 .addReg(VReg1, RegState::Define) 8343 .addConstantPoolIndex(Idx) 8344 .add(predOps(ARMCC::AL)); 8345 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8346 .addReg(NewVReg1) 8347 .addReg(VReg1) 8348 .add(predOps(ARMCC::AL)); 8349 } 8350 8351 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8352 .addMBB(TrapBB) 8353 .addImm(ARMCC::HI) 8354 .addReg(ARM::CPSR); 8355 8356 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8357 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8358 .addReg(ARM::CPSR, RegState::Define) 8359 .addReg(NewVReg1) 8360 .addImm(2) 8361 .add(predOps(ARMCC::AL)); 8362 8363 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8364 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8365 .addJumpTableIndex(MJTI) 8366 .add(predOps(ARMCC::AL)); 8367 8368 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8369 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8370 .addReg(ARM::CPSR, RegState::Define) 8371 .addReg(NewVReg2, RegState::Kill) 8372 .addReg(NewVReg3) 8373 .add(predOps(ARMCC::AL)); 8374 8375 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8376 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8377 8378 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8379 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8380 .addReg(NewVReg4, RegState::Kill) 8381 .addImm(0) 8382 .addMemOperand(JTMMOLd) 8383 .add(predOps(ARMCC::AL)); 8384 8385 unsigned NewVReg6 = NewVReg5; 8386 if (IsPositionIndependent) { 8387 NewVReg6 = MRI->createVirtualRegister(TRC); 8388 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8389 .addReg(ARM::CPSR, RegState::Define) 8390 .addReg(NewVReg5, RegState::Kill) 8391 .addReg(NewVReg3) 8392 .add(predOps(ARMCC::AL)); 8393 } 8394 8395 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8396 .addReg(NewVReg6, RegState::Kill) 8397 .addJumpTableIndex(MJTI); 8398 } else { 8399 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8400 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8401 .addFrameIndex(FI) 8402 .addImm(4) 8403 .addMemOperand(FIMMOLd) 8404 .add(predOps(ARMCC::AL)); 8405 8406 if (NumLPads < 256) { 8407 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8408 .addReg(NewVReg1) 8409 .addImm(NumLPads) 8410 .add(predOps(ARMCC::AL)); 8411 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8412 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8413 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8414 .addImm(NumLPads & 0xFFFF) 8415 .add(predOps(ARMCC::AL)); 8416 8417 unsigned VReg2 = VReg1; 8418 if ((NumLPads & 0xFFFF0000) != 0) { 8419 VReg2 = MRI->createVirtualRegister(TRC); 8420 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8421 .addReg(VReg1) 8422 .addImm(NumLPads >> 16) 8423 .add(predOps(ARMCC::AL)); 8424 } 8425 8426 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8427 .addReg(NewVReg1) 8428 .addReg(VReg2) 8429 .add(predOps(ARMCC::AL)); 8430 } else { 8431 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8432 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8433 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8434 8435 // MachineConstantPool wants an explicit alignment. 8436 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8437 if (Align == 0) 8438 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8439 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8440 8441 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8442 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8443 .addReg(VReg1, RegState::Define) 8444 .addConstantPoolIndex(Idx) 8445 .addImm(0) 8446 .add(predOps(ARMCC::AL)); 8447 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8448 .addReg(NewVReg1) 8449 .addReg(VReg1, RegState::Kill) 8450 .add(predOps(ARMCC::AL)); 8451 } 8452 8453 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8454 .addMBB(TrapBB) 8455 .addImm(ARMCC::HI) 8456 .addReg(ARM::CPSR); 8457 8458 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8459 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8460 .addReg(NewVReg1) 8461 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8462 .add(predOps(ARMCC::AL)) 8463 .add(condCodeOp()); 8464 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8465 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8466 .addJumpTableIndex(MJTI) 8467 .add(predOps(ARMCC::AL)); 8468 8469 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8470 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8471 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8472 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8473 .addReg(NewVReg3, RegState::Kill) 8474 .addReg(NewVReg4) 8475 .addImm(0) 8476 .addMemOperand(JTMMOLd) 8477 .add(predOps(ARMCC::AL)); 8478 8479 if (IsPositionIndependent) { 8480 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8481 .addReg(NewVReg5, RegState::Kill) 8482 .addReg(NewVReg4) 8483 .addJumpTableIndex(MJTI); 8484 } else { 8485 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8486 .addReg(NewVReg5, RegState::Kill) 8487 .addJumpTableIndex(MJTI); 8488 } 8489 } 8490 8491 // Add the jump table entries as successors to the MBB. 8492 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8493 for (std::vector<MachineBasicBlock*>::iterator 8494 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8495 MachineBasicBlock *CurMBB = *I; 8496 if (SeenMBBs.insert(CurMBB).second) 8497 DispContBB->addSuccessor(CurMBB); 8498 } 8499 8500 // N.B. the order the invoke BBs are processed in doesn't matter here. 8501 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8502 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8503 for (MachineBasicBlock *BB : InvokeBBs) { 8504 8505 // Remove the landing pad successor from the invoke block and replace it 8506 // with the new dispatch block. 8507 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8508 BB->succ_end()); 8509 while (!Successors.empty()) { 8510 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8511 if (SMBB->isEHPad()) { 8512 BB->removeSuccessor(SMBB); 8513 MBBLPads.push_back(SMBB); 8514 } 8515 } 8516 8517 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8518 BB->normalizeSuccProbs(); 8519 8520 // Find the invoke call and mark all of the callee-saved registers as 8521 // 'implicit defined' so that they're spilled. This prevents code from 8522 // moving instructions to before the EH block, where they will never be 8523 // executed. 8524 for (MachineBasicBlock::reverse_iterator 8525 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8526 if (!II->isCall()) continue; 8527 8528 DenseMap<unsigned, bool> DefRegs; 8529 for (MachineInstr::mop_iterator 8530 OI = II->operands_begin(), OE = II->operands_end(); 8531 OI != OE; ++OI) { 8532 if (!OI->isReg()) continue; 8533 DefRegs[OI->getReg()] = true; 8534 } 8535 8536 MachineInstrBuilder MIB(*MF, &*II); 8537 8538 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8539 unsigned Reg = SavedRegs[i]; 8540 if (Subtarget->isThumb2() && 8541 !ARM::tGPRRegClass.contains(Reg) && 8542 !ARM::hGPRRegClass.contains(Reg)) 8543 continue; 8544 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8545 continue; 8546 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8547 continue; 8548 if (!DefRegs[Reg]) 8549 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8550 } 8551 8552 break; 8553 } 8554 } 8555 8556 // Mark all former landing pads as non-landing pads. The dispatch is the only 8557 // landing pad now. 8558 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8559 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8560 (*I)->setIsEHPad(false); 8561 8562 // The instruction is gone now. 8563 MI.eraseFromParent(); 8564 } 8565 8566 static 8567 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8568 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8569 E = MBB->succ_end(); I != E; ++I) 8570 if (*I != Succ) 8571 return *I; 8572 llvm_unreachable("Expecting a BB with two successors!"); 8573 } 8574 8575 /// Return the load opcode for a given load size. If load size >= 8, 8576 /// neon opcode will be returned. 8577 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8578 if (LdSize >= 8) 8579 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8580 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8581 if (IsThumb1) 8582 return LdSize == 4 ? ARM::tLDRi 8583 : LdSize == 2 ? ARM::tLDRHi 8584 : LdSize == 1 ? ARM::tLDRBi : 0; 8585 if (IsThumb2) 8586 return LdSize == 4 ? ARM::t2LDR_POST 8587 : LdSize == 2 ? ARM::t2LDRH_POST 8588 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8589 return LdSize == 4 ? ARM::LDR_POST_IMM 8590 : LdSize == 2 ? ARM::LDRH_POST 8591 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8592 } 8593 8594 /// Return the store opcode for a given store size. If store size >= 8, 8595 /// neon opcode will be returned. 8596 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8597 if (StSize >= 8) 8598 return StSize == 16 ? ARM::VST1q32wb_fixed 8599 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8600 if (IsThumb1) 8601 return StSize == 4 ? ARM::tSTRi 8602 : StSize == 2 ? ARM::tSTRHi 8603 : StSize == 1 ? ARM::tSTRBi : 0; 8604 if (IsThumb2) 8605 return StSize == 4 ? ARM::t2STR_POST 8606 : StSize == 2 ? ARM::t2STRH_POST 8607 : StSize == 1 ? ARM::t2STRB_POST : 0; 8608 return StSize == 4 ? ARM::STR_POST_IMM 8609 : StSize == 2 ? ARM::STRH_POST 8610 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8611 } 8612 8613 /// Emit a post-increment load operation with given size. The instructions 8614 /// will be added to BB at Pos. 8615 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8616 const TargetInstrInfo *TII, const DebugLoc &dl, 8617 unsigned LdSize, unsigned Data, unsigned AddrIn, 8618 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8619 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8620 assert(LdOpc != 0 && "Should have a load opcode"); 8621 if (LdSize >= 8) { 8622 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8623 .addReg(AddrOut, RegState::Define) 8624 .addReg(AddrIn) 8625 .addImm(0) 8626 .add(predOps(ARMCC::AL)); 8627 } else if (IsThumb1) { 8628 // load + update AddrIn 8629 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8630 .addReg(AddrIn) 8631 .addImm(0) 8632 .add(predOps(ARMCC::AL)); 8633 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8634 .add(t1CondCodeOp()) 8635 .addReg(AddrIn) 8636 .addImm(LdSize) 8637 .add(predOps(ARMCC::AL)); 8638 } else if (IsThumb2) { 8639 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8640 .addReg(AddrOut, RegState::Define) 8641 .addReg(AddrIn) 8642 .addImm(LdSize) 8643 .add(predOps(ARMCC::AL)); 8644 } else { // arm 8645 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8646 .addReg(AddrOut, RegState::Define) 8647 .addReg(AddrIn) 8648 .addReg(0) 8649 .addImm(LdSize) 8650 .add(predOps(ARMCC::AL)); 8651 } 8652 } 8653 8654 /// Emit a post-increment store operation with given size. The instructions 8655 /// will be added to BB at Pos. 8656 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8657 const TargetInstrInfo *TII, const DebugLoc &dl, 8658 unsigned StSize, unsigned Data, unsigned AddrIn, 8659 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8660 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8661 assert(StOpc != 0 && "Should have a store opcode"); 8662 if (StSize >= 8) { 8663 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8664 .addReg(AddrIn) 8665 .addImm(0) 8666 .addReg(Data) 8667 .add(predOps(ARMCC::AL)); 8668 } else if (IsThumb1) { 8669 // store + update AddrIn 8670 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8671 .addReg(Data) 8672 .addReg(AddrIn) 8673 .addImm(0) 8674 .add(predOps(ARMCC::AL)); 8675 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8676 .add(t1CondCodeOp()) 8677 .addReg(AddrIn) 8678 .addImm(StSize) 8679 .add(predOps(ARMCC::AL)); 8680 } else if (IsThumb2) { 8681 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8682 .addReg(Data) 8683 .addReg(AddrIn) 8684 .addImm(StSize) 8685 .add(predOps(ARMCC::AL)); 8686 } else { // arm 8687 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8688 .addReg(Data) 8689 .addReg(AddrIn) 8690 .addReg(0) 8691 .addImm(StSize) 8692 .add(predOps(ARMCC::AL)); 8693 } 8694 } 8695 8696 MachineBasicBlock * 8697 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8698 MachineBasicBlock *BB) const { 8699 // This pseudo instruction has 3 operands: dst, src, size 8700 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8701 // Otherwise, we will generate unrolled scalar copies. 8702 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8703 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8704 MachineFunction::iterator It = ++BB->getIterator(); 8705 8706 unsigned dest = MI.getOperand(0).getReg(); 8707 unsigned src = MI.getOperand(1).getReg(); 8708 unsigned SizeVal = MI.getOperand(2).getImm(); 8709 unsigned Align = MI.getOperand(3).getImm(); 8710 DebugLoc dl = MI.getDebugLoc(); 8711 8712 MachineFunction *MF = BB->getParent(); 8713 MachineRegisterInfo &MRI = MF->getRegInfo(); 8714 unsigned UnitSize = 0; 8715 const TargetRegisterClass *TRC = nullptr; 8716 const TargetRegisterClass *VecTRC = nullptr; 8717 8718 bool IsThumb1 = Subtarget->isThumb1Only(); 8719 bool IsThumb2 = Subtarget->isThumb2(); 8720 bool IsThumb = Subtarget->isThumb(); 8721 8722 if (Align & 1) { 8723 UnitSize = 1; 8724 } else if (Align & 2) { 8725 UnitSize = 2; 8726 } else { 8727 // Check whether we can use NEON instructions. 8728 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 8729 Subtarget->hasNEON()) { 8730 if ((Align % 16 == 0) && SizeVal >= 16) 8731 UnitSize = 16; 8732 else if ((Align % 8 == 0) && SizeVal >= 8) 8733 UnitSize = 8; 8734 } 8735 // Can't use NEON instructions. 8736 if (UnitSize == 0) 8737 UnitSize = 4; 8738 } 8739 8740 // Select the correct opcode and register class for unit size load/store 8741 bool IsNeon = UnitSize >= 8; 8742 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8743 if (IsNeon) 8744 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8745 : UnitSize == 8 ? &ARM::DPRRegClass 8746 : nullptr; 8747 8748 unsigned BytesLeft = SizeVal % UnitSize; 8749 unsigned LoopSize = SizeVal - BytesLeft; 8750 8751 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8752 // Use LDR and STR to copy. 8753 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8754 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8755 unsigned srcIn = src; 8756 unsigned destIn = dest; 8757 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8758 unsigned srcOut = MRI.createVirtualRegister(TRC); 8759 unsigned destOut = MRI.createVirtualRegister(TRC); 8760 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8761 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8762 IsThumb1, IsThumb2); 8763 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8764 IsThumb1, IsThumb2); 8765 srcIn = srcOut; 8766 destIn = destOut; 8767 } 8768 8769 // Handle the leftover bytes with LDRB and STRB. 8770 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8771 // [destOut] = STRB_POST(scratch, destIn, 1) 8772 for (unsigned i = 0; i < BytesLeft; i++) { 8773 unsigned srcOut = MRI.createVirtualRegister(TRC); 8774 unsigned destOut = MRI.createVirtualRegister(TRC); 8775 unsigned scratch = MRI.createVirtualRegister(TRC); 8776 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8777 IsThumb1, IsThumb2); 8778 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8779 IsThumb1, IsThumb2); 8780 srcIn = srcOut; 8781 destIn = destOut; 8782 } 8783 MI.eraseFromParent(); // The instruction is gone now. 8784 return BB; 8785 } 8786 8787 // Expand the pseudo op to a loop. 8788 // thisMBB: 8789 // ... 8790 // movw varEnd, # --> with thumb2 8791 // movt varEnd, # 8792 // ldrcp varEnd, idx --> without thumb2 8793 // fallthrough --> loopMBB 8794 // loopMBB: 8795 // PHI varPhi, varEnd, varLoop 8796 // PHI srcPhi, src, srcLoop 8797 // PHI destPhi, dst, destLoop 8798 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8799 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8800 // subs varLoop, varPhi, #UnitSize 8801 // bne loopMBB 8802 // fallthrough --> exitMBB 8803 // exitMBB: 8804 // epilogue to handle left-over bytes 8805 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8806 // [destOut] = STRB_POST(scratch, destLoop, 1) 8807 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8808 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8809 MF->insert(It, loopMBB); 8810 MF->insert(It, exitMBB); 8811 8812 // Transfer the remainder of BB and its successor edges to exitMBB. 8813 exitMBB->splice(exitMBB->begin(), BB, 8814 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8815 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8816 8817 // Load an immediate to varEnd. 8818 unsigned varEnd = MRI.createVirtualRegister(TRC); 8819 if (Subtarget->useMovt(*MF)) { 8820 unsigned Vtmp = varEnd; 8821 if ((LoopSize & 0xFFFF0000) != 0) 8822 Vtmp = MRI.createVirtualRegister(TRC); 8823 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8824 .addImm(LoopSize & 0xFFFF) 8825 .add(predOps(ARMCC::AL)); 8826 8827 if ((LoopSize & 0xFFFF0000) != 0) 8828 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 8829 .addReg(Vtmp) 8830 .addImm(LoopSize >> 16) 8831 .add(predOps(ARMCC::AL)); 8832 } else { 8833 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8834 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8835 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8836 8837 // MachineConstantPool wants an explicit alignment. 8838 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8839 if (Align == 0) 8840 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8841 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8842 8843 if (IsThumb) 8844 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 8845 .addReg(varEnd, RegState::Define) 8846 .addConstantPoolIndex(Idx) 8847 .add(predOps(ARMCC::AL)); 8848 else 8849 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 8850 .addReg(varEnd, RegState::Define) 8851 .addConstantPoolIndex(Idx) 8852 .addImm(0) 8853 .add(predOps(ARMCC::AL)); 8854 } 8855 BB->addSuccessor(loopMBB); 8856 8857 // Generate the loop body: 8858 // varPhi = PHI(varLoop, varEnd) 8859 // srcPhi = PHI(srcLoop, src) 8860 // destPhi = PHI(destLoop, dst) 8861 MachineBasicBlock *entryBB = BB; 8862 BB = loopMBB; 8863 unsigned varLoop = MRI.createVirtualRegister(TRC); 8864 unsigned varPhi = MRI.createVirtualRegister(TRC); 8865 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8866 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8867 unsigned destLoop = MRI.createVirtualRegister(TRC); 8868 unsigned destPhi = MRI.createVirtualRegister(TRC); 8869 8870 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8871 .addReg(varLoop).addMBB(loopMBB) 8872 .addReg(varEnd).addMBB(entryBB); 8873 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8874 .addReg(srcLoop).addMBB(loopMBB) 8875 .addReg(src).addMBB(entryBB); 8876 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8877 .addReg(destLoop).addMBB(loopMBB) 8878 .addReg(dest).addMBB(entryBB); 8879 8880 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8881 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8882 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8883 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8884 IsThumb1, IsThumb2); 8885 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8886 IsThumb1, IsThumb2); 8887 8888 // Decrement loop variable by UnitSize. 8889 if (IsThumb1) { 8890 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 8891 .add(t1CondCodeOp()) 8892 .addReg(varPhi) 8893 .addImm(UnitSize) 8894 .add(predOps(ARMCC::AL)); 8895 } else { 8896 MachineInstrBuilder MIB = 8897 BuildMI(*BB, BB->end(), dl, 8898 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8899 MIB.addReg(varPhi) 8900 .addImm(UnitSize) 8901 .add(predOps(ARMCC::AL)) 8902 .add(condCodeOp()); 8903 MIB->getOperand(5).setReg(ARM::CPSR); 8904 MIB->getOperand(5).setIsDef(true); 8905 } 8906 BuildMI(*BB, BB->end(), dl, 8907 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8908 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8909 8910 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8911 BB->addSuccessor(loopMBB); 8912 BB->addSuccessor(exitMBB); 8913 8914 // Add epilogue to handle BytesLeft. 8915 BB = exitMBB; 8916 auto StartOfExit = exitMBB->begin(); 8917 8918 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8919 // [destOut] = STRB_POST(scratch, destLoop, 1) 8920 unsigned srcIn = srcLoop; 8921 unsigned destIn = destLoop; 8922 for (unsigned i = 0; i < BytesLeft; i++) { 8923 unsigned srcOut = MRI.createVirtualRegister(TRC); 8924 unsigned destOut = MRI.createVirtualRegister(TRC); 8925 unsigned scratch = MRI.createVirtualRegister(TRC); 8926 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8927 IsThumb1, IsThumb2); 8928 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8929 IsThumb1, IsThumb2); 8930 srcIn = srcOut; 8931 destIn = destOut; 8932 } 8933 8934 MI.eraseFromParent(); // The instruction is gone now. 8935 return BB; 8936 } 8937 8938 MachineBasicBlock * 8939 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8940 MachineBasicBlock *MBB) const { 8941 const TargetMachine &TM = getTargetMachine(); 8942 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8943 DebugLoc DL = MI.getDebugLoc(); 8944 8945 assert(Subtarget->isTargetWindows() && 8946 "__chkstk is only supported on Windows"); 8947 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8948 8949 // __chkstk takes the number of words to allocate on the stack in R4, and 8950 // returns the stack adjustment in number of bytes in R4. This will not 8951 // clober any other registers (other than the obvious lr). 8952 // 8953 // Although, technically, IP should be considered a register which may be 8954 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8955 // thumb-2 environment, so there is no interworking required. As a result, we 8956 // do not expect a veneer to be emitted by the linker, clobbering IP. 8957 // 8958 // Each module receives its own copy of __chkstk, so no import thunk is 8959 // required, again, ensuring that IP is not clobbered. 8960 // 8961 // Finally, although some linkers may theoretically provide a trampoline for 8962 // out of range calls (which is quite common due to a 32M range limitation of 8963 // branches for Thumb), we can generate the long-call version via 8964 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8965 // IP. 8966 8967 switch (TM.getCodeModel()) { 8968 case CodeModel::Small: 8969 case CodeModel::Medium: 8970 case CodeModel::Kernel: 8971 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8972 .add(predOps(ARMCC::AL)) 8973 .addExternalSymbol("__chkstk") 8974 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8975 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8976 .addReg(ARM::R12, 8977 RegState::Implicit | RegState::Define | RegState::Dead) 8978 .addReg(ARM::CPSR, 8979 RegState::Implicit | RegState::Define | RegState::Dead); 8980 break; 8981 case CodeModel::Large: { 8982 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8983 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8984 8985 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8986 .addExternalSymbol("__chkstk"); 8987 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8988 .add(predOps(ARMCC::AL)) 8989 .addReg(Reg, RegState::Kill) 8990 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8991 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8992 .addReg(ARM::R12, 8993 RegState::Implicit | RegState::Define | RegState::Dead) 8994 .addReg(ARM::CPSR, 8995 RegState::Implicit | RegState::Define | RegState::Dead); 8996 break; 8997 } 8998 } 8999 9000 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9001 .addReg(ARM::SP, RegState::Kill) 9002 .addReg(ARM::R4, RegState::Kill) 9003 .setMIFlags(MachineInstr::FrameSetup) 9004 .add(predOps(ARMCC::AL)) 9005 .add(condCodeOp()); 9006 9007 MI.eraseFromParent(); 9008 return MBB; 9009 } 9010 9011 MachineBasicBlock * 9012 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9013 MachineBasicBlock *MBB) const { 9014 DebugLoc DL = MI.getDebugLoc(); 9015 MachineFunction *MF = MBB->getParent(); 9016 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9017 9018 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9019 MF->insert(++MBB->getIterator(), ContBB); 9020 ContBB->splice(ContBB->begin(), MBB, 9021 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9022 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9023 MBB->addSuccessor(ContBB); 9024 9025 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9026 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9027 MF->push_back(TrapBB); 9028 MBB->addSuccessor(TrapBB); 9029 9030 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9031 .addReg(MI.getOperand(0).getReg()) 9032 .addImm(0) 9033 .add(predOps(ARMCC::AL)); 9034 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9035 .addMBB(TrapBB) 9036 .addImm(ARMCC::EQ) 9037 .addReg(ARM::CPSR); 9038 9039 MI.eraseFromParent(); 9040 return ContBB; 9041 } 9042 9043 MachineBasicBlock * 9044 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9045 MachineBasicBlock *BB) const { 9046 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9047 DebugLoc dl = MI.getDebugLoc(); 9048 bool isThumb2 = Subtarget->isThumb2(); 9049 switch (MI.getOpcode()) { 9050 default: { 9051 MI.print(errs()); 9052 llvm_unreachable("Unexpected instr type to insert"); 9053 } 9054 9055 // Thumb1 post-indexed loads are really just single-register LDMs. 9056 case ARM::tLDR_postidx: { 9057 MachineOperand Def(MI.getOperand(1)); 9058 if (TargetRegisterInfo::isPhysicalRegister(Def.getReg())) 9059 Def.setIsRenamable(false); 9060 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9061 .add(Def) // Rn_wb 9062 .add(MI.getOperand(2)) // Rn 9063 .add(MI.getOperand(3)) // PredImm 9064 .add(MI.getOperand(4)) // PredReg 9065 .add(MI.getOperand(0)); // Rt 9066 MI.eraseFromParent(); 9067 return BB; 9068 } 9069 9070 // The Thumb2 pre-indexed stores have the same MI operands, they just 9071 // define them differently in the .td files from the isel patterns, so 9072 // they need pseudos. 9073 case ARM::t2STR_preidx: 9074 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9075 return BB; 9076 case ARM::t2STRB_preidx: 9077 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9078 return BB; 9079 case ARM::t2STRH_preidx: 9080 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9081 return BB; 9082 9083 case ARM::STRi_preidx: 9084 case ARM::STRBi_preidx: { 9085 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9086 : ARM::STRB_PRE_IMM; 9087 // Decode the offset. 9088 unsigned Offset = MI.getOperand(4).getImm(); 9089 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9090 Offset = ARM_AM::getAM2Offset(Offset); 9091 if (isSub) 9092 Offset = -Offset; 9093 9094 MachineMemOperand *MMO = *MI.memoperands_begin(); 9095 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9096 .add(MI.getOperand(0)) // Rn_wb 9097 .add(MI.getOperand(1)) // Rt 9098 .add(MI.getOperand(2)) // Rn 9099 .addImm(Offset) // offset (skip GPR==zero_reg) 9100 .add(MI.getOperand(5)) // pred 9101 .add(MI.getOperand(6)) 9102 .addMemOperand(MMO); 9103 MI.eraseFromParent(); 9104 return BB; 9105 } 9106 case ARM::STRr_preidx: 9107 case ARM::STRBr_preidx: 9108 case ARM::STRH_preidx: { 9109 unsigned NewOpc; 9110 switch (MI.getOpcode()) { 9111 default: llvm_unreachable("unexpected opcode!"); 9112 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9113 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9114 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9115 } 9116 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9117 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9118 MIB.add(MI.getOperand(i)); 9119 MI.eraseFromParent(); 9120 return BB; 9121 } 9122 9123 case ARM::tMOVCCr_pseudo: { 9124 // To "insert" a SELECT_CC instruction, we actually have to insert the 9125 // diamond control-flow pattern. The incoming instruction knows the 9126 // destination vreg to set, the condition code register to branch on, the 9127 // true/false values to select between, and a branch opcode to use. 9128 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9129 MachineFunction::iterator It = ++BB->getIterator(); 9130 9131 // thisMBB: 9132 // ... 9133 // TrueVal = ... 9134 // cmpTY ccX, r1, r2 9135 // bCC copy1MBB 9136 // fallthrough --> copy0MBB 9137 MachineBasicBlock *thisMBB = BB; 9138 MachineFunction *F = BB->getParent(); 9139 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9140 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9141 F->insert(It, copy0MBB); 9142 F->insert(It, sinkMBB); 9143 9144 // Transfer the remainder of BB and its successor edges to sinkMBB. 9145 sinkMBB->splice(sinkMBB->begin(), BB, 9146 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9147 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9148 9149 BB->addSuccessor(copy0MBB); 9150 BB->addSuccessor(sinkMBB); 9151 9152 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9153 .addMBB(sinkMBB) 9154 .addImm(MI.getOperand(3).getImm()) 9155 .addReg(MI.getOperand(4).getReg()); 9156 9157 // copy0MBB: 9158 // %FalseValue = ... 9159 // # fallthrough to sinkMBB 9160 BB = copy0MBB; 9161 9162 // Update machine-CFG edges 9163 BB->addSuccessor(sinkMBB); 9164 9165 // sinkMBB: 9166 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9167 // ... 9168 BB = sinkMBB; 9169 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9170 .addReg(MI.getOperand(1).getReg()) 9171 .addMBB(copy0MBB) 9172 .addReg(MI.getOperand(2).getReg()) 9173 .addMBB(thisMBB); 9174 9175 MI.eraseFromParent(); // The pseudo instruction is gone now. 9176 return BB; 9177 } 9178 9179 case ARM::BCCi64: 9180 case ARM::BCCZi64: { 9181 // If there is an unconditional branch to the other successor, remove it. 9182 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9183 9184 // Compare both parts that make up the double comparison separately for 9185 // equality. 9186 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9187 9188 unsigned LHS1 = MI.getOperand(1).getReg(); 9189 unsigned LHS2 = MI.getOperand(2).getReg(); 9190 if (RHSisZero) { 9191 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9192 .addReg(LHS1) 9193 .addImm(0) 9194 .add(predOps(ARMCC::AL)); 9195 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9196 .addReg(LHS2).addImm(0) 9197 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9198 } else { 9199 unsigned RHS1 = MI.getOperand(3).getReg(); 9200 unsigned RHS2 = MI.getOperand(4).getReg(); 9201 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9202 .addReg(LHS1) 9203 .addReg(RHS1) 9204 .add(predOps(ARMCC::AL)); 9205 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9206 .addReg(LHS2).addReg(RHS2) 9207 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9208 } 9209 9210 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9211 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9212 if (MI.getOperand(0).getImm() == ARMCC::NE) 9213 std::swap(destMBB, exitMBB); 9214 9215 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9216 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9217 if (isThumb2) 9218 BuildMI(BB, dl, TII->get(ARM::t2B)) 9219 .addMBB(exitMBB) 9220 .add(predOps(ARMCC::AL)); 9221 else 9222 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9223 9224 MI.eraseFromParent(); // The pseudo instruction is gone now. 9225 return BB; 9226 } 9227 9228 case ARM::Int_eh_sjlj_setjmp: 9229 case ARM::Int_eh_sjlj_setjmp_nofp: 9230 case ARM::tInt_eh_sjlj_setjmp: 9231 case ARM::t2Int_eh_sjlj_setjmp: 9232 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9233 return BB; 9234 9235 case ARM::Int_eh_sjlj_setup_dispatch: 9236 EmitSjLjDispatchBlock(MI, BB); 9237 return BB; 9238 9239 case ARM::ABS: 9240 case ARM::t2ABS: { 9241 // To insert an ABS instruction, we have to insert the 9242 // diamond control-flow pattern. The incoming instruction knows the 9243 // source vreg to test against 0, the destination vreg to set, 9244 // the condition code register to branch on, the 9245 // true/false values to select between, and a branch opcode to use. 9246 // It transforms 9247 // V1 = ABS V0 9248 // into 9249 // V2 = MOVS V0 9250 // BCC (branch to SinkBB if V0 >= 0) 9251 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9252 // SinkBB: V1 = PHI(V2, V3) 9253 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9254 MachineFunction::iterator BBI = ++BB->getIterator(); 9255 MachineFunction *Fn = BB->getParent(); 9256 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9257 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9258 Fn->insert(BBI, RSBBB); 9259 Fn->insert(BBI, SinkBB); 9260 9261 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9262 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9263 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9264 bool isThumb2 = Subtarget->isThumb2(); 9265 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9266 // In Thumb mode S must not be specified if source register is the SP or 9267 // PC and if destination register is the SP, so restrict register class 9268 unsigned NewRsbDstReg = 9269 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9270 9271 // Transfer the remainder of BB and its successor edges to sinkMBB. 9272 SinkBB->splice(SinkBB->begin(), BB, 9273 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9274 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9275 9276 BB->addSuccessor(RSBBB); 9277 BB->addSuccessor(SinkBB); 9278 9279 // fall through to SinkMBB 9280 RSBBB->addSuccessor(SinkBB); 9281 9282 // insert a cmp at the end of BB 9283 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9284 .addReg(ABSSrcReg) 9285 .addImm(0) 9286 .add(predOps(ARMCC::AL)); 9287 9288 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9289 BuildMI(BB, dl, 9290 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9291 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9292 9293 // insert rsbri in RSBBB 9294 // Note: BCC and rsbri will be converted into predicated rsbmi 9295 // by if-conversion pass 9296 BuildMI(*RSBBB, RSBBB->begin(), dl, 9297 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9298 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9299 .addImm(0) 9300 .add(predOps(ARMCC::AL)) 9301 .add(condCodeOp()); 9302 9303 // insert PHI in SinkBB, 9304 // reuse ABSDstReg to not change uses of ABS instruction 9305 BuildMI(*SinkBB, SinkBB->begin(), dl, 9306 TII->get(ARM::PHI), ABSDstReg) 9307 .addReg(NewRsbDstReg).addMBB(RSBBB) 9308 .addReg(ABSSrcReg).addMBB(BB); 9309 9310 // remove ABS instruction 9311 MI.eraseFromParent(); 9312 9313 // return last added BB 9314 return SinkBB; 9315 } 9316 case ARM::COPY_STRUCT_BYVAL_I32: 9317 ++NumLoopByVals; 9318 return EmitStructByval(MI, BB); 9319 case ARM::WIN__CHKSTK: 9320 return EmitLowered__chkstk(MI, BB); 9321 case ARM::WIN__DBZCHK: 9322 return EmitLowered__dbzchk(MI, BB); 9323 } 9324 } 9325 9326 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 9327 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9328 /// instead of as a custom inserter because we need the use list from the SDNode. 9329 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9330 MachineInstr &MI, const SDNode *Node) { 9331 bool isThumb1 = Subtarget->isThumb1Only(); 9332 9333 DebugLoc DL = MI.getDebugLoc(); 9334 MachineFunction *MF = MI.getParent()->getParent(); 9335 MachineRegisterInfo &MRI = MF->getRegInfo(); 9336 MachineInstrBuilder MIB(*MF, MI); 9337 9338 // If the new dst/src is unused mark it as dead. 9339 if (!Node->hasAnyUseOfValue(0)) { 9340 MI.getOperand(0).setIsDead(true); 9341 } 9342 if (!Node->hasAnyUseOfValue(1)) { 9343 MI.getOperand(1).setIsDead(true); 9344 } 9345 9346 // The MEMCPY both defines and kills the scratch registers. 9347 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9348 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9349 : &ARM::GPRRegClass); 9350 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9351 } 9352 } 9353 9354 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9355 SDNode *Node) const { 9356 if (MI.getOpcode() == ARM::MEMCPY) { 9357 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9358 return; 9359 } 9360 9361 const MCInstrDesc *MCID = &MI.getDesc(); 9362 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9363 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9364 // operand is still set to noreg. If needed, set the optional operand's 9365 // register to CPSR, and remove the redundant implicit def. 9366 // 9367 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9368 9369 // Rename pseudo opcodes. 9370 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9371 unsigned ccOutIdx; 9372 if (NewOpc) { 9373 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9374 MCID = &TII->get(NewOpc); 9375 9376 assert(MCID->getNumOperands() == 9377 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9378 && "converted opcode should be the same except for cc_out" 9379 " (and, on Thumb1, pred)"); 9380 9381 MI.setDesc(*MCID); 9382 9383 // Add the optional cc_out operand 9384 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9385 9386 // On Thumb1, move all input operands to the end, then add the predicate 9387 if (Subtarget->isThumb1Only()) { 9388 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9389 MI.addOperand(MI.getOperand(1)); 9390 MI.RemoveOperand(1); 9391 } 9392 9393 // Restore the ties 9394 for (unsigned i = MI.getNumOperands(); i--;) { 9395 const MachineOperand& op = MI.getOperand(i); 9396 if (op.isReg() && op.isUse()) { 9397 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9398 if (DefIdx != -1) 9399 MI.tieOperands(DefIdx, i); 9400 } 9401 } 9402 9403 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9404 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9405 ccOutIdx = 1; 9406 } else 9407 ccOutIdx = MCID->getNumOperands() - 1; 9408 } else 9409 ccOutIdx = MCID->getNumOperands() - 1; 9410 9411 // Any ARM instruction that sets the 's' bit should specify an optional 9412 // "cc_out" operand in the last operand position. 9413 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9414 assert(!NewOpc && "Optional cc_out operand required"); 9415 return; 9416 } 9417 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9418 // since we already have an optional CPSR def. 9419 bool definesCPSR = false; 9420 bool deadCPSR = false; 9421 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9422 ++i) { 9423 const MachineOperand &MO = MI.getOperand(i); 9424 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9425 definesCPSR = true; 9426 if (MO.isDead()) 9427 deadCPSR = true; 9428 MI.RemoveOperand(i); 9429 break; 9430 } 9431 } 9432 if (!definesCPSR) { 9433 assert(!NewOpc && "Optional cc_out operand required"); 9434 return; 9435 } 9436 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9437 if (deadCPSR) { 9438 assert(!MI.getOperand(ccOutIdx).getReg() && 9439 "expect uninitialized optional cc_out operand"); 9440 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9441 if (!Subtarget->isThumb1Only()) 9442 return; 9443 } 9444 9445 // If this instruction was defined with an optional CPSR def and its dag node 9446 // had a live implicit CPSR def, then activate the optional CPSR def. 9447 MachineOperand &MO = MI.getOperand(ccOutIdx); 9448 MO.setReg(ARM::CPSR); 9449 MO.setIsDef(true); 9450 } 9451 9452 //===----------------------------------------------------------------------===// 9453 // ARM Optimization Hooks 9454 //===----------------------------------------------------------------------===// 9455 9456 // Helper function that checks if N is a null or all ones constant. 9457 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9458 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9459 } 9460 9461 // Return true if N is conditionally 0 or all ones. 9462 // Detects these expressions where cc is an i1 value: 9463 // 9464 // (select cc 0, y) [AllOnes=0] 9465 // (select cc y, 0) [AllOnes=0] 9466 // (zext cc) [AllOnes=0] 9467 // (sext cc) [AllOnes=0/1] 9468 // (select cc -1, y) [AllOnes=1] 9469 // (select cc y, -1) [AllOnes=1] 9470 // 9471 // Invert is set when N is the null/all ones constant when CC is false. 9472 // OtherOp is set to the alternative value of N. 9473 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9474 SDValue &CC, bool &Invert, 9475 SDValue &OtherOp, 9476 SelectionDAG &DAG) { 9477 switch (N->getOpcode()) { 9478 default: return false; 9479 case ISD::SELECT: { 9480 CC = N->getOperand(0); 9481 SDValue N1 = N->getOperand(1); 9482 SDValue N2 = N->getOperand(2); 9483 if (isZeroOrAllOnes(N1, AllOnes)) { 9484 Invert = false; 9485 OtherOp = N2; 9486 return true; 9487 } 9488 if (isZeroOrAllOnes(N2, AllOnes)) { 9489 Invert = true; 9490 OtherOp = N1; 9491 return true; 9492 } 9493 return false; 9494 } 9495 case ISD::ZERO_EXTEND: 9496 // (zext cc) can never be the all ones value. 9497 if (AllOnes) 9498 return false; 9499 LLVM_FALLTHROUGH; 9500 case ISD::SIGN_EXTEND: { 9501 SDLoc dl(N); 9502 EVT VT = N->getValueType(0); 9503 CC = N->getOperand(0); 9504 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9505 return false; 9506 Invert = !AllOnes; 9507 if (AllOnes) 9508 // When looking for an AllOnes constant, N is an sext, and the 'other' 9509 // value is 0. 9510 OtherOp = DAG.getConstant(0, dl, VT); 9511 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9512 // When looking for a 0 constant, N can be zext or sext. 9513 OtherOp = DAG.getConstant(1, dl, VT); 9514 else 9515 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9516 VT); 9517 return true; 9518 } 9519 } 9520 } 9521 9522 // Combine a constant select operand into its use: 9523 // 9524 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9525 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9526 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9527 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9528 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9529 // 9530 // The transform is rejected if the select doesn't have a constant operand that 9531 // is null, or all ones when AllOnes is set. 9532 // 9533 // Also recognize sext/zext from i1: 9534 // 9535 // (add (zext cc), x) -> (select cc (add x, 1), x) 9536 // (add (sext cc), x) -> (select cc (add x, -1), x) 9537 // 9538 // These transformations eventually create predicated instructions. 9539 // 9540 // @param N The node to transform. 9541 // @param Slct The N operand that is a select. 9542 // @param OtherOp The other N operand (x above). 9543 // @param DCI Context. 9544 // @param AllOnes Require the select constant to be all ones instead of null. 9545 // @returns The new node, or SDValue() on failure. 9546 static 9547 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9548 TargetLowering::DAGCombinerInfo &DCI, 9549 bool AllOnes = false) { 9550 SelectionDAG &DAG = DCI.DAG; 9551 EVT VT = N->getValueType(0); 9552 SDValue NonConstantVal; 9553 SDValue CCOp; 9554 bool SwapSelectOps; 9555 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9556 NonConstantVal, DAG)) 9557 return SDValue(); 9558 9559 // Slct is now know to be the desired identity constant when CC is true. 9560 SDValue TrueVal = OtherOp; 9561 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9562 OtherOp, NonConstantVal); 9563 // Unless SwapSelectOps says CC should be false. 9564 if (SwapSelectOps) 9565 std::swap(TrueVal, FalseVal); 9566 9567 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9568 CCOp, TrueVal, FalseVal); 9569 } 9570 9571 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9572 static 9573 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9574 TargetLowering::DAGCombinerInfo &DCI) { 9575 SDValue N0 = N->getOperand(0); 9576 SDValue N1 = N->getOperand(1); 9577 if (N0.getNode()->hasOneUse()) 9578 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9579 return Result; 9580 if (N1.getNode()->hasOneUse()) 9581 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9582 return Result; 9583 return SDValue(); 9584 } 9585 9586 static bool IsVUZPShuffleNode(SDNode *N) { 9587 // VUZP shuffle node. 9588 if (N->getOpcode() == ARMISD::VUZP) 9589 return true; 9590 9591 // "VUZP" on i32 is an alias for VTRN. 9592 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9593 return true; 9594 9595 return false; 9596 } 9597 9598 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9599 TargetLowering::DAGCombinerInfo &DCI, 9600 const ARMSubtarget *Subtarget) { 9601 // Look for ADD(VUZP.0, VUZP.1). 9602 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9603 N0 == N1) 9604 return SDValue(); 9605 9606 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9607 if (!N->getValueType(0).is64BitVector()) 9608 return SDValue(); 9609 9610 // Generate vpadd. 9611 SelectionDAG &DAG = DCI.DAG; 9612 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9613 SDLoc dl(N); 9614 SDNode *Unzip = N0.getNode(); 9615 EVT VT = N->getValueType(0); 9616 9617 SmallVector<SDValue, 8> Ops; 9618 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9619 TLI.getPointerTy(DAG.getDataLayout()))); 9620 Ops.push_back(Unzip->getOperand(0)); 9621 Ops.push_back(Unzip->getOperand(1)); 9622 9623 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9624 } 9625 9626 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9627 TargetLowering::DAGCombinerInfo &DCI, 9628 const ARMSubtarget *Subtarget) { 9629 // Check for two extended operands. 9630 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9631 N1.getOpcode() == ISD::SIGN_EXTEND) && 9632 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9633 N1.getOpcode() == ISD::ZERO_EXTEND)) 9634 return SDValue(); 9635 9636 SDValue N00 = N0.getOperand(0); 9637 SDValue N10 = N1.getOperand(0); 9638 9639 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9640 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9641 N00 == N10) 9642 return SDValue(); 9643 9644 // We only recognize Q register paddl here; this can't be reached until 9645 // after type legalization. 9646 if (!N00.getValueType().is64BitVector() || 9647 !N0.getValueType().is128BitVector()) 9648 return SDValue(); 9649 9650 // Generate vpaddl. 9651 SelectionDAG &DAG = DCI.DAG; 9652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9653 SDLoc dl(N); 9654 EVT VT = N->getValueType(0); 9655 9656 SmallVector<SDValue, 8> Ops; 9657 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9658 unsigned Opcode; 9659 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9660 Opcode = Intrinsic::arm_neon_vpaddls; 9661 else 9662 Opcode = Intrinsic::arm_neon_vpaddlu; 9663 Ops.push_back(DAG.getConstant(Opcode, dl, 9664 TLI.getPointerTy(DAG.getDataLayout()))); 9665 EVT ElemTy = N00.getValueType().getVectorElementType(); 9666 unsigned NumElts = VT.getVectorNumElements(); 9667 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9668 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9669 N00.getOperand(0), N00.getOperand(1)); 9670 Ops.push_back(Concat); 9671 9672 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9673 } 9674 9675 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9676 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9677 // much easier to match. 9678 static SDValue 9679 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9680 TargetLowering::DAGCombinerInfo &DCI, 9681 const ARMSubtarget *Subtarget) { 9682 // Only perform optimization if after legalize, and if NEON is available. We 9683 // also expected both operands to be BUILD_VECTORs. 9684 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9685 || N0.getOpcode() != ISD::BUILD_VECTOR 9686 || N1.getOpcode() != ISD::BUILD_VECTOR) 9687 return SDValue(); 9688 9689 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9690 EVT VT = N->getValueType(0); 9691 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9692 return SDValue(); 9693 9694 // Check that the vector operands are of the right form. 9695 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9696 // operands, where N is the size of the formed vector. 9697 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9698 // index such that we have a pair wise add pattern. 9699 9700 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9701 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9702 return SDValue(); 9703 SDValue Vec = N0->getOperand(0)->getOperand(0); 9704 SDNode *V = Vec.getNode(); 9705 unsigned nextIndex = 0; 9706 9707 // For each operands to the ADD which are BUILD_VECTORs, 9708 // check to see if each of their operands are an EXTRACT_VECTOR with 9709 // the same vector and appropriate index. 9710 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9711 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9712 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9713 9714 SDValue ExtVec0 = N0->getOperand(i); 9715 SDValue ExtVec1 = N1->getOperand(i); 9716 9717 // First operand is the vector, verify its the same. 9718 if (V != ExtVec0->getOperand(0).getNode() || 9719 V != ExtVec1->getOperand(0).getNode()) 9720 return SDValue(); 9721 9722 // Second is the constant, verify its correct. 9723 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9724 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9725 9726 // For the constant, we want to see all the even or all the odd. 9727 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9728 || C1->getZExtValue() != nextIndex+1) 9729 return SDValue(); 9730 9731 // Increment index. 9732 nextIndex+=2; 9733 } else 9734 return SDValue(); 9735 } 9736 9737 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9738 // we're using the entire input vector, otherwise there's a size/legality 9739 // mismatch somewhere. 9740 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9741 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9742 return SDValue(); 9743 9744 // Create VPADDL node. 9745 SelectionDAG &DAG = DCI.DAG; 9746 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9747 9748 SDLoc dl(N); 9749 9750 // Build operand list. 9751 SmallVector<SDValue, 8> Ops; 9752 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9753 TLI.getPointerTy(DAG.getDataLayout()))); 9754 9755 // Input is the vector. 9756 Ops.push_back(Vec); 9757 9758 // Get widened type and narrowed type. 9759 MVT widenType; 9760 unsigned numElem = VT.getVectorNumElements(); 9761 9762 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9763 switch (inputLaneType.getSimpleVT().SimpleTy) { 9764 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9765 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9766 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9767 default: 9768 llvm_unreachable("Invalid vector element type for padd optimization."); 9769 } 9770 9771 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9772 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9773 return DAG.getNode(ExtOp, dl, VT, tmp); 9774 } 9775 9776 static SDValue findMUL_LOHI(SDValue V) { 9777 if (V->getOpcode() == ISD::UMUL_LOHI || 9778 V->getOpcode() == ISD::SMUL_LOHI) 9779 return V; 9780 return SDValue(); 9781 } 9782 9783 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 9784 TargetLowering::DAGCombinerInfo &DCI, 9785 const ARMSubtarget *Subtarget) { 9786 if (Subtarget->isThumb()) { 9787 if (!Subtarget->hasDSP()) 9788 return SDValue(); 9789 } else if (!Subtarget->hasV5TEOps()) 9790 return SDValue(); 9791 9792 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 9793 // accumulates the product into a 64-bit value. The 16-bit values will 9794 // be sign extended somehow or SRA'd into 32-bit values 9795 // (addc (adde (mul 16bit, 16bit), lo), hi) 9796 SDValue Mul = AddcNode->getOperand(0); 9797 SDValue Lo = AddcNode->getOperand(1); 9798 if (Mul.getOpcode() != ISD::MUL) { 9799 Lo = AddcNode->getOperand(0); 9800 Mul = AddcNode->getOperand(1); 9801 if (Mul.getOpcode() != ISD::MUL) 9802 return SDValue(); 9803 } 9804 9805 SDValue SRA = AddeNode->getOperand(0); 9806 SDValue Hi = AddeNode->getOperand(1); 9807 if (SRA.getOpcode() != ISD::SRA) { 9808 SRA = AddeNode->getOperand(1); 9809 Hi = AddeNode->getOperand(0); 9810 if (SRA.getOpcode() != ISD::SRA) 9811 return SDValue(); 9812 } 9813 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 9814 if (Const->getZExtValue() != 31) 9815 return SDValue(); 9816 } else 9817 return SDValue(); 9818 9819 if (SRA.getOperand(0) != Mul) 9820 return SDValue(); 9821 9822 SelectionDAG &DAG = DCI.DAG; 9823 SDLoc dl(AddcNode); 9824 unsigned Opcode = 0; 9825 SDValue Op0; 9826 SDValue Op1; 9827 9828 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 9829 Opcode = ARMISD::SMLALBB; 9830 Op0 = Mul.getOperand(0); 9831 Op1 = Mul.getOperand(1); 9832 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 9833 Opcode = ARMISD::SMLALBT; 9834 Op0 = Mul.getOperand(0); 9835 Op1 = Mul.getOperand(1).getOperand(0); 9836 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 9837 Opcode = ARMISD::SMLALTB; 9838 Op0 = Mul.getOperand(0).getOperand(0); 9839 Op1 = Mul.getOperand(1); 9840 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 9841 Opcode = ARMISD::SMLALTT; 9842 Op0 = Mul->getOperand(0).getOperand(0); 9843 Op1 = Mul->getOperand(1).getOperand(0); 9844 } 9845 9846 if (!Op0 || !Op1) 9847 return SDValue(); 9848 9849 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 9850 Op0, Op1, Lo, Hi); 9851 // Replace the ADDs' nodes uses by the MLA node's values. 9852 SDValue HiMLALResult(SMLAL.getNode(), 1); 9853 SDValue LoMLALResult(SMLAL.getNode(), 0); 9854 9855 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9856 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9857 9858 // Return original node to notify the driver to stop replacing. 9859 SDValue resNode(AddcNode, 0); 9860 return resNode; 9861 } 9862 9863 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode, 9864 TargetLowering::DAGCombinerInfo &DCI, 9865 const ARMSubtarget *Subtarget) { 9866 // Look for multiply add opportunities. 9867 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 9868 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 9869 // a glue link from the first add to the second add. 9870 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 9871 // a S/UMLAL instruction. 9872 // UMUL_LOHI 9873 // / :lo \ :hi 9874 // V \ [no multiline comment] 9875 // loAdd -> ADDC | 9876 // \ :carry / 9877 // V V 9878 // ADDE <- hiAdd 9879 // 9880 assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE"); 9881 9882 assert(AddeNode->getNumOperands() == 3 && 9883 AddeNode->getOperand(2).getValueType() == MVT::i32 && 9884 "ADDE node has the wrong inputs"); 9885 9886 // Check that we are chained to the right ADDC node. 9887 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9888 if (AddcNode->getOpcode() != ARMISD::ADDC) 9889 return SDValue(); 9890 9891 SDValue AddcOp0 = AddcNode->getOperand(0); 9892 SDValue AddcOp1 = AddcNode->getOperand(1); 9893 9894 // Check if the two operands are from the same mul_lohi node. 9895 if (AddcOp0.getNode() == AddcOp1.getNode()) 9896 return SDValue(); 9897 9898 assert(AddcNode->getNumValues() == 2 && 9899 AddcNode->getValueType(0) == MVT::i32 && 9900 "Expect ADDC with two result values. First: i32"); 9901 9902 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 9903 // maybe a SMLAL which multiplies two 16-bit values. 9904 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 9905 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 9906 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 9907 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 9908 return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget); 9909 9910 // Check for the triangle shape. 9911 SDValue AddeOp0 = AddeNode->getOperand(0); 9912 SDValue AddeOp1 = AddeNode->getOperand(1); 9913 9914 // Make sure that the ADDE operands are not coming from the same node. 9915 if (AddeOp0.getNode() == AddeOp1.getNode()) 9916 return SDValue(); 9917 9918 // Find the MUL_LOHI node walking up ADDE's operands. 9919 bool IsLeftOperandMUL = false; 9920 SDValue MULOp = findMUL_LOHI(AddeOp0); 9921 if (MULOp == SDValue()) 9922 MULOp = findMUL_LOHI(AddeOp1); 9923 else 9924 IsLeftOperandMUL = true; 9925 if (MULOp == SDValue()) 9926 return SDValue(); 9927 9928 // Figure out the right opcode. 9929 unsigned Opc = MULOp->getOpcode(); 9930 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 9931 9932 // Figure out the high and low input values to the MLAL node. 9933 SDValue* HiAdd = nullptr; 9934 SDValue* LoMul = nullptr; 9935 SDValue* LowAdd = nullptr; 9936 9937 // Ensure that ADDE is from high result of ISD::xMUL_LOHI. 9938 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 9939 return SDValue(); 9940 9941 if (IsLeftOperandMUL) 9942 HiAdd = &AddeOp1; 9943 else 9944 HiAdd = &AddeOp0; 9945 9946 9947 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 9948 // whose low result is fed to the ADDC we are checking. 9949 9950 if (AddcOp0 == MULOp.getValue(0)) { 9951 LoMul = &AddcOp0; 9952 LowAdd = &AddcOp1; 9953 } 9954 if (AddcOp1 == MULOp.getValue(0)) { 9955 LoMul = &AddcOp1; 9956 LowAdd = &AddcOp0; 9957 } 9958 9959 if (!LoMul) 9960 return SDValue(); 9961 9962 // If HiAdd is the same node as ADDC or is a predecessor of ADDC the 9963 // replacement below will create a cycle. 9964 if (AddcNode == HiAdd->getNode() || 9965 AddcNode->isPredecessorOf(HiAdd->getNode())) 9966 return SDValue(); 9967 9968 // Create the merged node. 9969 SelectionDAG &DAG = DCI.DAG; 9970 9971 // Build operand list. 9972 SmallVector<SDValue, 8> Ops; 9973 Ops.push_back(LoMul->getOperand(0)); 9974 Ops.push_back(LoMul->getOperand(1)); 9975 Ops.push_back(*LowAdd); 9976 Ops.push_back(*HiAdd); 9977 9978 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 9979 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9980 9981 // Replace the ADDs' nodes uses by the MLA node's values. 9982 SDValue HiMLALResult(MLALNode.getNode(), 1); 9983 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9984 9985 SDValue LoMLALResult(MLALNode.getNode(), 0); 9986 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9987 9988 // Return original node to notify the driver to stop replacing. 9989 return SDValue(AddeNode, 0); 9990 } 9991 9992 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 9993 TargetLowering::DAGCombinerInfo &DCI, 9994 const ARMSubtarget *Subtarget) { 9995 // UMAAL is similar to UMLAL except that it adds two unsigned values. 9996 // While trying to combine for the other MLAL nodes, first search for the 9997 // chance to use UMAAL. Check if Addc uses a node which has already 9998 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 9999 // as the addend, and it's handled in PerformUMLALCombine. 10000 10001 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10002 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10003 10004 // Check that we have a glued ADDC node. 10005 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10006 if (AddcNode->getOpcode() != ARMISD::ADDC) 10007 return SDValue(); 10008 10009 // Find the converted UMAAL or quit if it doesn't exist. 10010 SDNode *UmlalNode = nullptr; 10011 SDValue AddHi; 10012 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10013 UmlalNode = AddcNode->getOperand(0).getNode(); 10014 AddHi = AddcNode->getOperand(1); 10015 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10016 UmlalNode = AddcNode->getOperand(1).getNode(); 10017 AddHi = AddcNode->getOperand(0); 10018 } else { 10019 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10020 } 10021 10022 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10023 // the ADDC as well as Zero. 10024 if (!isNullConstant(UmlalNode->getOperand(3))) 10025 return SDValue(); 10026 10027 if ((isNullConstant(AddeNode->getOperand(0)) && 10028 AddeNode->getOperand(1).getNode() == UmlalNode) || 10029 (AddeNode->getOperand(0).getNode() == UmlalNode && 10030 isNullConstant(AddeNode->getOperand(1)))) { 10031 SelectionDAG &DAG = DCI.DAG; 10032 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10033 UmlalNode->getOperand(2), AddHi }; 10034 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10035 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10036 10037 // Replace the ADDs' nodes uses by the UMAAL node's values. 10038 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10039 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10040 10041 // Return original node to notify the driver to stop replacing. 10042 return SDValue(AddeNode, 0); 10043 } 10044 return SDValue(); 10045 } 10046 10047 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10048 const ARMSubtarget *Subtarget) { 10049 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10050 return SDValue(); 10051 10052 // Check that we have a pair of ADDC and ADDE as operands. 10053 // Both addends of the ADDE must be zero. 10054 SDNode* AddcNode = N->getOperand(2).getNode(); 10055 SDNode* AddeNode = N->getOperand(3).getNode(); 10056 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10057 (AddeNode->getOpcode() == ARMISD::ADDE) && 10058 isNullConstant(AddeNode->getOperand(0)) && 10059 isNullConstant(AddeNode->getOperand(1)) && 10060 (AddeNode->getOperand(2).getNode() == AddcNode)) 10061 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10062 DAG.getVTList(MVT::i32, MVT::i32), 10063 {N->getOperand(0), N->getOperand(1), 10064 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10065 else 10066 return SDValue(); 10067 } 10068 10069 static SDValue PerformAddcSubcCombine(SDNode *N, 10070 TargetLowering::DAGCombinerInfo &DCI, 10071 const ARMSubtarget *Subtarget) { 10072 SelectionDAG &DAG(DCI.DAG); 10073 10074 if (N->getOpcode() == ARMISD::ADDC) { 10075 // (ADDC (ADDE 0, 0, C), -1) -> C 10076 SDValue LHS = N->getOperand(0); 10077 SDValue RHS = N->getOperand(1); 10078 if (LHS->getOpcode() == ARMISD::ADDE && 10079 isNullConstant(LHS->getOperand(0)) && 10080 isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) { 10081 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10082 } 10083 } 10084 10085 if (Subtarget->isThumb1Only()) { 10086 SDValue RHS = N->getOperand(1); 10087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10088 int32_t imm = C->getSExtValue(); 10089 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10090 SDLoc DL(N); 10091 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10092 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10093 : ARMISD::ADDC; 10094 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10095 } 10096 } 10097 } 10098 return SDValue(); 10099 } 10100 10101 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG, 10102 const ARMSubtarget *Subtarget) { 10103 if (Subtarget->isThumb1Only()) { 10104 SDValue RHS = N->getOperand(1); 10105 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10106 int64_t imm = C->getSExtValue(); 10107 if (imm < 0) { 10108 SDLoc DL(N); 10109 10110 // The with-carry-in form matches bitwise not instead of the negation. 10111 // Effectively, the inverse interpretation of the carry flag already 10112 // accounts for part of the negation. 10113 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10114 10115 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10116 : ARMISD::ADDE; 10117 return DAG.getNode(Opcode, DL, N->getVTList(), 10118 N->getOperand(0), RHS, N->getOperand(2)); 10119 } 10120 } 10121 } 10122 return SDValue(); 10123 } 10124 10125 /// PerformADDECombine - Target-specific dag combine transform from 10126 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10127 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10128 static SDValue PerformADDECombine(SDNode *N, 10129 TargetLowering::DAGCombinerInfo &DCI, 10130 const ARMSubtarget *Subtarget) { 10131 // Only ARM and Thumb2 support UMLAL/SMLAL. 10132 if (Subtarget->isThumb1Only()) 10133 return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 10134 10135 // Only perform the checks after legalize when the pattern is available. 10136 if (DCI.isBeforeLegalize()) return SDValue(); 10137 10138 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10139 } 10140 10141 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10142 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10143 /// called with the default operands, and if that fails, with commuted 10144 /// operands. 10145 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10146 TargetLowering::DAGCombinerInfo &DCI, 10147 const ARMSubtarget *Subtarget){ 10148 // Attempt to create vpadd for this add. 10149 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10150 return Result; 10151 10152 // Attempt to create vpaddl for this add. 10153 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10154 return Result; 10155 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10156 Subtarget)) 10157 return Result; 10158 10159 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10160 if (N0.getNode()->hasOneUse()) 10161 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10162 return Result; 10163 return SDValue(); 10164 } 10165 10166 static SDValue PerformSHLSimplify(SDNode *N, 10167 TargetLowering::DAGCombinerInfo &DCI, 10168 const ARMSubtarget *ST) { 10169 // Allow the generic combiner to identify potential bswaps. 10170 if (DCI.isBeforeLegalize()) 10171 return SDValue(); 10172 10173 // DAG combiner will fold: 10174 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10175 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10176 // Other code patterns that can be also be modified have the following form: 10177 // b + ((a << 1) | 510) 10178 // b + ((a << 1) & 510) 10179 // b + ((a << 1) ^ 510) 10180 // b + ((a << 1) + 510) 10181 10182 // Many instructions can perform the shift for free, but it requires both 10183 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10184 // instruction will needed. So, unfold back to the original pattern if: 10185 // - if c1 and c2 are small enough that they don't require mov imms. 10186 // - the user(s) of the node can perform an shl 10187 10188 // No shifted operands for 16-bit instructions. 10189 if (ST->isThumb() && ST->isThumb1Only()) 10190 return SDValue(); 10191 10192 // Check that all the users could perform the shl themselves. 10193 for (auto U : N->uses()) { 10194 switch(U->getOpcode()) { 10195 default: 10196 return SDValue(); 10197 case ISD::SUB: 10198 case ISD::ADD: 10199 case ISD::AND: 10200 case ISD::OR: 10201 case ISD::XOR: 10202 case ISD::SETCC: 10203 case ARMISD::CMP: 10204 // Check that its not already using a shl. 10205 if (U->getOperand(0).getOpcode() == ISD::SHL || 10206 U->getOperand(1).getOpcode() == ISD::SHL) 10207 return SDValue(); 10208 break; 10209 } 10210 } 10211 10212 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10213 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10214 return SDValue(); 10215 10216 if (N->getOperand(0).getOpcode() != ISD::SHL) 10217 return SDValue(); 10218 10219 SDValue SHL = N->getOperand(0); 10220 10221 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10222 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10223 if (!C1ShlC2 || !C2) 10224 return SDValue(); 10225 10226 DEBUG(dbgs() << "Trying to simplify shl: "; N->dump()); 10227 10228 APInt C2Int = C2->getAPIntValue(); 10229 APInt C1Int = C1ShlC2->getAPIntValue(); 10230 10231 // Check that performing a lshr will not lose any information. 10232 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10233 C2Int.getBitWidth() - C2->getZExtValue()); 10234 if ((C1Int & Mask) != C1Int) 10235 return SDValue(); 10236 10237 // Shift the first constant. 10238 C1Int.lshrInPlace(C2Int); 10239 10240 // The immediates are encoded as an 8-bit value that can be rotated. 10241 unsigned Zeros = C1Int.countLeadingZeros() + C1Int.countTrailingZeros(); 10242 if (C1Int.getBitWidth() - Zeros > 8) 10243 return SDValue(); 10244 10245 Zeros = C2Int.countLeadingZeros() + C2Int.countTrailingZeros(); 10246 if (C2Int.getBitWidth() - Zeros > 8) 10247 return SDValue(); 10248 10249 SelectionDAG &DAG = DCI.DAG; 10250 SDLoc dl(N); 10251 SDValue X = SHL.getOperand(0); 10252 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10253 DAG.getConstant(C1Int, dl, MVT::i32)); 10254 // Shift left to compensate for the lshr of C1Int. 10255 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10256 10257 DAG.ReplaceAllUsesWith(SDValue(N, 0), Res); 10258 return SDValue(N, 0); 10259 } 10260 10261 10262 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10263 /// 10264 static SDValue PerformADDCombine(SDNode *N, 10265 TargetLowering::DAGCombinerInfo &DCI, 10266 const ARMSubtarget *Subtarget) { 10267 SDValue N0 = N->getOperand(0); 10268 SDValue N1 = N->getOperand(1); 10269 10270 // Only works one way, because it needs an immediate operand. 10271 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10272 return Result; 10273 10274 // First try with the default operand order. 10275 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10276 return Result; 10277 10278 // If that didn't work, try again with the operands commuted. 10279 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10280 } 10281 10282 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10283 /// 10284 static SDValue PerformSUBCombine(SDNode *N, 10285 TargetLowering::DAGCombinerInfo &DCI) { 10286 SDValue N0 = N->getOperand(0); 10287 SDValue N1 = N->getOperand(1); 10288 10289 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10290 if (N1.getNode()->hasOneUse()) 10291 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10292 return Result; 10293 10294 return SDValue(); 10295 } 10296 10297 /// PerformVMULCombine 10298 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10299 /// special multiplier accumulator forwarding. 10300 /// vmul d3, d0, d2 10301 /// vmla d3, d1, d2 10302 /// is faster than 10303 /// vadd d3, d0, d1 10304 /// vmul d3, d3, d2 10305 // However, for (A + B) * (A + B), 10306 // vadd d2, d0, d1 10307 // vmul d3, d0, d2 10308 // vmla d3, d1, d2 10309 // is slower than 10310 // vadd d2, d0, d1 10311 // vmul d3, d2, d2 10312 static SDValue PerformVMULCombine(SDNode *N, 10313 TargetLowering::DAGCombinerInfo &DCI, 10314 const ARMSubtarget *Subtarget) { 10315 if (!Subtarget->hasVMLxForwarding()) 10316 return SDValue(); 10317 10318 SelectionDAG &DAG = DCI.DAG; 10319 SDValue N0 = N->getOperand(0); 10320 SDValue N1 = N->getOperand(1); 10321 unsigned Opcode = N0.getOpcode(); 10322 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10323 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10324 Opcode = N1.getOpcode(); 10325 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10326 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10327 return SDValue(); 10328 std::swap(N0, N1); 10329 } 10330 10331 if (N0 == N1) 10332 return SDValue(); 10333 10334 EVT VT = N->getValueType(0); 10335 SDLoc DL(N); 10336 SDValue N00 = N0->getOperand(0); 10337 SDValue N01 = N0->getOperand(1); 10338 return DAG.getNode(Opcode, DL, VT, 10339 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10340 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10341 } 10342 10343 static SDValue PerformMULCombine(SDNode *N, 10344 TargetLowering::DAGCombinerInfo &DCI, 10345 const ARMSubtarget *Subtarget) { 10346 SelectionDAG &DAG = DCI.DAG; 10347 10348 if (Subtarget->isThumb1Only()) 10349 return SDValue(); 10350 10351 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10352 return SDValue(); 10353 10354 EVT VT = N->getValueType(0); 10355 if (VT.is64BitVector() || VT.is128BitVector()) 10356 return PerformVMULCombine(N, DCI, Subtarget); 10357 if (VT != MVT::i32) 10358 return SDValue(); 10359 10360 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10361 if (!C) 10362 return SDValue(); 10363 10364 int64_t MulAmt = C->getSExtValue(); 10365 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10366 10367 ShiftAmt = ShiftAmt & (32 - 1); 10368 SDValue V = N->getOperand(0); 10369 SDLoc DL(N); 10370 10371 SDValue Res; 10372 MulAmt >>= ShiftAmt; 10373 10374 if (MulAmt >= 0) { 10375 if (isPowerOf2_32(MulAmt - 1)) { 10376 // (mul x, 2^N + 1) => (add (shl x, N), x) 10377 Res = DAG.getNode(ISD::ADD, DL, VT, 10378 V, 10379 DAG.getNode(ISD::SHL, DL, VT, 10380 V, 10381 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10382 MVT::i32))); 10383 } else if (isPowerOf2_32(MulAmt + 1)) { 10384 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10385 Res = DAG.getNode(ISD::SUB, DL, VT, 10386 DAG.getNode(ISD::SHL, DL, VT, 10387 V, 10388 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10389 MVT::i32)), 10390 V); 10391 } else 10392 return SDValue(); 10393 } else { 10394 uint64_t MulAmtAbs = -MulAmt; 10395 if (isPowerOf2_32(MulAmtAbs + 1)) { 10396 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10397 Res = DAG.getNode(ISD::SUB, DL, VT, 10398 V, 10399 DAG.getNode(ISD::SHL, DL, VT, 10400 V, 10401 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10402 MVT::i32))); 10403 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10404 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10405 Res = DAG.getNode(ISD::ADD, DL, VT, 10406 V, 10407 DAG.getNode(ISD::SHL, DL, VT, 10408 V, 10409 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10410 MVT::i32))); 10411 Res = DAG.getNode(ISD::SUB, DL, VT, 10412 DAG.getConstant(0, DL, MVT::i32), Res); 10413 } else 10414 return SDValue(); 10415 } 10416 10417 if (ShiftAmt != 0) 10418 Res = DAG.getNode(ISD::SHL, DL, VT, 10419 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10420 10421 // Do not add new nodes to DAG combiner worklist. 10422 DCI.CombineTo(N, Res, false); 10423 return SDValue(); 10424 } 10425 10426 static SDValue PerformANDCombine(SDNode *N, 10427 TargetLowering::DAGCombinerInfo &DCI, 10428 const ARMSubtarget *Subtarget) { 10429 // Attempt to use immediate-form VBIC 10430 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10431 SDLoc dl(N); 10432 EVT VT = N->getValueType(0); 10433 SelectionDAG &DAG = DCI.DAG; 10434 10435 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10436 return SDValue(); 10437 10438 APInt SplatBits, SplatUndef; 10439 unsigned SplatBitSize; 10440 bool HasAnyUndefs; 10441 if (BVN && 10442 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10443 if (SplatBitSize <= 64) { 10444 EVT VbicVT; 10445 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10446 SplatUndef.getZExtValue(), SplatBitSize, 10447 DAG, dl, VbicVT, VT.is128BitVector(), 10448 OtherModImm); 10449 if (Val.getNode()) { 10450 SDValue Input = 10451 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10452 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10453 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10454 } 10455 } 10456 } 10457 10458 if (!Subtarget->isThumb1Only()) { 10459 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10460 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10461 return Result; 10462 10463 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10464 return Result; 10465 } 10466 10467 return SDValue(); 10468 } 10469 10470 // Try combining OR nodes to SMULWB, SMULWT. 10471 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10472 TargetLowering::DAGCombinerInfo &DCI, 10473 const ARMSubtarget *Subtarget) { 10474 if (!Subtarget->hasV6Ops() || 10475 (Subtarget->isThumb() && 10476 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10477 return SDValue(); 10478 10479 SDValue SRL = OR->getOperand(0); 10480 SDValue SHL = OR->getOperand(1); 10481 10482 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10483 SRL = OR->getOperand(1); 10484 SHL = OR->getOperand(0); 10485 } 10486 if (!isSRL16(SRL) || !isSHL16(SHL)) 10487 return SDValue(); 10488 10489 // The first operands to the shifts need to be the two results from the 10490 // same smul_lohi node. 10491 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10492 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10493 return SDValue(); 10494 10495 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10496 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10497 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10498 return SDValue(); 10499 10500 // Now we have: 10501 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10502 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10503 // For SMUWB the 16-bit value will signed extended somehow. 10504 // For SMULWT only the SRA is required. 10505 // Check both sides of SMUL_LOHI 10506 SDValue OpS16 = SMULLOHI->getOperand(0); 10507 SDValue OpS32 = SMULLOHI->getOperand(1); 10508 10509 SelectionDAG &DAG = DCI.DAG; 10510 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10511 OpS16 = OpS32; 10512 OpS32 = SMULLOHI->getOperand(0); 10513 } 10514 10515 SDLoc dl(OR); 10516 unsigned Opcode = 0; 10517 if (isS16(OpS16, DAG)) 10518 Opcode = ARMISD::SMULWB; 10519 else if (isSRA16(OpS16)) { 10520 Opcode = ARMISD::SMULWT; 10521 OpS16 = OpS16->getOperand(0); 10522 } 10523 else 10524 return SDValue(); 10525 10526 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10527 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10528 return SDValue(OR, 0); 10529 } 10530 10531 static SDValue PerformORCombineToBFI(SDNode *N, 10532 TargetLowering::DAGCombinerInfo &DCI, 10533 const ARMSubtarget *Subtarget) { 10534 // BFI is only available on V6T2+ 10535 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10536 return SDValue(); 10537 10538 EVT VT = N->getValueType(0); 10539 SDValue N0 = N->getOperand(0); 10540 SDValue N1 = N->getOperand(1); 10541 SelectionDAG &DAG = DCI.DAG; 10542 SDLoc DL(N); 10543 // 1) or (and A, mask), val => ARMbfi A, val, mask 10544 // iff (val & mask) == val 10545 // 10546 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10547 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10548 // && mask == ~mask2 10549 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10550 // && ~mask == mask2 10551 // (i.e., copy a bitfield value into another bitfield of the same width) 10552 10553 if (VT != MVT::i32) 10554 return SDValue(); 10555 10556 SDValue N00 = N0.getOperand(0); 10557 10558 // The value and the mask need to be constants so we can verify this is 10559 // actually a bitfield set. If the mask is 0xffff, we can do better 10560 // via a movt instruction, so don't use BFI in that case. 10561 SDValue MaskOp = N0.getOperand(1); 10562 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10563 if (!MaskC) 10564 return SDValue(); 10565 unsigned Mask = MaskC->getZExtValue(); 10566 if (Mask == 0xffff) 10567 return SDValue(); 10568 SDValue Res; 10569 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10570 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10571 if (N1C) { 10572 unsigned Val = N1C->getZExtValue(); 10573 if ((Val & ~Mask) != Val) 10574 return SDValue(); 10575 10576 if (ARM::isBitFieldInvertedMask(Mask)) { 10577 Val >>= countTrailingZeros(~Mask); 10578 10579 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10580 DAG.getConstant(Val, DL, MVT::i32), 10581 DAG.getConstant(Mask, DL, MVT::i32)); 10582 10583 DCI.CombineTo(N, Res, false); 10584 // Return value from the original node to inform the combiner than N is 10585 // now dead. 10586 return SDValue(N, 0); 10587 } 10588 } else if (N1.getOpcode() == ISD::AND) { 10589 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10590 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10591 if (!N11C) 10592 return SDValue(); 10593 unsigned Mask2 = N11C->getZExtValue(); 10594 10595 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10596 // as is to match. 10597 if (ARM::isBitFieldInvertedMask(Mask) && 10598 (Mask == ~Mask2)) { 10599 // The pack halfword instruction works better for masks that fit it, 10600 // so use that when it's available. 10601 if (Subtarget->hasDSP() && 10602 (Mask == 0xffff || Mask == 0xffff0000)) 10603 return SDValue(); 10604 // 2a 10605 unsigned amt = countTrailingZeros(Mask2); 10606 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10607 DAG.getConstant(amt, DL, MVT::i32)); 10608 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10609 DAG.getConstant(Mask, DL, MVT::i32)); 10610 DCI.CombineTo(N, Res, false); 10611 // Return value from the original node to inform the combiner than N is 10612 // now dead. 10613 return SDValue(N, 0); 10614 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10615 (~Mask == Mask2)) { 10616 // The pack halfword instruction works better for masks that fit it, 10617 // so use that when it's available. 10618 if (Subtarget->hasDSP() && 10619 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10620 return SDValue(); 10621 // 2b 10622 unsigned lsb = countTrailingZeros(Mask); 10623 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10624 DAG.getConstant(lsb, DL, MVT::i32)); 10625 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10626 DAG.getConstant(Mask2, DL, MVT::i32)); 10627 DCI.CombineTo(N, Res, false); 10628 // Return value from the original node to inform the combiner than N is 10629 // now dead. 10630 return SDValue(N, 0); 10631 } 10632 } 10633 10634 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10635 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10636 ARM::isBitFieldInvertedMask(~Mask)) { 10637 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10638 // where lsb(mask) == #shamt and masked bits of B are known zero. 10639 SDValue ShAmt = N00.getOperand(1); 10640 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10641 unsigned LSB = countTrailingZeros(Mask); 10642 if (ShAmtC != LSB) 10643 return SDValue(); 10644 10645 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10646 DAG.getConstant(~Mask, DL, MVT::i32)); 10647 10648 DCI.CombineTo(N, Res, false); 10649 // Return value from the original node to inform the combiner than N is 10650 // now dead. 10651 return SDValue(N, 0); 10652 } 10653 10654 return SDValue(); 10655 } 10656 10657 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10658 static SDValue PerformORCombine(SDNode *N, 10659 TargetLowering::DAGCombinerInfo &DCI, 10660 const ARMSubtarget *Subtarget) { 10661 // Attempt to use immediate-form VORR 10662 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10663 SDLoc dl(N); 10664 EVT VT = N->getValueType(0); 10665 SelectionDAG &DAG = DCI.DAG; 10666 10667 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10668 return SDValue(); 10669 10670 APInt SplatBits, SplatUndef; 10671 unsigned SplatBitSize; 10672 bool HasAnyUndefs; 10673 if (BVN && Subtarget->hasNEON() && 10674 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10675 if (SplatBitSize <= 64) { 10676 EVT VorrVT; 10677 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10678 SplatUndef.getZExtValue(), SplatBitSize, 10679 DAG, dl, VorrVT, VT.is128BitVector(), 10680 OtherModImm); 10681 if (Val.getNode()) { 10682 SDValue Input = 10683 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10684 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10685 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10686 } 10687 } 10688 } 10689 10690 if (!Subtarget->isThumb1Only()) { 10691 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10692 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10693 return Result; 10694 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10695 return Result; 10696 } 10697 10698 SDValue N0 = N->getOperand(0); 10699 SDValue N1 = N->getOperand(1); 10700 10701 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10702 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10703 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10704 10705 // The code below optimizes (or (and X, Y), Z). 10706 // The AND operand needs to have a single user to make these optimizations 10707 // profitable. 10708 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10709 return SDValue(); 10710 10711 APInt SplatUndef; 10712 unsigned SplatBitSize; 10713 bool HasAnyUndefs; 10714 10715 APInt SplatBits0, SplatBits1; 10716 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 10717 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 10718 // Ensure that the second operand of both ands are constants 10719 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 10720 HasAnyUndefs) && !HasAnyUndefs) { 10721 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 10722 HasAnyUndefs) && !HasAnyUndefs) { 10723 // Ensure that the bit width of the constants are the same and that 10724 // the splat arguments are logical inverses as per the pattern we 10725 // are trying to simplify. 10726 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 10727 SplatBits0 == ~SplatBits1) { 10728 // Canonicalize the vector type to make instruction selection 10729 // simpler. 10730 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 10731 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 10732 N0->getOperand(1), 10733 N0->getOperand(0), 10734 N1->getOperand(0)); 10735 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 10736 } 10737 } 10738 } 10739 } 10740 10741 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 10742 // reasonable. 10743 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 10744 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 10745 return Res; 10746 } 10747 10748 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10749 return Result; 10750 10751 return SDValue(); 10752 } 10753 10754 static SDValue PerformXORCombine(SDNode *N, 10755 TargetLowering::DAGCombinerInfo &DCI, 10756 const ARMSubtarget *Subtarget) { 10757 EVT VT = N->getValueType(0); 10758 SelectionDAG &DAG = DCI.DAG; 10759 10760 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10761 return SDValue(); 10762 10763 if (!Subtarget->isThumb1Only()) { 10764 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10765 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10766 return Result; 10767 10768 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10769 return Result; 10770 } 10771 10772 return SDValue(); 10773 } 10774 10775 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 10776 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 10777 // their position in "to" (Rd). 10778 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 10779 assert(N->getOpcode() == ARMISD::BFI); 10780 10781 SDValue From = N->getOperand(1); 10782 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 10783 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 10784 10785 // If the Base came from a SHR #C, we can deduce that it is really testing bit 10786 // #C in the base of the SHR. 10787 if (From->getOpcode() == ISD::SRL && 10788 isa<ConstantSDNode>(From->getOperand(1))) { 10789 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 10790 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 10791 FromMask <<= Shift.getLimitedValue(31); 10792 From = From->getOperand(0); 10793 } 10794 10795 return From; 10796 } 10797 10798 // If A and B contain one contiguous set of bits, does A | B == A . B? 10799 // 10800 // Neither A nor B must be zero. 10801 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 10802 unsigned LastActiveBitInA = A.countTrailingZeros(); 10803 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 10804 return LastActiveBitInA - 1 == FirstActiveBitInB; 10805 } 10806 10807 static SDValue FindBFIToCombineWith(SDNode *N) { 10808 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 10809 // if one exists. 10810 APInt ToMask, FromMask; 10811 SDValue From = ParseBFI(N, ToMask, FromMask); 10812 SDValue To = N->getOperand(0); 10813 10814 // Now check for a compatible BFI to merge with. We can pass through BFIs that 10815 // aren't compatible, but not if they set the same bit in their destination as 10816 // we do (or that of any BFI we're going to combine with). 10817 SDValue V = To; 10818 APInt CombinedToMask = ToMask; 10819 while (V.getOpcode() == ARMISD::BFI) { 10820 APInt NewToMask, NewFromMask; 10821 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 10822 if (NewFrom != From) { 10823 // This BFI has a different base. Keep going. 10824 CombinedToMask |= NewToMask; 10825 V = V.getOperand(0); 10826 continue; 10827 } 10828 10829 // Do the written bits conflict with any we've seen so far? 10830 if ((NewToMask & CombinedToMask).getBoolValue()) 10831 // Conflicting bits - bail out because going further is unsafe. 10832 return SDValue(); 10833 10834 // Are the new bits contiguous when combined with the old bits? 10835 if (BitsProperlyConcatenate(ToMask, NewToMask) && 10836 BitsProperlyConcatenate(FromMask, NewFromMask)) 10837 return V; 10838 if (BitsProperlyConcatenate(NewToMask, ToMask) && 10839 BitsProperlyConcatenate(NewFromMask, FromMask)) 10840 return V; 10841 10842 // We've seen a write to some bits, so track it. 10843 CombinedToMask |= NewToMask; 10844 // Keep going... 10845 V = V.getOperand(0); 10846 } 10847 10848 return SDValue(); 10849 } 10850 10851 static SDValue PerformBFICombine(SDNode *N, 10852 TargetLowering::DAGCombinerInfo &DCI) { 10853 SDValue N1 = N->getOperand(1); 10854 if (N1.getOpcode() == ISD::AND) { 10855 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 10856 // the bits being cleared by the AND are not demanded by the BFI. 10857 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10858 if (!N11C) 10859 return SDValue(); 10860 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10861 unsigned LSB = countTrailingZeros(~InvMask); 10862 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 10863 assert(Width < 10864 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 10865 "undefined behavior"); 10866 unsigned Mask = (1u << Width) - 1; 10867 unsigned Mask2 = N11C->getZExtValue(); 10868 if ((Mask & (~Mask2)) == 0) 10869 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 10870 N->getOperand(0), N1.getOperand(0), 10871 N->getOperand(2)); 10872 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 10873 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 10874 // Keep track of any consecutive bits set that all come from the same base 10875 // value. We can combine these together into a single BFI. 10876 SDValue CombineBFI = FindBFIToCombineWith(N); 10877 if (CombineBFI == SDValue()) 10878 return SDValue(); 10879 10880 // We've found a BFI. 10881 APInt ToMask1, FromMask1; 10882 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 10883 10884 APInt ToMask2, FromMask2; 10885 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 10886 assert(From1 == From2); 10887 (void)From2; 10888 10889 // First, unlink CombineBFI. 10890 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 10891 // Then create a new BFI, combining the two together. 10892 APInt NewFromMask = FromMask1 | FromMask2; 10893 APInt NewToMask = ToMask1 | ToMask2; 10894 10895 EVT VT = N->getValueType(0); 10896 SDLoc dl(N); 10897 10898 if (NewFromMask[0] == 0) 10899 From1 = DCI.DAG.getNode( 10900 ISD::SRL, dl, VT, From1, 10901 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 10902 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 10903 DCI.DAG.getConstant(~NewToMask, dl, VT)); 10904 } 10905 return SDValue(); 10906 } 10907 10908 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 10909 /// ARMISD::VMOVRRD. 10910 static SDValue PerformVMOVRRDCombine(SDNode *N, 10911 TargetLowering::DAGCombinerInfo &DCI, 10912 const ARMSubtarget *Subtarget) { 10913 // vmovrrd(vmovdrr x, y) -> x,y 10914 SDValue InDouble = N->getOperand(0); 10915 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 10916 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 10917 10918 // vmovrrd(load f64) -> (load i32), (load i32) 10919 SDNode *InNode = InDouble.getNode(); 10920 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 10921 InNode->getValueType(0) == MVT::f64 && 10922 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 10923 !cast<LoadSDNode>(InNode)->isVolatile()) { 10924 // TODO: Should this be done for non-FrameIndex operands? 10925 LoadSDNode *LD = cast<LoadSDNode>(InNode); 10926 10927 SelectionDAG &DAG = DCI.DAG; 10928 SDLoc DL(LD); 10929 SDValue BasePtr = LD->getBasePtr(); 10930 SDValue NewLD1 = 10931 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 10932 LD->getAlignment(), LD->getMemOperand()->getFlags()); 10933 10934 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10935 DAG.getConstant(4, DL, MVT::i32)); 10936 SDValue NewLD2 = DAG.getLoad( 10937 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 10938 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 10939 10940 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 10941 if (DCI.DAG.getDataLayout().isBigEndian()) 10942 std::swap (NewLD1, NewLD2); 10943 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 10944 return Result; 10945 } 10946 10947 return SDValue(); 10948 } 10949 10950 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 10951 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 10952 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 10953 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 10954 SDValue Op0 = N->getOperand(0); 10955 SDValue Op1 = N->getOperand(1); 10956 if (Op0.getOpcode() == ISD::BITCAST) 10957 Op0 = Op0.getOperand(0); 10958 if (Op1.getOpcode() == ISD::BITCAST) 10959 Op1 = Op1.getOperand(0); 10960 if (Op0.getOpcode() == ARMISD::VMOVRRD && 10961 Op0.getNode() == Op1.getNode() && 10962 Op0.getResNo() == 0 && Op1.getResNo() == 1) 10963 return DAG.getNode(ISD::BITCAST, SDLoc(N), 10964 N->getValueType(0), Op0.getOperand(0)); 10965 return SDValue(); 10966 } 10967 10968 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 10969 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 10970 /// i64 vector to have f64 elements, since the value can then be loaded 10971 /// directly into a VFP register. 10972 static bool hasNormalLoadOperand(SDNode *N) { 10973 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 10974 for (unsigned i = 0; i < NumElts; ++i) { 10975 SDNode *Elt = N->getOperand(i).getNode(); 10976 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 10977 return true; 10978 } 10979 return false; 10980 } 10981 10982 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 10983 /// ISD::BUILD_VECTOR. 10984 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 10985 TargetLowering::DAGCombinerInfo &DCI, 10986 const ARMSubtarget *Subtarget) { 10987 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 10988 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 10989 // into a pair of GPRs, which is fine when the value is used as a scalar, 10990 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 10991 SelectionDAG &DAG = DCI.DAG; 10992 if (N->getNumOperands() == 2) 10993 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 10994 return RV; 10995 10996 // Load i64 elements as f64 values so that type legalization does not split 10997 // them up into i32 values. 10998 EVT VT = N->getValueType(0); 10999 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11000 return SDValue(); 11001 SDLoc dl(N); 11002 SmallVector<SDValue, 8> Ops; 11003 unsigned NumElts = VT.getVectorNumElements(); 11004 for (unsigned i = 0; i < NumElts; ++i) { 11005 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11006 Ops.push_back(V); 11007 // Make the DAGCombiner fold the bitcast. 11008 DCI.AddToWorklist(V.getNode()); 11009 } 11010 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11011 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11012 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11013 } 11014 11015 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11016 static SDValue 11017 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11018 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11019 // At that time, we may have inserted bitcasts from integer to float. 11020 // If these bitcasts have survived DAGCombine, change the lowering of this 11021 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11022 // force to use floating point types. 11023 11024 // Make sure we can change the type of the vector. 11025 // This is possible iff: 11026 // 1. The vector is only used in a bitcast to a integer type. I.e., 11027 // 1.1. Vector is used only once. 11028 // 1.2. Use is a bit convert to an integer type. 11029 // 2. The size of its operands are 32-bits (64-bits are not legal). 11030 EVT VT = N->getValueType(0); 11031 EVT EltVT = VT.getVectorElementType(); 11032 11033 // Check 1.1. and 2. 11034 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11035 return SDValue(); 11036 11037 // By construction, the input type must be float. 11038 assert(EltVT == MVT::f32 && "Unexpected type!"); 11039 11040 // Check 1.2. 11041 SDNode *Use = *N->use_begin(); 11042 if (Use->getOpcode() != ISD::BITCAST || 11043 Use->getValueType(0).isFloatingPoint()) 11044 return SDValue(); 11045 11046 // Check profitability. 11047 // Model is, if more than half of the relevant operands are bitcast from 11048 // i32, turn the build_vector into a sequence of insert_vector_elt. 11049 // Relevant operands are everything that is not statically 11050 // (i.e., at compile time) bitcasted. 11051 unsigned NumOfBitCastedElts = 0; 11052 unsigned NumElts = VT.getVectorNumElements(); 11053 unsigned NumOfRelevantElts = NumElts; 11054 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11055 SDValue Elt = N->getOperand(Idx); 11056 if (Elt->getOpcode() == ISD::BITCAST) { 11057 // Assume only bit cast to i32 will go away. 11058 if (Elt->getOperand(0).getValueType() == MVT::i32) 11059 ++NumOfBitCastedElts; 11060 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11061 // Constants are statically casted, thus do not count them as 11062 // relevant operands. 11063 --NumOfRelevantElts; 11064 } 11065 11066 // Check if more than half of the elements require a non-free bitcast. 11067 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11068 return SDValue(); 11069 11070 SelectionDAG &DAG = DCI.DAG; 11071 // Create the new vector type. 11072 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11073 // Check if the type is legal. 11074 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11075 if (!TLI.isTypeLegal(VecVT)) 11076 return SDValue(); 11077 11078 // Combine: 11079 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11080 // => BITCAST INSERT_VECTOR_ELT 11081 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11082 // (BITCAST EN), N. 11083 SDValue Vec = DAG.getUNDEF(VecVT); 11084 SDLoc dl(N); 11085 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11086 SDValue V = N->getOperand(Idx); 11087 if (V.isUndef()) 11088 continue; 11089 if (V.getOpcode() == ISD::BITCAST && 11090 V->getOperand(0).getValueType() == MVT::i32) 11091 // Fold obvious case. 11092 V = V.getOperand(0); 11093 else { 11094 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11095 // Make the DAGCombiner fold the bitcasts. 11096 DCI.AddToWorklist(V.getNode()); 11097 } 11098 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11099 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11100 } 11101 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11102 // Make the DAGCombiner fold the bitcasts. 11103 DCI.AddToWorklist(Vec.getNode()); 11104 return Vec; 11105 } 11106 11107 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11108 /// ISD::INSERT_VECTOR_ELT. 11109 static SDValue PerformInsertEltCombine(SDNode *N, 11110 TargetLowering::DAGCombinerInfo &DCI) { 11111 // Bitcast an i64 load inserted into a vector to f64. 11112 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11113 EVT VT = N->getValueType(0); 11114 SDNode *Elt = N->getOperand(1).getNode(); 11115 if (VT.getVectorElementType() != MVT::i64 || 11116 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11117 return SDValue(); 11118 11119 SelectionDAG &DAG = DCI.DAG; 11120 SDLoc dl(N); 11121 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11122 VT.getVectorNumElements()); 11123 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11124 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11125 // Make the DAGCombiner fold the bitcasts. 11126 DCI.AddToWorklist(Vec.getNode()); 11127 DCI.AddToWorklist(V.getNode()); 11128 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11129 Vec, V, N->getOperand(2)); 11130 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11131 } 11132 11133 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11134 /// ISD::VECTOR_SHUFFLE. 11135 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11136 // The LLVM shufflevector instruction does not require the shuffle mask 11137 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11138 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11139 // operands do not match the mask length, they are extended by concatenating 11140 // them with undef vectors. That is probably the right thing for other 11141 // targets, but for NEON it is better to concatenate two double-register 11142 // size vector operands into a single quad-register size vector. Do that 11143 // transformation here: 11144 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11145 // shuffle(concat(v1, v2), undef) 11146 SDValue Op0 = N->getOperand(0); 11147 SDValue Op1 = N->getOperand(1); 11148 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11149 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11150 Op0.getNumOperands() != 2 || 11151 Op1.getNumOperands() != 2) 11152 return SDValue(); 11153 SDValue Concat0Op1 = Op0.getOperand(1); 11154 SDValue Concat1Op1 = Op1.getOperand(1); 11155 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11156 return SDValue(); 11157 // Skip the transformation if any of the types are illegal. 11158 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11159 EVT VT = N->getValueType(0); 11160 if (!TLI.isTypeLegal(VT) || 11161 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11162 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11163 return SDValue(); 11164 11165 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11166 Op0.getOperand(0), Op1.getOperand(0)); 11167 // Translate the shuffle mask. 11168 SmallVector<int, 16> NewMask; 11169 unsigned NumElts = VT.getVectorNumElements(); 11170 unsigned HalfElts = NumElts/2; 11171 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11172 for (unsigned n = 0; n < NumElts; ++n) { 11173 int MaskElt = SVN->getMaskElt(n); 11174 int NewElt = -1; 11175 if (MaskElt < (int)HalfElts) 11176 NewElt = MaskElt; 11177 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11178 NewElt = HalfElts + MaskElt - NumElts; 11179 NewMask.push_back(NewElt); 11180 } 11181 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11182 DAG.getUNDEF(VT), NewMask); 11183 } 11184 11185 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11186 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11187 /// base address updates. 11188 /// For generic load/stores, the memory type is assumed to be a vector. 11189 /// The caller is assumed to have checked legality. 11190 static SDValue CombineBaseUpdate(SDNode *N, 11191 TargetLowering::DAGCombinerInfo &DCI) { 11192 SelectionDAG &DAG = DCI.DAG; 11193 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11194 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11195 const bool isStore = N->getOpcode() == ISD::STORE; 11196 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11197 SDValue Addr = N->getOperand(AddrOpIdx); 11198 MemSDNode *MemN = cast<MemSDNode>(N); 11199 SDLoc dl(N); 11200 11201 // Search for a use of the address operand that is an increment. 11202 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11203 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11204 SDNode *User = *UI; 11205 if (User->getOpcode() != ISD::ADD || 11206 UI.getUse().getResNo() != Addr.getResNo()) 11207 continue; 11208 11209 // Check that the add is independent of the load/store. Otherwise, folding 11210 // it would create a cycle. 11211 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 11212 continue; 11213 11214 // Find the new opcode for the updating load/store. 11215 bool isLoadOp = true; 11216 bool isLaneOp = false; 11217 unsigned NewOpc = 0; 11218 unsigned NumVecs = 0; 11219 if (isIntrinsic) { 11220 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11221 switch (IntNo) { 11222 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11223 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11224 NumVecs = 1; break; 11225 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11226 NumVecs = 2; break; 11227 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11228 NumVecs = 3; break; 11229 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11230 NumVecs = 4; break; 11231 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11232 NumVecs = 2; isLaneOp = true; break; 11233 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11234 NumVecs = 3; isLaneOp = true; break; 11235 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11236 NumVecs = 4; isLaneOp = true; break; 11237 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11238 NumVecs = 1; isLoadOp = false; break; 11239 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11240 NumVecs = 2; isLoadOp = false; break; 11241 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11242 NumVecs = 3; isLoadOp = false; break; 11243 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11244 NumVecs = 4; isLoadOp = false; break; 11245 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11246 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11247 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11248 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11249 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11250 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11251 } 11252 } else { 11253 isLaneOp = true; 11254 switch (N->getOpcode()) { 11255 default: llvm_unreachable("unexpected opcode for Neon base update"); 11256 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11257 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11258 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11259 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11260 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11261 NumVecs = 1; isLaneOp = false; break; 11262 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11263 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11264 } 11265 } 11266 11267 // Find the size of memory referenced by the load/store. 11268 EVT VecTy; 11269 if (isLoadOp) { 11270 VecTy = N->getValueType(0); 11271 } else if (isIntrinsic) { 11272 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11273 } else { 11274 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11275 VecTy = N->getOperand(1).getValueType(); 11276 } 11277 11278 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11279 if (isLaneOp) 11280 NumBytes /= VecTy.getVectorNumElements(); 11281 11282 // If the increment is a constant, it must match the memory ref size. 11283 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11284 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11285 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11286 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11287 // separate instructions that make it harder to use a non-constant update. 11288 continue; 11289 } 11290 11291 // OK, we found an ADD we can fold into the base update. 11292 // Now, create a _UPD node, taking care of not breaking alignment. 11293 11294 EVT AlignedVecTy = VecTy; 11295 unsigned Alignment = MemN->getAlignment(); 11296 11297 // If this is a less-than-standard-aligned load/store, change the type to 11298 // match the standard alignment. 11299 // The alignment is overlooked when selecting _UPD variants; and it's 11300 // easier to introduce bitcasts here than fix that. 11301 // There are 3 ways to get to this base-update combine: 11302 // - intrinsics: they are assumed to be properly aligned (to the standard 11303 // alignment of the memory type), so we don't need to do anything. 11304 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11305 // intrinsics, so, likewise, there's nothing to do. 11306 // - generic load/store instructions: the alignment is specified as an 11307 // explicit operand, rather than implicitly as the standard alignment 11308 // of the memory type (like the intrisics). We need to change the 11309 // memory type to match the explicit alignment. That way, we don't 11310 // generate non-standard-aligned ARMISD::VLDx nodes. 11311 if (isa<LSBaseSDNode>(N)) { 11312 if (Alignment == 0) 11313 Alignment = 1; 11314 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11315 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11316 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11317 assert(!isLaneOp && "Unexpected generic load/store lane."); 11318 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11319 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11320 } 11321 // Don't set an explicit alignment on regular load/stores that we want 11322 // to transform to VLD/VST 1_UPD nodes. 11323 // This matches the behavior of regular load/stores, which only get an 11324 // explicit alignment if the MMO alignment is larger than the standard 11325 // alignment of the memory type. 11326 // Intrinsics, however, always get an explicit alignment, set to the 11327 // alignment of the MMO. 11328 Alignment = 1; 11329 } 11330 11331 // Create the new updating load/store node. 11332 // First, create an SDVTList for the new updating node's results. 11333 EVT Tys[6]; 11334 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11335 unsigned n; 11336 for (n = 0; n < NumResultVecs; ++n) 11337 Tys[n] = AlignedVecTy; 11338 Tys[n++] = MVT::i32; 11339 Tys[n] = MVT::Other; 11340 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11341 11342 // Then, gather the new node's operands. 11343 SmallVector<SDValue, 8> Ops; 11344 Ops.push_back(N->getOperand(0)); // incoming chain 11345 Ops.push_back(N->getOperand(AddrOpIdx)); 11346 Ops.push_back(Inc); 11347 11348 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11349 // Try to match the intrinsic's signature 11350 Ops.push_back(StN->getValue()); 11351 } else { 11352 // Loads (and of course intrinsics) match the intrinsics' signature, 11353 // so just add all but the alignment operand. 11354 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11355 Ops.push_back(N->getOperand(i)); 11356 } 11357 11358 // For all node types, the alignment operand is always the last one. 11359 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11360 11361 // If this is a non-standard-aligned STORE, the penultimate operand is the 11362 // stored value. Bitcast it to the aligned type. 11363 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11364 SDValue &StVal = Ops[Ops.size()-2]; 11365 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11366 } 11367 11368 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11369 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11370 MemN->getMemOperand()); 11371 11372 // Update the uses. 11373 SmallVector<SDValue, 5> NewResults; 11374 for (unsigned i = 0; i < NumResultVecs; ++i) 11375 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11376 11377 // If this is an non-standard-aligned LOAD, the first result is the loaded 11378 // value. Bitcast it to the expected result type. 11379 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11380 SDValue &LdVal = NewResults[0]; 11381 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11382 } 11383 11384 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11385 DCI.CombineTo(N, NewResults); 11386 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11387 11388 break; 11389 } 11390 return SDValue(); 11391 } 11392 11393 static SDValue PerformVLDCombine(SDNode *N, 11394 TargetLowering::DAGCombinerInfo &DCI) { 11395 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11396 return SDValue(); 11397 11398 return CombineBaseUpdate(N, DCI); 11399 } 11400 11401 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11402 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11403 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11404 /// return true. 11405 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11406 SelectionDAG &DAG = DCI.DAG; 11407 EVT VT = N->getValueType(0); 11408 // vldN-dup instructions only support 64-bit vectors for N > 1. 11409 if (!VT.is64BitVector()) 11410 return false; 11411 11412 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11413 SDNode *VLD = N->getOperand(0).getNode(); 11414 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11415 return false; 11416 unsigned NumVecs = 0; 11417 unsigned NewOpc = 0; 11418 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11419 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11420 NumVecs = 2; 11421 NewOpc = ARMISD::VLD2DUP; 11422 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11423 NumVecs = 3; 11424 NewOpc = ARMISD::VLD3DUP; 11425 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11426 NumVecs = 4; 11427 NewOpc = ARMISD::VLD4DUP; 11428 } else { 11429 return false; 11430 } 11431 11432 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11433 // numbers match the load. 11434 unsigned VLDLaneNo = 11435 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11436 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11437 UI != UE; ++UI) { 11438 // Ignore uses of the chain result. 11439 if (UI.getUse().getResNo() == NumVecs) 11440 continue; 11441 SDNode *User = *UI; 11442 if (User->getOpcode() != ARMISD::VDUPLANE || 11443 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11444 return false; 11445 } 11446 11447 // Create the vldN-dup node. 11448 EVT Tys[5]; 11449 unsigned n; 11450 for (n = 0; n < NumVecs; ++n) 11451 Tys[n] = VT; 11452 Tys[n] = MVT::Other; 11453 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11454 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11455 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11456 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11457 Ops, VLDMemInt->getMemoryVT(), 11458 VLDMemInt->getMemOperand()); 11459 11460 // Update the uses. 11461 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11462 UI != UE; ++UI) { 11463 unsigned ResNo = UI.getUse().getResNo(); 11464 // Ignore uses of the chain result. 11465 if (ResNo == NumVecs) 11466 continue; 11467 SDNode *User = *UI; 11468 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11469 } 11470 11471 // Now the vldN-lane intrinsic is dead except for its chain result. 11472 // Update uses of the chain. 11473 std::vector<SDValue> VLDDupResults; 11474 for (unsigned n = 0; n < NumVecs; ++n) 11475 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11476 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11477 DCI.CombineTo(VLD, VLDDupResults); 11478 11479 return true; 11480 } 11481 11482 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11483 /// ARMISD::VDUPLANE. 11484 static SDValue PerformVDUPLANECombine(SDNode *N, 11485 TargetLowering::DAGCombinerInfo &DCI) { 11486 SDValue Op = N->getOperand(0); 11487 11488 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11489 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11490 if (CombineVLDDUP(N, DCI)) 11491 return SDValue(N, 0); 11492 11493 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11494 // redundant. Ignore bit_converts for now; element sizes are checked below. 11495 while (Op.getOpcode() == ISD::BITCAST) 11496 Op = Op.getOperand(0); 11497 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11498 return SDValue(); 11499 11500 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11501 unsigned EltSize = Op.getScalarValueSizeInBits(); 11502 // The canonical VMOV for a zero vector uses a 32-bit element size. 11503 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11504 unsigned EltBits; 11505 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11506 EltSize = 8; 11507 EVT VT = N->getValueType(0); 11508 if (EltSize > VT.getScalarSizeInBits()) 11509 return SDValue(); 11510 11511 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11512 } 11513 11514 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11515 static SDValue PerformVDUPCombine(SDNode *N, 11516 TargetLowering::DAGCombinerInfo &DCI) { 11517 SelectionDAG &DAG = DCI.DAG; 11518 SDValue Op = N->getOperand(0); 11519 11520 // Match VDUP(LOAD) -> VLD1DUP. 11521 // We match this pattern here rather than waiting for isel because the 11522 // transform is only legal for unindexed loads. 11523 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11524 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11525 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11526 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11527 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11528 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11529 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11530 Ops, LD->getMemoryVT(), 11531 LD->getMemOperand()); 11532 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11533 return VLDDup; 11534 } 11535 11536 return SDValue(); 11537 } 11538 11539 static SDValue PerformLOADCombine(SDNode *N, 11540 TargetLowering::DAGCombinerInfo &DCI) { 11541 EVT VT = N->getValueType(0); 11542 11543 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11544 if (ISD::isNormalLoad(N) && VT.isVector() && 11545 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11546 return CombineBaseUpdate(N, DCI); 11547 11548 return SDValue(); 11549 } 11550 11551 /// PerformSTORECombine - Target-specific dag combine xforms for 11552 /// ISD::STORE. 11553 static SDValue PerformSTORECombine(SDNode *N, 11554 TargetLowering::DAGCombinerInfo &DCI) { 11555 StoreSDNode *St = cast<StoreSDNode>(N); 11556 if (St->isVolatile()) 11557 return SDValue(); 11558 11559 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11560 // pack all of the elements in one place. Next, store to memory in fewer 11561 // chunks. 11562 SDValue StVal = St->getValue(); 11563 EVT VT = StVal.getValueType(); 11564 if (St->isTruncatingStore() && VT.isVector()) { 11565 SelectionDAG &DAG = DCI.DAG; 11566 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11567 EVT StVT = St->getMemoryVT(); 11568 unsigned NumElems = VT.getVectorNumElements(); 11569 assert(StVT != VT && "Cannot truncate to the same type"); 11570 unsigned FromEltSz = VT.getScalarSizeInBits(); 11571 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11572 11573 // From, To sizes and ElemCount must be pow of two 11574 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11575 11576 // We are going to use the original vector elt for storing. 11577 // Accumulated smaller vector elements must be a multiple of the store size. 11578 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11579 11580 unsigned SizeRatio = FromEltSz / ToEltSz; 11581 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11582 11583 // Create a type on which we perform the shuffle. 11584 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11585 NumElems*SizeRatio); 11586 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11587 11588 SDLoc DL(St); 11589 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11590 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11591 for (unsigned i = 0; i < NumElems; ++i) 11592 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11593 ? (i + 1) * SizeRatio - 1 11594 : i * SizeRatio; 11595 11596 // Can't shuffle using an illegal type. 11597 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11598 11599 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11600 DAG.getUNDEF(WideVec.getValueType()), 11601 ShuffleVec); 11602 // At this point all of the data is stored at the bottom of the 11603 // register. We now need to save it to mem. 11604 11605 // Find the largest store unit 11606 MVT StoreType = MVT::i8; 11607 for (MVT Tp : MVT::integer_valuetypes()) { 11608 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11609 StoreType = Tp; 11610 } 11611 // Didn't find a legal store type. 11612 if (!TLI.isTypeLegal(StoreType)) 11613 return SDValue(); 11614 11615 // Bitcast the original vector into a vector of store-size units 11616 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11617 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11618 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11619 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11620 SmallVector<SDValue, 8> Chains; 11621 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11622 TLI.getPointerTy(DAG.getDataLayout())); 11623 SDValue BasePtr = St->getBasePtr(); 11624 11625 // Perform one or more big stores into memory. 11626 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11627 for (unsigned I = 0; I < E; I++) { 11628 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11629 StoreType, ShuffWide, 11630 DAG.getIntPtrConstant(I, DL)); 11631 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11632 St->getPointerInfo(), St->getAlignment(), 11633 St->getMemOperand()->getFlags()); 11634 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11635 Increment); 11636 Chains.push_back(Ch); 11637 } 11638 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11639 } 11640 11641 if (!ISD::isNormalStore(St)) 11642 return SDValue(); 11643 11644 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11645 // ARM stores of arguments in the same cache line. 11646 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11647 StVal.getNode()->hasOneUse()) { 11648 SelectionDAG &DAG = DCI.DAG; 11649 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11650 SDLoc DL(St); 11651 SDValue BasePtr = St->getBasePtr(); 11652 SDValue NewST1 = DAG.getStore( 11653 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11654 BasePtr, St->getPointerInfo(), St->getAlignment(), 11655 St->getMemOperand()->getFlags()); 11656 11657 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11658 DAG.getConstant(4, DL, MVT::i32)); 11659 return DAG.getStore(NewST1.getValue(0), DL, 11660 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11661 OffsetPtr, St->getPointerInfo(), 11662 std::min(4U, St->getAlignment() / 2), 11663 St->getMemOperand()->getFlags()); 11664 } 11665 11666 if (StVal.getValueType() == MVT::i64 && 11667 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11668 11669 // Bitcast an i64 store extracted from a vector to f64. 11670 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11671 SelectionDAG &DAG = DCI.DAG; 11672 SDLoc dl(StVal); 11673 SDValue IntVec = StVal.getOperand(0); 11674 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11675 IntVec.getValueType().getVectorNumElements()); 11676 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11677 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11678 Vec, StVal.getOperand(1)); 11679 dl = SDLoc(N); 11680 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11681 // Make the DAGCombiner fold the bitcasts. 11682 DCI.AddToWorklist(Vec.getNode()); 11683 DCI.AddToWorklist(ExtElt.getNode()); 11684 DCI.AddToWorklist(V.getNode()); 11685 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11686 St->getPointerInfo(), St->getAlignment(), 11687 St->getMemOperand()->getFlags(), St->getAAInfo()); 11688 } 11689 11690 // If this is a legal vector store, try to combine it into a VST1_UPD. 11691 if (ISD::isNormalStore(N) && VT.isVector() && 11692 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11693 return CombineBaseUpdate(N, DCI); 11694 11695 return SDValue(); 11696 } 11697 11698 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11699 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11700 /// when the VMUL has a constant operand that is a power of 2. 11701 /// 11702 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11703 /// vmul.f32 d16, d17, d16 11704 /// vcvt.s32.f32 d16, d16 11705 /// becomes: 11706 /// vcvt.s32.f32 d16, d16, #3 11707 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11708 const ARMSubtarget *Subtarget) { 11709 if (!Subtarget->hasNEON()) 11710 return SDValue(); 11711 11712 SDValue Op = N->getOperand(0); 11713 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11714 Op.getOpcode() != ISD::FMUL) 11715 return SDValue(); 11716 11717 SDValue ConstVec = Op->getOperand(1); 11718 if (!isa<BuildVectorSDNode>(ConstVec)) 11719 return SDValue(); 11720 11721 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11722 uint32_t FloatBits = FloatTy.getSizeInBits(); 11723 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11724 uint32_t IntBits = IntTy.getSizeInBits(); 11725 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11726 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11727 // These instructions only exist converting from f32 to i32. We can handle 11728 // smaller integers by generating an extra truncate, but larger ones would 11729 // be lossy. We also can't handle more then 4 lanes, since these intructions 11730 // only support v2i32/v4i32 types. 11731 return SDValue(); 11732 } 11733 11734 BitVector UndefElements; 11735 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11736 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11737 if (C == -1 || C == 0 || C > 32) 11738 return SDValue(); 11739 11740 SDLoc dl(N); 11741 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11742 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11743 Intrinsic::arm_neon_vcvtfp2fxu; 11744 SDValue FixConv = DAG.getNode( 11745 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11746 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 11747 DAG.getConstant(C, dl, MVT::i32)); 11748 11749 if (IntBits < FloatBits) 11750 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 11751 11752 return FixConv; 11753 } 11754 11755 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 11756 /// can replace combinations of VCVT (integer to floating-point) and VDIV 11757 /// when the VDIV has a constant operand that is a power of 2. 11758 /// 11759 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11760 /// vcvt.f32.s32 d16, d16 11761 /// vdiv.f32 d16, d17, d16 11762 /// becomes: 11763 /// vcvt.f32.s32 d16, d16, #3 11764 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 11765 const ARMSubtarget *Subtarget) { 11766 if (!Subtarget->hasNEON()) 11767 return SDValue(); 11768 11769 SDValue Op = N->getOperand(0); 11770 unsigned OpOpcode = Op.getNode()->getOpcode(); 11771 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 11772 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 11773 return SDValue(); 11774 11775 SDValue ConstVec = N->getOperand(1); 11776 if (!isa<BuildVectorSDNode>(ConstVec)) 11777 return SDValue(); 11778 11779 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 11780 uint32_t FloatBits = FloatTy.getSizeInBits(); 11781 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 11782 uint32_t IntBits = IntTy.getSizeInBits(); 11783 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11784 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11785 // These instructions only exist converting from i32 to f32. We can handle 11786 // smaller integers by generating an extra extend, but larger ones would 11787 // be lossy. We also can't handle more then 4 lanes, since these intructions 11788 // only support v2i32/v4i32 types. 11789 return SDValue(); 11790 } 11791 11792 BitVector UndefElements; 11793 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11794 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11795 if (C == -1 || C == 0 || C > 32) 11796 return SDValue(); 11797 11798 SDLoc dl(N); 11799 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 11800 SDValue ConvInput = Op.getOperand(0); 11801 if (IntBits < FloatBits) 11802 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 11803 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11804 ConvInput); 11805 11806 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 11807 Intrinsic::arm_neon_vcvtfxu2fp; 11808 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 11809 Op.getValueType(), 11810 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 11811 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 11812 } 11813 11814 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 11815 /// operand of a vector shift operation, where all the elements of the 11816 /// build_vector must have the same constant integer value. 11817 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 11818 // Ignore bit_converts. 11819 while (Op.getOpcode() == ISD::BITCAST) 11820 Op = Op.getOperand(0); 11821 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 11822 APInt SplatBits, SplatUndef; 11823 unsigned SplatBitSize; 11824 bool HasAnyUndefs; 11825 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 11826 HasAnyUndefs, ElementBits) || 11827 SplatBitSize > ElementBits) 11828 return false; 11829 Cnt = SplatBits.getSExtValue(); 11830 return true; 11831 } 11832 11833 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 11834 /// operand of a vector shift left operation. That value must be in the range: 11835 /// 0 <= Value < ElementBits for a left shift; or 11836 /// 0 <= Value <= ElementBits for a long left shift. 11837 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 11838 assert(VT.isVector() && "vector shift count is not a vector type"); 11839 int64_t ElementBits = VT.getScalarSizeInBits(); 11840 if (! getVShiftImm(Op, ElementBits, Cnt)) 11841 return false; 11842 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 11843 } 11844 11845 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 11846 /// operand of a vector shift right operation. For a shift opcode, the value 11847 /// is positive, but for an intrinsic the value count must be negative. The 11848 /// absolute value must be in the range: 11849 /// 1 <= |Value| <= ElementBits for a right shift; or 11850 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 11851 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 11852 int64_t &Cnt) { 11853 assert(VT.isVector() && "vector shift count is not a vector type"); 11854 int64_t ElementBits = VT.getScalarSizeInBits(); 11855 if (! getVShiftImm(Op, ElementBits, Cnt)) 11856 return false; 11857 if (!isIntrinsic) 11858 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 11859 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 11860 Cnt = -Cnt; 11861 return true; 11862 } 11863 return false; 11864 } 11865 11866 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 11867 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 11868 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 11869 switch (IntNo) { 11870 default: 11871 // Don't do anything for most intrinsics. 11872 break; 11873 11874 // Vector shifts: check for immediate versions and lower them. 11875 // Note: This is done during DAG combining instead of DAG legalizing because 11876 // the build_vectors for 64-bit vector element shift counts are generally 11877 // not legal, and it is hard to see their values after they get legalized to 11878 // loads from a constant pool. 11879 case Intrinsic::arm_neon_vshifts: 11880 case Intrinsic::arm_neon_vshiftu: 11881 case Intrinsic::arm_neon_vrshifts: 11882 case Intrinsic::arm_neon_vrshiftu: 11883 case Intrinsic::arm_neon_vrshiftn: 11884 case Intrinsic::arm_neon_vqshifts: 11885 case Intrinsic::arm_neon_vqshiftu: 11886 case Intrinsic::arm_neon_vqshiftsu: 11887 case Intrinsic::arm_neon_vqshiftns: 11888 case Intrinsic::arm_neon_vqshiftnu: 11889 case Intrinsic::arm_neon_vqshiftnsu: 11890 case Intrinsic::arm_neon_vqrshiftns: 11891 case Intrinsic::arm_neon_vqrshiftnu: 11892 case Intrinsic::arm_neon_vqrshiftnsu: { 11893 EVT VT = N->getOperand(1).getValueType(); 11894 int64_t Cnt; 11895 unsigned VShiftOpc = 0; 11896 11897 switch (IntNo) { 11898 case Intrinsic::arm_neon_vshifts: 11899 case Intrinsic::arm_neon_vshiftu: 11900 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 11901 VShiftOpc = ARMISD::VSHL; 11902 break; 11903 } 11904 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 11905 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 11906 ARMISD::VSHRs : ARMISD::VSHRu); 11907 break; 11908 } 11909 return SDValue(); 11910 11911 case Intrinsic::arm_neon_vrshifts: 11912 case Intrinsic::arm_neon_vrshiftu: 11913 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 11914 break; 11915 return SDValue(); 11916 11917 case Intrinsic::arm_neon_vqshifts: 11918 case Intrinsic::arm_neon_vqshiftu: 11919 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11920 break; 11921 return SDValue(); 11922 11923 case Intrinsic::arm_neon_vqshiftsu: 11924 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11925 break; 11926 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 11927 11928 case Intrinsic::arm_neon_vrshiftn: 11929 case Intrinsic::arm_neon_vqshiftns: 11930 case Intrinsic::arm_neon_vqshiftnu: 11931 case Intrinsic::arm_neon_vqshiftnsu: 11932 case Intrinsic::arm_neon_vqrshiftns: 11933 case Intrinsic::arm_neon_vqrshiftnu: 11934 case Intrinsic::arm_neon_vqrshiftnsu: 11935 // Narrowing shifts require an immediate right shift. 11936 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 11937 break; 11938 llvm_unreachable("invalid shift count for narrowing vector shift " 11939 "intrinsic"); 11940 11941 default: 11942 llvm_unreachable("unhandled vector shift"); 11943 } 11944 11945 switch (IntNo) { 11946 case Intrinsic::arm_neon_vshifts: 11947 case Intrinsic::arm_neon_vshiftu: 11948 // Opcode already set above. 11949 break; 11950 case Intrinsic::arm_neon_vrshifts: 11951 VShiftOpc = ARMISD::VRSHRs; break; 11952 case Intrinsic::arm_neon_vrshiftu: 11953 VShiftOpc = ARMISD::VRSHRu; break; 11954 case Intrinsic::arm_neon_vrshiftn: 11955 VShiftOpc = ARMISD::VRSHRN; break; 11956 case Intrinsic::arm_neon_vqshifts: 11957 VShiftOpc = ARMISD::VQSHLs; break; 11958 case Intrinsic::arm_neon_vqshiftu: 11959 VShiftOpc = ARMISD::VQSHLu; break; 11960 case Intrinsic::arm_neon_vqshiftsu: 11961 VShiftOpc = ARMISD::VQSHLsu; break; 11962 case Intrinsic::arm_neon_vqshiftns: 11963 VShiftOpc = ARMISD::VQSHRNs; break; 11964 case Intrinsic::arm_neon_vqshiftnu: 11965 VShiftOpc = ARMISD::VQSHRNu; break; 11966 case Intrinsic::arm_neon_vqshiftnsu: 11967 VShiftOpc = ARMISD::VQSHRNsu; break; 11968 case Intrinsic::arm_neon_vqrshiftns: 11969 VShiftOpc = ARMISD::VQRSHRNs; break; 11970 case Intrinsic::arm_neon_vqrshiftnu: 11971 VShiftOpc = ARMISD::VQRSHRNu; break; 11972 case Intrinsic::arm_neon_vqrshiftnsu: 11973 VShiftOpc = ARMISD::VQRSHRNsu; break; 11974 } 11975 11976 SDLoc dl(N); 11977 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11978 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 11979 } 11980 11981 case Intrinsic::arm_neon_vshiftins: { 11982 EVT VT = N->getOperand(1).getValueType(); 11983 int64_t Cnt; 11984 unsigned VShiftOpc = 0; 11985 11986 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 11987 VShiftOpc = ARMISD::VSLI; 11988 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 11989 VShiftOpc = ARMISD::VSRI; 11990 else { 11991 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 11992 } 11993 11994 SDLoc dl(N); 11995 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11996 N->getOperand(1), N->getOperand(2), 11997 DAG.getConstant(Cnt, dl, MVT::i32)); 11998 } 11999 12000 case Intrinsic::arm_neon_vqrshifts: 12001 case Intrinsic::arm_neon_vqrshiftu: 12002 // No immediate versions of these to check for. 12003 break; 12004 } 12005 12006 return SDValue(); 12007 } 12008 12009 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12010 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12011 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12012 /// vector element shift counts are generally not legal, and it is hard to see 12013 /// their values after they get legalized to loads from a constant pool. 12014 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 12015 const ARMSubtarget *ST) { 12016 EVT VT = N->getValueType(0); 12017 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12018 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12019 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12020 SDValue N1 = N->getOperand(1); 12021 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12022 SDValue N0 = N->getOperand(0); 12023 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12024 DAG.MaskedValueIsZero(N0.getOperand(0), 12025 APInt::getHighBitsSet(32, 16))) 12026 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12027 } 12028 } 12029 12030 // Nothing to be done for scalar shifts. 12031 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12032 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12033 return SDValue(); 12034 12035 assert(ST->hasNEON() && "unexpected vector shift"); 12036 int64_t Cnt; 12037 12038 switch (N->getOpcode()) { 12039 default: llvm_unreachable("unexpected shift opcode"); 12040 12041 case ISD::SHL: 12042 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12043 SDLoc dl(N); 12044 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 12045 DAG.getConstant(Cnt, dl, MVT::i32)); 12046 } 12047 break; 12048 12049 case ISD::SRA: 12050 case ISD::SRL: 12051 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12052 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 12053 ARMISD::VSHRs : ARMISD::VSHRu); 12054 SDLoc dl(N); 12055 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12056 DAG.getConstant(Cnt, dl, MVT::i32)); 12057 } 12058 } 12059 return SDValue(); 12060 } 12061 12062 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12063 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12064 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12065 const ARMSubtarget *ST) { 12066 SDValue N0 = N->getOperand(0); 12067 12068 // Check for sign- and zero-extensions of vector extract operations of 8- 12069 // and 16-bit vector elements. NEON supports these directly. They are 12070 // handled during DAG combining because type legalization will promote them 12071 // to 32-bit types and it is messy to recognize the operations after that. 12072 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12073 SDValue Vec = N0.getOperand(0); 12074 SDValue Lane = N0.getOperand(1); 12075 EVT VT = N->getValueType(0); 12076 EVT EltVT = N0.getValueType(); 12077 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12078 12079 if (VT == MVT::i32 && 12080 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12081 TLI.isTypeLegal(Vec.getValueType()) && 12082 isa<ConstantSDNode>(Lane)) { 12083 12084 unsigned Opc = 0; 12085 switch (N->getOpcode()) { 12086 default: llvm_unreachable("unexpected opcode"); 12087 case ISD::SIGN_EXTEND: 12088 Opc = ARMISD::VGETLANEs; 12089 break; 12090 case ISD::ZERO_EXTEND: 12091 case ISD::ANY_EXTEND: 12092 Opc = ARMISD::VGETLANEu; 12093 break; 12094 } 12095 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12096 } 12097 } 12098 12099 return SDValue(); 12100 } 12101 12102 static const APInt *isPowerOf2Constant(SDValue V) { 12103 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12104 if (!C) 12105 return nullptr; 12106 const APInt *CV = &C->getAPIntValue(); 12107 return CV->isPowerOf2() ? CV : nullptr; 12108 } 12109 12110 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12111 // If we have a CMOV, OR and AND combination such as: 12112 // if (x & CN) 12113 // y |= CM; 12114 // 12115 // And: 12116 // * CN is a single bit; 12117 // * All bits covered by CM are known zero in y 12118 // 12119 // Then we can convert this into a sequence of BFI instructions. This will 12120 // always be a win if CM is a single bit, will always be no worse than the 12121 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12122 // three bits (due to the extra IT instruction). 12123 12124 SDValue Op0 = CMOV->getOperand(0); 12125 SDValue Op1 = CMOV->getOperand(1); 12126 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12127 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12128 SDValue CmpZ = CMOV->getOperand(4); 12129 12130 // The compare must be against zero. 12131 if (!isNullConstant(CmpZ->getOperand(1))) 12132 return SDValue(); 12133 12134 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12135 SDValue And = CmpZ->getOperand(0); 12136 if (And->getOpcode() != ISD::AND) 12137 return SDValue(); 12138 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12139 if (!AndC) 12140 return SDValue(); 12141 SDValue X = And->getOperand(0); 12142 12143 if (CC == ARMCC::EQ) { 12144 // We're performing an "equal to zero" compare. Swap the operands so we 12145 // canonicalize on a "not equal to zero" compare. 12146 std::swap(Op0, Op1); 12147 } else { 12148 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12149 } 12150 12151 if (Op1->getOpcode() != ISD::OR) 12152 return SDValue(); 12153 12154 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12155 if (!OrC) 12156 return SDValue(); 12157 SDValue Y = Op1->getOperand(0); 12158 12159 if (Op0 != Y) 12160 return SDValue(); 12161 12162 // Now, is it profitable to continue? 12163 APInt OrCI = OrC->getAPIntValue(); 12164 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12165 if (OrCI.countPopulation() > Heuristic) 12166 return SDValue(); 12167 12168 // Lastly, can we determine that the bits defined by OrCI 12169 // are zero in Y? 12170 KnownBits Known; 12171 DAG.computeKnownBits(Y, Known); 12172 if ((OrCI & Known.Zero) != OrCI) 12173 return SDValue(); 12174 12175 // OK, we can do the combine. 12176 SDValue V = Y; 12177 SDLoc dl(X); 12178 EVT VT = X.getValueType(); 12179 unsigned BitInX = AndC->logBase2(); 12180 12181 if (BitInX != 0) { 12182 // We must shift X first. 12183 X = DAG.getNode(ISD::SRL, dl, VT, X, 12184 DAG.getConstant(BitInX, dl, VT)); 12185 } 12186 12187 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12188 BitInY < NumActiveBits; ++BitInY) { 12189 if (OrCI[BitInY] == 0) 12190 continue; 12191 APInt Mask(VT.getSizeInBits(), 0); 12192 Mask.setBit(BitInY); 12193 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12194 // Confusingly, the operand is an *inverted* mask. 12195 DAG.getConstant(~Mask, dl, VT)); 12196 } 12197 12198 return V; 12199 } 12200 12201 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12202 SDValue 12203 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12204 SDValue Cmp = N->getOperand(4); 12205 if (Cmp.getOpcode() != ARMISD::CMPZ) 12206 // Only looking at NE cases. 12207 return SDValue(); 12208 12209 EVT VT = N->getValueType(0); 12210 SDLoc dl(N); 12211 SDValue LHS = Cmp.getOperand(0); 12212 SDValue RHS = Cmp.getOperand(1); 12213 SDValue Chain = N->getOperand(0); 12214 SDValue BB = N->getOperand(1); 12215 SDValue ARMcc = N->getOperand(2); 12216 ARMCC::CondCodes CC = 12217 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12218 12219 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12220 // -> (brcond Chain BB CC CPSR Cmp) 12221 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12222 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12223 LHS->getOperand(0)->hasOneUse()) { 12224 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12225 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12226 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12227 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12228 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12229 (LHS01C && LHS01C->getZExtValue() == 1) && 12230 (LHS1C && LHS1C->getZExtValue() == 1) && 12231 (RHSC && RHSC->getZExtValue() == 0)) { 12232 return DAG.getNode( 12233 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12234 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12235 } 12236 } 12237 12238 return SDValue(); 12239 } 12240 12241 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12242 SDValue 12243 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12244 SDValue Cmp = N->getOperand(4); 12245 if (Cmp.getOpcode() != ARMISD::CMPZ) 12246 // Only looking at EQ and NE cases. 12247 return SDValue(); 12248 12249 EVT VT = N->getValueType(0); 12250 SDLoc dl(N); 12251 SDValue LHS = Cmp.getOperand(0); 12252 SDValue RHS = Cmp.getOperand(1); 12253 SDValue FalseVal = N->getOperand(0); 12254 SDValue TrueVal = N->getOperand(1); 12255 SDValue ARMcc = N->getOperand(2); 12256 ARMCC::CondCodes CC = 12257 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12258 12259 // BFI is only available on V6T2+. 12260 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12261 SDValue R = PerformCMOVToBFICombine(N, DAG); 12262 if (R) 12263 return R; 12264 } 12265 12266 // Simplify 12267 // mov r1, r0 12268 // cmp r1, x 12269 // mov r0, y 12270 // moveq r0, x 12271 // to 12272 // cmp r0, x 12273 // movne r0, y 12274 // 12275 // mov r1, r0 12276 // cmp r1, x 12277 // mov r0, x 12278 // movne r0, y 12279 // to 12280 // cmp r0, x 12281 // movne r0, y 12282 /// FIXME: Turn this into a target neutral optimization? 12283 SDValue Res; 12284 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12285 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12286 N->getOperand(3), Cmp); 12287 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12288 SDValue ARMcc; 12289 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12290 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12291 N->getOperand(3), NewCmp); 12292 } 12293 12294 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12295 // -> (cmov F T CC CPSR Cmp) 12296 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12297 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12298 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12299 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12300 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12301 (LHS1C && LHS1C->getZExtValue() == 1) && 12302 (RHSC && RHSC->getZExtValue() == 0)) { 12303 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12304 LHS->getOperand(2), LHS->getOperand(3), 12305 LHS->getOperand(4)); 12306 } 12307 } 12308 12309 if (Res.getNode()) { 12310 KnownBits Known; 12311 DAG.computeKnownBits(SDValue(N,0), Known); 12312 // Capture demanded bits information that would be otherwise lost. 12313 if (Known.Zero == 0xfffffffe) 12314 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12315 DAG.getValueType(MVT::i1)); 12316 else if (Known.Zero == 0xffffff00) 12317 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12318 DAG.getValueType(MVT::i8)); 12319 else if (Known.Zero == 0xffff0000) 12320 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12321 DAG.getValueType(MVT::i16)); 12322 } 12323 12324 return Res; 12325 } 12326 12327 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12328 DAGCombinerInfo &DCI) const { 12329 switch (N->getOpcode()) { 12330 default: break; 12331 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12332 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12333 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12334 case ISD::SUB: return PerformSUBCombine(N, DCI); 12335 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12336 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12337 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12338 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12339 case ARMISD::ADDC: 12340 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12341 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 12342 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12343 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12344 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12345 case ISD::STORE: return PerformSTORECombine(N, DCI); 12346 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12347 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12348 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12349 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12350 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12351 case ISD::FP_TO_SINT: 12352 case ISD::FP_TO_UINT: 12353 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12354 case ISD::FDIV: 12355 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12356 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12357 case ISD::SHL: 12358 case ISD::SRA: 12359 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 12360 case ISD::SIGN_EXTEND: 12361 case ISD::ZERO_EXTEND: 12362 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12363 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12364 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12365 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12366 case ARMISD::VLD1DUP: 12367 case ARMISD::VLD2DUP: 12368 case ARMISD::VLD3DUP: 12369 case ARMISD::VLD4DUP: 12370 return PerformVLDCombine(N, DCI); 12371 case ARMISD::BUILD_VECTOR: 12372 return PerformARMBUILD_VECTORCombine(N, DCI); 12373 case ARMISD::SMULWB: { 12374 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12375 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12376 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12377 return SDValue(); 12378 break; 12379 } 12380 case ARMISD::SMULWT: { 12381 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12382 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12383 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12384 return SDValue(); 12385 break; 12386 } 12387 case ARMISD::SMLALBB: { 12388 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12389 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12390 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12391 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12392 return SDValue(); 12393 break; 12394 } 12395 case ARMISD::SMLALBT: { 12396 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12397 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12398 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12399 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12400 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12401 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12402 return SDValue(); 12403 break; 12404 } 12405 case ARMISD::SMLALTB: { 12406 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12407 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12408 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12409 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12410 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12411 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12412 return SDValue(); 12413 break; 12414 } 12415 case ARMISD::SMLALTT: { 12416 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12417 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12418 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12419 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12420 return SDValue(); 12421 break; 12422 } 12423 case ISD::INTRINSIC_VOID: 12424 case ISD::INTRINSIC_W_CHAIN: 12425 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12426 case Intrinsic::arm_neon_vld1: 12427 case Intrinsic::arm_neon_vld2: 12428 case Intrinsic::arm_neon_vld3: 12429 case Intrinsic::arm_neon_vld4: 12430 case Intrinsic::arm_neon_vld2lane: 12431 case Intrinsic::arm_neon_vld3lane: 12432 case Intrinsic::arm_neon_vld4lane: 12433 case Intrinsic::arm_neon_vst1: 12434 case Intrinsic::arm_neon_vst2: 12435 case Intrinsic::arm_neon_vst3: 12436 case Intrinsic::arm_neon_vst4: 12437 case Intrinsic::arm_neon_vst2lane: 12438 case Intrinsic::arm_neon_vst3lane: 12439 case Intrinsic::arm_neon_vst4lane: 12440 return PerformVLDCombine(N, DCI); 12441 default: break; 12442 } 12443 break; 12444 } 12445 return SDValue(); 12446 } 12447 12448 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12449 EVT VT) const { 12450 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12451 } 12452 12453 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12454 unsigned, 12455 unsigned, 12456 bool *Fast) const { 12457 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12458 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12459 12460 switch (VT.getSimpleVT().SimpleTy) { 12461 default: 12462 return false; 12463 case MVT::i8: 12464 case MVT::i16: 12465 case MVT::i32: { 12466 // Unaligned access can use (for example) LRDB, LRDH, LDR 12467 if (AllowsUnaligned) { 12468 if (Fast) 12469 *Fast = Subtarget->hasV7Ops(); 12470 return true; 12471 } 12472 return false; 12473 } 12474 case MVT::f64: 12475 case MVT::v2f64: { 12476 // For any little-endian targets with neon, we can support unaligned ld/st 12477 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12478 // A big-endian target may also explicitly support unaligned accesses 12479 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12480 if (Fast) 12481 *Fast = true; 12482 return true; 12483 } 12484 return false; 12485 } 12486 } 12487 } 12488 12489 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12490 unsigned AlignCheck) { 12491 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12492 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12493 } 12494 12495 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12496 unsigned DstAlign, unsigned SrcAlign, 12497 bool IsMemset, bool ZeroMemset, 12498 bool MemcpyStrSrc, 12499 MachineFunction &MF) const { 12500 const Function &F = MF.getFunction(); 12501 12502 // See if we can use NEON instructions for this... 12503 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12504 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 12505 bool Fast; 12506 if (Size >= 16 && 12507 (memOpAlign(SrcAlign, DstAlign, 16) || 12508 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12509 return MVT::v2f64; 12510 } else if (Size >= 8 && 12511 (memOpAlign(SrcAlign, DstAlign, 8) || 12512 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12513 Fast))) { 12514 return MVT::f64; 12515 } 12516 } 12517 12518 // Let the target-independent logic figure it out. 12519 return MVT::Other; 12520 } 12521 12522 // 64-bit integers are split into their high and low parts and held in two 12523 // different registers, so the trunc is free since the low register can just 12524 // be used. 12525 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 12526 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 12527 return false; 12528 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 12529 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 12530 return (SrcBits == 64 && DestBits == 32); 12531 } 12532 12533 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 12534 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 12535 !DstVT.isInteger()) 12536 return false; 12537 unsigned SrcBits = SrcVT.getSizeInBits(); 12538 unsigned DestBits = DstVT.getSizeInBits(); 12539 return (SrcBits == 64 && DestBits == 32); 12540 } 12541 12542 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12543 if (Val.getOpcode() != ISD::LOAD) 12544 return false; 12545 12546 EVT VT1 = Val.getValueType(); 12547 if (!VT1.isSimple() || !VT1.isInteger() || 12548 !VT2.isSimple() || !VT2.isInteger()) 12549 return false; 12550 12551 switch (VT1.getSimpleVT().SimpleTy) { 12552 default: break; 12553 case MVT::i1: 12554 case MVT::i8: 12555 case MVT::i16: 12556 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12557 return true; 12558 } 12559 12560 return false; 12561 } 12562 12563 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12564 EVT VT = ExtVal.getValueType(); 12565 12566 if (!isTypeLegal(VT)) 12567 return false; 12568 12569 // Don't create a loadext if we can fold the extension into a wide/long 12570 // instruction. 12571 // If there's more than one user instruction, the loadext is desirable no 12572 // matter what. There can be two uses by the same instruction. 12573 if (ExtVal->use_empty() || 12574 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12575 return true; 12576 12577 SDNode *U = *ExtVal->use_begin(); 12578 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12579 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12580 return false; 12581 12582 return true; 12583 } 12584 12585 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12586 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12587 return false; 12588 12589 if (!isTypeLegal(EVT::getEVT(Ty1))) 12590 return false; 12591 12592 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12593 12594 // Assuming the caller doesn't have a zeroext or signext return parameter, 12595 // truncation all the way down to i1 is valid. 12596 return true; 12597 } 12598 12599 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12600 const AddrMode &AM, Type *Ty, 12601 unsigned AS) const { 12602 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12603 if (Subtarget->hasFPAO()) 12604 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12605 return 0; 12606 } 12607 return -1; 12608 } 12609 12610 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 12611 if (V < 0) 12612 return false; 12613 12614 unsigned Scale = 1; 12615 switch (VT.getSimpleVT().SimpleTy) { 12616 default: return false; 12617 case MVT::i1: 12618 case MVT::i8: 12619 // Scale == 1; 12620 break; 12621 case MVT::i16: 12622 // Scale == 2; 12623 Scale = 2; 12624 break; 12625 case MVT::i32: 12626 // Scale == 4; 12627 Scale = 4; 12628 break; 12629 } 12630 12631 if ((V & (Scale - 1)) != 0) 12632 return false; 12633 V /= Scale; 12634 return V == (V & ((1LL << 5) - 1)); 12635 } 12636 12637 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 12638 const ARMSubtarget *Subtarget) { 12639 bool isNeg = false; 12640 if (V < 0) { 12641 isNeg = true; 12642 V = - V; 12643 } 12644 12645 switch (VT.getSimpleVT().SimpleTy) { 12646 default: return false; 12647 case MVT::i1: 12648 case MVT::i8: 12649 case MVT::i16: 12650 case MVT::i32: 12651 // + imm12 or - imm8 12652 if (isNeg) 12653 return V == (V & ((1LL << 8) - 1)); 12654 return V == (V & ((1LL << 12) - 1)); 12655 case MVT::f32: 12656 case MVT::f64: 12657 // Same as ARM mode. FIXME: NEON? 12658 if (!Subtarget->hasVFP2()) 12659 return false; 12660 if ((V & 3) != 0) 12661 return false; 12662 V >>= 2; 12663 return V == (V & ((1LL << 8) - 1)); 12664 } 12665 } 12666 12667 /// isLegalAddressImmediate - Return true if the integer value can be used 12668 /// as the offset of the target addressing mode for load / store of the 12669 /// given type. 12670 static bool isLegalAddressImmediate(int64_t V, EVT VT, 12671 const ARMSubtarget *Subtarget) { 12672 if (V == 0) 12673 return true; 12674 12675 if (!VT.isSimple()) 12676 return false; 12677 12678 if (Subtarget->isThumb1Only()) 12679 return isLegalT1AddressImmediate(V, VT); 12680 else if (Subtarget->isThumb2()) 12681 return isLegalT2AddressImmediate(V, VT, Subtarget); 12682 12683 // ARM mode. 12684 if (V < 0) 12685 V = - V; 12686 switch (VT.getSimpleVT().SimpleTy) { 12687 default: return false; 12688 case MVT::i1: 12689 case MVT::i8: 12690 case MVT::i32: 12691 // +- imm12 12692 return V == (V & ((1LL << 12) - 1)); 12693 case MVT::i16: 12694 // +- imm8 12695 return V == (V & ((1LL << 8) - 1)); 12696 case MVT::f32: 12697 case MVT::f64: 12698 if (!Subtarget->hasVFP2()) // FIXME: NEON? 12699 return false; 12700 if ((V & 3) != 0) 12701 return false; 12702 V >>= 2; 12703 return V == (V & ((1LL << 8) - 1)); 12704 } 12705 } 12706 12707 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 12708 EVT VT) const { 12709 int Scale = AM.Scale; 12710 if (Scale < 0) 12711 return false; 12712 12713 switch (VT.getSimpleVT().SimpleTy) { 12714 default: return false; 12715 case MVT::i1: 12716 case MVT::i8: 12717 case MVT::i16: 12718 case MVT::i32: 12719 if (Scale == 1) 12720 return true; 12721 // r + r << imm 12722 Scale = Scale & ~1; 12723 return Scale == 2 || Scale == 4 || Scale == 8; 12724 case MVT::i64: 12725 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 12726 // version in Thumb mode. 12727 // r + r 12728 if (Scale == 1) 12729 return true; 12730 // r * 2 (this can be lowered to r + r). 12731 if (!AM.HasBaseReg && Scale == 2) 12732 return true; 12733 return false; 12734 case MVT::isVoid: 12735 // Note, we allow "void" uses (basically, uses that aren't loads or 12736 // stores), because arm allows folding a scale into many arithmetic 12737 // operations. This should be made more precise and revisited later. 12738 12739 // Allow r << imm, but the imm has to be a multiple of two. 12740 if (Scale & 1) return false; 12741 return isPowerOf2_32(Scale); 12742 } 12743 } 12744 12745 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 12746 EVT VT) const { 12747 const int Scale = AM.Scale; 12748 12749 // Negative scales are not supported in Thumb1. 12750 if (Scale < 0) 12751 return false; 12752 12753 // Thumb1 addressing modes do not support register scaling excepting the 12754 // following cases: 12755 // 1. Scale == 1 means no scaling. 12756 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 12757 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 12758 } 12759 12760 /// isLegalAddressingMode - Return true if the addressing mode represented 12761 /// by AM is legal for this target, for a load/store of the specified type. 12762 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12763 const AddrMode &AM, Type *Ty, 12764 unsigned AS, Instruction *I) const { 12765 EVT VT = getValueType(DL, Ty, true); 12766 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 12767 return false; 12768 12769 // Can never fold addr of global into load/store. 12770 if (AM.BaseGV) 12771 return false; 12772 12773 switch (AM.Scale) { 12774 case 0: // no scale reg, must be "r+i" or "r", or "i". 12775 break; 12776 default: 12777 // ARM doesn't support any R+R*scale+imm addr modes. 12778 if (AM.BaseOffs) 12779 return false; 12780 12781 if (!VT.isSimple()) 12782 return false; 12783 12784 if (Subtarget->isThumb1Only()) 12785 return isLegalT1ScaledAddressingMode(AM, VT); 12786 12787 if (Subtarget->isThumb2()) 12788 return isLegalT2ScaledAddressingMode(AM, VT); 12789 12790 int Scale = AM.Scale; 12791 switch (VT.getSimpleVT().SimpleTy) { 12792 default: return false; 12793 case MVT::i1: 12794 case MVT::i8: 12795 case MVT::i32: 12796 if (Scale < 0) Scale = -Scale; 12797 if (Scale == 1) 12798 return true; 12799 // r + r << imm 12800 return isPowerOf2_32(Scale & ~1); 12801 case MVT::i16: 12802 case MVT::i64: 12803 // r +/- r 12804 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 12805 return true; 12806 // r * 2 (this can be lowered to r + r). 12807 if (!AM.HasBaseReg && Scale == 2) 12808 return true; 12809 return false; 12810 12811 case MVT::isVoid: 12812 // Note, we allow "void" uses (basically, uses that aren't loads or 12813 // stores), because arm allows folding a scale into many arithmetic 12814 // operations. This should be made more precise and revisited later. 12815 12816 // Allow r << imm, but the imm has to be a multiple of two. 12817 if (Scale & 1) return false; 12818 return isPowerOf2_32(Scale); 12819 } 12820 } 12821 return true; 12822 } 12823 12824 /// isLegalICmpImmediate - Return true if the specified immediate is legal 12825 /// icmp immediate, that is the target has icmp instructions which can compare 12826 /// a register against the immediate without having to materialize the 12827 /// immediate into a register. 12828 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12829 // Thumb2 and ARM modes can use cmn for negative immediates. 12830 if (!Subtarget->isThumb()) 12831 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 12832 if (Subtarget->isThumb2()) 12833 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 12834 // Thumb1 doesn't have cmn, and only 8-bit immediates. 12835 return Imm >= 0 && Imm <= 255; 12836 } 12837 12838 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 12839 /// *or sub* immediate, that is the target has add or sub instructions which can 12840 /// add a register with the immediate without having to materialize the 12841 /// immediate into a register. 12842 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 12843 // Same encoding for add/sub, just flip the sign. 12844 int64_t AbsImm = std::abs(Imm); 12845 if (!Subtarget->isThumb()) 12846 return ARM_AM::getSOImmVal(AbsImm) != -1; 12847 if (Subtarget->isThumb2()) 12848 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 12849 // Thumb1 only has 8-bit unsigned immediate. 12850 return AbsImm >= 0 && AbsImm <= 255; 12851 } 12852 12853 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 12854 bool isSEXTLoad, SDValue &Base, 12855 SDValue &Offset, bool &isInc, 12856 SelectionDAG &DAG) { 12857 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12858 return false; 12859 12860 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 12861 // AddressingMode 3 12862 Base = Ptr->getOperand(0); 12863 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12864 int RHSC = (int)RHS->getZExtValue(); 12865 if (RHSC < 0 && RHSC > -256) { 12866 assert(Ptr->getOpcode() == ISD::ADD); 12867 isInc = false; 12868 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12869 return true; 12870 } 12871 } 12872 isInc = (Ptr->getOpcode() == ISD::ADD); 12873 Offset = Ptr->getOperand(1); 12874 return true; 12875 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 12876 // AddressingMode 2 12877 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12878 int RHSC = (int)RHS->getZExtValue(); 12879 if (RHSC < 0 && RHSC > -0x1000) { 12880 assert(Ptr->getOpcode() == ISD::ADD); 12881 isInc = false; 12882 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12883 Base = Ptr->getOperand(0); 12884 return true; 12885 } 12886 } 12887 12888 if (Ptr->getOpcode() == ISD::ADD) { 12889 isInc = true; 12890 ARM_AM::ShiftOpc ShOpcVal= 12891 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 12892 if (ShOpcVal != ARM_AM::no_shift) { 12893 Base = Ptr->getOperand(1); 12894 Offset = Ptr->getOperand(0); 12895 } else { 12896 Base = Ptr->getOperand(0); 12897 Offset = Ptr->getOperand(1); 12898 } 12899 return true; 12900 } 12901 12902 isInc = (Ptr->getOpcode() == ISD::ADD); 12903 Base = Ptr->getOperand(0); 12904 Offset = Ptr->getOperand(1); 12905 return true; 12906 } 12907 12908 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 12909 return false; 12910 } 12911 12912 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 12913 bool isSEXTLoad, SDValue &Base, 12914 SDValue &Offset, bool &isInc, 12915 SelectionDAG &DAG) { 12916 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12917 return false; 12918 12919 Base = Ptr->getOperand(0); 12920 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12921 int RHSC = (int)RHS->getZExtValue(); 12922 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 12923 assert(Ptr->getOpcode() == ISD::ADD); 12924 isInc = false; 12925 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12926 return true; 12927 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 12928 isInc = Ptr->getOpcode() == ISD::ADD; 12929 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12930 return true; 12931 } 12932 } 12933 12934 return false; 12935 } 12936 12937 /// getPreIndexedAddressParts - returns true by value, base pointer and 12938 /// offset pointer and addressing mode by reference if the node's address 12939 /// can be legally represented as pre-indexed load / store address. 12940 bool 12941 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 12942 SDValue &Offset, 12943 ISD::MemIndexedMode &AM, 12944 SelectionDAG &DAG) const { 12945 if (Subtarget->isThumb1Only()) 12946 return false; 12947 12948 EVT VT; 12949 SDValue Ptr; 12950 bool isSEXTLoad = false; 12951 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12952 Ptr = LD->getBasePtr(); 12953 VT = LD->getMemoryVT(); 12954 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12955 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12956 Ptr = ST->getBasePtr(); 12957 VT = ST->getMemoryVT(); 12958 } else 12959 return false; 12960 12961 bool isInc; 12962 bool isLegal = false; 12963 if (Subtarget->isThumb2()) 12964 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12965 Offset, isInc, DAG); 12966 else 12967 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12968 Offset, isInc, DAG); 12969 if (!isLegal) 12970 return false; 12971 12972 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 12973 return true; 12974 } 12975 12976 /// getPostIndexedAddressParts - returns true by value, base pointer and 12977 /// offset pointer and addressing mode by reference if this node can be 12978 /// combined with a load / store to form a post-indexed load / store. 12979 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 12980 SDValue &Base, 12981 SDValue &Offset, 12982 ISD::MemIndexedMode &AM, 12983 SelectionDAG &DAG) const { 12984 EVT VT; 12985 SDValue Ptr; 12986 bool isSEXTLoad = false, isNonExt; 12987 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12988 VT = LD->getMemoryVT(); 12989 Ptr = LD->getBasePtr(); 12990 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12991 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 12992 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12993 VT = ST->getMemoryVT(); 12994 Ptr = ST->getBasePtr(); 12995 isNonExt = !ST->isTruncatingStore(); 12996 } else 12997 return false; 12998 12999 if (Subtarget->isThumb1Only()) { 13000 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 13001 // must be non-extending/truncating, i32, with an offset of 4. 13002 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 13003 if (Op->getOpcode() != ISD::ADD || !isNonExt) 13004 return false; 13005 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 13006 if (!RHS || RHS->getZExtValue() != 4) 13007 return false; 13008 13009 Offset = Op->getOperand(1); 13010 Base = Op->getOperand(0); 13011 AM = ISD::POST_INC; 13012 return true; 13013 } 13014 13015 bool isInc; 13016 bool isLegal = false; 13017 if (Subtarget->isThumb2()) 13018 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13019 isInc, DAG); 13020 else 13021 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13022 isInc, DAG); 13023 if (!isLegal) 13024 return false; 13025 13026 if (Ptr != Base) { 13027 // Swap base ptr and offset to catch more post-index load / store when 13028 // it's legal. In Thumb2 mode, offset must be an immediate. 13029 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 13030 !Subtarget->isThumb2()) 13031 std::swap(Base, Offset); 13032 13033 // Post-indexed load / store update the base pointer. 13034 if (Ptr != Base) 13035 return false; 13036 } 13037 13038 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 13039 return true; 13040 } 13041 13042 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13043 KnownBits &Known, 13044 const APInt &DemandedElts, 13045 const SelectionDAG &DAG, 13046 unsigned Depth) const { 13047 unsigned BitWidth = Known.getBitWidth(); 13048 Known.resetAll(); 13049 switch (Op.getOpcode()) { 13050 default: break; 13051 case ARMISD::ADDC: 13052 case ARMISD::ADDE: 13053 case ARMISD::SUBC: 13054 case ARMISD::SUBE: 13055 // Special cases when we convert a carry to a boolean. 13056 if (Op.getResNo() == 0) { 13057 SDValue LHS = Op.getOperand(0); 13058 SDValue RHS = Op.getOperand(1); 13059 // (ADDE 0, 0, C) will give us a single bit. 13060 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 13061 isNullConstant(RHS)) { 13062 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 13063 return; 13064 } 13065 } 13066 break; 13067 case ARMISD::CMOV: { 13068 // Bits are known zero/one if known on the LHS and RHS. 13069 DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1); 13070 if (Known.isUnknown()) 13071 return; 13072 13073 KnownBits KnownRHS; 13074 DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1); 13075 Known.Zero &= KnownRHS.Zero; 13076 Known.One &= KnownRHS.One; 13077 return; 13078 } 13079 case ISD::INTRINSIC_W_CHAIN: { 13080 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 13081 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13082 switch (IntID) { 13083 default: return; 13084 case Intrinsic::arm_ldaex: 13085 case Intrinsic::arm_ldrex: { 13086 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 13087 unsigned MemBits = VT.getScalarSizeInBits(); 13088 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 13089 return; 13090 } 13091 } 13092 } 13093 case ARMISD::BFI: { 13094 // Conservatively, we can recurse down the first operand 13095 // and just mask out all affected bits. 13096 DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1); 13097 13098 // The operand to BFI is already a mask suitable for removing the bits it 13099 // sets. 13100 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 13101 const APInt &Mask = CI->getAPIntValue(); 13102 Known.Zero &= Mask; 13103 Known.One &= Mask; 13104 return; 13105 } 13106 } 13107 } 13108 13109 //===----------------------------------------------------------------------===// 13110 // ARM Inline Assembly Support 13111 //===----------------------------------------------------------------------===// 13112 13113 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 13114 // Looking for "rev" which is V6+. 13115 if (!Subtarget->hasV6Ops()) 13116 return false; 13117 13118 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 13119 std::string AsmStr = IA->getAsmString(); 13120 SmallVector<StringRef, 4> AsmPieces; 13121 SplitString(AsmStr, AsmPieces, ";\n"); 13122 13123 switch (AsmPieces.size()) { 13124 default: return false; 13125 case 1: 13126 AsmStr = AsmPieces[0]; 13127 AsmPieces.clear(); 13128 SplitString(AsmStr, AsmPieces, " \t,"); 13129 13130 // rev $0, $1 13131 if (AsmPieces.size() == 3 && 13132 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 13133 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 13134 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 13135 if (Ty && Ty->getBitWidth() == 32) 13136 return IntrinsicLowering::LowerToByteSwap(CI); 13137 } 13138 break; 13139 } 13140 13141 return false; 13142 } 13143 13144 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 13145 // At this point, we have to lower this constraint to something else, so we 13146 // lower it to an "r" or "w". However, by doing this we will force the result 13147 // to be in register, while the X constraint is much more permissive. 13148 // 13149 // Although we are correct (we are free to emit anything, without 13150 // constraints), we might break use cases that would expect us to be more 13151 // efficient and emit something else. 13152 if (!Subtarget->hasVFP2()) 13153 return "r"; 13154 if (ConstraintVT.isFloatingPoint()) 13155 return "w"; 13156 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 13157 (ConstraintVT.getSizeInBits() == 64 || 13158 ConstraintVT.getSizeInBits() == 128)) 13159 return "w"; 13160 13161 return "r"; 13162 } 13163 13164 /// getConstraintType - Given a constraint letter, return the type of 13165 /// constraint it is for this target. 13166 ARMTargetLowering::ConstraintType 13167 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 13168 if (Constraint.size() == 1) { 13169 switch (Constraint[0]) { 13170 default: break; 13171 case 'l': return C_RegisterClass; 13172 case 'w': return C_RegisterClass; 13173 case 'h': return C_RegisterClass; 13174 case 'x': return C_RegisterClass; 13175 case 't': return C_RegisterClass; 13176 case 'j': return C_Other; // Constant for movw. 13177 // An address with a single base register. Due to the way we 13178 // currently handle addresses it is the same as an 'r' memory constraint. 13179 case 'Q': return C_Memory; 13180 } 13181 } else if (Constraint.size() == 2) { 13182 switch (Constraint[0]) { 13183 default: break; 13184 // All 'U+' constraints are addresses. 13185 case 'U': return C_Memory; 13186 } 13187 } 13188 return TargetLowering::getConstraintType(Constraint); 13189 } 13190 13191 /// Examine constraint type and operand type and determine a weight value. 13192 /// This object must already have been set up with the operand type 13193 /// and the current alternative constraint selected. 13194 TargetLowering::ConstraintWeight 13195 ARMTargetLowering::getSingleConstraintMatchWeight( 13196 AsmOperandInfo &info, const char *constraint) const { 13197 ConstraintWeight weight = CW_Invalid; 13198 Value *CallOperandVal = info.CallOperandVal; 13199 // If we don't have a value, we can't do a match, 13200 // but allow it at the lowest weight. 13201 if (!CallOperandVal) 13202 return CW_Default; 13203 Type *type = CallOperandVal->getType(); 13204 // Look at the constraint type. 13205 switch (*constraint) { 13206 default: 13207 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13208 break; 13209 case 'l': 13210 if (type->isIntegerTy()) { 13211 if (Subtarget->isThumb()) 13212 weight = CW_SpecificReg; 13213 else 13214 weight = CW_Register; 13215 } 13216 break; 13217 case 'w': 13218 if (type->isFloatingPointTy()) 13219 weight = CW_Register; 13220 break; 13221 } 13222 return weight; 13223 } 13224 13225 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13226 13227 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13228 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13229 if (Constraint.size() == 1) { 13230 // GCC ARM Constraint Letters 13231 switch (Constraint[0]) { 13232 case 'l': // Low regs or general regs. 13233 if (Subtarget->isThumb()) 13234 return RCPair(0U, &ARM::tGPRRegClass); 13235 return RCPair(0U, &ARM::GPRRegClass); 13236 case 'h': // High regs or no regs. 13237 if (Subtarget->isThumb()) 13238 return RCPair(0U, &ARM::hGPRRegClass); 13239 break; 13240 case 'r': 13241 if (Subtarget->isThumb1Only()) 13242 return RCPair(0U, &ARM::tGPRRegClass); 13243 return RCPair(0U, &ARM::GPRRegClass); 13244 case 'w': 13245 if (VT == MVT::Other) 13246 break; 13247 if (VT == MVT::f32) 13248 return RCPair(0U, &ARM::SPRRegClass); 13249 if (VT.getSizeInBits() == 64) 13250 return RCPair(0U, &ARM::DPRRegClass); 13251 if (VT.getSizeInBits() == 128) 13252 return RCPair(0U, &ARM::QPRRegClass); 13253 break; 13254 case 'x': 13255 if (VT == MVT::Other) 13256 break; 13257 if (VT == MVT::f32) 13258 return RCPair(0U, &ARM::SPR_8RegClass); 13259 if (VT.getSizeInBits() == 64) 13260 return RCPair(0U, &ARM::DPR_8RegClass); 13261 if (VT.getSizeInBits() == 128) 13262 return RCPair(0U, &ARM::QPR_8RegClass); 13263 break; 13264 case 't': 13265 if (VT == MVT::f32 || VT == MVT::i32) 13266 return RCPair(0U, &ARM::SPRRegClass); 13267 break; 13268 } 13269 } 13270 if (StringRef("{cc}").equals_lower(Constraint)) 13271 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 13272 13273 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13274 } 13275 13276 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13277 /// vector. If it is invalid, don't add anything to Ops. 13278 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13279 std::string &Constraint, 13280 std::vector<SDValue>&Ops, 13281 SelectionDAG &DAG) const { 13282 SDValue Result; 13283 13284 // Currently only support length 1 constraints. 13285 if (Constraint.length() != 1) return; 13286 13287 char ConstraintLetter = Constraint[0]; 13288 switch (ConstraintLetter) { 13289 default: break; 13290 case 'j': 13291 case 'I': case 'J': case 'K': case 'L': 13292 case 'M': case 'N': case 'O': 13293 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 13294 if (!C) 13295 return; 13296 13297 int64_t CVal64 = C->getSExtValue(); 13298 int CVal = (int) CVal64; 13299 // None of these constraints allow values larger than 32 bits. Check 13300 // that the value fits in an int. 13301 if (CVal != CVal64) 13302 return; 13303 13304 switch (ConstraintLetter) { 13305 case 'j': 13306 // Constant suitable for movw, must be between 0 and 13307 // 65535. 13308 if (Subtarget->hasV6T2Ops()) 13309 if (CVal >= 0 && CVal <= 65535) 13310 break; 13311 return; 13312 case 'I': 13313 if (Subtarget->isThumb1Only()) { 13314 // This must be a constant between 0 and 255, for ADD 13315 // immediates. 13316 if (CVal >= 0 && CVal <= 255) 13317 break; 13318 } else if (Subtarget->isThumb2()) { 13319 // A constant that can be used as an immediate value in a 13320 // data-processing instruction. 13321 if (ARM_AM::getT2SOImmVal(CVal) != -1) 13322 break; 13323 } else { 13324 // A constant that can be used as an immediate value in a 13325 // data-processing instruction. 13326 if (ARM_AM::getSOImmVal(CVal) != -1) 13327 break; 13328 } 13329 return; 13330 13331 case 'J': 13332 if (Subtarget->isThumb1Only()) { 13333 // This must be a constant between -255 and -1, for negated ADD 13334 // immediates. This can be used in GCC with an "n" modifier that 13335 // prints the negated value, for use with SUB instructions. It is 13336 // not useful otherwise but is implemented for compatibility. 13337 if (CVal >= -255 && CVal <= -1) 13338 break; 13339 } else { 13340 // This must be a constant between -4095 and 4095. It is not clear 13341 // what this constraint is intended for. Implemented for 13342 // compatibility with GCC. 13343 if (CVal >= -4095 && CVal <= 4095) 13344 break; 13345 } 13346 return; 13347 13348 case 'K': 13349 if (Subtarget->isThumb1Only()) { 13350 // A 32-bit value where only one byte has a nonzero value. Exclude 13351 // zero to match GCC. This constraint is used by GCC internally for 13352 // constants that can be loaded with a move/shift combination. 13353 // It is not useful otherwise but is implemented for compatibility. 13354 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 13355 break; 13356 } else if (Subtarget->isThumb2()) { 13357 // A constant whose bitwise inverse can be used as an immediate 13358 // value in a data-processing instruction. This can be used in GCC 13359 // with a "B" modifier that prints the inverted value, for use with 13360 // BIC and MVN instructions. It is not useful otherwise but is 13361 // implemented for compatibility. 13362 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 13363 break; 13364 } else { 13365 // A constant whose bitwise inverse can be used as an immediate 13366 // value in a data-processing instruction. This can be used in GCC 13367 // with a "B" modifier that prints the inverted value, for use with 13368 // BIC and MVN instructions. It is not useful otherwise but is 13369 // implemented for compatibility. 13370 if (ARM_AM::getSOImmVal(~CVal) != -1) 13371 break; 13372 } 13373 return; 13374 13375 case 'L': 13376 if (Subtarget->isThumb1Only()) { 13377 // This must be a constant between -7 and 7, 13378 // for 3-operand ADD/SUB immediate instructions. 13379 if (CVal >= -7 && CVal < 7) 13380 break; 13381 } else if (Subtarget->isThumb2()) { 13382 // A constant whose negation can be used as an immediate value in a 13383 // data-processing instruction. This can be used in GCC with an "n" 13384 // modifier that prints the negated value, for use with SUB 13385 // instructions. It is not useful otherwise but is implemented for 13386 // compatibility. 13387 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 13388 break; 13389 } else { 13390 // A constant whose negation can be used as an immediate value in a 13391 // data-processing instruction. This can be used in GCC with an "n" 13392 // modifier that prints the negated value, for use with SUB 13393 // instructions. It is not useful otherwise but is implemented for 13394 // compatibility. 13395 if (ARM_AM::getSOImmVal(-CVal) != -1) 13396 break; 13397 } 13398 return; 13399 13400 case 'M': 13401 if (Subtarget->isThumb1Only()) { 13402 // This must be a multiple of 4 between 0 and 1020, for 13403 // ADD sp + immediate. 13404 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 13405 break; 13406 } else { 13407 // A power of two or a constant between 0 and 32. This is used in 13408 // GCC for the shift amount on shifted register operands, but it is 13409 // useful in general for any shift amounts. 13410 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 13411 break; 13412 } 13413 return; 13414 13415 case 'N': 13416 if (Subtarget->isThumb()) { // FIXME thumb2 13417 // This must be a constant between 0 and 31, for shift amounts. 13418 if (CVal >= 0 && CVal <= 31) 13419 break; 13420 } 13421 return; 13422 13423 case 'O': 13424 if (Subtarget->isThumb()) { // FIXME thumb2 13425 // This must be a multiple of 4 between -508 and 508, for 13426 // ADD/SUB sp = sp + immediate. 13427 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 13428 break; 13429 } 13430 return; 13431 } 13432 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 13433 break; 13434 } 13435 13436 if (Result.getNode()) { 13437 Ops.push_back(Result); 13438 return; 13439 } 13440 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13441 } 13442 13443 static RTLIB::Libcall getDivRemLibcall( 13444 const SDNode *N, MVT::SimpleValueType SVT) { 13445 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13446 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13447 "Unhandled Opcode in getDivRemLibcall"); 13448 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13449 N->getOpcode() == ISD::SREM; 13450 RTLIB::Libcall LC; 13451 switch (SVT) { 13452 default: llvm_unreachable("Unexpected request for libcall!"); 13453 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 13454 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 13455 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 13456 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 13457 } 13458 return LC; 13459 } 13460 13461 static TargetLowering::ArgListTy getDivRemArgList( 13462 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13463 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13464 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13465 "Unhandled Opcode in getDivRemArgList"); 13466 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13467 N->getOpcode() == ISD::SREM; 13468 TargetLowering::ArgListTy Args; 13469 TargetLowering::ArgListEntry Entry; 13470 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13471 EVT ArgVT = N->getOperand(i).getValueType(); 13472 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13473 Entry.Node = N->getOperand(i); 13474 Entry.Ty = ArgTy; 13475 Entry.IsSExt = isSigned; 13476 Entry.IsZExt = !isSigned; 13477 Args.push_back(Entry); 13478 } 13479 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13480 std::swap(Args[0], Args[1]); 13481 return Args; 13482 } 13483 13484 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13485 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13486 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13487 Subtarget->isTargetWindows()) && 13488 "Register-based DivRem lowering only"); 13489 unsigned Opcode = Op->getOpcode(); 13490 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13491 "Invalid opcode for Div/Rem lowering"); 13492 bool isSigned = (Opcode == ISD::SDIVREM); 13493 EVT VT = Op->getValueType(0); 13494 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13495 SDLoc dl(Op); 13496 13497 // If the target has hardware divide, use divide + multiply + subtract: 13498 // div = a / b 13499 // rem = a - b * div 13500 // return {div, rem} 13501 // This should be lowered into UDIV/SDIV + MLS later on. 13502 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 13503 : Subtarget->hasDivideInARMMode(); 13504 if (hasDivide && Op->getValueType(0).isSimple() && 13505 Op->getSimpleValueType(0) == MVT::i32) { 13506 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13507 const SDValue Dividend = Op->getOperand(0); 13508 const SDValue Divisor = Op->getOperand(1); 13509 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13510 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13511 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13512 13513 SDValue Values[2] = {Div, Rem}; 13514 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13515 } 13516 13517 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13518 VT.getSimpleVT().SimpleTy); 13519 SDValue InChain = DAG.getEntryNode(); 13520 13521 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13522 DAG.getContext(), 13523 Subtarget); 13524 13525 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13526 getPointerTy(DAG.getDataLayout())); 13527 13528 Type *RetTy = StructType::get(Ty, Ty); 13529 13530 if (Subtarget->isTargetWindows()) 13531 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13532 13533 TargetLowering::CallLoweringInfo CLI(DAG); 13534 CLI.setDebugLoc(dl).setChain(InChain) 13535 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13536 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13537 13538 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13539 return CallInfo.first; 13540 } 13541 13542 // Lowers REM using divmod helpers 13543 // see RTABI section 4.2/4.3 13544 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13545 // Build return types (div and rem) 13546 std::vector<Type*> RetTyParams; 13547 Type *RetTyElement; 13548 13549 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13550 default: llvm_unreachable("Unexpected request for libcall!"); 13551 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13552 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13553 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13554 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13555 } 13556 13557 RetTyParams.push_back(RetTyElement); 13558 RetTyParams.push_back(RetTyElement); 13559 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13560 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13561 13562 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13563 SimpleTy); 13564 SDValue InChain = DAG.getEntryNode(); 13565 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13566 Subtarget); 13567 bool isSigned = N->getOpcode() == ISD::SREM; 13568 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13569 getPointerTy(DAG.getDataLayout())); 13570 13571 if (Subtarget->isTargetWindows()) 13572 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13573 13574 // Lower call 13575 CallLoweringInfo CLI(DAG); 13576 CLI.setChain(InChain) 13577 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13578 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13579 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13580 13581 // Return second (rem) result operand (first contains div) 13582 SDNode *ResNode = CallResult.first.getNode(); 13583 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13584 return ResNode->getOperand(1); 13585 } 13586 13587 SDValue 13588 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13589 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13590 SDLoc DL(Op); 13591 13592 // Get the inputs. 13593 SDValue Chain = Op.getOperand(0); 13594 SDValue Size = Op.getOperand(1); 13595 13596 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 13597 DAG.getConstant(2, DL, MVT::i32)); 13598 13599 SDValue Flag; 13600 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 13601 Flag = Chain.getValue(1); 13602 13603 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 13604 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 13605 13606 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13607 Chain = NewSP.getValue(1); 13608 13609 SDValue Ops[2] = { NewSP, Chain }; 13610 return DAG.getMergeValues(Ops, DL); 13611 } 13612 13613 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 13614 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 13615 "Unexpected type for custom-lowering FP_EXTEND"); 13616 13617 RTLIB::Libcall LC; 13618 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 13619 13620 SDValue SrcVal = Op.getOperand(0); 13621 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13622 SDLoc(Op)).first; 13623 } 13624 13625 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 13626 assert(Op.getOperand(0).getValueType() == MVT::f64 && 13627 Subtarget->isFPOnlySP() && 13628 "Unexpected type for custom-lowering FP_ROUND"); 13629 13630 RTLIB::Libcall LC; 13631 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 13632 13633 SDValue SrcVal = Op.getOperand(0); 13634 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13635 SDLoc(Op)).first; 13636 } 13637 13638 bool 13639 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13640 // The ARM target isn't yet aware of offsets. 13641 return false; 13642 } 13643 13644 bool ARM::isBitFieldInvertedMask(unsigned v) { 13645 if (v == 0xffffffff) 13646 return false; 13647 13648 // there can be 1's on either or both "outsides", all the "inside" 13649 // bits must be 0's 13650 return isShiftedMask_32(~v); 13651 } 13652 13653 /// isFPImmLegal - Returns true if the target can instruction select the 13654 /// specified FP immediate natively. If false, the legalizer will 13655 /// materialize the FP immediate as a load from a constant pool. 13656 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13657 if (!Subtarget->hasVFP3()) 13658 return false; 13659 if (VT == MVT::f32) 13660 return ARM_AM::getFP32Imm(Imm) != -1; 13661 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 13662 return ARM_AM::getFP64Imm(Imm) != -1; 13663 return false; 13664 } 13665 13666 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 13667 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 13668 /// specified in the intrinsic calls. 13669 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13670 const CallInst &I, 13671 MachineFunction &MF, 13672 unsigned Intrinsic) const { 13673 switch (Intrinsic) { 13674 case Intrinsic::arm_neon_vld1: 13675 case Intrinsic::arm_neon_vld2: 13676 case Intrinsic::arm_neon_vld3: 13677 case Intrinsic::arm_neon_vld4: 13678 case Intrinsic::arm_neon_vld2lane: 13679 case Intrinsic::arm_neon_vld3lane: 13680 case Intrinsic::arm_neon_vld4lane: { 13681 Info.opc = ISD::INTRINSIC_W_CHAIN; 13682 // Conservatively set memVT to the entire set of vectors loaded. 13683 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13684 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 13685 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13686 Info.ptrVal = I.getArgOperand(0); 13687 Info.offset = 0; 13688 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13689 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13690 // volatile loads with NEON intrinsics not supported 13691 Info.flags = MachineMemOperand::MOLoad; 13692 return true; 13693 } 13694 case Intrinsic::arm_neon_vst1: 13695 case Intrinsic::arm_neon_vst2: 13696 case Intrinsic::arm_neon_vst3: 13697 case Intrinsic::arm_neon_vst4: 13698 case Intrinsic::arm_neon_vst2lane: 13699 case Intrinsic::arm_neon_vst3lane: 13700 case Intrinsic::arm_neon_vst4lane: { 13701 Info.opc = ISD::INTRINSIC_VOID; 13702 // Conservatively set memVT to the entire set of vectors stored. 13703 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13704 unsigned NumElts = 0; 13705 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 13706 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 13707 if (!ArgTy->isVectorTy()) 13708 break; 13709 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 13710 } 13711 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13712 Info.ptrVal = I.getArgOperand(0); 13713 Info.offset = 0; 13714 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13715 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13716 // volatile stores with NEON intrinsics not supported 13717 Info.flags = MachineMemOperand::MOStore; 13718 return true; 13719 } 13720 case Intrinsic::arm_ldaex: 13721 case Intrinsic::arm_ldrex: { 13722 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13723 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 13724 Info.opc = ISD::INTRINSIC_W_CHAIN; 13725 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13726 Info.ptrVal = I.getArgOperand(0); 13727 Info.offset = 0; 13728 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13729 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 13730 return true; 13731 } 13732 case Intrinsic::arm_stlex: 13733 case Intrinsic::arm_strex: { 13734 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13735 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 13736 Info.opc = ISD::INTRINSIC_W_CHAIN; 13737 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13738 Info.ptrVal = I.getArgOperand(1); 13739 Info.offset = 0; 13740 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13741 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 13742 return true; 13743 } 13744 case Intrinsic::arm_stlexd: 13745 case Intrinsic::arm_strexd: 13746 Info.opc = ISD::INTRINSIC_W_CHAIN; 13747 Info.memVT = MVT::i64; 13748 Info.ptrVal = I.getArgOperand(2); 13749 Info.offset = 0; 13750 Info.align = 8; 13751 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 13752 return true; 13753 13754 case Intrinsic::arm_ldaexd: 13755 case Intrinsic::arm_ldrexd: 13756 Info.opc = ISD::INTRINSIC_W_CHAIN; 13757 Info.memVT = MVT::i64; 13758 Info.ptrVal = I.getArgOperand(0); 13759 Info.offset = 0; 13760 Info.align = 8; 13761 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 13762 return true; 13763 13764 default: 13765 break; 13766 } 13767 13768 return false; 13769 } 13770 13771 /// \brief Returns true if it is beneficial to convert a load of a constant 13772 /// to just the constant itself. 13773 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13774 Type *Ty) const { 13775 assert(Ty->isIntegerTy()); 13776 13777 unsigned Bits = Ty->getPrimitiveSizeInBits(); 13778 if (Bits == 0 || Bits > 32) 13779 return false; 13780 return true; 13781 } 13782 13783 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 13784 unsigned Index) const { 13785 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 13786 return false; 13787 13788 return (Index == 0 || Index == ResVT.getVectorNumElements()); 13789 } 13790 13791 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 13792 ARM_MB::MemBOpt Domain) const { 13793 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13794 13795 // First, if the target has no DMB, see what fallback we can use. 13796 if (!Subtarget->hasDataBarrier()) { 13797 // Some ARMv6 cpus can support data barriers with an mcr instruction. 13798 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 13799 // here. 13800 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 13801 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 13802 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 13803 Builder.getInt32(0), Builder.getInt32(7), 13804 Builder.getInt32(10), Builder.getInt32(5)}; 13805 return Builder.CreateCall(MCR, args); 13806 } else { 13807 // Instead of using barriers, atomic accesses on these subtargets use 13808 // libcalls. 13809 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 13810 } 13811 } else { 13812 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 13813 // Only a full system barrier exists in the M-class architectures. 13814 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 13815 Constant *CDomain = Builder.getInt32(Domain); 13816 return Builder.CreateCall(DMB, CDomain); 13817 } 13818 } 13819 13820 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 13821 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 13822 Instruction *Inst, 13823 AtomicOrdering Ord) const { 13824 switch (Ord) { 13825 case AtomicOrdering::NotAtomic: 13826 case AtomicOrdering::Unordered: 13827 llvm_unreachable("Invalid fence: unordered/non-atomic"); 13828 case AtomicOrdering::Monotonic: 13829 case AtomicOrdering::Acquire: 13830 return nullptr; // Nothing to do 13831 case AtomicOrdering::SequentiallyConsistent: 13832 if (!Inst->hasAtomicStore()) 13833 return nullptr; // Nothing to do 13834 LLVM_FALLTHROUGH; 13835 case AtomicOrdering::Release: 13836 case AtomicOrdering::AcquireRelease: 13837 if (Subtarget->preferISHSTBarriers()) 13838 return makeDMB(Builder, ARM_MB::ISHST); 13839 // FIXME: add a comment with a link to documentation justifying this. 13840 else 13841 return makeDMB(Builder, ARM_MB::ISH); 13842 } 13843 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 13844 } 13845 13846 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 13847 Instruction *Inst, 13848 AtomicOrdering Ord) const { 13849 switch (Ord) { 13850 case AtomicOrdering::NotAtomic: 13851 case AtomicOrdering::Unordered: 13852 llvm_unreachable("Invalid fence: unordered/not-atomic"); 13853 case AtomicOrdering::Monotonic: 13854 case AtomicOrdering::Release: 13855 return nullptr; // Nothing to do 13856 case AtomicOrdering::Acquire: 13857 case AtomicOrdering::AcquireRelease: 13858 case AtomicOrdering::SequentiallyConsistent: 13859 return makeDMB(Builder, ARM_MB::ISH); 13860 } 13861 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 13862 } 13863 13864 // Loads and stores less than 64-bits are already atomic; ones above that 13865 // are doomed anyway, so defer to the default libcall and blame the OS when 13866 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13867 // anything for those. 13868 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 13869 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 13870 return (Size == 64) && !Subtarget->isMClass(); 13871 } 13872 13873 // Loads and stores less than 64-bits are already atomic; ones above that 13874 // are doomed anyway, so defer to the default libcall and blame the OS when 13875 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13876 // anything for those. 13877 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 13878 // guarantee, see DDI0406C ARM architecture reference manual, 13879 // sections A8.8.72-74 LDRD) 13880 TargetLowering::AtomicExpansionKind 13881 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 13882 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 13883 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 13884 : AtomicExpansionKind::None; 13885 } 13886 13887 // For the real atomic operations, we have ldrex/strex up to 32 bits, 13888 // and up to 64 bits on the non-M profiles 13889 TargetLowering::AtomicExpansionKind 13890 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13891 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13892 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13893 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 13894 ? AtomicExpansionKind::LLSC 13895 : AtomicExpansionKind::None; 13896 } 13897 13898 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 13899 AtomicCmpXchgInst *AI) const { 13900 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 13901 // implement cmpxchg without spilling. If the address being exchanged is also 13902 // on the stack and close enough to the spill slot, this can lead to a 13903 // situation where the monitor always gets cleared and the atomic operation 13904 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 13905 bool hasAtomicCmpXchg = 13906 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13907 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 13908 } 13909 13910 bool ARMTargetLowering::shouldInsertFencesForAtomic( 13911 const Instruction *I) const { 13912 return InsertFencesForAtomic; 13913 } 13914 13915 // This has so far only been implemented for MachO. 13916 bool ARMTargetLowering::useLoadStackGuardNode() const { 13917 return Subtarget->isTargetMachO(); 13918 } 13919 13920 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 13921 unsigned &Cost) const { 13922 // If we do not have NEON, vector types are not natively supported. 13923 if (!Subtarget->hasNEON()) 13924 return false; 13925 13926 // Floating point values and vector values map to the same register file. 13927 // Therefore, although we could do a store extract of a vector type, this is 13928 // better to leave at float as we have more freedom in the addressing mode for 13929 // those. 13930 if (VectorTy->isFPOrFPVectorTy()) 13931 return false; 13932 13933 // If the index is unknown at compile time, this is very expensive to lower 13934 // and it is not possible to combine the store with the extract. 13935 if (!isa<ConstantInt>(Idx)) 13936 return false; 13937 13938 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 13939 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 13940 // We can do a store + vector extract on any vector that fits perfectly in a D 13941 // or Q register. 13942 if (BitWidth == 64 || BitWidth == 128) { 13943 Cost = 0; 13944 return true; 13945 } 13946 return false; 13947 } 13948 13949 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 13950 return Subtarget->hasV6T2Ops(); 13951 } 13952 13953 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 13954 return Subtarget->hasV6T2Ops(); 13955 } 13956 13957 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 13958 AtomicOrdering Ord) const { 13959 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13960 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 13961 bool IsAcquire = isAcquireOrStronger(Ord); 13962 13963 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 13964 // intrinsic must return {i32, i32} and we have to recombine them into a 13965 // single i64 here. 13966 if (ValTy->getPrimitiveSizeInBits() == 64) { 13967 Intrinsic::ID Int = 13968 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 13969 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 13970 13971 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13972 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 13973 13974 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 13975 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 13976 if (!Subtarget->isLittle()) 13977 std::swap (Lo, Hi); 13978 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 13979 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 13980 return Builder.CreateOr( 13981 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 13982 } 13983 13984 Type *Tys[] = { Addr->getType() }; 13985 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 13986 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 13987 13988 return Builder.CreateTruncOrBitCast( 13989 Builder.CreateCall(Ldrex, Addr), 13990 cast<PointerType>(Addr->getType())->getElementType()); 13991 } 13992 13993 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 13994 IRBuilder<> &Builder) const { 13995 if (!Subtarget->hasV7Ops()) 13996 return; 13997 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13998 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 13999 } 14000 14001 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 14002 Value *Addr, 14003 AtomicOrdering Ord) const { 14004 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14005 bool IsRelease = isReleaseOrStronger(Ord); 14006 14007 // Since the intrinsics must have legal type, the i64 intrinsics take two 14008 // parameters: "i32, i32". We must marshal Val into the appropriate form 14009 // before the call. 14010 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 14011 Intrinsic::ID Int = 14012 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 14013 Function *Strex = Intrinsic::getDeclaration(M, Int); 14014 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 14015 14016 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 14017 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 14018 if (!Subtarget->isLittle()) 14019 std::swap(Lo, Hi); 14020 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14021 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 14022 } 14023 14024 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 14025 Type *Tys[] = { Addr->getType() }; 14026 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 14027 14028 return Builder.CreateCall( 14029 Strex, {Builder.CreateZExtOrBitCast( 14030 Val, Strex->getFunctionType()->getParamType(0)), 14031 Addr}); 14032 } 14033 14034 /// A helper function for determining the number of interleaved accesses we 14035 /// will generate when lowering accesses of the given type. 14036 unsigned 14037 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 14038 const DataLayout &DL) const { 14039 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 14040 } 14041 14042 bool ARMTargetLowering::isLegalInterleavedAccessType( 14043 VectorType *VecTy, const DataLayout &DL) const { 14044 14045 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 14046 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 14047 14048 // Ensure the vector doesn't have f16 elements. Even though we could do an 14049 // i16 vldN, we can't hold the f16 vectors and will end up converting via 14050 // f32. 14051 if (VecTy->getElementType()->isHalfTy()) 14052 return false; 14053 14054 // Ensure the number of vector elements is greater than 1. 14055 if (VecTy->getNumElements() < 2) 14056 return false; 14057 14058 // Ensure the element type is legal. 14059 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 14060 return false; 14061 14062 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 14063 // 128 will be split into multiple interleaved accesses. 14064 return VecSize == 64 || VecSize % 128 == 0; 14065 } 14066 14067 /// \brief Lower an interleaved load into a vldN intrinsic. 14068 /// 14069 /// E.g. Lower an interleaved load (Factor = 2): 14070 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 14071 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 14072 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 14073 /// 14074 /// Into: 14075 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 14076 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 14077 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 14078 bool ARMTargetLowering::lowerInterleavedLoad( 14079 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 14080 ArrayRef<unsigned> Indices, unsigned Factor) const { 14081 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14082 "Invalid interleave factor"); 14083 assert(!Shuffles.empty() && "Empty shufflevector input"); 14084 assert(Shuffles.size() == Indices.size() && 14085 "Unmatched number of shufflevectors and indices"); 14086 14087 VectorType *VecTy = Shuffles[0]->getType(); 14088 Type *EltTy = VecTy->getVectorElementType(); 14089 14090 const DataLayout &DL = LI->getModule()->getDataLayout(); 14091 14092 // Skip if we do not have NEON and skip illegal vector types. We can 14093 // "legalize" wide vector types into multiple interleaved accesses as long as 14094 // the vector types are divisible by 128. 14095 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 14096 return false; 14097 14098 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 14099 14100 // A pointer vector can not be the return type of the ldN intrinsics. Need to 14101 // load integer vectors first and then convert to pointer vectors. 14102 if (EltTy->isPointerTy()) 14103 VecTy = 14104 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 14105 14106 IRBuilder<> Builder(LI); 14107 14108 // The base address of the load. 14109 Value *BaseAddr = LI->getPointerOperand(); 14110 14111 if (NumLoads > 1) { 14112 // If we're going to generate more than one load, reset the sub-vector type 14113 // to something legal. 14114 VecTy = VectorType::get(VecTy->getVectorElementType(), 14115 VecTy->getVectorNumElements() / NumLoads); 14116 14117 // We will compute the pointer operand of each load from the original base 14118 // address using GEPs. Cast the base address to a pointer to the scalar 14119 // element type. 14120 BaseAddr = Builder.CreateBitCast( 14121 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 14122 LI->getPointerAddressSpace())); 14123 } 14124 14125 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 14126 14127 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 14128 Type *Tys[] = {VecTy, Int8Ptr}; 14129 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 14130 Intrinsic::arm_neon_vld3, 14131 Intrinsic::arm_neon_vld4}; 14132 Function *VldnFunc = 14133 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 14134 14135 // Holds sub-vectors extracted from the load intrinsic return values. The 14136 // sub-vectors are associated with the shufflevector instructions they will 14137 // replace. 14138 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 14139 14140 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 14141 // If we're generating more than one load, compute the base address of 14142 // subsequent loads as an offset from the previous. 14143 if (LoadCount > 0) 14144 BaseAddr = Builder.CreateConstGEP1_32( 14145 BaseAddr, VecTy->getVectorNumElements() * Factor); 14146 14147 SmallVector<Value *, 2> Ops; 14148 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14149 Ops.push_back(Builder.getInt32(LI->getAlignment())); 14150 14151 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 14152 14153 // Replace uses of each shufflevector with the corresponding vector loaded 14154 // by ldN. 14155 for (unsigned i = 0; i < Shuffles.size(); i++) { 14156 ShuffleVectorInst *SV = Shuffles[i]; 14157 unsigned Index = Indices[i]; 14158 14159 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 14160 14161 // Convert the integer vector to pointer vector if the element is pointer. 14162 if (EltTy->isPointerTy()) 14163 SubVec = Builder.CreateIntToPtr( 14164 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 14165 VecTy->getVectorNumElements())); 14166 14167 SubVecs[SV].push_back(SubVec); 14168 } 14169 } 14170 14171 // Replace uses of the shufflevector instructions with the sub-vectors 14172 // returned by the load intrinsic. If a shufflevector instruction is 14173 // associated with more than one sub-vector, those sub-vectors will be 14174 // concatenated into a single wide vector. 14175 for (ShuffleVectorInst *SVI : Shuffles) { 14176 auto &SubVec = SubVecs[SVI]; 14177 auto *WideVec = 14178 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 14179 SVI->replaceAllUsesWith(WideVec); 14180 } 14181 14182 return true; 14183 } 14184 14185 /// \brief Lower an interleaved store into a vstN intrinsic. 14186 /// 14187 /// E.g. Lower an interleaved store (Factor = 3): 14188 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 14189 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 14190 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 14191 /// 14192 /// Into: 14193 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 14194 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 14195 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 14196 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14197 /// 14198 /// Note that the new shufflevectors will be removed and we'll only generate one 14199 /// vst3 instruction in CodeGen. 14200 /// 14201 /// Example for a more general valid mask (Factor 3). Lower: 14202 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 14203 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 14204 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 14205 /// 14206 /// Into: 14207 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 14208 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 14209 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 14210 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14211 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 14212 ShuffleVectorInst *SVI, 14213 unsigned Factor) const { 14214 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14215 "Invalid interleave factor"); 14216 14217 VectorType *VecTy = SVI->getType(); 14218 assert(VecTy->getVectorNumElements() % Factor == 0 && 14219 "Invalid interleaved store"); 14220 14221 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 14222 Type *EltTy = VecTy->getVectorElementType(); 14223 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 14224 14225 const DataLayout &DL = SI->getModule()->getDataLayout(); 14226 14227 // Skip if we do not have NEON and skip illegal vector types. We can 14228 // "legalize" wide vector types into multiple interleaved accesses as long as 14229 // the vector types are divisible by 128. 14230 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 14231 return false; 14232 14233 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 14234 14235 Value *Op0 = SVI->getOperand(0); 14236 Value *Op1 = SVI->getOperand(1); 14237 IRBuilder<> Builder(SI); 14238 14239 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 14240 // vectors to integer vectors. 14241 if (EltTy->isPointerTy()) { 14242 Type *IntTy = DL.getIntPtrType(EltTy); 14243 14244 // Convert to the corresponding integer vector. 14245 Type *IntVecTy = 14246 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 14247 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 14248 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 14249 14250 SubVecTy = VectorType::get(IntTy, LaneLen); 14251 } 14252 14253 // The base address of the store. 14254 Value *BaseAddr = SI->getPointerOperand(); 14255 14256 if (NumStores > 1) { 14257 // If we're going to generate more than one store, reset the lane length 14258 // and sub-vector type to something legal. 14259 LaneLen /= NumStores; 14260 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 14261 14262 // We will compute the pointer operand of each store from the original base 14263 // address using GEPs. Cast the base address to a pointer to the scalar 14264 // element type. 14265 BaseAddr = Builder.CreateBitCast( 14266 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 14267 SI->getPointerAddressSpace())); 14268 } 14269 14270 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 14271 14272 auto Mask = SVI->getShuffleMask(); 14273 14274 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 14275 Type *Tys[] = {Int8Ptr, SubVecTy}; 14276 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 14277 Intrinsic::arm_neon_vst3, 14278 Intrinsic::arm_neon_vst4}; 14279 14280 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 14281 // If we generating more than one store, we compute the base address of 14282 // subsequent stores as an offset from the previous. 14283 if (StoreCount > 0) 14284 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 14285 14286 SmallVector<Value *, 6> Ops; 14287 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14288 14289 Function *VstNFunc = 14290 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 14291 14292 // Split the shufflevector operands into sub vectors for the new vstN call. 14293 for (unsigned i = 0; i < Factor; i++) { 14294 unsigned IdxI = StoreCount * LaneLen * Factor + i; 14295 if (Mask[IdxI] >= 0) { 14296 Ops.push_back(Builder.CreateShuffleVector( 14297 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 14298 } else { 14299 unsigned StartMask = 0; 14300 for (unsigned j = 1; j < LaneLen; j++) { 14301 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 14302 if (Mask[IdxJ * Factor + IdxI] >= 0) { 14303 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 14304 break; 14305 } 14306 } 14307 // Note: If all elements in a chunk are undefs, StartMask=0! 14308 // Note: Filling undef gaps with random elements is ok, since 14309 // those elements were being written anyway (with undefs). 14310 // In the case of all undefs we're defaulting to using elems from 0 14311 // Note: StartMask cannot be negative, it's checked in 14312 // isReInterleaveMask 14313 Ops.push_back(Builder.CreateShuffleVector( 14314 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 14315 } 14316 } 14317 14318 Ops.push_back(Builder.getInt32(SI->getAlignment())); 14319 Builder.CreateCall(VstNFunc, Ops); 14320 } 14321 return true; 14322 } 14323 14324 enum HABaseType { 14325 HA_UNKNOWN = 0, 14326 HA_FLOAT, 14327 HA_DOUBLE, 14328 HA_VECT64, 14329 HA_VECT128 14330 }; 14331 14332 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 14333 uint64_t &Members) { 14334 if (auto *ST = dyn_cast<StructType>(Ty)) { 14335 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 14336 uint64_t SubMembers = 0; 14337 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 14338 return false; 14339 Members += SubMembers; 14340 } 14341 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 14342 uint64_t SubMembers = 0; 14343 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 14344 return false; 14345 Members += SubMembers * AT->getNumElements(); 14346 } else if (Ty->isFloatTy()) { 14347 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 14348 return false; 14349 Members = 1; 14350 Base = HA_FLOAT; 14351 } else if (Ty->isDoubleTy()) { 14352 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 14353 return false; 14354 Members = 1; 14355 Base = HA_DOUBLE; 14356 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 14357 Members = 1; 14358 switch (Base) { 14359 case HA_FLOAT: 14360 case HA_DOUBLE: 14361 return false; 14362 case HA_VECT64: 14363 return VT->getBitWidth() == 64; 14364 case HA_VECT128: 14365 return VT->getBitWidth() == 128; 14366 case HA_UNKNOWN: 14367 switch (VT->getBitWidth()) { 14368 case 64: 14369 Base = HA_VECT64; 14370 return true; 14371 case 128: 14372 Base = HA_VECT128; 14373 return true; 14374 default: 14375 return false; 14376 } 14377 } 14378 } 14379 14380 return (Members > 0 && Members <= 4); 14381 } 14382 14383 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 14384 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 14385 /// passing according to AAPCS rules. 14386 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 14387 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 14388 if (getEffectiveCallingConv(CallConv, isVarArg) != 14389 CallingConv::ARM_AAPCS_VFP) 14390 return false; 14391 14392 HABaseType Base = HA_UNKNOWN; 14393 uint64_t Members = 0; 14394 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 14395 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 14396 14397 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 14398 return IsHA || IsIntArray; 14399 } 14400 14401 unsigned ARMTargetLowering::getExceptionPointerRegister( 14402 const Constant *PersonalityFn) const { 14403 // Platforms which do not use SjLj EH may return values in these registers 14404 // via the personality function. 14405 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 14406 } 14407 14408 unsigned ARMTargetLowering::getExceptionSelectorRegister( 14409 const Constant *PersonalityFn) const { 14410 // Platforms which do not use SjLj EH may return values in these registers 14411 // via the personality function. 14412 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 14413 } 14414 14415 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14416 // Update IsSplitCSR in ARMFunctionInfo. 14417 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 14418 AFI->setIsSplitCSR(true); 14419 } 14420 14421 void ARMTargetLowering::insertCopiesSplitCSR( 14422 MachineBasicBlock *Entry, 14423 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14424 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 14425 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14426 if (!IStart) 14427 return; 14428 14429 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 14430 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14431 MachineBasicBlock::iterator MBBI = Entry->begin(); 14432 for (const MCPhysReg *I = IStart; *I; ++I) { 14433 const TargetRegisterClass *RC = nullptr; 14434 if (ARM::GPRRegClass.contains(*I)) 14435 RC = &ARM::GPRRegClass; 14436 else if (ARM::DPRRegClass.contains(*I)) 14437 RC = &ARM::DPRRegClass; 14438 else 14439 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14440 14441 unsigned NewVR = MRI->createVirtualRegister(RC); 14442 // Create copy from CSR to a virtual register. 14443 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14444 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14445 // nounwind. If we want to generalize this later, we may need to emit 14446 // CFI pseudo-instructions. 14447 assert(Entry->getParent()->getFunction().hasFnAttribute( 14448 Attribute::NoUnwind) && 14449 "Function should be nounwind in insertCopiesSplitCSR!"); 14450 Entry->addLiveIn(*I); 14451 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14452 .addReg(*I); 14453 14454 // Insert the copy-back instructions right before the terminator. 14455 for (auto *Exit : Exits) 14456 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14457 TII->get(TargetOpcode::COPY), *I) 14458 .addReg(NewVR); 14459 } 14460 } 14461 14462 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 14463 MF.getFrameInfo().computeMaxCallFrameSize(MF); 14464 TargetLoweringBase::finalizeLowering(MF); 14465 } 14466