1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that ARM uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "ARMISelLowering.h" 15 #include "ARMBaseInstrInfo.h" 16 #include "ARMBaseRegisterInfo.h" 17 #include "ARMCallingConv.h" 18 #include "ARMConstantPoolValue.h" 19 #include "ARMMachineFunctionInfo.h" 20 #include "ARMPerfectShuffle.h" 21 #include "ARMRegisterInfo.h" 22 #include "ARMSelectionDAGInfo.h" 23 #include "ARMSubtarget.h" 24 #include "MCTargetDesc/ARMAddressingModes.h" 25 #include "MCTargetDesc/ARMBaseInfo.h" 26 #include "Utils/ARMBaseInfo.h" 27 #include "llvm/ADT/APFloat.h" 28 #include "llvm/ADT/APInt.h" 29 #include "llvm/ADT/ArrayRef.h" 30 #include "llvm/ADT/BitVector.h" 31 #include "llvm/ADT/DenseMap.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/ADT/StringRef.h" 38 #include "llvm/ADT/StringSwitch.h" 39 #include "llvm/ADT/Triple.h" 40 #include "llvm/ADT/Twine.h" 41 #include "llvm/Analysis/VectorUtils.h" 42 #include "llvm/CodeGen/CallingConvLower.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/IntrinsicLowering.h" 45 #include "llvm/CodeGen/MachineBasicBlock.h" 46 #include "llvm/CodeGen/MachineConstantPool.h" 47 #include "llvm/CodeGen/MachineFrameInfo.h" 48 #include "llvm/CodeGen/MachineFunction.h" 49 #include "llvm/CodeGen/MachineInstr.h" 50 #include "llvm/CodeGen/MachineInstrBuilder.h" 51 #include "llvm/CodeGen/MachineJumpTableInfo.h" 52 #include "llvm/CodeGen/MachineMemOperand.h" 53 #include "llvm/CodeGen/MachineOperand.h" 54 #include "llvm/CodeGen/MachineRegisterInfo.h" 55 #include "llvm/CodeGen/RuntimeLibcalls.h" 56 #include "llvm/CodeGen/SelectionDAG.h" 57 #include "llvm/CodeGen/SelectionDAGNodes.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/IR/Attributes.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DebugLoc.h" 70 #include "llvm/IR/DerivedTypes.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GlobalAlias.h" 73 #include "llvm/IR/GlobalValue.h" 74 #include "llvm/IR/GlobalVariable.h" 75 #include "llvm/IR/IRBuilder.h" 76 #include "llvm/IR/InlineAsm.h" 77 #include "llvm/IR/Instruction.h" 78 #include "llvm/IR/Instructions.h" 79 #include "llvm/IR/IntrinsicInst.h" 80 #include "llvm/IR/Intrinsics.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/PatternMatch.h" 83 #include "llvm/IR/Type.h" 84 #include "llvm/IR/User.h" 85 #include "llvm/IR/Value.h" 86 #include "llvm/MC/MCInstrDesc.h" 87 #include "llvm/MC/MCInstrItineraries.h" 88 #include "llvm/MC/MCRegisterInfo.h" 89 #include "llvm/MC/MCSchedule.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/BranchProbability.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CodeGen.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/ErrorHandling.h" 98 #include "llvm/Support/KnownBits.h" 99 #include "llvm/Support/MachineValueType.h" 100 #include "llvm/Support/MathExtras.h" 101 #include "llvm/Support/raw_ostream.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.h" 104 #include <algorithm> 105 #include <cassert> 106 #include <cstdint> 107 #include <cstdlib> 108 #include <iterator> 109 #include <limits> 110 #include <string> 111 #include <tuple> 112 #include <utility> 113 #include <vector> 114 115 using namespace llvm; 116 using namespace llvm::PatternMatch; 117 118 #define DEBUG_TYPE "arm-isel" 119 120 STATISTIC(NumTailCalls, "Number of tail calls"); 121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 123 STATISTIC(NumConstpoolPromoted, 124 "Number of constants with their storage promoted into constant pools"); 125 126 static cl::opt<bool> 127 ARMInterworking("arm-interworking", cl::Hidden, 128 cl::desc("Enable / disable ARM interworking (for debugging only)"), 129 cl::init(true)); 130 131 static cl::opt<bool> EnableConstpoolPromotion( 132 "arm-promote-constant", cl::Hidden, 133 cl::desc("Enable / disable promotion of unnamed_addr constants into " 134 "constant pools"), 135 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 136 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 137 "arm-promote-constant-max-size", cl::Hidden, 138 cl::desc("Maximum size of constant to promote into a constant pool"), 139 cl::init(64)); 140 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 141 "arm-promote-constant-max-total", cl::Hidden, 142 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 143 cl::init(128)); 144 145 // The APCS parameter registers. 146 static const MCPhysReg GPRArgRegs[] = { 147 ARM::R0, ARM::R1, ARM::R2, ARM::R3 148 }; 149 150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 151 MVT PromotedBitwiseVT) { 152 if (VT != PromotedLdStVT) { 153 setOperationAction(ISD::LOAD, VT, Promote); 154 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 155 156 setOperationAction(ISD::STORE, VT, Promote); 157 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 158 } 159 160 MVT ElemTy = VT.getVectorElementType(); 161 if (ElemTy != MVT::f64) 162 setOperationAction(ISD::SETCC, VT, Custom); 163 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 164 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 165 if (ElemTy == MVT::i32) { 166 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 167 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 168 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 169 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 170 } else { 171 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 172 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 173 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 174 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 175 } 176 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 177 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 178 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 179 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 180 setOperationAction(ISD::SELECT, VT, Expand); 181 setOperationAction(ISD::SELECT_CC, VT, Expand); 182 setOperationAction(ISD::VSELECT, VT, Expand); 183 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 184 if (VT.isInteger()) { 185 setOperationAction(ISD::SHL, VT, Custom); 186 setOperationAction(ISD::SRA, VT, Custom); 187 setOperationAction(ISD::SRL, VT, Custom); 188 } 189 190 // Promote all bit-wise operations. 191 if (VT.isInteger() && VT != PromotedBitwiseVT) { 192 setOperationAction(ISD::AND, VT, Promote); 193 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 194 setOperationAction(ISD::OR, VT, Promote); 195 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 196 setOperationAction(ISD::XOR, VT, Promote); 197 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 198 } 199 200 // Neon does not support vector divide/remainder operations. 201 setOperationAction(ISD::SDIV, VT, Expand); 202 setOperationAction(ISD::UDIV, VT, Expand); 203 setOperationAction(ISD::FDIV, VT, Expand); 204 setOperationAction(ISD::SREM, VT, Expand); 205 setOperationAction(ISD::UREM, VT, Expand); 206 setOperationAction(ISD::FREM, VT, Expand); 207 208 if (!VT.isFloatingPoint() && 209 VT != MVT::v2i64 && VT != MVT::v1i64) 210 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 211 setOperationAction(Opcode, VT, Legal); 212 } 213 214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 215 addRegisterClass(VT, &ARM::DPRRegClass); 216 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 217 } 218 219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 220 addRegisterClass(VT, &ARM::DPairRegClass); 221 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 222 } 223 224 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 225 const ARMSubtarget &STI) 226 : TargetLowering(TM), Subtarget(&STI) { 227 RegInfo = Subtarget->getRegisterInfo(); 228 Itins = Subtarget->getInstrItineraryData(); 229 230 setBooleanContents(ZeroOrOneBooleanContent); 231 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 232 233 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 234 !Subtarget->isTargetWatchOS()) { 235 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 236 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 237 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 238 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 239 : CallingConv::ARM_AAPCS); 240 } 241 242 if (Subtarget->isTargetMachO()) { 243 // Uses VFP for Thumb libfuncs if available. 244 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 245 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 246 static const struct { 247 const RTLIB::Libcall Op; 248 const char * const Name; 249 const ISD::CondCode Cond; 250 } LibraryCalls[] = { 251 // Single-precision floating-point arithmetic. 252 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 253 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 254 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 255 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 256 257 // Double-precision floating-point arithmetic. 258 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 259 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 260 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 261 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 262 263 // Single-precision comparisons. 264 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 265 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 266 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 267 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 268 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 269 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 270 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 271 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 272 273 // Double-precision comparisons. 274 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 275 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 276 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 277 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 278 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 279 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 280 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 281 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 282 283 // Floating-point to integer conversions. 284 // i64 conversions are done via library routines even when generating VFP 285 // instructions, so use the same ones. 286 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 287 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 288 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 289 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 290 291 // Conversions between floating types. 292 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 293 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 294 295 // Integer to floating-point conversions. 296 // i64 conversions are done via library routines even when generating VFP 297 // instructions, so use the same ones. 298 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 299 // e.g., __floatunsidf vs. __floatunssidfvfp. 300 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 301 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 302 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 303 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 304 }; 305 306 for (const auto &LC : LibraryCalls) { 307 setLibcallName(LC.Op, LC.Name); 308 if (LC.Cond != ISD::SETCC_INVALID) 309 setCmpLibcallCC(LC.Op, LC.Cond); 310 } 311 } 312 } 313 314 // These libcalls are not available in 32-bit. 315 setLibcallName(RTLIB::SHL_I128, nullptr); 316 setLibcallName(RTLIB::SRL_I128, nullptr); 317 setLibcallName(RTLIB::SRA_I128, nullptr); 318 319 // RTLIB 320 if (Subtarget->isAAPCS_ABI() && 321 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 322 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 323 static const struct { 324 const RTLIB::Libcall Op; 325 const char * const Name; 326 const CallingConv::ID CC; 327 const ISD::CondCode Cond; 328 } LibraryCalls[] = { 329 // Double-precision floating-point arithmetic helper functions 330 // RTABI chapter 4.1.2, Table 2 331 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 334 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 335 336 // Double-precision floating-point comparison helper functions 337 // RTABI chapter 4.1.2, Table 3 338 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 339 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 340 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 341 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 342 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 343 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 344 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 345 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 346 347 // Single-precision floating-point arithmetic helper functions 348 // RTABI chapter 4.1.2, Table 4 349 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 350 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 351 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 352 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 353 354 // Single-precision floating-point comparison helper functions 355 // RTABI chapter 4.1.2, Table 5 356 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 357 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 358 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 359 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 360 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 361 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 362 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 363 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 364 365 // Floating-point to integer conversions. 366 // RTABI chapter 4.1.2, Table 6 367 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 368 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 369 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 370 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 371 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 372 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 373 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 374 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 375 376 // Conversions between floating types. 377 // RTABI chapter 4.1.2, Table 7 378 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 380 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 381 382 // Integer to floating-point conversions. 383 // RTABI chapter 4.1.2, Table 8 384 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 385 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 386 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 387 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 388 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 389 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 390 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 391 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 392 393 // Long long helper functions 394 // RTABI chapter 4.2, Table 9 395 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 398 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 399 400 // Integer division functions 401 // RTABI chapter 4.3.1 402 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 403 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 404 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 406 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 407 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 408 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 409 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 410 }; 411 412 for (const auto &LC : LibraryCalls) { 413 setLibcallName(LC.Op, LC.Name); 414 setLibcallCallingConv(LC.Op, LC.CC); 415 if (LC.Cond != ISD::SETCC_INVALID) 416 setCmpLibcallCC(LC.Op, LC.Cond); 417 } 418 419 // EABI dependent RTLIB 420 if (TM.Options.EABIVersion == EABI::EABI4 || 421 TM.Options.EABIVersion == EABI::EABI5) { 422 static const struct { 423 const RTLIB::Libcall Op; 424 const char *const Name; 425 const CallingConv::ID CC; 426 const ISD::CondCode Cond; 427 } MemOpsLibraryCalls[] = { 428 // Memory operations 429 // RTABI chapter 4.3.4 430 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 431 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 432 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 433 }; 434 435 for (const auto &LC : MemOpsLibraryCalls) { 436 setLibcallName(LC.Op, LC.Name); 437 setLibcallCallingConv(LC.Op, LC.CC); 438 if (LC.Cond != ISD::SETCC_INVALID) 439 setCmpLibcallCC(LC.Op, LC.Cond); 440 } 441 } 442 } 443 444 if (Subtarget->isTargetWindows()) { 445 static const struct { 446 const RTLIB::Libcall Op; 447 const char * const Name; 448 const CallingConv::ID CC; 449 } LibraryCalls[] = { 450 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 451 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 452 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 453 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 454 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 455 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 456 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 457 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 458 }; 459 460 for (const auto &LC : LibraryCalls) { 461 setLibcallName(LC.Op, LC.Name); 462 setLibcallCallingConv(LC.Op, LC.CC); 463 } 464 } 465 466 // Use divmod compiler-rt calls for iOS 5.0 and later. 467 if (Subtarget->isTargetMachO() && 468 !(Subtarget->isTargetIOS() && 469 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 470 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 471 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 472 } 473 474 // The half <-> float conversion functions are always soft-float on 475 // non-watchos platforms, but are needed for some targets which use a 476 // hard-float calling convention by default. 477 if (!Subtarget->isTargetWatchABI()) { 478 if (Subtarget->isAAPCS_ABI()) { 479 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 480 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 481 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 482 } else { 483 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 484 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 485 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 486 } 487 } 488 489 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 490 // a __gnu_ prefix (which is the default). 491 if (Subtarget->isTargetAEABI()) { 492 static const struct { 493 const RTLIB::Libcall Op; 494 const char * const Name; 495 const CallingConv::ID CC; 496 } LibraryCalls[] = { 497 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 498 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 499 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 500 }; 501 502 for (const auto &LC : LibraryCalls) { 503 setLibcallName(LC.Op, LC.Name); 504 setLibcallCallingConv(LC.Op, LC.CC); 505 } 506 } 507 508 if (Subtarget->isThumb1Only()) 509 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 510 else 511 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 512 513 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 514 !Subtarget->isThumb1Only()) { 515 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 516 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 517 } 518 519 if (Subtarget->hasFullFP16()) { 520 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 521 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 522 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 523 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 524 525 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 526 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 527 } 528 529 for (MVT VT : MVT::vector_valuetypes()) { 530 for (MVT InnerVT : MVT::vector_valuetypes()) { 531 setTruncStoreAction(VT, InnerVT, Expand); 532 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 533 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 534 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 535 } 536 537 setOperationAction(ISD::MULHS, VT, Expand); 538 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 539 setOperationAction(ISD::MULHU, VT, Expand); 540 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 541 542 setOperationAction(ISD::BSWAP, VT, Expand); 543 } 544 545 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 546 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 547 548 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 549 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 550 551 if (Subtarget->hasNEON()) { 552 addDRTypeForNEON(MVT::v2f32); 553 addDRTypeForNEON(MVT::v8i8); 554 addDRTypeForNEON(MVT::v4i16); 555 addDRTypeForNEON(MVT::v2i32); 556 addDRTypeForNEON(MVT::v1i64); 557 558 addQRTypeForNEON(MVT::v4f32); 559 addQRTypeForNEON(MVT::v2f64); 560 addQRTypeForNEON(MVT::v16i8); 561 addQRTypeForNEON(MVT::v8i16); 562 addQRTypeForNEON(MVT::v4i32); 563 addQRTypeForNEON(MVT::v2i64); 564 565 if (Subtarget->hasFullFP16()) { 566 addQRTypeForNEON(MVT::v8f16); 567 addDRTypeForNEON(MVT::v4f16); 568 } 569 570 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 571 // neither Neon nor VFP support any arithmetic operations on it. 572 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 573 // supported for v4f32. 574 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 575 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 576 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 577 // FIXME: Code duplication: FDIV and FREM are expanded always, see 578 // ARMTargetLowering::addTypeForNEON method for details. 579 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 580 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 581 // FIXME: Create unittest. 582 // In another words, find a way when "copysign" appears in DAG with vector 583 // operands. 584 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 585 // FIXME: Code duplication: SETCC has custom operation action, see 586 // ARMTargetLowering::addTypeForNEON method for details. 587 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 588 // FIXME: Create unittest for FNEG and for FABS. 589 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 590 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 591 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 592 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 593 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 594 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 595 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 596 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 597 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 598 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 599 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 600 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 601 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 602 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 603 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 604 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 605 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 606 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 607 608 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 609 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 610 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 611 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 612 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 613 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 614 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 615 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 616 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 617 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 618 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 619 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 620 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 621 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 622 623 // Mark v2f32 intrinsics. 624 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 625 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 626 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 627 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 628 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 629 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 630 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 631 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 632 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 633 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 634 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 635 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 636 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 637 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 638 639 // Neon does not support some operations on v1i64 and v2i64 types. 640 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 641 // Custom handling for some quad-vector types to detect VMULL. 642 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 643 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 644 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 645 // Custom handling for some vector types to avoid expensive expansions 646 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 647 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 648 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 649 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 650 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 651 // a destination type that is wider than the source, and nor does 652 // it have a FP_TO_[SU]INT instruction with a narrower destination than 653 // source. 654 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 655 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 656 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 657 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 658 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 659 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 660 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 661 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 662 663 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 664 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 665 666 // NEON does not have single instruction CTPOP for vectors with element 667 // types wider than 8-bits. However, custom lowering can leverage the 668 // v8i8/v16i8 vcnt instruction. 669 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 670 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 671 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 672 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 673 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 674 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 675 676 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 677 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 678 679 // NEON does not have single instruction CTTZ for vectors. 680 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 681 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 682 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 683 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 684 685 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 686 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 687 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 688 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 689 690 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 691 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 692 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 693 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 694 695 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 696 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 697 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 698 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 699 700 // NEON only has FMA instructions as of VFP4. 701 if (!Subtarget->hasVFP4Base()) { 702 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 703 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 704 } 705 706 setTargetDAGCombine(ISD::INTRINSIC_VOID); 707 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 708 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 709 setTargetDAGCombine(ISD::SHL); 710 setTargetDAGCombine(ISD::SRL); 711 setTargetDAGCombine(ISD::SRA); 712 setTargetDAGCombine(ISD::SIGN_EXTEND); 713 setTargetDAGCombine(ISD::ZERO_EXTEND); 714 setTargetDAGCombine(ISD::ANY_EXTEND); 715 setTargetDAGCombine(ISD::BUILD_VECTOR); 716 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 717 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 718 setTargetDAGCombine(ISD::STORE); 719 setTargetDAGCombine(ISD::FP_TO_SINT); 720 setTargetDAGCombine(ISD::FP_TO_UINT); 721 setTargetDAGCombine(ISD::FDIV); 722 setTargetDAGCombine(ISD::LOAD); 723 724 // It is legal to extload from v4i8 to v4i16 or v4i32. 725 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 726 MVT::v2i32}) { 727 for (MVT VT : MVT::integer_vector_valuetypes()) { 728 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 729 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 730 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 731 } 732 } 733 } 734 735 if (!Subtarget->hasFP64()) { 736 // When targeting a floating-point unit with only single-precision 737 // operations, f64 is legal for the few double-precision instructions which 738 // are present However, no double-precision operations other than moves, 739 // loads and stores are provided by the hardware. 740 setOperationAction(ISD::FADD, MVT::f64, Expand); 741 setOperationAction(ISD::FSUB, MVT::f64, Expand); 742 setOperationAction(ISD::FMUL, MVT::f64, Expand); 743 setOperationAction(ISD::FMA, MVT::f64, Expand); 744 setOperationAction(ISD::FDIV, MVT::f64, Expand); 745 setOperationAction(ISD::FREM, MVT::f64, Expand); 746 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 747 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 748 setOperationAction(ISD::FNEG, MVT::f64, Expand); 749 setOperationAction(ISD::FABS, MVT::f64, Expand); 750 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 751 setOperationAction(ISD::FSIN, MVT::f64, Expand); 752 setOperationAction(ISD::FCOS, MVT::f64, Expand); 753 setOperationAction(ISD::FPOW, MVT::f64, Expand); 754 setOperationAction(ISD::FLOG, MVT::f64, Expand); 755 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 756 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 757 setOperationAction(ISD::FEXP, MVT::f64, Expand); 758 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 759 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 760 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 761 setOperationAction(ISD::FRINT, MVT::f64, Expand); 762 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 763 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 764 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 765 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 766 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 767 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 768 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 769 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 770 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 771 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 772 } 773 774 computeRegisterProperties(Subtarget->getRegisterInfo()); 775 776 // ARM does not have floating-point extending loads. 777 for (MVT VT : MVT::fp_valuetypes()) { 778 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 779 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 780 } 781 782 // ... or truncating stores 783 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 784 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 785 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 786 787 // ARM does not have i1 sign extending load. 788 for (MVT VT : MVT::integer_valuetypes()) 789 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 790 791 // ARM supports all 4 flavors of integer indexed load / store. 792 if (!Subtarget->isThumb1Only()) { 793 for (unsigned im = (unsigned)ISD::PRE_INC; 794 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 795 setIndexedLoadAction(im, MVT::i1, Legal); 796 setIndexedLoadAction(im, MVT::i8, Legal); 797 setIndexedLoadAction(im, MVT::i16, Legal); 798 setIndexedLoadAction(im, MVT::i32, Legal); 799 setIndexedStoreAction(im, MVT::i1, Legal); 800 setIndexedStoreAction(im, MVT::i8, Legal); 801 setIndexedStoreAction(im, MVT::i16, Legal); 802 setIndexedStoreAction(im, MVT::i32, Legal); 803 } 804 } else { 805 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 806 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 807 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 808 } 809 810 setOperationAction(ISD::SADDO, MVT::i32, Custom); 811 setOperationAction(ISD::UADDO, MVT::i32, Custom); 812 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 813 setOperationAction(ISD::USUBO, MVT::i32, Custom); 814 815 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 816 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 817 818 // i64 operation support. 819 setOperationAction(ISD::MUL, MVT::i64, Expand); 820 setOperationAction(ISD::MULHU, MVT::i32, Expand); 821 if (Subtarget->isThumb1Only()) { 822 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 823 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 824 } 825 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 826 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 827 setOperationAction(ISD::MULHS, MVT::i32, Expand); 828 829 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 830 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 831 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 832 setOperationAction(ISD::SRL, MVT::i64, Custom); 833 setOperationAction(ISD::SRA, MVT::i64, Custom); 834 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 835 836 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 837 if (Subtarget->isThumb1Only()) { 838 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 839 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 840 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 841 } 842 843 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 844 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 845 846 // ARM does not have ROTL. 847 setOperationAction(ISD::ROTL, MVT::i32, Expand); 848 for (MVT VT : MVT::vector_valuetypes()) { 849 setOperationAction(ISD::ROTL, VT, Expand); 850 setOperationAction(ISD::ROTR, VT, Expand); 851 } 852 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 853 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 854 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 855 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 856 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 857 } 858 859 // @llvm.readcyclecounter requires the Performance Monitors extension. 860 // Default to the 0 expansion on unsupported platforms. 861 // FIXME: Technically there are older ARM CPUs that have 862 // implementation-specific ways of obtaining this information. 863 if (Subtarget->hasPerfMon()) 864 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 865 866 // Only ARMv6 has BSWAP. 867 if (!Subtarget->hasV6Ops()) 868 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 869 870 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 871 : Subtarget->hasDivideInARMMode(); 872 if (!hasDivide) { 873 // These are expanded into libcalls if the cpu doesn't have HW divider. 874 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 875 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 876 } 877 878 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 879 setOperationAction(ISD::SDIV, MVT::i32, Custom); 880 setOperationAction(ISD::UDIV, MVT::i32, Custom); 881 882 setOperationAction(ISD::SDIV, MVT::i64, Custom); 883 setOperationAction(ISD::UDIV, MVT::i64, Custom); 884 } 885 886 setOperationAction(ISD::SREM, MVT::i32, Expand); 887 setOperationAction(ISD::UREM, MVT::i32, Expand); 888 889 // Register based DivRem for AEABI (RTABI 4.2) 890 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 891 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 892 Subtarget->isTargetWindows()) { 893 setOperationAction(ISD::SREM, MVT::i64, Custom); 894 setOperationAction(ISD::UREM, MVT::i64, Custom); 895 HasStandaloneRem = false; 896 897 if (Subtarget->isTargetWindows()) { 898 const struct { 899 const RTLIB::Libcall Op; 900 const char * const Name; 901 const CallingConv::ID CC; 902 } LibraryCalls[] = { 903 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 904 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 905 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 906 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 907 908 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 909 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 910 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 911 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 912 }; 913 914 for (const auto &LC : LibraryCalls) { 915 setLibcallName(LC.Op, LC.Name); 916 setLibcallCallingConv(LC.Op, LC.CC); 917 } 918 } else { 919 const struct { 920 const RTLIB::Libcall Op; 921 const char * const Name; 922 const CallingConv::ID CC; 923 } LibraryCalls[] = { 924 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 925 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 926 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 927 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 928 929 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 930 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 931 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 932 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 933 }; 934 935 for (const auto &LC : LibraryCalls) { 936 setLibcallName(LC.Op, LC.Name); 937 setLibcallCallingConv(LC.Op, LC.CC); 938 } 939 } 940 941 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 942 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 943 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 944 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 945 } else { 946 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 947 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 948 } 949 950 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 951 for (auto &VT : {MVT::f32, MVT::f64}) 952 setOperationAction(ISD::FPOWI, VT, Custom); 953 954 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 955 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 956 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 957 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 958 959 setOperationAction(ISD::TRAP, MVT::Other, Legal); 960 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 961 962 // Use the default implementation. 963 setOperationAction(ISD::VASTART, MVT::Other, Custom); 964 setOperationAction(ISD::VAARG, MVT::Other, Expand); 965 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 966 setOperationAction(ISD::VAEND, MVT::Other, Expand); 967 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 968 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 969 970 if (Subtarget->isTargetWindows()) 971 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 972 else 973 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 974 975 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 976 // the default expansion. 977 InsertFencesForAtomic = false; 978 if (Subtarget->hasAnyDataBarrier() && 979 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 980 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 981 // to ldrex/strex loops already. 982 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 983 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 984 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 985 986 // On v8, we have particularly efficient implementations of atomic fences 987 // if they can be combined with nearby atomic loads and stores. 988 if (!Subtarget->hasAcquireRelease() || 989 getTargetMachine().getOptLevel() == 0) { 990 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 991 InsertFencesForAtomic = true; 992 } 993 } else { 994 // If there's anything we can use as a barrier, go through custom lowering 995 // for ATOMIC_FENCE. 996 // If target has DMB in thumb, Fences can be inserted. 997 if (Subtarget->hasDataBarrier()) 998 InsertFencesForAtomic = true; 999 1000 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1001 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1002 1003 // Set them all for expansion, which will force libcalls. 1004 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1005 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1006 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1007 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1008 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1009 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1010 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1011 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1012 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1013 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1014 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1015 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1016 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1017 // Unordered/Monotonic case. 1018 if (!InsertFencesForAtomic) { 1019 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1020 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1021 } 1022 } 1023 1024 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1025 1026 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1027 if (!Subtarget->hasV6Ops()) { 1028 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1029 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1030 } 1031 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1032 1033 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1034 !Subtarget->isThumb1Only()) { 1035 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1036 // iff target supports vfp2. 1037 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1038 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1039 } 1040 1041 // We want to custom lower some of our intrinsics. 1042 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1043 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1044 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1045 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1046 if (Subtarget->useSjLjEH()) 1047 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1048 1049 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1050 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1051 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1052 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1053 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1054 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1055 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1056 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1057 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1058 if (Subtarget->hasFullFP16()) { 1059 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1060 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1061 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1062 } 1063 1064 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1065 1066 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1067 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1068 if (Subtarget->hasFullFP16()) 1069 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1070 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1071 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1072 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1073 1074 // We don't support sin/cos/fmod/copysign/pow 1075 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1076 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1077 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1078 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1079 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1080 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1081 setOperationAction(ISD::FREM, MVT::f64, Expand); 1082 setOperationAction(ISD::FREM, MVT::f32, Expand); 1083 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1084 !Subtarget->isThumb1Only()) { 1085 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1086 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1087 } 1088 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1089 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1090 1091 if (!Subtarget->hasVFP4Base()) { 1092 setOperationAction(ISD::FMA, MVT::f64, Expand); 1093 setOperationAction(ISD::FMA, MVT::f32, Expand); 1094 } 1095 1096 // Various VFP goodness 1097 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1098 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1099 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1100 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1101 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1102 } 1103 1104 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1105 if (!Subtarget->hasFP16()) { 1106 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1107 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1108 } 1109 } 1110 1111 // Use __sincos_stret if available. 1112 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1113 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1114 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1115 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1116 } 1117 1118 // FP-ARMv8 implements a lot of rounding-like FP operations. 1119 if (Subtarget->hasFPARMv8Base()) { 1120 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1121 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1122 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1123 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1124 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1125 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1126 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1127 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1128 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1129 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1130 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1131 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1132 1133 if (Subtarget->hasFP64()) { 1134 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1135 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1136 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1137 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1138 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1139 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1140 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1141 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1142 } 1143 } 1144 1145 // FP16 often need to be promoted to call lib functions 1146 if (Subtarget->hasFullFP16()) { 1147 setOperationAction(ISD::FREM, MVT::f16, Promote); 1148 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1149 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1150 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1151 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1152 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1153 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1154 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1155 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1156 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1157 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1158 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1159 1160 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1161 } 1162 1163 if (Subtarget->hasNEON()) { 1164 // vmin and vmax aren't available in a scalar form, so we use 1165 // a NEON instruction with an undef lane instead. 1166 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1167 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1168 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1169 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1170 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1171 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1172 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1173 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1174 1175 if (Subtarget->hasFullFP16()) { 1176 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1177 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1178 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1179 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1180 1181 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1182 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1183 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1184 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1185 } 1186 } 1187 1188 // We have target-specific dag combine patterns for the following nodes: 1189 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1190 setTargetDAGCombine(ISD::ADD); 1191 setTargetDAGCombine(ISD::SUB); 1192 setTargetDAGCombine(ISD::MUL); 1193 setTargetDAGCombine(ISD::AND); 1194 setTargetDAGCombine(ISD::OR); 1195 setTargetDAGCombine(ISD::XOR); 1196 1197 if (Subtarget->hasV6Ops()) 1198 setTargetDAGCombine(ISD::SRL); 1199 if (Subtarget->isThumb1Only()) 1200 setTargetDAGCombine(ISD::SHL); 1201 1202 setStackPointerRegisterToSaveRestore(ARM::SP); 1203 1204 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1205 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1206 setSchedulingPreference(Sched::RegPressure); 1207 else 1208 setSchedulingPreference(Sched::Hybrid); 1209 1210 //// temporary - rewrite interface to use type 1211 MaxStoresPerMemset = 8; 1212 MaxStoresPerMemsetOptSize = 4; 1213 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1214 MaxStoresPerMemcpyOptSize = 2; 1215 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1216 MaxStoresPerMemmoveOptSize = 2; 1217 1218 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1219 // are at least 4 bytes aligned. 1220 setMinStackArgumentAlignment(4); 1221 1222 // Prefer likely predicted branches to selects on out-of-order cores. 1223 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1224 1225 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment()); 1226 1227 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1228 1229 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1230 setTargetDAGCombine(ISD::ABS); 1231 } 1232 1233 bool ARMTargetLowering::useSoftFloat() const { 1234 return Subtarget->useSoftFloat(); 1235 } 1236 1237 // FIXME: It might make sense to define the representative register class as the 1238 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1239 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1240 // SPR's representative would be DPR_VFP2. This should work well if register 1241 // pressure tracking were modified such that a register use would increment the 1242 // pressure of the register class's representative and all of it's super 1243 // classes' representatives transitively. We have not implemented this because 1244 // of the difficulty prior to coalescing of modeling operand register classes 1245 // due to the common occurrence of cross class copies and subregister insertions 1246 // and extractions. 1247 std::pair<const TargetRegisterClass *, uint8_t> 1248 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1249 MVT VT) const { 1250 const TargetRegisterClass *RRC = nullptr; 1251 uint8_t Cost = 1; 1252 switch (VT.SimpleTy) { 1253 default: 1254 return TargetLowering::findRepresentativeClass(TRI, VT); 1255 // Use DPR as representative register class for all floating point 1256 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1257 // the cost is 1 for both f32 and f64. 1258 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1259 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1260 RRC = &ARM::DPRRegClass; 1261 // When NEON is used for SP, only half of the register file is available 1262 // because operations that define both SP and DP results will be constrained 1263 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1264 // coalescing by double-counting the SP regs. See the FIXME above. 1265 if (Subtarget->useNEONForSinglePrecisionFP()) 1266 Cost = 2; 1267 break; 1268 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1269 case MVT::v4f32: case MVT::v2f64: 1270 RRC = &ARM::DPRRegClass; 1271 Cost = 2; 1272 break; 1273 case MVT::v4i64: 1274 RRC = &ARM::DPRRegClass; 1275 Cost = 4; 1276 break; 1277 case MVT::v8i64: 1278 RRC = &ARM::DPRRegClass; 1279 Cost = 8; 1280 break; 1281 } 1282 return std::make_pair(RRC, Cost); 1283 } 1284 1285 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1286 switch ((ARMISD::NodeType)Opcode) { 1287 case ARMISD::FIRST_NUMBER: break; 1288 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1289 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1290 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1291 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1292 case ARMISD::CALL: return "ARMISD::CALL"; 1293 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1294 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1295 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1296 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1297 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1298 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1299 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1300 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1301 case ARMISD::CMP: return "ARMISD::CMP"; 1302 case ARMISD::CMN: return "ARMISD::CMN"; 1303 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1304 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1305 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1306 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1307 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1308 1309 case ARMISD::CMOV: return "ARMISD::CMOV"; 1310 case ARMISD::SUBS: return "ARMISD::SUBS"; 1311 1312 case ARMISD::SSAT: return "ARMISD::SSAT"; 1313 case ARMISD::USAT: return "ARMISD::USAT"; 1314 1315 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1316 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1317 case ARMISD::RRX: return "ARMISD::RRX"; 1318 1319 case ARMISD::ADDC: return "ARMISD::ADDC"; 1320 case ARMISD::ADDE: return "ARMISD::ADDE"; 1321 case ARMISD::SUBC: return "ARMISD::SUBC"; 1322 case ARMISD::SUBE: return "ARMISD::SUBE"; 1323 1324 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1325 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1326 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1327 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1328 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1329 1330 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1331 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1332 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1333 1334 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1335 1336 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1337 1338 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1339 1340 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1341 1342 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1343 1344 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1345 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1346 1347 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1348 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1349 case ARMISD::VCGE: return "ARMISD::VCGE"; 1350 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1351 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1352 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1353 case ARMISD::VCGT: return "ARMISD::VCGT"; 1354 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1355 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1356 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1357 case ARMISD::VTST: return "ARMISD::VTST"; 1358 1359 case ARMISD::VSHL: return "ARMISD::VSHL"; 1360 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1361 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1362 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1363 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1364 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1365 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1366 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1367 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1368 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1369 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1370 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1371 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1372 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1373 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1374 case ARMISD::VSLI: return "ARMISD::VSLI"; 1375 case ARMISD::VSRI: return "ARMISD::VSRI"; 1376 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1377 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1378 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1379 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1380 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1381 case ARMISD::VDUP: return "ARMISD::VDUP"; 1382 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1383 case ARMISD::VEXT: return "ARMISD::VEXT"; 1384 case ARMISD::VREV64: return "ARMISD::VREV64"; 1385 case ARMISD::VREV32: return "ARMISD::VREV32"; 1386 case ARMISD::VREV16: return "ARMISD::VREV16"; 1387 case ARMISD::VZIP: return "ARMISD::VZIP"; 1388 case ARMISD::VUZP: return "ARMISD::VUZP"; 1389 case ARMISD::VTRN: return "ARMISD::VTRN"; 1390 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1391 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1392 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1393 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1394 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1395 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1396 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1397 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1398 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1399 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1400 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1401 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1402 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1403 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1404 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1405 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1406 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1407 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1408 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1409 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1410 case ARMISD::BFI: return "ARMISD::BFI"; 1411 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1412 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1413 case ARMISD::VBSL: return "ARMISD::VBSL"; 1414 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1415 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1416 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1417 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1418 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1419 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1420 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1421 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1422 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1423 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1424 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1425 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1426 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1427 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1428 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1429 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1430 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1431 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1432 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1433 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1434 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1435 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1436 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1437 } 1438 return nullptr; 1439 } 1440 1441 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1442 EVT VT) const { 1443 if (!VT.isVector()) 1444 return getPointerTy(DL); 1445 return VT.changeVectorElementTypeToInteger(); 1446 } 1447 1448 /// getRegClassFor - Return the register class that should be used for the 1449 /// specified value type. 1450 const TargetRegisterClass * 1451 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1452 (void)isDivergent; 1453 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1454 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1455 // load / store 4 to 8 consecutive D registers. 1456 if (Subtarget->hasNEON()) { 1457 if (VT == MVT::v4i64) 1458 return &ARM::QQPRRegClass; 1459 if (VT == MVT::v8i64) 1460 return &ARM::QQQQPRRegClass; 1461 } 1462 return TargetLowering::getRegClassFor(VT); 1463 } 1464 1465 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1466 // source/dest is aligned and the copy size is large enough. We therefore want 1467 // to align such objects passed to memory intrinsics. 1468 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1469 unsigned &PrefAlign) const { 1470 if (!isa<MemIntrinsic>(CI)) 1471 return false; 1472 MinSize = 8; 1473 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1474 // cycle faster than 4-byte aligned LDM. 1475 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1476 return true; 1477 } 1478 1479 // Create a fast isel object. 1480 FastISel * 1481 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1482 const TargetLibraryInfo *libInfo) const { 1483 return ARM::createFastISel(funcInfo, libInfo); 1484 } 1485 1486 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1487 unsigned NumVals = N->getNumValues(); 1488 if (!NumVals) 1489 return Sched::RegPressure; 1490 1491 for (unsigned i = 0; i != NumVals; ++i) { 1492 EVT VT = N->getValueType(i); 1493 if (VT == MVT::Glue || VT == MVT::Other) 1494 continue; 1495 if (VT.isFloatingPoint() || VT.isVector()) 1496 return Sched::ILP; 1497 } 1498 1499 if (!N->isMachineOpcode()) 1500 return Sched::RegPressure; 1501 1502 // Load are scheduled for latency even if there instruction itinerary 1503 // is not available. 1504 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1505 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1506 1507 if (MCID.getNumDefs() == 0) 1508 return Sched::RegPressure; 1509 if (!Itins->isEmpty() && 1510 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1511 return Sched::ILP; 1512 1513 return Sched::RegPressure; 1514 } 1515 1516 //===----------------------------------------------------------------------===// 1517 // Lowering Code 1518 //===----------------------------------------------------------------------===// 1519 1520 static bool isSRL16(const SDValue &Op) { 1521 if (Op.getOpcode() != ISD::SRL) 1522 return false; 1523 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1524 return Const->getZExtValue() == 16; 1525 return false; 1526 } 1527 1528 static bool isSRA16(const SDValue &Op) { 1529 if (Op.getOpcode() != ISD::SRA) 1530 return false; 1531 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1532 return Const->getZExtValue() == 16; 1533 return false; 1534 } 1535 1536 static bool isSHL16(const SDValue &Op) { 1537 if (Op.getOpcode() != ISD::SHL) 1538 return false; 1539 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1540 return Const->getZExtValue() == 16; 1541 return false; 1542 } 1543 1544 // Check for a signed 16-bit value. We special case SRA because it makes it 1545 // more simple when also looking for SRAs that aren't sign extending a 1546 // smaller value. Without the check, we'd need to take extra care with 1547 // checking order for some operations. 1548 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1549 if (isSRA16(Op)) 1550 return isSHL16(Op.getOperand(0)); 1551 return DAG.ComputeNumSignBits(Op) == 17; 1552 } 1553 1554 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1555 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1556 switch (CC) { 1557 default: llvm_unreachable("Unknown condition code!"); 1558 case ISD::SETNE: return ARMCC::NE; 1559 case ISD::SETEQ: return ARMCC::EQ; 1560 case ISD::SETGT: return ARMCC::GT; 1561 case ISD::SETGE: return ARMCC::GE; 1562 case ISD::SETLT: return ARMCC::LT; 1563 case ISD::SETLE: return ARMCC::LE; 1564 case ISD::SETUGT: return ARMCC::HI; 1565 case ISD::SETUGE: return ARMCC::HS; 1566 case ISD::SETULT: return ARMCC::LO; 1567 case ISD::SETULE: return ARMCC::LS; 1568 } 1569 } 1570 1571 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1572 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1573 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1574 CondCode2 = ARMCC::AL; 1575 InvalidOnQNaN = true; 1576 switch (CC) { 1577 default: llvm_unreachable("Unknown FP condition!"); 1578 case ISD::SETEQ: 1579 case ISD::SETOEQ: 1580 CondCode = ARMCC::EQ; 1581 InvalidOnQNaN = false; 1582 break; 1583 case ISD::SETGT: 1584 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1585 case ISD::SETGE: 1586 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1587 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1588 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1589 case ISD::SETONE: 1590 CondCode = ARMCC::MI; 1591 CondCode2 = ARMCC::GT; 1592 InvalidOnQNaN = false; 1593 break; 1594 case ISD::SETO: CondCode = ARMCC::VC; break; 1595 case ISD::SETUO: CondCode = ARMCC::VS; break; 1596 case ISD::SETUEQ: 1597 CondCode = ARMCC::EQ; 1598 CondCode2 = ARMCC::VS; 1599 InvalidOnQNaN = false; 1600 break; 1601 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1602 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1603 case ISD::SETLT: 1604 case ISD::SETULT: CondCode = ARMCC::LT; break; 1605 case ISD::SETLE: 1606 case ISD::SETULE: CondCode = ARMCC::LE; break; 1607 case ISD::SETNE: 1608 case ISD::SETUNE: 1609 CondCode = ARMCC::NE; 1610 InvalidOnQNaN = false; 1611 break; 1612 } 1613 } 1614 1615 //===----------------------------------------------------------------------===// 1616 // Calling Convention Implementation 1617 //===----------------------------------------------------------------------===// 1618 1619 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1620 /// account presence of floating point hardware and calling convention 1621 /// limitations, such as support for variadic functions. 1622 CallingConv::ID 1623 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1624 bool isVarArg) const { 1625 switch (CC) { 1626 default: 1627 report_fatal_error("Unsupported calling convention"); 1628 case CallingConv::ARM_AAPCS: 1629 case CallingConv::ARM_APCS: 1630 case CallingConv::GHC: 1631 return CC; 1632 case CallingConv::PreserveMost: 1633 return CallingConv::PreserveMost; 1634 case CallingConv::ARM_AAPCS_VFP: 1635 case CallingConv::Swift: 1636 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1637 case CallingConv::C: 1638 if (!Subtarget->isAAPCS_ABI()) 1639 return CallingConv::ARM_APCS; 1640 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1641 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1642 !isVarArg) 1643 return CallingConv::ARM_AAPCS_VFP; 1644 else 1645 return CallingConv::ARM_AAPCS; 1646 case CallingConv::Fast: 1647 case CallingConv::CXX_FAST_TLS: 1648 if (!Subtarget->isAAPCS_ABI()) { 1649 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 1650 return CallingConv::Fast; 1651 return CallingConv::ARM_APCS; 1652 } else if (Subtarget->hasVFP2Base() && 1653 !Subtarget->isThumb1Only() && !isVarArg) 1654 return CallingConv::ARM_AAPCS_VFP; 1655 else 1656 return CallingConv::ARM_AAPCS; 1657 } 1658 } 1659 1660 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1661 bool isVarArg) const { 1662 return CCAssignFnForNode(CC, false, isVarArg); 1663 } 1664 1665 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1666 bool isVarArg) const { 1667 return CCAssignFnForNode(CC, true, isVarArg); 1668 } 1669 1670 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1671 /// CallingConvention. 1672 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1673 bool Return, 1674 bool isVarArg) const { 1675 switch (getEffectiveCallingConv(CC, isVarArg)) { 1676 default: 1677 report_fatal_error("Unsupported calling convention"); 1678 case CallingConv::ARM_APCS: 1679 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1680 case CallingConv::ARM_AAPCS: 1681 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1682 case CallingConv::ARM_AAPCS_VFP: 1683 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1684 case CallingConv::Fast: 1685 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1686 case CallingConv::GHC: 1687 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1688 case CallingConv::PreserveMost: 1689 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1690 } 1691 } 1692 1693 /// LowerCallResult - Lower the result values of a call into the 1694 /// appropriate copies out of appropriate physical registers. 1695 SDValue ARMTargetLowering::LowerCallResult( 1696 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1697 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1698 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1699 SDValue ThisVal) const { 1700 // Assign locations to each value returned by this call. 1701 SmallVector<CCValAssign, 16> RVLocs; 1702 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1703 *DAG.getContext()); 1704 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1705 1706 // Copy all of the result registers out of their specified physreg. 1707 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1708 CCValAssign VA = RVLocs[i]; 1709 1710 // Pass 'this' value directly from the argument to return value, to avoid 1711 // reg unit interference 1712 if (i == 0 && isThisReturn) { 1713 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1714 "unexpected return calling convention register assignment"); 1715 InVals.push_back(ThisVal); 1716 continue; 1717 } 1718 1719 SDValue Val; 1720 if (VA.needsCustom()) { 1721 // Handle f64 or half of a v2f64. 1722 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1723 InFlag); 1724 Chain = Lo.getValue(1); 1725 InFlag = Lo.getValue(2); 1726 VA = RVLocs[++i]; // skip ahead to next loc 1727 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1728 InFlag); 1729 Chain = Hi.getValue(1); 1730 InFlag = Hi.getValue(2); 1731 if (!Subtarget->isLittle()) 1732 std::swap (Lo, Hi); 1733 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1734 1735 if (VA.getLocVT() == MVT::v2f64) { 1736 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1737 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1738 DAG.getConstant(0, dl, MVT::i32)); 1739 1740 VA = RVLocs[++i]; // skip ahead to next loc 1741 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1742 Chain = Lo.getValue(1); 1743 InFlag = Lo.getValue(2); 1744 VA = RVLocs[++i]; // skip ahead to next loc 1745 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1746 Chain = Hi.getValue(1); 1747 InFlag = Hi.getValue(2); 1748 if (!Subtarget->isLittle()) 1749 std::swap (Lo, Hi); 1750 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1751 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1752 DAG.getConstant(1, dl, MVT::i32)); 1753 } 1754 } else { 1755 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1756 InFlag); 1757 Chain = Val.getValue(1); 1758 InFlag = Val.getValue(2); 1759 } 1760 1761 switch (VA.getLocInfo()) { 1762 default: llvm_unreachable("Unknown loc info!"); 1763 case CCValAssign::Full: break; 1764 case CCValAssign::BCvt: 1765 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1766 break; 1767 } 1768 1769 InVals.push_back(Val); 1770 } 1771 1772 return Chain; 1773 } 1774 1775 /// LowerMemOpCallTo - Store the argument to the stack. 1776 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1777 SDValue Arg, const SDLoc &dl, 1778 SelectionDAG &DAG, 1779 const CCValAssign &VA, 1780 ISD::ArgFlagsTy Flags) const { 1781 unsigned LocMemOffset = VA.getLocMemOffset(); 1782 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1783 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1784 StackPtr, PtrOff); 1785 return DAG.getStore( 1786 Chain, dl, Arg, PtrOff, 1787 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1788 } 1789 1790 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1791 SDValue Chain, SDValue &Arg, 1792 RegsToPassVector &RegsToPass, 1793 CCValAssign &VA, CCValAssign &NextVA, 1794 SDValue &StackPtr, 1795 SmallVectorImpl<SDValue> &MemOpChains, 1796 ISD::ArgFlagsTy Flags) const { 1797 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1798 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1799 unsigned id = Subtarget->isLittle() ? 0 : 1; 1800 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1801 1802 if (NextVA.isRegLoc()) 1803 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1804 else { 1805 assert(NextVA.isMemLoc()); 1806 if (!StackPtr.getNode()) 1807 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1808 getPointerTy(DAG.getDataLayout())); 1809 1810 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1811 dl, DAG, NextVA, 1812 Flags)); 1813 } 1814 } 1815 1816 /// LowerCall - Lowering a call into a callseq_start <- 1817 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1818 /// nodes. 1819 SDValue 1820 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1821 SmallVectorImpl<SDValue> &InVals) const { 1822 SelectionDAG &DAG = CLI.DAG; 1823 SDLoc &dl = CLI.DL; 1824 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1825 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1826 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1827 SDValue Chain = CLI.Chain; 1828 SDValue Callee = CLI.Callee; 1829 bool &isTailCall = CLI.IsTailCall; 1830 CallingConv::ID CallConv = CLI.CallConv; 1831 bool doesNotRet = CLI.DoesNotReturn; 1832 bool isVarArg = CLI.IsVarArg; 1833 1834 MachineFunction &MF = DAG.getMachineFunction(); 1835 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1836 bool isThisReturn = false; 1837 bool isSibCall = false; 1838 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1839 1840 // Disable tail calls if they're not supported. 1841 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1842 isTailCall = false; 1843 1844 if (isTailCall) { 1845 // Check if it's really possible to do a tail call. 1846 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1847 isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(), 1848 Outs, OutVals, Ins, DAG); 1849 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1850 report_fatal_error("failed to perform tail call elimination on a call " 1851 "site marked musttail"); 1852 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1853 // detected sibcalls. 1854 if (isTailCall) { 1855 ++NumTailCalls; 1856 isSibCall = true; 1857 } 1858 } 1859 1860 // Analyze operands of the call, assigning locations to each operand. 1861 SmallVector<CCValAssign, 16> ArgLocs; 1862 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1863 *DAG.getContext()); 1864 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1865 1866 // Get a count of how many bytes are to be pushed on the stack. 1867 unsigned NumBytes = CCInfo.getNextStackOffset(); 1868 1869 // For tail calls, memory operands are available in our caller's stack. 1870 if (isSibCall) 1871 NumBytes = 0; 1872 1873 // Adjust the stack pointer for the new arguments... 1874 // These operations are automatically eliminated by the prolog/epilog pass 1875 if (!isSibCall) 1876 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1877 1878 SDValue StackPtr = 1879 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1880 1881 RegsToPassVector RegsToPass; 1882 SmallVector<SDValue, 8> MemOpChains; 1883 1884 // Walk the register/memloc assignments, inserting copies/loads. In the case 1885 // of tail call optimization, arguments are handled later. 1886 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1887 i != e; 1888 ++i, ++realArgIdx) { 1889 CCValAssign &VA = ArgLocs[i]; 1890 SDValue Arg = OutVals[realArgIdx]; 1891 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1892 bool isByVal = Flags.isByVal(); 1893 1894 // Promote the value if needed. 1895 switch (VA.getLocInfo()) { 1896 default: llvm_unreachable("Unknown loc info!"); 1897 case CCValAssign::Full: break; 1898 case CCValAssign::SExt: 1899 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1900 break; 1901 case CCValAssign::ZExt: 1902 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1903 break; 1904 case CCValAssign::AExt: 1905 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1906 break; 1907 case CCValAssign::BCvt: 1908 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1909 break; 1910 } 1911 1912 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1913 if (VA.needsCustom()) { 1914 if (VA.getLocVT() == MVT::v2f64) { 1915 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1916 DAG.getConstant(0, dl, MVT::i32)); 1917 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1918 DAG.getConstant(1, dl, MVT::i32)); 1919 1920 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1921 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1922 1923 VA = ArgLocs[++i]; // skip ahead to next loc 1924 if (VA.isRegLoc()) { 1925 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1926 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1927 } else { 1928 assert(VA.isMemLoc()); 1929 1930 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1931 dl, DAG, VA, Flags)); 1932 } 1933 } else { 1934 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1935 StackPtr, MemOpChains, Flags); 1936 } 1937 } else if (VA.isRegLoc()) { 1938 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1939 Outs[0].VT == MVT::i32) { 1940 assert(VA.getLocVT() == MVT::i32 && 1941 "unexpected calling convention register assignment"); 1942 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1943 "unexpected use of 'returned'"); 1944 isThisReturn = true; 1945 } 1946 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1947 } else if (isByVal) { 1948 assert(VA.isMemLoc()); 1949 unsigned offset = 0; 1950 1951 // True if this byval aggregate will be split between registers 1952 // and memory. 1953 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1954 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1955 1956 if (CurByValIdx < ByValArgsCount) { 1957 1958 unsigned RegBegin, RegEnd; 1959 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1960 1961 EVT PtrVT = 1962 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1963 unsigned int i, j; 1964 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1965 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1966 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1967 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1968 MachinePointerInfo(), 1969 DAG.InferPtrAlignment(AddArg)); 1970 MemOpChains.push_back(Load.getValue(1)); 1971 RegsToPass.push_back(std::make_pair(j, Load)); 1972 } 1973 1974 // If parameter size outsides register area, "offset" value 1975 // helps us to calculate stack slot for remained part properly. 1976 offset = RegEnd - RegBegin; 1977 1978 CCInfo.nextInRegsParam(); 1979 } 1980 1981 if (Flags.getByValSize() > 4*offset) { 1982 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1983 unsigned LocMemOffset = VA.getLocMemOffset(); 1984 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1985 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1986 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1987 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1988 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1989 MVT::i32); 1990 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1991 MVT::i32); 1992 1993 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1994 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1995 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1996 Ops)); 1997 } 1998 } else if (!isSibCall) { 1999 assert(VA.isMemLoc()); 2000 2001 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2002 dl, DAG, VA, Flags)); 2003 } 2004 } 2005 2006 if (!MemOpChains.empty()) 2007 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2008 2009 // Build a sequence of copy-to-reg nodes chained together with token chain 2010 // and flag operands which copy the outgoing args into the appropriate regs. 2011 SDValue InFlag; 2012 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2013 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2014 RegsToPass[i].second, InFlag); 2015 InFlag = Chain.getValue(1); 2016 } 2017 2018 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2019 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2020 // node so that legalize doesn't hack it. 2021 bool isDirect = false; 2022 2023 const TargetMachine &TM = getTargetMachine(); 2024 const Module *Mod = MF.getFunction().getParent(); 2025 const GlobalValue *GV = nullptr; 2026 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2027 GV = G->getGlobal(); 2028 bool isStub = 2029 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2030 2031 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2032 bool isLocalARMFunc = false; 2033 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2034 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2035 2036 if (Subtarget->genLongCalls()) { 2037 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2038 "long-calls codegen is not position independent!"); 2039 // Handle a global address or an external symbol. If it's not one of 2040 // those, the target's already in a register, so we don't need to do 2041 // anything extra. 2042 if (isa<GlobalAddressSDNode>(Callee)) { 2043 // Create a constant pool entry for the callee address 2044 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2045 ARMConstantPoolValue *CPV = 2046 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2047 2048 // Get the address of the callee into a register 2049 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2050 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2051 Callee = DAG.getLoad( 2052 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2053 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2054 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2055 const char *Sym = S->getSymbol(); 2056 2057 // Create a constant pool entry for the callee address 2058 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2059 ARMConstantPoolValue *CPV = 2060 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2061 ARMPCLabelIndex, 0); 2062 // Get the address of the callee into a register 2063 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2064 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2065 Callee = DAG.getLoad( 2066 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2067 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2068 } 2069 } else if (isa<GlobalAddressSDNode>(Callee)) { 2070 // If we're optimizing for minimum size and the function is called three or 2071 // more times in this block, we can improve codesize by calling indirectly 2072 // as BLXr has a 16-bit encoding. 2073 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2074 auto *BB = CLI.CS.getParent(); 2075 bool PreferIndirect = 2076 Subtarget->isThumb() && Subtarget->hasMinSize() && 2077 count_if(GV->users(), [&BB](const User *U) { 2078 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2079 }) > 2; 2080 2081 if (!PreferIndirect) { 2082 isDirect = true; 2083 bool isDef = GV->isStrongDefinitionForLinker(); 2084 2085 // ARM call to a local ARM function is predicable. 2086 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2087 // tBX takes a register source operand. 2088 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2089 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2090 Callee = DAG.getNode( 2091 ARMISD::WrapperPIC, dl, PtrVt, 2092 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2093 Callee = DAG.getLoad( 2094 PtrVt, dl, DAG.getEntryNode(), Callee, 2095 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2096 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2097 MachineMemOperand::MOInvariant); 2098 } else if (Subtarget->isTargetCOFF()) { 2099 assert(Subtarget->isTargetWindows() && 2100 "Windows is the only supported COFF target"); 2101 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2102 ? ARMII::MO_DLLIMPORT 2103 : ARMII::MO_NO_FLAG; 2104 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2105 TargetFlags); 2106 if (GV->hasDLLImportStorageClass()) 2107 Callee = 2108 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2109 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2110 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2111 } else { 2112 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2113 } 2114 } 2115 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2116 isDirect = true; 2117 // tBX takes a register source operand. 2118 const char *Sym = S->getSymbol(); 2119 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2120 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2121 ARMConstantPoolValue *CPV = 2122 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2123 ARMPCLabelIndex, 4); 2124 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2125 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2126 Callee = DAG.getLoad( 2127 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2128 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2129 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2130 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2131 } else { 2132 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2133 } 2134 } 2135 2136 // FIXME: handle tail calls differently. 2137 unsigned CallOpc; 2138 if (Subtarget->isThumb()) { 2139 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2140 CallOpc = ARMISD::CALL_NOLINK; 2141 else 2142 CallOpc = ARMISD::CALL; 2143 } else { 2144 if (!isDirect && !Subtarget->hasV5TOps()) 2145 CallOpc = ARMISD::CALL_NOLINK; 2146 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2147 // Emit regular call when code size is the priority 2148 !Subtarget->hasMinSize()) 2149 // "mov lr, pc; b _foo" to avoid confusing the RSP 2150 CallOpc = ARMISD::CALL_NOLINK; 2151 else 2152 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2153 } 2154 2155 std::vector<SDValue> Ops; 2156 Ops.push_back(Chain); 2157 Ops.push_back(Callee); 2158 2159 // Add argument registers to the end of the list so that they are known live 2160 // into the call. 2161 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2162 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2163 RegsToPass[i].second.getValueType())); 2164 2165 // Add a register mask operand representing the call-preserved registers. 2166 if (!isTailCall) { 2167 const uint32_t *Mask; 2168 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2169 if (isThisReturn) { 2170 // For 'this' returns, use the R0-preserving mask if applicable 2171 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2172 if (!Mask) { 2173 // Set isThisReturn to false if the calling convention is not one that 2174 // allows 'returned' to be modeled in this way, so LowerCallResult does 2175 // not try to pass 'this' straight through 2176 isThisReturn = false; 2177 Mask = ARI->getCallPreservedMask(MF, CallConv); 2178 } 2179 } else 2180 Mask = ARI->getCallPreservedMask(MF, CallConv); 2181 2182 assert(Mask && "Missing call preserved mask for calling convention"); 2183 Ops.push_back(DAG.getRegisterMask(Mask)); 2184 } 2185 2186 if (InFlag.getNode()) 2187 Ops.push_back(InFlag); 2188 2189 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2190 if (isTailCall) { 2191 MF.getFrameInfo().setHasTailCall(); 2192 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2193 } 2194 2195 // Returns a chain and a flag for retval copy to use. 2196 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2197 InFlag = Chain.getValue(1); 2198 2199 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2200 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2201 if (!Ins.empty()) 2202 InFlag = Chain.getValue(1); 2203 2204 // Handle result values, copying them out of physregs into vregs that we 2205 // return. 2206 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2207 InVals, isThisReturn, 2208 isThisReturn ? OutVals[0] : SDValue()); 2209 } 2210 2211 /// HandleByVal - Every parameter *after* a byval parameter is passed 2212 /// on the stack. Remember the next parameter register to allocate, 2213 /// and then confiscate the rest of the parameter registers to insure 2214 /// this. 2215 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2216 unsigned Align) const { 2217 // Byval (as with any stack) slots are always at least 4 byte aligned. 2218 Align = std::max(Align, 4U); 2219 2220 unsigned Reg = State->AllocateReg(GPRArgRegs); 2221 if (!Reg) 2222 return; 2223 2224 unsigned AlignInRegs = Align / 4; 2225 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2226 for (unsigned i = 0; i < Waste; ++i) 2227 Reg = State->AllocateReg(GPRArgRegs); 2228 2229 if (!Reg) 2230 return; 2231 2232 unsigned Excess = 4 * (ARM::R4 - Reg); 2233 2234 // Special case when NSAA != SP and parameter size greater than size of 2235 // all remained GPR regs. In that case we can't split parameter, we must 2236 // send it to stack. We also must set NCRN to R4, so waste all 2237 // remained registers. 2238 const unsigned NSAAOffset = State->getNextStackOffset(); 2239 if (NSAAOffset != 0 && Size > Excess) { 2240 while (State->AllocateReg(GPRArgRegs)) 2241 ; 2242 return; 2243 } 2244 2245 // First register for byval parameter is the first register that wasn't 2246 // allocated before this method call, so it would be "reg". 2247 // If parameter is small enough to be saved in range [reg, r4), then 2248 // the end (first after last) register would be reg + param-size-in-regs, 2249 // else parameter would be splitted between registers and stack, 2250 // end register would be r4 in this case. 2251 unsigned ByValRegBegin = Reg; 2252 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2253 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2254 // Note, first register is allocated in the beginning of function already, 2255 // allocate remained amount of registers we need. 2256 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2257 State->AllocateReg(GPRArgRegs); 2258 // A byval parameter that is split between registers and memory needs its 2259 // size truncated here. 2260 // In the case where the entire structure fits in registers, we set the 2261 // size in memory to zero. 2262 Size = std::max<int>(Size - Excess, 0); 2263 } 2264 2265 /// MatchingStackOffset - Return true if the given stack call argument is 2266 /// already available in the same position (relatively) of the caller's 2267 /// incoming argument stack. 2268 static 2269 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2270 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2271 const TargetInstrInfo *TII) { 2272 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2273 int FI = std::numeric_limits<int>::max(); 2274 if (Arg.getOpcode() == ISD::CopyFromReg) { 2275 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2276 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2277 return false; 2278 MachineInstr *Def = MRI->getVRegDef(VR); 2279 if (!Def) 2280 return false; 2281 if (!Flags.isByVal()) { 2282 if (!TII->isLoadFromStackSlot(*Def, FI)) 2283 return false; 2284 } else { 2285 return false; 2286 } 2287 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2288 if (Flags.isByVal()) 2289 // ByVal argument is passed in as a pointer but it's now being 2290 // dereferenced. e.g. 2291 // define @foo(%struct.X* %A) { 2292 // tail call @bar(%struct.X* byval %A) 2293 // } 2294 return false; 2295 SDValue Ptr = Ld->getBasePtr(); 2296 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2297 if (!FINode) 2298 return false; 2299 FI = FINode->getIndex(); 2300 } else 2301 return false; 2302 2303 assert(FI != std::numeric_limits<int>::max()); 2304 if (!MFI.isFixedObjectIndex(FI)) 2305 return false; 2306 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2307 } 2308 2309 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2310 /// for tail call optimization. Targets which want to do tail call 2311 /// optimization should implement this function. 2312 bool 2313 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2314 CallingConv::ID CalleeCC, 2315 bool isVarArg, 2316 bool isCalleeStructRet, 2317 bool isCallerStructRet, 2318 const SmallVectorImpl<ISD::OutputArg> &Outs, 2319 const SmallVectorImpl<SDValue> &OutVals, 2320 const SmallVectorImpl<ISD::InputArg> &Ins, 2321 SelectionDAG& DAG) const { 2322 MachineFunction &MF = DAG.getMachineFunction(); 2323 const Function &CallerF = MF.getFunction(); 2324 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2325 2326 assert(Subtarget->supportsTailCall()); 2327 2328 // Tail calls to function pointers cannot be optimized for Thumb1 if the args 2329 // to the call take up r0-r3. The reason is that there are no legal registers 2330 // left to hold the pointer to the function to be called. 2331 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2332 !isa<GlobalAddressSDNode>(Callee.getNode())) 2333 return false; 2334 2335 // Look for obvious safe cases to perform tail call optimization that do not 2336 // require ABI changes. This is what gcc calls sibcall. 2337 2338 // Exception-handling functions need a special set of instructions to indicate 2339 // a return to the hardware. Tail-calling another function would probably 2340 // break this. 2341 if (CallerF.hasFnAttribute("interrupt")) 2342 return false; 2343 2344 // Also avoid sibcall optimization if either caller or callee uses struct 2345 // return semantics. 2346 if (isCalleeStructRet || isCallerStructRet) 2347 return false; 2348 2349 // Externally-defined functions with weak linkage should not be 2350 // tail-called on ARM when the OS does not support dynamic 2351 // pre-emption of symbols, as the AAELF spec requires normal calls 2352 // to undefined weak functions to be replaced with a NOP or jump to the 2353 // next instruction. The behaviour of branch instructions in this 2354 // situation (as used for tail calls) is implementation-defined, so we 2355 // cannot rely on the linker replacing the tail call with a return. 2356 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2357 const GlobalValue *GV = G->getGlobal(); 2358 const Triple &TT = getTargetMachine().getTargetTriple(); 2359 if (GV->hasExternalWeakLinkage() && 2360 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2361 return false; 2362 } 2363 2364 // Check that the call results are passed in the same way. 2365 LLVMContext &C = *DAG.getContext(); 2366 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2367 CCAssignFnForReturn(CalleeCC, isVarArg), 2368 CCAssignFnForReturn(CallerCC, isVarArg))) 2369 return false; 2370 // The callee has to preserve all registers the caller needs to preserve. 2371 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2372 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2373 if (CalleeCC != CallerCC) { 2374 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2375 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2376 return false; 2377 } 2378 2379 // If Caller's vararg or byval argument has been split between registers and 2380 // stack, do not perform tail call, since part of the argument is in caller's 2381 // local frame. 2382 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2383 if (AFI_Caller->getArgRegsSaveSize()) 2384 return false; 2385 2386 // If the callee takes no arguments then go on to check the results of the 2387 // call. 2388 if (!Outs.empty()) { 2389 // Check if stack adjustment is needed. For now, do not do this if any 2390 // argument is passed on the stack. 2391 SmallVector<CCValAssign, 16> ArgLocs; 2392 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2393 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2394 if (CCInfo.getNextStackOffset()) { 2395 // Check if the arguments are already laid out in the right way as 2396 // the caller's fixed stack objects. 2397 MachineFrameInfo &MFI = MF.getFrameInfo(); 2398 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2399 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2400 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2401 i != e; 2402 ++i, ++realArgIdx) { 2403 CCValAssign &VA = ArgLocs[i]; 2404 EVT RegVT = VA.getLocVT(); 2405 SDValue Arg = OutVals[realArgIdx]; 2406 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2407 if (VA.getLocInfo() == CCValAssign::Indirect) 2408 return false; 2409 if (VA.needsCustom()) { 2410 // f64 and vector types are split into multiple registers or 2411 // register/stack-slot combinations. The types will not match 2412 // the registers; give up on memory f64 refs until we figure 2413 // out what to do about this. 2414 if (!VA.isRegLoc()) 2415 return false; 2416 if (!ArgLocs[++i].isRegLoc()) 2417 return false; 2418 if (RegVT == MVT::v2f64) { 2419 if (!ArgLocs[++i].isRegLoc()) 2420 return false; 2421 if (!ArgLocs[++i].isRegLoc()) 2422 return false; 2423 } 2424 } else if (!VA.isRegLoc()) { 2425 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2426 MFI, MRI, TII)) 2427 return false; 2428 } 2429 } 2430 } 2431 2432 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2433 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2434 return false; 2435 } 2436 2437 return true; 2438 } 2439 2440 bool 2441 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2442 MachineFunction &MF, bool isVarArg, 2443 const SmallVectorImpl<ISD::OutputArg> &Outs, 2444 LLVMContext &Context) const { 2445 SmallVector<CCValAssign, 16> RVLocs; 2446 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2447 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2448 } 2449 2450 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2451 const SDLoc &DL, SelectionDAG &DAG) { 2452 const MachineFunction &MF = DAG.getMachineFunction(); 2453 const Function &F = MF.getFunction(); 2454 2455 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2456 2457 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2458 // version of the "preferred return address". These offsets affect the return 2459 // instruction if this is a return from PL1 without hypervisor extensions. 2460 // IRQ/FIQ: +4 "subs pc, lr, #4" 2461 // SWI: 0 "subs pc, lr, #0" 2462 // ABORT: +4 "subs pc, lr, #4" 2463 // UNDEF: +4/+2 "subs pc, lr, #0" 2464 // UNDEF varies depending on where the exception came from ARM or Thumb 2465 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2466 2467 int64_t LROffset; 2468 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2469 IntKind == "ABORT") 2470 LROffset = 4; 2471 else if (IntKind == "SWI" || IntKind == "UNDEF") 2472 LROffset = 0; 2473 else 2474 report_fatal_error("Unsupported interrupt attribute. If present, value " 2475 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2476 2477 RetOps.insert(RetOps.begin() + 1, 2478 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2479 2480 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2481 } 2482 2483 SDValue 2484 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2485 bool isVarArg, 2486 const SmallVectorImpl<ISD::OutputArg> &Outs, 2487 const SmallVectorImpl<SDValue> &OutVals, 2488 const SDLoc &dl, SelectionDAG &DAG) const { 2489 // CCValAssign - represent the assignment of the return value to a location. 2490 SmallVector<CCValAssign, 16> RVLocs; 2491 2492 // CCState - Info about the registers and stack slots. 2493 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2494 *DAG.getContext()); 2495 2496 // Analyze outgoing return values. 2497 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2498 2499 SDValue Flag; 2500 SmallVector<SDValue, 4> RetOps; 2501 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2502 bool isLittleEndian = Subtarget->isLittle(); 2503 2504 MachineFunction &MF = DAG.getMachineFunction(); 2505 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2506 AFI->setReturnRegsCount(RVLocs.size()); 2507 2508 // Copy the result values into the output registers. 2509 for (unsigned i = 0, realRVLocIdx = 0; 2510 i != RVLocs.size(); 2511 ++i, ++realRVLocIdx) { 2512 CCValAssign &VA = RVLocs[i]; 2513 assert(VA.isRegLoc() && "Can only return in registers!"); 2514 2515 SDValue Arg = OutVals[realRVLocIdx]; 2516 bool ReturnF16 = false; 2517 2518 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2519 // Half-precision return values can be returned like this: 2520 // 2521 // t11 f16 = fadd ... 2522 // t12: i16 = bitcast t11 2523 // t13: i32 = zero_extend t12 2524 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2525 // 2526 // to avoid code generation for bitcasts, we simply set Arg to the node 2527 // that produces the f16 value, t11 in this case. 2528 // 2529 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2530 SDValue ZE = Arg.getOperand(0); 2531 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2532 SDValue BC = ZE.getOperand(0); 2533 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2534 Arg = BC.getOperand(0); 2535 ReturnF16 = true; 2536 } 2537 } 2538 } 2539 } 2540 2541 switch (VA.getLocInfo()) { 2542 default: llvm_unreachable("Unknown loc info!"); 2543 case CCValAssign::Full: break; 2544 case CCValAssign::BCvt: 2545 if (!ReturnF16) 2546 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2547 break; 2548 } 2549 2550 if (VA.needsCustom()) { 2551 if (VA.getLocVT() == MVT::v2f64) { 2552 // Extract the first half and return it in two registers. 2553 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2554 DAG.getConstant(0, dl, MVT::i32)); 2555 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2556 DAG.getVTList(MVT::i32, MVT::i32), Half); 2557 2558 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2559 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2560 Flag); 2561 Flag = Chain.getValue(1); 2562 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2563 VA = RVLocs[++i]; // skip ahead to next loc 2564 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2565 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2566 Flag); 2567 Flag = Chain.getValue(1); 2568 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2569 VA = RVLocs[++i]; // skip ahead to next loc 2570 2571 // Extract the 2nd half and fall through to handle it as an f64 value. 2572 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2573 DAG.getConstant(1, dl, MVT::i32)); 2574 } 2575 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2576 // available. 2577 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2578 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2579 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2580 fmrrd.getValue(isLittleEndian ? 0 : 1), 2581 Flag); 2582 Flag = Chain.getValue(1); 2583 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2584 VA = RVLocs[++i]; // skip ahead to next loc 2585 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2586 fmrrd.getValue(isLittleEndian ? 1 : 0), 2587 Flag); 2588 } else 2589 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2590 2591 // Guarantee that all emitted copies are 2592 // stuck together, avoiding something bad. 2593 Flag = Chain.getValue(1); 2594 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2595 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2596 } 2597 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2598 const MCPhysReg *I = 2599 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2600 if (I) { 2601 for (; *I; ++I) { 2602 if (ARM::GPRRegClass.contains(*I)) 2603 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2604 else if (ARM::DPRRegClass.contains(*I)) 2605 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2606 else 2607 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2608 } 2609 } 2610 2611 // Update chain and glue. 2612 RetOps[0] = Chain; 2613 if (Flag.getNode()) 2614 RetOps.push_back(Flag); 2615 2616 // CPUs which aren't M-class use a special sequence to return from 2617 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2618 // though we use "subs pc, lr, #N"). 2619 // 2620 // M-class CPUs actually use a normal return sequence with a special 2621 // (hardware-provided) value in LR, so the normal code path works. 2622 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2623 !Subtarget->isMClass()) { 2624 if (Subtarget->isThumb1Only()) 2625 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2626 return LowerInterruptReturn(RetOps, dl, DAG); 2627 } 2628 2629 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2630 } 2631 2632 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2633 if (N->getNumValues() != 1) 2634 return false; 2635 if (!N->hasNUsesOfValue(1, 0)) 2636 return false; 2637 2638 SDValue TCChain = Chain; 2639 SDNode *Copy = *N->use_begin(); 2640 if (Copy->getOpcode() == ISD::CopyToReg) { 2641 // If the copy has a glue operand, we conservatively assume it isn't safe to 2642 // perform a tail call. 2643 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2644 return false; 2645 TCChain = Copy->getOperand(0); 2646 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2647 SDNode *VMov = Copy; 2648 // f64 returned in a pair of GPRs. 2649 SmallPtrSet<SDNode*, 2> Copies; 2650 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2651 UI != UE; ++UI) { 2652 if (UI->getOpcode() != ISD::CopyToReg) 2653 return false; 2654 Copies.insert(*UI); 2655 } 2656 if (Copies.size() > 2) 2657 return false; 2658 2659 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2660 UI != UE; ++UI) { 2661 SDValue UseChain = UI->getOperand(0); 2662 if (Copies.count(UseChain.getNode())) 2663 // Second CopyToReg 2664 Copy = *UI; 2665 else { 2666 // We are at the top of this chain. 2667 // If the copy has a glue operand, we conservatively assume it 2668 // isn't safe to perform a tail call. 2669 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2670 return false; 2671 // First CopyToReg 2672 TCChain = UseChain; 2673 } 2674 } 2675 } else if (Copy->getOpcode() == ISD::BITCAST) { 2676 // f32 returned in a single GPR. 2677 if (!Copy->hasOneUse()) 2678 return false; 2679 Copy = *Copy->use_begin(); 2680 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2681 return false; 2682 // If the copy has a glue operand, we conservatively assume it isn't safe to 2683 // perform a tail call. 2684 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2685 return false; 2686 TCChain = Copy->getOperand(0); 2687 } else { 2688 return false; 2689 } 2690 2691 bool HasRet = false; 2692 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2693 UI != UE; ++UI) { 2694 if (UI->getOpcode() != ARMISD::RET_FLAG && 2695 UI->getOpcode() != ARMISD::INTRET_FLAG) 2696 return false; 2697 HasRet = true; 2698 } 2699 2700 if (!HasRet) 2701 return false; 2702 2703 Chain = TCChain; 2704 return true; 2705 } 2706 2707 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2708 if (!Subtarget->supportsTailCall()) 2709 return false; 2710 2711 auto Attr = 2712 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2713 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2714 return false; 2715 2716 return true; 2717 } 2718 2719 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2720 // and pass the lower and high parts through. 2721 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2722 SDLoc DL(Op); 2723 SDValue WriteValue = Op->getOperand(2); 2724 2725 // This function is only supposed to be called for i64 type argument. 2726 assert(WriteValue.getValueType() == MVT::i64 2727 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2728 2729 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2730 DAG.getConstant(0, DL, MVT::i32)); 2731 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2732 DAG.getConstant(1, DL, MVT::i32)); 2733 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2734 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2735 } 2736 2737 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2738 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2739 // one of the above mentioned nodes. It has to be wrapped because otherwise 2740 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2741 // be used to form addressing mode. These wrapped nodes will be selected 2742 // into MOVi. 2743 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2744 SelectionDAG &DAG) const { 2745 EVT PtrVT = Op.getValueType(); 2746 // FIXME there is no actual debug info here 2747 SDLoc dl(Op); 2748 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2749 SDValue Res; 2750 2751 // When generating execute-only code Constant Pools must be promoted to the 2752 // global data section. It's a bit ugly that we can't share them across basic 2753 // blocks, but this way we guarantee that execute-only behaves correct with 2754 // position-independent addressing modes. 2755 if (Subtarget->genExecuteOnly()) { 2756 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2757 auto T = const_cast<Type*>(CP->getType()); 2758 auto C = const_cast<Constant*>(CP->getConstVal()); 2759 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2760 getFunction().getParent()); 2761 auto GV = new GlobalVariable( 2762 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2763 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2764 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2765 Twine(AFI->createPICLabelUId()) 2766 ); 2767 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2768 dl, PtrVT); 2769 return LowerGlobalAddress(GA, DAG); 2770 } 2771 2772 if (CP->isMachineConstantPoolEntry()) 2773 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2774 CP->getAlignment()); 2775 else 2776 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2777 CP->getAlignment()); 2778 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2779 } 2780 2781 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2782 return MachineJumpTableInfo::EK_Inline; 2783 } 2784 2785 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2786 SelectionDAG &DAG) const { 2787 MachineFunction &MF = DAG.getMachineFunction(); 2788 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2789 unsigned ARMPCLabelIndex = 0; 2790 SDLoc DL(Op); 2791 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2792 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2793 SDValue CPAddr; 2794 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2795 if (!IsPositionIndependent) { 2796 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2797 } else { 2798 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2799 ARMPCLabelIndex = AFI->createPICLabelUId(); 2800 ARMConstantPoolValue *CPV = 2801 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2802 ARMCP::CPBlockAddress, PCAdj); 2803 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2804 } 2805 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2806 SDValue Result = DAG.getLoad( 2807 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2808 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2809 if (!IsPositionIndependent) 2810 return Result; 2811 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2812 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2813 } 2814 2815 /// Convert a TLS address reference into the correct sequence of loads 2816 /// and calls to compute the variable's address for Darwin, and return an 2817 /// SDValue containing the final node. 2818 2819 /// Darwin only has one TLS scheme which must be capable of dealing with the 2820 /// fully general situation, in the worst case. This means: 2821 /// + "extern __thread" declaration. 2822 /// + Defined in a possibly unknown dynamic library. 2823 /// 2824 /// The general system is that each __thread variable has a [3 x i32] descriptor 2825 /// which contains information used by the runtime to calculate the address. The 2826 /// only part of this the compiler needs to know about is the first word, which 2827 /// contains a function pointer that must be called with the address of the 2828 /// entire descriptor in "r0". 2829 /// 2830 /// Since this descriptor may be in a different unit, in general access must 2831 /// proceed along the usual ARM rules. A common sequence to produce is: 2832 /// 2833 /// movw rT1, :lower16:_var$non_lazy_ptr 2834 /// movt rT1, :upper16:_var$non_lazy_ptr 2835 /// ldr r0, [rT1] 2836 /// ldr rT2, [r0] 2837 /// blx rT2 2838 /// [...address now in r0...] 2839 SDValue 2840 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2841 SelectionDAG &DAG) const { 2842 assert(Subtarget->isTargetDarwin() && 2843 "This function expects a Darwin target"); 2844 SDLoc DL(Op); 2845 2846 // First step is to get the address of the actua global symbol. This is where 2847 // the TLS descriptor lives. 2848 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2849 2850 // The first entry in the descriptor is a function pointer that we must call 2851 // to obtain the address of the variable. 2852 SDValue Chain = DAG.getEntryNode(); 2853 SDValue FuncTLVGet = DAG.getLoad( 2854 MVT::i32, DL, Chain, DescAddr, 2855 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2856 /* Alignment = */ 4, 2857 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2858 MachineMemOperand::MOInvariant); 2859 Chain = FuncTLVGet.getValue(1); 2860 2861 MachineFunction &F = DAG.getMachineFunction(); 2862 MachineFrameInfo &MFI = F.getFrameInfo(); 2863 MFI.setAdjustsStack(true); 2864 2865 // TLS calls preserve all registers except those that absolutely must be 2866 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2867 // silly). 2868 auto TRI = 2869 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2870 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2871 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2872 2873 // Finally, we can make the call. This is just a degenerate version of a 2874 // normal AArch64 call node: r0 takes the address of the descriptor, and 2875 // returns the address of the variable in this thread. 2876 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2877 Chain = 2878 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2879 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2880 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2881 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2882 } 2883 2884 SDValue 2885 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2886 SelectionDAG &DAG) const { 2887 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2888 2889 SDValue Chain = DAG.getEntryNode(); 2890 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2891 SDLoc DL(Op); 2892 2893 // Load the current TEB (thread environment block) 2894 SDValue Ops[] = {Chain, 2895 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2896 DAG.getConstant(15, DL, MVT::i32), 2897 DAG.getConstant(0, DL, MVT::i32), 2898 DAG.getConstant(13, DL, MVT::i32), 2899 DAG.getConstant(0, DL, MVT::i32), 2900 DAG.getConstant(2, DL, MVT::i32)}; 2901 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2902 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2903 2904 SDValue TEB = CurrentTEB.getValue(0); 2905 Chain = CurrentTEB.getValue(1); 2906 2907 // Load the ThreadLocalStoragePointer from the TEB 2908 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2909 SDValue TLSArray = 2910 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2911 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2912 2913 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2914 // offset into the TLSArray. 2915 2916 // Load the TLS index from the C runtime 2917 SDValue TLSIndex = 2918 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2919 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2920 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2921 2922 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2923 DAG.getConstant(2, DL, MVT::i32)); 2924 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2925 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2926 MachinePointerInfo()); 2927 2928 // Get the offset of the start of the .tls section (section base) 2929 const auto *GA = cast<GlobalAddressSDNode>(Op); 2930 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2931 SDValue Offset = DAG.getLoad( 2932 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2933 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2934 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2935 2936 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2937 } 2938 2939 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2940 SDValue 2941 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2942 SelectionDAG &DAG) const { 2943 SDLoc dl(GA); 2944 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2945 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2946 MachineFunction &MF = DAG.getMachineFunction(); 2947 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2948 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2949 ARMConstantPoolValue *CPV = 2950 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2951 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2952 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2953 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2954 Argument = DAG.getLoad( 2955 PtrVT, dl, DAG.getEntryNode(), Argument, 2956 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2957 SDValue Chain = Argument.getValue(1); 2958 2959 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2960 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2961 2962 // call __tls_get_addr. 2963 ArgListTy Args; 2964 ArgListEntry Entry; 2965 Entry.Node = Argument; 2966 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2967 Args.push_back(Entry); 2968 2969 // FIXME: is there useful debug info available here? 2970 TargetLowering::CallLoweringInfo CLI(DAG); 2971 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2972 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2973 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2974 2975 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2976 return CallResult.first; 2977 } 2978 2979 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2980 // "local exec" model. 2981 SDValue 2982 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2983 SelectionDAG &DAG, 2984 TLSModel::Model model) const { 2985 const GlobalValue *GV = GA->getGlobal(); 2986 SDLoc dl(GA); 2987 SDValue Offset; 2988 SDValue Chain = DAG.getEntryNode(); 2989 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2990 // Get the Thread Pointer 2991 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2992 2993 if (model == TLSModel::InitialExec) { 2994 MachineFunction &MF = DAG.getMachineFunction(); 2995 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2996 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2997 // Initial exec model. 2998 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2999 ARMConstantPoolValue *CPV = 3000 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3001 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3002 true); 3003 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3004 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3005 Offset = DAG.getLoad( 3006 PtrVT, dl, Chain, Offset, 3007 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3008 Chain = Offset.getValue(1); 3009 3010 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3011 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3012 3013 Offset = DAG.getLoad( 3014 PtrVT, dl, Chain, Offset, 3015 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3016 } else { 3017 // local exec model 3018 assert(model == TLSModel::LocalExec); 3019 ARMConstantPoolValue *CPV = 3020 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3021 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3022 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3023 Offset = DAG.getLoad( 3024 PtrVT, dl, Chain, Offset, 3025 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3026 } 3027 3028 // The address of the thread local variable is the add of the thread 3029 // pointer with the offset of the variable. 3030 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3031 } 3032 3033 SDValue 3034 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3035 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3036 if (DAG.getTarget().useEmulatedTLS()) 3037 return LowerToTLSEmulatedModel(GA, DAG); 3038 3039 if (Subtarget->isTargetDarwin()) 3040 return LowerGlobalTLSAddressDarwin(Op, DAG); 3041 3042 if (Subtarget->isTargetWindows()) 3043 return LowerGlobalTLSAddressWindows(Op, DAG); 3044 3045 // TODO: implement the "local dynamic" model 3046 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3047 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3048 3049 switch (model) { 3050 case TLSModel::GeneralDynamic: 3051 case TLSModel::LocalDynamic: 3052 return LowerToTLSGeneralDynamicModel(GA, DAG); 3053 case TLSModel::InitialExec: 3054 case TLSModel::LocalExec: 3055 return LowerToTLSExecModels(GA, DAG, model); 3056 } 3057 llvm_unreachable("bogus TLS model"); 3058 } 3059 3060 /// Return true if all users of V are within function F, looking through 3061 /// ConstantExprs. 3062 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3063 SmallVector<const User*,4> Worklist; 3064 for (auto *U : V->users()) 3065 Worklist.push_back(U); 3066 while (!Worklist.empty()) { 3067 auto *U = Worklist.pop_back_val(); 3068 if (isa<ConstantExpr>(U)) { 3069 for (auto *UU : U->users()) 3070 Worklist.push_back(UU); 3071 continue; 3072 } 3073 3074 auto *I = dyn_cast<Instruction>(U); 3075 if (!I || I->getParent()->getParent() != F) 3076 return false; 3077 } 3078 return true; 3079 } 3080 3081 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3082 const GlobalValue *GV, SelectionDAG &DAG, 3083 EVT PtrVT, const SDLoc &dl) { 3084 // If we're creating a pool entry for a constant global with unnamed address, 3085 // and the global is small enough, we can emit it inline into the constant pool 3086 // to save ourselves an indirection. 3087 // 3088 // This is a win if the constant is only used in one function (so it doesn't 3089 // need to be duplicated) or duplicating the constant wouldn't increase code 3090 // size (implying the constant is no larger than 4 bytes). 3091 const Function &F = DAG.getMachineFunction().getFunction(); 3092 3093 // We rely on this decision to inline being idemopotent and unrelated to the 3094 // use-site. We know that if we inline a variable at one use site, we'll 3095 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3096 // doesn't know about this optimization, so bail out if it's enabled else 3097 // we could decide to inline here (and thus never emit the GV) but require 3098 // the GV from fast-isel generated code. 3099 if (!EnableConstpoolPromotion || 3100 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3101 return SDValue(); 3102 3103 auto *GVar = dyn_cast<GlobalVariable>(GV); 3104 if (!GVar || !GVar->hasInitializer() || 3105 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3106 !GVar->hasLocalLinkage()) 3107 return SDValue(); 3108 3109 // If we inline a value that contains relocations, we move the relocations 3110 // from .data to .text. This is not allowed in position-independent code. 3111 auto *Init = GVar->getInitializer(); 3112 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3113 Init->needsRelocation()) 3114 return SDValue(); 3115 3116 // The constant islands pass can only really deal with alignment requests 3117 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3118 // any type wanting greater alignment requirements than 4 bytes. We also 3119 // can only promote constants that are multiples of 4 bytes in size or 3120 // are paddable to a multiple of 4. Currently we only try and pad constants 3121 // that are strings for simplicity. 3122 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3123 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3124 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3125 unsigned RequiredPadding = 4 - (Size % 4); 3126 bool PaddingPossible = 3127 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3128 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3129 Size == 0) 3130 return SDValue(); 3131 3132 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3133 MachineFunction &MF = DAG.getMachineFunction(); 3134 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3135 3136 // We can't bloat the constant pool too much, else the ConstantIslands pass 3137 // may fail to converge. If we haven't promoted this global yet (it may have 3138 // multiple uses), and promoting it would increase the constant pool size (Sz 3139 // > 4), ensure we have space to do so up to MaxTotal. 3140 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3141 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3142 ConstpoolPromotionMaxTotal) 3143 return SDValue(); 3144 3145 // This is only valid if all users are in a single function; we can't clone 3146 // the constant in general. The LLVM IR unnamed_addr allows merging 3147 // constants, but not cloning them. 3148 // 3149 // We could potentially allow cloning if we could prove all uses of the 3150 // constant in the current function don't care about the address, like 3151 // printf format strings. But that isn't implemented for now. 3152 if (!allUsersAreInFunction(GVar, &F)) 3153 return SDValue(); 3154 3155 // We're going to inline this global. Pad it out if needed. 3156 if (RequiredPadding != 4) { 3157 StringRef S = CDAInit->getAsString(); 3158 3159 SmallVector<uint8_t,16> V(S.size()); 3160 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3161 while (RequiredPadding--) 3162 V.push_back(0); 3163 Init = ConstantDataArray::get(*DAG.getContext(), V); 3164 } 3165 3166 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3167 SDValue CPAddr = 3168 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3169 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3170 AFI->markGlobalAsPromotedToConstantPool(GVar); 3171 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3172 PaddedSize - 4); 3173 } 3174 ++NumConstpoolPromoted; 3175 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3176 } 3177 3178 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3179 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3180 if (!(GV = GA->getBaseObject())) 3181 return false; 3182 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3183 return V->isConstant(); 3184 return isa<Function>(GV); 3185 } 3186 3187 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3188 SelectionDAG &DAG) const { 3189 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3190 default: llvm_unreachable("unknown object format"); 3191 case Triple::COFF: 3192 return LowerGlobalAddressWindows(Op, DAG); 3193 case Triple::ELF: 3194 return LowerGlobalAddressELF(Op, DAG); 3195 case Triple::MachO: 3196 return LowerGlobalAddressDarwin(Op, DAG); 3197 } 3198 } 3199 3200 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3201 SelectionDAG &DAG) const { 3202 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3203 SDLoc dl(Op); 3204 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3205 const TargetMachine &TM = getTargetMachine(); 3206 bool IsRO = isReadOnly(GV); 3207 3208 // promoteToConstantPool only if not generating XO text section 3209 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3210 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3211 return V; 3212 3213 if (isPositionIndependent()) { 3214 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3215 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3216 UseGOT_PREL ? ARMII::MO_GOT : 0); 3217 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3218 if (UseGOT_PREL) 3219 Result = 3220 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3221 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3222 return Result; 3223 } else if (Subtarget->isROPI() && IsRO) { 3224 // PC-relative. 3225 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3226 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3227 return Result; 3228 } else if (Subtarget->isRWPI() && !IsRO) { 3229 // SB-relative. 3230 SDValue RelAddr; 3231 if (Subtarget->useMovt()) { 3232 ++NumMovwMovt; 3233 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3234 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3235 } else { // use literal pool for address constant 3236 ARMConstantPoolValue *CPV = 3237 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3238 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3239 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3240 RelAddr = DAG.getLoad( 3241 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3242 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3243 } 3244 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3245 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3246 return Result; 3247 } 3248 3249 // If we have T2 ops, we can materialize the address directly via movt/movw 3250 // pair. This is always cheaper. 3251 if (Subtarget->useMovt()) { 3252 ++NumMovwMovt; 3253 // FIXME: Once remat is capable of dealing with instructions with register 3254 // operands, expand this into two nodes. 3255 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3256 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3257 } else { 3258 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3259 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3260 return DAG.getLoad( 3261 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3262 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3263 } 3264 } 3265 3266 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3267 SelectionDAG &DAG) const { 3268 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3269 "ROPI/RWPI not currently supported for Darwin"); 3270 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3271 SDLoc dl(Op); 3272 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3273 3274 if (Subtarget->useMovt()) 3275 ++NumMovwMovt; 3276 3277 // FIXME: Once remat is capable of dealing with instructions with register 3278 // operands, expand this into multiple nodes 3279 unsigned Wrapper = 3280 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3281 3282 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3283 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3284 3285 if (Subtarget->isGVIndirectSymbol(GV)) 3286 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3287 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3288 return Result; 3289 } 3290 3291 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3292 SelectionDAG &DAG) const { 3293 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3294 assert(Subtarget->useMovt() && 3295 "Windows on ARM expects to use movw/movt"); 3296 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3297 "ROPI/RWPI not currently supported for Windows"); 3298 3299 const TargetMachine &TM = getTargetMachine(); 3300 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3301 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3302 if (GV->hasDLLImportStorageClass()) 3303 TargetFlags = ARMII::MO_DLLIMPORT; 3304 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3305 TargetFlags = ARMII::MO_COFFSTUB; 3306 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3307 SDValue Result; 3308 SDLoc DL(Op); 3309 3310 ++NumMovwMovt; 3311 3312 // FIXME: Once remat is capable of dealing with instructions with register 3313 // operands, expand this into two nodes. 3314 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3315 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3316 TargetFlags)); 3317 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3318 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3319 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3320 return Result; 3321 } 3322 3323 SDValue 3324 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3325 SDLoc dl(Op); 3326 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3327 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3328 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3329 Op.getOperand(1), Val); 3330 } 3331 3332 SDValue 3333 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3334 SDLoc dl(Op); 3335 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3336 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3337 } 3338 3339 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3340 SelectionDAG &DAG) const { 3341 SDLoc dl(Op); 3342 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3343 Op.getOperand(0)); 3344 } 3345 3346 SDValue 3347 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3348 const ARMSubtarget *Subtarget) const { 3349 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3350 SDLoc dl(Op); 3351 switch (IntNo) { 3352 default: return SDValue(); // Don't custom lower most intrinsics. 3353 case Intrinsic::thread_pointer: { 3354 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3355 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3356 } 3357 case Intrinsic::eh_sjlj_lsda: { 3358 MachineFunction &MF = DAG.getMachineFunction(); 3359 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3360 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3361 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3362 SDValue CPAddr; 3363 bool IsPositionIndependent = isPositionIndependent(); 3364 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3365 ARMConstantPoolValue *CPV = 3366 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3367 ARMCP::CPLSDA, PCAdj); 3368 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3369 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3370 SDValue Result = DAG.getLoad( 3371 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3372 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3373 3374 if (IsPositionIndependent) { 3375 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3376 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3377 } 3378 return Result; 3379 } 3380 case Intrinsic::arm_neon_vabs: 3381 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3382 Op.getOperand(1)); 3383 case Intrinsic::arm_neon_vmulls: 3384 case Intrinsic::arm_neon_vmullu: { 3385 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3386 ? ARMISD::VMULLs : ARMISD::VMULLu; 3387 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3388 Op.getOperand(1), Op.getOperand(2)); 3389 } 3390 case Intrinsic::arm_neon_vminnm: 3391 case Intrinsic::arm_neon_vmaxnm: { 3392 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3393 ? ISD::FMINNUM : ISD::FMAXNUM; 3394 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3395 Op.getOperand(1), Op.getOperand(2)); 3396 } 3397 case Intrinsic::arm_neon_vminu: 3398 case Intrinsic::arm_neon_vmaxu: { 3399 if (Op.getValueType().isFloatingPoint()) 3400 return SDValue(); 3401 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3402 ? ISD::UMIN : ISD::UMAX; 3403 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3404 Op.getOperand(1), Op.getOperand(2)); 3405 } 3406 case Intrinsic::arm_neon_vmins: 3407 case Intrinsic::arm_neon_vmaxs: { 3408 // v{min,max}s is overloaded between signed integers and floats. 3409 if (!Op.getValueType().isFloatingPoint()) { 3410 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3411 ? ISD::SMIN : ISD::SMAX; 3412 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3413 Op.getOperand(1), Op.getOperand(2)); 3414 } 3415 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3416 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3417 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3418 Op.getOperand(1), Op.getOperand(2)); 3419 } 3420 case Intrinsic::arm_neon_vtbl1: 3421 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3422 Op.getOperand(1), Op.getOperand(2)); 3423 case Intrinsic::arm_neon_vtbl2: 3424 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3425 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3426 } 3427 } 3428 3429 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3430 const ARMSubtarget *Subtarget) { 3431 SDLoc dl(Op); 3432 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3433 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3434 if (SSID == SyncScope::SingleThread) 3435 return Op; 3436 3437 if (!Subtarget->hasDataBarrier()) { 3438 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3439 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3440 // here. 3441 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3442 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3443 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3444 DAG.getConstant(0, dl, MVT::i32)); 3445 } 3446 3447 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3448 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3449 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3450 if (Subtarget->isMClass()) { 3451 // Only a full system barrier exists in the M-class architectures. 3452 Domain = ARM_MB::SY; 3453 } else if (Subtarget->preferISHSTBarriers() && 3454 Ord == AtomicOrdering::Release) { 3455 // Swift happens to implement ISHST barriers in a way that's compatible with 3456 // Release semantics but weaker than ISH so we'd be fools not to use 3457 // it. Beware: other processors probably don't! 3458 Domain = ARM_MB::ISHST; 3459 } 3460 3461 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3462 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3463 DAG.getConstant(Domain, dl, MVT::i32)); 3464 } 3465 3466 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3467 const ARMSubtarget *Subtarget) { 3468 // ARM pre v5TE and Thumb1 does not have preload instructions. 3469 if (!(Subtarget->isThumb2() || 3470 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3471 // Just preserve the chain. 3472 return Op.getOperand(0); 3473 3474 SDLoc dl(Op); 3475 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3476 if (!isRead && 3477 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3478 // ARMv7 with MP extension has PLDW. 3479 return Op.getOperand(0); 3480 3481 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3482 if (Subtarget->isThumb()) { 3483 // Invert the bits. 3484 isRead = ~isRead & 1; 3485 isData = ~isData & 1; 3486 } 3487 3488 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3489 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3490 DAG.getConstant(isData, dl, MVT::i32)); 3491 } 3492 3493 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3494 MachineFunction &MF = DAG.getMachineFunction(); 3495 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3496 3497 // vastart just stores the address of the VarArgsFrameIndex slot into the 3498 // memory location argument. 3499 SDLoc dl(Op); 3500 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3501 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3502 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3503 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3504 MachinePointerInfo(SV)); 3505 } 3506 3507 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3508 CCValAssign &NextVA, 3509 SDValue &Root, 3510 SelectionDAG &DAG, 3511 const SDLoc &dl) const { 3512 MachineFunction &MF = DAG.getMachineFunction(); 3513 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3514 3515 const TargetRegisterClass *RC; 3516 if (AFI->isThumb1OnlyFunction()) 3517 RC = &ARM::tGPRRegClass; 3518 else 3519 RC = &ARM::GPRRegClass; 3520 3521 // Transform the arguments stored in physical registers into virtual ones. 3522 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3523 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3524 3525 SDValue ArgValue2; 3526 if (NextVA.isMemLoc()) { 3527 MachineFrameInfo &MFI = MF.getFrameInfo(); 3528 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3529 3530 // Create load node to retrieve arguments from the stack. 3531 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3532 ArgValue2 = DAG.getLoad( 3533 MVT::i32, dl, Root, FIN, 3534 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3535 } else { 3536 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3537 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3538 } 3539 if (!Subtarget->isLittle()) 3540 std::swap (ArgValue, ArgValue2); 3541 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3542 } 3543 3544 // The remaining GPRs hold either the beginning of variable-argument 3545 // data, or the beginning of an aggregate passed by value (usually 3546 // byval). Either way, we allocate stack slots adjacent to the data 3547 // provided by our caller, and store the unallocated registers there. 3548 // If this is a variadic function, the va_list pointer will begin with 3549 // these values; otherwise, this reassembles a (byval) structure that 3550 // was split between registers and memory. 3551 // Return: The frame index registers were stored into. 3552 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3553 const SDLoc &dl, SDValue &Chain, 3554 const Value *OrigArg, 3555 unsigned InRegsParamRecordIdx, 3556 int ArgOffset, unsigned ArgSize) const { 3557 // Currently, two use-cases possible: 3558 // Case #1. Non-var-args function, and we meet first byval parameter. 3559 // Setup first unallocated register as first byval register; 3560 // eat all remained registers 3561 // (these two actions are performed by HandleByVal method). 3562 // Then, here, we initialize stack frame with 3563 // "store-reg" instructions. 3564 // Case #2. Var-args function, that doesn't contain byval parameters. 3565 // The same: eat all remained unallocated registers, 3566 // initialize stack frame. 3567 3568 MachineFunction &MF = DAG.getMachineFunction(); 3569 MachineFrameInfo &MFI = MF.getFrameInfo(); 3570 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3571 unsigned RBegin, REnd; 3572 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3573 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3574 } else { 3575 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3576 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3577 REnd = ARM::R4; 3578 } 3579 3580 if (REnd != RBegin) 3581 ArgOffset = -4 * (ARM::R4 - RBegin); 3582 3583 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3584 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3585 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3586 3587 SmallVector<SDValue, 4> MemOps; 3588 const TargetRegisterClass *RC = 3589 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3590 3591 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3592 unsigned VReg = MF.addLiveIn(Reg, RC); 3593 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3594 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3595 MachinePointerInfo(OrigArg, 4 * i)); 3596 MemOps.push_back(Store); 3597 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3598 } 3599 3600 if (!MemOps.empty()) 3601 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3602 return FrameIndex; 3603 } 3604 3605 // Setup stack frame, the va_list pointer will start from. 3606 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3607 const SDLoc &dl, SDValue &Chain, 3608 unsigned ArgOffset, 3609 unsigned TotalArgRegsSaveSize, 3610 bool ForceMutable) const { 3611 MachineFunction &MF = DAG.getMachineFunction(); 3612 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3613 3614 // Try to store any remaining integer argument regs 3615 // to their spots on the stack so that they may be loaded by dereferencing 3616 // the result of va_next. 3617 // If there is no regs to be stored, just point address after last 3618 // argument passed via stack. 3619 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3620 CCInfo.getInRegsParamsCount(), 3621 CCInfo.getNextStackOffset(), 4); 3622 AFI->setVarArgsFrameIndex(FrameIndex); 3623 } 3624 3625 SDValue ARMTargetLowering::LowerFormalArguments( 3626 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3627 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3628 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3629 MachineFunction &MF = DAG.getMachineFunction(); 3630 MachineFrameInfo &MFI = MF.getFrameInfo(); 3631 3632 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3633 3634 // Assign locations to all of the incoming arguments. 3635 SmallVector<CCValAssign, 16> ArgLocs; 3636 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3637 *DAG.getContext()); 3638 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3639 3640 SmallVector<SDValue, 16> ArgValues; 3641 SDValue ArgValue; 3642 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3643 unsigned CurArgIdx = 0; 3644 3645 // Initially ArgRegsSaveSize is zero. 3646 // Then we increase this value each time we meet byval parameter. 3647 // We also increase this value in case of varargs function. 3648 AFI->setArgRegsSaveSize(0); 3649 3650 // Calculate the amount of stack space that we need to allocate to store 3651 // byval and variadic arguments that are passed in registers. 3652 // We need to know this before we allocate the first byval or variadic 3653 // argument, as they will be allocated a stack slot below the CFA (Canonical 3654 // Frame Address, the stack pointer at entry to the function). 3655 unsigned ArgRegBegin = ARM::R4; 3656 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3657 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3658 break; 3659 3660 CCValAssign &VA = ArgLocs[i]; 3661 unsigned Index = VA.getValNo(); 3662 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3663 if (!Flags.isByVal()) 3664 continue; 3665 3666 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3667 unsigned RBegin, REnd; 3668 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3669 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3670 3671 CCInfo.nextInRegsParam(); 3672 } 3673 CCInfo.rewindByValRegsInfo(); 3674 3675 int lastInsIndex = -1; 3676 if (isVarArg && MFI.hasVAStart()) { 3677 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3678 if (RegIdx != array_lengthof(GPRArgRegs)) 3679 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3680 } 3681 3682 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3683 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3684 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3685 3686 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3687 CCValAssign &VA = ArgLocs[i]; 3688 if (Ins[VA.getValNo()].isOrigArg()) { 3689 std::advance(CurOrigArg, 3690 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3691 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3692 } 3693 // Arguments stored in registers. 3694 if (VA.isRegLoc()) { 3695 EVT RegVT = VA.getLocVT(); 3696 3697 if (VA.needsCustom()) { 3698 // f64 and vector types are split up into multiple registers or 3699 // combinations of registers and stack slots. 3700 if (VA.getLocVT() == MVT::v2f64) { 3701 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3702 Chain, DAG, dl); 3703 VA = ArgLocs[++i]; // skip ahead to next loc 3704 SDValue ArgValue2; 3705 if (VA.isMemLoc()) { 3706 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3707 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3708 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3709 MachinePointerInfo::getFixedStack( 3710 DAG.getMachineFunction(), FI)); 3711 } else { 3712 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3713 Chain, DAG, dl); 3714 } 3715 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3716 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3717 ArgValue, ArgValue1, 3718 DAG.getIntPtrConstant(0, dl)); 3719 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3720 ArgValue, ArgValue2, 3721 DAG.getIntPtrConstant(1, dl)); 3722 } else 3723 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3724 } else { 3725 const TargetRegisterClass *RC; 3726 3727 3728 if (RegVT == MVT::f16) 3729 RC = &ARM::HPRRegClass; 3730 else if (RegVT == MVT::f32) 3731 RC = &ARM::SPRRegClass; 3732 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3733 RC = &ARM::DPRRegClass; 3734 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3735 RC = &ARM::QPRRegClass; 3736 else if (RegVT == MVT::i32) 3737 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3738 : &ARM::GPRRegClass; 3739 else 3740 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3741 3742 // Transform the arguments in physical registers into virtual ones. 3743 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3744 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3745 } 3746 3747 // If this is an 8 or 16-bit value, it is really passed promoted 3748 // to 32 bits. Insert an assert[sz]ext to capture this, then 3749 // truncate to the right size. 3750 switch (VA.getLocInfo()) { 3751 default: llvm_unreachable("Unknown loc info!"); 3752 case CCValAssign::Full: break; 3753 case CCValAssign::BCvt: 3754 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3755 break; 3756 case CCValAssign::SExt: 3757 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3758 DAG.getValueType(VA.getValVT())); 3759 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3760 break; 3761 case CCValAssign::ZExt: 3762 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3763 DAG.getValueType(VA.getValVT())); 3764 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3765 break; 3766 } 3767 3768 InVals.push_back(ArgValue); 3769 } else { // VA.isRegLoc() 3770 // sanity check 3771 assert(VA.isMemLoc()); 3772 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3773 3774 int index = VA.getValNo(); 3775 3776 // Some Ins[] entries become multiple ArgLoc[] entries. 3777 // Process them only once. 3778 if (index != lastInsIndex) 3779 { 3780 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3781 // FIXME: For now, all byval parameter objects are marked mutable. 3782 // This can be changed with more analysis. 3783 // In case of tail call optimization mark all arguments mutable. 3784 // Since they could be overwritten by lowering of arguments in case of 3785 // a tail call. 3786 if (Flags.isByVal()) { 3787 assert(Ins[index].isOrigArg() && 3788 "Byval arguments cannot be implicit"); 3789 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3790 3791 int FrameIndex = StoreByValRegs( 3792 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3793 VA.getLocMemOffset(), Flags.getByValSize()); 3794 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3795 CCInfo.nextInRegsParam(); 3796 } else { 3797 unsigned FIOffset = VA.getLocMemOffset(); 3798 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3799 FIOffset, true); 3800 3801 // Create load nodes to retrieve arguments from the stack. 3802 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3803 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3804 MachinePointerInfo::getFixedStack( 3805 DAG.getMachineFunction(), FI))); 3806 } 3807 lastInsIndex = index; 3808 } 3809 } 3810 } 3811 3812 // varargs 3813 if (isVarArg && MFI.hasVAStart()) 3814 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3815 CCInfo.getNextStackOffset(), 3816 TotalArgRegsSaveSize); 3817 3818 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3819 3820 return Chain; 3821 } 3822 3823 /// isFloatingPointZero - Return true if this is +0.0. 3824 static bool isFloatingPointZero(SDValue Op) { 3825 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3826 return CFP->getValueAPF().isPosZero(); 3827 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3828 // Maybe this has already been legalized into the constant pool? 3829 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3830 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3831 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3832 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3833 return CFP->getValueAPF().isPosZero(); 3834 } 3835 } else if (Op->getOpcode() == ISD::BITCAST && 3836 Op->getValueType(0) == MVT::f64) { 3837 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3838 // created by LowerConstantFP(). 3839 SDValue BitcastOp = Op->getOperand(0); 3840 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3841 isNullConstant(BitcastOp->getOperand(0))) 3842 return true; 3843 } 3844 return false; 3845 } 3846 3847 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3848 /// the given operands. 3849 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3850 SDValue &ARMcc, SelectionDAG &DAG, 3851 const SDLoc &dl) const { 3852 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3853 unsigned C = RHSC->getZExtValue(); 3854 if (!isLegalICmpImmediate((int32_t)C)) { 3855 // Constant does not fit, try adjusting it by one. 3856 switch (CC) { 3857 default: break; 3858 case ISD::SETLT: 3859 case ISD::SETGE: 3860 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3861 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3862 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3863 } 3864 break; 3865 case ISD::SETULT: 3866 case ISD::SETUGE: 3867 if (C != 0 && isLegalICmpImmediate(C-1)) { 3868 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3869 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3870 } 3871 break; 3872 case ISD::SETLE: 3873 case ISD::SETGT: 3874 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3875 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3876 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3877 } 3878 break; 3879 case ISD::SETULE: 3880 case ISD::SETUGT: 3881 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3882 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3883 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3884 } 3885 break; 3886 } 3887 } 3888 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3889 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3890 // In ARM and Thumb-2, the compare instructions can shift their second 3891 // operand. 3892 CC = ISD::getSetCCSwappedOperands(CC); 3893 std::swap(LHS, RHS); 3894 } 3895 3896 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3897 ARMISD::NodeType CompareType; 3898 switch (CondCode) { 3899 default: 3900 CompareType = ARMISD::CMP; 3901 break; 3902 case ARMCC::EQ: 3903 case ARMCC::NE: 3904 // Uses only Z Flag 3905 CompareType = ARMISD::CMPZ; 3906 break; 3907 } 3908 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3909 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3910 } 3911 3912 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3913 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3914 SelectionDAG &DAG, const SDLoc &dl, 3915 bool InvalidOnQNaN) const { 3916 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 3917 SDValue Cmp; 3918 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3919 if (!isFloatingPointZero(RHS)) 3920 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3921 else 3922 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3923 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3924 } 3925 3926 /// duplicateCmp - Glue values can have only one use, so this function 3927 /// duplicates a comparison node. 3928 SDValue 3929 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3930 unsigned Opc = Cmp.getOpcode(); 3931 SDLoc DL(Cmp); 3932 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3933 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3934 3935 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3936 Cmp = Cmp.getOperand(0); 3937 Opc = Cmp.getOpcode(); 3938 if (Opc == ARMISD::CMPFP) 3939 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3940 Cmp.getOperand(1), Cmp.getOperand(2)); 3941 else { 3942 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3943 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3944 Cmp.getOperand(1)); 3945 } 3946 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3947 } 3948 3949 // This function returns three things: the arithmetic computation itself 3950 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 3951 // comparison and the condition code define the case in which the arithmetic 3952 // computation *does not* overflow. 3953 std::pair<SDValue, SDValue> 3954 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3955 SDValue &ARMcc) const { 3956 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3957 3958 SDValue Value, OverflowCmp; 3959 SDValue LHS = Op.getOperand(0); 3960 SDValue RHS = Op.getOperand(1); 3961 SDLoc dl(Op); 3962 3963 // FIXME: We are currently always generating CMPs because we don't support 3964 // generating CMN through the backend. This is not as good as the natural 3965 // CMP case because it causes a register dependency and cannot be folded 3966 // later. 3967 3968 switch (Op.getOpcode()) { 3969 default: 3970 llvm_unreachable("Unknown overflow instruction!"); 3971 case ISD::SADDO: 3972 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3973 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3974 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3975 break; 3976 case ISD::UADDO: 3977 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3978 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 3979 // We do not use it in the USUBO case as Value may not be used. 3980 Value = DAG.getNode(ARMISD::ADDC, dl, 3981 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 3982 .getValue(0); 3983 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3984 break; 3985 case ISD::SSUBO: 3986 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3987 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3988 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3989 break; 3990 case ISD::USUBO: 3991 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3992 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3993 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3994 break; 3995 case ISD::UMULO: 3996 // We generate a UMUL_LOHI and then check if the high word is 0. 3997 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 3998 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 3999 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4000 LHS, RHS); 4001 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4002 DAG.getConstant(0, dl, MVT::i32)); 4003 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4004 break; 4005 case ISD::SMULO: 4006 // We generate a SMUL_LOHI and then check if all the bits of the high word 4007 // are the same as the sign bit of the low word. 4008 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4009 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4010 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4011 LHS, RHS); 4012 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4013 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4014 Value.getValue(0), 4015 DAG.getConstant(31, dl, MVT::i32))); 4016 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4017 break; 4018 } // switch (...) 4019 4020 return std::make_pair(Value, OverflowCmp); 4021 } 4022 4023 SDValue 4024 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4025 // Let legalize expand this if it isn't a legal type yet. 4026 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4027 return SDValue(); 4028 4029 SDValue Value, OverflowCmp; 4030 SDValue ARMcc; 4031 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4032 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4033 SDLoc dl(Op); 4034 // We use 0 and 1 as false and true values. 4035 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4036 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4037 EVT VT = Op.getValueType(); 4038 4039 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4040 ARMcc, CCR, OverflowCmp); 4041 4042 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4043 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4044 } 4045 4046 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4047 SelectionDAG &DAG) { 4048 SDLoc DL(BoolCarry); 4049 EVT CarryVT = BoolCarry.getValueType(); 4050 4051 // This converts the boolean value carry into the carry flag by doing 4052 // ARMISD::SUBC Carry, 1 4053 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4054 DAG.getVTList(CarryVT, MVT::i32), 4055 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4056 return Carry.getValue(1); 4057 } 4058 4059 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4060 SelectionDAG &DAG) { 4061 SDLoc DL(Flags); 4062 4063 // Now convert the carry flag into a boolean carry. We do this 4064 // using ARMISD:ADDE 0, 0, Carry 4065 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4066 DAG.getConstant(0, DL, MVT::i32), 4067 DAG.getConstant(0, DL, MVT::i32), Flags); 4068 } 4069 4070 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4071 SelectionDAG &DAG) const { 4072 // Let legalize expand this if it isn't a legal type yet. 4073 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4074 return SDValue(); 4075 4076 SDValue LHS = Op.getOperand(0); 4077 SDValue RHS = Op.getOperand(1); 4078 SDLoc dl(Op); 4079 4080 EVT VT = Op.getValueType(); 4081 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4082 SDValue Value; 4083 SDValue Overflow; 4084 switch (Op.getOpcode()) { 4085 default: 4086 llvm_unreachable("Unknown overflow instruction!"); 4087 case ISD::UADDO: 4088 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4089 // Convert the carry flag into a boolean value. 4090 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4091 break; 4092 case ISD::USUBO: { 4093 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4094 // Convert the carry flag into a boolean value. 4095 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4096 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4097 // value. So compute 1 - C. 4098 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4099 DAG.getConstant(1, dl, MVT::i32), Overflow); 4100 break; 4101 } 4102 } 4103 4104 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4105 } 4106 4107 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4108 SDValue Cond = Op.getOperand(0); 4109 SDValue SelectTrue = Op.getOperand(1); 4110 SDValue SelectFalse = Op.getOperand(2); 4111 SDLoc dl(Op); 4112 unsigned Opc = Cond.getOpcode(); 4113 4114 if (Cond.getResNo() == 1 && 4115 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4116 Opc == ISD::USUBO)) { 4117 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4118 return SDValue(); 4119 4120 SDValue Value, OverflowCmp; 4121 SDValue ARMcc; 4122 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4123 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4124 EVT VT = Op.getValueType(); 4125 4126 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4127 OverflowCmp, DAG); 4128 } 4129 4130 // Convert: 4131 // 4132 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4133 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4134 // 4135 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4136 const ConstantSDNode *CMOVTrue = 4137 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4138 const ConstantSDNode *CMOVFalse = 4139 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4140 4141 if (CMOVTrue && CMOVFalse) { 4142 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4143 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4144 4145 SDValue True; 4146 SDValue False; 4147 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4148 True = SelectTrue; 4149 False = SelectFalse; 4150 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4151 True = SelectFalse; 4152 False = SelectTrue; 4153 } 4154 4155 if (True.getNode() && False.getNode()) { 4156 EVT VT = Op.getValueType(); 4157 SDValue ARMcc = Cond.getOperand(2); 4158 SDValue CCR = Cond.getOperand(3); 4159 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4160 assert(True.getValueType() == VT); 4161 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4162 } 4163 } 4164 } 4165 4166 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4167 // undefined bits before doing a full-word comparison with zero. 4168 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4169 DAG.getConstant(1, dl, Cond.getValueType())); 4170 4171 return DAG.getSelectCC(dl, Cond, 4172 DAG.getConstant(0, dl, Cond.getValueType()), 4173 SelectTrue, SelectFalse, ISD::SETNE); 4174 } 4175 4176 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4177 bool &swpCmpOps, bool &swpVselOps) { 4178 // Start by selecting the GE condition code for opcodes that return true for 4179 // 'equality' 4180 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4181 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4182 CondCode = ARMCC::GE; 4183 4184 // and GT for opcodes that return false for 'equality'. 4185 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4186 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4187 CondCode = ARMCC::GT; 4188 4189 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4190 // to swap the compare operands. 4191 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4192 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4193 swpCmpOps = true; 4194 4195 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4196 // If we have an unordered opcode, we need to swap the operands to the VSEL 4197 // instruction (effectively negating the condition). 4198 // 4199 // This also has the effect of swapping which one of 'less' or 'greater' 4200 // returns true, so we also swap the compare operands. It also switches 4201 // whether we return true for 'equality', so we compensate by picking the 4202 // opposite condition code to our original choice. 4203 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4204 CC == ISD::SETUGT) { 4205 swpCmpOps = !swpCmpOps; 4206 swpVselOps = !swpVselOps; 4207 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4208 } 4209 4210 // 'ordered' is 'anything but unordered', so use the VS condition code and 4211 // swap the VSEL operands. 4212 if (CC == ISD::SETO) { 4213 CondCode = ARMCC::VS; 4214 swpVselOps = true; 4215 } 4216 4217 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4218 // code and swap the VSEL operands. Also do this if we don't care about the 4219 // unordered case. 4220 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4221 CondCode = ARMCC::EQ; 4222 swpVselOps = true; 4223 } 4224 } 4225 4226 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4227 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4228 SDValue Cmp, SelectionDAG &DAG) const { 4229 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4230 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4231 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4232 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4233 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4234 4235 SDValue TrueLow = TrueVal.getValue(0); 4236 SDValue TrueHigh = TrueVal.getValue(1); 4237 SDValue FalseLow = FalseVal.getValue(0); 4238 SDValue FalseHigh = FalseVal.getValue(1); 4239 4240 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4241 ARMcc, CCR, Cmp); 4242 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4243 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4244 4245 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4246 } else { 4247 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4248 Cmp); 4249 } 4250 } 4251 4252 static bool isGTorGE(ISD::CondCode CC) { 4253 return CC == ISD::SETGT || CC == ISD::SETGE; 4254 } 4255 4256 static bool isLTorLE(ISD::CondCode CC) { 4257 return CC == ISD::SETLT || CC == ISD::SETLE; 4258 } 4259 4260 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4261 // All of these conditions (and their <= and >= counterparts) will do: 4262 // x < k ? k : x 4263 // x > k ? x : k 4264 // k < x ? x : k 4265 // k > x ? k : x 4266 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4267 const SDValue TrueVal, const SDValue FalseVal, 4268 const ISD::CondCode CC, const SDValue K) { 4269 return (isGTorGE(CC) && 4270 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4271 (isLTorLE(CC) && 4272 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4273 } 4274 4275 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4276 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4277 const SDValue TrueVal, const SDValue FalseVal, 4278 const ISD::CondCode CC, const SDValue K) { 4279 return (isGTorGE(CC) && 4280 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4281 (isLTorLE(CC) && 4282 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4283 } 4284 4285 // Check if two chained conditionals could be converted into SSAT or USAT. 4286 // 4287 // SSAT can replace a set of two conditional selectors that bound a number to an 4288 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4289 // 4290 // x < -k ? -k : (x > k ? k : x) 4291 // x < -k ? -k : (x < k ? x : k) 4292 // x > -k ? (x > k ? k : x) : -k 4293 // x < k ? (x < -k ? -k : x) : k 4294 // etc. 4295 // 4296 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4297 // a power of 2. 4298 // 4299 // It returns true if the conversion can be done, false otherwise. 4300 // Additionally, the variable is returned in parameter V, the constant in K and 4301 // usat is set to true if the conditional represents an unsigned saturation 4302 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4303 uint64_t &K, bool &usat) { 4304 SDValue LHS1 = Op.getOperand(0); 4305 SDValue RHS1 = Op.getOperand(1); 4306 SDValue TrueVal1 = Op.getOperand(2); 4307 SDValue FalseVal1 = Op.getOperand(3); 4308 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4309 4310 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4311 if (Op2.getOpcode() != ISD::SELECT_CC) 4312 return false; 4313 4314 SDValue LHS2 = Op2.getOperand(0); 4315 SDValue RHS2 = Op2.getOperand(1); 4316 SDValue TrueVal2 = Op2.getOperand(2); 4317 SDValue FalseVal2 = Op2.getOperand(3); 4318 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4319 4320 // Find out which are the constants and which are the variables 4321 // in each conditional 4322 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4323 ? &RHS1 4324 : nullptr; 4325 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4326 ? &RHS2 4327 : nullptr; 4328 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4329 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4330 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4331 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4332 4333 // We must detect cases where the original operations worked with 16- or 4334 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4335 // must work with sign-extended values but the select operations return 4336 // the original non-extended value. 4337 SDValue V2TmpReg = V2Tmp; 4338 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4339 V2TmpReg = V2Tmp->getOperand(0); 4340 4341 // Check that the registers and the constants have the correct values 4342 // in both conditionals 4343 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4344 V2TmpReg != V2) 4345 return false; 4346 4347 // Figure out which conditional is saturating the lower/upper bound. 4348 const SDValue *LowerCheckOp = 4349 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4350 ? &Op 4351 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4352 ? &Op2 4353 : nullptr; 4354 const SDValue *UpperCheckOp = 4355 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4356 ? &Op 4357 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4358 ? &Op2 4359 : nullptr; 4360 4361 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4362 return false; 4363 4364 // Check that the constant in the lower-bound check is 4365 // the opposite of the constant in the upper-bound check 4366 // in 1's complement. 4367 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4368 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4369 int64_t PosVal = std::max(Val1, Val2); 4370 int64_t NegVal = std::min(Val1, Val2); 4371 4372 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4373 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4374 isPowerOf2_64(PosVal + 1)) { 4375 4376 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4377 if (Val1 == ~Val2) 4378 usat = false; 4379 else if (NegVal == 0) 4380 usat = true; 4381 else 4382 return false; 4383 4384 V = V2; 4385 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4386 4387 return true; 4388 } 4389 4390 return false; 4391 } 4392 4393 // Check if a condition of the type x < k ? k : x can be converted into a 4394 // bit operation instead of conditional moves. 4395 // Currently this is allowed given: 4396 // - The conditions and values match up 4397 // - k is 0 or -1 (all ones) 4398 // This function will not check the last condition, thats up to the caller 4399 // It returns true if the transformation can be made, and in such case 4400 // returns x in V, and k in SatK. 4401 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4402 SDValue &SatK) 4403 { 4404 SDValue LHS = Op.getOperand(0); 4405 SDValue RHS = Op.getOperand(1); 4406 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4407 SDValue TrueVal = Op.getOperand(2); 4408 SDValue FalseVal = Op.getOperand(3); 4409 4410 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4411 ? &RHS 4412 : nullptr; 4413 4414 // No constant operation in comparison, early out 4415 if (!K) 4416 return false; 4417 4418 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4419 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4420 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4421 4422 // If the constant on left and right side, or variable on left and right, 4423 // does not match, early out 4424 if (*K != KTmp || V != VTmp) 4425 return false; 4426 4427 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4428 SatK = *K; 4429 return true; 4430 } 4431 4432 return false; 4433 } 4434 4435 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4436 EVT VT = Op.getValueType(); 4437 SDLoc dl(Op); 4438 4439 // Try to convert two saturating conditional selects into a single SSAT 4440 SDValue SatValue; 4441 uint64_t SatConstant; 4442 bool SatUSat; 4443 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4444 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4445 if (SatUSat) 4446 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4447 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4448 else 4449 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4450 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4451 } 4452 4453 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4454 // into more efficient bit operations, which is possible when k is 0 or -1 4455 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4456 // single instructions. On Thumb the shift and the bit operation will be two 4457 // instructions. 4458 // Only allow this transformation on full-width (32-bit) operations 4459 SDValue LowerSatConstant; 4460 if (VT == MVT::i32 && 4461 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4462 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4463 DAG.getConstant(31, dl, VT)); 4464 if (isNullConstant(LowerSatConstant)) { 4465 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4466 DAG.getAllOnesConstant(dl, VT)); 4467 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4468 } else if (isAllOnesConstant(LowerSatConstant)) 4469 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4470 } 4471 4472 SDValue LHS = Op.getOperand(0); 4473 SDValue RHS = Op.getOperand(1); 4474 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4475 SDValue TrueVal = Op.getOperand(2); 4476 SDValue FalseVal = Op.getOperand(3); 4477 4478 if (!Subtarget->hasFP64() && LHS.getValueType() == MVT::f64) { 4479 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4480 dl); 4481 4482 // If softenSetCCOperands only returned one value, we should compare it to 4483 // zero. 4484 if (!RHS.getNode()) { 4485 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4486 CC = ISD::SETNE; 4487 } 4488 } 4489 4490 if (LHS.getValueType() == MVT::i32) { 4491 // Try to generate VSEL on ARMv8. 4492 // The VSEL instruction can't use all the usual ARM condition 4493 // codes: it only has two bits to select the condition code, so it's 4494 // constrained to use only GE, GT, VS and EQ. 4495 // 4496 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4497 // swap the operands of the previous compare instruction (effectively 4498 // inverting the compare condition, swapping 'less' and 'greater') and 4499 // sometimes need to swap the operands to the VSEL (which inverts the 4500 // condition in the sense of firing whenever the previous condition didn't) 4501 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 4502 TrueVal.getValueType() == MVT::f32 || 4503 TrueVal.getValueType() == MVT::f64)) { 4504 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4505 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4506 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4507 CC = ISD::getSetCCInverse(CC, true); 4508 std::swap(TrueVal, FalseVal); 4509 } 4510 } 4511 4512 SDValue ARMcc; 4513 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4514 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4515 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4516 } 4517 4518 ARMCC::CondCodes CondCode, CondCode2; 4519 bool InvalidOnQNaN; 4520 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4521 4522 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 4523 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 4524 // must use VSEL (limited condition codes), due to not having conditional f16 4525 // moves. 4526 if (Subtarget->hasFPARMv8Base() && 4527 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 4528 (TrueVal.getValueType() == MVT::f16 || 4529 TrueVal.getValueType() == MVT::f32 || 4530 TrueVal.getValueType() == MVT::f64)) { 4531 bool swpCmpOps = false; 4532 bool swpVselOps = false; 4533 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4534 4535 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4536 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4537 if (swpCmpOps) 4538 std::swap(LHS, RHS); 4539 if (swpVselOps) 4540 std::swap(TrueVal, FalseVal); 4541 } 4542 } 4543 4544 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4545 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4546 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4547 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4548 if (CondCode2 != ARMCC::AL) { 4549 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4550 // FIXME: Needs another CMP because flag can have but one use. 4551 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4552 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4553 } 4554 return Result; 4555 } 4556 4557 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4558 /// to morph to an integer compare sequence. 4559 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4560 const ARMSubtarget *Subtarget) { 4561 SDNode *N = Op.getNode(); 4562 if (!N->hasOneUse()) 4563 // Otherwise it requires moving the value from fp to integer registers. 4564 return false; 4565 if (!N->getNumValues()) 4566 return false; 4567 EVT VT = Op.getValueType(); 4568 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4569 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4570 // vmrs are very slow, e.g. cortex-a8. 4571 return false; 4572 4573 if (isFloatingPointZero(Op)) { 4574 SeenZero = true; 4575 return true; 4576 } 4577 return ISD::isNormalLoad(N); 4578 } 4579 4580 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4581 if (isFloatingPointZero(Op)) 4582 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4583 4584 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4585 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4586 Ld->getPointerInfo(), Ld->getAlignment(), 4587 Ld->getMemOperand()->getFlags()); 4588 4589 llvm_unreachable("Unknown VFP cmp argument!"); 4590 } 4591 4592 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4593 SDValue &RetVal1, SDValue &RetVal2) { 4594 SDLoc dl(Op); 4595 4596 if (isFloatingPointZero(Op)) { 4597 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4598 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4599 return; 4600 } 4601 4602 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4603 SDValue Ptr = Ld->getBasePtr(); 4604 RetVal1 = 4605 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4606 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4607 4608 EVT PtrType = Ptr.getValueType(); 4609 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4610 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4611 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4612 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4613 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4614 Ld->getMemOperand()->getFlags()); 4615 return; 4616 } 4617 4618 llvm_unreachable("Unknown VFP cmp argument!"); 4619 } 4620 4621 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4622 /// f32 and even f64 comparisons to integer ones. 4623 SDValue 4624 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4625 SDValue Chain = Op.getOperand(0); 4626 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4627 SDValue LHS = Op.getOperand(2); 4628 SDValue RHS = Op.getOperand(3); 4629 SDValue Dest = Op.getOperand(4); 4630 SDLoc dl(Op); 4631 4632 bool LHSSeenZero = false; 4633 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4634 bool RHSSeenZero = false; 4635 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4636 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4637 // If unsafe fp math optimization is enabled and there are no other uses of 4638 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4639 // to an integer comparison. 4640 if (CC == ISD::SETOEQ) 4641 CC = ISD::SETEQ; 4642 else if (CC == ISD::SETUNE) 4643 CC = ISD::SETNE; 4644 4645 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4646 SDValue ARMcc; 4647 if (LHS.getValueType() == MVT::f32) { 4648 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4649 bitcastf32Toi32(LHS, DAG), Mask); 4650 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4651 bitcastf32Toi32(RHS, DAG), Mask); 4652 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4653 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4654 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4655 Chain, Dest, ARMcc, CCR, Cmp); 4656 } 4657 4658 SDValue LHS1, LHS2; 4659 SDValue RHS1, RHS2; 4660 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4661 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4662 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4663 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4664 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4665 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4666 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4667 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4668 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4669 } 4670 4671 return SDValue(); 4672 } 4673 4674 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4675 SDValue Chain = Op.getOperand(0); 4676 SDValue Cond = Op.getOperand(1); 4677 SDValue Dest = Op.getOperand(2); 4678 SDLoc dl(Op); 4679 4680 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4681 // instruction. 4682 unsigned Opc = Cond.getOpcode(); 4683 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4684 !Subtarget->isThumb1Only(); 4685 if (Cond.getResNo() == 1 && 4686 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4687 Opc == ISD::USUBO || OptimizeMul)) { 4688 // Only lower legal XALUO ops. 4689 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4690 return SDValue(); 4691 4692 // The actual operation with overflow check. 4693 SDValue Value, OverflowCmp; 4694 SDValue ARMcc; 4695 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4696 4697 // Reverse the condition code. 4698 ARMCC::CondCodes CondCode = 4699 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4700 CondCode = ARMCC::getOppositeCondition(CondCode); 4701 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4702 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4703 4704 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4705 OverflowCmp); 4706 } 4707 4708 return SDValue(); 4709 } 4710 4711 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4712 SDValue Chain = Op.getOperand(0); 4713 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4714 SDValue LHS = Op.getOperand(2); 4715 SDValue RHS = Op.getOperand(3); 4716 SDValue Dest = Op.getOperand(4); 4717 SDLoc dl(Op); 4718 4719 if (!Subtarget->hasFP64() && LHS.getValueType() == MVT::f64) { 4720 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4721 dl); 4722 4723 // If softenSetCCOperands only returned one value, we should compare it to 4724 // zero. 4725 if (!RHS.getNode()) { 4726 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4727 CC = ISD::SETNE; 4728 } 4729 } 4730 4731 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4732 // instruction. 4733 unsigned Opc = LHS.getOpcode(); 4734 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4735 !Subtarget->isThumb1Only(); 4736 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4737 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4738 Opc == ISD::USUBO || OptimizeMul) && 4739 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4740 // Only lower legal XALUO ops. 4741 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4742 return SDValue(); 4743 4744 // The actual operation with overflow check. 4745 SDValue Value, OverflowCmp; 4746 SDValue ARMcc; 4747 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4748 4749 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4750 // Reverse the condition code. 4751 ARMCC::CondCodes CondCode = 4752 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4753 CondCode = ARMCC::getOppositeCondition(CondCode); 4754 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4755 } 4756 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4757 4758 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4759 OverflowCmp); 4760 } 4761 4762 if (LHS.getValueType() == MVT::i32) { 4763 SDValue ARMcc; 4764 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4765 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4766 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4767 Chain, Dest, ARMcc, CCR, Cmp); 4768 } 4769 4770 if (getTargetMachine().Options.UnsafeFPMath && 4771 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4772 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4773 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4774 return Result; 4775 } 4776 4777 ARMCC::CondCodes CondCode, CondCode2; 4778 bool InvalidOnQNaN; 4779 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4780 4781 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4782 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4783 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4784 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4785 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4786 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4787 if (CondCode2 != ARMCC::AL) { 4788 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4789 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4790 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4791 } 4792 return Res; 4793 } 4794 4795 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4796 SDValue Chain = Op.getOperand(0); 4797 SDValue Table = Op.getOperand(1); 4798 SDValue Index = Op.getOperand(2); 4799 SDLoc dl(Op); 4800 4801 EVT PTy = getPointerTy(DAG.getDataLayout()); 4802 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4803 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4804 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4805 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4806 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4807 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4808 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4809 // which does another jump to the destination. This also makes it easier 4810 // to translate it to TBB / TBH later (Thumb2 only). 4811 // FIXME: This might not work if the function is extremely large. 4812 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4813 Addr, Op.getOperand(2), JTI); 4814 } 4815 if (isPositionIndependent() || Subtarget->isROPI()) { 4816 Addr = 4817 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4818 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4819 Chain = Addr.getValue(1); 4820 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4821 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4822 } else { 4823 Addr = 4824 DAG.getLoad(PTy, dl, Chain, Addr, 4825 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4826 Chain = Addr.getValue(1); 4827 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4828 } 4829 } 4830 4831 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4832 EVT VT = Op.getValueType(); 4833 SDLoc dl(Op); 4834 4835 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4836 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4837 return Op; 4838 return DAG.UnrollVectorOp(Op.getNode()); 4839 } 4840 4841 const bool HasFullFP16 = 4842 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 4843 4844 EVT NewTy; 4845 const EVT OpTy = Op.getOperand(0).getValueType(); 4846 if (OpTy == MVT::v4f32) 4847 NewTy = MVT::v4i32; 4848 else if (OpTy == MVT::v4f16 && HasFullFP16) 4849 NewTy = MVT::v4i16; 4850 else if (OpTy == MVT::v8f16 && HasFullFP16) 4851 NewTy = MVT::v8i16; 4852 else 4853 llvm_unreachable("Invalid type for custom lowering!"); 4854 4855 if (VT != MVT::v4i16 && VT != MVT::v8i16) 4856 return DAG.UnrollVectorOp(Op.getNode()); 4857 4858 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 4859 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4860 } 4861 4862 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4863 EVT VT = Op.getValueType(); 4864 if (VT.isVector()) 4865 return LowerVectorFP_TO_INT(Op, DAG); 4866 if (!Subtarget->hasFP64() && Op.getOperand(0).getValueType() == MVT::f64) { 4867 RTLIB::Libcall LC; 4868 if (Op.getOpcode() == ISD::FP_TO_SINT) 4869 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4870 Op.getValueType()); 4871 else 4872 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4873 Op.getValueType()); 4874 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4875 /*isSigned*/ false, SDLoc(Op)).first; 4876 } 4877 4878 return Op; 4879 } 4880 4881 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4882 EVT VT = Op.getValueType(); 4883 SDLoc dl(Op); 4884 4885 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4886 if (VT.getVectorElementType() == MVT::f32) 4887 return Op; 4888 return DAG.UnrollVectorOp(Op.getNode()); 4889 } 4890 4891 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 4892 Op.getOperand(0).getValueType() == MVT::v8i16) && 4893 "Invalid type for custom lowering!"); 4894 4895 const bool HasFullFP16 = 4896 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 4897 4898 EVT DestVecType; 4899 if (VT == MVT::v4f32) 4900 DestVecType = MVT::v4i32; 4901 else if (VT == MVT::v4f16 && HasFullFP16) 4902 DestVecType = MVT::v4i16; 4903 else if (VT == MVT::v8f16 && HasFullFP16) 4904 DestVecType = MVT::v8i16; 4905 else 4906 return DAG.UnrollVectorOp(Op.getNode()); 4907 4908 unsigned CastOpc; 4909 unsigned Opc; 4910 switch (Op.getOpcode()) { 4911 default: llvm_unreachable("Invalid opcode!"); 4912 case ISD::SINT_TO_FP: 4913 CastOpc = ISD::SIGN_EXTEND; 4914 Opc = ISD::SINT_TO_FP; 4915 break; 4916 case ISD::UINT_TO_FP: 4917 CastOpc = ISD::ZERO_EXTEND; 4918 Opc = ISD::UINT_TO_FP; 4919 break; 4920 } 4921 4922 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 4923 return DAG.getNode(Opc, dl, VT, Op); 4924 } 4925 4926 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4927 EVT VT = Op.getValueType(); 4928 if (VT.isVector()) 4929 return LowerVectorINT_TO_FP(Op, DAG); 4930 if (!Subtarget->hasFP64() && Op.getValueType() == MVT::f64) { 4931 RTLIB::Libcall LC; 4932 if (Op.getOpcode() == ISD::SINT_TO_FP) 4933 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4934 Op.getValueType()); 4935 else 4936 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4937 Op.getValueType()); 4938 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4939 /*isSigned*/ false, SDLoc(Op)).first; 4940 } 4941 4942 return Op; 4943 } 4944 4945 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4946 // Implement fcopysign with a fabs and a conditional fneg. 4947 SDValue Tmp0 = Op.getOperand(0); 4948 SDValue Tmp1 = Op.getOperand(1); 4949 SDLoc dl(Op); 4950 EVT VT = Op.getValueType(); 4951 EVT SrcVT = Tmp1.getValueType(); 4952 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4953 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4954 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4955 4956 if (UseNEON) { 4957 // Use VBSL to copy the sign bit. 4958 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4959 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4960 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4961 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4962 if (VT == MVT::f64) 4963 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4964 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4965 DAG.getConstant(32, dl, MVT::i32)); 4966 else /*if (VT == MVT::f32)*/ 4967 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4968 if (SrcVT == MVT::f32) { 4969 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4970 if (VT == MVT::f64) 4971 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4972 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4973 DAG.getConstant(32, dl, MVT::i32)); 4974 } else if (VT == MVT::f32) 4975 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4976 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4977 DAG.getConstant(32, dl, MVT::i32)); 4978 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4979 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4980 4981 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4982 dl, MVT::i32); 4983 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4984 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4985 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4986 4987 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4988 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4989 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4990 if (VT == MVT::f32) { 4991 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4992 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4993 DAG.getConstant(0, dl, MVT::i32)); 4994 } else { 4995 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4996 } 4997 4998 return Res; 4999 } 5000 5001 // Bitcast operand 1 to i32. 5002 if (SrcVT == MVT::f64) 5003 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5004 Tmp1).getValue(1); 5005 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5006 5007 // Or in the signbit with integer operations. 5008 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5009 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5010 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5011 if (VT == MVT::f32) { 5012 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5013 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5014 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5015 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5016 } 5017 5018 // f64: Or the high part with signbit and then combine two parts. 5019 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5020 Tmp0); 5021 SDValue Lo = Tmp0.getValue(0); 5022 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5023 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5024 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5025 } 5026 5027 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5028 MachineFunction &MF = DAG.getMachineFunction(); 5029 MachineFrameInfo &MFI = MF.getFrameInfo(); 5030 MFI.setReturnAddressIsTaken(true); 5031 5032 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5033 return SDValue(); 5034 5035 EVT VT = Op.getValueType(); 5036 SDLoc dl(Op); 5037 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5038 if (Depth) { 5039 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5040 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5041 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5042 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5043 MachinePointerInfo()); 5044 } 5045 5046 // Return LR, which contains the return address. Mark it an implicit live-in. 5047 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5048 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5049 } 5050 5051 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5052 const ARMBaseRegisterInfo &ARI = 5053 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5054 MachineFunction &MF = DAG.getMachineFunction(); 5055 MachineFrameInfo &MFI = MF.getFrameInfo(); 5056 MFI.setFrameAddressIsTaken(true); 5057 5058 EVT VT = Op.getValueType(); 5059 SDLoc dl(Op); // FIXME probably not meaningful 5060 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5061 unsigned FrameReg = ARI.getFrameRegister(MF); 5062 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5063 while (Depth--) 5064 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5065 MachinePointerInfo()); 5066 return FrameAddr; 5067 } 5068 5069 // FIXME? Maybe this could be a TableGen attribute on some registers and 5070 // this table could be generated automatically from RegInfo. 5071 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5072 SelectionDAG &DAG) const { 5073 unsigned Reg = StringSwitch<unsigned>(RegName) 5074 .Case("sp", ARM::SP) 5075 .Default(0); 5076 if (Reg) 5077 return Reg; 5078 report_fatal_error(Twine("Invalid register name \"" 5079 + StringRef(RegName) + "\".")); 5080 } 5081 5082 // Result is 64 bit value so split into two 32 bit values and return as a 5083 // pair of values. 5084 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5085 SelectionDAG &DAG) { 5086 SDLoc DL(N); 5087 5088 // This function is only supposed to be called for i64 type destination. 5089 assert(N->getValueType(0) == MVT::i64 5090 && "ExpandREAD_REGISTER called for non-i64 type result."); 5091 5092 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5093 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5094 N->getOperand(0), 5095 N->getOperand(1)); 5096 5097 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5098 Read.getValue(1))); 5099 Results.push_back(Read.getOperand(0)); 5100 } 5101 5102 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5103 /// When \p DstVT, the destination type of \p BC, is on the vector 5104 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5105 /// it might be possible to combine them, such that everything stays on the 5106 /// vector register bank. 5107 /// \p return The node that would replace \p BT, if the combine 5108 /// is possible. 5109 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5110 SelectionDAG &DAG) { 5111 SDValue Op = BC->getOperand(0); 5112 EVT DstVT = BC->getValueType(0); 5113 5114 // The only vector instruction that can produce a scalar (remember, 5115 // since the bitcast was about to be turned into VMOVDRR, the source 5116 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5117 // Moreover, we can do this combine only if there is one use. 5118 // Finally, if the destination type is not a vector, there is not 5119 // much point on forcing everything on the vector bank. 5120 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5121 !Op.hasOneUse()) 5122 return SDValue(); 5123 5124 // If the index is not constant, we will introduce an additional 5125 // multiply that will stick. 5126 // Give up in that case. 5127 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5128 if (!Index) 5129 return SDValue(); 5130 unsigned DstNumElt = DstVT.getVectorNumElements(); 5131 5132 // Compute the new index. 5133 const APInt &APIntIndex = Index->getAPIntValue(); 5134 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5135 NewIndex *= APIntIndex; 5136 // Check if the new constant index fits into i32. 5137 if (NewIndex.getBitWidth() > 32) 5138 return SDValue(); 5139 5140 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5141 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5142 SDLoc dl(Op); 5143 SDValue ExtractSrc = Op.getOperand(0); 5144 EVT VecVT = EVT::getVectorVT( 5145 *DAG.getContext(), DstVT.getScalarType(), 5146 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5147 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5148 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5149 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5150 } 5151 5152 /// ExpandBITCAST - If the target supports VFP, this function is called to 5153 /// expand a bit convert where either the source or destination type is i64 to 5154 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5155 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5156 /// vectors), since the legalizer won't know what to do with that. 5157 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5158 const ARMSubtarget *Subtarget) { 5159 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5160 SDLoc dl(N); 5161 SDValue Op = N->getOperand(0); 5162 5163 // This function is only supposed to be called for i64 types, either as the 5164 // source or destination of the bit convert. 5165 EVT SrcVT = Op.getValueType(); 5166 EVT DstVT = N->getValueType(0); 5167 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5168 5169 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5170 // FullFP16: half values are passed in S-registers, and we don't 5171 // need any of the bitcast and moves: 5172 // 5173 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5174 // t5: i32 = bitcast t2 5175 // t18: f16 = ARMISD::VMOVhr t5 5176 if (Op.getOpcode() != ISD::CopyFromReg || 5177 Op.getValueType() != MVT::f32) 5178 return SDValue(); 5179 5180 auto Move = N->use_begin(); 5181 if (Move->getOpcode() != ARMISD::VMOVhr) 5182 return SDValue(); 5183 5184 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5185 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5186 DAG.ReplaceAllUsesWith(*Move, &Copy); 5187 return Copy; 5188 } 5189 5190 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5191 if (!HasFullFP16) 5192 return SDValue(); 5193 // SoftFP: read half-precision arguments: 5194 // 5195 // t2: i32,ch = ... 5196 // t7: i16 = truncate t2 <~~~~ Op 5197 // t8: f16 = bitcast t7 <~~~~ N 5198 // 5199 if (Op.getOperand(0).getValueType() == MVT::i32) 5200 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5201 MVT::f16, Op.getOperand(0)); 5202 5203 return SDValue(); 5204 } 5205 5206 // Half-precision return values 5207 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5208 if (!HasFullFP16) 5209 return SDValue(); 5210 // 5211 // t11: f16 = fadd t8, t10 5212 // t12: i16 = bitcast t11 <~~~ SDNode N 5213 // t13: i32 = zero_extend t12 5214 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5215 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5216 // 5217 // transform this into: 5218 // 5219 // t20: i32 = ARMISD::VMOVrh t11 5220 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5221 // 5222 auto ZeroExtend = N->use_begin(); 5223 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5224 ZeroExtend->getValueType(0) != MVT::i32) 5225 return SDValue(); 5226 5227 auto Copy = ZeroExtend->use_begin(); 5228 if (Copy->getOpcode() == ISD::CopyToReg && 5229 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5230 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5231 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5232 return Cvt; 5233 } 5234 return SDValue(); 5235 } 5236 5237 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5238 return SDValue(); 5239 5240 // Turn i64->f64 into VMOVDRR. 5241 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5242 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5243 // if we can combine the bitcast with its source. 5244 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5245 return Val; 5246 5247 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5248 DAG.getConstant(0, dl, MVT::i32)); 5249 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5250 DAG.getConstant(1, dl, MVT::i32)); 5251 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5252 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5253 } 5254 5255 // Turn f64->i64 into VMOVRRD. 5256 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5257 SDValue Cvt; 5258 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5259 SrcVT.getVectorNumElements() > 1) 5260 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5261 DAG.getVTList(MVT::i32, MVT::i32), 5262 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5263 else 5264 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5265 DAG.getVTList(MVT::i32, MVT::i32), Op); 5266 // Merge the pieces into a single i64 value. 5267 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5268 } 5269 5270 return SDValue(); 5271 } 5272 5273 /// getZeroVector - Returns a vector of specified type with all zero elements. 5274 /// Zero vectors are used to represent vector negation and in those cases 5275 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5276 /// not support i64 elements, so sometimes the zero vectors will need to be 5277 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5278 /// zero vector. 5279 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5280 assert(VT.isVector() && "Expected a vector type"); 5281 // The canonical modified immediate encoding of a zero vector is....0! 5282 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5283 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5284 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5285 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5286 } 5287 5288 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5289 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5290 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5291 SelectionDAG &DAG) const { 5292 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5293 EVT VT = Op.getValueType(); 5294 unsigned VTBits = VT.getSizeInBits(); 5295 SDLoc dl(Op); 5296 SDValue ShOpLo = Op.getOperand(0); 5297 SDValue ShOpHi = Op.getOperand(1); 5298 SDValue ShAmt = Op.getOperand(2); 5299 SDValue ARMcc; 5300 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5301 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5302 5303 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5304 5305 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5306 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5307 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5308 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5309 DAG.getConstant(VTBits, dl, MVT::i32)); 5310 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5311 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5312 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5313 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5314 ISD::SETGE, ARMcc, DAG, dl); 5315 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5316 ARMcc, CCR, CmpLo); 5317 5318 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5319 SDValue HiBigShift = Opc == ISD::SRA 5320 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5321 DAG.getConstant(VTBits - 1, dl, VT)) 5322 : DAG.getConstant(0, dl, VT); 5323 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5324 ISD::SETGE, ARMcc, DAG, dl); 5325 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5326 ARMcc, CCR, CmpHi); 5327 5328 SDValue Ops[2] = { Lo, Hi }; 5329 return DAG.getMergeValues(Ops, dl); 5330 } 5331 5332 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5333 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5334 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5335 SelectionDAG &DAG) const { 5336 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5337 EVT VT = Op.getValueType(); 5338 unsigned VTBits = VT.getSizeInBits(); 5339 SDLoc dl(Op); 5340 SDValue ShOpLo = Op.getOperand(0); 5341 SDValue ShOpHi = Op.getOperand(1); 5342 SDValue ShAmt = Op.getOperand(2); 5343 SDValue ARMcc; 5344 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5345 5346 assert(Op.getOpcode() == ISD::SHL_PARTS); 5347 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5348 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5349 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5350 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5351 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5352 5353 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5354 DAG.getConstant(VTBits, dl, MVT::i32)); 5355 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5356 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5357 ISD::SETGE, ARMcc, DAG, dl); 5358 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5359 ARMcc, CCR, CmpHi); 5360 5361 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5362 ISD::SETGE, ARMcc, DAG, dl); 5363 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5364 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5365 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5366 5367 SDValue Ops[2] = { Lo, Hi }; 5368 return DAG.getMergeValues(Ops, dl); 5369 } 5370 5371 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5372 SelectionDAG &DAG) const { 5373 // The rounding mode is in bits 23:22 of the FPSCR. 5374 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5375 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5376 // so that the shift + and get folded into a bitfield extract. 5377 SDLoc dl(Op); 5378 SDValue Ops[] = { DAG.getEntryNode(), 5379 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5380 5381 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5382 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5383 DAG.getConstant(1U << 22, dl, MVT::i32)); 5384 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5385 DAG.getConstant(22, dl, MVT::i32)); 5386 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5387 DAG.getConstant(3, dl, MVT::i32)); 5388 } 5389 5390 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5391 const ARMSubtarget *ST) { 5392 SDLoc dl(N); 5393 EVT VT = N->getValueType(0); 5394 if (VT.isVector()) { 5395 assert(ST->hasNEON()); 5396 5397 // Compute the least significant set bit: LSB = X & -X 5398 SDValue X = N->getOperand(0); 5399 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5400 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5401 5402 EVT ElemTy = VT.getVectorElementType(); 5403 5404 if (ElemTy == MVT::i8) { 5405 // Compute with: cttz(x) = ctpop(lsb - 1) 5406 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5407 DAG.getTargetConstant(1, dl, ElemTy)); 5408 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5409 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5410 } 5411 5412 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5413 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5414 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5415 unsigned NumBits = ElemTy.getSizeInBits(); 5416 SDValue WidthMinus1 = 5417 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5418 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5419 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5420 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5421 } 5422 5423 // Compute with: cttz(x) = ctpop(lsb - 1) 5424 5425 // Compute LSB - 1. 5426 SDValue Bits; 5427 if (ElemTy == MVT::i64) { 5428 // Load constant 0xffff'ffff'ffff'ffff to register. 5429 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5430 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5431 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5432 } else { 5433 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5434 DAG.getTargetConstant(1, dl, ElemTy)); 5435 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5436 } 5437 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5438 } 5439 5440 if (!ST->hasV6T2Ops()) 5441 return SDValue(); 5442 5443 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5444 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5445 } 5446 5447 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5448 const ARMSubtarget *ST) { 5449 EVT VT = N->getValueType(0); 5450 SDLoc DL(N); 5451 5452 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5453 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5454 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5455 "Unexpected type for custom ctpop lowering"); 5456 5457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5458 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5459 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 5460 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 5461 5462 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5463 unsigned EltSize = 8; 5464 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5465 while (EltSize != VT.getScalarSizeInBits()) { 5466 SmallVector<SDValue, 8> Ops; 5467 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 5468 TLI.getPointerTy(DAG.getDataLayout()))); 5469 Ops.push_back(Res); 5470 5471 EltSize *= 2; 5472 NumElts /= 2; 5473 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5474 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 5475 } 5476 5477 return Res; 5478 } 5479 5480 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5481 const ARMSubtarget *ST) { 5482 EVT VT = N->getValueType(0); 5483 SDLoc dl(N); 5484 5485 if (!VT.isVector()) 5486 return SDValue(); 5487 5488 // Lower vector shifts on NEON to use VSHL. 5489 assert(ST->hasNEON() && "unexpected vector shift"); 5490 5491 // Left shifts translate directly to the vshiftu intrinsic. 5492 if (N->getOpcode() == ISD::SHL) 5493 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5494 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5495 MVT::i32), 5496 N->getOperand(0), N->getOperand(1)); 5497 5498 assert((N->getOpcode() == ISD::SRA || 5499 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5500 5501 // NEON uses the same intrinsics for both left and right shifts. For 5502 // right shifts, the shift amounts are negative, so negate the vector of 5503 // shift amounts. 5504 EVT ShiftVT = N->getOperand(1).getValueType(); 5505 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5506 getZeroVector(ShiftVT, DAG, dl), 5507 N->getOperand(1)); 5508 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5509 Intrinsic::arm_neon_vshifts : 5510 Intrinsic::arm_neon_vshiftu); 5511 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5512 DAG.getConstant(vshiftInt, dl, MVT::i32), 5513 N->getOperand(0), NegatedCount); 5514 } 5515 5516 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5517 const ARMSubtarget *ST) { 5518 EVT VT = N->getValueType(0); 5519 SDLoc dl(N); 5520 5521 // We can get here for a node like i32 = ISD::SHL i32, i64 5522 if (VT != MVT::i64) 5523 return SDValue(); 5524 5525 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5526 "Unknown shift to lower!"); 5527 5528 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5529 if (!isOneConstant(N->getOperand(1))) 5530 return SDValue(); 5531 5532 // If we are in thumb mode, we don't have RRX. 5533 if (ST->isThumb1Only()) return SDValue(); 5534 5535 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5536 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5537 DAG.getConstant(0, dl, MVT::i32)); 5538 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5539 DAG.getConstant(1, dl, MVT::i32)); 5540 5541 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5542 // captures the result into a carry flag. 5543 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5544 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5545 5546 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5547 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5548 5549 // Merge the pieces into a single i64 value. 5550 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5551 } 5552 5553 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5554 SDValue TmpOp0, TmpOp1; 5555 bool Invert = false; 5556 bool Swap = false; 5557 unsigned Opc = 0; 5558 5559 SDValue Op0 = Op.getOperand(0); 5560 SDValue Op1 = Op.getOperand(1); 5561 SDValue CC = Op.getOperand(2); 5562 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5563 EVT VT = Op.getValueType(); 5564 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5565 SDLoc dl(Op); 5566 5567 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5568 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5569 // Special-case integer 64-bit equality comparisons. They aren't legal, 5570 // but they can be lowered with a few vector instructions. 5571 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5572 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5573 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5574 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5575 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5576 DAG.getCondCode(ISD::SETEQ)); 5577 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5578 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5579 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5580 if (SetCCOpcode == ISD::SETNE) 5581 Merged = DAG.getNOT(dl, Merged, CmpVT); 5582 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5583 return Merged; 5584 } 5585 5586 if (CmpVT.getVectorElementType() == MVT::i64) 5587 // 64-bit comparisons are not legal in general. 5588 return SDValue(); 5589 5590 if (Op1.getValueType().isFloatingPoint()) { 5591 switch (SetCCOpcode) { 5592 default: llvm_unreachable("Illegal FP comparison"); 5593 case ISD::SETUNE: 5594 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5595 case ISD::SETOEQ: 5596 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5597 case ISD::SETOLT: 5598 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5599 case ISD::SETOGT: 5600 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5601 case ISD::SETOLE: 5602 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5603 case ISD::SETOGE: 5604 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5605 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5606 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5607 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5608 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5609 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5610 case ISD::SETONE: 5611 // Expand this to (OLT | OGT). 5612 TmpOp0 = Op0; 5613 TmpOp1 = Op1; 5614 Opc = ISD::OR; 5615 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5616 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5617 break; 5618 case ISD::SETUO: 5619 Invert = true; 5620 LLVM_FALLTHROUGH; 5621 case ISD::SETO: 5622 // Expand this to (OLT | OGE). 5623 TmpOp0 = Op0; 5624 TmpOp1 = Op1; 5625 Opc = ISD::OR; 5626 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5627 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5628 break; 5629 } 5630 } else { 5631 // Integer comparisons. 5632 switch (SetCCOpcode) { 5633 default: llvm_unreachable("Illegal integer comparison"); 5634 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5635 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5636 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5637 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5638 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5639 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5640 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5641 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5642 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5643 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5644 } 5645 5646 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5647 if (Opc == ARMISD::VCEQ) { 5648 SDValue AndOp; 5649 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5650 AndOp = Op0; 5651 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5652 AndOp = Op1; 5653 5654 // Ignore bitconvert. 5655 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5656 AndOp = AndOp.getOperand(0); 5657 5658 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5659 Opc = ARMISD::VTST; 5660 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5661 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5662 Invert = !Invert; 5663 } 5664 } 5665 } 5666 5667 if (Swap) 5668 std::swap(Op0, Op1); 5669 5670 // If one of the operands is a constant vector zero, attempt to fold the 5671 // comparison to a specialized compare-against-zero form. 5672 SDValue SingleOp; 5673 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5674 SingleOp = Op0; 5675 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5676 if (Opc == ARMISD::VCGE) 5677 Opc = ARMISD::VCLEZ; 5678 else if (Opc == ARMISD::VCGT) 5679 Opc = ARMISD::VCLTZ; 5680 SingleOp = Op1; 5681 } 5682 5683 SDValue Result; 5684 if (SingleOp.getNode()) { 5685 switch (Opc) { 5686 case ARMISD::VCEQ: 5687 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5688 case ARMISD::VCGE: 5689 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5690 case ARMISD::VCLEZ: 5691 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5692 case ARMISD::VCGT: 5693 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5694 case ARMISD::VCLTZ: 5695 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5696 default: 5697 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5698 } 5699 } else { 5700 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5701 } 5702 5703 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5704 5705 if (Invert) 5706 Result = DAG.getNOT(dl, Result, VT); 5707 5708 return Result; 5709 } 5710 5711 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 5712 SDValue LHS = Op.getOperand(0); 5713 SDValue RHS = Op.getOperand(1); 5714 SDValue Carry = Op.getOperand(2); 5715 SDValue Cond = Op.getOperand(3); 5716 SDLoc DL(Op); 5717 5718 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 5719 5720 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 5721 // have to invert the carry first. 5722 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 5723 DAG.getConstant(1, DL, MVT::i32), Carry); 5724 // This converts the boolean value carry into the carry flag. 5725 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 5726 5727 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5728 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5729 5730 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5731 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5732 SDValue ARMcc = DAG.getConstant( 5733 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5734 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5735 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5736 Cmp.getValue(1), SDValue()); 5737 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5738 CCR, Chain.getValue(1)); 5739 } 5740 5741 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5742 /// valid vector constant for a NEON instruction with a "modified immediate" 5743 /// operand (e.g., VMOV). If so, return the encoded value. 5744 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5745 unsigned SplatBitSize, SelectionDAG &DAG, 5746 const SDLoc &dl, EVT &VT, bool is128Bits, 5747 NEONModImmType type) { 5748 unsigned OpCmode, Imm; 5749 5750 // SplatBitSize is set to the smallest size that splats the vector, so a 5751 // zero vector will always have SplatBitSize == 8. However, NEON modified 5752 // immediate instructions others than VMOV do not support the 8-bit encoding 5753 // of a zero vector, and the default encoding of zero is supposed to be the 5754 // 32-bit version. 5755 if (SplatBits == 0) 5756 SplatBitSize = 32; 5757 5758 switch (SplatBitSize) { 5759 case 8: 5760 if (type != VMOVModImm) 5761 return SDValue(); 5762 // Any 1-byte value is OK. Op=0, Cmode=1110. 5763 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5764 OpCmode = 0xe; 5765 Imm = SplatBits; 5766 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5767 break; 5768 5769 case 16: 5770 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5771 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5772 if ((SplatBits & ~0xff) == 0) { 5773 // Value = 0x00nn: Op=x, Cmode=100x. 5774 OpCmode = 0x8; 5775 Imm = SplatBits; 5776 break; 5777 } 5778 if ((SplatBits & ~0xff00) == 0) { 5779 // Value = 0xnn00: Op=x, Cmode=101x. 5780 OpCmode = 0xa; 5781 Imm = SplatBits >> 8; 5782 break; 5783 } 5784 return SDValue(); 5785 5786 case 32: 5787 // NEON's 32-bit VMOV supports splat values where: 5788 // * only one byte is nonzero, or 5789 // * the least significant byte is 0xff and the second byte is nonzero, or 5790 // * the least significant 2 bytes are 0xff and the third is nonzero. 5791 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5792 if ((SplatBits & ~0xff) == 0) { 5793 // Value = 0x000000nn: Op=x, Cmode=000x. 5794 OpCmode = 0; 5795 Imm = SplatBits; 5796 break; 5797 } 5798 if ((SplatBits & ~0xff00) == 0) { 5799 // Value = 0x0000nn00: Op=x, Cmode=001x. 5800 OpCmode = 0x2; 5801 Imm = SplatBits >> 8; 5802 break; 5803 } 5804 if ((SplatBits & ~0xff0000) == 0) { 5805 // Value = 0x00nn0000: Op=x, Cmode=010x. 5806 OpCmode = 0x4; 5807 Imm = SplatBits >> 16; 5808 break; 5809 } 5810 if ((SplatBits & ~0xff000000) == 0) { 5811 // Value = 0xnn000000: Op=x, Cmode=011x. 5812 OpCmode = 0x6; 5813 Imm = SplatBits >> 24; 5814 break; 5815 } 5816 5817 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5818 if (type == OtherModImm) return SDValue(); 5819 5820 if ((SplatBits & ~0xffff) == 0 && 5821 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5822 // Value = 0x0000nnff: Op=x, Cmode=1100. 5823 OpCmode = 0xc; 5824 Imm = SplatBits >> 8; 5825 break; 5826 } 5827 5828 if ((SplatBits & ~0xffffff) == 0 && 5829 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5830 // Value = 0x00nnffff: Op=x, Cmode=1101. 5831 OpCmode = 0xd; 5832 Imm = SplatBits >> 16; 5833 break; 5834 } 5835 5836 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5837 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5838 // VMOV.I32. A (very) minor optimization would be to replicate the value 5839 // and fall through here to test for a valid 64-bit splat. But, then the 5840 // caller would also need to check and handle the change in size. 5841 return SDValue(); 5842 5843 case 64: { 5844 if (type != VMOVModImm) 5845 return SDValue(); 5846 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5847 uint64_t BitMask = 0xff; 5848 uint64_t Val = 0; 5849 unsigned ImmMask = 1; 5850 Imm = 0; 5851 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5852 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5853 Val |= BitMask; 5854 Imm |= ImmMask; 5855 } else if ((SplatBits & BitMask) != 0) { 5856 return SDValue(); 5857 } 5858 BitMask <<= 8; 5859 ImmMask <<= 1; 5860 } 5861 5862 if (DAG.getDataLayout().isBigEndian()) 5863 // swap higher and lower 32 bit word 5864 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5865 5866 // Op=1, Cmode=1110. 5867 OpCmode = 0x1e; 5868 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5869 break; 5870 } 5871 5872 default: 5873 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5874 } 5875 5876 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5877 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5878 } 5879 5880 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5881 const ARMSubtarget *ST) const { 5882 EVT VT = Op.getValueType(); 5883 bool IsDouble = (VT == MVT::f64); 5884 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5885 const APFloat &FPVal = CFP->getValueAPF(); 5886 5887 // Prevent floating-point constants from using literal loads 5888 // when execute-only is enabled. 5889 if (ST->genExecuteOnly()) { 5890 // If we can represent the constant as an immediate, don't lower it 5891 if (isFPImmLegal(FPVal, VT)) 5892 return Op; 5893 // Otherwise, construct as integer, and move to float register 5894 APInt INTVal = FPVal.bitcastToAPInt(); 5895 SDLoc DL(CFP); 5896 switch (VT.getSimpleVT().SimpleTy) { 5897 default: 5898 llvm_unreachable("Unknown floating point type!"); 5899 break; 5900 case MVT::f64: { 5901 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5902 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5903 if (!ST->isLittle()) 5904 std::swap(Lo, Hi); 5905 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5906 } 5907 case MVT::f32: 5908 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 5909 DAG.getConstant(INTVal, DL, MVT::i32)); 5910 } 5911 } 5912 5913 if (!ST->hasVFP3Base()) 5914 return SDValue(); 5915 5916 // Use the default (constant pool) lowering for double constants when we have 5917 // an SP-only FPU 5918 if (IsDouble && !Subtarget->hasFP64()) 5919 return SDValue(); 5920 5921 // Try splatting with a VMOV.f32... 5922 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5923 5924 if (ImmVal != -1) { 5925 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5926 // We have code in place to select a valid ConstantFP already, no need to 5927 // do any mangling. 5928 return Op; 5929 } 5930 5931 // It's a float and we are trying to use NEON operations where 5932 // possible. Lower it to a splat followed by an extract. 5933 SDLoc DL(Op); 5934 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5935 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5936 NewVal); 5937 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5938 DAG.getConstant(0, DL, MVT::i32)); 5939 } 5940 5941 // The rest of our options are NEON only, make sure that's allowed before 5942 // proceeding.. 5943 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5944 return SDValue(); 5945 5946 EVT VMovVT; 5947 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5948 5949 // It wouldn't really be worth bothering for doubles except for one very 5950 // important value, which does happen to match: 0.0. So make sure we don't do 5951 // anything stupid. 5952 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5953 return SDValue(); 5954 5955 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5956 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5957 VMovVT, false, VMOVModImm); 5958 if (NewVal != SDValue()) { 5959 SDLoc DL(Op); 5960 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5961 NewVal); 5962 if (IsDouble) 5963 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5964 5965 // It's a float: cast and extract a vector element. 5966 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5967 VecConstant); 5968 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5969 DAG.getConstant(0, DL, MVT::i32)); 5970 } 5971 5972 // Finally, try a VMVN.i32 5973 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5974 false, VMVNModImm); 5975 if (NewVal != SDValue()) { 5976 SDLoc DL(Op); 5977 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5978 5979 if (IsDouble) 5980 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5981 5982 // It's a float: cast and extract a vector element. 5983 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5984 VecConstant); 5985 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5986 DAG.getConstant(0, DL, MVT::i32)); 5987 } 5988 5989 return SDValue(); 5990 } 5991 5992 // check if an VEXT instruction can handle the shuffle mask when the 5993 // vector sources of the shuffle are the same. 5994 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5995 unsigned NumElts = VT.getVectorNumElements(); 5996 5997 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5998 if (M[0] < 0) 5999 return false; 6000 6001 Imm = M[0]; 6002 6003 // If this is a VEXT shuffle, the immediate value is the index of the first 6004 // element. The other shuffle indices must be the successive elements after 6005 // the first one. 6006 unsigned ExpectedElt = Imm; 6007 for (unsigned i = 1; i < NumElts; ++i) { 6008 // Increment the expected index. If it wraps around, just follow it 6009 // back to index zero and keep going. 6010 ++ExpectedElt; 6011 if (ExpectedElt == NumElts) 6012 ExpectedElt = 0; 6013 6014 if (M[i] < 0) continue; // ignore UNDEF indices 6015 if (ExpectedElt != static_cast<unsigned>(M[i])) 6016 return false; 6017 } 6018 6019 return true; 6020 } 6021 6022 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6023 bool &ReverseVEXT, unsigned &Imm) { 6024 unsigned NumElts = VT.getVectorNumElements(); 6025 ReverseVEXT = false; 6026 6027 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6028 if (M[0] < 0) 6029 return false; 6030 6031 Imm = M[0]; 6032 6033 // If this is a VEXT shuffle, the immediate value is the index of the first 6034 // element. The other shuffle indices must be the successive elements after 6035 // the first one. 6036 unsigned ExpectedElt = Imm; 6037 for (unsigned i = 1; i < NumElts; ++i) { 6038 // Increment the expected index. If it wraps around, it may still be 6039 // a VEXT but the source vectors must be swapped. 6040 ExpectedElt += 1; 6041 if (ExpectedElt == NumElts * 2) { 6042 ExpectedElt = 0; 6043 ReverseVEXT = true; 6044 } 6045 6046 if (M[i] < 0) continue; // ignore UNDEF indices 6047 if (ExpectedElt != static_cast<unsigned>(M[i])) 6048 return false; 6049 } 6050 6051 // Adjust the index value if the source operands will be swapped. 6052 if (ReverseVEXT) 6053 Imm -= NumElts; 6054 6055 return true; 6056 } 6057 6058 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6059 /// instruction with the specified blocksize. (The order of the elements 6060 /// within each block of the vector is reversed.) 6061 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6062 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6063 "Only possible block sizes for VREV are: 16, 32, 64"); 6064 6065 unsigned EltSz = VT.getScalarSizeInBits(); 6066 if (EltSz == 64) 6067 return false; 6068 6069 unsigned NumElts = VT.getVectorNumElements(); 6070 unsigned BlockElts = M[0] + 1; 6071 // If the first shuffle index is UNDEF, be optimistic. 6072 if (M[0] < 0) 6073 BlockElts = BlockSize / EltSz; 6074 6075 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6076 return false; 6077 6078 for (unsigned i = 0; i < NumElts; ++i) { 6079 if (M[i] < 0) continue; // ignore UNDEF indices 6080 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6081 return false; 6082 } 6083 6084 return true; 6085 } 6086 6087 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6088 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6089 // range, then 0 is placed into the resulting vector. So pretty much any mask 6090 // of 8 elements can work here. 6091 return VT == MVT::v8i8 && M.size() == 8; 6092 } 6093 6094 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6095 unsigned Index) { 6096 if (Mask.size() == Elements * 2) 6097 return Index / Elements; 6098 return Mask[Index] == 0 ? 0 : 1; 6099 } 6100 6101 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6102 // checking that pairs of elements in the shuffle mask represent the same index 6103 // in each vector, incrementing the expected index by 2 at each step. 6104 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6105 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6106 // v2={e,f,g,h} 6107 // WhichResult gives the offset for each element in the mask based on which 6108 // of the two results it belongs to. 6109 // 6110 // The transpose can be represented either as: 6111 // result1 = shufflevector v1, v2, result1_shuffle_mask 6112 // result2 = shufflevector v1, v2, result2_shuffle_mask 6113 // where v1/v2 and the shuffle masks have the same number of elements 6114 // (here WhichResult (see below) indicates which result is being checked) 6115 // 6116 // or as: 6117 // results = shufflevector v1, v2, shuffle_mask 6118 // where both results are returned in one vector and the shuffle mask has twice 6119 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6120 // want to check the low half and high half of the shuffle mask as if it were 6121 // the other case 6122 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6123 unsigned EltSz = VT.getScalarSizeInBits(); 6124 if (EltSz == 64) 6125 return false; 6126 6127 unsigned NumElts = VT.getVectorNumElements(); 6128 if (M.size() != NumElts && M.size() != NumElts*2) 6129 return false; 6130 6131 // If the mask is twice as long as the input vector then we need to check the 6132 // upper and lower parts of the mask with a matching value for WhichResult 6133 // FIXME: A mask with only even values will be rejected in case the first 6134 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6135 // M[0] is used to determine WhichResult 6136 for (unsigned i = 0; i < M.size(); i += NumElts) { 6137 WhichResult = SelectPairHalf(NumElts, M, i); 6138 for (unsigned j = 0; j < NumElts; j += 2) { 6139 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6140 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6141 return false; 6142 } 6143 } 6144 6145 if (M.size() == NumElts*2) 6146 WhichResult = 0; 6147 6148 return true; 6149 } 6150 6151 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6152 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6153 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6154 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6155 unsigned EltSz = VT.getScalarSizeInBits(); 6156 if (EltSz == 64) 6157 return false; 6158 6159 unsigned NumElts = VT.getVectorNumElements(); 6160 if (M.size() != NumElts && M.size() != NumElts*2) 6161 return false; 6162 6163 for (unsigned i = 0; i < M.size(); i += NumElts) { 6164 WhichResult = SelectPairHalf(NumElts, M, i); 6165 for (unsigned j = 0; j < NumElts; j += 2) { 6166 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6167 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6168 return false; 6169 } 6170 } 6171 6172 if (M.size() == NumElts*2) 6173 WhichResult = 0; 6174 6175 return true; 6176 } 6177 6178 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6179 // that the mask elements are either all even and in steps of size 2 or all odd 6180 // and in steps of size 2. 6181 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6182 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6183 // v2={e,f,g,h} 6184 // Requires similar checks to that of isVTRNMask with 6185 // respect the how results are returned. 6186 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6187 unsigned EltSz = VT.getScalarSizeInBits(); 6188 if (EltSz == 64) 6189 return false; 6190 6191 unsigned NumElts = VT.getVectorNumElements(); 6192 if (M.size() != NumElts && M.size() != NumElts*2) 6193 return false; 6194 6195 for (unsigned i = 0; i < M.size(); i += NumElts) { 6196 WhichResult = SelectPairHalf(NumElts, M, i); 6197 for (unsigned j = 0; j < NumElts; ++j) { 6198 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6199 return false; 6200 } 6201 } 6202 6203 if (M.size() == NumElts*2) 6204 WhichResult = 0; 6205 6206 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6207 if (VT.is64BitVector() && EltSz == 32) 6208 return false; 6209 6210 return true; 6211 } 6212 6213 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6214 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6215 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6216 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6217 unsigned EltSz = VT.getScalarSizeInBits(); 6218 if (EltSz == 64) 6219 return false; 6220 6221 unsigned NumElts = VT.getVectorNumElements(); 6222 if (M.size() != NumElts && M.size() != NumElts*2) 6223 return false; 6224 6225 unsigned Half = NumElts / 2; 6226 for (unsigned i = 0; i < M.size(); i += NumElts) { 6227 WhichResult = SelectPairHalf(NumElts, M, i); 6228 for (unsigned j = 0; j < NumElts; j += Half) { 6229 unsigned Idx = WhichResult; 6230 for (unsigned k = 0; k < Half; ++k) { 6231 int MIdx = M[i + j + k]; 6232 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6233 return false; 6234 Idx += 2; 6235 } 6236 } 6237 } 6238 6239 if (M.size() == NumElts*2) 6240 WhichResult = 0; 6241 6242 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6243 if (VT.is64BitVector() && EltSz == 32) 6244 return false; 6245 6246 return true; 6247 } 6248 6249 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6250 // that pairs of elements of the shufflemask represent the same index in each 6251 // vector incrementing sequentially through the vectors. 6252 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6253 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6254 // v2={e,f,g,h} 6255 // Requires similar checks to that of isVTRNMask with respect the how results 6256 // are returned. 6257 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6258 unsigned EltSz = VT.getScalarSizeInBits(); 6259 if (EltSz == 64) 6260 return false; 6261 6262 unsigned NumElts = VT.getVectorNumElements(); 6263 if (M.size() != NumElts && M.size() != NumElts*2) 6264 return false; 6265 6266 for (unsigned i = 0; i < M.size(); i += NumElts) { 6267 WhichResult = SelectPairHalf(NumElts, M, i); 6268 unsigned Idx = WhichResult * NumElts / 2; 6269 for (unsigned j = 0; j < NumElts; j += 2) { 6270 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6271 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6272 return false; 6273 Idx += 1; 6274 } 6275 } 6276 6277 if (M.size() == NumElts*2) 6278 WhichResult = 0; 6279 6280 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6281 if (VT.is64BitVector() && EltSz == 32) 6282 return false; 6283 6284 return true; 6285 } 6286 6287 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6288 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6289 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6290 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6291 unsigned EltSz = VT.getScalarSizeInBits(); 6292 if (EltSz == 64) 6293 return false; 6294 6295 unsigned NumElts = VT.getVectorNumElements(); 6296 if (M.size() != NumElts && M.size() != NumElts*2) 6297 return false; 6298 6299 for (unsigned i = 0; i < M.size(); i += NumElts) { 6300 WhichResult = SelectPairHalf(NumElts, M, i); 6301 unsigned Idx = WhichResult * NumElts / 2; 6302 for (unsigned j = 0; j < NumElts; j += 2) { 6303 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6304 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6305 return false; 6306 Idx += 1; 6307 } 6308 } 6309 6310 if (M.size() == NumElts*2) 6311 WhichResult = 0; 6312 6313 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6314 if (VT.is64BitVector() && EltSz == 32) 6315 return false; 6316 6317 return true; 6318 } 6319 6320 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6321 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6322 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6323 unsigned &WhichResult, 6324 bool &isV_UNDEF) { 6325 isV_UNDEF = false; 6326 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6327 return ARMISD::VTRN; 6328 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6329 return ARMISD::VUZP; 6330 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6331 return ARMISD::VZIP; 6332 6333 isV_UNDEF = true; 6334 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6335 return ARMISD::VTRN; 6336 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6337 return ARMISD::VUZP; 6338 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6339 return ARMISD::VZIP; 6340 6341 return 0; 6342 } 6343 6344 /// \return true if this is a reverse operation on an vector. 6345 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6346 unsigned NumElts = VT.getVectorNumElements(); 6347 // Make sure the mask has the right size. 6348 if (NumElts != M.size()) 6349 return false; 6350 6351 // Look for <15, ..., 3, -1, 1, 0>. 6352 for (unsigned i = 0; i != NumElts; ++i) 6353 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6354 return false; 6355 6356 return true; 6357 } 6358 6359 // If N is an integer constant that can be moved into a register in one 6360 // instruction, return an SDValue of such a constant (will become a MOV 6361 // instruction). Otherwise return null. 6362 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6363 const ARMSubtarget *ST, const SDLoc &dl) { 6364 uint64_t Val; 6365 if (!isa<ConstantSDNode>(N)) 6366 return SDValue(); 6367 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6368 6369 if (ST->isThumb1Only()) { 6370 if (Val <= 255 || ~Val <= 255) 6371 return DAG.getConstant(Val, dl, MVT::i32); 6372 } else { 6373 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6374 return DAG.getConstant(Val, dl, MVT::i32); 6375 } 6376 return SDValue(); 6377 } 6378 6379 // If this is a case we can't handle, return null and let the default 6380 // expansion code take care of it. 6381 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6382 const ARMSubtarget *ST) const { 6383 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6384 SDLoc dl(Op); 6385 EVT VT = Op.getValueType(); 6386 6387 APInt SplatBits, SplatUndef; 6388 unsigned SplatBitSize; 6389 bool HasAnyUndefs; 6390 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6391 if (SplatUndef.isAllOnesValue()) 6392 return DAG.getUNDEF(VT); 6393 6394 if (SplatBitSize <= 64) { 6395 // Check if an immediate VMOV works. 6396 EVT VmovVT; 6397 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6398 SplatUndef.getZExtValue(), SplatBitSize, 6399 DAG, dl, VmovVT, VT.is128BitVector(), 6400 VMOVModImm); 6401 if (Val.getNode()) { 6402 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6403 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6404 } 6405 6406 // Try an immediate VMVN. 6407 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6408 Val = isNEONModifiedImm(NegatedImm, 6409 SplatUndef.getZExtValue(), SplatBitSize, 6410 DAG, dl, VmovVT, VT.is128BitVector(), 6411 VMVNModImm); 6412 if (Val.getNode()) { 6413 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6414 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6415 } 6416 6417 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6418 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6419 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6420 if (ImmVal != -1) { 6421 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6422 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6423 } 6424 } 6425 } 6426 } 6427 6428 // Scan through the operands to see if only one value is used. 6429 // 6430 // As an optimisation, even if more than one value is used it may be more 6431 // profitable to splat with one value then change some lanes. 6432 // 6433 // Heuristically we decide to do this if the vector has a "dominant" value, 6434 // defined as splatted to more than half of the lanes. 6435 unsigned NumElts = VT.getVectorNumElements(); 6436 bool isOnlyLowElement = true; 6437 bool usesOnlyOneValue = true; 6438 bool hasDominantValue = false; 6439 bool isConstant = true; 6440 6441 // Map of the number of times a particular SDValue appears in the 6442 // element list. 6443 DenseMap<SDValue, unsigned> ValueCounts; 6444 SDValue Value; 6445 for (unsigned i = 0; i < NumElts; ++i) { 6446 SDValue V = Op.getOperand(i); 6447 if (V.isUndef()) 6448 continue; 6449 if (i > 0) 6450 isOnlyLowElement = false; 6451 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6452 isConstant = false; 6453 6454 ValueCounts.insert(std::make_pair(V, 0)); 6455 unsigned &Count = ValueCounts[V]; 6456 6457 // Is this value dominant? (takes up more than half of the lanes) 6458 if (++Count > (NumElts / 2)) { 6459 hasDominantValue = true; 6460 Value = V; 6461 } 6462 } 6463 if (ValueCounts.size() != 1) 6464 usesOnlyOneValue = false; 6465 if (!Value.getNode() && !ValueCounts.empty()) 6466 Value = ValueCounts.begin()->first; 6467 6468 if (ValueCounts.empty()) 6469 return DAG.getUNDEF(VT); 6470 6471 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6472 // Keep going if we are hitting this case. 6473 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6474 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6475 6476 unsigned EltSize = VT.getScalarSizeInBits(); 6477 6478 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6479 // i32 and try again. 6480 if (hasDominantValue && EltSize <= 32) { 6481 if (!isConstant) { 6482 SDValue N; 6483 6484 // If we are VDUPing a value that comes directly from a vector, that will 6485 // cause an unnecessary move to and from a GPR, where instead we could 6486 // just use VDUPLANE. We can only do this if the lane being extracted 6487 // is at a constant index, as the VDUP from lane instructions only have 6488 // constant-index forms. 6489 ConstantSDNode *constIndex; 6490 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6491 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6492 // We need to create a new undef vector to use for the VDUPLANE if the 6493 // size of the vector from which we get the value is different than the 6494 // size of the vector that we need to create. We will insert the element 6495 // such that the register coalescer will remove unnecessary copies. 6496 if (VT != Value->getOperand(0).getValueType()) { 6497 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6498 VT.getVectorNumElements(); 6499 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6500 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6501 Value, DAG.getConstant(index, dl, MVT::i32)), 6502 DAG.getConstant(index, dl, MVT::i32)); 6503 } else 6504 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6505 Value->getOperand(0), Value->getOperand(1)); 6506 } else 6507 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6508 6509 if (!usesOnlyOneValue) { 6510 // The dominant value was splatted as 'N', but we now have to insert 6511 // all differing elements. 6512 for (unsigned I = 0; I < NumElts; ++I) { 6513 if (Op.getOperand(I) == Value) 6514 continue; 6515 SmallVector<SDValue, 3> Ops; 6516 Ops.push_back(N); 6517 Ops.push_back(Op.getOperand(I)); 6518 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6519 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6520 } 6521 } 6522 return N; 6523 } 6524 if (VT.getVectorElementType().isFloatingPoint()) { 6525 SmallVector<SDValue, 8> Ops; 6526 for (unsigned i = 0; i < NumElts; ++i) 6527 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6528 Op.getOperand(i))); 6529 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6530 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6531 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6532 if (Val.getNode()) 6533 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6534 } 6535 if (usesOnlyOneValue) { 6536 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6537 if (isConstant && Val.getNode()) 6538 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6539 } 6540 } 6541 6542 // If all elements are constants and the case above didn't get hit, fall back 6543 // to the default expansion, which will generate a load from the constant 6544 // pool. 6545 if (isConstant) 6546 return SDValue(); 6547 6548 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6549 if (NumElts >= 4) { 6550 SDValue shuffle = ReconstructShuffle(Op, DAG); 6551 if (shuffle != SDValue()) 6552 return shuffle; 6553 } 6554 6555 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6556 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6557 // into two 64-bit vectors; we might discover a better way to lower it. 6558 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6559 EVT ExtVT = VT.getVectorElementType(); 6560 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6561 SDValue Lower = 6562 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6563 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6564 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6565 SDValue Upper = DAG.getBuildVector( 6566 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6567 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6568 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6569 if (Lower && Upper) 6570 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6571 } 6572 6573 // Vectors with 32- or 64-bit elements can be built by directly assigning 6574 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6575 // will be legalized. 6576 if (EltSize >= 32) { 6577 // Do the expansion with floating-point types, since that is what the VFP 6578 // registers are defined to use, and since i64 is not legal. 6579 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6580 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6581 SmallVector<SDValue, 8> Ops; 6582 for (unsigned i = 0; i < NumElts; ++i) 6583 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6584 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6585 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6586 } 6587 6588 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6589 // know the default expansion would otherwise fall back on something even 6590 // worse. For a vector with one or two non-undef values, that's 6591 // scalar_to_vector for the elements followed by a shuffle (provided the 6592 // shuffle is valid for the target) and materialization element by element 6593 // on the stack followed by a load for everything else. 6594 if (!isConstant && !usesOnlyOneValue) { 6595 SDValue Vec = DAG.getUNDEF(VT); 6596 for (unsigned i = 0 ; i < NumElts; ++i) { 6597 SDValue V = Op.getOperand(i); 6598 if (V.isUndef()) 6599 continue; 6600 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6601 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6602 } 6603 return Vec; 6604 } 6605 6606 return SDValue(); 6607 } 6608 6609 // Gather data to see if the operation can be modelled as a 6610 // shuffle in combination with VEXTs. 6611 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6612 SelectionDAG &DAG) const { 6613 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6614 SDLoc dl(Op); 6615 EVT VT = Op.getValueType(); 6616 unsigned NumElts = VT.getVectorNumElements(); 6617 6618 struct ShuffleSourceInfo { 6619 SDValue Vec; 6620 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6621 unsigned MaxElt = 0; 6622 6623 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6624 // be compatible with the shuffle we intend to construct. As a result 6625 // ShuffleVec will be some sliding window into the original Vec. 6626 SDValue ShuffleVec; 6627 6628 // Code should guarantee that element i in Vec starts at element "WindowBase 6629 // + i * WindowScale in ShuffleVec". 6630 int WindowBase = 0; 6631 int WindowScale = 1; 6632 6633 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6634 6635 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6636 }; 6637 6638 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6639 // node. 6640 SmallVector<ShuffleSourceInfo, 2> Sources; 6641 for (unsigned i = 0; i < NumElts; ++i) { 6642 SDValue V = Op.getOperand(i); 6643 if (V.isUndef()) 6644 continue; 6645 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6646 // A shuffle can only come from building a vector from various 6647 // elements of other vectors. 6648 return SDValue(); 6649 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6650 // Furthermore, shuffles require a constant mask, whereas extractelts 6651 // accept variable indices. 6652 return SDValue(); 6653 } 6654 6655 // Add this element source to the list if it's not already there. 6656 SDValue SourceVec = V.getOperand(0); 6657 auto Source = llvm::find(Sources, SourceVec); 6658 if (Source == Sources.end()) 6659 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6660 6661 // Update the minimum and maximum lane number seen. 6662 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6663 Source->MinElt = std::min(Source->MinElt, EltNo); 6664 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6665 } 6666 6667 // Currently only do something sane when at most two source vectors 6668 // are involved. 6669 if (Sources.size() > 2) 6670 return SDValue(); 6671 6672 // Find out the smallest element size among result and two sources, and use 6673 // it as element size to build the shuffle_vector. 6674 EVT SmallestEltTy = VT.getVectorElementType(); 6675 for (auto &Source : Sources) { 6676 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6677 if (SrcEltTy.bitsLT(SmallestEltTy)) 6678 SmallestEltTy = SrcEltTy; 6679 } 6680 unsigned ResMultiplier = 6681 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6682 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6683 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6684 6685 // If the source vector is too wide or too narrow, we may nevertheless be able 6686 // to construct a compatible shuffle either by concatenating it with UNDEF or 6687 // extracting a suitable range of elements. 6688 for (auto &Src : Sources) { 6689 EVT SrcVT = Src.ShuffleVec.getValueType(); 6690 6691 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6692 continue; 6693 6694 // This stage of the search produces a source with the same element type as 6695 // the original, but with a total width matching the BUILD_VECTOR output. 6696 EVT EltVT = SrcVT.getVectorElementType(); 6697 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6698 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6699 6700 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6701 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6702 return SDValue(); 6703 // We can pad out the smaller vector for free, so if it's part of a 6704 // shuffle... 6705 Src.ShuffleVec = 6706 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6707 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6708 continue; 6709 } 6710 6711 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6712 return SDValue(); 6713 6714 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6715 // Span too large for a VEXT to cope 6716 return SDValue(); 6717 } 6718 6719 if (Src.MinElt >= NumSrcElts) { 6720 // The extraction can just take the second half 6721 Src.ShuffleVec = 6722 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6723 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6724 Src.WindowBase = -NumSrcElts; 6725 } else if (Src.MaxElt < NumSrcElts) { 6726 // The extraction can just take the first half 6727 Src.ShuffleVec = 6728 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6729 DAG.getConstant(0, dl, MVT::i32)); 6730 } else { 6731 // An actual VEXT is needed 6732 SDValue VEXTSrc1 = 6733 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6734 DAG.getConstant(0, dl, MVT::i32)); 6735 SDValue VEXTSrc2 = 6736 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6737 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6738 6739 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6740 VEXTSrc2, 6741 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6742 Src.WindowBase = -Src.MinElt; 6743 } 6744 } 6745 6746 // Another possible incompatibility occurs from the vector element types. We 6747 // can fix this by bitcasting the source vectors to the same type we intend 6748 // for the shuffle. 6749 for (auto &Src : Sources) { 6750 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6751 if (SrcEltTy == SmallestEltTy) 6752 continue; 6753 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6754 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6755 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6756 Src.WindowBase *= Src.WindowScale; 6757 } 6758 6759 // Final sanity check before we try to actually produce a shuffle. 6760 LLVM_DEBUG(for (auto Src 6761 : Sources) 6762 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6763 6764 // The stars all align, our next step is to produce the mask for the shuffle. 6765 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6766 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6767 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6768 SDValue Entry = Op.getOperand(i); 6769 if (Entry.isUndef()) 6770 continue; 6771 6772 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6773 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6774 6775 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6776 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6777 // segment. 6778 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6779 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6780 VT.getScalarSizeInBits()); 6781 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6782 6783 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6784 // starting at the appropriate offset. 6785 int *LaneMask = &Mask[i * ResMultiplier]; 6786 6787 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6788 ExtractBase += NumElts * (Src - Sources.begin()); 6789 for (int j = 0; j < LanesDefined; ++j) 6790 LaneMask[j] = ExtractBase + j; 6791 } 6792 6793 // Final check before we try to produce nonsense... 6794 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6795 return SDValue(); 6796 6797 // We can't handle more than two sources. This should have already 6798 // been checked before this point. 6799 assert(Sources.size() <= 2 && "Too many sources!"); 6800 6801 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6802 for (unsigned i = 0; i < Sources.size(); ++i) 6803 ShuffleOps[i] = Sources[i].ShuffleVec; 6804 6805 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6806 ShuffleOps[1], Mask); 6807 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6808 } 6809 6810 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6811 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6812 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6813 /// are assumed to be legal. 6814 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6815 if (VT.getVectorNumElements() == 4 && 6816 (VT.is128BitVector() || VT.is64BitVector())) { 6817 unsigned PFIndexes[4]; 6818 for (unsigned i = 0; i != 4; ++i) { 6819 if (M[i] < 0) 6820 PFIndexes[i] = 8; 6821 else 6822 PFIndexes[i] = M[i]; 6823 } 6824 6825 // Compute the index in the perfect shuffle table. 6826 unsigned PFTableIndex = 6827 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6828 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6829 unsigned Cost = (PFEntry >> 30); 6830 6831 if (Cost <= 4) 6832 return true; 6833 } 6834 6835 bool ReverseVEXT, isV_UNDEF; 6836 unsigned Imm, WhichResult; 6837 6838 unsigned EltSize = VT.getScalarSizeInBits(); 6839 return (EltSize >= 32 || 6840 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6841 isVREVMask(M, VT, 64) || 6842 isVREVMask(M, VT, 32) || 6843 isVREVMask(M, VT, 16) || 6844 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6845 isVTBLMask(M, VT) || 6846 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6847 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6848 } 6849 6850 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6851 /// the specified operations to build the shuffle. 6852 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6853 SDValue RHS, SelectionDAG &DAG, 6854 const SDLoc &dl) { 6855 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6856 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6857 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6858 6859 enum { 6860 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6861 OP_VREV, 6862 OP_VDUP0, 6863 OP_VDUP1, 6864 OP_VDUP2, 6865 OP_VDUP3, 6866 OP_VEXT1, 6867 OP_VEXT2, 6868 OP_VEXT3, 6869 OP_VUZPL, // VUZP, left result 6870 OP_VUZPR, // VUZP, right result 6871 OP_VZIPL, // VZIP, left result 6872 OP_VZIPR, // VZIP, right result 6873 OP_VTRNL, // VTRN, left result 6874 OP_VTRNR // VTRN, right result 6875 }; 6876 6877 if (OpNum == OP_COPY) { 6878 if (LHSID == (1*9+2)*9+3) return LHS; 6879 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6880 return RHS; 6881 } 6882 6883 SDValue OpLHS, OpRHS; 6884 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6885 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6886 EVT VT = OpLHS.getValueType(); 6887 6888 switch (OpNum) { 6889 default: llvm_unreachable("Unknown shuffle opcode!"); 6890 case OP_VREV: 6891 // VREV divides the vector in half and swaps within the half. 6892 if (VT.getVectorElementType() == MVT::i32 || 6893 VT.getVectorElementType() == MVT::f32) 6894 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6895 // vrev <4 x i16> -> VREV32 6896 if (VT.getVectorElementType() == MVT::i16) 6897 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6898 // vrev <4 x i8> -> VREV16 6899 assert(VT.getVectorElementType() == MVT::i8); 6900 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6901 case OP_VDUP0: 6902 case OP_VDUP1: 6903 case OP_VDUP2: 6904 case OP_VDUP3: 6905 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6906 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6907 case OP_VEXT1: 6908 case OP_VEXT2: 6909 case OP_VEXT3: 6910 return DAG.getNode(ARMISD::VEXT, dl, VT, 6911 OpLHS, OpRHS, 6912 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6913 case OP_VUZPL: 6914 case OP_VUZPR: 6915 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6916 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6917 case OP_VZIPL: 6918 case OP_VZIPR: 6919 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6920 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6921 case OP_VTRNL: 6922 case OP_VTRNR: 6923 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6924 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6925 } 6926 } 6927 6928 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6929 ArrayRef<int> ShuffleMask, 6930 SelectionDAG &DAG) { 6931 // Check to see if we can use the VTBL instruction. 6932 SDValue V1 = Op.getOperand(0); 6933 SDValue V2 = Op.getOperand(1); 6934 SDLoc DL(Op); 6935 6936 SmallVector<SDValue, 8> VTBLMask; 6937 for (ArrayRef<int>::iterator 6938 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6939 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6940 6941 if (V2.getNode()->isUndef()) 6942 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6943 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6944 6945 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6946 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6947 } 6948 6949 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6950 SelectionDAG &DAG) { 6951 SDLoc DL(Op); 6952 SDValue OpLHS = Op.getOperand(0); 6953 EVT VT = OpLHS.getValueType(); 6954 6955 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6956 "Expect an v8i16/v16i8 type"); 6957 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6958 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6959 // extract the first 8 bytes into the top double word and the last 8 bytes 6960 // into the bottom double word. The v8i16 case is similar. 6961 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6962 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6963 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6964 } 6965 6966 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6967 SDValue V1 = Op.getOperand(0); 6968 SDValue V2 = Op.getOperand(1); 6969 SDLoc dl(Op); 6970 EVT VT = Op.getValueType(); 6971 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6972 6973 // Convert shuffles that are directly supported on NEON to target-specific 6974 // DAG nodes, instead of keeping them as shuffles and matching them again 6975 // during code selection. This is more efficient and avoids the possibility 6976 // of inconsistencies between legalization and selection. 6977 // FIXME: floating-point vectors should be canonicalized to integer vectors 6978 // of the same time so that they get CSEd properly. 6979 ArrayRef<int> ShuffleMask = SVN->getMask(); 6980 6981 unsigned EltSize = VT.getScalarSizeInBits(); 6982 if (EltSize <= 32) { 6983 if (SVN->isSplat()) { 6984 int Lane = SVN->getSplatIndex(); 6985 // If this is undef splat, generate it via "just" vdup, if possible. 6986 if (Lane == -1) Lane = 0; 6987 6988 // Test if V1 is a SCALAR_TO_VECTOR. 6989 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6990 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6991 } 6992 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6993 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6994 // reaches it). 6995 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6996 !isa<ConstantSDNode>(V1.getOperand(0))) { 6997 bool IsScalarToVector = true; 6998 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6999 if (!V1.getOperand(i).isUndef()) { 7000 IsScalarToVector = false; 7001 break; 7002 } 7003 if (IsScalarToVector) 7004 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7005 } 7006 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7007 DAG.getConstant(Lane, dl, MVT::i32)); 7008 } 7009 7010 bool ReverseVEXT = false; 7011 unsigned Imm = 0; 7012 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7013 if (ReverseVEXT) 7014 std::swap(V1, V2); 7015 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7016 DAG.getConstant(Imm, dl, MVT::i32)); 7017 } 7018 7019 if (isVREVMask(ShuffleMask, VT, 64)) 7020 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7021 if (isVREVMask(ShuffleMask, VT, 32)) 7022 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7023 if (isVREVMask(ShuffleMask, VT, 16)) 7024 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7025 7026 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7027 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7028 DAG.getConstant(Imm, dl, MVT::i32)); 7029 } 7030 7031 // Check for Neon shuffles that modify both input vectors in place. 7032 // If both results are used, i.e., if there are two shuffles with the same 7033 // source operands and with masks corresponding to both results of one of 7034 // these operations, DAG memoization will ensure that a single node is 7035 // used for both shuffles. 7036 unsigned WhichResult = 0; 7037 bool isV_UNDEF = false; 7038 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7039 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7040 if (isV_UNDEF) 7041 V2 = V1; 7042 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7043 .getValue(WhichResult); 7044 } 7045 7046 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7047 // shuffles that produce a result larger than their operands with: 7048 // shuffle(concat(v1, undef), concat(v2, undef)) 7049 // -> 7050 // shuffle(concat(v1, v2), undef) 7051 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7052 // 7053 // This is useful in the general case, but there are special cases where 7054 // native shuffles produce larger results: the two-result ops. 7055 // 7056 // Look through the concat when lowering them: 7057 // shuffle(concat(v1, v2), undef) 7058 // -> 7059 // concat(VZIP(v1, v2):0, :1) 7060 // 7061 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7062 SDValue SubV1 = V1->getOperand(0); 7063 SDValue SubV2 = V1->getOperand(1); 7064 EVT SubVT = SubV1.getValueType(); 7065 7066 // We expect these to have been canonicalized to -1. 7067 assert(llvm::all_of(ShuffleMask, [&](int i) { 7068 return i < (int)VT.getVectorNumElements(); 7069 }) && "Unexpected shuffle index into UNDEF operand!"); 7070 7071 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7072 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7073 if (isV_UNDEF) 7074 SubV2 = SubV1; 7075 assert((WhichResult == 0) && 7076 "In-place shuffle of concat can only have one result!"); 7077 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7078 SubV1, SubV2); 7079 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7080 Res.getValue(1)); 7081 } 7082 } 7083 } 7084 7085 // If the shuffle is not directly supported and it has 4 elements, use 7086 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7087 unsigned NumElts = VT.getVectorNumElements(); 7088 if (NumElts == 4) { 7089 unsigned PFIndexes[4]; 7090 for (unsigned i = 0; i != 4; ++i) { 7091 if (ShuffleMask[i] < 0) 7092 PFIndexes[i] = 8; 7093 else 7094 PFIndexes[i] = ShuffleMask[i]; 7095 } 7096 7097 // Compute the index in the perfect shuffle table. 7098 unsigned PFTableIndex = 7099 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7100 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7101 unsigned Cost = (PFEntry >> 30); 7102 7103 if (Cost <= 4) 7104 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7105 } 7106 7107 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7108 if (EltSize >= 32) { 7109 // Do the expansion with floating-point types, since that is what the VFP 7110 // registers are defined to use, and since i64 is not legal. 7111 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7112 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7113 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7114 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7115 SmallVector<SDValue, 8> Ops; 7116 for (unsigned i = 0; i < NumElts; ++i) { 7117 if (ShuffleMask[i] < 0) 7118 Ops.push_back(DAG.getUNDEF(EltVT)); 7119 else 7120 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7121 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7122 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7123 dl, MVT::i32))); 7124 } 7125 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7126 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7127 } 7128 7129 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7130 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7131 7132 if (VT == MVT::v8i8) 7133 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7134 return NewOp; 7135 7136 return SDValue(); 7137 } 7138 7139 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7140 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7141 SDValue Lane = Op.getOperand(2); 7142 if (!isa<ConstantSDNode>(Lane)) 7143 return SDValue(); 7144 7145 return Op; 7146 } 7147 7148 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7149 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7150 SDValue Lane = Op.getOperand(1); 7151 if (!isa<ConstantSDNode>(Lane)) 7152 return SDValue(); 7153 7154 SDValue Vec = Op.getOperand(0); 7155 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7156 SDLoc dl(Op); 7157 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7158 } 7159 7160 return Op; 7161 } 7162 7163 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7164 // The only time a CONCAT_VECTORS operation can have legal types is when 7165 // two 64-bit vectors are concatenated to a 128-bit vector. 7166 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7167 "unexpected CONCAT_VECTORS"); 7168 SDLoc dl(Op); 7169 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7170 SDValue Op0 = Op.getOperand(0); 7171 SDValue Op1 = Op.getOperand(1); 7172 if (!Op0.isUndef()) 7173 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7174 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7175 DAG.getIntPtrConstant(0, dl)); 7176 if (!Op1.isUndef()) 7177 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7178 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7179 DAG.getIntPtrConstant(1, dl)); 7180 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7181 } 7182 7183 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7184 /// element has been zero/sign-extended, depending on the isSigned parameter, 7185 /// from an integer type half its size. 7186 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7187 bool isSigned) { 7188 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7189 EVT VT = N->getValueType(0); 7190 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7191 SDNode *BVN = N->getOperand(0).getNode(); 7192 if (BVN->getValueType(0) != MVT::v4i32 || 7193 BVN->getOpcode() != ISD::BUILD_VECTOR) 7194 return false; 7195 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7196 unsigned HiElt = 1 - LoElt; 7197 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7198 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7199 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7200 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7201 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7202 return false; 7203 if (isSigned) { 7204 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7205 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7206 return true; 7207 } else { 7208 if (Hi0->isNullValue() && Hi1->isNullValue()) 7209 return true; 7210 } 7211 return false; 7212 } 7213 7214 if (N->getOpcode() != ISD::BUILD_VECTOR) 7215 return false; 7216 7217 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7218 SDNode *Elt = N->getOperand(i).getNode(); 7219 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7220 unsigned EltSize = VT.getScalarSizeInBits(); 7221 unsigned HalfSize = EltSize / 2; 7222 if (isSigned) { 7223 if (!isIntN(HalfSize, C->getSExtValue())) 7224 return false; 7225 } else { 7226 if (!isUIntN(HalfSize, C->getZExtValue())) 7227 return false; 7228 } 7229 continue; 7230 } 7231 return false; 7232 } 7233 7234 return true; 7235 } 7236 7237 /// isSignExtended - Check if a node is a vector value that is sign-extended 7238 /// or a constant BUILD_VECTOR with sign-extended elements. 7239 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7240 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7241 return true; 7242 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7243 return true; 7244 return false; 7245 } 7246 7247 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7248 /// or a constant BUILD_VECTOR with zero-extended elements. 7249 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7250 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7251 return true; 7252 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7253 return true; 7254 return false; 7255 } 7256 7257 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7258 if (OrigVT.getSizeInBits() >= 64) 7259 return OrigVT; 7260 7261 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7262 7263 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7264 switch (OrigSimpleTy) { 7265 default: llvm_unreachable("Unexpected Vector Type"); 7266 case MVT::v2i8: 7267 case MVT::v2i16: 7268 return MVT::v2i32; 7269 case MVT::v4i8: 7270 return MVT::v4i16; 7271 } 7272 } 7273 7274 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7275 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7276 /// We insert the required extension here to get the vector to fill a D register. 7277 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7278 const EVT &OrigTy, 7279 const EVT &ExtTy, 7280 unsigned ExtOpcode) { 7281 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7282 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7283 // 64-bits we need to insert a new extension so that it will be 64-bits. 7284 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7285 if (OrigTy.getSizeInBits() >= 64) 7286 return N; 7287 7288 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7289 EVT NewVT = getExtensionTo64Bits(OrigTy); 7290 7291 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7292 } 7293 7294 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7295 /// does not do any sign/zero extension. If the original vector is less 7296 /// than 64 bits, an appropriate extension will be added after the load to 7297 /// reach a total size of 64 bits. We have to add the extension separately 7298 /// because ARM does not have a sign/zero extending load for vectors. 7299 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7300 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7301 7302 // The load already has the right type. 7303 if (ExtendedTy == LD->getMemoryVT()) 7304 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7305 LD->getBasePtr(), LD->getPointerInfo(), 7306 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7307 7308 // We need to create a zextload/sextload. We cannot just create a load 7309 // followed by a zext/zext node because LowerMUL is also run during normal 7310 // operation legalization where we can't create illegal types. 7311 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7312 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7313 LD->getMemoryVT(), LD->getAlignment(), 7314 LD->getMemOperand()->getFlags()); 7315 } 7316 7317 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7318 /// extending load, or BUILD_VECTOR with extended elements, return the 7319 /// unextended value. The unextended vector should be 64 bits so that it can 7320 /// be used as an operand to a VMULL instruction. If the original vector size 7321 /// before extension is less than 64 bits we add a an extension to resize 7322 /// the vector to 64 bits. 7323 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7324 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7325 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7326 N->getOperand(0)->getValueType(0), 7327 N->getValueType(0), 7328 N->getOpcode()); 7329 7330 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7331 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7332 "Expected extending load"); 7333 7334 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7335 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7336 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7337 SDValue extLoad = 7338 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7339 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7340 7341 return newLoad; 7342 } 7343 7344 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7345 // have been legalized as a BITCAST from v4i32. 7346 if (N->getOpcode() == ISD::BITCAST) { 7347 SDNode *BVN = N->getOperand(0).getNode(); 7348 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7349 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7350 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7351 return DAG.getBuildVector( 7352 MVT::v2i32, SDLoc(N), 7353 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7354 } 7355 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7356 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7357 EVT VT = N->getValueType(0); 7358 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7359 unsigned NumElts = VT.getVectorNumElements(); 7360 MVT TruncVT = MVT::getIntegerVT(EltSize); 7361 SmallVector<SDValue, 8> Ops; 7362 SDLoc dl(N); 7363 for (unsigned i = 0; i != NumElts; ++i) { 7364 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7365 const APInt &CInt = C->getAPIntValue(); 7366 // Element types smaller than 32 bits are not legal, so use i32 elements. 7367 // The values are implicitly truncated so sext vs. zext doesn't matter. 7368 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7369 } 7370 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7371 } 7372 7373 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7374 unsigned Opcode = N->getOpcode(); 7375 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7376 SDNode *N0 = N->getOperand(0).getNode(); 7377 SDNode *N1 = N->getOperand(1).getNode(); 7378 return N0->hasOneUse() && N1->hasOneUse() && 7379 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7380 } 7381 return false; 7382 } 7383 7384 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7385 unsigned Opcode = N->getOpcode(); 7386 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7387 SDNode *N0 = N->getOperand(0).getNode(); 7388 SDNode *N1 = N->getOperand(1).getNode(); 7389 return N0->hasOneUse() && N1->hasOneUse() && 7390 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7391 } 7392 return false; 7393 } 7394 7395 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7396 // Multiplications are only custom-lowered for 128-bit vectors so that 7397 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7398 EVT VT = Op.getValueType(); 7399 assert(VT.is128BitVector() && VT.isInteger() && 7400 "unexpected type for custom-lowering ISD::MUL"); 7401 SDNode *N0 = Op.getOperand(0).getNode(); 7402 SDNode *N1 = Op.getOperand(1).getNode(); 7403 unsigned NewOpc = 0; 7404 bool isMLA = false; 7405 bool isN0SExt = isSignExtended(N0, DAG); 7406 bool isN1SExt = isSignExtended(N1, DAG); 7407 if (isN0SExt && isN1SExt) 7408 NewOpc = ARMISD::VMULLs; 7409 else { 7410 bool isN0ZExt = isZeroExtended(N0, DAG); 7411 bool isN1ZExt = isZeroExtended(N1, DAG); 7412 if (isN0ZExt && isN1ZExt) 7413 NewOpc = ARMISD::VMULLu; 7414 else if (isN1SExt || isN1ZExt) { 7415 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7416 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7417 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7418 NewOpc = ARMISD::VMULLs; 7419 isMLA = true; 7420 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7421 NewOpc = ARMISD::VMULLu; 7422 isMLA = true; 7423 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7424 std::swap(N0, N1); 7425 NewOpc = ARMISD::VMULLu; 7426 isMLA = true; 7427 } 7428 } 7429 7430 if (!NewOpc) { 7431 if (VT == MVT::v2i64) 7432 // Fall through to expand this. It is not legal. 7433 return SDValue(); 7434 else 7435 // Other vector multiplications are legal. 7436 return Op; 7437 } 7438 } 7439 7440 // Legalize to a VMULL instruction. 7441 SDLoc DL(Op); 7442 SDValue Op0; 7443 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7444 if (!isMLA) { 7445 Op0 = SkipExtensionForVMULL(N0, DAG); 7446 assert(Op0.getValueType().is64BitVector() && 7447 Op1.getValueType().is64BitVector() && 7448 "unexpected types for extended operands to VMULL"); 7449 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7450 } 7451 7452 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7453 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7454 // vmull q0, d4, d6 7455 // vmlal q0, d5, d6 7456 // is faster than 7457 // vaddl q0, d4, d5 7458 // vmovl q1, d6 7459 // vmul q0, q0, q1 7460 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7461 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7462 EVT Op1VT = Op1.getValueType(); 7463 return DAG.getNode(N0->getOpcode(), DL, VT, 7464 DAG.getNode(NewOpc, DL, VT, 7465 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7466 DAG.getNode(NewOpc, DL, VT, 7467 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7468 } 7469 7470 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7471 SelectionDAG &DAG) { 7472 // TODO: Should this propagate fast-math-flags? 7473 7474 // Convert to float 7475 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7476 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7477 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7478 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7479 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7480 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7481 // Get reciprocal estimate. 7482 // float4 recip = vrecpeq_f32(yf); 7483 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7484 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7485 Y); 7486 // Because char has a smaller range than uchar, we can actually get away 7487 // without any newton steps. This requires that we use a weird bias 7488 // of 0xb000, however (again, this has been exhaustively tested). 7489 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7490 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7491 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7492 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7493 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7494 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7495 // Convert back to short. 7496 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7497 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7498 return X; 7499 } 7500 7501 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7502 SelectionDAG &DAG) { 7503 // TODO: Should this propagate fast-math-flags? 7504 7505 SDValue N2; 7506 // Convert to float. 7507 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7508 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7509 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7510 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7511 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7512 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7513 7514 // Use reciprocal estimate and one refinement step. 7515 // float4 recip = vrecpeq_f32(yf); 7516 // recip *= vrecpsq_f32(yf, recip); 7517 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7518 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7519 N1); 7520 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7521 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7522 N1, N2); 7523 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7524 // Because short has a smaller range than ushort, we can actually get away 7525 // with only a single newton step. This requires that we use a weird bias 7526 // of 89, however (again, this has been exhaustively tested). 7527 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7528 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7529 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7530 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7531 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7532 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7533 // Convert back to integer and return. 7534 // return vmovn_s32(vcvt_s32_f32(result)); 7535 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7536 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7537 return N0; 7538 } 7539 7540 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7541 EVT VT = Op.getValueType(); 7542 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7543 "unexpected type for custom-lowering ISD::SDIV"); 7544 7545 SDLoc dl(Op); 7546 SDValue N0 = Op.getOperand(0); 7547 SDValue N1 = Op.getOperand(1); 7548 SDValue N2, N3; 7549 7550 if (VT == MVT::v8i8) { 7551 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7552 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7553 7554 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7555 DAG.getIntPtrConstant(4, dl)); 7556 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7557 DAG.getIntPtrConstant(4, dl)); 7558 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7559 DAG.getIntPtrConstant(0, dl)); 7560 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7561 DAG.getIntPtrConstant(0, dl)); 7562 7563 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7564 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7565 7566 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7567 N0 = LowerCONCAT_VECTORS(N0, DAG); 7568 7569 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7570 return N0; 7571 } 7572 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7573 } 7574 7575 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7576 // TODO: Should this propagate fast-math-flags? 7577 EVT VT = Op.getValueType(); 7578 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7579 "unexpected type for custom-lowering ISD::UDIV"); 7580 7581 SDLoc dl(Op); 7582 SDValue N0 = Op.getOperand(0); 7583 SDValue N1 = Op.getOperand(1); 7584 SDValue N2, N3; 7585 7586 if (VT == MVT::v8i8) { 7587 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7588 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7589 7590 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7591 DAG.getIntPtrConstant(4, dl)); 7592 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7593 DAG.getIntPtrConstant(4, dl)); 7594 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7595 DAG.getIntPtrConstant(0, dl)); 7596 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7597 DAG.getIntPtrConstant(0, dl)); 7598 7599 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7600 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7601 7602 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7603 N0 = LowerCONCAT_VECTORS(N0, DAG); 7604 7605 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7606 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7607 MVT::i32), 7608 N0); 7609 return N0; 7610 } 7611 7612 // v4i16 sdiv ... Convert to float. 7613 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7614 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7615 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7616 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7617 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7618 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7619 7620 // Use reciprocal estimate and two refinement steps. 7621 // float4 recip = vrecpeq_f32(yf); 7622 // recip *= vrecpsq_f32(yf, recip); 7623 // recip *= vrecpsq_f32(yf, recip); 7624 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7625 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7626 BN1); 7627 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7628 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7629 BN1, N2); 7630 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7631 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7632 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7633 BN1, N2); 7634 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7635 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7636 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7637 // and that it will never cause us to return an answer too large). 7638 // float4 result = as_float4(as_int4(xf*recip) + 2); 7639 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7640 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7641 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7642 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7643 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7644 // Convert back to integer and return. 7645 // return vmovn_u32(vcvt_s32_f32(result)); 7646 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7647 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7648 return N0; 7649 } 7650 7651 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7652 SDNode *N = Op.getNode(); 7653 EVT VT = N->getValueType(0); 7654 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7655 7656 SDValue Carry = Op.getOperand(2); 7657 7658 SDLoc DL(Op); 7659 7660 SDValue Result; 7661 if (Op.getOpcode() == ISD::ADDCARRY) { 7662 // This converts the boolean value carry into the carry flag. 7663 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7664 7665 // Do the addition proper using the carry flag we wanted. 7666 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7667 Op.getOperand(1), Carry); 7668 7669 // Now convert the carry flag into a boolean value. 7670 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7671 } else { 7672 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7673 // have to invert the carry first. 7674 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7675 DAG.getConstant(1, DL, MVT::i32), Carry); 7676 // This converts the boolean value carry into the carry flag. 7677 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7678 7679 // Do the subtraction proper using the carry flag we wanted. 7680 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7681 Op.getOperand(1), Carry); 7682 7683 // Now convert the carry flag into a boolean value. 7684 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7685 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7686 // by ISD::SUBCARRY, so compute 1 - C. 7687 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7688 DAG.getConstant(1, DL, MVT::i32), Carry); 7689 } 7690 7691 // Return both values. 7692 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7693 } 7694 7695 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7696 assert(Subtarget->isTargetDarwin()); 7697 7698 // For iOS, we want to call an alternative entry point: __sincos_stret, 7699 // return values are passed via sret. 7700 SDLoc dl(Op); 7701 SDValue Arg = Op.getOperand(0); 7702 EVT ArgVT = Arg.getValueType(); 7703 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7704 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7705 7706 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7707 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7708 7709 // Pair of floats / doubles used to pass the result. 7710 Type *RetTy = StructType::get(ArgTy, ArgTy); 7711 auto &DL = DAG.getDataLayout(); 7712 7713 ArgListTy Args; 7714 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7715 SDValue SRet; 7716 if (ShouldUseSRet) { 7717 // Create stack object for sret. 7718 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7719 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7720 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7721 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7722 7723 ArgListEntry Entry; 7724 Entry.Node = SRet; 7725 Entry.Ty = RetTy->getPointerTo(); 7726 Entry.IsSExt = false; 7727 Entry.IsZExt = false; 7728 Entry.IsSRet = true; 7729 Args.push_back(Entry); 7730 RetTy = Type::getVoidTy(*DAG.getContext()); 7731 } 7732 7733 ArgListEntry Entry; 7734 Entry.Node = Arg; 7735 Entry.Ty = ArgTy; 7736 Entry.IsSExt = false; 7737 Entry.IsZExt = false; 7738 Args.push_back(Entry); 7739 7740 RTLIB::Libcall LC = 7741 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 7742 const char *LibcallName = getLibcallName(LC); 7743 CallingConv::ID CC = getLibcallCallingConv(LC); 7744 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7745 7746 TargetLowering::CallLoweringInfo CLI(DAG); 7747 CLI.setDebugLoc(dl) 7748 .setChain(DAG.getEntryNode()) 7749 .setCallee(CC, RetTy, Callee, std::move(Args)) 7750 .setDiscardResult(ShouldUseSRet); 7751 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7752 7753 if (!ShouldUseSRet) 7754 return CallResult.first; 7755 7756 SDValue LoadSin = 7757 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7758 7759 // Address of cos field. 7760 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7761 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7762 SDValue LoadCos = 7763 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7764 7765 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7766 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7767 LoadSin.getValue(0), LoadCos.getValue(0)); 7768 } 7769 7770 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7771 bool Signed, 7772 SDValue &Chain) const { 7773 EVT VT = Op.getValueType(); 7774 assert((VT == MVT::i32 || VT == MVT::i64) && 7775 "unexpected type for custom lowering DIV"); 7776 SDLoc dl(Op); 7777 7778 const auto &DL = DAG.getDataLayout(); 7779 const auto &TLI = DAG.getTargetLoweringInfo(); 7780 7781 const char *Name = nullptr; 7782 if (Signed) 7783 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7784 else 7785 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7786 7787 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7788 7789 ARMTargetLowering::ArgListTy Args; 7790 7791 for (auto AI : {1, 0}) { 7792 ArgListEntry Arg; 7793 Arg.Node = Op.getOperand(AI); 7794 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7795 Args.push_back(Arg); 7796 } 7797 7798 CallLoweringInfo CLI(DAG); 7799 CLI.setDebugLoc(dl) 7800 .setChain(Chain) 7801 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7802 ES, std::move(Args)); 7803 7804 return LowerCallTo(CLI).first; 7805 } 7806 7807 // This is a code size optimisation: return the original SDIV node to 7808 // DAGCombiner when we don't want to expand SDIV into a sequence of 7809 // instructions, and an empty node otherwise which will cause the 7810 // SDIV to be expanded in DAGCombine. 7811 SDValue 7812 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 7813 SelectionDAG &DAG, 7814 SmallVectorImpl<SDNode *> &Created) const { 7815 // TODO: Support SREM 7816 if (N->getOpcode() != ISD::SDIV) 7817 return SDValue(); 7818 7819 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 7820 const bool MinSize = ST.hasMinSize(); 7821 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 7822 : ST.hasDivideInARMMode(); 7823 7824 // Don't touch vector types; rewriting this may lead to scalarizing 7825 // the int divs. 7826 if (N->getOperand(0).getValueType().isVector()) 7827 return SDValue(); 7828 7829 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 7830 // hwdiv support for this to be really profitable. 7831 if (!(MinSize && HasDivide)) 7832 return SDValue(); 7833 7834 // ARM mode is a bit simpler than Thumb: we can handle large power 7835 // of 2 immediates with 1 mov instruction; no further checks required, 7836 // just return the sdiv node. 7837 if (!ST.isThumb()) 7838 return SDValue(N, 0); 7839 7840 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 7841 // and thus lose the code size benefits of a MOVS that requires only 2. 7842 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 7843 // but as it's doing exactly this, it's not worth the trouble to get TTI. 7844 if (Divisor.sgt(128)) 7845 return SDValue(); 7846 7847 return SDValue(N, 0); 7848 } 7849 7850 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7851 bool Signed) const { 7852 assert(Op.getValueType() == MVT::i32 && 7853 "unexpected type for custom lowering DIV"); 7854 SDLoc dl(Op); 7855 7856 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7857 DAG.getEntryNode(), Op.getOperand(1)); 7858 7859 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7860 } 7861 7862 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7863 SDLoc DL(N); 7864 SDValue Op = N->getOperand(1); 7865 if (N->getValueType(0) == MVT::i32) 7866 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7867 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7868 DAG.getConstant(0, DL, MVT::i32)); 7869 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7870 DAG.getConstant(1, DL, MVT::i32)); 7871 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7872 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7873 } 7874 7875 void ARMTargetLowering::ExpandDIV_Windows( 7876 SDValue Op, SelectionDAG &DAG, bool Signed, 7877 SmallVectorImpl<SDValue> &Results) const { 7878 const auto &DL = DAG.getDataLayout(); 7879 const auto &TLI = DAG.getTargetLoweringInfo(); 7880 7881 assert(Op.getValueType() == MVT::i64 && 7882 "unexpected type for custom lowering DIV"); 7883 SDLoc dl(Op); 7884 7885 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7886 7887 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7888 7889 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7890 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7891 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7892 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7893 7894 Results.push_back(Lower); 7895 Results.push_back(Upper); 7896 } 7897 7898 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7899 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7900 // Acquire/Release load/store is not legal for targets without a dmb or 7901 // equivalent available. 7902 return SDValue(); 7903 7904 // Monotonic load/store is legal for all targets. 7905 return Op; 7906 } 7907 7908 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7909 SmallVectorImpl<SDValue> &Results, 7910 SelectionDAG &DAG, 7911 const ARMSubtarget *Subtarget) { 7912 SDLoc DL(N); 7913 // Under Power Management extensions, the cycle-count is: 7914 // mrc p15, #0, <Rt>, c9, c13, #0 7915 SDValue Ops[] = { N->getOperand(0), // Chain 7916 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7917 DAG.getConstant(15, DL, MVT::i32), 7918 DAG.getConstant(0, DL, MVT::i32), 7919 DAG.getConstant(9, DL, MVT::i32), 7920 DAG.getConstant(13, DL, MVT::i32), 7921 DAG.getConstant(0, DL, MVT::i32) 7922 }; 7923 7924 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7925 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7926 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7927 DAG.getConstant(0, DL, MVT::i32))); 7928 Results.push_back(Cycles32.getValue(1)); 7929 } 7930 7931 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7932 SDLoc dl(V.getNode()); 7933 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7934 SDValue VHi = DAG.getAnyExtOrTrunc( 7935 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7936 dl, MVT::i32); 7937 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7938 if (isBigEndian) 7939 std::swap (VLo, VHi); 7940 SDValue RegClass = 7941 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7942 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7943 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7944 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7945 return SDValue( 7946 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7947 } 7948 7949 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7950 SmallVectorImpl<SDValue> & Results, 7951 SelectionDAG &DAG) { 7952 assert(N->getValueType(0) == MVT::i64 && 7953 "AtomicCmpSwap on types less than 64 should be legal"); 7954 SDValue Ops[] = {N->getOperand(1), 7955 createGPRPairNode(DAG, N->getOperand(2)), 7956 createGPRPairNode(DAG, N->getOperand(3)), 7957 N->getOperand(0)}; 7958 SDNode *CmpSwap = DAG.getMachineNode( 7959 ARM::CMP_SWAP_64, SDLoc(N), 7960 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7961 7962 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 7963 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 7964 7965 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7966 7967 Results.push_back( 7968 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 7969 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7970 Results.push_back( 7971 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 7972 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7973 Results.push_back(SDValue(CmpSwap, 2)); 7974 } 7975 7976 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7977 SelectionDAG &DAG) { 7978 const auto &TLI = DAG.getTargetLoweringInfo(); 7979 7980 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7981 "Custom lowering is MSVCRT specific!"); 7982 7983 SDLoc dl(Op); 7984 SDValue Val = Op.getOperand(0); 7985 MVT Ty = Val->getSimpleValueType(0); 7986 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7987 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7988 TLI.getPointerTy(DAG.getDataLayout())); 7989 7990 TargetLowering::ArgListTy Args; 7991 TargetLowering::ArgListEntry Entry; 7992 7993 Entry.Node = Val; 7994 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7995 Entry.IsZExt = true; 7996 Args.push_back(Entry); 7997 7998 Entry.Node = Exponent; 7999 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 8000 Entry.IsZExt = true; 8001 Args.push_back(Entry); 8002 8003 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8004 8005 // In the in-chain to the call is the entry node If we are emitting a 8006 // tailcall, the chain will be mutated if the node has a non-entry input 8007 // chain. 8008 SDValue InChain = DAG.getEntryNode(); 8009 SDValue TCChain = InChain; 8010 8011 const Function &F = DAG.getMachineFunction().getFunction(); 8012 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8013 F.getReturnType() == LCRTy; 8014 if (IsTC) 8015 InChain = TCChain; 8016 8017 TargetLowering::CallLoweringInfo CLI(DAG); 8018 CLI.setDebugLoc(dl) 8019 .setChain(InChain) 8020 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8021 .setTailCall(IsTC); 8022 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8023 8024 // Return the chain (the DAG root) if it is a tail call 8025 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8026 } 8027 8028 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8029 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8030 switch (Op.getOpcode()) { 8031 default: llvm_unreachable("Don't know how to custom lower this!"); 8032 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8033 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8034 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8035 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8036 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8037 case ISD::SELECT: return LowerSELECT(Op, DAG); 8038 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8039 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8040 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8041 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8042 case ISD::VASTART: return LowerVASTART(Op, DAG); 8043 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8044 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8045 case ISD::SINT_TO_FP: 8046 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8047 case ISD::FP_TO_SINT: 8048 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8049 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8050 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8051 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8052 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8053 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8054 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8055 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8056 Subtarget); 8057 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8058 case ISD::SHL: 8059 case ISD::SRL: 8060 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8061 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8062 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8063 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8064 case ISD::SRL_PARTS: 8065 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8066 case ISD::CTTZ: 8067 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8068 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8069 case ISD::SETCC: return LowerVSETCC(Op, DAG); 8070 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8071 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8072 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8073 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 8074 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8075 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8076 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 8077 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8078 case ISD::MUL: return LowerMUL(Op, DAG); 8079 case ISD::SDIV: 8080 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8081 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8082 return LowerSDIV(Op, DAG); 8083 case ISD::UDIV: 8084 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8085 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8086 return LowerUDIV(Op, DAG); 8087 case ISD::ADDCARRY: 8088 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8089 case ISD::SADDO: 8090 case ISD::SSUBO: 8091 return LowerSignedALUO(Op, DAG); 8092 case ISD::UADDO: 8093 case ISD::USUBO: 8094 return LowerUnsignedALUO(Op, DAG); 8095 case ISD::ATOMIC_LOAD: 8096 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8097 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8098 case ISD::SDIVREM: 8099 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8100 case ISD::DYNAMIC_STACKALLOC: 8101 if (Subtarget->isTargetWindows()) 8102 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8103 llvm_unreachable("Don't know how to custom lower this!"); 8104 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8105 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8106 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8107 case ARMISD::WIN__DBZCHK: return SDValue(); 8108 } 8109 } 8110 8111 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8112 SelectionDAG &DAG) { 8113 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8114 unsigned Opc = 0; 8115 if (IntNo == Intrinsic::arm_smlald) 8116 Opc = ARMISD::SMLALD; 8117 else if (IntNo == Intrinsic::arm_smlaldx) 8118 Opc = ARMISD::SMLALDX; 8119 else if (IntNo == Intrinsic::arm_smlsld) 8120 Opc = ARMISD::SMLSLD; 8121 else if (IntNo == Intrinsic::arm_smlsldx) 8122 Opc = ARMISD::SMLSLDX; 8123 else 8124 return; 8125 8126 SDLoc dl(N); 8127 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8128 N->getOperand(3), 8129 DAG.getConstant(0, dl, MVT::i32)); 8130 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8131 N->getOperand(3), 8132 DAG.getConstant(1, dl, MVT::i32)); 8133 8134 SDValue LongMul = DAG.getNode(Opc, dl, 8135 DAG.getVTList(MVT::i32, MVT::i32), 8136 N->getOperand(1), N->getOperand(2), 8137 Lo, Hi); 8138 Results.push_back(LongMul.getValue(0)); 8139 Results.push_back(LongMul.getValue(1)); 8140 } 8141 8142 /// ReplaceNodeResults - Replace the results of node with an illegal result 8143 /// type with new values built out of custom code. 8144 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8145 SmallVectorImpl<SDValue> &Results, 8146 SelectionDAG &DAG) const { 8147 SDValue Res; 8148 switch (N->getOpcode()) { 8149 default: 8150 llvm_unreachable("Don't know how to custom expand this!"); 8151 case ISD::READ_REGISTER: 8152 ExpandREAD_REGISTER(N, Results, DAG); 8153 break; 8154 case ISD::BITCAST: 8155 Res = ExpandBITCAST(N, DAG, Subtarget); 8156 break; 8157 case ISD::SRL: 8158 case ISD::SRA: 8159 Res = Expand64BitShift(N, DAG, Subtarget); 8160 break; 8161 case ISD::SREM: 8162 case ISD::UREM: 8163 Res = LowerREM(N, DAG); 8164 break; 8165 case ISD::SDIVREM: 8166 case ISD::UDIVREM: 8167 Res = LowerDivRem(SDValue(N, 0), DAG); 8168 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8169 Results.push_back(Res.getValue(0)); 8170 Results.push_back(Res.getValue(1)); 8171 return; 8172 case ISD::READCYCLECOUNTER: 8173 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8174 return; 8175 case ISD::UDIV: 8176 case ISD::SDIV: 8177 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8178 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8179 Results); 8180 case ISD::ATOMIC_CMP_SWAP: 8181 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8182 return; 8183 case ISD::INTRINSIC_WO_CHAIN: 8184 return ReplaceLongIntrinsic(N, Results, DAG); 8185 case ISD::ABS: 8186 lowerABS(N, Results, DAG); 8187 return ; 8188 8189 } 8190 if (Res.getNode()) 8191 Results.push_back(Res); 8192 } 8193 8194 //===----------------------------------------------------------------------===// 8195 // ARM Scheduler Hooks 8196 //===----------------------------------------------------------------------===// 8197 8198 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8199 /// registers the function context. 8200 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8201 MachineBasicBlock *MBB, 8202 MachineBasicBlock *DispatchBB, 8203 int FI) const { 8204 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8205 "ROPI/RWPI not currently supported with SjLj"); 8206 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8207 DebugLoc dl = MI.getDebugLoc(); 8208 MachineFunction *MF = MBB->getParent(); 8209 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8210 MachineConstantPool *MCP = MF->getConstantPool(); 8211 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8212 const Function &F = MF->getFunction(); 8213 8214 bool isThumb = Subtarget->isThumb(); 8215 bool isThumb2 = Subtarget->isThumb2(); 8216 8217 unsigned PCLabelId = AFI->createPICLabelUId(); 8218 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8219 ARMConstantPoolValue *CPV = 8220 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8221 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8222 8223 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8224 : &ARM::GPRRegClass; 8225 8226 // Grab constant pool and fixed stack memory operands. 8227 MachineMemOperand *CPMMO = 8228 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8229 MachineMemOperand::MOLoad, 4, 4); 8230 8231 MachineMemOperand *FIMMOSt = 8232 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8233 MachineMemOperand::MOStore, 4, 4); 8234 8235 // Load the address of the dispatch MBB into the jump buffer. 8236 if (isThumb2) { 8237 // Incoming value: jbuf 8238 // ldr.n r5, LCPI1_1 8239 // orr r5, r5, #1 8240 // add r5, pc 8241 // str r5, [$jbuf, #+4] ; &jbuf[1] 8242 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8243 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8244 .addConstantPoolIndex(CPI) 8245 .addMemOperand(CPMMO) 8246 .add(predOps(ARMCC::AL)); 8247 // Set the low bit because of thumb mode. 8248 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8249 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8250 .addReg(NewVReg1, RegState::Kill) 8251 .addImm(0x01) 8252 .add(predOps(ARMCC::AL)) 8253 .add(condCodeOp()); 8254 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8255 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8256 .addReg(NewVReg2, RegState::Kill) 8257 .addImm(PCLabelId); 8258 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8259 .addReg(NewVReg3, RegState::Kill) 8260 .addFrameIndex(FI) 8261 .addImm(36) // &jbuf[1] :: pc 8262 .addMemOperand(FIMMOSt) 8263 .add(predOps(ARMCC::AL)); 8264 } else if (isThumb) { 8265 // Incoming value: jbuf 8266 // ldr.n r1, LCPI1_4 8267 // add r1, pc 8268 // mov r2, #1 8269 // orrs r1, r2 8270 // add r2, $jbuf, #+4 ; &jbuf[1] 8271 // str r1, [r2] 8272 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8273 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8274 .addConstantPoolIndex(CPI) 8275 .addMemOperand(CPMMO) 8276 .add(predOps(ARMCC::AL)); 8277 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8278 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8279 .addReg(NewVReg1, RegState::Kill) 8280 .addImm(PCLabelId); 8281 // Set the low bit because of thumb mode. 8282 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8283 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8284 .addReg(ARM::CPSR, RegState::Define) 8285 .addImm(1) 8286 .add(predOps(ARMCC::AL)); 8287 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8288 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8289 .addReg(ARM::CPSR, RegState::Define) 8290 .addReg(NewVReg2, RegState::Kill) 8291 .addReg(NewVReg3, RegState::Kill) 8292 .add(predOps(ARMCC::AL)); 8293 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8294 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8295 .addFrameIndex(FI) 8296 .addImm(36); // &jbuf[1] :: pc 8297 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8298 .addReg(NewVReg4, RegState::Kill) 8299 .addReg(NewVReg5, RegState::Kill) 8300 .addImm(0) 8301 .addMemOperand(FIMMOSt) 8302 .add(predOps(ARMCC::AL)); 8303 } else { 8304 // Incoming value: jbuf 8305 // ldr r1, LCPI1_1 8306 // add r1, pc, r1 8307 // str r1, [$jbuf, #+4] ; &jbuf[1] 8308 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8309 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8310 .addConstantPoolIndex(CPI) 8311 .addImm(0) 8312 .addMemOperand(CPMMO) 8313 .add(predOps(ARMCC::AL)); 8314 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8315 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8316 .addReg(NewVReg1, RegState::Kill) 8317 .addImm(PCLabelId) 8318 .add(predOps(ARMCC::AL)); 8319 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8320 .addReg(NewVReg2, RegState::Kill) 8321 .addFrameIndex(FI) 8322 .addImm(36) // &jbuf[1] :: pc 8323 .addMemOperand(FIMMOSt) 8324 .add(predOps(ARMCC::AL)); 8325 } 8326 } 8327 8328 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8329 MachineBasicBlock *MBB) const { 8330 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8331 DebugLoc dl = MI.getDebugLoc(); 8332 MachineFunction *MF = MBB->getParent(); 8333 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8334 MachineFrameInfo &MFI = MF->getFrameInfo(); 8335 int FI = MFI.getFunctionContextIndex(); 8336 8337 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8338 : &ARM::GPRnopcRegClass; 8339 8340 // Get a mapping of the call site numbers to all of the landing pads they're 8341 // associated with. 8342 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8343 unsigned MaxCSNum = 0; 8344 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8345 ++BB) { 8346 if (!BB->isEHPad()) continue; 8347 8348 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8349 // pad. 8350 for (MachineBasicBlock::iterator 8351 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8352 if (!II->isEHLabel()) continue; 8353 8354 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8355 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8356 8357 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8358 for (SmallVectorImpl<unsigned>::iterator 8359 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8360 CSI != CSE; ++CSI) { 8361 CallSiteNumToLPad[*CSI].push_back(&*BB); 8362 MaxCSNum = std::max(MaxCSNum, *CSI); 8363 } 8364 break; 8365 } 8366 } 8367 8368 // Get an ordered list of the machine basic blocks for the jump table. 8369 std::vector<MachineBasicBlock*> LPadList; 8370 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8371 LPadList.reserve(CallSiteNumToLPad.size()); 8372 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8373 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8374 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8375 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8376 LPadList.push_back(*II); 8377 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8378 } 8379 } 8380 8381 assert(!LPadList.empty() && 8382 "No landing pad destinations for the dispatch jump table!"); 8383 8384 // Create the jump table and associated information. 8385 MachineJumpTableInfo *JTI = 8386 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8387 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8388 8389 // Create the MBBs for the dispatch code. 8390 8391 // Shove the dispatch's address into the return slot in the function context. 8392 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8393 DispatchBB->setIsEHPad(); 8394 8395 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8396 unsigned trap_opcode; 8397 if (Subtarget->isThumb()) 8398 trap_opcode = ARM::tTRAP; 8399 else 8400 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8401 8402 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8403 DispatchBB->addSuccessor(TrapBB); 8404 8405 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8406 DispatchBB->addSuccessor(DispContBB); 8407 8408 // Insert and MBBs. 8409 MF->insert(MF->end(), DispatchBB); 8410 MF->insert(MF->end(), DispContBB); 8411 MF->insert(MF->end(), TrapBB); 8412 8413 // Insert code into the entry block that creates and registers the function 8414 // context. 8415 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8416 8417 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8418 MachinePointerInfo::getFixedStack(*MF, FI), 8419 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8420 8421 MachineInstrBuilder MIB; 8422 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8423 8424 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8425 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8426 8427 // Add a register mask with no preserved registers. This results in all 8428 // registers being marked as clobbered. This can't work if the dispatch block 8429 // is in a Thumb1 function and is linked with ARM code which uses the FP 8430 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8431 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8432 8433 bool IsPositionIndependent = isPositionIndependent(); 8434 unsigned NumLPads = LPadList.size(); 8435 if (Subtarget->isThumb2()) { 8436 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8437 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8438 .addFrameIndex(FI) 8439 .addImm(4) 8440 .addMemOperand(FIMMOLd) 8441 .add(predOps(ARMCC::AL)); 8442 8443 if (NumLPads < 256) { 8444 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8445 .addReg(NewVReg1) 8446 .addImm(LPadList.size()) 8447 .add(predOps(ARMCC::AL)); 8448 } else { 8449 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8450 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8451 .addImm(NumLPads & 0xFFFF) 8452 .add(predOps(ARMCC::AL)); 8453 8454 unsigned VReg2 = VReg1; 8455 if ((NumLPads & 0xFFFF0000) != 0) { 8456 VReg2 = MRI->createVirtualRegister(TRC); 8457 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8458 .addReg(VReg1) 8459 .addImm(NumLPads >> 16) 8460 .add(predOps(ARMCC::AL)); 8461 } 8462 8463 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8464 .addReg(NewVReg1) 8465 .addReg(VReg2) 8466 .add(predOps(ARMCC::AL)); 8467 } 8468 8469 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8470 .addMBB(TrapBB) 8471 .addImm(ARMCC::HI) 8472 .addReg(ARM::CPSR); 8473 8474 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8475 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8476 .addJumpTableIndex(MJTI) 8477 .add(predOps(ARMCC::AL)); 8478 8479 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8480 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8481 .addReg(NewVReg3, RegState::Kill) 8482 .addReg(NewVReg1) 8483 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8484 .add(predOps(ARMCC::AL)) 8485 .add(condCodeOp()); 8486 8487 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8488 .addReg(NewVReg4, RegState::Kill) 8489 .addReg(NewVReg1) 8490 .addJumpTableIndex(MJTI); 8491 } else if (Subtarget->isThumb()) { 8492 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8493 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8494 .addFrameIndex(FI) 8495 .addImm(1) 8496 .addMemOperand(FIMMOLd) 8497 .add(predOps(ARMCC::AL)); 8498 8499 if (NumLPads < 256) { 8500 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8501 .addReg(NewVReg1) 8502 .addImm(NumLPads) 8503 .add(predOps(ARMCC::AL)); 8504 } else { 8505 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8506 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8507 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8508 8509 // MachineConstantPool wants an explicit alignment. 8510 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8511 if (Align == 0) 8512 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8513 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8514 8515 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8516 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8517 .addReg(VReg1, RegState::Define) 8518 .addConstantPoolIndex(Idx) 8519 .add(predOps(ARMCC::AL)); 8520 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8521 .addReg(NewVReg1) 8522 .addReg(VReg1) 8523 .add(predOps(ARMCC::AL)); 8524 } 8525 8526 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8527 .addMBB(TrapBB) 8528 .addImm(ARMCC::HI) 8529 .addReg(ARM::CPSR); 8530 8531 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8532 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8533 .addReg(ARM::CPSR, RegState::Define) 8534 .addReg(NewVReg1) 8535 .addImm(2) 8536 .add(predOps(ARMCC::AL)); 8537 8538 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8539 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8540 .addJumpTableIndex(MJTI) 8541 .add(predOps(ARMCC::AL)); 8542 8543 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8544 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8545 .addReg(ARM::CPSR, RegState::Define) 8546 .addReg(NewVReg2, RegState::Kill) 8547 .addReg(NewVReg3) 8548 .add(predOps(ARMCC::AL)); 8549 8550 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8551 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8552 8553 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8554 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8555 .addReg(NewVReg4, RegState::Kill) 8556 .addImm(0) 8557 .addMemOperand(JTMMOLd) 8558 .add(predOps(ARMCC::AL)); 8559 8560 unsigned NewVReg6 = NewVReg5; 8561 if (IsPositionIndependent) { 8562 NewVReg6 = MRI->createVirtualRegister(TRC); 8563 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8564 .addReg(ARM::CPSR, RegState::Define) 8565 .addReg(NewVReg5, RegState::Kill) 8566 .addReg(NewVReg3) 8567 .add(predOps(ARMCC::AL)); 8568 } 8569 8570 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8571 .addReg(NewVReg6, RegState::Kill) 8572 .addJumpTableIndex(MJTI); 8573 } else { 8574 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8575 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8576 .addFrameIndex(FI) 8577 .addImm(4) 8578 .addMemOperand(FIMMOLd) 8579 .add(predOps(ARMCC::AL)); 8580 8581 if (NumLPads < 256) { 8582 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8583 .addReg(NewVReg1) 8584 .addImm(NumLPads) 8585 .add(predOps(ARMCC::AL)); 8586 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8587 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8588 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8589 .addImm(NumLPads & 0xFFFF) 8590 .add(predOps(ARMCC::AL)); 8591 8592 unsigned VReg2 = VReg1; 8593 if ((NumLPads & 0xFFFF0000) != 0) { 8594 VReg2 = MRI->createVirtualRegister(TRC); 8595 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8596 .addReg(VReg1) 8597 .addImm(NumLPads >> 16) 8598 .add(predOps(ARMCC::AL)); 8599 } 8600 8601 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8602 .addReg(NewVReg1) 8603 .addReg(VReg2) 8604 .add(predOps(ARMCC::AL)); 8605 } else { 8606 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8607 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8608 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8609 8610 // MachineConstantPool wants an explicit alignment. 8611 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8612 if (Align == 0) 8613 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8614 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8615 8616 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8617 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8618 .addReg(VReg1, RegState::Define) 8619 .addConstantPoolIndex(Idx) 8620 .addImm(0) 8621 .add(predOps(ARMCC::AL)); 8622 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8623 .addReg(NewVReg1) 8624 .addReg(VReg1, RegState::Kill) 8625 .add(predOps(ARMCC::AL)); 8626 } 8627 8628 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8629 .addMBB(TrapBB) 8630 .addImm(ARMCC::HI) 8631 .addReg(ARM::CPSR); 8632 8633 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8634 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8635 .addReg(NewVReg1) 8636 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8637 .add(predOps(ARMCC::AL)) 8638 .add(condCodeOp()); 8639 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8640 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8641 .addJumpTableIndex(MJTI) 8642 .add(predOps(ARMCC::AL)); 8643 8644 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8645 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8646 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8647 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8648 .addReg(NewVReg3, RegState::Kill) 8649 .addReg(NewVReg4) 8650 .addImm(0) 8651 .addMemOperand(JTMMOLd) 8652 .add(predOps(ARMCC::AL)); 8653 8654 if (IsPositionIndependent) { 8655 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8656 .addReg(NewVReg5, RegState::Kill) 8657 .addReg(NewVReg4) 8658 .addJumpTableIndex(MJTI); 8659 } else { 8660 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8661 .addReg(NewVReg5, RegState::Kill) 8662 .addJumpTableIndex(MJTI); 8663 } 8664 } 8665 8666 // Add the jump table entries as successors to the MBB. 8667 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8668 for (std::vector<MachineBasicBlock*>::iterator 8669 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8670 MachineBasicBlock *CurMBB = *I; 8671 if (SeenMBBs.insert(CurMBB).second) 8672 DispContBB->addSuccessor(CurMBB); 8673 } 8674 8675 // N.B. the order the invoke BBs are processed in doesn't matter here. 8676 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8677 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8678 for (MachineBasicBlock *BB : InvokeBBs) { 8679 8680 // Remove the landing pad successor from the invoke block and replace it 8681 // with the new dispatch block. 8682 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8683 BB->succ_end()); 8684 while (!Successors.empty()) { 8685 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8686 if (SMBB->isEHPad()) { 8687 BB->removeSuccessor(SMBB); 8688 MBBLPads.push_back(SMBB); 8689 } 8690 } 8691 8692 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8693 BB->normalizeSuccProbs(); 8694 8695 // Find the invoke call and mark all of the callee-saved registers as 8696 // 'implicit defined' so that they're spilled. This prevents code from 8697 // moving instructions to before the EH block, where they will never be 8698 // executed. 8699 for (MachineBasicBlock::reverse_iterator 8700 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8701 if (!II->isCall()) continue; 8702 8703 DenseMap<unsigned, bool> DefRegs; 8704 for (MachineInstr::mop_iterator 8705 OI = II->operands_begin(), OE = II->operands_end(); 8706 OI != OE; ++OI) { 8707 if (!OI->isReg()) continue; 8708 DefRegs[OI->getReg()] = true; 8709 } 8710 8711 MachineInstrBuilder MIB(*MF, &*II); 8712 8713 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8714 unsigned Reg = SavedRegs[i]; 8715 if (Subtarget->isThumb2() && 8716 !ARM::tGPRRegClass.contains(Reg) && 8717 !ARM::hGPRRegClass.contains(Reg)) 8718 continue; 8719 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8720 continue; 8721 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8722 continue; 8723 if (!DefRegs[Reg]) 8724 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8725 } 8726 8727 break; 8728 } 8729 } 8730 8731 // Mark all former landing pads as non-landing pads. The dispatch is the only 8732 // landing pad now. 8733 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8734 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8735 (*I)->setIsEHPad(false); 8736 8737 // The instruction is gone now. 8738 MI.eraseFromParent(); 8739 } 8740 8741 static 8742 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8743 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8744 E = MBB->succ_end(); I != E; ++I) 8745 if (*I != Succ) 8746 return *I; 8747 llvm_unreachable("Expecting a BB with two successors!"); 8748 } 8749 8750 /// Return the load opcode for a given load size. If load size >= 8, 8751 /// neon opcode will be returned. 8752 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8753 if (LdSize >= 8) 8754 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8755 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8756 if (IsThumb1) 8757 return LdSize == 4 ? ARM::tLDRi 8758 : LdSize == 2 ? ARM::tLDRHi 8759 : LdSize == 1 ? ARM::tLDRBi : 0; 8760 if (IsThumb2) 8761 return LdSize == 4 ? ARM::t2LDR_POST 8762 : LdSize == 2 ? ARM::t2LDRH_POST 8763 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8764 return LdSize == 4 ? ARM::LDR_POST_IMM 8765 : LdSize == 2 ? ARM::LDRH_POST 8766 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8767 } 8768 8769 /// Return the store opcode for a given store size. If store size >= 8, 8770 /// neon opcode will be returned. 8771 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8772 if (StSize >= 8) 8773 return StSize == 16 ? ARM::VST1q32wb_fixed 8774 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8775 if (IsThumb1) 8776 return StSize == 4 ? ARM::tSTRi 8777 : StSize == 2 ? ARM::tSTRHi 8778 : StSize == 1 ? ARM::tSTRBi : 0; 8779 if (IsThumb2) 8780 return StSize == 4 ? ARM::t2STR_POST 8781 : StSize == 2 ? ARM::t2STRH_POST 8782 : StSize == 1 ? ARM::t2STRB_POST : 0; 8783 return StSize == 4 ? ARM::STR_POST_IMM 8784 : StSize == 2 ? ARM::STRH_POST 8785 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8786 } 8787 8788 /// Emit a post-increment load operation with given size. The instructions 8789 /// will be added to BB at Pos. 8790 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8791 const TargetInstrInfo *TII, const DebugLoc &dl, 8792 unsigned LdSize, unsigned Data, unsigned AddrIn, 8793 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8794 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8795 assert(LdOpc != 0 && "Should have a load opcode"); 8796 if (LdSize >= 8) { 8797 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8798 .addReg(AddrOut, RegState::Define) 8799 .addReg(AddrIn) 8800 .addImm(0) 8801 .add(predOps(ARMCC::AL)); 8802 } else if (IsThumb1) { 8803 // load + update AddrIn 8804 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8805 .addReg(AddrIn) 8806 .addImm(0) 8807 .add(predOps(ARMCC::AL)); 8808 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8809 .add(t1CondCodeOp()) 8810 .addReg(AddrIn) 8811 .addImm(LdSize) 8812 .add(predOps(ARMCC::AL)); 8813 } else if (IsThumb2) { 8814 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8815 .addReg(AddrOut, RegState::Define) 8816 .addReg(AddrIn) 8817 .addImm(LdSize) 8818 .add(predOps(ARMCC::AL)); 8819 } else { // arm 8820 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8821 .addReg(AddrOut, RegState::Define) 8822 .addReg(AddrIn) 8823 .addReg(0) 8824 .addImm(LdSize) 8825 .add(predOps(ARMCC::AL)); 8826 } 8827 } 8828 8829 /// Emit a post-increment store operation with given size. The instructions 8830 /// will be added to BB at Pos. 8831 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8832 const TargetInstrInfo *TII, const DebugLoc &dl, 8833 unsigned StSize, unsigned Data, unsigned AddrIn, 8834 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8835 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8836 assert(StOpc != 0 && "Should have a store opcode"); 8837 if (StSize >= 8) { 8838 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8839 .addReg(AddrIn) 8840 .addImm(0) 8841 .addReg(Data) 8842 .add(predOps(ARMCC::AL)); 8843 } else if (IsThumb1) { 8844 // store + update AddrIn 8845 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8846 .addReg(Data) 8847 .addReg(AddrIn) 8848 .addImm(0) 8849 .add(predOps(ARMCC::AL)); 8850 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8851 .add(t1CondCodeOp()) 8852 .addReg(AddrIn) 8853 .addImm(StSize) 8854 .add(predOps(ARMCC::AL)); 8855 } else if (IsThumb2) { 8856 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8857 .addReg(Data) 8858 .addReg(AddrIn) 8859 .addImm(StSize) 8860 .add(predOps(ARMCC::AL)); 8861 } else { // arm 8862 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8863 .addReg(Data) 8864 .addReg(AddrIn) 8865 .addReg(0) 8866 .addImm(StSize) 8867 .add(predOps(ARMCC::AL)); 8868 } 8869 } 8870 8871 MachineBasicBlock * 8872 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8873 MachineBasicBlock *BB) const { 8874 // This pseudo instruction has 3 operands: dst, src, size 8875 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8876 // Otherwise, we will generate unrolled scalar copies. 8877 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8878 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8879 MachineFunction::iterator It = ++BB->getIterator(); 8880 8881 unsigned dest = MI.getOperand(0).getReg(); 8882 unsigned src = MI.getOperand(1).getReg(); 8883 unsigned SizeVal = MI.getOperand(2).getImm(); 8884 unsigned Align = MI.getOperand(3).getImm(); 8885 DebugLoc dl = MI.getDebugLoc(); 8886 8887 MachineFunction *MF = BB->getParent(); 8888 MachineRegisterInfo &MRI = MF->getRegInfo(); 8889 unsigned UnitSize = 0; 8890 const TargetRegisterClass *TRC = nullptr; 8891 const TargetRegisterClass *VecTRC = nullptr; 8892 8893 bool IsThumb1 = Subtarget->isThumb1Only(); 8894 bool IsThumb2 = Subtarget->isThumb2(); 8895 bool IsThumb = Subtarget->isThumb(); 8896 8897 if (Align & 1) { 8898 UnitSize = 1; 8899 } else if (Align & 2) { 8900 UnitSize = 2; 8901 } else { 8902 // Check whether we can use NEON instructions. 8903 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 8904 Subtarget->hasNEON()) { 8905 if ((Align % 16 == 0) && SizeVal >= 16) 8906 UnitSize = 16; 8907 else if ((Align % 8 == 0) && SizeVal >= 8) 8908 UnitSize = 8; 8909 } 8910 // Can't use NEON instructions. 8911 if (UnitSize == 0) 8912 UnitSize = 4; 8913 } 8914 8915 // Select the correct opcode and register class for unit size load/store 8916 bool IsNeon = UnitSize >= 8; 8917 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8918 if (IsNeon) 8919 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8920 : UnitSize == 8 ? &ARM::DPRRegClass 8921 : nullptr; 8922 8923 unsigned BytesLeft = SizeVal % UnitSize; 8924 unsigned LoopSize = SizeVal - BytesLeft; 8925 8926 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8927 // Use LDR and STR to copy. 8928 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8929 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8930 unsigned srcIn = src; 8931 unsigned destIn = dest; 8932 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8933 unsigned srcOut = MRI.createVirtualRegister(TRC); 8934 unsigned destOut = MRI.createVirtualRegister(TRC); 8935 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8936 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8937 IsThumb1, IsThumb2); 8938 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8939 IsThumb1, IsThumb2); 8940 srcIn = srcOut; 8941 destIn = destOut; 8942 } 8943 8944 // Handle the leftover bytes with LDRB and STRB. 8945 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8946 // [destOut] = STRB_POST(scratch, destIn, 1) 8947 for (unsigned i = 0; i < BytesLeft; i++) { 8948 unsigned srcOut = MRI.createVirtualRegister(TRC); 8949 unsigned destOut = MRI.createVirtualRegister(TRC); 8950 unsigned scratch = MRI.createVirtualRegister(TRC); 8951 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8952 IsThumb1, IsThumb2); 8953 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8954 IsThumb1, IsThumb2); 8955 srcIn = srcOut; 8956 destIn = destOut; 8957 } 8958 MI.eraseFromParent(); // The instruction is gone now. 8959 return BB; 8960 } 8961 8962 // Expand the pseudo op to a loop. 8963 // thisMBB: 8964 // ... 8965 // movw varEnd, # --> with thumb2 8966 // movt varEnd, # 8967 // ldrcp varEnd, idx --> without thumb2 8968 // fallthrough --> loopMBB 8969 // loopMBB: 8970 // PHI varPhi, varEnd, varLoop 8971 // PHI srcPhi, src, srcLoop 8972 // PHI destPhi, dst, destLoop 8973 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8974 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8975 // subs varLoop, varPhi, #UnitSize 8976 // bne loopMBB 8977 // fallthrough --> exitMBB 8978 // exitMBB: 8979 // epilogue to handle left-over bytes 8980 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8981 // [destOut] = STRB_POST(scratch, destLoop, 1) 8982 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8983 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8984 MF->insert(It, loopMBB); 8985 MF->insert(It, exitMBB); 8986 8987 // Transfer the remainder of BB and its successor edges to exitMBB. 8988 exitMBB->splice(exitMBB->begin(), BB, 8989 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8990 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8991 8992 // Load an immediate to varEnd. 8993 unsigned varEnd = MRI.createVirtualRegister(TRC); 8994 if (Subtarget->useMovt()) { 8995 unsigned Vtmp = varEnd; 8996 if ((LoopSize & 0xFFFF0000) != 0) 8997 Vtmp = MRI.createVirtualRegister(TRC); 8998 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8999 .addImm(LoopSize & 0xFFFF) 9000 .add(predOps(ARMCC::AL)); 9001 9002 if ((LoopSize & 0xFFFF0000) != 0) 9003 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9004 .addReg(Vtmp) 9005 .addImm(LoopSize >> 16) 9006 .add(predOps(ARMCC::AL)); 9007 } else { 9008 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9009 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9010 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9011 9012 // MachineConstantPool wants an explicit alignment. 9013 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9014 if (Align == 0) 9015 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9016 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9017 MachineMemOperand *CPMMO = 9018 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9019 MachineMemOperand::MOLoad, 4, 4); 9020 9021 if (IsThumb) 9022 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9023 .addReg(varEnd, RegState::Define) 9024 .addConstantPoolIndex(Idx) 9025 .add(predOps(ARMCC::AL)) 9026 .addMemOperand(CPMMO); 9027 else 9028 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9029 .addReg(varEnd, RegState::Define) 9030 .addConstantPoolIndex(Idx) 9031 .addImm(0) 9032 .add(predOps(ARMCC::AL)) 9033 .addMemOperand(CPMMO); 9034 } 9035 BB->addSuccessor(loopMBB); 9036 9037 // Generate the loop body: 9038 // varPhi = PHI(varLoop, varEnd) 9039 // srcPhi = PHI(srcLoop, src) 9040 // destPhi = PHI(destLoop, dst) 9041 MachineBasicBlock *entryBB = BB; 9042 BB = loopMBB; 9043 unsigned varLoop = MRI.createVirtualRegister(TRC); 9044 unsigned varPhi = MRI.createVirtualRegister(TRC); 9045 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9046 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9047 unsigned destLoop = MRI.createVirtualRegister(TRC); 9048 unsigned destPhi = MRI.createVirtualRegister(TRC); 9049 9050 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9051 .addReg(varLoop).addMBB(loopMBB) 9052 .addReg(varEnd).addMBB(entryBB); 9053 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9054 .addReg(srcLoop).addMBB(loopMBB) 9055 .addReg(src).addMBB(entryBB); 9056 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9057 .addReg(destLoop).addMBB(loopMBB) 9058 .addReg(dest).addMBB(entryBB); 9059 9060 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9061 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9062 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9063 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9064 IsThumb1, IsThumb2); 9065 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9066 IsThumb1, IsThumb2); 9067 9068 // Decrement loop variable by UnitSize. 9069 if (IsThumb1) { 9070 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9071 .add(t1CondCodeOp()) 9072 .addReg(varPhi) 9073 .addImm(UnitSize) 9074 .add(predOps(ARMCC::AL)); 9075 } else { 9076 MachineInstrBuilder MIB = 9077 BuildMI(*BB, BB->end(), dl, 9078 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9079 MIB.addReg(varPhi) 9080 .addImm(UnitSize) 9081 .add(predOps(ARMCC::AL)) 9082 .add(condCodeOp()); 9083 MIB->getOperand(5).setReg(ARM::CPSR); 9084 MIB->getOperand(5).setIsDef(true); 9085 } 9086 BuildMI(*BB, BB->end(), dl, 9087 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9088 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9089 9090 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9091 BB->addSuccessor(loopMBB); 9092 BB->addSuccessor(exitMBB); 9093 9094 // Add epilogue to handle BytesLeft. 9095 BB = exitMBB; 9096 auto StartOfExit = exitMBB->begin(); 9097 9098 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9099 // [destOut] = STRB_POST(scratch, destLoop, 1) 9100 unsigned srcIn = srcLoop; 9101 unsigned destIn = destLoop; 9102 for (unsigned i = 0; i < BytesLeft; i++) { 9103 unsigned srcOut = MRI.createVirtualRegister(TRC); 9104 unsigned destOut = MRI.createVirtualRegister(TRC); 9105 unsigned scratch = MRI.createVirtualRegister(TRC); 9106 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9107 IsThumb1, IsThumb2); 9108 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9109 IsThumb1, IsThumb2); 9110 srcIn = srcOut; 9111 destIn = destOut; 9112 } 9113 9114 MI.eraseFromParent(); // The instruction is gone now. 9115 return BB; 9116 } 9117 9118 MachineBasicBlock * 9119 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9120 MachineBasicBlock *MBB) const { 9121 const TargetMachine &TM = getTargetMachine(); 9122 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9123 DebugLoc DL = MI.getDebugLoc(); 9124 9125 assert(Subtarget->isTargetWindows() && 9126 "__chkstk is only supported on Windows"); 9127 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9128 9129 // __chkstk takes the number of words to allocate on the stack in R4, and 9130 // returns the stack adjustment in number of bytes in R4. This will not 9131 // clober any other registers (other than the obvious lr). 9132 // 9133 // Although, technically, IP should be considered a register which may be 9134 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9135 // thumb-2 environment, so there is no interworking required. As a result, we 9136 // do not expect a veneer to be emitted by the linker, clobbering IP. 9137 // 9138 // Each module receives its own copy of __chkstk, so no import thunk is 9139 // required, again, ensuring that IP is not clobbered. 9140 // 9141 // Finally, although some linkers may theoretically provide a trampoline for 9142 // out of range calls (which is quite common due to a 32M range limitation of 9143 // branches for Thumb), we can generate the long-call version via 9144 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9145 // IP. 9146 9147 switch (TM.getCodeModel()) { 9148 case CodeModel::Tiny: 9149 llvm_unreachable("Tiny code model not available on ARM."); 9150 case CodeModel::Small: 9151 case CodeModel::Medium: 9152 case CodeModel::Kernel: 9153 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9154 .add(predOps(ARMCC::AL)) 9155 .addExternalSymbol("__chkstk") 9156 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9157 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9158 .addReg(ARM::R12, 9159 RegState::Implicit | RegState::Define | RegState::Dead) 9160 .addReg(ARM::CPSR, 9161 RegState::Implicit | RegState::Define | RegState::Dead); 9162 break; 9163 case CodeModel::Large: { 9164 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9165 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9166 9167 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9168 .addExternalSymbol("__chkstk"); 9169 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9170 .add(predOps(ARMCC::AL)) 9171 .addReg(Reg, RegState::Kill) 9172 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9173 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9174 .addReg(ARM::R12, 9175 RegState::Implicit | RegState::Define | RegState::Dead) 9176 .addReg(ARM::CPSR, 9177 RegState::Implicit | RegState::Define | RegState::Dead); 9178 break; 9179 } 9180 } 9181 9182 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9183 .addReg(ARM::SP, RegState::Kill) 9184 .addReg(ARM::R4, RegState::Kill) 9185 .setMIFlags(MachineInstr::FrameSetup) 9186 .add(predOps(ARMCC::AL)) 9187 .add(condCodeOp()); 9188 9189 MI.eraseFromParent(); 9190 return MBB; 9191 } 9192 9193 MachineBasicBlock * 9194 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9195 MachineBasicBlock *MBB) const { 9196 DebugLoc DL = MI.getDebugLoc(); 9197 MachineFunction *MF = MBB->getParent(); 9198 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9199 9200 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9201 MF->insert(++MBB->getIterator(), ContBB); 9202 ContBB->splice(ContBB->begin(), MBB, 9203 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9204 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9205 MBB->addSuccessor(ContBB); 9206 9207 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9208 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9209 MF->push_back(TrapBB); 9210 MBB->addSuccessor(TrapBB); 9211 9212 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9213 .addReg(MI.getOperand(0).getReg()) 9214 .addImm(0) 9215 .add(predOps(ARMCC::AL)); 9216 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9217 .addMBB(TrapBB) 9218 .addImm(ARMCC::EQ) 9219 .addReg(ARM::CPSR); 9220 9221 MI.eraseFromParent(); 9222 return ContBB; 9223 } 9224 9225 // The CPSR operand of SelectItr might be missing a kill marker 9226 // because there were multiple uses of CPSR, and ISel didn't know 9227 // which to mark. Figure out whether SelectItr should have had a 9228 // kill marker, and set it if it should. Returns the correct kill 9229 // marker value. 9230 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 9231 MachineBasicBlock* BB, 9232 const TargetRegisterInfo* TRI) { 9233 // Scan forward through BB for a use/def of CPSR. 9234 MachineBasicBlock::iterator miI(std::next(SelectItr)); 9235 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 9236 const MachineInstr& mi = *miI; 9237 if (mi.readsRegister(ARM::CPSR)) 9238 return false; 9239 if (mi.definesRegister(ARM::CPSR)) 9240 break; // Should have kill-flag - update below. 9241 } 9242 9243 // If we hit the end of the block, check whether CPSR is live into a 9244 // successor. 9245 if (miI == BB->end()) { 9246 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 9247 sEnd = BB->succ_end(); 9248 sItr != sEnd; ++sItr) { 9249 MachineBasicBlock* succ = *sItr; 9250 if (succ->isLiveIn(ARM::CPSR)) 9251 return false; 9252 } 9253 } 9254 9255 // We found a def, or hit the end of the basic block and CPSR wasn't live 9256 // out. SelectMI should have a kill flag on CPSR. 9257 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 9258 return true; 9259 } 9260 9261 MachineBasicBlock * 9262 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9263 MachineBasicBlock *BB) const { 9264 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9265 DebugLoc dl = MI.getDebugLoc(); 9266 bool isThumb2 = Subtarget->isThumb2(); 9267 switch (MI.getOpcode()) { 9268 default: { 9269 MI.print(errs()); 9270 llvm_unreachable("Unexpected instr type to insert"); 9271 } 9272 9273 // Thumb1 post-indexed loads are really just single-register LDMs. 9274 case ARM::tLDR_postidx: { 9275 MachineOperand Def(MI.getOperand(1)); 9276 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9277 .add(Def) // Rn_wb 9278 .add(MI.getOperand(2)) // Rn 9279 .add(MI.getOperand(3)) // PredImm 9280 .add(MI.getOperand(4)) // PredReg 9281 .add(MI.getOperand(0)) // Rt 9282 .cloneMemRefs(MI); 9283 MI.eraseFromParent(); 9284 return BB; 9285 } 9286 9287 // The Thumb2 pre-indexed stores have the same MI operands, they just 9288 // define them differently in the .td files from the isel patterns, so 9289 // they need pseudos. 9290 case ARM::t2STR_preidx: 9291 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9292 return BB; 9293 case ARM::t2STRB_preidx: 9294 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9295 return BB; 9296 case ARM::t2STRH_preidx: 9297 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9298 return BB; 9299 9300 case ARM::STRi_preidx: 9301 case ARM::STRBi_preidx: { 9302 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9303 : ARM::STRB_PRE_IMM; 9304 // Decode the offset. 9305 unsigned Offset = MI.getOperand(4).getImm(); 9306 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9307 Offset = ARM_AM::getAM2Offset(Offset); 9308 if (isSub) 9309 Offset = -Offset; 9310 9311 MachineMemOperand *MMO = *MI.memoperands_begin(); 9312 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9313 .add(MI.getOperand(0)) // Rn_wb 9314 .add(MI.getOperand(1)) // Rt 9315 .add(MI.getOperand(2)) // Rn 9316 .addImm(Offset) // offset (skip GPR==zero_reg) 9317 .add(MI.getOperand(5)) // pred 9318 .add(MI.getOperand(6)) 9319 .addMemOperand(MMO); 9320 MI.eraseFromParent(); 9321 return BB; 9322 } 9323 case ARM::STRr_preidx: 9324 case ARM::STRBr_preidx: 9325 case ARM::STRH_preidx: { 9326 unsigned NewOpc; 9327 switch (MI.getOpcode()) { 9328 default: llvm_unreachable("unexpected opcode!"); 9329 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9330 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9331 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9332 } 9333 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9334 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9335 MIB.add(MI.getOperand(i)); 9336 MI.eraseFromParent(); 9337 return BB; 9338 } 9339 9340 case ARM::tMOVCCr_pseudo: { 9341 // To "insert" a SELECT_CC instruction, we actually have to insert the 9342 // diamond control-flow pattern. The incoming instruction knows the 9343 // destination vreg to set, the condition code register to branch on, the 9344 // true/false values to select between, and a branch opcode to use. 9345 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9346 MachineFunction::iterator It = ++BB->getIterator(); 9347 9348 // thisMBB: 9349 // ... 9350 // TrueVal = ... 9351 // cmpTY ccX, r1, r2 9352 // bCC copy1MBB 9353 // fallthrough --> copy0MBB 9354 MachineBasicBlock *thisMBB = BB; 9355 MachineFunction *F = BB->getParent(); 9356 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9357 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9358 F->insert(It, copy0MBB); 9359 F->insert(It, sinkMBB); 9360 9361 // Check whether CPSR is live past the tMOVCCr_pseudo. 9362 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 9363 if (!MI.killsRegister(ARM::CPSR) && 9364 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 9365 copy0MBB->addLiveIn(ARM::CPSR); 9366 sinkMBB->addLiveIn(ARM::CPSR); 9367 } 9368 9369 // Transfer the remainder of BB and its successor edges to sinkMBB. 9370 sinkMBB->splice(sinkMBB->begin(), BB, 9371 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9372 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9373 9374 BB->addSuccessor(copy0MBB); 9375 BB->addSuccessor(sinkMBB); 9376 9377 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9378 .addMBB(sinkMBB) 9379 .addImm(MI.getOperand(3).getImm()) 9380 .addReg(MI.getOperand(4).getReg()); 9381 9382 // copy0MBB: 9383 // %FalseValue = ... 9384 // # fallthrough to sinkMBB 9385 BB = copy0MBB; 9386 9387 // Update machine-CFG edges 9388 BB->addSuccessor(sinkMBB); 9389 9390 // sinkMBB: 9391 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9392 // ... 9393 BB = sinkMBB; 9394 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9395 .addReg(MI.getOperand(1).getReg()) 9396 .addMBB(copy0MBB) 9397 .addReg(MI.getOperand(2).getReg()) 9398 .addMBB(thisMBB); 9399 9400 MI.eraseFromParent(); // The pseudo instruction is gone now. 9401 return BB; 9402 } 9403 9404 case ARM::BCCi64: 9405 case ARM::BCCZi64: { 9406 // If there is an unconditional branch to the other successor, remove it. 9407 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9408 9409 // Compare both parts that make up the double comparison separately for 9410 // equality. 9411 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9412 9413 unsigned LHS1 = MI.getOperand(1).getReg(); 9414 unsigned LHS2 = MI.getOperand(2).getReg(); 9415 if (RHSisZero) { 9416 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9417 .addReg(LHS1) 9418 .addImm(0) 9419 .add(predOps(ARMCC::AL)); 9420 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9421 .addReg(LHS2).addImm(0) 9422 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9423 } else { 9424 unsigned RHS1 = MI.getOperand(3).getReg(); 9425 unsigned RHS2 = MI.getOperand(4).getReg(); 9426 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9427 .addReg(LHS1) 9428 .addReg(RHS1) 9429 .add(predOps(ARMCC::AL)); 9430 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9431 .addReg(LHS2).addReg(RHS2) 9432 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9433 } 9434 9435 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9436 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9437 if (MI.getOperand(0).getImm() == ARMCC::NE) 9438 std::swap(destMBB, exitMBB); 9439 9440 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9441 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9442 if (isThumb2) 9443 BuildMI(BB, dl, TII->get(ARM::t2B)) 9444 .addMBB(exitMBB) 9445 .add(predOps(ARMCC::AL)); 9446 else 9447 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9448 9449 MI.eraseFromParent(); // The pseudo instruction is gone now. 9450 return BB; 9451 } 9452 9453 case ARM::Int_eh_sjlj_setjmp: 9454 case ARM::Int_eh_sjlj_setjmp_nofp: 9455 case ARM::tInt_eh_sjlj_setjmp: 9456 case ARM::t2Int_eh_sjlj_setjmp: 9457 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9458 return BB; 9459 9460 case ARM::Int_eh_sjlj_setup_dispatch: 9461 EmitSjLjDispatchBlock(MI, BB); 9462 return BB; 9463 9464 case ARM::ABS: 9465 case ARM::t2ABS: { 9466 // To insert an ABS instruction, we have to insert the 9467 // diamond control-flow pattern. The incoming instruction knows the 9468 // source vreg to test against 0, the destination vreg to set, 9469 // the condition code register to branch on, the 9470 // true/false values to select between, and a branch opcode to use. 9471 // It transforms 9472 // V1 = ABS V0 9473 // into 9474 // V2 = MOVS V0 9475 // BCC (branch to SinkBB if V0 >= 0) 9476 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9477 // SinkBB: V1 = PHI(V2, V3) 9478 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9479 MachineFunction::iterator BBI = ++BB->getIterator(); 9480 MachineFunction *Fn = BB->getParent(); 9481 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9482 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9483 Fn->insert(BBI, RSBBB); 9484 Fn->insert(BBI, SinkBB); 9485 9486 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9487 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9488 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9489 bool isThumb2 = Subtarget->isThumb2(); 9490 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9491 // In Thumb mode S must not be specified if source register is the SP or 9492 // PC and if destination register is the SP, so restrict register class 9493 unsigned NewRsbDstReg = 9494 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9495 9496 // Transfer the remainder of BB and its successor edges to sinkMBB. 9497 SinkBB->splice(SinkBB->begin(), BB, 9498 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9499 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9500 9501 BB->addSuccessor(RSBBB); 9502 BB->addSuccessor(SinkBB); 9503 9504 // fall through to SinkMBB 9505 RSBBB->addSuccessor(SinkBB); 9506 9507 // insert a cmp at the end of BB 9508 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9509 .addReg(ABSSrcReg) 9510 .addImm(0) 9511 .add(predOps(ARMCC::AL)); 9512 9513 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9514 BuildMI(BB, dl, 9515 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9516 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9517 9518 // insert rsbri in RSBBB 9519 // Note: BCC and rsbri will be converted into predicated rsbmi 9520 // by if-conversion pass 9521 BuildMI(*RSBBB, RSBBB->begin(), dl, 9522 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9523 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9524 .addImm(0) 9525 .add(predOps(ARMCC::AL)) 9526 .add(condCodeOp()); 9527 9528 // insert PHI in SinkBB, 9529 // reuse ABSDstReg to not change uses of ABS instruction 9530 BuildMI(*SinkBB, SinkBB->begin(), dl, 9531 TII->get(ARM::PHI), ABSDstReg) 9532 .addReg(NewRsbDstReg).addMBB(RSBBB) 9533 .addReg(ABSSrcReg).addMBB(BB); 9534 9535 // remove ABS instruction 9536 MI.eraseFromParent(); 9537 9538 // return last added BB 9539 return SinkBB; 9540 } 9541 case ARM::COPY_STRUCT_BYVAL_I32: 9542 ++NumLoopByVals; 9543 return EmitStructByval(MI, BB); 9544 case ARM::WIN__CHKSTK: 9545 return EmitLowered__chkstk(MI, BB); 9546 case ARM::WIN__DBZCHK: 9547 return EmitLowered__dbzchk(MI, BB); 9548 } 9549 } 9550 9551 /// Attaches vregs to MEMCPY that it will use as scratch registers 9552 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9553 /// instead of as a custom inserter because we need the use list from the SDNode. 9554 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9555 MachineInstr &MI, const SDNode *Node) { 9556 bool isThumb1 = Subtarget->isThumb1Only(); 9557 9558 DebugLoc DL = MI.getDebugLoc(); 9559 MachineFunction *MF = MI.getParent()->getParent(); 9560 MachineRegisterInfo &MRI = MF->getRegInfo(); 9561 MachineInstrBuilder MIB(*MF, MI); 9562 9563 // If the new dst/src is unused mark it as dead. 9564 if (!Node->hasAnyUseOfValue(0)) { 9565 MI.getOperand(0).setIsDead(true); 9566 } 9567 if (!Node->hasAnyUseOfValue(1)) { 9568 MI.getOperand(1).setIsDead(true); 9569 } 9570 9571 // The MEMCPY both defines and kills the scratch registers. 9572 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9573 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9574 : &ARM::GPRRegClass); 9575 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9576 } 9577 } 9578 9579 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9580 SDNode *Node) const { 9581 if (MI.getOpcode() == ARM::MEMCPY) { 9582 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9583 return; 9584 } 9585 9586 const MCInstrDesc *MCID = &MI.getDesc(); 9587 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9588 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9589 // operand is still set to noreg. If needed, set the optional operand's 9590 // register to CPSR, and remove the redundant implicit def. 9591 // 9592 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9593 9594 // Rename pseudo opcodes. 9595 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9596 unsigned ccOutIdx; 9597 if (NewOpc) { 9598 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9599 MCID = &TII->get(NewOpc); 9600 9601 assert(MCID->getNumOperands() == 9602 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9603 && "converted opcode should be the same except for cc_out" 9604 " (and, on Thumb1, pred)"); 9605 9606 MI.setDesc(*MCID); 9607 9608 // Add the optional cc_out operand 9609 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9610 9611 // On Thumb1, move all input operands to the end, then add the predicate 9612 if (Subtarget->isThumb1Only()) { 9613 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9614 MI.addOperand(MI.getOperand(1)); 9615 MI.RemoveOperand(1); 9616 } 9617 9618 // Restore the ties 9619 for (unsigned i = MI.getNumOperands(); i--;) { 9620 const MachineOperand& op = MI.getOperand(i); 9621 if (op.isReg() && op.isUse()) { 9622 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9623 if (DefIdx != -1) 9624 MI.tieOperands(DefIdx, i); 9625 } 9626 } 9627 9628 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9629 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9630 ccOutIdx = 1; 9631 } else 9632 ccOutIdx = MCID->getNumOperands() - 1; 9633 } else 9634 ccOutIdx = MCID->getNumOperands() - 1; 9635 9636 // Any ARM instruction that sets the 's' bit should specify an optional 9637 // "cc_out" operand in the last operand position. 9638 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9639 assert(!NewOpc && "Optional cc_out operand required"); 9640 return; 9641 } 9642 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9643 // since we already have an optional CPSR def. 9644 bool definesCPSR = false; 9645 bool deadCPSR = false; 9646 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9647 ++i) { 9648 const MachineOperand &MO = MI.getOperand(i); 9649 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9650 definesCPSR = true; 9651 if (MO.isDead()) 9652 deadCPSR = true; 9653 MI.RemoveOperand(i); 9654 break; 9655 } 9656 } 9657 if (!definesCPSR) { 9658 assert(!NewOpc && "Optional cc_out operand required"); 9659 return; 9660 } 9661 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9662 if (deadCPSR) { 9663 assert(!MI.getOperand(ccOutIdx).getReg() && 9664 "expect uninitialized optional cc_out operand"); 9665 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9666 if (!Subtarget->isThumb1Only()) 9667 return; 9668 } 9669 9670 // If this instruction was defined with an optional CPSR def and its dag node 9671 // had a live implicit CPSR def, then activate the optional CPSR def. 9672 MachineOperand &MO = MI.getOperand(ccOutIdx); 9673 MO.setReg(ARM::CPSR); 9674 MO.setIsDef(true); 9675 } 9676 9677 //===----------------------------------------------------------------------===// 9678 // ARM Optimization Hooks 9679 //===----------------------------------------------------------------------===// 9680 9681 // Helper function that checks if N is a null or all ones constant. 9682 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9683 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9684 } 9685 9686 // Return true if N is conditionally 0 or all ones. 9687 // Detects these expressions where cc is an i1 value: 9688 // 9689 // (select cc 0, y) [AllOnes=0] 9690 // (select cc y, 0) [AllOnes=0] 9691 // (zext cc) [AllOnes=0] 9692 // (sext cc) [AllOnes=0/1] 9693 // (select cc -1, y) [AllOnes=1] 9694 // (select cc y, -1) [AllOnes=1] 9695 // 9696 // Invert is set when N is the null/all ones constant when CC is false. 9697 // OtherOp is set to the alternative value of N. 9698 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9699 SDValue &CC, bool &Invert, 9700 SDValue &OtherOp, 9701 SelectionDAG &DAG) { 9702 switch (N->getOpcode()) { 9703 default: return false; 9704 case ISD::SELECT: { 9705 CC = N->getOperand(0); 9706 SDValue N1 = N->getOperand(1); 9707 SDValue N2 = N->getOperand(2); 9708 if (isZeroOrAllOnes(N1, AllOnes)) { 9709 Invert = false; 9710 OtherOp = N2; 9711 return true; 9712 } 9713 if (isZeroOrAllOnes(N2, AllOnes)) { 9714 Invert = true; 9715 OtherOp = N1; 9716 return true; 9717 } 9718 return false; 9719 } 9720 case ISD::ZERO_EXTEND: 9721 // (zext cc) can never be the all ones value. 9722 if (AllOnes) 9723 return false; 9724 LLVM_FALLTHROUGH; 9725 case ISD::SIGN_EXTEND: { 9726 SDLoc dl(N); 9727 EVT VT = N->getValueType(0); 9728 CC = N->getOperand(0); 9729 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9730 return false; 9731 Invert = !AllOnes; 9732 if (AllOnes) 9733 // When looking for an AllOnes constant, N is an sext, and the 'other' 9734 // value is 0. 9735 OtherOp = DAG.getConstant(0, dl, VT); 9736 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9737 // When looking for a 0 constant, N can be zext or sext. 9738 OtherOp = DAG.getConstant(1, dl, VT); 9739 else 9740 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9741 VT); 9742 return true; 9743 } 9744 } 9745 } 9746 9747 // Combine a constant select operand into its use: 9748 // 9749 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9750 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9751 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9752 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9753 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9754 // 9755 // The transform is rejected if the select doesn't have a constant operand that 9756 // is null, or all ones when AllOnes is set. 9757 // 9758 // Also recognize sext/zext from i1: 9759 // 9760 // (add (zext cc), x) -> (select cc (add x, 1), x) 9761 // (add (sext cc), x) -> (select cc (add x, -1), x) 9762 // 9763 // These transformations eventually create predicated instructions. 9764 // 9765 // @param N The node to transform. 9766 // @param Slct The N operand that is a select. 9767 // @param OtherOp The other N operand (x above). 9768 // @param DCI Context. 9769 // @param AllOnes Require the select constant to be all ones instead of null. 9770 // @returns The new node, or SDValue() on failure. 9771 static 9772 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9773 TargetLowering::DAGCombinerInfo &DCI, 9774 bool AllOnes = false) { 9775 SelectionDAG &DAG = DCI.DAG; 9776 EVT VT = N->getValueType(0); 9777 SDValue NonConstantVal; 9778 SDValue CCOp; 9779 bool SwapSelectOps; 9780 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9781 NonConstantVal, DAG)) 9782 return SDValue(); 9783 9784 // Slct is now know to be the desired identity constant when CC is true. 9785 SDValue TrueVal = OtherOp; 9786 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9787 OtherOp, NonConstantVal); 9788 // Unless SwapSelectOps says CC should be false. 9789 if (SwapSelectOps) 9790 std::swap(TrueVal, FalseVal); 9791 9792 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9793 CCOp, TrueVal, FalseVal); 9794 } 9795 9796 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9797 static 9798 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9799 TargetLowering::DAGCombinerInfo &DCI) { 9800 SDValue N0 = N->getOperand(0); 9801 SDValue N1 = N->getOperand(1); 9802 if (N0.getNode()->hasOneUse()) 9803 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9804 return Result; 9805 if (N1.getNode()->hasOneUse()) 9806 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9807 return Result; 9808 return SDValue(); 9809 } 9810 9811 static bool IsVUZPShuffleNode(SDNode *N) { 9812 // VUZP shuffle node. 9813 if (N->getOpcode() == ARMISD::VUZP) 9814 return true; 9815 9816 // "VUZP" on i32 is an alias for VTRN. 9817 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9818 return true; 9819 9820 return false; 9821 } 9822 9823 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9824 TargetLowering::DAGCombinerInfo &DCI, 9825 const ARMSubtarget *Subtarget) { 9826 // Look for ADD(VUZP.0, VUZP.1). 9827 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9828 N0 == N1) 9829 return SDValue(); 9830 9831 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9832 if (!N->getValueType(0).is64BitVector()) 9833 return SDValue(); 9834 9835 // Generate vpadd. 9836 SelectionDAG &DAG = DCI.DAG; 9837 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9838 SDLoc dl(N); 9839 SDNode *Unzip = N0.getNode(); 9840 EVT VT = N->getValueType(0); 9841 9842 SmallVector<SDValue, 8> Ops; 9843 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9844 TLI.getPointerTy(DAG.getDataLayout()))); 9845 Ops.push_back(Unzip->getOperand(0)); 9846 Ops.push_back(Unzip->getOperand(1)); 9847 9848 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9849 } 9850 9851 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9852 TargetLowering::DAGCombinerInfo &DCI, 9853 const ARMSubtarget *Subtarget) { 9854 // Check for two extended operands. 9855 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9856 N1.getOpcode() == ISD::SIGN_EXTEND) && 9857 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9858 N1.getOpcode() == ISD::ZERO_EXTEND)) 9859 return SDValue(); 9860 9861 SDValue N00 = N0.getOperand(0); 9862 SDValue N10 = N1.getOperand(0); 9863 9864 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9865 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9866 N00 == N10) 9867 return SDValue(); 9868 9869 // We only recognize Q register paddl here; this can't be reached until 9870 // after type legalization. 9871 if (!N00.getValueType().is64BitVector() || 9872 !N0.getValueType().is128BitVector()) 9873 return SDValue(); 9874 9875 // Generate vpaddl. 9876 SelectionDAG &DAG = DCI.DAG; 9877 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9878 SDLoc dl(N); 9879 EVT VT = N->getValueType(0); 9880 9881 SmallVector<SDValue, 8> Ops; 9882 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9883 unsigned Opcode; 9884 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9885 Opcode = Intrinsic::arm_neon_vpaddls; 9886 else 9887 Opcode = Intrinsic::arm_neon_vpaddlu; 9888 Ops.push_back(DAG.getConstant(Opcode, dl, 9889 TLI.getPointerTy(DAG.getDataLayout()))); 9890 EVT ElemTy = N00.getValueType().getVectorElementType(); 9891 unsigned NumElts = VT.getVectorNumElements(); 9892 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9893 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9894 N00.getOperand(0), N00.getOperand(1)); 9895 Ops.push_back(Concat); 9896 9897 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9898 } 9899 9900 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9901 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9902 // much easier to match. 9903 static SDValue 9904 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9905 TargetLowering::DAGCombinerInfo &DCI, 9906 const ARMSubtarget *Subtarget) { 9907 // Only perform optimization if after legalize, and if NEON is available. We 9908 // also expected both operands to be BUILD_VECTORs. 9909 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9910 || N0.getOpcode() != ISD::BUILD_VECTOR 9911 || N1.getOpcode() != ISD::BUILD_VECTOR) 9912 return SDValue(); 9913 9914 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9915 EVT VT = N->getValueType(0); 9916 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9917 return SDValue(); 9918 9919 // Check that the vector operands are of the right form. 9920 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9921 // operands, where N is the size of the formed vector. 9922 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9923 // index such that we have a pair wise add pattern. 9924 9925 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9926 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9927 return SDValue(); 9928 SDValue Vec = N0->getOperand(0)->getOperand(0); 9929 SDNode *V = Vec.getNode(); 9930 unsigned nextIndex = 0; 9931 9932 // For each operands to the ADD which are BUILD_VECTORs, 9933 // check to see if each of their operands are an EXTRACT_VECTOR with 9934 // the same vector and appropriate index. 9935 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9936 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9937 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9938 9939 SDValue ExtVec0 = N0->getOperand(i); 9940 SDValue ExtVec1 = N1->getOperand(i); 9941 9942 // First operand is the vector, verify its the same. 9943 if (V != ExtVec0->getOperand(0).getNode() || 9944 V != ExtVec1->getOperand(0).getNode()) 9945 return SDValue(); 9946 9947 // Second is the constant, verify its correct. 9948 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9949 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9950 9951 // For the constant, we want to see all the even or all the odd. 9952 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9953 || C1->getZExtValue() != nextIndex+1) 9954 return SDValue(); 9955 9956 // Increment index. 9957 nextIndex+=2; 9958 } else 9959 return SDValue(); 9960 } 9961 9962 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9963 // we're using the entire input vector, otherwise there's a size/legality 9964 // mismatch somewhere. 9965 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9966 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9967 return SDValue(); 9968 9969 // Create VPADDL node. 9970 SelectionDAG &DAG = DCI.DAG; 9971 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9972 9973 SDLoc dl(N); 9974 9975 // Build operand list. 9976 SmallVector<SDValue, 8> Ops; 9977 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9978 TLI.getPointerTy(DAG.getDataLayout()))); 9979 9980 // Input is the vector. 9981 Ops.push_back(Vec); 9982 9983 // Get widened type and narrowed type. 9984 MVT widenType; 9985 unsigned numElem = VT.getVectorNumElements(); 9986 9987 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9988 switch (inputLaneType.getSimpleVT().SimpleTy) { 9989 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9990 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9991 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9992 default: 9993 llvm_unreachable("Invalid vector element type for padd optimization."); 9994 } 9995 9996 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9997 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9998 return DAG.getNode(ExtOp, dl, VT, tmp); 9999 } 10000 10001 static SDValue findMUL_LOHI(SDValue V) { 10002 if (V->getOpcode() == ISD::UMUL_LOHI || 10003 V->getOpcode() == ISD::SMUL_LOHI) 10004 return V; 10005 return SDValue(); 10006 } 10007 10008 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 10009 TargetLowering::DAGCombinerInfo &DCI, 10010 const ARMSubtarget *Subtarget) { 10011 if (Subtarget->isThumb()) { 10012 if (!Subtarget->hasDSP()) 10013 return SDValue(); 10014 } else if (!Subtarget->hasV5TEOps()) 10015 return SDValue(); 10016 10017 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 10018 // accumulates the product into a 64-bit value. The 16-bit values will 10019 // be sign extended somehow or SRA'd into 32-bit values 10020 // (addc (adde (mul 16bit, 16bit), lo), hi) 10021 SDValue Mul = AddcNode->getOperand(0); 10022 SDValue Lo = AddcNode->getOperand(1); 10023 if (Mul.getOpcode() != ISD::MUL) { 10024 Lo = AddcNode->getOperand(0); 10025 Mul = AddcNode->getOperand(1); 10026 if (Mul.getOpcode() != ISD::MUL) 10027 return SDValue(); 10028 } 10029 10030 SDValue SRA = AddeNode->getOperand(0); 10031 SDValue Hi = AddeNode->getOperand(1); 10032 if (SRA.getOpcode() != ISD::SRA) { 10033 SRA = AddeNode->getOperand(1); 10034 Hi = AddeNode->getOperand(0); 10035 if (SRA.getOpcode() != ISD::SRA) 10036 return SDValue(); 10037 } 10038 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10039 if (Const->getZExtValue() != 31) 10040 return SDValue(); 10041 } else 10042 return SDValue(); 10043 10044 if (SRA.getOperand(0) != Mul) 10045 return SDValue(); 10046 10047 SelectionDAG &DAG = DCI.DAG; 10048 SDLoc dl(AddcNode); 10049 unsigned Opcode = 0; 10050 SDValue Op0; 10051 SDValue Op1; 10052 10053 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10054 Opcode = ARMISD::SMLALBB; 10055 Op0 = Mul.getOperand(0); 10056 Op1 = Mul.getOperand(1); 10057 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10058 Opcode = ARMISD::SMLALBT; 10059 Op0 = Mul.getOperand(0); 10060 Op1 = Mul.getOperand(1).getOperand(0); 10061 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10062 Opcode = ARMISD::SMLALTB; 10063 Op0 = Mul.getOperand(0).getOperand(0); 10064 Op1 = Mul.getOperand(1); 10065 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10066 Opcode = ARMISD::SMLALTT; 10067 Op0 = Mul->getOperand(0).getOperand(0); 10068 Op1 = Mul->getOperand(1).getOperand(0); 10069 } 10070 10071 if (!Op0 || !Op1) 10072 return SDValue(); 10073 10074 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10075 Op0, Op1, Lo, Hi); 10076 // Replace the ADDs' nodes uses by the MLA node's values. 10077 SDValue HiMLALResult(SMLAL.getNode(), 1); 10078 SDValue LoMLALResult(SMLAL.getNode(), 0); 10079 10080 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10081 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10082 10083 // Return original node to notify the driver to stop replacing. 10084 SDValue resNode(AddcNode, 0); 10085 return resNode; 10086 } 10087 10088 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10089 TargetLowering::DAGCombinerInfo &DCI, 10090 const ARMSubtarget *Subtarget) { 10091 // Look for multiply add opportunities. 10092 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10093 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10094 // a glue link from the first add to the second add. 10095 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10096 // a S/UMLAL instruction. 10097 // UMUL_LOHI 10098 // / :lo \ :hi 10099 // V \ [no multiline comment] 10100 // loAdd -> ADDC | 10101 // \ :carry / 10102 // V V 10103 // ADDE <- hiAdd 10104 // 10105 // In the special case where only the higher part of a signed result is used 10106 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10107 // a constant with the exact value of 0x80000000, we recognize we are dealing 10108 // with a "rounded multiply and add" (or subtract) and transform it into 10109 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10110 10111 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10112 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10113 "Expect an ADDE or SUBE"); 10114 10115 assert(AddeSubeNode->getNumOperands() == 3 && 10116 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10117 "ADDE node has the wrong inputs"); 10118 10119 // Check that we are chained to the right ADDC or SUBC node. 10120 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10121 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10122 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10123 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10124 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10125 return SDValue(); 10126 10127 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10128 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10129 10130 // Check if the two operands are from the same mul_lohi node. 10131 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10132 return SDValue(); 10133 10134 assert(AddcSubcNode->getNumValues() == 2 && 10135 AddcSubcNode->getValueType(0) == MVT::i32 && 10136 "Expect ADDC with two result values. First: i32"); 10137 10138 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10139 // maybe a SMLAL which multiplies two 16-bit values. 10140 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10141 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10142 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10143 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10144 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10145 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10146 10147 // Check for the triangle shape. 10148 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10149 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10150 10151 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10152 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10153 return SDValue(); 10154 10155 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10156 bool IsLeftOperandMUL = false; 10157 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10158 if (MULOp == SDValue()) 10159 MULOp = findMUL_LOHI(AddeSubeOp1); 10160 else 10161 IsLeftOperandMUL = true; 10162 if (MULOp == SDValue()) 10163 return SDValue(); 10164 10165 // Figure out the right opcode. 10166 unsigned Opc = MULOp->getOpcode(); 10167 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10168 10169 // Figure out the high and low input values to the MLAL node. 10170 SDValue *HiAddSub = nullptr; 10171 SDValue *LoMul = nullptr; 10172 SDValue *LowAddSub = nullptr; 10173 10174 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10175 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10176 return SDValue(); 10177 10178 if (IsLeftOperandMUL) 10179 HiAddSub = &AddeSubeOp1; 10180 else 10181 HiAddSub = &AddeSubeOp0; 10182 10183 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10184 // whose low result is fed to the ADDC/SUBC we are checking. 10185 10186 if (AddcSubcOp0 == MULOp.getValue(0)) { 10187 LoMul = &AddcSubcOp0; 10188 LowAddSub = &AddcSubcOp1; 10189 } 10190 if (AddcSubcOp1 == MULOp.getValue(0)) { 10191 LoMul = &AddcSubcOp1; 10192 LowAddSub = &AddcSubcOp0; 10193 } 10194 10195 if (!LoMul) 10196 return SDValue(); 10197 10198 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10199 // the replacement below will create a cycle. 10200 if (AddcSubcNode == HiAddSub->getNode() || 10201 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10202 return SDValue(); 10203 10204 // Create the merged node. 10205 SelectionDAG &DAG = DCI.DAG; 10206 10207 // Start building operand list. 10208 SmallVector<SDValue, 8> Ops; 10209 Ops.push_back(LoMul->getOperand(0)); 10210 Ops.push_back(LoMul->getOperand(1)); 10211 10212 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10213 // the case, we must be doing signed multiplication and only use the higher 10214 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10215 // addition or subtraction with the value of 0x800000. 10216 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10217 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10218 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10219 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10220 0x80000000) { 10221 Ops.push_back(*HiAddSub); 10222 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10223 FinalOpc = ARMISD::SMMLSR; 10224 } else { 10225 FinalOpc = ARMISD::SMMLAR; 10226 } 10227 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10228 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10229 10230 return SDValue(AddeSubeNode, 0); 10231 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10232 // SMMLS is generated during instruction selection and the rest of this 10233 // function can not handle the case where AddcSubcNode is a SUBC. 10234 return SDValue(); 10235 10236 // Finish building the operand list for {U/S}MLAL 10237 Ops.push_back(*LowAddSub); 10238 Ops.push_back(*HiAddSub); 10239 10240 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 10241 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10242 10243 // Replace the ADDs' nodes uses by the MLA node's values. 10244 SDValue HiMLALResult(MLALNode.getNode(), 1); 10245 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 10246 10247 SDValue LoMLALResult(MLALNode.getNode(), 0); 10248 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 10249 10250 // Return original node to notify the driver to stop replacing. 10251 return SDValue(AddeSubeNode, 0); 10252 } 10253 10254 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 10255 TargetLowering::DAGCombinerInfo &DCI, 10256 const ARMSubtarget *Subtarget) { 10257 // UMAAL is similar to UMLAL except that it adds two unsigned values. 10258 // While trying to combine for the other MLAL nodes, first search for the 10259 // chance to use UMAAL. Check if Addc uses a node which has already 10260 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 10261 // as the addend, and it's handled in PerformUMLALCombine. 10262 10263 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10264 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10265 10266 // Check that we have a glued ADDC node. 10267 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10268 if (AddcNode->getOpcode() != ARMISD::ADDC) 10269 return SDValue(); 10270 10271 // Find the converted UMAAL or quit if it doesn't exist. 10272 SDNode *UmlalNode = nullptr; 10273 SDValue AddHi; 10274 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10275 UmlalNode = AddcNode->getOperand(0).getNode(); 10276 AddHi = AddcNode->getOperand(1); 10277 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10278 UmlalNode = AddcNode->getOperand(1).getNode(); 10279 AddHi = AddcNode->getOperand(0); 10280 } else { 10281 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10282 } 10283 10284 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10285 // the ADDC as well as Zero. 10286 if (!isNullConstant(UmlalNode->getOperand(3))) 10287 return SDValue(); 10288 10289 if ((isNullConstant(AddeNode->getOperand(0)) && 10290 AddeNode->getOperand(1).getNode() == UmlalNode) || 10291 (AddeNode->getOperand(0).getNode() == UmlalNode && 10292 isNullConstant(AddeNode->getOperand(1)))) { 10293 SelectionDAG &DAG = DCI.DAG; 10294 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10295 UmlalNode->getOperand(2), AddHi }; 10296 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10297 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10298 10299 // Replace the ADDs' nodes uses by the UMAAL node's values. 10300 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10301 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10302 10303 // Return original node to notify the driver to stop replacing. 10304 return SDValue(AddeNode, 0); 10305 } 10306 return SDValue(); 10307 } 10308 10309 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10310 const ARMSubtarget *Subtarget) { 10311 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10312 return SDValue(); 10313 10314 // Check that we have a pair of ADDC and ADDE as operands. 10315 // Both addends of the ADDE must be zero. 10316 SDNode* AddcNode = N->getOperand(2).getNode(); 10317 SDNode* AddeNode = N->getOperand(3).getNode(); 10318 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10319 (AddeNode->getOpcode() == ARMISD::ADDE) && 10320 isNullConstant(AddeNode->getOperand(0)) && 10321 isNullConstant(AddeNode->getOperand(1)) && 10322 (AddeNode->getOperand(2).getNode() == AddcNode)) 10323 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10324 DAG.getVTList(MVT::i32, MVT::i32), 10325 {N->getOperand(0), N->getOperand(1), 10326 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10327 else 10328 return SDValue(); 10329 } 10330 10331 static SDValue PerformAddcSubcCombine(SDNode *N, 10332 TargetLowering::DAGCombinerInfo &DCI, 10333 const ARMSubtarget *Subtarget) { 10334 SelectionDAG &DAG(DCI.DAG); 10335 10336 if (N->getOpcode() == ARMISD::SUBC) { 10337 // (SUBC (ADDE 0, 0, C), 1) -> C 10338 SDValue LHS = N->getOperand(0); 10339 SDValue RHS = N->getOperand(1); 10340 if (LHS->getOpcode() == ARMISD::ADDE && 10341 isNullConstant(LHS->getOperand(0)) && 10342 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 10343 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10344 } 10345 } 10346 10347 if (Subtarget->isThumb1Only()) { 10348 SDValue RHS = N->getOperand(1); 10349 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10350 int32_t imm = C->getSExtValue(); 10351 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10352 SDLoc DL(N); 10353 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10354 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10355 : ARMISD::ADDC; 10356 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10357 } 10358 } 10359 } 10360 10361 return SDValue(); 10362 } 10363 10364 static SDValue PerformAddeSubeCombine(SDNode *N, 10365 TargetLowering::DAGCombinerInfo &DCI, 10366 const ARMSubtarget *Subtarget) { 10367 if (Subtarget->isThumb1Only()) { 10368 SelectionDAG &DAG = DCI.DAG; 10369 SDValue RHS = N->getOperand(1); 10370 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10371 int64_t imm = C->getSExtValue(); 10372 if (imm < 0) { 10373 SDLoc DL(N); 10374 10375 // The with-carry-in form matches bitwise not instead of the negation. 10376 // Effectively, the inverse interpretation of the carry flag already 10377 // accounts for part of the negation. 10378 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10379 10380 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10381 : ARMISD::ADDE; 10382 return DAG.getNode(Opcode, DL, N->getVTList(), 10383 N->getOperand(0), RHS, N->getOperand(2)); 10384 } 10385 } 10386 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 10387 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 10388 } 10389 return SDValue(); 10390 } 10391 10392 static SDValue PerformABSCombine(SDNode *N, 10393 TargetLowering::DAGCombinerInfo &DCI, 10394 const ARMSubtarget *Subtarget) { 10395 SDValue res; 10396 SelectionDAG &DAG = DCI.DAG; 10397 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10398 10399 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 10400 return SDValue(); 10401 10402 if (!TLI.expandABS(N, res, DAG)) 10403 return SDValue(); 10404 10405 return res; 10406 } 10407 10408 /// PerformADDECombine - Target-specific dag combine transform from 10409 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10410 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10411 static SDValue PerformADDECombine(SDNode *N, 10412 TargetLowering::DAGCombinerInfo &DCI, 10413 const ARMSubtarget *Subtarget) { 10414 // Only ARM and Thumb2 support UMLAL/SMLAL. 10415 if (Subtarget->isThumb1Only()) 10416 return PerformAddeSubeCombine(N, DCI, Subtarget); 10417 10418 // Only perform the checks after legalize when the pattern is available. 10419 if (DCI.isBeforeLegalize()) return SDValue(); 10420 10421 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10422 } 10423 10424 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10425 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10426 /// called with the default operands, and if that fails, with commuted 10427 /// operands. 10428 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10429 TargetLowering::DAGCombinerInfo &DCI, 10430 const ARMSubtarget *Subtarget){ 10431 // Attempt to create vpadd for this add. 10432 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10433 return Result; 10434 10435 // Attempt to create vpaddl for this add. 10436 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10437 return Result; 10438 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10439 Subtarget)) 10440 return Result; 10441 10442 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10443 if (N0.getNode()->hasOneUse()) 10444 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10445 return Result; 10446 return SDValue(); 10447 } 10448 10449 bool 10450 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 10451 CombineLevel Level) const { 10452 if (Level == BeforeLegalizeTypes) 10453 return true; 10454 10455 if (N->getOpcode() != ISD::SHL) 10456 return true; 10457 10458 if (Subtarget->isThumb1Only()) { 10459 // Avoid making expensive immediates by commuting shifts. (This logic 10460 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 10461 // for free.) 10462 if (N->getOpcode() != ISD::SHL) 10463 return true; 10464 SDValue N1 = N->getOperand(0); 10465 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 10466 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 10467 return true; 10468 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 10469 if (Const->getAPIntValue().ult(256)) 10470 return false; 10471 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 10472 Const->getAPIntValue().sgt(-256)) 10473 return false; 10474 } 10475 return true; 10476 } 10477 10478 // Turn off commute-with-shift transform after legalization, so it doesn't 10479 // conflict with PerformSHLSimplify. (We could try to detect when 10480 // PerformSHLSimplify would trigger more precisely, but it isn't 10481 // really necessary.) 10482 return false; 10483 } 10484 10485 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 10486 const SDNode *N, CombineLevel Level) const { 10487 if (!Subtarget->isThumb1Only()) 10488 return true; 10489 10490 if (Level == BeforeLegalizeTypes) 10491 return true; 10492 10493 return false; 10494 } 10495 10496 static SDValue PerformSHLSimplify(SDNode *N, 10497 TargetLowering::DAGCombinerInfo &DCI, 10498 const ARMSubtarget *ST) { 10499 // Allow the generic combiner to identify potential bswaps. 10500 if (DCI.isBeforeLegalize()) 10501 return SDValue(); 10502 10503 // DAG combiner will fold: 10504 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10505 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10506 // Other code patterns that can be also be modified have the following form: 10507 // b + ((a << 1) | 510) 10508 // b + ((a << 1) & 510) 10509 // b + ((a << 1) ^ 510) 10510 // b + ((a << 1) + 510) 10511 10512 // Many instructions can perform the shift for free, but it requires both 10513 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10514 // instruction will needed. So, unfold back to the original pattern if: 10515 // - if c1 and c2 are small enough that they don't require mov imms. 10516 // - the user(s) of the node can perform an shl 10517 10518 // No shifted operands for 16-bit instructions. 10519 if (ST->isThumb() && ST->isThumb1Only()) 10520 return SDValue(); 10521 10522 // Check that all the users could perform the shl themselves. 10523 for (auto U : N->uses()) { 10524 switch(U->getOpcode()) { 10525 default: 10526 return SDValue(); 10527 case ISD::SUB: 10528 case ISD::ADD: 10529 case ISD::AND: 10530 case ISD::OR: 10531 case ISD::XOR: 10532 case ISD::SETCC: 10533 case ARMISD::CMP: 10534 // Check that the user isn't already using a constant because there 10535 // aren't any instructions that support an immediate operand and a 10536 // shifted operand. 10537 if (isa<ConstantSDNode>(U->getOperand(0)) || 10538 isa<ConstantSDNode>(U->getOperand(1))) 10539 return SDValue(); 10540 10541 // Check that it's not already using a shift. 10542 if (U->getOperand(0).getOpcode() == ISD::SHL || 10543 U->getOperand(1).getOpcode() == ISD::SHL) 10544 return SDValue(); 10545 break; 10546 } 10547 } 10548 10549 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10550 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10551 return SDValue(); 10552 10553 if (N->getOperand(0).getOpcode() != ISD::SHL) 10554 return SDValue(); 10555 10556 SDValue SHL = N->getOperand(0); 10557 10558 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10559 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10560 if (!C1ShlC2 || !C2) 10561 return SDValue(); 10562 10563 APInt C2Int = C2->getAPIntValue(); 10564 APInt C1Int = C1ShlC2->getAPIntValue(); 10565 10566 // Check that performing a lshr will not lose any information. 10567 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10568 C2Int.getBitWidth() - C2->getZExtValue()); 10569 if ((C1Int & Mask) != C1Int) 10570 return SDValue(); 10571 10572 // Shift the first constant. 10573 C1Int.lshrInPlace(C2Int); 10574 10575 // The immediates are encoded as an 8-bit value that can be rotated. 10576 auto LargeImm = [](const APInt &Imm) { 10577 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 10578 return Imm.getBitWidth() - Zeros > 8; 10579 }; 10580 10581 if (LargeImm(C1Int) || LargeImm(C2Int)) 10582 return SDValue(); 10583 10584 SelectionDAG &DAG = DCI.DAG; 10585 SDLoc dl(N); 10586 SDValue X = SHL.getOperand(0); 10587 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10588 DAG.getConstant(C1Int, dl, MVT::i32)); 10589 // Shift left to compensate for the lshr of C1Int. 10590 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10591 10592 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 10593 SHL.dump(); N->dump()); 10594 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 10595 return Res; 10596 } 10597 10598 10599 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10600 /// 10601 static SDValue PerformADDCombine(SDNode *N, 10602 TargetLowering::DAGCombinerInfo &DCI, 10603 const ARMSubtarget *Subtarget) { 10604 SDValue N0 = N->getOperand(0); 10605 SDValue N1 = N->getOperand(1); 10606 10607 // Only works one way, because it needs an immediate operand. 10608 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10609 return Result; 10610 10611 // First try with the default operand order. 10612 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10613 return Result; 10614 10615 // If that didn't work, try again with the operands commuted. 10616 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10617 } 10618 10619 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10620 /// 10621 static SDValue PerformSUBCombine(SDNode *N, 10622 TargetLowering::DAGCombinerInfo &DCI) { 10623 SDValue N0 = N->getOperand(0); 10624 SDValue N1 = N->getOperand(1); 10625 10626 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10627 if (N1.getNode()->hasOneUse()) 10628 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10629 return Result; 10630 10631 return SDValue(); 10632 } 10633 10634 /// PerformVMULCombine 10635 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10636 /// special multiplier accumulator forwarding. 10637 /// vmul d3, d0, d2 10638 /// vmla d3, d1, d2 10639 /// is faster than 10640 /// vadd d3, d0, d1 10641 /// vmul d3, d3, d2 10642 // However, for (A + B) * (A + B), 10643 // vadd d2, d0, d1 10644 // vmul d3, d0, d2 10645 // vmla d3, d1, d2 10646 // is slower than 10647 // vadd d2, d0, d1 10648 // vmul d3, d2, d2 10649 static SDValue PerformVMULCombine(SDNode *N, 10650 TargetLowering::DAGCombinerInfo &DCI, 10651 const ARMSubtarget *Subtarget) { 10652 if (!Subtarget->hasVMLxForwarding()) 10653 return SDValue(); 10654 10655 SelectionDAG &DAG = DCI.DAG; 10656 SDValue N0 = N->getOperand(0); 10657 SDValue N1 = N->getOperand(1); 10658 unsigned Opcode = N0.getOpcode(); 10659 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10660 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10661 Opcode = N1.getOpcode(); 10662 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10663 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10664 return SDValue(); 10665 std::swap(N0, N1); 10666 } 10667 10668 if (N0 == N1) 10669 return SDValue(); 10670 10671 EVT VT = N->getValueType(0); 10672 SDLoc DL(N); 10673 SDValue N00 = N0->getOperand(0); 10674 SDValue N01 = N0->getOperand(1); 10675 return DAG.getNode(Opcode, DL, VT, 10676 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10677 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10678 } 10679 10680 static SDValue PerformMULCombine(SDNode *N, 10681 TargetLowering::DAGCombinerInfo &DCI, 10682 const ARMSubtarget *Subtarget) { 10683 SelectionDAG &DAG = DCI.DAG; 10684 10685 if (Subtarget->isThumb1Only()) 10686 return SDValue(); 10687 10688 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10689 return SDValue(); 10690 10691 EVT VT = N->getValueType(0); 10692 if (VT.is64BitVector() || VT.is128BitVector()) 10693 return PerformVMULCombine(N, DCI, Subtarget); 10694 if (VT != MVT::i32) 10695 return SDValue(); 10696 10697 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10698 if (!C) 10699 return SDValue(); 10700 10701 int64_t MulAmt = C->getSExtValue(); 10702 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10703 10704 ShiftAmt = ShiftAmt & (32 - 1); 10705 SDValue V = N->getOperand(0); 10706 SDLoc DL(N); 10707 10708 SDValue Res; 10709 MulAmt >>= ShiftAmt; 10710 10711 if (MulAmt >= 0) { 10712 if (isPowerOf2_32(MulAmt - 1)) { 10713 // (mul x, 2^N + 1) => (add (shl x, N), x) 10714 Res = DAG.getNode(ISD::ADD, DL, VT, 10715 V, 10716 DAG.getNode(ISD::SHL, DL, VT, 10717 V, 10718 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10719 MVT::i32))); 10720 } else if (isPowerOf2_32(MulAmt + 1)) { 10721 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10722 Res = DAG.getNode(ISD::SUB, DL, VT, 10723 DAG.getNode(ISD::SHL, DL, VT, 10724 V, 10725 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10726 MVT::i32)), 10727 V); 10728 } else 10729 return SDValue(); 10730 } else { 10731 uint64_t MulAmtAbs = -MulAmt; 10732 if (isPowerOf2_32(MulAmtAbs + 1)) { 10733 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10734 Res = DAG.getNode(ISD::SUB, DL, VT, 10735 V, 10736 DAG.getNode(ISD::SHL, DL, VT, 10737 V, 10738 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10739 MVT::i32))); 10740 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10741 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10742 Res = DAG.getNode(ISD::ADD, DL, VT, 10743 V, 10744 DAG.getNode(ISD::SHL, DL, VT, 10745 V, 10746 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10747 MVT::i32))); 10748 Res = DAG.getNode(ISD::SUB, DL, VT, 10749 DAG.getConstant(0, DL, MVT::i32), Res); 10750 } else 10751 return SDValue(); 10752 } 10753 10754 if (ShiftAmt != 0) 10755 Res = DAG.getNode(ISD::SHL, DL, VT, 10756 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10757 10758 // Do not add new nodes to DAG combiner worklist. 10759 DCI.CombineTo(N, Res, false); 10760 return SDValue(); 10761 } 10762 10763 static SDValue CombineANDShift(SDNode *N, 10764 TargetLowering::DAGCombinerInfo &DCI, 10765 const ARMSubtarget *Subtarget) { 10766 // Allow DAGCombine to pattern-match before we touch the canonical form. 10767 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10768 return SDValue(); 10769 10770 if (N->getValueType(0) != MVT::i32) 10771 return SDValue(); 10772 10773 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10774 if (!N1C) 10775 return SDValue(); 10776 10777 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 10778 // Don't transform uxtb/uxth. 10779 if (C1 == 255 || C1 == 65535) 10780 return SDValue(); 10781 10782 SDNode *N0 = N->getOperand(0).getNode(); 10783 if (!N0->hasOneUse()) 10784 return SDValue(); 10785 10786 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 10787 return SDValue(); 10788 10789 bool LeftShift = N0->getOpcode() == ISD::SHL; 10790 10791 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 10792 if (!N01C) 10793 return SDValue(); 10794 10795 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 10796 if (!C2 || C2 >= 32) 10797 return SDValue(); 10798 10799 // Clear irrelevant bits in the mask. 10800 if (LeftShift) 10801 C1 &= (-1U << C2); 10802 else 10803 C1 &= (-1U >> C2); 10804 10805 SelectionDAG &DAG = DCI.DAG; 10806 SDLoc DL(N); 10807 10808 // We have a pattern of the form "(and (shl x, c2) c1)" or 10809 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 10810 // transform to a pair of shifts, to save materializing c1. 10811 10812 // First pattern: right shift, then mask off leading bits. 10813 // FIXME: Use demanded bits? 10814 if (!LeftShift && isMask_32(C1)) { 10815 uint32_t C3 = countLeadingZeros(C1); 10816 if (C2 < C3) { 10817 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 10818 DAG.getConstant(C3 - C2, DL, MVT::i32)); 10819 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 10820 DAG.getConstant(C3, DL, MVT::i32)); 10821 } 10822 } 10823 10824 // First pattern, reversed: left shift, then mask off trailing bits. 10825 if (LeftShift && isMask_32(~C1)) { 10826 uint32_t C3 = countTrailingZeros(C1); 10827 if (C2 < C3) { 10828 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 10829 DAG.getConstant(C3 - C2, DL, MVT::i32)); 10830 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 10831 DAG.getConstant(C3, DL, MVT::i32)); 10832 } 10833 } 10834 10835 // Second pattern: left shift, then mask off leading bits. 10836 // FIXME: Use demanded bits? 10837 if (LeftShift && isShiftedMask_32(C1)) { 10838 uint32_t Trailing = countTrailingZeros(C1); 10839 uint32_t C3 = countLeadingZeros(C1); 10840 if (Trailing == C2 && C2 + C3 < 32) { 10841 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 10842 DAG.getConstant(C2 + C3, DL, MVT::i32)); 10843 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 10844 DAG.getConstant(C3, DL, MVT::i32)); 10845 } 10846 } 10847 10848 // Second pattern, reversed: right shift, then mask off trailing bits. 10849 // FIXME: Handle other patterns of known/demanded bits. 10850 if (!LeftShift && isShiftedMask_32(C1)) { 10851 uint32_t Leading = countLeadingZeros(C1); 10852 uint32_t C3 = countTrailingZeros(C1); 10853 if (Leading == C2 && C2 + C3 < 32) { 10854 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 10855 DAG.getConstant(C2 + C3, DL, MVT::i32)); 10856 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 10857 DAG.getConstant(C3, DL, MVT::i32)); 10858 } 10859 } 10860 10861 // FIXME: Transform "(and (shl x, c2) c1)" -> 10862 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 10863 // c1. 10864 return SDValue(); 10865 } 10866 10867 static SDValue PerformANDCombine(SDNode *N, 10868 TargetLowering::DAGCombinerInfo &DCI, 10869 const ARMSubtarget *Subtarget) { 10870 // Attempt to use immediate-form VBIC 10871 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10872 SDLoc dl(N); 10873 EVT VT = N->getValueType(0); 10874 SelectionDAG &DAG = DCI.DAG; 10875 10876 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10877 return SDValue(); 10878 10879 APInt SplatBits, SplatUndef; 10880 unsigned SplatBitSize; 10881 bool HasAnyUndefs; 10882 if (BVN && 10883 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10884 if (SplatBitSize <= 64) { 10885 EVT VbicVT; 10886 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10887 SplatUndef.getZExtValue(), SplatBitSize, 10888 DAG, dl, VbicVT, VT.is128BitVector(), 10889 OtherModImm); 10890 if (Val.getNode()) { 10891 SDValue Input = 10892 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10893 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10894 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10895 } 10896 } 10897 } 10898 10899 if (!Subtarget->isThumb1Only()) { 10900 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10901 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10902 return Result; 10903 10904 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10905 return Result; 10906 } 10907 10908 if (Subtarget->isThumb1Only()) 10909 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 10910 return Result; 10911 10912 return SDValue(); 10913 } 10914 10915 // Try combining OR nodes to SMULWB, SMULWT. 10916 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10917 TargetLowering::DAGCombinerInfo &DCI, 10918 const ARMSubtarget *Subtarget) { 10919 if (!Subtarget->hasV6Ops() || 10920 (Subtarget->isThumb() && 10921 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10922 return SDValue(); 10923 10924 SDValue SRL = OR->getOperand(0); 10925 SDValue SHL = OR->getOperand(1); 10926 10927 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10928 SRL = OR->getOperand(1); 10929 SHL = OR->getOperand(0); 10930 } 10931 if (!isSRL16(SRL) || !isSHL16(SHL)) 10932 return SDValue(); 10933 10934 // The first operands to the shifts need to be the two results from the 10935 // same smul_lohi node. 10936 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10937 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10938 return SDValue(); 10939 10940 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10941 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10942 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10943 return SDValue(); 10944 10945 // Now we have: 10946 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10947 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10948 // For SMUWB the 16-bit value will signed extended somehow. 10949 // For SMULWT only the SRA is required. 10950 // Check both sides of SMUL_LOHI 10951 SDValue OpS16 = SMULLOHI->getOperand(0); 10952 SDValue OpS32 = SMULLOHI->getOperand(1); 10953 10954 SelectionDAG &DAG = DCI.DAG; 10955 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10956 OpS16 = OpS32; 10957 OpS32 = SMULLOHI->getOperand(0); 10958 } 10959 10960 SDLoc dl(OR); 10961 unsigned Opcode = 0; 10962 if (isS16(OpS16, DAG)) 10963 Opcode = ARMISD::SMULWB; 10964 else if (isSRA16(OpS16)) { 10965 Opcode = ARMISD::SMULWT; 10966 OpS16 = OpS16->getOperand(0); 10967 } 10968 else 10969 return SDValue(); 10970 10971 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10972 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10973 return SDValue(OR, 0); 10974 } 10975 10976 static SDValue PerformORCombineToBFI(SDNode *N, 10977 TargetLowering::DAGCombinerInfo &DCI, 10978 const ARMSubtarget *Subtarget) { 10979 // BFI is only available on V6T2+ 10980 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10981 return SDValue(); 10982 10983 EVT VT = N->getValueType(0); 10984 SDValue N0 = N->getOperand(0); 10985 SDValue N1 = N->getOperand(1); 10986 SelectionDAG &DAG = DCI.DAG; 10987 SDLoc DL(N); 10988 // 1) or (and A, mask), val => ARMbfi A, val, mask 10989 // iff (val & mask) == val 10990 // 10991 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10992 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10993 // && mask == ~mask2 10994 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10995 // && ~mask == mask2 10996 // (i.e., copy a bitfield value into another bitfield of the same width) 10997 10998 if (VT != MVT::i32) 10999 return SDValue(); 11000 11001 SDValue N00 = N0.getOperand(0); 11002 11003 // The value and the mask need to be constants so we can verify this is 11004 // actually a bitfield set. If the mask is 0xffff, we can do better 11005 // via a movt instruction, so don't use BFI in that case. 11006 SDValue MaskOp = N0.getOperand(1); 11007 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 11008 if (!MaskC) 11009 return SDValue(); 11010 unsigned Mask = MaskC->getZExtValue(); 11011 if (Mask == 0xffff) 11012 return SDValue(); 11013 SDValue Res; 11014 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 11015 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 11016 if (N1C) { 11017 unsigned Val = N1C->getZExtValue(); 11018 if ((Val & ~Mask) != Val) 11019 return SDValue(); 11020 11021 if (ARM::isBitFieldInvertedMask(Mask)) { 11022 Val >>= countTrailingZeros(~Mask); 11023 11024 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 11025 DAG.getConstant(Val, DL, MVT::i32), 11026 DAG.getConstant(Mask, DL, MVT::i32)); 11027 11028 DCI.CombineTo(N, Res, false); 11029 // Return value from the original node to inform the combiner than N is 11030 // now dead. 11031 return SDValue(N, 0); 11032 } 11033 } else if (N1.getOpcode() == ISD::AND) { 11034 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11035 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11036 if (!N11C) 11037 return SDValue(); 11038 unsigned Mask2 = N11C->getZExtValue(); 11039 11040 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 11041 // as is to match. 11042 if (ARM::isBitFieldInvertedMask(Mask) && 11043 (Mask == ~Mask2)) { 11044 // The pack halfword instruction works better for masks that fit it, 11045 // so use that when it's available. 11046 if (Subtarget->hasDSP() && 11047 (Mask == 0xffff || Mask == 0xffff0000)) 11048 return SDValue(); 11049 // 2a 11050 unsigned amt = countTrailingZeros(Mask2); 11051 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 11052 DAG.getConstant(amt, DL, MVT::i32)); 11053 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 11054 DAG.getConstant(Mask, DL, MVT::i32)); 11055 DCI.CombineTo(N, Res, false); 11056 // Return value from the original node to inform the combiner than N is 11057 // now dead. 11058 return SDValue(N, 0); 11059 } else if (ARM::isBitFieldInvertedMask(~Mask) && 11060 (~Mask == Mask2)) { 11061 // The pack halfword instruction works better for masks that fit it, 11062 // so use that when it's available. 11063 if (Subtarget->hasDSP() && 11064 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 11065 return SDValue(); 11066 // 2b 11067 unsigned lsb = countTrailingZeros(Mask); 11068 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 11069 DAG.getConstant(lsb, DL, MVT::i32)); 11070 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 11071 DAG.getConstant(Mask2, DL, MVT::i32)); 11072 DCI.CombineTo(N, Res, false); 11073 // Return value from the original node to inform the combiner than N is 11074 // now dead. 11075 return SDValue(N, 0); 11076 } 11077 } 11078 11079 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 11080 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 11081 ARM::isBitFieldInvertedMask(~Mask)) { 11082 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 11083 // where lsb(mask) == #shamt and masked bits of B are known zero. 11084 SDValue ShAmt = N00.getOperand(1); 11085 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 11086 unsigned LSB = countTrailingZeros(Mask); 11087 if (ShAmtC != LSB) 11088 return SDValue(); 11089 11090 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 11091 DAG.getConstant(~Mask, DL, MVT::i32)); 11092 11093 DCI.CombineTo(N, Res, false); 11094 // Return value from the original node to inform the combiner than N is 11095 // now dead. 11096 return SDValue(N, 0); 11097 } 11098 11099 return SDValue(); 11100 } 11101 11102 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 11103 static SDValue PerformORCombine(SDNode *N, 11104 TargetLowering::DAGCombinerInfo &DCI, 11105 const ARMSubtarget *Subtarget) { 11106 // Attempt to use immediate-form VORR 11107 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11108 SDLoc dl(N); 11109 EVT VT = N->getValueType(0); 11110 SelectionDAG &DAG = DCI.DAG; 11111 11112 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11113 return SDValue(); 11114 11115 APInt SplatBits, SplatUndef; 11116 unsigned SplatBitSize; 11117 bool HasAnyUndefs; 11118 if (BVN && Subtarget->hasNEON() && 11119 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11120 if (SplatBitSize <= 64) { 11121 EVT VorrVT; 11122 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 11123 SplatUndef.getZExtValue(), SplatBitSize, 11124 DAG, dl, VorrVT, VT.is128BitVector(), 11125 OtherModImm); 11126 if (Val.getNode()) { 11127 SDValue Input = 11128 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 11129 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 11130 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 11131 } 11132 } 11133 } 11134 11135 if (!Subtarget->isThumb1Only()) { 11136 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11137 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11138 return Result; 11139 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 11140 return Result; 11141 } 11142 11143 SDValue N0 = N->getOperand(0); 11144 SDValue N1 = N->getOperand(1); 11145 11146 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 11147 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 11148 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 11149 11150 // The code below optimizes (or (and X, Y), Z). 11151 // The AND operand needs to have a single user to make these optimizations 11152 // profitable. 11153 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 11154 return SDValue(); 11155 11156 APInt SplatUndef; 11157 unsigned SplatBitSize; 11158 bool HasAnyUndefs; 11159 11160 APInt SplatBits0, SplatBits1; 11161 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 11162 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 11163 // Ensure that the second operand of both ands are constants 11164 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 11165 HasAnyUndefs) && !HasAnyUndefs) { 11166 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 11167 HasAnyUndefs) && !HasAnyUndefs) { 11168 // Ensure that the bit width of the constants are the same and that 11169 // the splat arguments are logical inverses as per the pattern we 11170 // are trying to simplify. 11171 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 11172 SplatBits0 == ~SplatBits1) { 11173 // Canonicalize the vector type to make instruction selection 11174 // simpler. 11175 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 11176 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 11177 N0->getOperand(1), 11178 N0->getOperand(0), 11179 N1->getOperand(0)); 11180 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 11181 } 11182 } 11183 } 11184 } 11185 11186 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 11187 // reasonable. 11188 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 11189 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 11190 return Res; 11191 } 11192 11193 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11194 return Result; 11195 11196 return SDValue(); 11197 } 11198 11199 static SDValue PerformXORCombine(SDNode *N, 11200 TargetLowering::DAGCombinerInfo &DCI, 11201 const ARMSubtarget *Subtarget) { 11202 EVT VT = N->getValueType(0); 11203 SelectionDAG &DAG = DCI.DAG; 11204 11205 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11206 return SDValue(); 11207 11208 if (!Subtarget->isThumb1Only()) { 11209 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11210 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11211 return Result; 11212 11213 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11214 return Result; 11215 } 11216 11217 return SDValue(); 11218 } 11219 11220 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 11221 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 11222 // their position in "to" (Rd). 11223 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 11224 assert(N->getOpcode() == ARMISD::BFI); 11225 11226 SDValue From = N->getOperand(1); 11227 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 11228 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 11229 11230 // If the Base came from a SHR #C, we can deduce that it is really testing bit 11231 // #C in the base of the SHR. 11232 if (From->getOpcode() == ISD::SRL && 11233 isa<ConstantSDNode>(From->getOperand(1))) { 11234 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 11235 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 11236 FromMask <<= Shift.getLimitedValue(31); 11237 From = From->getOperand(0); 11238 } 11239 11240 return From; 11241 } 11242 11243 // If A and B contain one contiguous set of bits, does A | B == A . B? 11244 // 11245 // Neither A nor B must be zero. 11246 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 11247 unsigned LastActiveBitInA = A.countTrailingZeros(); 11248 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 11249 return LastActiveBitInA - 1 == FirstActiveBitInB; 11250 } 11251 11252 static SDValue FindBFIToCombineWith(SDNode *N) { 11253 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 11254 // if one exists. 11255 APInt ToMask, FromMask; 11256 SDValue From = ParseBFI(N, ToMask, FromMask); 11257 SDValue To = N->getOperand(0); 11258 11259 // Now check for a compatible BFI to merge with. We can pass through BFIs that 11260 // aren't compatible, but not if they set the same bit in their destination as 11261 // we do (or that of any BFI we're going to combine with). 11262 SDValue V = To; 11263 APInt CombinedToMask = ToMask; 11264 while (V.getOpcode() == ARMISD::BFI) { 11265 APInt NewToMask, NewFromMask; 11266 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 11267 if (NewFrom != From) { 11268 // This BFI has a different base. Keep going. 11269 CombinedToMask |= NewToMask; 11270 V = V.getOperand(0); 11271 continue; 11272 } 11273 11274 // Do the written bits conflict with any we've seen so far? 11275 if ((NewToMask & CombinedToMask).getBoolValue()) 11276 // Conflicting bits - bail out because going further is unsafe. 11277 return SDValue(); 11278 11279 // Are the new bits contiguous when combined with the old bits? 11280 if (BitsProperlyConcatenate(ToMask, NewToMask) && 11281 BitsProperlyConcatenate(FromMask, NewFromMask)) 11282 return V; 11283 if (BitsProperlyConcatenate(NewToMask, ToMask) && 11284 BitsProperlyConcatenate(NewFromMask, FromMask)) 11285 return V; 11286 11287 // We've seen a write to some bits, so track it. 11288 CombinedToMask |= NewToMask; 11289 // Keep going... 11290 V = V.getOperand(0); 11291 } 11292 11293 return SDValue(); 11294 } 11295 11296 static SDValue PerformBFICombine(SDNode *N, 11297 TargetLowering::DAGCombinerInfo &DCI) { 11298 SDValue N1 = N->getOperand(1); 11299 if (N1.getOpcode() == ISD::AND) { 11300 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 11301 // the bits being cleared by the AND are not demanded by the BFI. 11302 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11303 if (!N11C) 11304 return SDValue(); 11305 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11306 unsigned LSB = countTrailingZeros(~InvMask); 11307 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 11308 assert(Width < 11309 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 11310 "undefined behavior"); 11311 unsigned Mask = (1u << Width) - 1; 11312 unsigned Mask2 = N11C->getZExtValue(); 11313 if ((Mask & (~Mask2)) == 0) 11314 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 11315 N->getOperand(0), N1.getOperand(0), 11316 N->getOperand(2)); 11317 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 11318 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 11319 // Keep track of any consecutive bits set that all come from the same base 11320 // value. We can combine these together into a single BFI. 11321 SDValue CombineBFI = FindBFIToCombineWith(N); 11322 if (CombineBFI == SDValue()) 11323 return SDValue(); 11324 11325 // We've found a BFI. 11326 APInt ToMask1, FromMask1; 11327 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 11328 11329 APInt ToMask2, FromMask2; 11330 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 11331 assert(From1 == From2); 11332 (void)From2; 11333 11334 // First, unlink CombineBFI. 11335 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 11336 // Then create a new BFI, combining the two together. 11337 APInt NewFromMask = FromMask1 | FromMask2; 11338 APInt NewToMask = ToMask1 | ToMask2; 11339 11340 EVT VT = N->getValueType(0); 11341 SDLoc dl(N); 11342 11343 if (NewFromMask[0] == 0) 11344 From1 = DCI.DAG.getNode( 11345 ISD::SRL, dl, VT, From1, 11346 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 11347 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 11348 DCI.DAG.getConstant(~NewToMask, dl, VT)); 11349 } 11350 return SDValue(); 11351 } 11352 11353 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 11354 /// ARMISD::VMOVRRD. 11355 static SDValue PerformVMOVRRDCombine(SDNode *N, 11356 TargetLowering::DAGCombinerInfo &DCI, 11357 const ARMSubtarget *Subtarget) { 11358 // vmovrrd(vmovdrr x, y) -> x,y 11359 SDValue InDouble = N->getOperand(0); 11360 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 11361 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 11362 11363 // vmovrrd(load f64) -> (load i32), (load i32) 11364 SDNode *InNode = InDouble.getNode(); 11365 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 11366 InNode->getValueType(0) == MVT::f64 && 11367 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 11368 !cast<LoadSDNode>(InNode)->isVolatile()) { 11369 // TODO: Should this be done for non-FrameIndex operands? 11370 LoadSDNode *LD = cast<LoadSDNode>(InNode); 11371 11372 SelectionDAG &DAG = DCI.DAG; 11373 SDLoc DL(LD); 11374 SDValue BasePtr = LD->getBasePtr(); 11375 SDValue NewLD1 = 11376 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 11377 LD->getAlignment(), LD->getMemOperand()->getFlags()); 11378 11379 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11380 DAG.getConstant(4, DL, MVT::i32)); 11381 SDValue NewLD2 = DAG.getLoad( 11382 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 11383 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 11384 11385 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 11386 if (DCI.DAG.getDataLayout().isBigEndian()) 11387 std::swap (NewLD1, NewLD2); 11388 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 11389 return Result; 11390 } 11391 11392 return SDValue(); 11393 } 11394 11395 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 11396 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 11397 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 11398 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 11399 SDValue Op0 = N->getOperand(0); 11400 SDValue Op1 = N->getOperand(1); 11401 if (Op0.getOpcode() == ISD::BITCAST) 11402 Op0 = Op0.getOperand(0); 11403 if (Op1.getOpcode() == ISD::BITCAST) 11404 Op1 = Op1.getOperand(0); 11405 if (Op0.getOpcode() == ARMISD::VMOVRRD && 11406 Op0.getNode() == Op1.getNode() && 11407 Op0.getResNo() == 0 && Op1.getResNo() == 1) 11408 return DAG.getNode(ISD::BITCAST, SDLoc(N), 11409 N->getValueType(0), Op0.getOperand(0)); 11410 return SDValue(); 11411 } 11412 11413 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 11414 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 11415 /// i64 vector to have f64 elements, since the value can then be loaded 11416 /// directly into a VFP register. 11417 static bool hasNormalLoadOperand(SDNode *N) { 11418 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 11419 for (unsigned i = 0; i < NumElts; ++i) { 11420 SDNode *Elt = N->getOperand(i).getNode(); 11421 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 11422 return true; 11423 } 11424 return false; 11425 } 11426 11427 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 11428 /// ISD::BUILD_VECTOR. 11429 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 11430 TargetLowering::DAGCombinerInfo &DCI, 11431 const ARMSubtarget *Subtarget) { 11432 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 11433 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 11434 // into a pair of GPRs, which is fine when the value is used as a scalar, 11435 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 11436 SelectionDAG &DAG = DCI.DAG; 11437 if (N->getNumOperands() == 2) 11438 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 11439 return RV; 11440 11441 // Load i64 elements as f64 values so that type legalization does not split 11442 // them up into i32 values. 11443 EVT VT = N->getValueType(0); 11444 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11445 return SDValue(); 11446 SDLoc dl(N); 11447 SmallVector<SDValue, 8> Ops; 11448 unsigned NumElts = VT.getVectorNumElements(); 11449 for (unsigned i = 0; i < NumElts; ++i) { 11450 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11451 Ops.push_back(V); 11452 // Make the DAGCombiner fold the bitcast. 11453 DCI.AddToWorklist(V.getNode()); 11454 } 11455 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11456 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11457 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11458 } 11459 11460 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11461 static SDValue 11462 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11463 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11464 // At that time, we may have inserted bitcasts from integer to float. 11465 // If these bitcasts have survived DAGCombine, change the lowering of this 11466 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11467 // force to use floating point types. 11468 11469 // Make sure we can change the type of the vector. 11470 // This is possible iff: 11471 // 1. The vector is only used in a bitcast to a integer type. I.e., 11472 // 1.1. Vector is used only once. 11473 // 1.2. Use is a bit convert to an integer type. 11474 // 2. The size of its operands are 32-bits (64-bits are not legal). 11475 EVT VT = N->getValueType(0); 11476 EVT EltVT = VT.getVectorElementType(); 11477 11478 // Check 1.1. and 2. 11479 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11480 return SDValue(); 11481 11482 // By construction, the input type must be float. 11483 assert(EltVT == MVT::f32 && "Unexpected type!"); 11484 11485 // Check 1.2. 11486 SDNode *Use = *N->use_begin(); 11487 if (Use->getOpcode() != ISD::BITCAST || 11488 Use->getValueType(0).isFloatingPoint()) 11489 return SDValue(); 11490 11491 // Check profitability. 11492 // Model is, if more than half of the relevant operands are bitcast from 11493 // i32, turn the build_vector into a sequence of insert_vector_elt. 11494 // Relevant operands are everything that is not statically 11495 // (i.e., at compile time) bitcasted. 11496 unsigned NumOfBitCastedElts = 0; 11497 unsigned NumElts = VT.getVectorNumElements(); 11498 unsigned NumOfRelevantElts = NumElts; 11499 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11500 SDValue Elt = N->getOperand(Idx); 11501 if (Elt->getOpcode() == ISD::BITCAST) { 11502 // Assume only bit cast to i32 will go away. 11503 if (Elt->getOperand(0).getValueType() == MVT::i32) 11504 ++NumOfBitCastedElts; 11505 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11506 // Constants are statically casted, thus do not count them as 11507 // relevant operands. 11508 --NumOfRelevantElts; 11509 } 11510 11511 // Check if more than half of the elements require a non-free bitcast. 11512 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11513 return SDValue(); 11514 11515 SelectionDAG &DAG = DCI.DAG; 11516 // Create the new vector type. 11517 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11518 // Check if the type is legal. 11519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11520 if (!TLI.isTypeLegal(VecVT)) 11521 return SDValue(); 11522 11523 // Combine: 11524 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11525 // => BITCAST INSERT_VECTOR_ELT 11526 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11527 // (BITCAST EN), N. 11528 SDValue Vec = DAG.getUNDEF(VecVT); 11529 SDLoc dl(N); 11530 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11531 SDValue V = N->getOperand(Idx); 11532 if (V.isUndef()) 11533 continue; 11534 if (V.getOpcode() == ISD::BITCAST && 11535 V->getOperand(0).getValueType() == MVT::i32) 11536 // Fold obvious case. 11537 V = V.getOperand(0); 11538 else { 11539 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11540 // Make the DAGCombiner fold the bitcasts. 11541 DCI.AddToWorklist(V.getNode()); 11542 } 11543 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11544 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11545 } 11546 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11547 // Make the DAGCombiner fold the bitcasts. 11548 DCI.AddToWorklist(Vec.getNode()); 11549 return Vec; 11550 } 11551 11552 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11553 /// ISD::INSERT_VECTOR_ELT. 11554 static SDValue PerformInsertEltCombine(SDNode *N, 11555 TargetLowering::DAGCombinerInfo &DCI) { 11556 // Bitcast an i64 load inserted into a vector to f64. 11557 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11558 EVT VT = N->getValueType(0); 11559 SDNode *Elt = N->getOperand(1).getNode(); 11560 if (VT.getVectorElementType() != MVT::i64 || 11561 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11562 return SDValue(); 11563 11564 SelectionDAG &DAG = DCI.DAG; 11565 SDLoc dl(N); 11566 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11567 VT.getVectorNumElements()); 11568 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11569 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11570 // Make the DAGCombiner fold the bitcasts. 11571 DCI.AddToWorklist(Vec.getNode()); 11572 DCI.AddToWorklist(V.getNode()); 11573 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11574 Vec, V, N->getOperand(2)); 11575 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11576 } 11577 11578 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11579 /// ISD::VECTOR_SHUFFLE. 11580 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11581 // The LLVM shufflevector instruction does not require the shuffle mask 11582 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11583 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11584 // operands do not match the mask length, they are extended by concatenating 11585 // them with undef vectors. That is probably the right thing for other 11586 // targets, but for NEON it is better to concatenate two double-register 11587 // size vector operands into a single quad-register size vector. Do that 11588 // transformation here: 11589 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11590 // shuffle(concat(v1, v2), undef) 11591 SDValue Op0 = N->getOperand(0); 11592 SDValue Op1 = N->getOperand(1); 11593 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11594 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11595 Op0.getNumOperands() != 2 || 11596 Op1.getNumOperands() != 2) 11597 return SDValue(); 11598 SDValue Concat0Op1 = Op0.getOperand(1); 11599 SDValue Concat1Op1 = Op1.getOperand(1); 11600 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11601 return SDValue(); 11602 // Skip the transformation if any of the types are illegal. 11603 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11604 EVT VT = N->getValueType(0); 11605 if (!TLI.isTypeLegal(VT) || 11606 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11607 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11608 return SDValue(); 11609 11610 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11611 Op0.getOperand(0), Op1.getOperand(0)); 11612 // Translate the shuffle mask. 11613 SmallVector<int, 16> NewMask; 11614 unsigned NumElts = VT.getVectorNumElements(); 11615 unsigned HalfElts = NumElts/2; 11616 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11617 for (unsigned n = 0; n < NumElts; ++n) { 11618 int MaskElt = SVN->getMaskElt(n); 11619 int NewElt = -1; 11620 if (MaskElt < (int)HalfElts) 11621 NewElt = MaskElt; 11622 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11623 NewElt = HalfElts + MaskElt - NumElts; 11624 NewMask.push_back(NewElt); 11625 } 11626 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11627 DAG.getUNDEF(VT), NewMask); 11628 } 11629 11630 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11631 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11632 /// base address updates. 11633 /// For generic load/stores, the memory type is assumed to be a vector. 11634 /// The caller is assumed to have checked legality. 11635 static SDValue CombineBaseUpdate(SDNode *N, 11636 TargetLowering::DAGCombinerInfo &DCI) { 11637 SelectionDAG &DAG = DCI.DAG; 11638 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11639 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11640 const bool isStore = N->getOpcode() == ISD::STORE; 11641 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11642 SDValue Addr = N->getOperand(AddrOpIdx); 11643 MemSDNode *MemN = cast<MemSDNode>(N); 11644 SDLoc dl(N); 11645 11646 // Search for a use of the address operand that is an increment. 11647 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11648 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11649 SDNode *User = *UI; 11650 if (User->getOpcode() != ISD::ADD || 11651 UI.getUse().getResNo() != Addr.getResNo()) 11652 continue; 11653 11654 // Check that the add is independent of the load/store. Otherwise, folding 11655 // it would create a cycle. We can avoid searching through Addr as it's a 11656 // predecessor to both. 11657 SmallPtrSet<const SDNode *, 32> Visited; 11658 SmallVector<const SDNode *, 16> Worklist; 11659 Visited.insert(Addr.getNode()); 11660 Worklist.push_back(N); 11661 Worklist.push_back(User); 11662 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 11663 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 11664 continue; 11665 11666 // Find the new opcode for the updating load/store. 11667 bool isLoadOp = true; 11668 bool isLaneOp = false; 11669 unsigned NewOpc = 0; 11670 unsigned NumVecs = 0; 11671 if (isIntrinsic) { 11672 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11673 switch (IntNo) { 11674 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11675 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11676 NumVecs = 1; break; 11677 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11678 NumVecs = 2; break; 11679 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11680 NumVecs = 3; break; 11681 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11682 NumVecs = 4; break; 11683 case Intrinsic::arm_neon_vld2dup: 11684 case Intrinsic::arm_neon_vld3dup: 11685 case Intrinsic::arm_neon_vld4dup: 11686 // TODO: Support updating VLDxDUP nodes. For now, we just skip 11687 // combining base updates for such intrinsics. 11688 continue; 11689 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11690 NumVecs = 2; isLaneOp = true; break; 11691 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11692 NumVecs = 3; isLaneOp = true; break; 11693 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11694 NumVecs = 4; isLaneOp = true; break; 11695 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11696 NumVecs = 1; isLoadOp = false; break; 11697 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11698 NumVecs = 2; isLoadOp = false; break; 11699 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11700 NumVecs = 3; isLoadOp = false; break; 11701 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11702 NumVecs = 4; isLoadOp = false; break; 11703 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11704 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11705 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11706 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11707 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11708 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11709 } 11710 } else { 11711 isLaneOp = true; 11712 switch (N->getOpcode()) { 11713 default: llvm_unreachable("unexpected opcode for Neon base update"); 11714 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11715 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11716 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11717 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11718 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11719 NumVecs = 1; isLaneOp = false; break; 11720 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11721 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11722 } 11723 } 11724 11725 // Find the size of memory referenced by the load/store. 11726 EVT VecTy; 11727 if (isLoadOp) { 11728 VecTy = N->getValueType(0); 11729 } else if (isIntrinsic) { 11730 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11731 } else { 11732 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11733 VecTy = N->getOperand(1).getValueType(); 11734 } 11735 11736 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11737 if (isLaneOp) 11738 NumBytes /= VecTy.getVectorNumElements(); 11739 11740 // If the increment is a constant, it must match the memory ref size. 11741 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11742 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11743 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11744 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11745 // separate instructions that make it harder to use a non-constant update. 11746 continue; 11747 } 11748 11749 // OK, we found an ADD we can fold into the base update. 11750 // Now, create a _UPD node, taking care of not breaking alignment. 11751 11752 EVT AlignedVecTy = VecTy; 11753 unsigned Alignment = MemN->getAlignment(); 11754 11755 // If this is a less-than-standard-aligned load/store, change the type to 11756 // match the standard alignment. 11757 // The alignment is overlooked when selecting _UPD variants; and it's 11758 // easier to introduce bitcasts here than fix that. 11759 // There are 3 ways to get to this base-update combine: 11760 // - intrinsics: they are assumed to be properly aligned (to the standard 11761 // alignment of the memory type), so we don't need to do anything. 11762 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11763 // intrinsics, so, likewise, there's nothing to do. 11764 // - generic load/store instructions: the alignment is specified as an 11765 // explicit operand, rather than implicitly as the standard alignment 11766 // of the memory type (like the intrisics). We need to change the 11767 // memory type to match the explicit alignment. That way, we don't 11768 // generate non-standard-aligned ARMISD::VLDx nodes. 11769 if (isa<LSBaseSDNode>(N)) { 11770 if (Alignment == 0) 11771 Alignment = 1; 11772 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11773 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11774 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11775 assert(!isLaneOp && "Unexpected generic load/store lane."); 11776 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11777 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11778 } 11779 // Don't set an explicit alignment on regular load/stores that we want 11780 // to transform to VLD/VST 1_UPD nodes. 11781 // This matches the behavior of regular load/stores, which only get an 11782 // explicit alignment if the MMO alignment is larger than the standard 11783 // alignment of the memory type. 11784 // Intrinsics, however, always get an explicit alignment, set to the 11785 // alignment of the MMO. 11786 Alignment = 1; 11787 } 11788 11789 // Create the new updating load/store node. 11790 // First, create an SDVTList for the new updating node's results. 11791 EVT Tys[6]; 11792 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11793 unsigned n; 11794 for (n = 0; n < NumResultVecs; ++n) 11795 Tys[n] = AlignedVecTy; 11796 Tys[n++] = MVT::i32; 11797 Tys[n] = MVT::Other; 11798 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11799 11800 // Then, gather the new node's operands. 11801 SmallVector<SDValue, 8> Ops; 11802 Ops.push_back(N->getOperand(0)); // incoming chain 11803 Ops.push_back(N->getOperand(AddrOpIdx)); 11804 Ops.push_back(Inc); 11805 11806 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11807 // Try to match the intrinsic's signature 11808 Ops.push_back(StN->getValue()); 11809 } else { 11810 // Loads (and of course intrinsics) match the intrinsics' signature, 11811 // so just add all but the alignment operand. 11812 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11813 Ops.push_back(N->getOperand(i)); 11814 } 11815 11816 // For all node types, the alignment operand is always the last one. 11817 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11818 11819 // If this is a non-standard-aligned STORE, the penultimate operand is the 11820 // stored value. Bitcast it to the aligned type. 11821 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11822 SDValue &StVal = Ops[Ops.size()-2]; 11823 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11824 } 11825 11826 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11827 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11828 MemN->getMemOperand()); 11829 11830 // Update the uses. 11831 SmallVector<SDValue, 5> NewResults; 11832 for (unsigned i = 0; i < NumResultVecs; ++i) 11833 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11834 11835 // If this is an non-standard-aligned LOAD, the first result is the loaded 11836 // value. Bitcast it to the expected result type. 11837 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11838 SDValue &LdVal = NewResults[0]; 11839 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11840 } 11841 11842 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11843 DCI.CombineTo(N, NewResults); 11844 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11845 11846 break; 11847 } 11848 return SDValue(); 11849 } 11850 11851 static SDValue PerformVLDCombine(SDNode *N, 11852 TargetLowering::DAGCombinerInfo &DCI) { 11853 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11854 return SDValue(); 11855 11856 return CombineBaseUpdate(N, DCI); 11857 } 11858 11859 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11860 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11861 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11862 /// return true. 11863 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11864 SelectionDAG &DAG = DCI.DAG; 11865 EVT VT = N->getValueType(0); 11866 // vldN-dup instructions only support 64-bit vectors for N > 1. 11867 if (!VT.is64BitVector()) 11868 return false; 11869 11870 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11871 SDNode *VLD = N->getOperand(0).getNode(); 11872 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11873 return false; 11874 unsigned NumVecs = 0; 11875 unsigned NewOpc = 0; 11876 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11877 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11878 NumVecs = 2; 11879 NewOpc = ARMISD::VLD2DUP; 11880 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11881 NumVecs = 3; 11882 NewOpc = ARMISD::VLD3DUP; 11883 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11884 NumVecs = 4; 11885 NewOpc = ARMISD::VLD4DUP; 11886 } else { 11887 return false; 11888 } 11889 11890 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11891 // numbers match the load. 11892 unsigned VLDLaneNo = 11893 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11894 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11895 UI != UE; ++UI) { 11896 // Ignore uses of the chain result. 11897 if (UI.getUse().getResNo() == NumVecs) 11898 continue; 11899 SDNode *User = *UI; 11900 if (User->getOpcode() != ARMISD::VDUPLANE || 11901 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11902 return false; 11903 } 11904 11905 // Create the vldN-dup node. 11906 EVT Tys[5]; 11907 unsigned n; 11908 for (n = 0; n < NumVecs; ++n) 11909 Tys[n] = VT; 11910 Tys[n] = MVT::Other; 11911 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11912 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11913 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11914 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11915 Ops, VLDMemInt->getMemoryVT(), 11916 VLDMemInt->getMemOperand()); 11917 11918 // Update the uses. 11919 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11920 UI != UE; ++UI) { 11921 unsigned ResNo = UI.getUse().getResNo(); 11922 // Ignore uses of the chain result. 11923 if (ResNo == NumVecs) 11924 continue; 11925 SDNode *User = *UI; 11926 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11927 } 11928 11929 // Now the vldN-lane intrinsic is dead except for its chain result. 11930 // Update uses of the chain. 11931 std::vector<SDValue> VLDDupResults; 11932 for (unsigned n = 0; n < NumVecs; ++n) 11933 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11934 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11935 DCI.CombineTo(VLD, VLDDupResults); 11936 11937 return true; 11938 } 11939 11940 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11941 /// ARMISD::VDUPLANE. 11942 static SDValue PerformVDUPLANECombine(SDNode *N, 11943 TargetLowering::DAGCombinerInfo &DCI) { 11944 SDValue Op = N->getOperand(0); 11945 11946 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11947 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11948 if (CombineVLDDUP(N, DCI)) 11949 return SDValue(N, 0); 11950 11951 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11952 // redundant. Ignore bit_converts for now; element sizes are checked below. 11953 while (Op.getOpcode() == ISD::BITCAST) 11954 Op = Op.getOperand(0); 11955 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11956 return SDValue(); 11957 11958 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11959 unsigned EltSize = Op.getScalarValueSizeInBits(); 11960 // The canonical VMOV for a zero vector uses a 32-bit element size. 11961 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11962 unsigned EltBits; 11963 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11964 EltSize = 8; 11965 EVT VT = N->getValueType(0); 11966 if (EltSize > VT.getScalarSizeInBits()) 11967 return SDValue(); 11968 11969 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11970 } 11971 11972 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11973 static SDValue PerformVDUPCombine(SDNode *N, 11974 TargetLowering::DAGCombinerInfo &DCI) { 11975 SelectionDAG &DAG = DCI.DAG; 11976 SDValue Op = N->getOperand(0); 11977 11978 // Match VDUP(LOAD) -> VLD1DUP. 11979 // We match this pattern here rather than waiting for isel because the 11980 // transform is only legal for unindexed loads. 11981 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11982 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11983 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11984 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11985 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11986 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11987 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11988 Ops, LD->getMemoryVT(), 11989 LD->getMemOperand()); 11990 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11991 return VLDDup; 11992 } 11993 11994 return SDValue(); 11995 } 11996 11997 static SDValue PerformLOADCombine(SDNode *N, 11998 TargetLowering::DAGCombinerInfo &DCI) { 11999 EVT VT = N->getValueType(0); 12000 12001 // If this is a legal vector load, try to combine it into a VLD1_UPD. 12002 if (ISD::isNormalLoad(N) && VT.isVector() && 12003 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12004 return CombineBaseUpdate(N, DCI); 12005 12006 return SDValue(); 12007 } 12008 12009 /// PerformSTORECombine - Target-specific dag combine xforms for 12010 /// ISD::STORE. 12011 static SDValue PerformSTORECombine(SDNode *N, 12012 TargetLowering::DAGCombinerInfo &DCI) { 12013 StoreSDNode *St = cast<StoreSDNode>(N); 12014 if (St->isVolatile()) 12015 return SDValue(); 12016 12017 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 12018 // pack all of the elements in one place. Next, store to memory in fewer 12019 // chunks. 12020 SDValue StVal = St->getValue(); 12021 EVT VT = StVal.getValueType(); 12022 if (St->isTruncatingStore() && VT.isVector()) { 12023 SelectionDAG &DAG = DCI.DAG; 12024 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12025 EVT StVT = St->getMemoryVT(); 12026 unsigned NumElems = VT.getVectorNumElements(); 12027 assert(StVT != VT && "Cannot truncate to the same type"); 12028 unsigned FromEltSz = VT.getScalarSizeInBits(); 12029 unsigned ToEltSz = StVT.getScalarSizeInBits(); 12030 12031 // From, To sizes and ElemCount must be pow of two 12032 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 12033 12034 // We are going to use the original vector elt for storing. 12035 // Accumulated smaller vector elements must be a multiple of the store size. 12036 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 12037 12038 unsigned SizeRatio = FromEltSz / ToEltSz; 12039 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 12040 12041 // Create a type on which we perform the shuffle. 12042 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 12043 NumElems*SizeRatio); 12044 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 12045 12046 SDLoc DL(St); 12047 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 12048 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 12049 for (unsigned i = 0; i < NumElems; ++i) 12050 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 12051 ? (i + 1) * SizeRatio - 1 12052 : i * SizeRatio; 12053 12054 // Can't shuffle using an illegal type. 12055 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 12056 12057 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 12058 DAG.getUNDEF(WideVec.getValueType()), 12059 ShuffleVec); 12060 // At this point all of the data is stored at the bottom of the 12061 // register. We now need to save it to mem. 12062 12063 // Find the largest store unit 12064 MVT StoreType = MVT::i8; 12065 for (MVT Tp : MVT::integer_valuetypes()) { 12066 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 12067 StoreType = Tp; 12068 } 12069 // Didn't find a legal store type. 12070 if (!TLI.isTypeLegal(StoreType)) 12071 return SDValue(); 12072 12073 // Bitcast the original vector into a vector of store-size units 12074 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 12075 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 12076 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 12077 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 12078 SmallVector<SDValue, 8> Chains; 12079 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 12080 TLI.getPointerTy(DAG.getDataLayout())); 12081 SDValue BasePtr = St->getBasePtr(); 12082 12083 // Perform one or more big stores into memory. 12084 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 12085 for (unsigned I = 0; I < E; I++) { 12086 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 12087 StoreType, ShuffWide, 12088 DAG.getIntPtrConstant(I, DL)); 12089 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 12090 St->getPointerInfo(), St->getAlignment(), 12091 St->getMemOperand()->getFlags()); 12092 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 12093 Increment); 12094 Chains.push_back(Ch); 12095 } 12096 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 12097 } 12098 12099 if (!ISD::isNormalStore(St)) 12100 return SDValue(); 12101 12102 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 12103 // ARM stores of arguments in the same cache line. 12104 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 12105 StVal.getNode()->hasOneUse()) { 12106 SelectionDAG &DAG = DCI.DAG; 12107 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 12108 SDLoc DL(St); 12109 SDValue BasePtr = St->getBasePtr(); 12110 SDValue NewST1 = DAG.getStore( 12111 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 12112 BasePtr, St->getPointerInfo(), St->getAlignment(), 12113 St->getMemOperand()->getFlags()); 12114 12115 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12116 DAG.getConstant(4, DL, MVT::i32)); 12117 return DAG.getStore(NewST1.getValue(0), DL, 12118 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 12119 OffsetPtr, St->getPointerInfo(), 12120 std::min(4U, St->getAlignment() / 2), 12121 St->getMemOperand()->getFlags()); 12122 } 12123 12124 if (StVal.getValueType() == MVT::i64 && 12125 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12126 12127 // Bitcast an i64 store extracted from a vector to f64. 12128 // Otherwise, the i64 value will be legalized to a pair of i32 values. 12129 SelectionDAG &DAG = DCI.DAG; 12130 SDLoc dl(StVal); 12131 SDValue IntVec = StVal.getOperand(0); 12132 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 12133 IntVec.getValueType().getVectorNumElements()); 12134 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 12135 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 12136 Vec, StVal.getOperand(1)); 12137 dl = SDLoc(N); 12138 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 12139 // Make the DAGCombiner fold the bitcasts. 12140 DCI.AddToWorklist(Vec.getNode()); 12141 DCI.AddToWorklist(ExtElt.getNode()); 12142 DCI.AddToWorklist(V.getNode()); 12143 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 12144 St->getPointerInfo(), St->getAlignment(), 12145 St->getMemOperand()->getFlags(), St->getAAInfo()); 12146 } 12147 12148 // If this is a legal vector store, try to combine it into a VST1_UPD. 12149 if (ISD::isNormalStore(N) && VT.isVector() && 12150 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12151 return CombineBaseUpdate(N, DCI); 12152 12153 return SDValue(); 12154 } 12155 12156 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 12157 /// can replace combinations of VMUL and VCVT (floating-point to integer) 12158 /// when the VMUL has a constant operand that is a power of 2. 12159 /// 12160 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12161 /// vmul.f32 d16, d17, d16 12162 /// vcvt.s32.f32 d16, d16 12163 /// becomes: 12164 /// vcvt.s32.f32 d16, d16, #3 12165 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 12166 const ARMSubtarget *Subtarget) { 12167 if (!Subtarget->hasNEON()) 12168 return SDValue(); 12169 12170 SDValue Op = N->getOperand(0); 12171 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12172 Op.getOpcode() != ISD::FMUL) 12173 return SDValue(); 12174 12175 SDValue ConstVec = Op->getOperand(1); 12176 if (!isa<BuildVectorSDNode>(ConstVec)) 12177 return SDValue(); 12178 12179 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 12180 uint32_t FloatBits = FloatTy.getSizeInBits(); 12181 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 12182 uint32_t IntBits = IntTy.getSizeInBits(); 12183 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12184 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 12185 // These instructions only exist converting from f32 to i32. We can handle 12186 // smaller integers by generating an extra truncate, but larger ones would 12187 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 12188 // these intructions only support v2i32/v4i32 types. 12189 return SDValue(); 12190 } 12191 12192 BitVector UndefElements; 12193 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12194 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12195 if (C == -1 || C == 0 || C > 32) 12196 return SDValue(); 12197 12198 SDLoc dl(N); 12199 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 12200 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 12201 Intrinsic::arm_neon_vcvtfp2fxu; 12202 SDValue FixConv = DAG.getNode( 12203 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12204 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 12205 DAG.getConstant(C, dl, MVT::i32)); 12206 12207 if (IntBits < FloatBits) 12208 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 12209 12210 return FixConv; 12211 } 12212 12213 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 12214 /// can replace combinations of VCVT (integer to floating-point) and VDIV 12215 /// when the VDIV has a constant operand that is a power of 2. 12216 /// 12217 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12218 /// vcvt.f32.s32 d16, d16 12219 /// vdiv.f32 d16, d17, d16 12220 /// becomes: 12221 /// vcvt.f32.s32 d16, d16, #3 12222 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 12223 const ARMSubtarget *Subtarget) { 12224 if (!Subtarget->hasNEON()) 12225 return SDValue(); 12226 12227 SDValue Op = N->getOperand(0); 12228 unsigned OpOpcode = Op.getNode()->getOpcode(); 12229 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 12230 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 12231 return SDValue(); 12232 12233 SDValue ConstVec = N->getOperand(1); 12234 if (!isa<BuildVectorSDNode>(ConstVec)) 12235 return SDValue(); 12236 12237 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12238 uint32_t FloatBits = FloatTy.getSizeInBits(); 12239 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12240 uint32_t IntBits = IntTy.getSizeInBits(); 12241 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12242 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 12243 // These instructions only exist converting from i32 to f32. We can handle 12244 // smaller integers by generating an extra extend, but larger ones would 12245 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 12246 // these intructions only support v2i32/v4i32 types. 12247 return SDValue(); 12248 } 12249 12250 BitVector UndefElements; 12251 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12252 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12253 if (C == -1 || C == 0 || C > 32) 12254 return SDValue(); 12255 12256 SDLoc dl(N); 12257 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 12258 SDValue ConvInput = Op.getOperand(0); 12259 if (IntBits < FloatBits) 12260 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12261 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12262 ConvInput); 12263 12264 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 12265 Intrinsic::arm_neon_vcvtfxu2fp; 12266 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 12267 Op.getValueType(), 12268 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 12269 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 12270 } 12271 12272 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 12273 /// operand of a vector shift operation, where all the elements of the 12274 /// build_vector must have the same constant integer value. 12275 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 12276 // Ignore bit_converts. 12277 while (Op.getOpcode() == ISD::BITCAST) 12278 Op = Op.getOperand(0); 12279 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 12280 APInt SplatBits, SplatUndef; 12281 unsigned SplatBitSize; 12282 bool HasAnyUndefs; 12283 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 12284 HasAnyUndefs, ElementBits) || 12285 SplatBitSize > ElementBits) 12286 return false; 12287 Cnt = SplatBits.getSExtValue(); 12288 return true; 12289 } 12290 12291 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 12292 /// operand of a vector shift left operation. That value must be in the range: 12293 /// 0 <= Value < ElementBits for a left shift; or 12294 /// 0 <= Value <= ElementBits for a long left shift. 12295 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 12296 assert(VT.isVector() && "vector shift count is not a vector type"); 12297 int64_t ElementBits = VT.getScalarSizeInBits(); 12298 if (! getVShiftImm(Op, ElementBits, Cnt)) 12299 return false; 12300 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 12301 } 12302 12303 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 12304 /// operand of a vector shift right operation. For a shift opcode, the value 12305 /// is positive, but for an intrinsic the value count must be negative. The 12306 /// absolute value must be in the range: 12307 /// 1 <= |Value| <= ElementBits for a right shift; or 12308 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 12309 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 12310 int64_t &Cnt) { 12311 assert(VT.isVector() && "vector shift count is not a vector type"); 12312 int64_t ElementBits = VT.getScalarSizeInBits(); 12313 if (! getVShiftImm(Op, ElementBits, Cnt)) 12314 return false; 12315 if (!isIntrinsic) 12316 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 12317 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 12318 Cnt = -Cnt; 12319 return true; 12320 } 12321 return false; 12322 } 12323 12324 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 12325 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 12326 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12327 switch (IntNo) { 12328 default: 12329 // Don't do anything for most intrinsics. 12330 break; 12331 12332 // Vector shifts: check for immediate versions and lower them. 12333 // Note: This is done during DAG combining instead of DAG legalizing because 12334 // the build_vectors for 64-bit vector element shift counts are generally 12335 // not legal, and it is hard to see their values after they get legalized to 12336 // loads from a constant pool. 12337 case Intrinsic::arm_neon_vshifts: 12338 case Intrinsic::arm_neon_vshiftu: 12339 case Intrinsic::arm_neon_vrshifts: 12340 case Intrinsic::arm_neon_vrshiftu: 12341 case Intrinsic::arm_neon_vrshiftn: 12342 case Intrinsic::arm_neon_vqshifts: 12343 case Intrinsic::arm_neon_vqshiftu: 12344 case Intrinsic::arm_neon_vqshiftsu: 12345 case Intrinsic::arm_neon_vqshiftns: 12346 case Intrinsic::arm_neon_vqshiftnu: 12347 case Intrinsic::arm_neon_vqshiftnsu: 12348 case Intrinsic::arm_neon_vqrshiftns: 12349 case Intrinsic::arm_neon_vqrshiftnu: 12350 case Intrinsic::arm_neon_vqrshiftnsu: { 12351 EVT VT = N->getOperand(1).getValueType(); 12352 int64_t Cnt; 12353 unsigned VShiftOpc = 0; 12354 12355 switch (IntNo) { 12356 case Intrinsic::arm_neon_vshifts: 12357 case Intrinsic::arm_neon_vshiftu: 12358 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 12359 VShiftOpc = ARMISD::VSHL; 12360 break; 12361 } 12362 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 12363 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 12364 ARMISD::VSHRs : ARMISD::VSHRu); 12365 break; 12366 } 12367 return SDValue(); 12368 12369 case Intrinsic::arm_neon_vrshifts: 12370 case Intrinsic::arm_neon_vrshiftu: 12371 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 12372 break; 12373 return SDValue(); 12374 12375 case Intrinsic::arm_neon_vqshifts: 12376 case Intrinsic::arm_neon_vqshiftu: 12377 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12378 break; 12379 return SDValue(); 12380 12381 case Intrinsic::arm_neon_vqshiftsu: 12382 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12383 break; 12384 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 12385 12386 case Intrinsic::arm_neon_vrshiftn: 12387 case Intrinsic::arm_neon_vqshiftns: 12388 case Intrinsic::arm_neon_vqshiftnu: 12389 case Intrinsic::arm_neon_vqshiftnsu: 12390 case Intrinsic::arm_neon_vqrshiftns: 12391 case Intrinsic::arm_neon_vqrshiftnu: 12392 case Intrinsic::arm_neon_vqrshiftnsu: 12393 // Narrowing shifts require an immediate right shift. 12394 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 12395 break; 12396 llvm_unreachable("invalid shift count for narrowing vector shift " 12397 "intrinsic"); 12398 12399 default: 12400 llvm_unreachable("unhandled vector shift"); 12401 } 12402 12403 switch (IntNo) { 12404 case Intrinsic::arm_neon_vshifts: 12405 case Intrinsic::arm_neon_vshiftu: 12406 // Opcode already set above. 12407 break; 12408 case Intrinsic::arm_neon_vrshifts: 12409 VShiftOpc = ARMISD::VRSHRs; break; 12410 case Intrinsic::arm_neon_vrshiftu: 12411 VShiftOpc = ARMISD::VRSHRu; break; 12412 case Intrinsic::arm_neon_vrshiftn: 12413 VShiftOpc = ARMISD::VRSHRN; break; 12414 case Intrinsic::arm_neon_vqshifts: 12415 VShiftOpc = ARMISD::VQSHLs; break; 12416 case Intrinsic::arm_neon_vqshiftu: 12417 VShiftOpc = ARMISD::VQSHLu; break; 12418 case Intrinsic::arm_neon_vqshiftsu: 12419 VShiftOpc = ARMISD::VQSHLsu; break; 12420 case Intrinsic::arm_neon_vqshiftns: 12421 VShiftOpc = ARMISD::VQSHRNs; break; 12422 case Intrinsic::arm_neon_vqshiftnu: 12423 VShiftOpc = ARMISD::VQSHRNu; break; 12424 case Intrinsic::arm_neon_vqshiftnsu: 12425 VShiftOpc = ARMISD::VQSHRNsu; break; 12426 case Intrinsic::arm_neon_vqrshiftns: 12427 VShiftOpc = ARMISD::VQRSHRNs; break; 12428 case Intrinsic::arm_neon_vqrshiftnu: 12429 VShiftOpc = ARMISD::VQRSHRNu; break; 12430 case Intrinsic::arm_neon_vqrshiftnsu: 12431 VShiftOpc = ARMISD::VQRSHRNsu; break; 12432 } 12433 12434 SDLoc dl(N); 12435 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12436 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 12437 } 12438 12439 case Intrinsic::arm_neon_vshiftins: { 12440 EVT VT = N->getOperand(1).getValueType(); 12441 int64_t Cnt; 12442 unsigned VShiftOpc = 0; 12443 12444 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 12445 VShiftOpc = ARMISD::VSLI; 12446 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 12447 VShiftOpc = ARMISD::VSRI; 12448 else { 12449 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 12450 } 12451 12452 SDLoc dl(N); 12453 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12454 N->getOperand(1), N->getOperand(2), 12455 DAG.getConstant(Cnt, dl, MVT::i32)); 12456 } 12457 12458 case Intrinsic::arm_neon_vqrshifts: 12459 case Intrinsic::arm_neon_vqrshiftu: 12460 // No immediate versions of these to check for. 12461 break; 12462 } 12463 12464 return SDValue(); 12465 } 12466 12467 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12468 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12469 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12470 /// vector element shift counts are generally not legal, and it is hard to see 12471 /// their values after they get legalized to loads from a constant pool. 12472 static SDValue PerformShiftCombine(SDNode *N, 12473 TargetLowering::DAGCombinerInfo &DCI, 12474 const ARMSubtarget *ST) { 12475 SelectionDAG &DAG = DCI.DAG; 12476 EVT VT = N->getValueType(0); 12477 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12478 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12479 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12480 SDValue N1 = N->getOperand(1); 12481 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12482 SDValue N0 = N->getOperand(0); 12483 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12484 DAG.MaskedValueIsZero(N0.getOperand(0), 12485 APInt::getHighBitsSet(32, 16))) 12486 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12487 } 12488 } 12489 12490 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 12491 N->getOperand(0)->getOpcode() == ISD::AND && 12492 N->getOperand(0)->hasOneUse()) { 12493 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12494 return SDValue(); 12495 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 12496 // usually show up because instcombine prefers to canonicalize it to 12497 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 12498 // out of GEP lowering in some cases. 12499 SDValue N0 = N->getOperand(0); 12500 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12501 if (!ShiftAmtNode) 12502 return SDValue(); 12503 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 12504 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12505 if (!AndMaskNode) 12506 return SDValue(); 12507 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 12508 // Don't transform uxtb/uxth. 12509 if (AndMask == 255 || AndMask == 65535) 12510 return SDValue(); 12511 if (isMask_32(AndMask)) { 12512 uint32_t MaskedBits = countLeadingZeros(AndMask); 12513 if (MaskedBits > ShiftAmt) { 12514 SDLoc DL(N); 12515 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12516 DAG.getConstant(MaskedBits, DL, MVT::i32)); 12517 return DAG.getNode( 12518 ISD::SRL, DL, MVT::i32, SHL, 12519 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 12520 } 12521 } 12522 } 12523 12524 // Nothing to be done for scalar shifts. 12525 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12526 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12527 return SDValue(); 12528 12529 assert(ST->hasNEON() && "unexpected vector shift"); 12530 int64_t Cnt; 12531 12532 switch (N->getOpcode()) { 12533 default: llvm_unreachable("unexpected shift opcode"); 12534 12535 case ISD::SHL: 12536 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12537 SDLoc dl(N); 12538 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 12539 DAG.getConstant(Cnt, dl, MVT::i32)); 12540 } 12541 break; 12542 12543 case ISD::SRA: 12544 case ISD::SRL: 12545 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12546 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 12547 ARMISD::VSHRs : ARMISD::VSHRu); 12548 SDLoc dl(N); 12549 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12550 DAG.getConstant(Cnt, dl, MVT::i32)); 12551 } 12552 } 12553 return SDValue(); 12554 } 12555 12556 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12557 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12558 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12559 const ARMSubtarget *ST) { 12560 SDValue N0 = N->getOperand(0); 12561 12562 // Check for sign- and zero-extensions of vector extract operations of 8- 12563 // and 16-bit vector elements. NEON supports these directly. They are 12564 // handled during DAG combining because type legalization will promote them 12565 // to 32-bit types and it is messy to recognize the operations after that. 12566 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12567 SDValue Vec = N0.getOperand(0); 12568 SDValue Lane = N0.getOperand(1); 12569 EVT VT = N->getValueType(0); 12570 EVT EltVT = N0.getValueType(); 12571 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12572 12573 if (VT == MVT::i32 && 12574 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12575 TLI.isTypeLegal(Vec.getValueType()) && 12576 isa<ConstantSDNode>(Lane)) { 12577 12578 unsigned Opc = 0; 12579 switch (N->getOpcode()) { 12580 default: llvm_unreachable("unexpected opcode"); 12581 case ISD::SIGN_EXTEND: 12582 Opc = ARMISD::VGETLANEs; 12583 break; 12584 case ISD::ZERO_EXTEND: 12585 case ISD::ANY_EXTEND: 12586 Opc = ARMISD::VGETLANEu; 12587 break; 12588 } 12589 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12590 } 12591 } 12592 12593 return SDValue(); 12594 } 12595 12596 static const APInt *isPowerOf2Constant(SDValue V) { 12597 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12598 if (!C) 12599 return nullptr; 12600 const APInt *CV = &C->getAPIntValue(); 12601 return CV->isPowerOf2() ? CV : nullptr; 12602 } 12603 12604 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12605 // If we have a CMOV, OR and AND combination such as: 12606 // if (x & CN) 12607 // y |= CM; 12608 // 12609 // And: 12610 // * CN is a single bit; 12611 // * All bits covered by CM are known zero in y 12612 // 12613 // Then we can convert this into a sequence of BFI instructions. This will 12614 // always be a win if CM is a single bit, will always be no worse than the 12615 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12616 // three bits (due to the extra IT instruction). 12617 12618 SDValue Op0 = CMOV->getOperand(0); 12619 SDValue Op1 = CMOV->getOperand(1); 12620 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12621 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12622 SDValue CmpZ = CMOV->getOperand(4); 12623 12624 // The compare must be against zero. 12625 if (!isNullConstant(CmpZ->getOperand(1))) 12626 return SDValue(); 12627 12628 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12629 SDValue And = CmpZ->getOperand(0); 12630 if (And->getOpcode() != ISD::AND) 12631 return SDValue(); 12632 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12633 if (!AndC) 12634 return SDValue(); 12635 SDValue X = And->getOperand(0); 12636 12637 if (CC == ARMCC::EQ) { 12638 // We're performing an "equal to zero" compare. Swap the operands so we 12639 // canonicalize on a "not equal to zero" compare. 12640 std::swap(Op0, Op1); 12641 } else { 12642 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12643 } 12644 12645 if (Op1->getOpcode() != ISD::OR) 12646 return SDValue(); 12647 12648 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12649 if (!OrC) 12650 return SDValue(); 12651 SDValue Y = Op1->getOperand(0); 12652 12653 if (Op0 != Y) 12654 return SDValue(); 12655 12656 // Now, is it profitable to continue? 12657 APInt OrCI = OrC->getAPIntValue(); 12658 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12659 if (OrCI.countPopulation() > Heuristic) 12660 return SDValue(); 12661 12662 // Lastly, can we determine that the bits defined by OrCI 12663 // are zero in Y? 12664 KnownBits Known = DAG.computeKnownBits(Y); 12665 if ((OrCI & Known.Zero) != OrCI) 12666 return SDValue(); 12667 12668 // OK, we can do the combine. 12669 SDValue V = Y; 12670 SDLoc dl(X); 12671 EVT VT = X.getValueType(); 12672 unsigned BitInX = AndC->logBase2(); 12673 12674 if (BitInX != 0) { 12675 // We must shift X first. 12676 X = DAG.getNode(ISD::SRL, dl, VT, X, 12677 DAG.getConstant(BitInX, dl, VT)); 12678 } 12679 12680 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12681 BitInY < NumActiveBits; ++BitInY) { 12682 if (OrCI[BitInY] == 0) 12683 continue; 12684 APInt Mask(VT.getSizeInBits(), 0); 12685 Mask.setBit(BitInY); 12686 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12687 // Confusingly, the operand is an *inverted* mask. 12688 DAG.getConstant(~Mask, dl, VT)); 12689 } 12690 12691 return V; 12692 } 12693 12694 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12695 SDValue 12696 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12697 SDValue Cmp = N->getOperand(4); 12698 if (Cmp.getOpcode() != ARMISD::CMPZ) 12699 // Only looking at NE cases. 12700 return SDValue(); 12701 12702 EVT VT = N->getValueType(0); 12703 SDLoc dl(N); 12704 SDValue LHS = Cmp.getOperand(0); 12705 SDValue RHS = Cmp.getOperand(1); 12706 SDValue Chain = N->getOperand(0); 12707 SDValue BB = N->getOperand(1); 12708 SDValue ARMcc = N->getOperand(2); 12709 ARMCC::CondCodes CC = 12710 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12711 12712 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12713 // -> (brcond Chain BB CC CPSR Cmp) 12714 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12715 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12716 LHS->getOperand(0)->hasOneUse()) { 12717 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12718 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12719 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12720 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12721 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12722 (LHS01C && LHS01C->getZExtValue() == 1) && 12723 (LHS1C && LHS1C->getZExtValue() == 1) && 12724 (RHSC && RHSC->getZExtValue() == 0)) { 12725 return DAG.getNode( 12726 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12727 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12728 } 12729 } 12730 12731 return SDValue(); 12732 } 12733 12734 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12735 SDValue 12736 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12737 SDValue Cmp = N->getOperand(4); 12738 if (Cmp.getOpcode() != ARMISD::CMPZ) 12739 // Only looking at EQ and NE cases. 12740 return SDValue(); 12741 12742 EVT VT = N->getValueType(0); 12743 SDLoc dl(N); 12744 SDValue LHS = Cmp.getOperand(0); 12745 SDValue RHS = Cmp.getOperand(1); 12746 SDValue FalseVal = N->getOperand(0); 12747 SDValue TrueVal = N->getOperand(1); 12748 SDValue ARMcc = N->getOperand(2); 12749 ARMCC::CondCodes CC = 12750 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12751 12752 // BFI is only available on V6T2+. 12753 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12754 SDValue R = PerformCMOVToBFICombine(N, DAG); 12755 if (R) 12756 return R; 12757 } 12758 12759 // Simplify 12760 // mov r1, r0 12761 // cmp r1, x 12762 // mov r0, y 12763 // moveq r0, x 12764 // to 12765 // cmp r0, x 12766 // movne r0, y 12767 // 12768 // mov r1, r0 12769 // cmp r1, x 12770 // mov r0, x 12771 // movne r0, y 12772 // to 12773 // cmp r0, x 12774 // movne r0, y 12775 /// FIXME: Turn this into a target neutral optimization? 12776 SDValue Res; 12777 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12778 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12779 N->getOperand(3), Cmp); 12780 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12781 SDValue ARMcc; 12782 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12783 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12784 N->getOperand(3), NewCmp); 12785 } 12786 12787 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12788 // -> (cmov F T CC CPSR Cmp) 12789 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12790 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12791 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12792 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12793 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12794 (LHS1C && LHS1C->getZExtValue() == 1) && 12795 (RHSC && RHSC->getZExtValue() == 0)) { 12796 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12797 LHS->getOperand(2), LHS->getOperand(3), 12798 LHS->getOperand(4)); 12799 } 12800 } 12801 12802 if (!VT.isInteger()) 12803 return SDValue(); 12804 12805 // Materialize a boolean comparison for integers so we can avoid branching. 12806 if (isNullConstant(FalseVal)) { 12807 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 12808 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 12809 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 12810 // right 5 bits will make that 32 be 1, otherwise it will be 0. 12811 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 12812 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12813 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 12814 DAG.getConstant(5, dl, MVT::i32)); 12815 } else { 12816 // CMOV 0, 1, ==, (CMPZ x, y) -> 12817 // (ADDCARRY (SUB x, y), t:0, t:1) 12818 // where t = (SUBCARRY 0, (SUB x, y), 0) 12819 // 12820 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 12821 // x != y. In other words, a carry C == 1 when x == y, C == 0 12822 // otherwise. 12823 // The final ADDCARRY computes 12824 // x - y + (0 - (x - y)) + C == C 12825 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12826 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12827 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 12828 // ISD::SUBCARRY returns a borrow but we want the carry here 12829 // actually. 12830 SDValue Carry = 12831 DAG.getNode(ISD::SUB, dl, MVT::i32, 12832 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 12833 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 12834 } 12835 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 12836 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 12837 // This seems pointless but will allow us to combine it further below. 12838 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 12839 SDValue Sub = 12840 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 12841 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 12842 Sub.getValue(1), SDValue()); 12843 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 12844 N->getOperand(3), CPSRGlue.getValue(1)); 12845 FalseVal = Sub; 12846 } 12847 } else if (isNullConstant(TrueVal)) { 12848 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 12849 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 12850 // This seems pointless but will allow us to combine it further below 12851 // Note that we change == for != as this is the dual for the case above. 12852 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 12853 SDValue Sub = 12854 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 12855 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 12856 Sub.getValue(1), SDValue()); 12857 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 12858 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 12859 N->getOperand(3), CPSRGlue.getValue(1)); 12860 FalseVal = Sub; 12861 } 12862 } 12863 12864 // On Thumb1, the DAG above may be further combined if z is a power of 2 12865 // (z == 2 ^ K). 12866 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 12867 // t1 = (USUBO (SUB x, y), 1) 12868 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 12869 // Result = if K != 0 then (SHL t2:0, K) else t2:0 12870 // 12871 // This also handles the special case of comparing against zero; it's 12872 // essentially, the same pattern, except there's no SUBS: 12873 // CMOV x, z, !=, (CMPZ x, 0) -> 12874 // t1 = (USUBO x, 1) 12875 // t2 = (SUBCARRY x, t1:0, t1:1) 12876 // Result = if K != 0 then (SHL t2:0, K) else t2:0 12877 const APInt *TrueConst; 12878 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 12879 ((FalseVal.getOpcode() == ARMISD::SUBS && 12880 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 12881 (FalseVal == LHS && isNullConstant(RHS))) && 12882 (TrueConst = isPowerOf2Constant(TrueVal))) { 12883 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12884 unsigned ShiftAmount = TrueConst->logBase2(); 12885 if (ShiftAmount) 12886 TrueVal = DAG.getConstant(1, dl, VT); 12887 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 12888 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 12889 12890 if (ShiftAmount) 12891 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 12892 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 12893 } 12894 12895 if (Res.getNode()) { 12896 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 12897 // Capture demanded bits information that would be otherwise lost. 12898 if (Known.Zero == 0xfffffffe) 12899 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12900 DAG.getValueType(MVT::i1)); 12901 else if (Known.Zero == 0xffffff00) 12902 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12903 DAG.getValueType(MVT::i8)); 12904 else if (Known.Zero == 0xffff0000) 12905 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12906 DAG.getValueType(MVT::i16)); 12907 } 12908 12909 return Res; 12910 } 12911 12912 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12913 DAGCombinerInfo &DCI) const { 12914 switch (N->getOpcode()) { 12915 default: break; 12916 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 12917 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12918 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12919 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12920 case ISD::SUB: return PerformSUBCombine(N, DCI); 12921 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12922 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12923 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12924 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12925 case ARMISD::ADDC: 12926 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12927 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 12928 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12929 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12930 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12931 case ISD::STORE: return PerformSTORECombine(N, DCI); 12932 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12933 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12934 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12935 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12936 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12937 case ISD::FP_TO_SINT: 12938 case ISD::FP_TO_UINT: 12939 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12940 case ISD::FDIV: 12941 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12942 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12943 case ISD::SHL: 12944 case ISD::SRA: 12945 case ISD::SRL: 12946 return PerformShiftCombine(N, DCI, Subtarget); 12947 case ISD::SIGN_EXTEND: 12948 case ISD::ZERO_EXTEND: 12949 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12950 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12951 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12952 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12953 case ARMISD::VLD1DUP: 12954 case ARMISD::VLD2DUP: 12955 case ARMISD::VLD3DUP: 12956 case ARMISD::VLD4DUP: 12957 return PerformVLDCombine(N, DCI); 12958 case ARMISD::BUILD_VECTOR: 12959 return PerformARMBUILD_VECTORCombine(N, DCI); 12960 case ARMISD::SMULWB: { 12961 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12962 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12963 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12964 return SDValue(); 12965 break; 12966 } 12967 case ARMISD::SMULWT: { 12968 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12969 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12970 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12971 return SDValue(); 12972 break; 12973 } 12974 case ARMISD::SMLALBB: { 12975 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12976 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12977 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12978 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12979 return SDValue(); 12980 break; 12981 } 12982 case ARMISD::SMLALBT: { 12983 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12984 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12985 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12986 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12987 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12988 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12989 return SDValue(); 12990 break; 12991 } 12992 case ARMISD::SMLALTB: { 12993 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12994 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12995 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12996 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12997 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12998 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12999 return SDValue(); 13000 break; 13001 } 13002 case ARMISD::SMLALTT: { 13003 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13004 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 13005 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 13006 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 13007 return SDValue(); 13008 break; 13009 } 13010 case ISD::INTRINSIC_VOID: 13011 case ISD::INTRINSIC_W_CHAIN: 13012 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13013 case Intrinsic::arm_neon_vld1: 13014 case Intrinsic::arm_neon_vld1x2: 13015 case Intrinsic::arm_neon_vld1x3: 13016 case Intrinsic::arm_neon_vld1x4: 13017 case Intrinsic::arm_neon_vld2: 13018 case Intrinsic::arm_neon_vld3: 13019 case Intrinsic::arm_neon_vld4: 13020 case Intrinsic::arm_neon_vld2lane: 13021 case Intrinsic::arm_neon_vld3lane: 13022 case Intrinsic::arm_neon_vld4lane: 13023 case Intrinsic::arm_neon_vld2dup: 13024 case Intrinsic::arm_neon_vld3dup: 13025 case Intrinsic::arm_neon_vld4dup: 13026 case Intrinsic::arm_neon_vst1: 13027 case Intrinsic::arm_neon_vst1x2: 13028 case Intrinsic::arm_neon_vst1x3: 13029 case Intrinsic::arm_neon_vst1x4: 13030 case Intrinsic::arm_neon_vst2: 13031 case Intrinsic::arm_neon_vst3: 13032 case Intrinsic::arm_neon_vst4: 13033 case Intrinsic::arm_neon_vst2lane: 13034 case Intrinsic::arm_neon_vst3lane: 13035 case Intrinsic::arm_neon_vst4lane: 13036 return PerformVLDCombine(N, DCI); 13037 default: break; 13038 } 13039 break; 13040 } 13041 return SDValue(); 13042 } 13043 13044 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 13045 EVT VT) const { 13046 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 13047 } 13048 13049 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 13050 unsigned, 13051 unsigned, 13052 bool *Fast) const { 13053 // Depends what it gets converted into if the type is weird. 13054 if (!VT.isSimple()) 13055 return false; 13056 13057 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 13058 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 13059 13060 switch (VT.getSimpleVT().SimpleTy) { 13061 default: 13062 return false; 13063 case MVT::i8: 13064 case MVT::i16: 13065 case MVT::i32: { 13066 // Unaligned access can use (for example) LRDB, LRDH, LDR 13067 if (AllowsUnaligned) { 13068 if (Fast) 13069 *Fast = Subtarget->hasV7Ops(); 13070 return true; 13071 } 13072 return false; 13073 } 13074 case MVT::f64: 13075 case MVT::v2f64: { 13076 // For any little-endian targets with neon, we can support unaligned ld/st 13077 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 13078 // A big-endian target may also explicitly support unaligned accesses 13079 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 13080 if (Fast) 13081 *Fast = true; 13082 return true; 13083 } 13084 return false; 13085 } 13086 } 13087 } 13088 13089 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 13090 unsigned AlignCheck) { 13091 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 13092 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 13093 } 13094 13095 EVT ARMTargetLowering::getOptimalMemOpType( 13096 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 13097 bool ZeroMemset, bool MemcpyStrSrc, 13098 const AttributeList &FuncAttributes) const { 13099 // See if we can use NEON instructions for this... 13100 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 13101 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 13102 bool Fast; 13103 if (Size >= 16 && 13104 (memOpAlign(SrcAlign, DstAlign, 16) || 13105 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 13106 return MVT::v2f64; 13107 } else if (Size >= 8 && 13108 (memOpAlign(SrcAlign, DstAlign, 8) || 13109 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 13110 Fast))) { 13111 return MVT::f64; 13112 } 13113 } 13114 13115 // Let the target-independent logic figure it out. 13116 return MVT::Other; 13117 } 13118 13119 // 64-bit integers are split into their high and low parts and held in two 13120 // different registers, so the trunc is free since the low register can just 13121 // be used. 13122 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 13123 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 13124 return false; 13125 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 13126 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 13127 return (SrcBits == 64 && DestBits == 32); 13128 } 13129 13130 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 13131 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 13132 !DstVT.isInteger()) 13133 return false; 13134 unsigned SrcBits = SrcVT.getSizeInBits(); 13135 unsigned DestBits = DstVT.getSizeInBits(); 13136 return (SrcBits == 64 && DestBits == 32); 13137 } 13138 13139 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13140 if (Val.getOpcode() != ISD::LOAD) 13141 return false; 13142 13143 EVT VT1 = Val.getValueType(); 13144 if (!VT1.isSimple() || !VT1.isInteger() || 13145 !VT2.isSimple() || !VT2.isInteger()) 13146 return false; 13147 13148 switch (VT1.getSimpleVT().SimpleTy) { 13149 default: break; 13150 case MVT::i1: 13151 case MVT::i8: 13152 case MVT::i16: 13153 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 13154 return true; 13155 } 13156 13157 return false; 13158 } 13159 13160 bool ARMTargetLowering::isFNegFree(EVT VT) const { 13161 if (!VT.isSimple()) 13162 return false; 13163 13164 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 13165 // negate values directly (fneg is free). So, we don't want to let the DAG 13166 // combiner rewrite fneg into xors and some other instructions. For f16 and 13167 // FullFP16 argument passing, some bitcast nodes may be introduced, 13168 // triggering this DAG combine rewrite, so we are avoiding that with this. 13169 switch (VT.getSimpleVT().SimpleTy) { 13170 default: break; 13171 case MVT::f16: 13172 return Subtarget->hasFullFP16(); 13173 } 13174 13175 return false; 13176 } 13177 13178 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 13179 /// of the vector elements. 13180 static bool areExtractExts(Value *Ext1, Value *Ext2) { 13181 auto areExtDoubled = [](Instruction *Ext) { 13182 return Ext->getType()->getScalarSizeInBits() == 13183 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 13184 }; 13185 13186 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 13187 !match(Ext2, m_ZExtOrSExt(m_Value())) || 13188 !areExtDoubled(cast<Instruction>(Ext1)) || 13189 !areExtDoubled(cast<Instruction>(Ext2))) 13190 return false; 13191 13192 return true; 13193 } 13194 13195 /// Check if sinking \p I's operands to I's basic block is profitable, because 13196 /// the operands can be folded into a target instruction, e.g. 13197 /// sext/zext can be folded into vsubl. 13198 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 13199 SmallVectorImpl<Use *> &Ops) const { 13200 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy()) 13201 return false; 13202 13203 switch (I->getOpcode()) { 13204 case Instruction::Sub: 13205 case Instruction::Add: { 13206 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 13207 return false; 13208 Ops.push_back(&I->getOperandUse(0)); 13209 Ops.push_back(&I->getOperandUse(1)); 13210 return true; 13211 } 13212 default: 13213 return false; 13214 } 13215 return false; 13216 } 13217 13218 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 13219 EVT VT = ExtVal.getValueType(); 13220 13221 if (!isTypeLegal(VT)) 13222 return false; 13223 13224 // Don't create a loadext if we can fold the extension into a wide/long 13225 // instruction. 13226 // If there's more than one user instruction, the loadext is desirable no 13227 // matter what. There can be two uses by the same instruction. 13228 if (ExtVal->use_empty() || 13229 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 13230 return true; 13231 13232 SDNode *U = *ExtVal->use_begin(); 13233 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 13234 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 13235 return false; 13236 13237 return true; 13238 } 13239 13240 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 13241 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13242 return false; 13243 13244 if (!isTypeLegal(EVT::getEVT(Ty1))) 13245 return false; 13246 13247 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 13248 13249 // Assuming the caller doesn't have a zeroext or signext return parameter, 13250 // truncation all the way down to i1 is valid. 13251 return true; 13252 } 13253 13254 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 13255 const AddrMode &AM, Type *Ty, 13256 unsigned AS) const { 13257 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 13258 if (Subtarget->hasFPAO()) 13259 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 13260 return 0; 13261 } 13262 return -1; 13263 } 13264 13265 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 13266 if (V < 0) 13267 return false; 13268 13269 unsigned Scale = 1; 13270 switch (VT.getSimpleVT().SimpleTy) { 13271 default: return false; 13272 case MVT::i1: 13273 case MVT::i8: 13274 // Scale == 1; 13275 break; 13276 case MVT::i16: 13277 // Scale == 2; 13278 Scale = 2; 13279 break; 13280 case MVT::i32: 13281 // Scale == 4; 13282 Scale = 4; 13283 break; 13284 } 13285 13286 if ((V & (Scale - 1)) != 0) 13287 return false; 13288 return isUInt<5>(V / Scale); 13289 } 13290 13291 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 13292 const ARMSubtarget *Subtarget) { 13293 if (!VT.isInteger() && !VT.isFloatingPoint()) 13294 return false; 13295 if (Subtarget->hasNEON() && VT.isVector()) 13296 return false; 13297 13298 bool IsNeg = false; 13299 if (V < 0) { 13300 IsNeg = true; 13301 V = -V; 13302 } 13303 13304 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U); 13305 13306 // VLDR and LDRD: 4 * imm8 13307 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 13308 return isShiftedUInt<8, 2>(V); 13309 13310 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 13311 // + imm12 or - imm8 13312 if (IsNeg) 13313 return isUInt<8>(V); 13314 return isUInt<12>(V); 13315 } 13316 13317 return false; 13318 } 13319 13320 /// isLegalAddressImmediate - Return true if the integer value can be used 13321 /// as the offset of the target addressing mode for load / store of the 13322 /// given type. 13323 static bool isLegalAddressImmediate(int64_t V, EVT VT, 13324 const ARMSubtarget *Subtarget) { 13325 if (V == 0) 13326 return true; 13327 13328 if (!VT.isSimple()) 13329 return false; 13330 13331 if (Subtarget->isThumb1Only()) 13332 return isLegalT1AddressImmediate(V, VT); 13333 else if (Subtarget->isThumb2()) 13334 return isLegalT2AddressImmediate(V, VT, Subtarget); 13335 13336 // ARM mode. 13337 if (V < 0) 13338 V = - V; 13339 switch (VT.getSimpleVT().SimpleTy) { 13340 default: return false; 13341 case MVT::i1: 13342 case MVT::i8: 13343 case MVT::i32: 13344 // +- imm12 13345 return isUInt<12>(V); 13346 case MVT::i16: 13347 // +- imm8 13348 return isUInt<8>(V); 13349 case MVT::f32: 13350 case MVT::f64: 13351 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 13352 return false; 13353 return isShiftedUInt<8, 2>(V); 13354 } 13355 } 13356 13357 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 13358 EVT VT) const { 13359 int Scale = AM.Scale; 13360 if (Scale < 0) 13361 return false; 13362 13363 switch (VT.getSimpleVT().SimpleTy) { 13364 default: return false; 13365 case MVT::i1: 13366 case MVT::i8: 13367 case MVT::i16: 13368 case MVT::i32: 13369 if (Scale == 1) 13370 return true; 13371 // r + r << imm 13372 Scale = Scale & ~1; 13373 return Scale == 2 || Scale == 4 || Scale == 8; 13374 case MVT::i64: 13375 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 13376 // version in Thumb mode. 13377 // r + r 13378 if (Scale == 1) 13379 return true; 13380 // r * 2 (this can be lowered to r + r). 13381 if (!AM.HasBaseReg && Scale == 2) 13382 return true; 13383 return false; 13384 case MVT::isVoid: 13385 // Note, we allow "void" uses (basically, uses that aren't loads or 13386 // stores), because arm allows folding a scale into many arithmetic 13387 // operations. This should be made more precise and revisited later. 13388 13389 // Allow r << imm, but the imm has to be a multiple of two. 13390 if (Scale & 1) return false; 13391 return isPowerOf2_32(Scale); 13392 } 13393 } 13394 13395 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 13396 EVT VT) const { 13397 const int Scale = AM.Scale; 13398 13399 // Negative scales are not supported in Thumb1. 13400 if (Scale < 0) 13401 return false; 13402 13403 // Thumb1 addressing modes do not support register scaling excepting the 13404 // following cases: 13405 // 1. Scale == 1 means no scaling. 13406 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 13407 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 13408 } 13409 13410 /// isLegalAddressingMode - Return true if the addressing mode represented 13411 /// by AM is legal for this target, for a load/store of the specified type. 13412 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13413 const AddrMode &AM, Type *Ty, 13414 unsigned AS, Instruction *I) const { 13415 EVT VT = getValueType(DL, Ty, true); 13416 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 13417 return false; 13418 13419 // Can never fold addr of global into load/store. 13420 if (AM.BaseGV) 13421 return false; 13422 13423 switch (AM.Scale) { 13424 case 0: // no scale reg, must be "r+i" or "r", or "i". 13425 break; 13426 default: 13427 // ARM doesn't support any R+R*scale+imm addr modes. 13428 if (AM.BaseOffs) 13429 return false; 13430 13431 if (!VT.isSimple()) 13432 return false; 13433 13434 if (Subtarget->isThumb1Only()) 13435 return isLegalT1ScaledAddressingMode(AM, VT); 13436 13437 if (Subtarget->isThumb2()) 13438 return isLegalT2ScaledAddressingMode(AM, VT); 13439 13440 int Scale = AM.Scale; 13441 switch (VT.getSimpleVT().SimpleTy) { 13442 default: return false; 13443 case MVT::i1: 13444 case MVT::i8: 13445 case MVT::i32: 13446 if (Scale < 0) Scale = -Scale; 13447 if (Scale == 1) 13448 return true; 13449 // r + r << imm 13450 return isPowerOf2_32(Scale & ~1); 13451 case MVT::i16: 13452 case MVT::i64: 13453 // r +/- r 13454 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 13455 return true; 13456 // r * 2 (this can be lowered to r + r). 13457 if (!AM.HasBaseReg && Scale == 2) 13458 return true; 13459 return false; 13460 13461 case MVT::isVoid: 13462 // Note, we allow "void" uses (basically, uses that aren't loads or 13463 // stores), because arm allows folding a scale into many arithmetic 13464 // operations. This should be made more precise and revisited later. 13465 13466 // Allow r << imm, but the imm has to be a multiple of two. 13467 if (Scale & 1) return false; 13468 return isPowerOf2_32(Scale); 13469 } 13470 } 13471 return true; 13472 } 13473 13474 /// isLegalICmpImmediate - Return true if the specified immediate is legal 13475 /// icmp immediate, that is the target has icmp instructions which can compare 13476 /// a register against the immediate without having to materialize the 13477 /// immediate into a register. 13478 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13479 // Thumb2 and ARM modes can use cmn for negative immediates. 13480 if (!Subtarget->isThumb()) 13481 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 13482 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 13483 if (Subtarget->isThumb2()) 13484 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 13485 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 13486 // Thumb1 doesn't have cmn, and only 8-bit immediates. 13487 return Imm >= 0 && Imm <= 255; 13488 } 13489 13490 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 13491 /// *or sub* immediate, that is the target has add or sub instructions which can 13492 /// add a register with the immediate without having to materialize the 13493 /// immediate into a register. 13494 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13495 // Same encoding for add/sub, just flip the sign. 13496 int64_t AbsImm = std::abs(Imm); 13497 if (!Subtarget->isThumb()) 13498 return ARM_AM::getSOImmVal(AbsImm) != -1; 13499 if (Subtarget->isThumb2()) 13500 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 13501 // Thumb1 only has 8-bit unsigned immediate. 13502 return AbsImm >= 0 && AbsImm <= 255; 13503 } 13504 13505 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 13506 bool isSEXTLoad, SDValue &Base, 13507 SDValue &Offset, bool &isInc, 13508 SelectionDAG &DAG) { 13509 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13510 return false; 13511 13512 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 13513 // AddressingMode 3 13514 Base = Ptr->getOperand(0); 13515 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13516 int RHSC = (int)RHS->getZExtValue(); 13517 if (RHSC < 0 && RHSC > -256) { 13518 assert(Ptr->getOpcode() == ISD::ADD); 13519 isInc = false; 13520 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13521 return true; 13522 } 13523 } 13524 isInc = (Ptr->getOpcode() == ISD::ADD); 13525 Offset = Ptr->getOperand(1); 13526 return true; 13527 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 13528 // AddressingMode 2 13529 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13530 int RHSC = (int)RHS->getZExtValue(); 13531 if (RHSC < 0 && RHSC > -0x1000) { 13532 assert(Ptr->getOpcode() == ISD::ADD); 13533 isInc = false; 13534 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13535 Base = Ptr->getOperand(0); 13536 return true; 13537 } 13538 } 13539 13540 if (Ptr->getOpcode() == ISD::ADD) { 13541 isInc = true; 13542 ARM_AM::ShiftOpc ShOpcVal= 13543 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 13544 if (ShOpcVal != ARM_AM::no_shift) { 13545 Base = Ptr->getOperand(1); 13546 Offset = Ptr->getOperand(0); 13547 } else { 13548 Base = Ptr->getOperand(0); 13549 Offset = Ptr->getOperand(1); 13550 } 13551 return true; 13552 } 13553 13554 isInc = (Ptr->getOpcode() == ISD::ADD); 13555 Base = Ptr->getOperand(0); 13556 Offset = Ptr->getOperand(1); 13557 return true; 13558 } 13559 13560 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 13561 return false; 13562 } 13563 13564 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 13565 bool isSEXTLoad, SDValue &Base, 13566 SDValue &Offset, bool &isInc, 13567 SelectionDAG &DAG) { 13568 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13569 return false; 13570 13571 Base = Ptr->getOperand(0); 13572 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13573 int RHSC = (int)RHS->getZExtValue(); 13574 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 13575 assert(Ptr->getOpcode() == ISD::ADD); 13576 isInc = false; 13577 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13578 return true; 13579 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 13580 isInc = Ptr->getOpcode() == ISD::ADD; 13581 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13582 return true; 13583 } 13584 } 13585 13586 return false; 13587 } 13588 13589 /// getPreIndexedAddressParts - returns true by value, base pointer and 13590 /// offset pointer and addressing mode by reference if the node's address 13591 /// can be legally represented as pre-indexed load / store address. 13592 bool 13593 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13594 SDValue &Offset, 13595 ISD::MemIndexedMode &AM, 13596 SelectionDAG &DAG) const { 13597 if (Subtarget->isThumb1Only()) 13598 return false; 13599 13600 EVT VT; 13601 SDValue Ptr; 13602 bool isSEXTLoad = false; 13603 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13604 Ptr = LD->getBasePtr(); 13605 VT = LD->getMemoryVT(); 13606 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13607 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13608 Ptr = ST->getBasePtr(); 13609 VT = ST->getMemoryVT(); 13610 } else 13611 return false; 13612 13613 bool isInc; 13614 bool isLegal = false; 13615 if (Subtarget->isThumb2()) 13616 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13617 Offset, isInc, DAG); 13618 else 13619 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13620 Offset, isInc, DAG); 13621 if (!isLegal) 13622 return false; 13623 13624 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 13625 return true; 13626 } 13627 13628 /// getPostIndexedAddressParts - returns true by value, base pointer and 13629 /// offset pointer and addressing mode by reference if this node can be 13630 /// combined with a load / store to form a post-indexed load / store. 13631 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 13632 SDValue &Base, 13633 SDValue &Offset, 13634 ISD::MemIndexedMode &AM, 13635 SelectionDAG &DAG) const { 13636 EVT VT; 13637 SDValue Ptr; 13638 bool isSEXTLoad = false, isNonExt; 13639 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13640 VT = LD->getMemoryVT(); 13641 Ptr = LD->getBasePtr(); 13642 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13643 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 13644 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13645 VT = ST->getMemoryVT(); 13646 Ptr = ST->getBasePtr(); 13647 isNonExt = !ST->isTruncatingStore(); 13648 } else 13649 return false; 13650 13651 if (Subtarget->isThumb1Only()) { 13652 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 13653 // must be non-extending/truncating, i32, with an offset of 4. 13654 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 13655 if (Op->getOpcode() != ISD::ADD || !isNonExt) 13656 return false; 13657 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 13658 if (!RHS || RHS->getZExtValue() != 4) 13659 return false; 13660 13661 Offset = Op->getOperand(1); 13662 Base = Op->getOperand(0); 13663 AM = ISD::POST_INC; 13664 return true; 13665 } 13666 13667 bool isInc; 13668 bool isLegal = false; 13669 if (Subtarget->isThumb2()) 13670 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13671 isInc, DAG); 13672 else 13673 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13674 isInc, DAG); 13675 if (!isLegal) 13676 return false; 13677 13678 if (Ptr != Base) { 13679 // Swap base ptr and offset to catch more post-index load / store when 13680 // it's legal. In Thumb2 mode, offset must be an immediate. 13681 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 13682 !Subtarget->isThumb2()) 13683 std::swap(Base, Offset); 13684 13685 // Post-indexed load / store update the base pointer. 13686 if (Ptr != Base) 13687 return false; 13688 } 13689 13690 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 13691 return true; 13692 } 13693 13694 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13695 KnownBits &Known, 13696 const APInt &DemandedElts, 13697 const SelectionDAG &DAG, 13698 unsigned Depth) const { 13699 unsigned BitWidth = Known.getBitWidth(); 13700 Known.resetAll(); 13701 switch (Op.getOpcode()) { 13702 default: break; 13703 case ARMISD::ADDC: 13704 case ARMISD::ADDE: 13705 case ARMISD::SUBC: 13706 case ARMISD::SUBE: 13707 // Special cases when we convert a carry to a boolean. 13708 if (Op.getResNo() == 0) { 13709 SDValue LHS = Op.getOperand(0); 13710 SDValue RHS = Op.getOperand(1); 13711 // (ADDE 0, 0, C) will give us a single bit. 13712 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 13713 isNullConstant(RHS)) { 13714 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 13715 return; 13716 } 13717 } 13718 break; 13719 case ARMISD::CMOV: { 13720 // Bits are known zero/one if known on the LHS and RHS. 13721 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 13722 if (Known.isUnknown()) 13723 return; 13724 13725 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 13726 Known.Zero &= KnownRHS.Zero; 13727 Known.One &= KnownRHS.One; 13728 return; 13729 } 13730 case ISD::INTRINSIC_W_CHAIN: { 13731 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 13732 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13733 switch (IntID) { 13734 default: return; 13735 case Intrinsic::arm_ldaex: 13736 case Intrinsic::arm_ldrex: { 13737 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 13738 unsigned MemBits = VT.getScalarSizeInBits(); 13739 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 13740 return; 13741 } 13742 } 13743 } 13744 case ARMISD::BFI: { 13745 // Conservatively, we can recurse down the first operand 13746 // and just mask out all affected bits. 13747 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 13748 13749 // The operand to BFI is already a mask suitable for removing the bits it 13750 // sets. 13751 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 13752 const APInt &Mask = CI->getAPIntValue(); 13753 Known.Zero &= Mask; 13754 Known.One &= Mask; 13755 return; 13756 } 13757 case ARMISD::VGETLANEs: 13758 case ARMISD::VGETLANEu: { 13759 const SDValue &SrcSV = Op.getOperand(0); 13760 EVT VecVT = SrcSV.getValueType(); 13761 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 13762 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 13763 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 13764 assert(Pos->getAPIntValue().ult(NumSrcElts) && 13765 "VGETLANE index out of bounds"); 13766 unsigned Idx = Pos->getZExtValue(); 13767 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 13768 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 13769 13770 EVT VT = Op.getValueType(); 13771 const unsigned DstSz = VT.getScalarSizeInBits(); 13772 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 13773 (void)SrcSz; 13774 assert(SrcSz == Known.getBitWidth()); 13775 assert(DstSz > SrcSz); 13776 if (Op.getOpcode() == ARMISD::VGETLANEs) 13777 Known = Known.sext(DstSz); 13778 else { 13779 Known = Known.zext(DstSz, true /* extended bits are known zero */); 13780 } 13781 assert(DstSz == Known.getBitWidth()); 13782 break; 13783 } 13784 } 13785 } 13786 13787 bool 13788 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 13789 const APInt &DemandedAPInt, 13790 TargetLoweringOpt &TLO) const { 13791 // Delay optimization, so we don't have to deal with illegal types, or block 13792 // optimizations. 13793 if (!TLO.LegalOps) 13794 return false; 13795 13796 // Only optimize AND for now. 13797 if (Op.getOpcode() != ISD::AND) 13798 return false; 13799 13800 EVT VT = Op.getValueType(); 13801 13802 // Ignore vectors. 13803 if (VT.isVector()) 13804 return false; 13805 13806 assert(VT == MVT::i32 && "Unexpected integer type"); 13807 13808 // Make sure the RHS really is a constant. 13809 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13810 if (!C) 13811 return false; 13812 13813 unsigned Mask = C->getZExtValue(); 13814 13815 unsigned Demanded = DemandedAPInt.getZExtValue(); 13816 unsigned ShrunkMask = Mask & Demanded; 13817 unsigned ExpandedMask = Mask | ~Demanded; 13818 13819 // If the mask is all zeros, let the target-independent code replace the 13820 // result with zero. 13821 if (ShrunkMask == 0) 13822 return false; 13823 13824 // If the mask is all ones, erase the AND. (Currently, the target-independent 13825 // code won't do this, so we have to do it explicitly to avoid an infinite 13826 // loop in obscure cases.) 13827 if (ExpandedMask == ~0U) 13828 return TLO.CombineTo(Op, Op.getOperand(0)); 13829 13830 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 13831 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 13832 }; 13833 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 13834 if (NewMask == Mask) 13835 return true; 13836 SDLoc DL(Op); 13837 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 13838 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 13839 return TLO.CombineTo(Op, NewOp); 13840 }; 13841 13842 // Prefer uxtb mask. 13843 if (IsLegalMask(0xFF)) 13844 return UseMask(0xFF); 13845 13846 // Prefer uxth mask. 13847 if (IsLegalMask(0xFFFF)) 13848 return UseMask(0xFFFF); 13849 13850 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 13851 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 13852 if (ShrunkMask < 256) 13853 return UseMask(ShrunkMask); 13854 13855 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 13856 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 13857 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 13858 return UseMask(ExpandedMask); 13859 13860 // Potential improvements: 13861 // 13862 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 13863 // We could try to prefer Thumb1 immediates which can be lowered to a 13864 // two-instruction sequence. 13865 // We could try to recognize more legal ARM/Thumb2 immediates here. 13866 13867 return false; 13868 } 13869 13870 13871 //===----------------------------------------------------------------------===// 13872 // ARM Inline Assembly Support 13873 //===----------------------------------------------------------------------===// 13874 13875 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 13876 // Looking for "rev" which is V6+. 13877 if (!Subtarget->hasV6Ops()) 13878 return false; 13879 13880 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 13881 std::string AsmStr = IA->getAsmString(); 13882 SmallVector<StringRef, 4> AsmPieces; 13883 SplitString(AsmStr, AsmPieces, ";\n"); 13884 13885 switch (AsmPieces.size()) { 13886 default: return false; 13887 case 1: 13888 AsmStr = AsmPieces[0]; 13889 AsmPieces.clear(); 13890 SplitString(AsmStr, AsmPieces, " \t,"); 13891 13892 // rev $0, $1 13893 if (AsmPieces.size() == 3 && 13894 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 13895 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 13896 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 13897 if (Ty && Ty->getBitWidth() == 32) 13898 return IntrinsicLowering::LowerToByteSwap(CI); 13899 } 13900 break; 13901 } 13902 13903 return false; 13904 } 13905 13906 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 13907 // At this point, we have to lower this constraint to something else, so we 13908 // lower it to an "r" or "w". However, by doing this we will force the result 13909 // to be in register, while the X constraint is much more permissive. 13910 // 13911 // Although we are correct (we are free to emit anything, without 13912 // constraints), we might break use cases that would expect us to be more 13913 // efficient and emit something else. 13914 if (!Subtarget->hasVFP2Base()) 13915 return "r"; 13916 if (ConstraintVT.isFloatingPoint()) 13917 return "w"; 13918 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 13919 (ConstraintVT.getSizeInBits() == 64 || 13920 ConstraintVT.getSizeInBits() == 128)) 13921 return "w"; 13922 13923 return "r"; 13924 } 13925 13926 /// getConstraintType - Given a constraint letter, return the type of 13927 /// constraint it is for this target. 13928 ARMTargetLowering::ConstraintType 13929 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 13930 if (Constraint.size() == 1) { 13931 switch (Constraint[0]) { 13932 default: break; 13933 case 'l': return C_RegisterClass; 13934 case 'w': return C_RegisterClass; 13935 case 'h': return C_RegisterClass; 13936 case 'x': return C_RegisterClass; 13937 case 't': return C_RegisterClass; 13938 case 'j': return C_Other; // Constant for movw. 13939 // An address with a single base register. Due to the way we 13940 // currently handle addresses it is the same as an 'r' memory constraint. 13941 case 'Q': return C_Memory; 13942 } 13943 } else if (Constraint.size() == 2) { 13944 switch (Constraint[0]) { 13945 default: break; 13946 // All 'U+' constraints are addresses. 13947 case 'U': return C_Memory; 13948 } 13949 } 13950 return TargetLowering::getConstraintType(Constraint); 13951 } 13952 13953 /// Examine constraint type and operand type and determine a weight value. 13954 /// This object must already have been set up with the operand type 13955 /// and the current alternative constraint selected. 13956 TargetLowering::ConstraintWeight 13957 ARMTargetLowering::getSingleConstraintMatchWeight( 13958 AsmOperandInfo &info, const char *constraint) const { 13959 ConstraintWeight weight = CW_Invalid; 13960 Value *CallOperandVal = info.CallOperandVal; 13961 // If we don't have a value, we can't do a match, 13962 // but allow it at the lowest weight. 13963 if (!CallOperandVal) 13964 return CW_Default; 13965 Type *type = CallOperandVal->getType(); 13966 // Look at the constraint type. 13967 switch (*constraint) { 13968 default: 13969 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13970 break; 13971 case 'l': 13972 if (type->isIntegerTy()) { 13973 if (Subtarget->isThumb()) 13974 weight = CW_SpecificReg; 13975 else 13976 weight = CW_Register; 13977 } 13978 break; 13979 case 'w': 13980 if (type->isFloatingPointTy()) 13981 weight = CW_Register; 13982 break; 13983 } 13984 return weight; 13985 } 13986 13987 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13988 13989 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13990 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13991 if (Constraint.size() == 1) { 13992 // GCC ARM Constraint Letters 13993 switch (Constraint[0]) { 13994 case 'l': // Low regs or general regs. 13995 if (Subtarget->isThumb()) 13996 return RCPair(0U, &ARM::tGPRRegClass); 13997 return RCPair(0U, &ARM::GPRRegClass); 13998 case 'h': // High regs or no regs. 13999 if (Subtarget->isThumb()) 14000 return RCPair(0U, &ARM::hGPRRegClass); 14001 break; 14002 case 'r': 14003 if (Subtarget->isThumb1Only()) 14004 return RCPair(0U, &ARM::tGPRRegClass); 14005 return RCPair(0U, &ARM::GPRRegClass); 14006 case 'w': 14007 if (VT == MVT::Other) 14008 break; 14009 if (VT == MVT::f32) 14010 return RCPair(0U, &ARM::SPRRegClass); 14011 if (VT.getSizeInBits() == 64) 14012 return RCPair(0U, &ARM::DPRRegClass); 14013 if (VT.getSizeInBits() == 128) 14014 return RCPair(0U, &ARM::QPRRegClass); 14015 break; 14016 case 'x': 14017 if (VT == MVT::Other) 14018 break; 14019 if (VT == MVT::f32) 14020 return RCPair(0U, &ARM::SPR_8RegClass); 14021 if (VT.getSizeInBits() == 64) 14022 return RCPair(0U, &ARM::DPR_8RegClass); 14023 if (VT.getSizeInBits() == 128) 14024 return RCPair(0U, &ARM::QPR_8RegClass); 14025 break; 14026 case 't': 14027 if (VT == MVT::Other) 14028 break; 14029 if (VT == MVT::f32 || VT == MVT::i32) 14030 return RCPair(0U, &ARM::SPRRegClass); 14031 if (VT.getSizeInBits() == 64) 14032 return RCPair(0U, &ARM::DPR_VFP2RegClass); 14033 if (VT.getSizeInBits() == 128) 14034 return RCPair(0U, &ARM::QPR_VFP2RegClass); 14035 break; 14036 } 14037 } 14038 if (StringRef("{cc}").equals_lower(Constraint)) 14039 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 14040 14041 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14042 } 14043 14044 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14045 /// vector. If it is invalid, don't add anything to Ops. 14046 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14047 std::string &Constraint, 14048 std::vector<SDValue>&Ops, 14049 SelectionDAG &DAG) const { 14050 SDValue Result; 14051 14052 // Currently only support length 1 constraints. 14053 if (Constraint.length() != 1) return; 14054 14055 char ConstraintLetter = Constraint[0]; 14056 switch (ConstraintLetter) { 14057 default: break; 14058 case 'j': 14059 case 'I': case 'J': case 'K': case 'L': 14060 case 'M': case 'N': case 'O': 14061 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 14062 if (!C) 14063 return; 14064 14065 int64_t CVal64 = C->getSExtValue(); 14066 int CVal = (int) CVal64; 14067 // None of these constraints allow values larger than 32 bits. Check 14068 // that the value fits in an int. 14069 if (CVal != CVal64) 14070 return; 14071 14072 switch (ConstraintLetter) { 14073 case 'j': 14074 // Constant suitable for movw, must be between 0 and 14075 // 65535. 14076 if (Subtarget->hasV6T2Ops()) 14077 if (CVal >= 0 && CVal <= 65535) 14078 break; 14079 return; 14080 case 'I': 14081 if (Subtarget->isThumb1Only()) { 14082 // This must be a constant between 0 and 255, for ADD 14083 // immediates. 14084 if (CVal >= 0 && CVal <= 255) 14085 break; 14086 } else if (Subtarget->isThumb2()) { 14087 // A constant that can be used as an immediate value in a 14088 // data-processing instruction. 14089 if (ARM_AM::getT2SOImmVal(CVal) != -1) 14090 break; 14091 } else { 14092 // A constant that can be used as an immediate value in a 14093 // data-processing instruction. 14094 if (ARM_AM::getSOImmVal(CVal) != -1) 14095 break; 14096 } 14097 return; 14098 14099 case 'J': 14100 if (Subtarget->isThumb1Only()) { 14101 // This must be a constant between -255 and -1, for negated ADD 14102 // immediates. This can be used in GCC with an "n" modifier that 14103 // prints the negated value, for use with SUB instructions. It is 14104 // not useful otherwise but is implemented for compatibility. 14105 if (CVal >= -255 && CVal <= -1) 14106 break; 14107 } else { 14108 // This must be a constant between -4095 and 4095. It is not clear 14109 // what this constraint is intended for. Implemented for 14110 // compatibility with GCC. 14111 if (CVal >= -4095 && CVal <= 4095) 14112 break; 14113 } 14114 return; 14115 14116 case 'K': 14117 if (Subtarget->isThumb1Only()) { 14118 // A 32-bit value where only one byte has a nonzero value. Exclude 14119 // zero to match GCC. This constraint is used by GCC internally for 14120 // constants that can be loaded with a move/shift combination. 14121 // It is not useful otherwise but is implemented for compatibility. 14122 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 14123 break; 14124 } else if (Subtarget->isThumb2()) { 14125 // A constant whose bitwise inverse can be used as an immediate 14126 // value in a data-processing instruction. This can be used in GCC 14127 // with a "B" modifier that prints the inverted value, for use with 14128 // BIC and MVN instructions. It is not useful otherwise but is 14129 // implemented for compatibility. 14130 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 14131 break; 14132 } else { 14133 // A constant whose bitwise inverse can be used as an immediate 14134 // value in a data-processing instruction. This can be used in GCC 14135 // with a "B" modifier that prints the inverted value, for use with 14136 // BIC and MVN instructions. It is not useful otherwise but is 14137 // implemented for compatibility. 14138 if (ARM_AM::getSOImmVal(~CVal) != -1) 14139 break; 14140 } 14141 return; 14142 14143 case 'L': 14144 if (Subtarget->isThumb1Only()) { 14145 // This must be a constant between -7 and 7, 14146 // for 3-operand ADD/SUB immediate instructions. 14147 if (CVal >= -7 && CVal < 7) 14148 break; 14149 } else if (Subtarget->isThumb2()) { 14150 // A constant whose negation can be used as an immediate value in a 14151 // data-processing instruction. This can be used in GCC with an "n" 14152 // modifier that prints the negated value, for use with SUB 14153 // instructions. It is not useful otherwise but is implemented for 14154 // compatibility. 14155 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 14156 break; 14157 } else { 14158 // A constant whose negation can be used as an immediate value in a 14159 // data-processing instruction. This can be used in GCC with an "n" 14160 // modifier that prints the negated value, for use with SUB 14161 // instructions. It is not useful otherwise but is implemented for 14162 // compatibility. 14163 if (ARM_AM::getSOImmVal(-CVal) != -1) 14164 break; 14165 } 14166 return; 14167 14168 case 'M': 14169 if (Subtarget->isThumb1Only()) { 14170 // This must be a multiple of 4 between 0 and 1020, for 14171 // ADD sp + immediate. 14172 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 14173 break; 14174 } else { 14175 // A power of two or a constant between 0 and 32. This is used in 14176 // GCC for the shift amount on shifted register operands, but it is 14177 // useful in general for any shift amounts. 14178 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 14179 break; 14180 } 14181 return; 14182 14183 case 'N': 14184 if (Subtarget->isThumb()) { // FIXME thumb2 14185 // This must be a constant between 0 and 31, for shift amounts. 14186 if (CVal >= 0 && CVal <= 31) 14187 break; 14188 } 14189 return; 14190 14191 case 'O': 14192 if (Subtarget->isThumb()) { // FIXME thumb2 14193 // This must be a multiple of 4 between -508 and 508, for 14194 // ADD/SUB sp = sp + immediate. 14195 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 14196 break; 14197 } 14198 return; 14199 } 14200 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 14201 break; 14202 } 14203 14204 if (Result.getNode()) { 14205 Ops.push_back(Result); 14206 return; 14207 } 14208 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14209 } 14210 14211 static RTLIB::Libcall getDivRemLibcall( 14212 const SDNode *N, MVT::SimpleValueType SVT) { 14213 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 14214 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 14215 "Unhandled Opcode in getDivRemLibcall"); 14216 bool isSigned = N->getOpcode() == ISD::SDIVREM || 14217 N->getOpcode() == ISD::SREM; 14218 RTLIB::Libcall LC; 14219 switch (SVT) { 14220 default: llvm_unreachable("Unexpected request for libcall!"); 14221 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 14222 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 14223 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 14224 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 14225 } 14226 return LC; 14227 } 14228 14229 static TargetLowering::ArgListTy getDivRemArgList( 14230 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 14231 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 14232 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 14233 "Unhandled Opcode in getDivRemArgList"); 14234 bool isSigned = N->getOpcode() == ISD::SDIVREM || 14235 N->getOpcode() == ISD::SREM; 14236 TargetLowering::ArgListTy Args; 14237 TargetLowering::ArgListEntry Entry; 14238 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14239 EVT ArgVT = N->getOperand(i).getValueType(); 14240 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 14241 Entry.Node = N->getOperand(i); 14242 Entry.Ty = ArgTy; 14243 Entry.IsSExt = isSigned; 14244 Entry.IsZExt = !isSigned; 14245 Args.push_back(Entry); 14246 } 14247 if (Subtarget->isTargetWindows() && Args.size() >= 2) 14248 std::swap(Args[0], Args[1]); 14249 return Args; 14250 } 14251 14252 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 14253 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 14254 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 14255 Subtarget->isTargetWindows()) && 14256 "Register-based DivRem lowering only"); 14257 unsigned Opcode = Op->getOpcode(); 14258 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 14259 "Invalid opcode for Div/Rem lowering"); 14260 bool isSigned = (Opcode == ISD::SDIVREM); 14261 EVT VT = Op->getValueType(0); 14262 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 14263 SDLoc dl(Op); 14264 14265 // If the target has hardware divide, use divide + multiply + subtract: 14266 // div = a / b 14267 // rem = a - b * div 14268 // return {div, rem} 14269 // This should be lowered into UDIV/SDIV + MLS later on. 14270 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 14271 : Subtarget->hasDivideInARMMode(); 14272 if (hasDivide && Op->getValueType(0).isSimple() && 14273 Op->getSimpleValueType(0) == MVT::i32) { 14274 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 14275 const SDValue Dividend = Op->getOperand(0); 14276 const SDValue Divisor = Op->getOperand(1); 14277 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 14278 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 14279 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 14280 14281 SDValue Values[2] = {Div, Rem}; 14282 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 14283 } 14284 14285 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 14286 VT.getSimpleVT().SimpleTy); 14287 SDValue InChain = DAG.getEntryNode(); 14288 14289 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 14290 DAG.getContext(), 14291 Subtarget); 14292 14293 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 14294 getPointerTy(DAG.getDataLayout())); 14295 14296 Type *RetTy = StructType::get(Ty, Ty); 14297 14298 if (Subtarget->isTargetWindows()) 14299 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 14300 14301 TargetLowering::CallLoweringInfo CLI(DAG); 14302 CLI.setDebugLoc(dl).setChain(InChain) 14303 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 14304 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 14305 14306 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 14307 return CallInfo.first; 14308 } 14309 14310 // Lowers REM using divmod helpers 14311 // see RTABI section 4.2/4.3 14312 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 14313 // Build return types (div and rem) 14314 std::vector<Type*> RetTyParams; 14315 Type *RetTyElement; 14316 14317 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 14318 default: llvm_unreachable("Unexpected request for libcall!"); 14319 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 14320 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 14321 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 14322 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 14323 } 14324 14325 RetTyParams.push_back(RetTyElement); 14326 RetTyParams.push_back(RetTyElement); 14327 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 14328 Type *RetTy = StructType::get(*DAG.getContext(), ret); 14329 14330 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 14331 SimpleTy); 14332 SDValue InChain = DAG.getEntryNode(); 14333 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 14334 Subtarget); 14335 bool isSigned = N->getOpcode() == ISD::SREM; 14336 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 14337 getPointerTy(DAG.getDataLayout())); 14338 14339 if (Subtarget->isTargetWindows()) 14340 InChain = WinDBZCheckDenominator(DAG, N, InChain); 14341 14342 // Lower call 14343 CallLoweringInfo CLI(DAG); 14344 CLI.setChain(InChain) 14345 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 14346 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 14347 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 14348 14349 // Return second (rem) result operand (first contains div) 14350 SDNode *ResNode = CallResult.first.getNode(); 14351 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 14352 return ResNode->getOperand(1); 14353 } 14354 14355 SDValue 14356 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 14357 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 14358 SDLoc DL(Op); 14359 14360 // Get the inputs. 14361 SDValue Chain = Op.getOperand(0); 14362 SDValue Size = Op.getOperand(1); 14363 14364 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 14365 "no-stack-arg-probe")) { 14366 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 14367 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14368 Chain = SP.getValue(1); 14369 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 14370 if (Align) 14371 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 14372 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 14373 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 14374 SDValue Ops[2] = { SP, Chain }; 14375 return DAG.getMergeValues(Ops, DL); 14376 } 14377 14378 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 14379 DAG.getConstant(2, DL, MVT::i32)); 14380 14381 SDValue Flag; 14382 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 14383 Flag = Chain.getValue(1); 14384 14385 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 14386 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 14387 14388 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14389 Chain = NewSP.getValue(1); 14390 14391 SDValue Ops[2] = { NewSP, Chain }; 14392 return DAG.getMergeValues(Ops, DL); 14393 } 14394 14395 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 14396 assert(Op.getValueType() == MVT::f64 && !Subtarget->hasFP64() && 14397 "Unexpected type for custom-lowering FP_EXTEND"); 14398 14399 RTLIB::Libcall LC; 14400 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 14401 14402 SDValue SrcVal = Op.getOperand(0); 14403 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14404 SDLoc(Op)).first; 14405 } 14406 14407 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 14408 assert(Op.getOperand(0).getValueType() == MVT::f64 && !Subtarget->hasFP64() && 14409 "Unexpected type for custom-lowering FP_ROUND"); 14410 14411 RTLIB::Libcall LC; 14412 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 14413 14414 SDValue SrcVal = Op.getOperand(0); 14415 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14416 SDLoc(Op)).first; 14417 } 14418 14419 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 14420 SelectionDAG &DAG) const { 14421 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 14422 MVT HalfT = MVT::i32; 14423 SDLoc dl(N); 14424 SDValue Hi, Lo, Tmp; 14425 14426 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 14427 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 14428 return ; 14429 14430 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 14431 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 14432 14433 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 14434 DAG.getConstant(0, dl, HalfT)); 14435 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 14436 DAG.getConstant(1, dl, HalfT)); 14437 14438 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 14439 DAG.getConstant(OpTypeBits - 1, dl, 14440 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 14441 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 14442 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 14443 SDValue(Lo.getNode(), 1)); 14444 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 14445 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 14446 14447 Results.push_back(Lo); 14448 Results.push_back(Hi); 14449 } 14450 14451 bool 14452 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14453 // The ARM target isn't yet aware of offsets. 14454 return false; 14455 } 14456 14457 bool ARM::isBitFieldInvertedMask(unsigned v) { 14458 if (v == 0xffffffff) 14459 return false; 14460 14461 // there can be 1's on either or both "outsides", all the "inside" 14462 // bits must be 0's 14463 return isShiftedMask_32(~v); 14464 } 14465 14466 /// isFPImmLegal - Returns true if the target can instruction select the 14467 /// specified FP immediate natively. If false, the legalizer will 14468 /// materialize the FP immediate as a load from a constant pool. 14469 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14470 bool ForCodeSize) const { 14471 if (!Subtarget->hasVFP3Base()) 14472 return false; 14473 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 14474 return ARM_AM::getFP16Imm(Imm) != -1; 14475 if (VT == MVT::f32) 14476 return ARM_AM::getFP32Imm(Imm) != -1; 14477 if (VT == MVT::f64 && Subtarget->hasFP64()) 14478 return ARM_AM::getFP64Imm(Imm) != -1; 14479 return false; 14480 } 14481 14482 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 14483 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 14484 /// specified in the intrinsic calls. 14485 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14486 const CallInst &I, 14487 MachineFunction &MF, 14488 unsigned Intrinsic) const { 14489 switch (Intrinsic) { 14490 case Intrinsic::arm_neon_vld1: 14491 case Intrinsic::arm_neon_vld2: 14492 case Intrinsic::arm_neon_vld3: 14493 case Intrinsic::arm_neon_vld4: 14494 case Intrinsic::arm_neon_vld2lane: 14495 case Intrinsic::arm_neon_vld3lane: 14496 case Intrinsic::arm_neon_vld4lane: 14497 case Intrinsic::arm_neon_vld2dup: 14498 case Intrinsic::arm_neon_vld3dup: 14499 case Intrinsic::arm_neon_vld4dup: { 14500 Info.opc = ISD::INTRINSIC_W_CHAIN; 14501 // Conservatively set memVT to the entire set of vectors loaded. 14502 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14503 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14504 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14505 Info.ptrVal = I.getArgOperand(0); 14506 Info.offset = 0; 14507 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14508 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14509 // volatile loads with NEON intrinsics not supported 14510 Info.flags = MachineMemOperand::MOLoad; 14511 return true; 14512 } 14513 case Intrinsic::arm_neon_vld1x2: 14514 case Intrinsic::arm_neon_vld1x3: 14515 case Intrinsic::arm_neon_vld1x4: { 14516 Info.opc = ISD::INTRINSIC_W_CHAIN; 14517 // Conservatively set memVT to the entire set of vectors loaded. 14518 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14519 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14520 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14521 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 14522 Info.offset = 0; 14523 Info.align = 0; 14524 // volatile loads with NEON intrinsics not supported 14525 Info.flags = MachineMemOperand::MOLoad; 14526 return true; 14527 } 14528 case Intrinsic::arm_neon_vst1: 14529 case Intrinsic::arm_neon_vst2: 14530 case Intrinsic::arm_neon_vst3: 14531 case Intrinsic::arm_neon_vst4: 14532 case Intrinsic::arm_neon_vst2lane: 14533 case Intrinsic::arm_neon_vst3lane: 14534 case Intrinsic::arm_neon_vst4lane: { 14535 Info.opc = ISD::INTRINSIC_VOID; 14536 // Conservatively set memVT to the entire set of vectors stored. 14537 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14538 unsigned NumElts = 0; 14539 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14540 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14541 if (!ArgTy->isVectorTy()) 14542 break; 14543 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14544 } 14545 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14546 Info.ptrVal = I.getArgOperand(0); 14547 Info.offset = 0; 14548 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14549 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14550 // volatile stores with NEON intrinsics not supported 14551 Info.flags = MachineMemOperand::MOStore; 14552 return true; 14553 } 14554 case Intrinsic::arm_neon_vst1x2: 14555 case Intrinsic::arm_neon_vst1x3: 14556 case Intrinsic::arm_neon_vst1x4: { 14557 Info.opc = ISD::INTRINSIC_VOID; 14558 // Conservatively set memVT to the entire set of vectors stored. 14559 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14560 unsigned NumElts = 0; 14561 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14562 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14563 if (!ArgTy->isVectorTy()) 14564 break; 14565 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14566 } 14567 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14568 Info.ptrVal = I.getArgOperand(0); 14569 Info.offset = 0; 14570 Info.align = 0; 14571 // volatile stores with NEON intrinsics not supported 14572 Info.flags = MachineMemOperand::MOStore; 14573 return true; 14574 } 14575 case Intrinsic::arm_ldaex: 14576 case Intrinsic::arm_ldrex: { 14577 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14578 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 14579 Info.opc = ISD::INTRINSIC_W_CHAIN; 14580 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14581 Info.ptrVal = I.getArgOperand(0); 14582 Info.offset = 0; 14583 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14584 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14585 return true; 14586 } 14587 case Intrinsic::arm_stlex: 14588 case Intrinsic::arm_strex: { 14589 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14590 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 14591 Info.opc = ISD::INTRINSIC_W_CHAIN; 14592 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14593 Info.ptrVal = I.getArgOperand(1); 14594 Info.offset = 0; 14595 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14596 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14597 return true; 14598 } 14599 case Intrinsic::arm_stlexd: 14600 case Intrinsic::arm_strexd: 14601 Info.opc = ISD::INTRINSIC_W_CHAIN; 14602 Info.memVT = MVT::i64; 14603 Info.ptrVal = I.getArgOperand(2); 14604 Info.offset = 0; 14605 Info.align = 8; 14606 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14607 return true; 14608 14609 case Intrinsic::arm_ldaexd: 14610 case Intrinsic::arm_ldrexd: 14611 Info.opc = ISD::INTRINSIC_W_CHAIN; 14612 Info.memVT = MVT::i64; 14613 Info.ptrVal = I.getArgOperand(0); 14614 Info.offset = 0; 14615 Info.align = 8; 14616 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14617 return true; 14618 14619 default: 14620 break; 14621 } 14622 14623 return false; 14624 } 14625 14626 /// Returns true if it is beneficial to convert a load of a constant 14627 /// to just the constant itself. 14628 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14629 Type *Ty) const { 14630 assert(Ty->isIntegerTy()); 14631 14632 unsigned Bits = Ty->getPrimitiveSizeInBits(); 14633 if (Bits == 0 || Bits > 32) 14634 return false; 14635 return true; 14636 } 14637 14638 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 14639 unsigned Index) const { 14640 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 14641 return false; 14642 14643 return (Index == 0 || Index == ResVT.getVectorNumElements()); 14644 } 14645 14646 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 14647 ARM_MB::MemBOpt Domain) const { 14648 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14649 14650 // First, if the target has no DMB, see what fallback we can use. 14651 if (!Subtarget->hasDataBarrier()) { 14652 // Some ARMv6 cpus can support data barriers with an mcr instruction. 14653 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 14654 // here. 14655 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 14656 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 14657 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 14658 Builder.getInt32(0), Builder.getInt32(7), 14659 Builder.getInt32(10), Builder.getInt32(5)}; 14660 return Builder.CreateCall(MCR, args); 14661 } else { 14662 // Instead of using barriers, atomic accesses on these subtargets use 14663 // libcalls. 14664 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 14665 } 14666 } else { 14667 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 14668 // Only a full system barrier exists in the M-class architectures. 14669 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 14670 Constant *CDomain = Builder.getInt32(Domain); 14671 return Builder.CreateCall(DMB, CDomain); 14672 } 14673 } 14674 14675 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 14676 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 14677 Instruction *Inst, 14678 AtomicOrdering Ord) const { 14679 switch (Ord) { 14680 case AtomicOrdering::NotAtomic: 14681 case AtomicOrdering::Unordered: 14682 llvm_unreachable("Invalid fence: unordered/non-atomic"); 14683 case AtomicOrdering::Monotonic: 14684 case AtomicOrdering::Acquire: 14685 return nullptr; // Nothing to do 14686 case AtomicOrdering::SequentiallyConsistent: 14687 if (!Inst->hasAtomicStore()) 14688 return nullptr; // Nothing to do 14689 LLVM_FALLTHROUGH; 14690 case AtomicOrdering::Release: 14691 case AtomicOrdering::AcquireRelease: 14692 if (Subtarget->preferISHSTBarriers()) 14693 return makeDMB(Builder, ARM_MB::ISHST); 14694 // FIXME: add a comment with a link to documentation justifying this. 14695 else 14696 return makeDMB(Builder, ARM_MB::ISH); 14697 } 14698 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 14699 } 14700 14701 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 14702 Instruction *Inst, 14703 AtomicOrdering Ord) const { 14704 switch (Ord) { 14705 case AtomicOrdering::NotAtomic: 14706 case AtomicOrdering::Unordered: 14707 llvm_unreachable("Invalid fence: unordered/not-atomic"); 14708 case AtomicOrdering::Monotonic: 14709 case AtomicOrdering::Release: 14710 return nullptr; // Nothing to do 14711 case AtomicOrdering::Acquire: 14712 case AtomicOrdering::AcquireRelease: 14713 case AtomicOrdering::SequentiallyConsistent: 14714 return makeDMB(Builder, ARM_MB::ISH); 14715 } 14716 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 14717 } 14718 14719 // Loads and stores less than 64-bits are already atomic; ones above that 14720 // are doomed anyway, so defer to the default libcall and blame the OS when 14721 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14722 // anything for those. 14723 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 14724 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 14725 return (Size == 64) && !Subtarget->isMClass(); 14726 } 14727 14728 // Loads and stores less than 64-bits are already atomic; ones above that 14729 // are doomed anyway, so defer to the default libcall and blame the OS when 14730 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14731 // anything for those. 14732 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 14733 // guarantee, see DDI0406C ARM architecture reference manual, 14734 // sections A8.8.72-74 LDRD) 14735 TargetLowering::AtomicExpansionKind 14736 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 14737 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 14738 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 14739 : AtomicExpansionKind::None; 14740 } 14741 14742 // For the real atomic operations, we have ldrex/strex up to 32 bits, 14743 // and up to 64 bits on the non-M profiles 14744 TargetLowering::AtomicExpansionKind 14745 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 14746 if (AI->isFloatingPointOperation()) 14747 return AtomicExpansionKind::CmpXChg; 14748 14749 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 14750 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14751 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 14752 ? AtomicExpansionKind::LLSC 14753 : AtomicExpansionKind::None; 14754 } 14755 14756 TargetLowering::AtomicExpansionKind 14757 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 14758 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 14759 // implement cmpxchg without spilling. If the address being exchanged is also 14760 // on the stack and close enough to the spill slot, this can lead to a 14761 // situation where the monitor always gets cleared and the atomic operation 14762 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 14763 bool HasAtomicCmpXchg = 14764 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14765 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 14766 return AtomicExpansionKind::LLSC; 14767 return AtomicExpansionKind::None; 14768 } 14769 14770 bool ARMTargetLowering::shouldInsertFencesForAtomic( 14771 const Instruction *I) const { 14772 return InsertFencesForAtomic; 14773 } 14774 14775 // This has so far only been implemented for MachO. 14776 bool ARMTargetLowering::useLoadStackGuardNode() const { 14777 return Subtarget->isTargetMachO(); 14778 } 14779 14780 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 14781 unsigned &Cost) const { 14782 // If we do not have NEON, vector types are not natively supported. 14783 if (!Subtarget->hasNEON()) 14784 return false; 14785 14786 // Floating point values and vector values map to the same register file. 14787 // Therefore, although we could do a store extract of a vector type, this is 14788 // better to leave at float as we have more freedom in the addressing mode for 14789 // those. 14790 if (VectorTy->isFPOrFPVectorTy()) 14791 return false; 14792 14793 // If the index is unknown at compile time, this is very expensive to lower 14794 // and it is not possible to combine the store with the extract. 14795 if (!isa<ConstantInt>(Idx)) 14796 return false; 14797 14798 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 14799 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 14800 // We can do a store + vector extract on any vector that fits perfectly in a D 14801 // or Q register. 14802 if (BitWidth == 64 || BitWidth == 128) { 14803 Cost = 0; 14804 return true; 14805 } 14806 return false; 14807 } 14808 14809 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 14810 return Subtarget->hasV6T2Ops(); 14811 } 14812 14813 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 14814 return Subtarget->hasV6T2Ops(); 14815 } 14816 14817 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 14818 return !Subtarget->hasMinSize(); 14819 } 14820 14821 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 14822 AtomicOrdering Ord) const { 14823 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14824 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 14825 bool IsAcquire = isAcquireOrStronger(Ord); 14826 14827 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 14828 // intrinsic must return {i32, i32} and we have to recombine them into a 14829 // single i64 here. 14830 if (ValTy->getPrimitiveSizeInBits() == 64) { 14831 Intrinsic::ID Int = 14832 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 14833 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 14834 14835 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14836 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 14837 14838 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 14839 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 14840 if (!Subtarget->isLittle()) 14841 std::swap (Lo, Hi); 14842 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 14843 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 14844 return Builder.CreateOr( 14845 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 14846 } 14847 14848 Type *Tys[] = { Addr->getType() }; 14849 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 14850 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 14851 14852 return Builder.CreateTruncOrBitCast( 14853 Builder.CreateCall(Ldrex, Addr), 14854 cast<PointerType>(Addr->getType())->getElementType()); 14855 } 14856 14857 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 14858 IRBuilder<> &Builder) const { 14859 if (!Subtarget->hasV7Ops()) 14860 return; 14861 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14862 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 14863 } 14864 14865 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 14866 Value *Addr, 14867 AtomicOrdering Ord) const { 14868 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14869 bool IsRelease = isReleaseOrStronger(Ord); 14870 14871 // Since the intrinsics must have legal type, the i64 intrinsics take two 14872 // parameters: "i32, i32". We must marshal Val into the appropriate form 14873 // before the call. 14874 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 14875 Intrinsic::ID Int = 14876 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 14877 Function *Strex = Intrinsic::getDeclaration(M, Int); 14878 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 14879 14880 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 14881 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 14882 if (!Subtarget->isLittle()) 14883 std::swap(Lo, Hi); 14884 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14885 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 14886 } 14887 14888 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 14889 Type *Tys[] = { Addr->getType() }; 14890 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 14891 14892 return Builder.CreateCall( 14893 Strex, {Builder.CreateZExtOrBitCast( 14894 Val, Strex->getFunctionType()->getParamType(0)), 14895 Addr}); 14896 } 14897 14898 14899 bool ARMTargetLowering::alignLoopsWithOptSize() const { 14900 return Subtarget->isMClass(); 14901 } 14902 14903 /// A helper function for determining the number of interleaved accesses we 14904 /// will generate when lowering accesses of the given type. 14905 unsigned 14906 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 14907 const DataLayout &DL) const { 14908 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 14909 } 14910 14911 bool ARMTargetLowering::isLegalInterleavedAccessType( 14912 VectorType *VecTy, const DataLayout &DL) const { 14913 14914 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 14915 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 14916 14917 // Ensure the vector doesn't have f16 elements. Even though we could do an 14918 // i16 vldN, we can't hold the f16 vectors and will end up converting via 14919 // f32. 14920 if (VecTy->getElementType()->isHalfTy()) 14921 return false; 14922 14923 // Ensure the number of vector elements is greater than 1. 14924 if (VecTy->getNumElements() < 2) 14925 return false; 14926 14927 // Ensure the element type is legal. 14928 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 14929 return false; 14930 14931 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 14932 // 128 will be split into multiple interleaved accesses. 14933 return VecSize == 64 || VecSize % 128 == 0; 14934 } 14935 14936 /// Lower an interleaved load into a vldN intrinsic. 14937 /// 14938 /// E.g. Lower an interleaved load (Factor = 2): 14939 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 14940 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 14941 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 14942 /// 14943 /// Into: 14944 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 14945 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 14946 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 14947 bool ARMTargetLowering::lowerInterleavedLoad( 14948 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 14949 ArrayRef<unsigned> Indices, unsigned Factor) const { 14950 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14951 "Invalid interleave factor"); 14952 assert(!Shuffles.empty() && "Empty shufflevector input"); 14953 assert(Shuffles.size() == Indices.size() && 14954 "Unmatched number of shufflevectors and indices"); 14955 14956 VectorType *VecTy = Shuffles[0]->getType(); 14957 Type *EltTy = VecTy->getVectorElementType(); 14958 14959 const DataLayout &DL = LI->getModule()->getDataLayout(); 14960 14961 // Skip if we do not have NEON and skip illegal vector types. We can 14962 // "legalize" wide vector types into multiple interleaved accesses as long as 14963 // the vector types are divisible by 128. 14964 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 14965 return false; 14966 14967 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 14968 14969 // A pointer vector can not be the return type of the ldN intrinsics. Need to 14970 // load integer vectors first and then convert to pointer vectors. 14971 if (EltTy->isPointerTy()) 14972 VecTy = 14973 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 14974 14975 IRBuilder<> Builder(LI); 14976 14977 // The base address of the load. 14978 Value *BaseAddr = LI->getPointerOperand(); 14979 14980 if (NumLoads > 1) { 14981 // If we're going to generate more than one load, reset the sub-vector type 14982 // to something legal. 14983 VecTy = VectorType::get(VecTy->getVectorElementType(), 14984 VecTy->getVectorNumElements() / NumLoads); 14985 14986 // We will compute the pointer operand of each load from the original base 14987 // address using GEPs. Cast the base address to a pointer to the scalar 14988 // element type. 14989 BaseAddr = Builder.CreateBitCast( 14990 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 14991 LI->getPointerAddressSpace())); 14992 } 14993 14994 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 14995 14996 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 14997 Type *Tys[] = {VecTy, Int8Ptr}; 14998 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 14999 Intrinsic::arm_neon_vld3, 15000 Intrinsic::arm_neon_vld4}; 15001 Function *VldnFunc = 15002 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 15003 15004 // Holds sub-vectors extracted from the load intrinsic return values. The 15005 // sub-vectors are associated with the shufflevector instructions they will 15006 // replace. 15007 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 15008 15009 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 15010 // If we're generating more than one load, compute the base address of 15011 // subsequent loads as an offset from the previous. 15012 if (LoadCount > 0) 15013 BaseAddr = 15014 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 15015 VecTy->getVectorNumElements() * Factor); 15016 15017 SmallVector<Value *, 2> Ops; 15018 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 15019 Ops.push_back(Builder.getInt32(LI->getAlignment())); 15020 15021 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 15022 15023 // Replace uses of each shufflevector with the corresponding vector loaded 15024 // by ldN. 15025 for (unsigned i = 0; i < Shuffles.size(); i++) { 15026 ShuffleVectorInst *SV = Shuffles[i]; 15027 unsigned Index = Indices[i]; 15028 15029 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 15030 15031 // Convert the integer vector to pointer vector if the element is pointer. 15032 if (EltTy->isPointerTy()) 15033 SubVec = Builder.CreateIntToPtr( 15034 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 15035 VecTy->getVectorNumElements())); 15036 15037 SubVecs[SV].push_back(SubVec); 15038 } 15039 } 15040 15041 // Replace uses of the shufflevector instructions with the sub-vectors 15042 // returned by the load intrinsic. If a shufflevector instruction is 15043 // associated with more than one sub-vector, those sub-vectors will be 15044 // concatenated into a single wide vector. 15045 for (ShuffleVectorInst *SVI : Shuffles) { 15046 auto &SubVec = SubVecs[SVI]; 15047 auto *WideVec = 15048 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 15049 SVI->replaceAllUsesWith(WideVec); 15050 } 15051 15052 return true; 15053 } 15054 15055 /// Lower an interleaved store into a vstN intrinsic. 15056 /// 15057 /// E.g. Lower an interleaved store (Factor = 3): 15058 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 15059 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 15060 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 15061 /// 15062 /// Into: 15063 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 15064 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 15065 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 15066 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 15067 /// 15068 /// Note that the new shufflevectors will be removed and we'll only generate one 15069 /// vst3 instruction in CodeGen. 15070 /// 15071 /// Example for a more general valid mask (Factor 3). Lower: 15072 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 15073 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 15074 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 15075 /// 15076 /// Into: 15077 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 15078 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 15079 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 15080 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 15081 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 15082 ShuffleVectorInst *SVI, 15083 unsigned Factor) const { 15084 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 15085 "Invalid interleave factor"); 15086 15087 VectorType *VecTy = SVI->getType(); 15088 assert(VecTy->getVectorNumElements() % Factor == 0 && 15089 "Invalid interleaved store"); 15090 15091 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 15092 Type *EltTy = VecTy->getVectorElementType(); 15093 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 15094 15095 const DataLayout &DL = SI->getModule()->getDataLayout(); 15096 15097 // Skip if we do not have NEON and skip illegal vector types. We can 15098 // "legalize" wide vector types into multiple interleaved accesses as long as 15099 // the vector types are divisible by 128. 15100 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 15101 return false; 15102 15103 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 15104 15105 Value *Op0 = SVI->getOperand(0); 15106 Value *Op1 = SVI->getOperand(1); 15107 IRBuilder<> Builder(SI); 15108 15109 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 15110 // vectors to integer vectors. 15111 if (EltTy->isPointerTy()) { 15112 Type *IntTy = DL.getIntPtrType(EltTy); 15113 15114 // Convert to the corresponding integer vector. 15115 Type *IntVecTy = 15116 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 15117 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 15118 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 15119 15120 SubVecTy = VectorType::get(IntTy, LaneLen); 15121 } 15122 15123 // The base address of the store. 15124 Value *BaseAddr = SI->getPointerOperand(); 15125 15126 if (NumStores > 1) { 15127 // If we're going to generate more than one store, reset the lane length 15128 // and sub-vector type to something legal. 15129 LaneLen /= NumStores; 15130 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 15131 15132 // We will compute the pointer operand of each store from the original base 15133 // address using GEPs. Cast the base address to a pointer to the scalar 15134 // element type. 15135 BaseAddr = Builder.CreateBitCast( 15136 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 15137 SI->getPointerAddressSpace())); 15138 } 15139 15140 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 15141 15142 auto Mask = SVI->getShuffleMask(); 15143 15144 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 15145 Type *Tys[] = {Int8Ptr, SubVecTy}; 15146 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 15147 Intrinsic::arm_neon_vst3, 15148 Intrinsic::arm_neon_vst4}; 15149 15150 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 15151 // If we generating more than one store, we compute the base address of 15152 // subsequent stores as an offset from the previous. 15153 if (StoreCount > 0) 15154 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 15155 BaseAddr, LaneLen * Factor); 15156 15157 SmallVector<Value *, 6> Ops; 15158 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 15159 15160 Function *VstNFunc = 15161 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 15162 15163 // Split the shufflevector operands into sub vectors for the new vstN call. 15164 for (unsigned i = 0; i < Factor; i++) { 15165 unsigned IdxI = StoreCount * LaneLen * Factor + i; 15166 if (Mask[IdxI] >= 0) { 15167 Ops.push_back(Builder.CreateShuffleVector( 15168 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 15169 } else { 15170 unsigned StartMask = 0; 15171 for (unsigned j = 1; j < LaneLen; j++) { 15172 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 15173 if (Mask[IdxJ * Factor + IdxI] >= 0) { 15174 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 15175 break; 15176 } 15177 } 15178 // Note: If all elements in a chunk are undefs, StartMask=0! 15179 // Note: Filling undef gaps with random elements is ok, since 15180 // those elements were being written anyway (with undefs). 15181 // In the case of all undefs we're defaulting to using elems from 0 15182 // Note: StartMask cannot be negative, it's checked in 15183 // isReInterleaveMask 15184 Ops.push_back(Builder.CreateShuffleVector( 15185 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 15186 } 15187 } 15188 15189 Ops.push_back(Builder.getInt32(SI->getAlignment())); 15190 Builder.CreateCall(VstNFunc, Ops); 15191 } 15192 return true; 15193 } 15194 15195 enum HABaseType { 15196 HA_UNKNOWN = 0, 15197 HA_FLOAT, 15198 HA_DOUBLE, 15199 HA_VECT64, 15200 HA_VECT128 15201 }; 15202 15203 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 15204 uint64_t &Members) { 15205 if (auto *ST = dyn_cast<StructType>(Ty)) { 15206 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 15207 uint64_t SubMembers = 0; 15208 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 15209 return false; 15210 Members += SubMembers; 15211 } 15212 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 15213 uint64_t SubMembers = 0; 15214 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 15215 return false; 15216 Members += SubMembers * AT->getNumElements(); 15217 } else if (Ty->isFloatTy()) { 15218 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 15219 return false; 15220 Members = 1; 15221 Base = HA_FLOAT; 15222 } else if (Ty->isDoubleTy()) { 15223 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 15224 return false; 15225 Members = 1; 15226 Base = HA_DOUBLE; 15227 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 15228 Members = 1; 15229 switch (Base) { 15230 case HA_FLOAT: 15231 case HA_DOUBLE: 15232 return false; 15233 case HA_VECT64: 15234 return VT->getBitWidth() == 64; 15235 case HA_VECT128: 15236 return VT->getBitWidth() == 128; 15237 case HA_UNKNOWN: 15238 switch (VT->getBitWidth()) { 15239 case 64: 15240 Base = HA_VECT64; 15241 return true; 15242 case 128: 15243 Base = HA_VECT128; 15244 return true; 15245 default: 15246 return false; 15247 } 15248 } 15249 } 15250 15251 return (Members > 0 && Members <= 4); 15252 } 15253 15254 /// Return the correct alignment for the current calling convention. 15255 unsigned 15256 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 15257 DataLayout DL) const { 15258 if (!ArgTy->isVectorTy()) 15259 return DL.getABITypeAlignment(ArgTy); 15260 15261 // Avoid over-aligning vector parameters. It would require realigning the 15262 // stack and waste space for no real benefit. 15263 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 15264 } 15265 15266 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 15267 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 15268 /// passing according to AAPCS rules. 15269 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 15270 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 15271 if (getEffectiveCallingConv(CallConv, isVarArg) != 15272 CallingConv::ARM_AAPCS_VFP) 15273 return false; 15274 15275 HABaseType Base = HA_UNKNOWN; 15276 uint64_t Members = 0; 15277 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 15278 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 15279 15280 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 15281 return IsHA || IsIntArray; 15282 } 15283 15284 unsigned ARMTargetLowering::getExceptionPointerRegister( 15285 const Constant *PersonalityFn) const { 15286 // Platforms which do not use SjLj EH may return values in these registers 15287 // via the personality function. 15288 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 15289 } 15290 15291 unsigned ARMTargetLowering::getExceptionSelectorRegister( 15292 const Constant *PersonalityFn) const { 15293 // Platforms which do not use SjLj EH may return values in these registers 15294 // via the personality function. 15295 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 15296 } 15297 15298 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15299 // Update IsSplitCSR in ARMFunctionInfo. 15300 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 15301 AFI->setIsSplitCSR(true); 15302 } 15303 15304 void ARMTargetLowering::insertCopiesSplitCSR( 15305 MachineBasicBlock *Entry, 15306 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15307 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 15308 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15309 if (!IStart) 15310 return; 15311 15312 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 15313 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15314 MachineBasicBlock::iterator MBBI = Entry->begin(); 15315 for (const MCPhysReg *I = IStart; *I; ++I) { 15316 const TargetRegisterClass *RC = nullptr; 15317 if (ARM::GPRRegClass.contains(*I)) 15318 RC = &ARM::GPRRegClass; 15319 else if (ARM::DPRRegClass.contains(*I)) 15320 RC = &ARM::DPRRegClass; 15321 else 15322 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15323 15324 unsigned NewVR = MRI->createVirtualRegister(RC); 15325 // Create copy from CSR to a virtual register. 15326 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15327 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15328 // nounwind. If we want to generalize this later, we may need to emit 15329 // CFI pseudo-instructions. 15330 assert(Entry->getParent()->getFunction().hasFnAttribute( 15331 Attribute::NoUnwind) && 15332 "Function should be nounwind in insertCopiesSplitCSR!"); 15333 Entry->addLiveIn(*I); 15334 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15335 .addReg(*I); 15336 15337 // Insert the copy-back instructions right before the terminator. 15338 for (auto *Exit : Exits) 15339 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15340 TII->get(TargetOpcode::COPY), *I) 15341 .addReg(NewVR); 15342 } 15343 } 15344 15345 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 15346 MF.getFrameInfo().computeMaxCallFrameSize(MF); 15347 TargetLoweringBase::finalizeLowering(MF); 15348 } 15349