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/IntrinsicsARM.h" 82 #include "llvm/IR/Module.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Type.h" 85 #include "llvm/IR/User.h" 86 #include "llvm/IR/Value.h" 87 #include "llvm/MC/MCInstrDesc.h" 88 #include "llvm/MC/MCInstrItineraries.h" 89 #include "llvm/MC/MCRegisterInfo.h" 90 #include "llvm/MC/MCSchedule.h" 91 #include "llvm/Support/AtomicOrdering.h" 92 #include "llvm/Support/BranchProbability.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CodeGen.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/ErrorHandling.h" 99 #include "llvm/Support/KnownBits.h" 100 #include "llvm/Support/MachineValueType.h" 101 #include "llvm/Support/MathExtras.h" 102 #include "llvm/Support/raw_ostream.h" 103 #include "llvm/Target/TargetMachine.h" 104 #include "llvm/Target/TargetOptions.h" 105 #include <algorithm> 106 #include <cassert> 107 #include <cstdint> 108 #include <cstdlib> 109 #include <iterator> 110 #include <limits> 111 #include <string> 112 #include <tuple> 113 #include <utility> 114 #include <vector> 115 116 using namespace llvm; 117 using namespace llvm::PatternMatch; 118 119 #define DEBUG_TYPE "arm-isel" 120 121 STATISTIC(NumTailCalls, "Number of tail calls"); 122 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 123 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 124 STATISTIC(NumConstpoolPromoted, 125 "Number of constants with their storage promoted into constant pools"); 126 127 static cl::opt<bool> 128 ARMInterworking("arm-interworking", cl::Hidden, 129 cl::desc("Enable / disable ARM interworking (for debugging only)"), 130 cl::init(true)); 131 132 static cl::opt<bool> EnableConstpoolPromotion( 133 "arm-promote-constant", cl::Hidden, 134 cl::desc("Enable / disable promotion of unnamed_addr constants into " 135 "constant pools"), 136 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 137 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 138 "arm-promote-constant-max-size", cl::Hidden, 139 cl::desc("Maximum size of constant to promote into a constant pool"), 140 cl::init(64)); 141 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 142 "arm-promote-constant-max-total", cl::Hidden, 143 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 144 cl::init(128)); 145 146 cl::opt<unsigned> 147 MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden, 148 cl::desc("Maximum interleave factor for MVE VLDn to generate."), 149 cl::init(2)); 150 151 // The APCS parameter registers. 152 static const MCPhysReg GPRArgRegs[] = { 153 ARM::R0, ARM::R1, ARM::R2, ARM::R3 154 }; 155 156 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 157 MVT PromotedBitwiseVT) { 158 if (VT != PromotedLdStVT) { 159 setOperationAction(ISD::LOAD, VT, Promote); 160 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 161 162 setOperationAction(ISD::STORE, VT, Promote); 163 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 164 } 165 166 MVT ElemTy = VT.getVectorElementType(); 167 if (ElemTy != MVT::f64) 168 setOperationAction(ISD::SETCC, VT, Custom); 169 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 170 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 171 if (ElemTy == MVT::i32) { 172 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 173 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 174 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 175 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 176 } else { 177 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 178 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 179 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 180 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 181 } 182 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 183 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 184 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 185 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 186 setOperationAction(ISD::SELECT, VT, Expand); 187 setOperationAction(ISD::SELECT_CC, VT, Expand); 188 setOperationAction(ISD::VSELECT, VT, Expand); 189 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 190 if (VT.isInteger()) { 191 setOperationAction(ISD::SHL, VT, Custom); 192 setOperationAction(ISD::SRA, VT, Custom); 193 setOperationAction(ISD::SRL, VT, Custom); 194 } 195 196 // Promote all bit-wise operations. 197 if (VT.isInteger() && VT != PromotedBitwiseVT) { 198 setOperationAction(ISD::AND, VT, Promote); 199 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 200 setOperationAction(ISD::OR, VT, Promote); 201 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 202 setOperationAction(ISD::XOR, VT, Promote); 203 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 204 } 205 206 // Neon does not support vector divide/remainder operations. 207 setOperationAction(ISD::SDIV, VT, Expand); 208 setOperationAction(ISD::UDIV, VT, Expand); 209 setOperationAction(ISD::FDIV, VT, Expand); 210 setOperationAction(ISD::SREM, VT, Expand); 211 setOperationAction(ISD::UREM, VT, Expand); 212 setOperationAction(ISD::FREM, VT, Expand); 213 setOperationAction(ISD::SDIVREM, VT, Expand); 214 setOperationAction(ISD::UDIVREM, VT, Expand); 215 216 if (!VT.isFloatingPoint() && 217 VT != MVT::v2i64 && VT != MVT::v1i64) 218 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 219 setOperationAction(Opcode, VT, Legal); 220 if (!VT.isFloatingPoint()) 221 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}) 222 setOperationAction(Opcode, VT, Legal); 223 } 224 225 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 226 addRegisterClass(VT, &ARM::DPRRegClass); 227 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 228 } 229 230 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 231 addRegisterClass(VT, &ARM::DPairRegClass); 232 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 233 } 234 235 void ARMTargetLowering::setAllExpand(MVT VT) { 236 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc) 237 setOperationAction(Opc, VT, Expand); 238 239 // We support these really simple operations even on types where all 240 // the actual arithmetic has to be broken down into simpler 241 // operations or turned into library calls. 242 setOperationAction(ISD::BITCAST, VT, Legal); 243 setOperationAction(ISD::LOAD, VT, Legal); 244 setOperationAction(ISD::STORE, VT, Legal); 245 setOperationAction(ISD::UNDEF, VT, Legal); 246 } 247 248 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To, 249 LegalizeAction Action) { 250 setLoadExtAction(ISD::EXTLOAD, From, To, Action); 251 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action); 252 setLoadExtAction(ISD::SEXTLOAD, From, To, Action); 253 } 254 255 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) { 256 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 }; 257 258 for (auto VT : IntTypes) { 259 addRegisterClass(VT, &ARM::MQPRRegClass); 260 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 261 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 262 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 263 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 264 setOperationAction(ISD::SHL, VT, Custom); 265 setOperationAction(ISD::SRA, VT, Custom); 266 setOperationAction(ISD::SRL, VT, Custom); 267 setOperationAction(ISD::SMIN, VT, Legal); 268 setOperationAction(ISD::SMAX, VT, Legal); 269 setOperationAction(ISD::UMIN, VT, Legal); 270 setOperationAction(ISD::UMAX, VT, Legal); 271 setOperationAction(ISD::ABS, VT, Legal); 272 setOperationAction(ISD::SETCC, VT, Custom); 273 setOperationAction(ISD::MLOAD, VT, Custom); 274 setOperationAction(ISD::MSTORE, VT, Legal); 275 setOperationAction(ISD::CTLZ, VT, Legal); 276 setOperationAction(ISD::CTTZ, VT, Custom); 277 setOperationAction(ISD::BITREVERSE, VT, Legal); 278 setOperationAction(ISD::BSWAP, VT, Legal); 279 setOperationAction(ISD::SADDSAT, VT, Legal); 280 setOperationAction(ISD::UADDSAT, VT, Legal); 281 setOperationAction(ISD::SSUBSAT, VT, Legal); 282 setOperationAction(ISD::USUBSAT, VT, Legal); 283 284 // No native support for these. 285 setOperationAction(ISD::UDIV, VT, Expand); 286 setOperationAction(ISD::SDIV, VT, Expand); 287 setOperationAction(ISD::UREM, VT, Expand); 288 setOperationAction(ISD::SREM, VT, Expand); 289 setOperationAction(ISD::UDIVREM, VT, Expand); 290 setOperationAction(ISD::SDIVREM, VT, Expand); 291 setOperationAction(ISD::CTPOP, VT, Expand); 292 293 // Vector reductions 294 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal); 295 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal); 296 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal); 297 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal); 298 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal); 299 setOperationAction(ISD::VECREDUCE_MUL, VT, Custom); 300 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 301 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 302 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 303 304 if (!HasMVEFP) { 305 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 306 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 307 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 308 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 309 } 310 311 // Pre and Post inc are supported on loads and stores 312 for (unsigned im = (unsigned)ISD::PRE_INC; 313 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 314 setIndexedLoadAction(im, VT, Legal); 315 setIndexedStoreAction(im, VT, Legal); 316 setIndexedMaskedLoadAction(im, VT, Legal); 317 setIndexedMaskedStoreAction(im, VT, Legal); 318 } 319 } 320 321 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 }; 322 for (auto VT : FloatTypes) { 323 addRegisterClass(VT, &ARM::MQPRRegClass); 324 if (!HasMVEFP) 325 setAllExpand(VT); 326 327 // These are legal or custom whether we have MVE.fp or not 328 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 329 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 330 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom); 331 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 332 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 333 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom); 334 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal); 335 setOperationAction(ISD::SETCC, VT, Custom); 336 setOperationAction(ISD::MLOAD, VT, Custom); 337 setOperationAction(ISD::MSTORE, VT, Legal); 338 339 // Pre and Post inc are supported on loads and stores 340 for (unsigned im = (unsigned)ISD::PRE_INC; 341 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 342 setIndexedLoadAction(im, VT, Legal); 343 setIndexedStoreAction(im, VT, Legal); 344 setIndexedMaskedLoadAction(im, VT, Legal); 345 setIndexedMaskedStoreAction(im, VT, Legal); 346 } 347 348 if (HasMVEFP) { 349 setOperationAction(ISD::FMINNUM, VT, Legal); 350 setOperationAction(ISD::FMAXNUM, VT, Legal); 351 setOperationAction(ISD::FROUND, VT, Legal); 352 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 353 setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom); 354 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 355 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 356 357 // No native support for these. 358 setOperationAction(ISD::FDIV, VT, Expand); 359 setOperationAction(ISD::FREM, VT, Expand); 360 setOperationAction(ISD::FSQRT, VT, Expand); 361 setOperationAction(ISD::FSIN, VT, Expand); 362 setOperationAction(ISD::FCOS, VT, Expand); 363 setOperationAction(ISD::FPOW, VT, Expand); 364 setOperationAction(ISD::FLOG, VT, Expand); 365 setOperationAction(ISD::FLOG2, VT, Expand); 366 setOperationAction(ISD::FLOG10, VT, Expand); 367 setOperationAction(ISD::FEXP, VT, Expand); 368 setOperationAction(ISD::FEXP2, VT, Expand); 369 setOperationAction(ISD::FNEARBYINT, VT, Expand); 370 } 371 } 372 373 // Custom Expand smaller than legal vector reductions to prevent false zero 374 // items being added. 375 setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom); 376 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom); 377 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom); 378 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom); 379 setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom); 380 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom); 381 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom); 382 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom); 383 384 // We 'support' these types up to bitcast/load/store level, regardless of 385 // MVE integer-only / float support. Only doing FP data processing on the FP 386 // vector types is inhibited at integer-only level. 387 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 }; 388 for (auto VT : LongTypes) { 389 addRegisterClass(VT, &ARM::MQPRRegClass); 390 setAllExpand(VT); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 393 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 394 } 395 // We can do bitwise operations on v2i64 vectors 396 setOperationAction(ISD::AND, MVT::v2i64, Legal); 397 setOperationAction(ISD::OR, MVT::v2i64, Legal); 398 setOperationAction(ISD::XOR, MVT::v2i64, Legal); 399 400 // It is legal to extload from v4i8 to v4i16 or v4i32. 401 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal); 402 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal); 403 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal); 404 405 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16. 406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 407 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 408 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 409 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8, Legal); 410 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal); 411 412 // Some truncating stores are legal too. 413 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal); 414 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal); 415 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal); 416 417 // Pre and Post inc on these are legal, given the correct extends 418 for (unsigned im = (unsigned)ISD::PRE_INC; 419 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 420 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) { 421 setIndexedLoadAction(im, VT, Legal); 422 setIndexedStoreAction(im, VT, Legal); 423 setIndexedMaskedLoadAction(im, VT, Legal); 424 setIndexedMaskedStoreAction(im, VT, Legal); 425 } 426 } 427 428 // Predicate types 429 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1}; 430 for (auto VT : pTypes) { 431 addRegisterClass(VT, &ARM::VCCRRegClass); 432 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 433 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 434 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 435 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 436 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 437 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 438 setOperationAction(ISD::SETCC, VT, Custom); 439 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 440 setOperationAction(ISD::LOAD, VT, Custom); 441 setOperationAction(ISD::STORE, VT, Custom); 442 } 443 } 444 445 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 446 const ARMSubtarget &STI) 447 : TargetLowering(TM), Subtarget(&STI) { 448 RegInfo = Subtarget->getRegisterInfo(); 449 Itins = Subtarget->getInstrItineraryData(); 450 451 setBooleanContents(ZeroOrOneBooleanContent); 452 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 453 454 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 455 !Subtarget->isTargetWatchOS()) { 456 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 457 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 458 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 459 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 460 : CallingConv::ARM_AAPCS); 461 } 462 463 if (Subtarget->isTargetMachO()) { 464 // Uses VFP for Thumb libfuncs if available. 465 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 466 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 467 static const struct { 468 const RTLIB::Libcall Op; 469 const char * const Name; 470 const ISD::CondCode Cond; 471 } LibraryCalls[] = { 472 // Single-precision floating-point arithmetic. 473 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 474 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 475 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 476 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 477 478 // Double-precision floating-point arithmetic. 479 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 480 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 481 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 482 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 483 484 // Single-precision comparisons. 485 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 486 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 487 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 488 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 489 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 490 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 491 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 492 493 // Double-precision comparisons. 494 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 495 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 496 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 497 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 498 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 499 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 500 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 501 502 // Floating-point to integer conversions. 503 // i64 conversions are done via library routines even when generating VFP 504 // instructions, so use the same ones. 505 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 506 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 507 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 508 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 509 510 // Conversions between floating types. 511 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 512 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 513 514 // Integer to floating-point conversions. 515 // i64 conversions are done via library routines even when generating VFP 516 // instructions, so use the same ones. 517 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 518 // e.g., __floatunsidf vs. __floatunssidfvfp. 519 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 520 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 521 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 522 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 523 }; 524 525 for (const auto &LC : LibraryCalls) { 526 setLibcallName(LC.Op, LC.Name); 527 if (LC.Cond != ISD::SETCC_INVALID) 528 setCmpLibcallCC(LC.Op, LC.Cond); 529 } 530 } 531 } 532 533 // These libcalls are not available in 32-bit. 534 setLibcallName(RTLIB::SHL_I128, nullptr); 535 setLibcallName(RTLIB::SRL_I128, nullptr); 536 setLibcallName(RTLIB::SRA_I128, nullptr); 537 538 // RTLIB 539 if (Subtarget->isAAPCS_ABI() && 540 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 541 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 542 static const struct { 543 const RTLIB::Libcall Op; 544 const char * const Name; 545 const CallingConv::ID CC; 546 const ISD::CondCode Cond; 547 } LibraryCalls[] = { 548 // Double-precision floating-point arithmetic helper functions 549 // RTABI chapter 4.1.2, Table 2 550 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 551 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 552 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 553 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 554 555 // Double-precision floating-point comparison helper functions 556 // RTABI chapter 4.1.2, Table 3 557 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 558 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 559 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 560 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 561 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 562 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 563 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 564 565 // Single-precision floating-point arithmetic helper functions 566 // RTABI chapter 4.1.2, Table 4 567 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 568 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 569 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 570 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 571 572 // Single-precision floating-point comparison helper functions 573 // RTABI chapter 4.1.2, Table 5 574 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 575 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 576 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 577 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 578 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 579 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 580 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 581 582 // Floating-point to integer conversions. 583 // RTABI chapter 4.1.2, Table 6 584 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 585 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 586 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 587 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 588 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 589 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 590 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 591 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 592 593 // Conversions between floating types. 594 // RTABI chapter 4.1.2, Table 7 595 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 596 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 597 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 598 599 // Integer to floating-point conversions. 600 // RTABI chapter 4.1.2, Table 8 601 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 602 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 603 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 604 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 605 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 606 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 607 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 608 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 609 610 // Long long helper functions 611 // RTABI chapter 4.2, Table 9 612 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 613 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 614 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 615 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 616 617 // Integer division functions 618 // RTABI chapter 4.3.1 619 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 620 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 621 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 622 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 623 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 624 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 625 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 626 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 627 }; 628 629 for (const auto &LC : LibraryCalls) { 630 setLibcallName(LC.Op, LC.Name); 631 setLibcallCallingConv(LC.Op, LC.CC); 632 if (LC.Cond != ISD::SETCC_INVALID) 633 setCmpLibcallCC(LC.Op, LC.Cond); 634 } 635 636 // EABI dependent RTLIB 637 if (TM.Options.EABIVersion == EABI::EABI4 || 638 TM.Options.EABIVersion == EABI::EABI5) { 639 static const struct { 640 const RTLIB::Libcall Op; 641 const char *const Name; 642 const CallingConv::ID CC; 643 const ISD::CondCode Cond; 644 } MemOpsLibraryCalls[] = { 645 // Memory operations 646 // RTABI chapter 4.3.4 647 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 648 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 649 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 650 }; 651 652 for (const auto &LC : MemOpsLibraryCalls) { 653 setLibcallName(LC.Op, LC.Name); 654 setLibcallCallingConv(LC.Op, LC.CC); 655 if (LC.Cond != ISD::SETCC_INVALID) 656 setCmpLibcallCC(LC.Op, LC.Cond); 657 } 658 } 659 } 660 661 if (Subtarget->isTargetWindows()) { 662 static const struct { 663 const RTLIB::Libcall Op; 664 const char * const Name; 665 const CallingConv::ID CC; 666 } LibraryCalls[] = { 667 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 668 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 669 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 670 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 671 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 672 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 673 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 674 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 675 }; 676 677 for (const auto &LC : LibraryCalls) { 678 setLibcallName(LC.Op, LC.Name); 679 setLibcallCallingConv(LC.Op, LC.CC); 680 } 681 } 682 683 // Use divmod compiler-rt calls for iOS 5.0 and later. 684 if (Subtarget->isTargetMachO() && 685 !(Subtarget->isTargetIOS() && 686 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 687 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 688 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 689 } 690 691 // The half <-> float conversion functions are always soft-float on 692 // non-watchos platforms, but are needed for some targets which use a 693 // hard-float calling convention by default. 694 if (!Subtarget->isTargetWatchABI()) { 695 if (Subtarget->isAAPCS_ABI()) { 696 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 697 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 698 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 699 } else { 700 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 701 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 702 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 703 } 704 } 705 706 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 707 // a __gnu_ prefix (which is the default). 708 if (Subtarget->isTargetAEABI()) { 709 static const struct { 710 const RTLIB::Libcall Op; 711 const char * const Name; 712 const CallingConv::ID CC; 713 } LibraryCalls[] = { 714 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 715 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 716 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 717 }; 718 719 for (const auto &LC : LibraryCalls) { 720 setLibcallName(LC.Op, LC.Name); 721 setLibcallCallingConv(LC.Op, LC.CC); 722 } 723 } 724 725 if (Subtarget->isThumb1Only()) 726 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 727 else 728 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 729 730 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() && 731 Subtarget->hasFPRegs()) { 732 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 733 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 734 if (!Subtarget->hasVFP2Base()) 735 setAllExpand(MVT::f32); 736 if (!Subtarget->hasFP64()) 737 setAllExpand(MVT::f64); 738 } 739 740 if (Subtarget->hasFullFP16()) { 741 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 742 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 743 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 744 745 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 746 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 747 } 748 749 if (Subtarget->hasBF16()) { 750 addRegisterClass(MVT::bf16, &ARM::HPRRegClass); 751 setAllExpand(MVT::bf16); 752 if (!Subtarget->hasFullFP16()) 753 setOperationAction(ISD::BITCAST, MVT::bf16, Custom); 754 } 755 756 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 757 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 758 setTruncStoreAction(VT, InnerVT, Expand); 759 addAllExtLoads(VT, InnerVT, Expand); 760 } 761 762 setOperationAction(ISD::MULHS, VT, Expand); 763 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 764 setOperationAction(ISD::MULHU, VT, Expand); 765 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 766 767 setOperationAction(ISD::BSWAP, VT, Expand); 768 } 769 770 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 771 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 772 773 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 774 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 775 776 if (Subtarget->hasMVEIntegerOps()) 777 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 778 779 // Combine low-overhead loop intrinsics so that we can lower i1 types. 780 if (Subtarget->hasLOB()) { 781 setTargetDAGCombine(ISD::BRCOND); 782 setTargetDAGCombine(ISD::BR_CC); 783 } 784 785 if (Subtarget->hasNEON()) { 786 addDRTypeForNEON(MVT::v2f32); 787 addDRTypeForNEON(MVT::v8i8); 788 addDRTypeForNEON(MVT::v4i16); 789 addDRTypeForNEON(MVT::v2i32); 790 addDRTypeForNEON(MVT::v1i64); 791 792 addQRTypeForNEON(MVT::v4f32); 793 addQRTypeForNEON(MVT::v2f64); 794 addQRTypeForNEON(MVT::v16i8); 795 addQRTypeForNEON(MVT::v8i16); 796 addQRTypeForNEON(MVT::v4i32); 797 addQRTypeForNEON(MVT::v2i64); 798 799 if (Subtarget->hasFullFP16()) { 800 addQRTypeForNEON(MVT::v8f16); 801 addDRTypeForNEON(MVT::v4f16); 802 } 803 804 if (Subtarget->hasBF16()) { 805 addQRTypeForNEON(MVT::v8bf16); 806 addDRTypeForNEON(MVT::v4bf16); 807 } 808 } 809 810 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 811 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 812 // none of Neon, MVE or VFP supports any arithmetic operations on it. 813 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 814 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 815 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 816 // FIXME: Code duplication: FDIV and FREM are expanded always, see 817 // ARMTargetLowering::addTypeForNEON method for details. 818 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 819 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 820 // FIXME: Create unittest. 821 // In another words, find a way when "copysign" appears in DAG with vector 822 // operands. 823 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 824 // FIXME: Code duplication: SETCC has custom operation action, see 825 // ARMTargetLowering::addTypeForNEON method for details. 826 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 827 // FIXME: Create unittest for FNEG and for FABS. 828 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 829 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 830 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 831 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 832 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 833 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 834 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 835 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 836 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 837 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 838 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 839 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 840 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 841 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 842 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 843 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 844 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 845 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 846 } 847 848 if (Subtarget->hasNEON()) { 849 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 850 // supported for v4f32. 851 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 852 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 853 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 854 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 855 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 856 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 857 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 858 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 859 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 860 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 861 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 862 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 863 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 864 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 865 866 // Mark v2f32 intrinsics. 867 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 868 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 869 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 870 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 871 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 872 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 873 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 874 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 875 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 876 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 877 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 878 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 879 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 880 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 881 882 // Neon does not support some operations on v1i64 and v2i64 types. 883 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 884 // Custom handling for some quad-vector types to detect VMULL. 885 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 886 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 887 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 888 // Custom handling for some vector types to avoid expensive expansions 889 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 890 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 891 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 892 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 893 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 894 // a destination type that is wider than the source, and nor does 895 // it have a FP_TO_[SU]INT instruction with a narrower destination than 896 // source. 897 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 898 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 899 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 900 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 901 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 902 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 903 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 904 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 905 906 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 907 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 908 909 // NEON does not have single instruction CTPOP for vectors with element 910 // types wider than 8-bits. However, custom lowering can leverage the 911 // v8i8/v16i8 vcnt instruction. 912 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 913 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 914 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 915 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 916 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 917 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 918 919 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 920 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 921 922 // NEON does not have single instruction CTTZ for vectors. 923 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 924 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 925 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 926 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 927 928 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 929 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 930 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 931 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 932 933 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 934 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 935 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 936 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 937 938 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 939 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 940 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 941 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 942 943 // NEON only has FMA instructions as of VFP4. 944 if (!Subtarget->hasVFP4Base()) { 945 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 946 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 947 } 948 949 setTargetDAGCombine(ISD::SHL); 950 setTargetDAGCombine(ISD::SRL); 951 setTargetDAGCombine(ISD::SRA); 952 setTargetDAGCombine(ISD::FP_TO_SINT); 953 setTargetDAGCombine(ISD::FP_TO_UINT); 954 setTargetDAGCombine(ISD::FDIV); 955 setTargetDAGCombine(ISD::LOAD); 956 957 // It is legal to extload from v4i8 to v4i16 or v4i32. 958 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 959 MVT::v2i32}) { 960 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 961 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 962 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 963 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 964 } 965 } 966 } 967 968 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 969 setTargetDAGCombine(ISD::BUILD_VECTOR); 970 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 971 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 972 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 973 setTargetDAGCombine(ISD::STORE); 974 setTargetDAGCombine(ISD::SIGN_EXTEND); 975 setTargetDAGCombine(ISD::ZERO_EXTEND); 976 setTargetDAGCombine(ISD::ANY_EXTEND); 977 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 978 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 979 setTargetDAGCombine(ISD::INTRINSIC_VOID); 980 setTargetDAGCombine(ISD::VECREDUCE_ADD); 981 setTargetDAGCombine(ISD::ADD); 982 setTargetDAGCombine(ISD::BITCAST); 983 } 984 if (Subtarget->hasMVEIntegerOps()) { 985 setTargetDAGCombine(ISD::SMIN); 986 setTargetDAGCombine(ISD::UMIN); 987 setTargetDAGCombine(ISD::SMAX); 988 setTargetDAGCombine(ISD::UMAX); 989 setTargetDAGCombine(ISD::FP_EXTEND); 990 setTargetDAGCombine(ISD::SELECT); 991 setTargetDAGCombine(ISD::SELECT_CC); 992 } 993 994 if (!Subtarget->hasFP64()) { 995 // When targeting a floating-point unit with only single-precision 996 // operations, f64 is legal for the few double-precision instructions which 997 // are present However, no double-precision operations other than moves, 998 // loads and stores are provided by the hardware. 999 setOperationAction(ISD::FADD, MVT::f64, Expand); 1000 setOperationAction(ISD::FSUB, MVT::f64, Expand); 1001 setOperationAction(ISD::FMUL, MVT::f64, Expand); 1002 setOperationAction(ISD::FMA, MVT::f64, Expand); 1003 setOperationAction(ISD::FDIV, MVT::f64, Expand); 1004 setOperationAction(ISD::FREM, MVT::f64, Expand); 1005 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 1006 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 1007 setOperationAction(ISD::FNEG, MVT::f64, Expand); 1008 setOperationAction(ISD::FABS, MVT::f64, Expand); 1009 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 1010 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1011 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1012 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1013 setOperationAction(ISD::FLOG, MVT::f64, Expand); 1014 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 1015 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 1016 setOperationAction(ISD::FEXP, MVT::f64, Expand); 1017 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 1018 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 1019 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 1020 setOperationAction(ISD::FRINT, MVT::f64, Expand); 1021 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 1022 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 1023 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 1024 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 1025 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 1026 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 1027 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 1028 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 1029 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 1030 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 1031 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 1032 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom); 1033 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom); 1034 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 1035 } 1036 1037 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) { 1038 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 1039 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom); 1040 if (Subtarget->hasFullFP16()) { 1041 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 1042 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom); 1043 } 1044 } 1045 1046 if (!Subtarget->hasFP16()) { 1047 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 1048 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom); 1049 } 1050 1051 computeRegisterProperties(Subtarget->getRegisterInfo()); 1052 1053 // ARM does not have floating-point extending loads. 1054 for (MVT VT : MVT::fp_valuetypes()) { 1055 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 1056 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 1057 } 1058 1059 // ... or truncating stores 1060 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 1061 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 1062 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 1063 1064 // ARM does not have i1 sign extending load. 1065 for (MVT VT : MVT::integer_valuetypes()) 1066 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 1067 1068 // ARM supports all 4 flavors of integer indexed load / store. 1069 if (!Subtarget->isThumb1Only()) { 1070 for (unsigned im = (unsigned)ISD::PRE_INC; 1071 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 1072 setIndexedLoadAction(im, MVT::i1, Legal); 1073 setIndexedLoadAction(im, MVT::i8, Legal); 1074 setIndexedLoadAction(im, MVT::i16, Legal); 1075 setIndexedLoadAction(im, MVT::i32, Legal); 1076 setIndexedStoreAction(im, MVT::i1, Legal); 1077 setIndexedStoreAction(im, MVT::i8, Legal); 1078 setIndexedStoreAction(im, MVT::i16, Legal); 1079 setIndexedStoreAction(im, MVT::i32, Legal); 1080 } 1081 } else { 1082 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 1083 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 1084 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 1085 } 1086 1087 setOperationAction(ISD::SADDO, MVT::i32, Custom); 1088 setOperationAction(ISD::UADDO, MVT::i32, Custom); 1089 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 1090 setOperationAction(ISD::USUBO, MVT::i32, Custom); 1091 1092 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 1093 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 1094 if (Subtarget->hasDSP()) { 1095 setOperationAction(ISD::SADDSAT, MVT::i8, Custom); 1096 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom); 1097 setOperationAction(ISD::SADDSAT, MVT::i16, Custom); 1098 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom); 1099 } 1100 if (Subtarget->hasBaseDSP()) { 1101 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 1102 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 1103 } 1104 1105 // i64 operation support. 1106 setOperationAction(ISD::MUL, MVT::i64, Expand); 1107 setOperationAction(ISD::MULHU, MVT::i32, Expand); 1108 if (Subtarget->isThumb1Only()) { 1109 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 1110 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 1111 } 1112 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 1113 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 1114 setOperationAction(ISD::MULHS, MVT::i32, Expand); 1115 1116 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 1117 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 1118 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 1119 setOperationAction(ISD::SRL, MVT::i64, Custom); 1120 setOperationAction(ISD::SRA, MVT::i64, Custom); 1121 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 1122 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 1123 setOperationAction(ISD::LOAD, MVT::i64, Custom); 1124 setOperationAction(ISD::STORE, MVT::i64, Custom); 1125 1126 // MVE lowers 64 bit shifts to lsll and lsrl 1127 // assuming that ISD::SRL and SRA of i64 are already marked custom 1128 if (Subtarget->hasMVEIntegerOps()) 1129 setOperationAction(ISD::SHL, MVT::i64, Custom); 1130 1131 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 1132 if (Subtarget->isThumb1Only()) { 1133 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 1134 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 1135 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 1136 } 1137 1138 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 1139 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 1140 1141 // ARM does not have ROTL. 1142 setOperationAction(ISD::ROTL, MVT::i32, Expand); 1143 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 1144 setOperationAction(ISD::ROTL, VT, Expand); 1145 setOperationAction(ISD::ROTR, VT, Expand); 1146 } 1147 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1148 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1149 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1150 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1151 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1152 } 1153 1154 // @llvm.readcyclecounter requires the Performance Monitors extension. 1155 // Default to the 0 expansion on unsupported platforms. 1156 // FIXME: Technically there are older ARM CPUs that have 1157 // implementation-specific ways of obtaining this information. 1158 if (Subtarget->hasPerfMon()) 1159 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1160 1161 // Only ARMv6 has BSWAP. 1162 if (!Subtarget->hasV6Ops()) 1163 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1164 1165 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1166 : Subtarget->hasDivideInARMMode(); 1167 if (!hasDivide) { 1168 // These are expanded into libcalls if the cpu doesn't have HW divider. 1169 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1170 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1171 } 1172 1173 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1174 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1175 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1176 1177 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1178 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1179 } 1180 1181 setOperationAction(ISD::SREM, MVT::i32, Expand); 1182 setOperationAction(ISD::UREM, MVT::i32, Expand); 1183 1184 // Register based DivRem for AEABI (RTABI 4.2) 1185 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1186 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1187 Subtarget->isTargetWindows()) { 1188 setOperationAction(ISD::SREM, MVT::i64, Custom); 1189 setOperationAction(ISD::UREM, MVT::i64, Custom); 1190 HasStandaloneRem = false; 1191 1192 if (Subtarget->isTargetWindows()) { 1193 const struct { 1194 const RTLIB::Libcall Op; 1195 const char * const Name; 1196 const CallingConv::ID CC; 1197 } LibraryCalls[] = { 1198 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1199 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1200 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1201 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1202 1203 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1204 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1205 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1206 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1207 }; 1208 1209 for (const auto &LC : LibraryCalls) { 1210 setLibcallName(LC.Op, LC.Name); 1211 setLibcallCallingConv(LC.Op, LC.CC); 1212 } 1213 } else { 1214 const struct { 1215 const RTLIB::Libcall Op; 1216 const char * const Name; 1217 const CallingConv::ID CC; 1218 } LibraryCalls[] = { 1219 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1220 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1221 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1222 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1223 1224 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1225 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1226 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1227 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1228 }; 1229 1230 for (const auto &LC : LibraryCalls) { 1231 setLibcallName(LC.Op, LC.Name); 1232 setLibcallCallingConv(LC.Op, LC.CC); 1233 } 1234 } 1235 1236 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1237 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1238 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1239 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1240 } else { 1241 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1242 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1243 } 1244 1245 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 1246 // MSVCRT doesn't have powi; fall back to pow 1247 setLibcallName(RTLIB::POWI_F32, nullptr); 1248 setLibcallName(RTLIB::POWI_F64, nullptr); 1249 } 1250 1251 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1252 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1253 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1254 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1255 1256 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1257 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1258 1259 // Use the default implementation. 1260 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1261 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1262 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1263 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1264 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1265 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1266 1267 if (Subtarget->isTargetWindows()) 1268 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1269 else 1270 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1271 1272 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1273 // the default expansion. 1274 InsertFencesForAtomic = false; 1275 if (Subtarget->hasAnyDataBarrier() && 1276 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1277 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1278 // to ldrex/strex loops already. 1279 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1280 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1281 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1282 1283 // On v8, we have particularly efficient implementations of atomic fences 1284 // if they can be combined with nearby atomic loads and stores. 1285 if (!Subtarget->hasAcquireRelease() || 1286 getTargetMachine().getOptLevel() == 0) { 1287 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1288 InsertFencesForAtomic = true; 1289 } 1290 } else { 1291 // If there's anything we can use as a barrier, go through custom lowering 1292 // for ATOMIC_FENCE. 1293 // If target has DMB in thumb, Fences can be inserted. 1294 if (Subtarget->hasDataBarrier()) 1295 InsertFencesForAtomic = true; 1296 1297 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1298 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1299 1300 // Set them all for expansion, which will force libcalls. 1301 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1302 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1303 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1304 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1305 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1306 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1307 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1308 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1309 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1310 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1311 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1312 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1313 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1314 // Unordered/Monotonic case. 1315 if (!InsertFencesForAtomic) { 1316 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1317 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1318 } 1319 } 1320 1321 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1322 1323 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1324 if (!Subtarget->hasV6Ops()) { 1325 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1326 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1327 } 1328 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1329 1330 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1331 !Subtarget->isThumb1Only()) { 1332 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1333 // iff target supports vfp2. 1334 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1335 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1336 } 1337 1338 // We want to custom lower some of our intrinsics. 1339 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1340 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1341 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1342 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1343 if (Subtarget->useSjLjEH()) 1344 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1345 1346 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1347 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1348 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1349 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1350 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1351 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1352 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1353 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1354 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1355 if (Subtarget->hasFullFP16()) { 1356 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1357 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1358 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1359 } 1360 1361 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1362 1363 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1364 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1365 if (Subtarget->hasFullFP16()) 1366 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1367 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1368 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1369 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1370 1371 // We don't support sin/cos/fmod/copysign/pow 1372 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1373 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1374 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1375 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1376 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1377 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1378 setOperationAction(ISD::FREM, MVT::f64, Expand); 1379 setOperationAction(ISD::FREM, MVT::f32, Expand); 1380 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1381 !Subtarget->isThumb1Only()) { 1382 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1383 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1384 } 1385 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1386 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1387 1388 if (!Subtarget->hasVFP4Base()) { 1389 setOperationAction(ISD::FMA, MVT::f64, Expand); 1390 setOperationAction(ISD::FMA, MVT::f32, Expand); 1391 } 1392 1393 // Various VFP goodness 1394 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1395 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1396 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1397 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1398 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1399 } 1400 1401 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1402 if (!Subtarget->hasFP16()) { 1403 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1404 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1405 } 1406 1407 // Strict floating-point comparisons need custom lowering. 1408 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 1409 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 1410 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 1411 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 1412 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 1413 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 1414 } 1415 1416 // Use __sincos_stret if available. 1417 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1418 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1419 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1420 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1421 } 1422 1423 // FP-ARMv8 implements a lot of rounding-like FP operations. 1424 if (Subtarget->hasFPARMv8Base()) { 1425 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1426 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1427 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1428 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1429 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1430 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1431 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1432 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1433 if (Subtarget->hasNEON()) { 1434 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1435 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1436 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1437 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1438 } 1439 1440 if (Subtarget->hasFP64()) { 1441 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1442 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1443 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1444 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1445 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1446 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1447 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1448 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1449 } 1450 } 1451 1452 // FP16 often need to be promoted to call lib functions 1453 if (Subtarget->hasFullFP16()) { 1454 setOperationAction(ISD::FREM, MVT::f16, Promote); 1455 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1456 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1457 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1458 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1459 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1460 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1461 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1462 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1463 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1464 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1465 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1466 1467 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1468 } 1469 1470 if (Subtarget->hasNEON()) { 1471 // vmin and vmax aren't available in a scalar form, so we can use 1472 // a NEON instruction with an undef lane instead. This has a performance 1473 // penalty on some cores, so we don't do this unless we have been 1474 // asked to by the core tuning model. 1475 if (Subtarget->useNEONForSinglePrecisionFP()) { 1476 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1477 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1478 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1479 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1480 } 1481 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1482 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1483 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1484 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1485 1486 if (Subtarget->hasFullFP16()) { 1487 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1488 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1489 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1490 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1491 1492 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1493 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1494 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1495 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1496 } 1497 } 1498 1499 // We have target-specific dag combine patterns for the following nodes: 1500 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1501 setTargetDAGCombine(ISD::ADD); 1502 setTargetDAGCombine(ISD::SUB); 1503 setTargetDAGCombine(ISD::MUL); 1504 setTargetDAGCombine(ISD::AND); 1505 setTargetDAGCombine(ISD::OR); 1506 setTargetDAGCombine(ISD::XOR); 1507 1508 if (Subtarget->hasMVEIntegerOps()) 1509 setTargetDAGCombine(ISD::VSELECT); 1510 1511 if (Subtarget->hasV6Ops()) 1512 setTargetDAGCombine(ISD::SRL); 1513 if (Subtarget->isThumb1Only()) 1514 setTargetDAGCombine(ISD::SHL); 1515 1516 setStackPointerRegisterToSaveRestore(ARM::SP); 1517 1518 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1519 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1520 setSchedulingPreference(Sched::RegPressure); 1521 else 1522 setSchedulingPreference(Sched::Hybrid); 1523 1524 //// temporary - rewrite interface to use type 1525 MaxStoresPerMemset = 8; 1526 MaxStoresPerMemsetOptSize = 4; 1527 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1528 MaxStoresPerMemcpyOptSize = 2; 1529 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1530 MaxStoresPerMemmoveOptSize = 2; 1531 1532 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1533 // are at least 4 bytes aligned. 1534 setMinStackArgumentAlignment(Align(4)); 1535 1536 // Prefer likely predicted branches to selects on out-of-order cores. 1537 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1538 1539 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment())); 1540 1541 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4)); 1542 1543 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1544 setTargetDAGCombine(ISD::ABS); 1545 } 1546 1547 bool ARMTargetLowering::useSoftFloat() const { 1548 return Subtarget->useSoftFloat(); 1549 } 1550 1551 // FIXME: It might make sense to define the representative register class as the 1552 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1553 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1554 // SPR's representative would be DPR_VFP2. This should work well if register 1555 // pressure tracking were modified such that a register use would increment the 1556 // pressure of the register class's representative and all of it's super 1557 // classes' representatives transitively. We have not implemented this because 1558 // of the difficulty prior to coalescing of modeling operand register classes 1559 // due to the common occurrence of cross class copies and subregister insertions 1560 // and extractions. 1561 std::pair<const TargetRegisterClass *, uint8_t> 1562 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1563 MVT VT) const { 1564 const TargetRegisterClass *RRC = nullptr; 1565 uint8_t Cost = 1; 1566 switch (VT.SimpleTy) { 1567 default: 1568 return TargetLowering::findRepresentativeClass(TRI, VT); 1569 // Use DPR as representative register class for all floating point 1570 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1571 // the cost is 1 for both f32 and f64. 1572 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1573 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1574 RRC = &ARM::DPRRegClass; 1575 // When NEON is used for SP, only half of the register file is available 1576 // because operations that define both SP and DP results will be constrained 1577 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1578 // coalescing by double-counting the SP regs. See the FIXME above. 1579 if (Subtarget->useNEONForSinglePrecisionFP()) 1580 Cost = 2; 1581 break; 1582 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1583 case MVT::v4f32: case MVT::v2f64: 1584 RRC = &ARM::DPRRegClass; 1585 Cost = 2; 1586 break; 1587 case MVT::v4i64: 1588 RRC = &ARM::DPRRegClass; 1589 Cost = 4; 1590 break; 1591 case MVT::v8i64: 1592 RRC = &ARM::DPRRegClass; 1593 Cost = 8; 1594 break; 1595 } 1596 return std::make_pair(RRC, Cost); 1597 } 1598 1599 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1600 switch ((ARMISD::NodeType)Opcode) { 1601 case ARMISD::FIRST_NUMBER: break; 1602 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1603 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1604 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1605 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1606 case ARMISD::CALL: return "ARMISD::CALL"; 1607 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1608 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1609 case ARMISD::tSECALL: return "ARMISD::tSECALL"; 1610 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1611 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1612 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1613 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1614 case ARMISD::SERET_FLAG: return "ARMISD::SERET_FLAG"; 1615 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1616 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1617 case ARMISD::CMP: return "ARMISD::CMP"; 1618 case ARMISD::CMN: return "ARMISD::CMN"; 1619 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1620 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1621 case ARMISD::CMPFPE: return "ARMISD::CMPFPE"; 1622 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1623 case ARMISD::CMPFPEw0: return "ARMISD::CMPFPEw0"; 1624 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1625 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1626 1627 case ARMISD::CMOV: return "ARMISD::CMOV"; 1628 case ARMISD::SUBS: return "ARMISD::SUBS"; 1629 1630 case ARMISD::SSAT: return "ARMISD::SSAT"; 1631 case ARMISD::USAT: return "ARMISD::USAT"; 1632 1633 case ARMISD::ASRL: return "ARMISD::ASRL"; 1634 case ARMISD::LSRL: return "ARMISD::LSRL"; 1635 case ARMISD::LSLL: return "ARMISD::LSLL"; 1636 1637 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1638 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1639 case ARMISD::RRX: return "ARMISD::RRX"; 1640 1641 case ARMISD::ADDC: return "ARMISD::ADDC"; 1642 case ARMISD::ADDE: return "ARMISD::ADDE"; 1643 case ARMISD::SUBC: return "ARMISD::SUBC"; 1644 case ARMISD::SUBE: return "ARMISD::SUBE"; 1645 case ARMISD::LSLS: return "ARMISD::LSLS"; 1646 1647 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1648 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1649 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1650 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1651 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1652 1653 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1654 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1655 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1656 1657 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1658 1659 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1660 1661 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1662 1663 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1664 1665 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1666 1667 case ARMISD::LDRD: return "ARMISD::LDRD"; 1668 case ARMISD::STRD: return "ARMISD::STRD"; 1669 1670 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1671 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1672 1673 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST"; 1674 case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST"; 1675 case ARMISD::VCMP: return "ARMISD::VCMP"; 1676 case ARMISD::VCMPZ: return "ARMISD::VCMPZ"; 1677 case ARMISD::VTST: return "ARMISD::VTST"; 1678 1679 case ARMISD::VSHLs: return "ARMISD::VSHLs"; 1680 case ARMISD::VSHLu: return "ARMISD::VSHLu"; 1681 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM"; 1682 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM"; 1683 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM"; 1684 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM"; 1685 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM"; 1686 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM"; 1687 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM"; 1688 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM"; 1689 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM"; 1690 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM"; 1691 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM"; 1692 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM"; 1693 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM"; 1694 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM"; 1695 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM"; 1696 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM"; 1697 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM"; 1698 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1699 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1700 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1701 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1702 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1703 case ARMISD::VDUP: return "ARMISD::VDUP"; 1704 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1705 case ARMISD::VEXT: return "ARMISD::VEXT"; 1706 case ARMISD::VREV64: return "ARMISD::VREV64"; 1707 case ARMISD::VREV32: return "ARMISD::VREV32"; 1708 case ARMISD::VREV16: return "ARMISD::VREV16"; 1709 case ARMISD::VZIP: return "ARMISD::VZIP"; 1710 case ARMISD::VUZP: return "ARMISD::VUZP"; 1711 case ARMISD::VTRN: return "ARMISD::VTRN"; 1712 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1713 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1714 case ARMISD::VMOVN: return "ARMISD::VMOVN"; 1715 case ARMISD::VQMOVNs: return "ARMISD::VQMOVNs"; 1716 case ARMISD::VQMOVNu: return "ARMISD::VQMOVNu"; 1717 case ARMISD::VCVTN: return "ARMISD::VCVTN"; 1718 case ARMISD::VCVTL: return "ARMISD::VCVTL"; 1719 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1720 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1721 case ARMISD::VQDMULH: return "ARMISD::VQDMULH"; 1722 case ARMISD::VADDVs: return "ARMISD::VADDVs"; 1723 case ARMISD::VADDVu: return "ARMISD::VADDVu"; 1724 case ARMISD::VADDVps: return "ARMISD::VADDVps"; 1725 case ARMISD::VADDVpu: return "ARMISD::VADDVpu"; 1726 case ARMISD::VADDLVs: return "ARMISD::VADDLVs"; 1727 case ARMISD::VADDLVu: return "ARMISD::VADDLVu"; 1728 case ARMISD::VADDLVAs: return "ARMISD::VADDLVAs"; 1729 case ARMISD::VADDLVAu: return "ARMISD::VADDLVAu"; 1730 case ARMISD::VADDLVps: return "ARMISD::VADDLVps"; 1731 case ARMISD::VADDLVpu: return "ARMISD::VADDLVpu"; 1732 case ARMISD::VADDLVAps: return "ARMISD::VADDLVAps"; 1733 case ARMISD::VADDLVApu: return "ARMISD::VADDLVApu"; 1734 case ARMISD::VMLAVs: return "ARMISD::VMLAVs"; 1735 case ARMISD::VMLAVu: return "ARMISD::VMLAVu"; 1736 case ARMISD::VMLAVps: return "ARMISD::VMLAVps"; 1737 case ARMISD::VMLAVpu: return "ARMISD::VMLAVpu"; 1738 case ARMISD::VMLALVs: return "ARMISD::VMLALVs"; 1739 case ARMISD::VMLALVu: return "ARMISD::VMLALVu"; 1740 case ARMISD::VMLALVps: return "ARMISD::VMLALVps"; 1741 case ARMISD::VMLALVpu: return "ARMISD::VMLALVpu"; 1742 case ARMISD::VMLALVAs: return "ARMISD::VMLALVAs"; 1743 case ARMISD::VMLALVAu: return "ARMISD::VMLALVAu"; 1744 case ARMISD::VMLALVAps: return "ARMISD::VMLALVAps"; 1745 case ARMISD::VMLALVApu: return "ARMISD::VMLALVApu"; 1746 case ARMISD::VMINVu: return "ARMISD::VMINVu"; 1747 case ARMISD::VMINVs: return "ARMISD::VMINVs"; 1748 case ARMISD::VMAXVu: return "ARMISD::VMAXVu"; 1749 case ARMISD::VMAXVs: return "ARMISD::VMAXVs"; 1750 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1751 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1752 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1753 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1754 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1755 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1756 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1757 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1758 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1759 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1760 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1761 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1762 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1763 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1764 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1765 case ARMISD::QADD16b: return "ARMISD::QADD16b"; 1766 case ARMISD::QSUB16b: return "ARMISD::QSUB16b"; 1767 case ARMISD::QADD8b: return "ARMISD::QADD8b"; 1768 case ARMISD::QSUB8b: return "ARMISD::QSUB8b"; 1769 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1770 case ARMISD::BFI: return "ARMISD::BFI"; 1771 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1772 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1773 case ARMISD::VBSP: return "ARMISD::VBSP"; 1774 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1775 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1776 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1777 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1778 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1779 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1780 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1781 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1782 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1783 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1784 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1785 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1786 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1787 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1788 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1789 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1790 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1791 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1792 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1793 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1794 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1795 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1796 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1797 case ARMISD::WLS: return "ARMISD::WLS"; 1798 case ARMISD::LE: return "ARMISD::LE"; 1799 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1800 case ARMISD::CSINV: return "ARMISD::CSINV"; 1801 case ARMISD::CSNEG: return "ARMISD::CSNEG"; 1802 case ARMISD::CSINC: return "ARMISD::CSINC"; 1803 } 1804 return nullptr; 1805 } 1806 1807 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1808 EVT VT) const { 1809 if (!VT.isVector()) 1810 return getPointerTy(DL); 1811 1812 // MVE has a predicate register. 1813 if (Subtarget->hasMVEIntegerOps() && 1814 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1815 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1816 return VT.changeVectorElementTypeToInteger(); 1817 } 1818 1819 /// getRegClassFor - Return the register class that should be used for the 1820 /// specified value type. 1821 const TargetRegisterClass * 1822 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1823 (void)isDivergent; 1824 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1825 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1826 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1827 // MVE Q registers. 1828 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1829 if (VT == MVT::v4i64) 1830 return &ARM::QQPRRegClass; 1831 if (VT == MVT::v8i64) 1832 return &ARM::QQQQPRRegClass; 1833 } 1834 return TargetLowering::getRegClassFor(VT); 1835 } 1836 1837 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1838 // source/dest is aligned and the copy size is large enough. We therefore want 1839 // to align such objects passed to memory intrinsics. 1840 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1841 unsigned &PrefAlign) const { 1842 if (!isa<MemIntrinsic>(CI)) 1843 return false; 1844 MinSize = 8; 1845 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1846 // cycle faster than 4-byte aligned LDM. 1847 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1848 return true; 1849 } 1850 1851 // Create a fast isel object. 1852 FastISel * 1853 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1854 const TargetLibraryInfo *libInfo) const { 1855 return ARM::createFastISel(funcInfo, libInfo); 1856 } 1857 1858 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1859 unsigned NumVals = N->getNumValues(); 1860 if (!NumVals) 1861 return Sched::RegPressure; 1862 1863 for (unsigned i = 0; i != NumVals; ++i) { 1864 EVT VT = N->getValueType(i); 1865 if (VT == MVT::Glue || VT == MVT::Other) 1866 continue; 1867 if (VT.isFloatingPoint() || VT.isVector()) 1868 return Sched::ILP; 1869 } 1870 1871 if (!N->isMachineOpcode()) 1872 return Sched::RegPressure; 1873 1874 // Load are scheduled for latency even if there instruction itinerary 1875 // is not available. 1876 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1877 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1878 1879 if (MCID.getNumDefs() == 0) 1880 return Sched::RegPressure; 1881 if (!Itins->isEmpty() && 1882 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1883 return Sched::ILP; 1884 1885 return Sched::RegPressure; 1886 } 1887 1888 //===----------------------------------------------------------------------===// 1889 // Lowering Code 1890 //===----------------------------------------------------------------------===// 1891 1892 static bool isSRL16(const SDValue &Op) { 1893 if (Op.getOpcode() != ISD::SRL) 1894 return false; 1895 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1896 return Const->getZExtValue() == 16; 1897 return false; 1898 } 1899 1900 static bool isSRA16(const SDValue &Op) { 1901 if (Op.getOpcode() != ISD::SRA) 1902 return false; 1903 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1904 return Const->getZExtValue() == 16; 1905 return false; 1906 } 1907 1908 static bool isSHL16(const SDValue &Op) { 1909 if (Op.getOpcode() != ISD::SHL) 1910 return false; 1911 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1912 return Const->getZExtValue() == 16; 1913 return false; 1914 } 1915 1916 // Check for a signed 16-bit value. We special case SRA because it makes it 1917 // more simple when also looking for SRAs that aren't sign extending a 1918 // smaller value. Without the check, we'd need to take extra care with 1919 // checking order for some operations. 1920 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1921 if (isSRA16(Op)) 1922 return isSHL16(Op.getOperand(0)); 1923 return DAG.ComputeNumSignBits(Op) == 17; 1924 } 1925 1926 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1927 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1928 switch (CC) { 1929 default: llvm_unreachable("Unknown condition code!"); 1930 case ISD::SETNE: return ARMCC::NE; 1931 case ISD::SETEQ: return ARMCC::EQ; 1932 case ISD::SETGT: return ARMCC::GT; 1933 case ISD::SETGE: return ARMCC::GE; 1934 case ISD::SETLT: return ARMCC::LT; 1935 case ISD::SETLE: return ARMCC::LE; 1936 case ISD::SETUGT: return ARMCC::HI; 1937 case ISD::SETUGE: return ARMCC::HS; 1938 case ISD::SETULT: return ARMCC::LO; 1939 case ISD::SETULE: return ARMCC::LS; 1940 } 1941 } 1942 1943 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1944 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1945 ARMCC::CondCodes &CondCode2) { 1946 CondCode2 = ARMCC::AL; 1947 switch (CC) { 1948 default: llvm_unreachable("Unknown FP condition!"); 1949 case ISD::SETEQ: 1950 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1951 case ISD::SETGT: 1952 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1953 case ISD::SETGE: 1954 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1955 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1956 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1957 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1958 case ISD::SETO: CondCode = ARMCC::VC; break; 1959 case ISD::SETUO: CondCode = ARMCC::VS; break; 1960 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1961 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1962 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1963 case ISD::SETLT: 1964 case ISD::SETULT: CondCode = ARMCC::LT; break; 1965 case ISD::SETLE: 1966 case ISD::SETULE: CondCode = ARMCC::LE; break; 1967 case ISD::SETNE: 1968 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1969 } 1970 } 1971 1972 //===----------------------------------------------------------------------===// 1973 // Calling Convention Implementation 1974 //===----------------------------------------------------------------------===// 1975 1976 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1977 /// account presence of floating point hardware and calling convention 1978 /// limitations, such as support for variadic functions. 1979 CallingConv::ID 1980 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1981 bool isVarArg) const { 1982 switch (CC) { 1983 default: 1984 report_fatal_error("Unsupported calling convention"); 1985 case CallingConv::ARM_AAPCS: 1986 case CallingConv::ARM_APCS: 1987 case CallingConv::GHC: 1988 case CallingConv::CFGuard_Check: 1989 return CC; 1990 case CallingConv::PreserveMost: 1991 return CallingConv::PreserveMost; 1992 case CallingConv::ARM_AAPCS_VFP: 1993 case CallingConv::Swift: 1994 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1995 case CallingConv::C: 1996 if (!Subtarget->isAAPCS_ABI()) 1997 return CallingConv::ARM_APCS; 1998 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1999 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 2000 !isVarArg) 2001 return CallingConv::ARM_AAPCS_VFP; 2002 else 2003 return CallingConv::ARM_AAPCS; 2004 case CallingConv::Fast: 2005 case CallingConv::CXX_FAST_TLS: 2006 if (!Subtarget->isAAPCS_ABI()) { 2007 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 2008 return CallingConv::Fast; 2009 return CallingConv::ARM_APCS; 2010 } else if (Subtarget->hasVFP2Base() && 2011 !Subtarget->isThumb1Only() && !isVarArg) 2012 return CallingConv::ARM_AAPCS_VFP; 2013 else 2014 return CallingConv::ARM_AAPCS; 2015 } 2016 } 2017 2018 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2019 bool isVarArg) const { 2020 return CCAssignFnForNode(CC, false, isVarArg); 2021 } 2022 2023 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 2024 bool isVarArg) const { 2025 return CCAssignFnForNode(CC, true, isVarArg); 2026 } 2027 2028 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 2029 /// CallingConvention. 2030 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 2031 bool Return, 2032 bool isVarArg) const { 2033 switch (getEffectiveCallingConv(CC, isVarArg)) { 2034 default: 2035 report_fatal_error("Unsupported calling convention"); 2036 case CallingConv::ARM_APCS: 2037 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 2038 case CallingConv::ARM_AAPCS: 2039 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 2040 case CallingConv::ARM_AAPCS_VFP: 2041 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 2042 case CallingConv::Fast: 2043 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 2044 case CallingConv::GHC: 2045 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 2046 case CallingConv::PreserveMost: 2047 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 2048 case CallingConv::CFGuard_Check: 2049 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check); 2050 } 2051 } 2052 2053 SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG, 2054 MVT LocVT, MVT ValVT, SDValue Val) const { 2055 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()), 2056 Val); 2057 if (Subtarget->hasFullFP16()) { 2058 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val); 2059 } else { 2060 Val = DAG.getNode(ISD::TRUNCATE, dl, 2061 MVT::getIntegerVT(ValVT.getSizeInBits()), Val); 2062 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val); 2063 } 2064 return Val; 2065 } 2066 2067 SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG, 2068 MVT LocVT, MVT ValVT, 2069 SDValue Val) const { 2070 if (Subtarget->hasFullFP16()) { 2071 Val = DAG.getNode(ARMISD::VMOVrh, dl, 2072 MVT::getIntegerVT(LocVT.getSizeInBits()), Val); 2073 } else { 2074 Val = DAG.getNode(ISD::BITCAST, dl, 2075 MVT::getIntegerVT(ValVT.getSizeInBits()), Val); 2076 Val = DAG.getNode(ISD::ZERO_EXTEND, dl, 2077 MVT::getIntegerVT(LocVT.getSizeInBits()), Val); 2078 } 2079 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val); 2080 } 2081 2082 /// LowerCallResult - Lower the result values of a call into the 2083 /// appropriate copies out of appropriate physical registers. 2084 SDValue ARMTargetLowering::LowerCallResult( 2085 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2086 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 2087 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2088 SDValue ThisVal) const { 2089 // Assign locations to each value returned by this call. 2090 SmallVector<CCValAssign, 16> RVLocs; 2091 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2092 *DAG.getContext()); 2093 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 2094 2095 // Copy all of the result registers out of their specified physreg. 2096 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2097 CCValAssign VA = RVLocs[i]; 2098 2099 // Pass 'this' value directly from the argument to return value, to avoid 2100 // reg unit interference 2101 if (i == 0 && isThisReturn) { 2102 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 2103 "unexpected return calling convention register assignment"); 2104 InVals.push_back(ThisVal); 2105 continue; 2106 } 2107 2108 SDValue Val; 2109 if (VA.needsCustom() && 2110 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) { 2111 // Handle f64 or half of a v2f64. 2112 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2113 InFlag); 2114 Chain = Lo.getValue(1); 2115 InFlag = Lo.getValue(2); 2116 VA = RVLocs[++i]; // skip ahead to next loc 2117 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2118 InFlag); 2119 Chain = Hi.getValue(1); 2120 InFlag = Hi.getValue(2); 2121 if (!Subtarget->isLittle()) 2122 std::swap (Lo, Hi); 2123 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2124 2125 if (VA.getLocVT() == MVT::v2f64) { 2126 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 2127 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2128 DAG.getConstant(0, dl, MVT::i32)); 2129 2130 VA = RVLocs[++i]; // skip ahead to next loc 2131 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2132 Chain = Lo.getValue(1); 2133 InFlag = Lo.getValue(2); 2134 VA = RVLocs[++i]; // skip ahead to next loc 2135 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2136 Chain = Hi.getValue(1); 2137 InFlag = Hi.getValue(2); 2138 if (!Subtarget->isLittle()) 2139 std::swap (Lo, Hi); 2140 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2141 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2142 DAG.getConstant(1, dl, MVT::i32)); 2143 } 2144 } else { 2145 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 2146 InFlag); 2147 Chain = Val.getValue(1); 2148 InFlag = Val.getValue(2); 2149 } 2150 2151 switch (VA.getLocInfo()) { 2152 default: llvm_unreachable("Unknown loc info!"); 2153 case CCValAssign::Full: break; 2154 case CCValAssign::BCvt: 2155 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 2156 break; 2157 } 2158 2159 // f16 arguments have their size extended to 4 bytes and passed as if they 2160 // had been copied to the LSBs of a 32-bit register. 2161 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 2162 if (VA.needsCustom() && 2163 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) 2164 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val); 2165 2166 InVals.push_back(Val); 2167 } 2168 2169 return Chain; 2170 } 2171 2172 /// LowerMemOpCallTo - Store the argument to the stack. 2173 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 2174 SDValue Arg, const SDLoc &dl, 2175 SelectionDAG &DAG, 2176 const CCValAssign &VA, 2177 ISD::ArgFlagsTy Flags) const { 2178 unsigned LocMemOffset = VA.getLocMemOffset(); 2179 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2180 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 2181 StackPtr, PtrOff); 2182 return DAG.getStore( 2183 Chain, dl, Arg, PtrOff, 2184 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 2185 } 2186 2187 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 2188 SDValue Chain, SDValue &Arg, 2189 RegsToPassVector &RegsToPass, 2190 CCValAssign &VA, CCValAssign &NextVA, 2191 SDValue &StackPtr, 2192 SmallVectorImpl<SDValue> &MemOpChains, 2193 ISD::ArgFlagsTy Flags) const { 2194 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2195 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2196 unsigned id = Subtarget->isLittle() ? 0 : 1; 2197 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 2198 2199 if (NextVA.isRegLoc()) 2200 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 2201 else { 2202 assert(NextVA.isMemLoc()); 2203 if (!StackPtr.getNode()) 2204 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 2205 getPointerTy(DAG.getDataLayout())); 2206 2207 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 2208 dl, DAG, NextVA, 2209 Flags)); 2210 } 2211 } 2212 2213 /// LowerCall - Lowering a call into a callseq_start <- 2214 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 2215 /// nodes. 2216 SDValue 2217 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2218 SmallVectorImpl<SDValue> &InVals) const { 2219 SelectionDAG &DAG = CLI.DAG; 2220 SDLoc &dl = CLI.DL; 2221 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2222 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2223 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2224 SDValue Chain = CLI.Chain; 2225 SDValue Callee = CLI.Callee; 2226 bool &isTailCall = CLI.IsTailCall; 2227 CallingConv::ID CallConv = CLI.CallConv; 2228 bool doesNotRet = CLI.DoesNotReturn; 2229 bool isVarArg = CLI.IsVarArg; 2230 2231 MachineFunction &MF = DAG.getMachineFunction(); 2232 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2233 MachineFunction::CallSiteInfo CSInfo; 2234 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2235 bool isThisReturn = false; 2236 bool isCmseNSCall = false; 2237 bool PreferIndirect = false; 2238 2239 // Determine whether this is a non-secure function call. 2240 if (CLI.CB && CLI.CB->getAttributes().hasFnAttribute("cmse_nonsecure_call")) 2241 isCmseNSCall = true; 2242 2243 // Disable tail calls if they're not supported. 2244 if (!Subtarget->supportsTailCall()) 2245 isTailCall = false; 2246 2247 // For both the non-secure calls and the returns from a CMSE entry function, 2248 // the function needs to do some extra work afte r the call, or before the 2249 // return, respectively, thus it cannot end with atail call 2250 if (isCmseNSCall || AFI->isCmseNSEntryFunction()) 2251 isTailCall = false; 2252 2253 if (isa<GlobalAddressSDNode>(Callee)) { 2254 // If we're optimizing for minimum size and the function is called three or 2255 // more times in this block, we can improve codesize by calling indirectly 2256 // as BLXr has a 16-bit encoding. 2257 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2258 if (CLI.CB) { 2259 auto *BB = CLI.CB->getParent(); 2260 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2261 count_if(GV->users(), [&BB](const User *U) { 2262 return isa<Instruction>(U) && 2263 cast<Instruction>(U)->getParent() == BB; 2264 }) > 2; 2265 } 2266 } 2267 if (isTailCall) { 2268 // Check if it's really possible to do a tail call. 2269 isTailCall = IsEligibleForTailCallOptimization( 2270 Callee, CallConv, isVarArg, isStructRet, 2271 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2272 PreferIndirect); 2273 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall()) 2274 report_fatal_error("failed to perform tail call elimination on a call " 2275 "site marked musttail"); 2276 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2277 // detected sibcalls. 2278 if (isTailCall) 2279 ++NumTailCalls; 2280 } 2281 2282 // Analyze operands of the call, assigning locations to each operand. 2283 SmallVector<CCValAssign, 16> ArgLocs; 2284 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2285 *DAG.getContext()); 2286 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2287 2288 // Get a count of how many bytes are to be pushed on the stack. 2289 unsigned NumBytes = CCInfo.getNextStackOffset(); 2290 2291 if (isTailCall) { 2292 // For tail calls, memory operands are available in our caller's stack. 2293 NumBytes = 0; 2294 } else { 2295 // Adjust the stack pointer for the new arguments... 2296 // These operations are automatically eliminated by the prolog/epilog pass 2297 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2298 } 2299 2300 SDValue StackPtr = 2301 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2302 2303 RegsToPassVector RegsToPass; 2304 SmallVector<SDValue, 8> MemOpChains; 2305 2306 // Walk the register/memloc assignments, inserting copies/loads. In the case 2307 // of tail call optimization, arguments are handled later. 2308 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2309 i != e; 2310 ++i, ++realArgIdx) { 2311 CCValAssign &VA = ArgLocs[i]; 2312 SDValue Arg = OutVals[realArgIdx]; 2313 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2314 bool isByVal = Flags.isByVal(); 2315 2316 // Promote the value if needed. 2317 switch (VA.getLocInfo()) { 2318 default: llvm_unreachable("Unknown loc info!"); 2319 case CCValAssign::Full: break; 2320 case CCValAssign::SExt: 2321 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2322 break; 2323 case CCValAssign::ZExt: 2324 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2325 break; 2326 case CCValAssign::AExt: 2327 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2328 break; 2329 case CCValAssign::BCvt: 2330 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2331 break; 2332 } 2333 2334 // f16 arguments have their size extended to 4 bytes and passed as if they 2335 // had been copied to the LSBs of a 32-bit register. 2336 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 2337 if (VA.needsCustom() && 2338 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) { 2339 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg); 2340 } else { 2341 // f16 arguments could have been extended prior to argument lowering. 2342 // Mask them arguments if this is a CMSE nonsecure call. 2343 auto ArgVT = Outs[realArgIdx].ArgVT; 2344 if (isCmseNSCall && (ArgVT == MVT::f16)) { 2345 auto LocBits = VA.getLocVT().getSizeInBits(); 2346 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits()); 2347 SDValue Mask = 2348 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits)); 2349 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg); 2350 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask); 2351 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2352 } 2353 } 2354 2355 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2356 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) { 2357 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2358 DAG.getConstant(0, dl, MVT::i32)); 2359 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2360 DAG.getConstant(1, dl, MVT::i32)); 2361 2362 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i], 2363 StackPtr, MemOpChains, Flags); 2364 2365 VA = ArgLocs[++i]; // skip ahead to next loc 2366 if (VA.isRegLoc()) { 2367 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i], 2368 StackPtr, MemOpChains, Flags); 2369 } else { 2370 assert(VA.isMemLoc()); 2371 2372 MemOpChains.push_back( 2373 LowerMemOpCallTo(Chain, StackPtr, Op1, dl, DAG, VA, Flags)); 2374 } 2375 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) { 2376 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2377 StackPtr, MemOpChains, Flags); 2378 } else if (VA.isRegLoc()) { 2379 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2380 Outs[0].VT == MVT::i32) { 2381 assert(VA.getLocVT() == MVT::i32 && 2382 "unexpected calling convention register assignment"); 2383 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2384 "unexpected use of 'returned'"); 2385 isThisReturn = true; 2386 } 2387 const TargetOptions &Options = DAG.getTarget().Options; 2388 if (Options.EmitCallSiteInfo) 2389 CSInfo.emplace_back(VA.getLocReg(), i); 2390 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2391 } else if (isByVal) { 2392 assert(VA.isMemLoc()); 2393 unsigned offset = 0; 2394 2395 // True if this byval aggregate will be split between registers 2396 // and memory. 2397 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2398 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2399 2400 if (CurByValIdx < ByValArgsCount) { 2401 2402 unsigned RegBegin, RegEnd; 2403 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2404 2405 EVT PtrVT = 2406 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2407 unsigned int i, j; 2408 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2409 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2410 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2411 SDValue Load = 2412 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(), 2413 DAG.InferPtrAlign(AddArg)); 2414 MemOpChains.push_back(Load.getValue(1)); 2415 RegsToPass.push_back(std::make_pair(j, Load)); 2416 } 2417 2418 // If parameter size outsides register area, "offset" value 2419 // helps us to calculate stack slot for remained part properly. 2420 offset = RegEnd - RegBegin; 2421 2422 CCInfo.nextInRegsParam(); 2423 } 2424 2425 if (Flags.getByValSize() > 4*offset) { 2426 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2427 unsigned LocMemOffset = VA.getLocMemOffset(); 2428 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2429 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2430 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2431 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2432 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2433 MVT::i32); 2434 SDValue AlignNode = 2435 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32); 2436 2437 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2438 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2439 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2440 Ops)); 2441 } 2442 } else if (!isTailCall) { 2443 assert(VA.isMemLoc()); 2444 2445 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2446 dl, DAG, VA, Flags)); 2447 } 2448 } 2449 2450 if (!MemOpChains.empty()) 2451 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2452 2453 // Build a sequence of copy-to-reg nodes chained together with token chain 2454 // and flag operands which copy the outgoing args into the appropriate regs. 2455 SDValue InFlag; 2456 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2457 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2458 RegsToPass[i].second, InFlag); 2459 InFlag = Chain.getValue(1); 2460 } 2461 2462 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2463 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2464 // node so that legalize doesn't hack it. 2465 bool isDirect = false; 2466 2467 const TargetMachine &TM = getTargetMachine(); 2468 const Module *Mod = MF.getFunction().getParent(); 2469 const GlobalValue *GV = nullptr; 2470 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2471 GV = G->getGlobal(); 2472 bool isStub = 2473 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2474 2475 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2476 bool isLocalARMFunc = false; 2477 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2478 2479 if (Subtarget->genLongCalls()) { 2480 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2481 "long-calls codegen is not position independent!"); 2482 // Handle a global address or an external symbol. If it's not one of 2483 // those, the target's already in a register, so we don't need to do 2484 // anything extra. 2485 if (isa<GlobalAddressSDNode>(Callee)) { 2486 // Create a constant pool entry for the callee address 2487 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2488 ARMConstantPoolValue *CPV = 2489 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2490 2491 // Get the address of the callee into a register 2492 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2493 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2494 Callee = DAG.getLoad( 2495 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2496 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2497 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2498 const char *Sym = S->getSymbol(); 2499 2500 // Create a constant pool entry for the callee address 2501 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2502 ARMConstantPoolValue *CPV = 2503 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2504 ARMPCLabelIndex, 0); 2505 // Get the address of the callee into a register 2506 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2507 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2508 Callee = DAG.getLoad( 2509 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2510 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2511 } 2512 } else if (isa<GlobalAddressSDNode>(Callee)) { 2513 if (!PreferIndirect) { 2514 isDirect = true; 2515 bool isDef = GV->isStrongDefinitionForLinker(); 2516 2517 // ARM call to a local ARM function is predicable. 2518 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2519 // tBX takes a register source operand. 2520 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2521 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2522 Callee = DAG.getNode( 2523 ARMISD::WrapperPIC, dl, PtrVt, 2524 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2525 Callee = DAG.getLoad( 2526 PtrVt, dl, DAG.getEntryNode(), Callee, 2527 MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(), 2528 MachineMemOperand::MODereferenceable | 2529 MachineMemOperand::MOInvariant); 2530 } else if (Subtarget->isTargetCOFF()) { 2531 assert(Subtarget->isTargetWindows() && 2532 "Windows is the only supported COFF target"); 2533 unsigned TargetFlags = ARMII::MO_NO_FLAG; 2534 if (GV->hasDLLImportStorageClass()) 2535 TargetFlags = ARMII::MO_DLLIMPORT; 2536 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 2537 TargetFlags = ARMII::MO_COFFSTUB; 2538 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2539 TargetFlags); 2540 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 2541 Callee = 2542 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2543 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2544 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2545 } else { 2546 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2547 } 2548 } 2549 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2550 isDirect = true; 2551 // tBX takes a register source operand. 2552 const char *Sym = S->getSymbol(); 2553 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2554 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2555 ARMConstantPoolValue *CPV = 2556 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2557 ARMPCLabelIndex, 4); 2558 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2559 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2560 Callee = DAG.getLoad( 2561 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2562 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2563 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2564 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2565 } else { 2566 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2567 } 2568 } 2569 2570 if (isCmseNSCall) { 2571 assert(!isARMFunc && !isDirect && 2572 "Cannot handle call to ARM function or direct call"); 2573 if (NumBytes > 0) { 2574 DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(), 2575 "call to non-secure function would " 2576 "require passing arguments on stack", 2577 dl.getDebugLoc()); 2578 DAG.getContext()->diagnose(Diag); 2579 } 2580 if (isStructRet) { 2581 DiagnosticInfoUnsupported Diag( 2582 DAG.getMachineFunction().getFunction(), 2583 "call to non-secure function would return value through pointer", 2584 dl.getDebugLoc()); 2585 DAG.getContext()->diagnose(Diag); 2586 } 2587 } 2588 2589 // FIXME: handle tail calls differently. 2590 unsigned CallOpc; 2591 if (Subtarget->isThumb()) { 2592 if (isCmseNSCall) 2593 CallOpc = ARMISD::tSECALL; 2594 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2595 CallOpc = ARMISD::CALL_NOLINK; 2596 else 2597 CallOpc = ARMISD::CALL; 2598 } else { 2599 if (!isDirect && !Subtarget->hasV5TOps()) 2600 CallOpc = ARMISD::CALL_NOLINK; 2601 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2602 // Emit regular call when code size is the priority 2603 !Subtarget->hasMinSize()) 2604 // "mov lr, pc; b _foo" to avoid confusing the RSP 2605 CallOpc = ARMISD::CALL_NOLINK; 2606 else 2607 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2608 } 2609 2610 std::vector<SDValue> Ops; 2611 Ops.push_back(Chain); 2612 Ops.push_back(Callee); 2613 2614 // Add argument registers to the end of the list so that they are known live 2615 // into the call. 2616 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2617 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2618 RegsToPass[i].second.getValueType())); 2619 2620 // Add a register mask operand representing the call-preserved registers. 2621 if (!isTailCall) { 2622 const uint32_t *Mask; 2623 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2624 if (isThisReturn) { 2625 // For 'this' returns, use the R0-preserving mask if applicable 2626 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2627 if (!Mask) { 2628 // Set isThisReturn to false if the calling convention is not one that 2629 // allows 'returned' to be modeled in this way, so LowerCallResult does 2630 // not try to pass 'this' straight through 2631 isThisReturn = false; 2632 Mask = ARI->getCallPreservedMask(MF, CallConv); 2633 } 2634 } else 2635 Mask = ARI->getCallPreservedMask(MF, CallConv); 2636 2637 assert(Mask && "Missing call preserved mask for calling convention"); 2638 Ops.push_back(DAG.getRegisterMask(Mask)); 2639 } 2640 2641 if (InFlag.getNode()) 2642 Ops.push_back(InFlag); 2643 2644 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2645 if (isTailCall) { 2646 MF.getFrameInfo().setHasTailCall(); 2647 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2648 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 2649 return Ret; 2650 } 2651 2652 // Returns a chain and a flag for retval copy to use. 2653 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2654 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 2655 InFlag = Chain.getValue(1); 2656 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 2657 2658 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2659 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2660 if (!Ins.empty()) 2661 InFlag = Chain.getValue(1); 2662 2663 // Handle result values, copying them out of physregs into vregs that we 2664 // return. 2665 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2666 InVals, isThisReturn, 2667 isThisReturn ? OutVals[0] : SDValue()); 2668 } 2669 2670 /// HandleByVal - Every parameter *after* a byval parameter is passed 2671 /// on the stack. Remember the next parameter register to allocate, 2672 /// and then confiscate the rest of the parameter registers to insure 2673 /// this. 2674 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2675 Align Alignment) const { 2676 // Byval (as with any stack) slots are always at least 4 byte aligned. 2677 Alignment = std::max(Alignment, Align(4)); 2678 2679 unsigned Reg = State->AllocateReg(GPRArgRegs); 2680 if (!Reg) 2681 return; 2682 2683 unsigned AlignInRegs = Alignment.value() / 4; 2684 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2685 for (unsigned i = 0; i < Waste; ++i) 2686 Reg = State->AllocateReg(GPRArgRegs); 2687 2688 if (!Reg) 2689 return; 2690 2691 unsigned Excess = 4 * (ARM::R4 - Reg); 2692 2693 // Special case when NSAA != SP and parameter size greater than size of 2694 // all remained GPR regs. In that case we can't split parameter, we must 2695 // send it to stack. We also must set NCRN to R4, so waste all 2696 // remained registers. 2697 const unsigned NSAAOffset = State->getNextStackOffset(); 2698 if (NSAAOffset != 0 && Size > Excess) { 2699 while (State->AllocateReg(GPRArgRegs)) 2700 ; 2701 return; 2702 } 2703 2704 // First register for byval parameter is the first register that wasn't 2705 // allocated before this method call, so it would be "reg". 2706 // If parameter is small enough to be saved in range [reg, r4), then 2707 // the end (first after last) register would be reg + param-size-in-regs, 2708 // else parameter would be splitted between registers and stack, 2709 // end register would be r4 in this case. 2710 unsigned ByValRegBegin = Reg; 2711 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2712 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2713 // Note, first register is allocated in the beginning of function already, 2714 // allocate remained amount of registers we need. 2715 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2716 State->AllocateReg(GPRArgRegs); 2717 // A byval parameter that is split between registers and memory needs its 2718 // size truncated here. 2719 // In the case where the entire structure fits in registers, we set the 2720 // size in memory to zero. 2721 Size = std::max<int>(Size - Excess, 0); 2722 } 2723 2724 /// MatchingStackOffset - Return true if the given stack call argument is 2725 /// already available in the same position (relatively) of the caller's 2726 /// incoming argument stack. 2727 static 2728 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2729 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2730 const TargetInstrInfo *TII) { 2731 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2732 int FI = std::numeric_limits<int>::max(); 2733 if (Arg.getOpcode() == ISD::CopyFromReg) { 2734 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2735 if (!Register::isVirtualRegister(VR)) 2736 return false; 2737 MachineInstr *Def = MRI->getVRegDef(VR); 2738 if (!Def) 2739 return false; 2740 if (!Flags.isByVal()) { 2741 if (!TII->isLoadFromStackSlot(*Def, FI)) 2742 return false; 2743 } else { 2744 return false; 2745 } 2746 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2747 if (Flags.isByVal()) 2748 // ByVal argument is passed in as a pointer but it's now being 2749 // dereferenced. e.g. 2750 // define @foo(%struct.X* %A) { 2751 // tail call @bar(%struct.X* byval %A) 2752 // } 2753 return false; 2754 SDValue Ptr = Ld->getBasePtr(); 2755 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2756 if (!FINode) 2757 return false; 2758 FI = FINode->getIndex(); 2759 } else 2760 return false; 2761 2762 assert(FI != std::numeric_limits<int>::max()); 2763 if (!MFI.isFixedObjectIndex(FI)) 2764 return false; 2765 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2766 } 2767 2768 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2769 /// for tail call optimization. Targets which want to do tail call 2770 /// optimization should implement this function. 2771 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2772 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2773 bool isCalleeStructRet, bool isCallerStructRet, 2774 const SmallVectorImpl<ISD::OutputArg> &Outs, 2775 const SmallVectorImpl<SDValue> &OutVals, 2776 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2777 const bool isIndirect) const { 2778 MachineFunction &MF = DAG.getMachineFunction(); 2779 const Function &CallerF = MF.getFunction(); 2780 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2781 2782 assert(Subtarget->supportsTailCall()); 2783 2784 // Indirect tail calls cannot be optimized for Thumb1 if the args 2785 // to the call take up r0-r3. The reason is that there are no legal registers 2786 // left to hold the pointer to the function to be called. 2787 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2788 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2789 return false; 2790 2791 // Look for obvious safe cases to perform tail call optimization that do not 2792 // require ABI changes. This is what gcc calls sibcall. 2793 2794 // Exception-handling functions need a special set of instructions to indicate 2795 // a return to the hardware. Tail-calling another function would probably 2796 // break this. 2797 if (CallerF.hasFnAttribute("interrupt")) 2798 return false; 2799 2800 // Also avoid sibcall optimization if either caller or callee uses struct 2801 // return semantics. 2802 if (isCalleeStructRet || isCallerStructRet) 2803 return false; 2804 2805 // Externally-defined functions with weak linkage should not be 2806 // tail-called on ARM when the OS does not support dynamic 2807 // pre-emption of symbols, as the AAELF spec requires normal calls 2808 // to undefined weak functions to be replaced with a NOP or jump to the 2809 // next instruction. The behaviour of branch instructions in this 2810 // situation (as used for tail calls) is implementation-defined, so we 2811 // cannot rely on the linker replacing the tail call with a return. 2812 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2813 const GlobalValue *GV = G->getGlobal(); 2814 const Triple &TT = getTargetMachine().getTargetTriple(); 2815 if (GV->hasExternalWeakLinkage() && 2816 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2817 return false; 2818 } 2819 2820 // Check that the call results are passed in the same way. 2821 LLVMContext &C = *DAG.getContext(); 2822 if (!CCState::resultsCompatible( 2823 getEffectiveCallingConv(CalleeCC, isVarArg), 2824 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins, 2825 CCAssignFnForReturn(CalleeCC, isVarArg), 2826 CCAssignFnForReturn(CallerCC, CallerF.isVarArg()))) 2827 return false; 2828 // The callee has to preserve all registers the caller needs to preserve. 2829 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2830 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2831 if (CalleeCC != CallerCC) { 2832 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2833 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2834 return false; 2835 } 2836 2837 // If Caller's vararg or byval argument has been split between registers and 2838 // stack, do not perform tail call, since part of the argument is in caller's 2839 // local frame. 2840 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2841 if (AFI_Caller->getArgRegsSaveSize()) 2842 return false; 2843 2844 // If the callee takes no arguments then go on to check the results of the 2845 // call. 2846 if (!Outs.empty()) { 2847 // Check if stack adjustment is needed. For now, do not do this if any 2848 // argument is passed on the stack. 2849 SmallVector<CCValAssign, 16> ArgLocs; 2850 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2851 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2852 if (CCInfo.getNextStackOffset()) { 2853 // Check if the arguments are already laid out in the right way as 2854 // the caller's fixed stack objects. 2855 MachineFrameInfo &MFI = MF.getFrameInfo(); 2856 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2857 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2858 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2859 i != e; 2860 ++i, ++realArgIdx) { 2861 CCValAssign &VA = ArgLocs[i]; 2862 EVT RegVT = VA.getLocVT(); 2863 SDValue Arg = OutVals[realArgIdx]; 2864 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2865 if (VA.getLocInfo() == CCValAssign::Indirect) 2866 return false; 2867 if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) { 2868 // f64 and vector types are split into multiple registers or 2869 // register/stack-slot combinations. The types will not match 2870 // the registers; give up on memory f64 refs until we figure 2871 // out what to do about this. 2872 if (!VA.isRegLoc()) 2873 return false; 2874 if (!ArgLocs[++i].isRegLoc()) 2875 return false; 2876 if (RegVT == MVT::v2f64) { 2877 if (!ArgLocs[++i].isRegLoc()) 2878 return false; 2879 if (!ArgLocs[++i].isRegLoc()) 2880 return false; 2881 } 2882 } else if (!VA.isRegLoc()) { 2883 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2884 MFI, MRI, TII)) 2885 return false; 2886 } 2887 } 2888 } 2889 2890 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2891 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2892 return false; 2893 } 2894 2895 return true; 2896 } 2897 2898 bool 2899 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2900 MachineFunction &MF, bool isVarArg, 2901 const SmallVectorImpl<ISD::OutputArg> &Outs, 2902 LLVMContext &Context) const { 2903 SmallVector<CCValAssign, 16> RVLocs; 2904 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2905 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2906 } 2907 2908 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2909 const SDLoc &DL, SelectionDAG &DAG) { 2910 const MachineFunction &MF = DAG.getMachineFunction(); 2911 const Function &F = MF.getFunction(); 2912 2913 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2914 2915 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2916 // version of the "preferred return address". These offsets affect the return 2917 // instruction if this is a return from PL1 without hypervisor extensions. 2918 // IRQ/FIQ: +4 "subs pc, lr, #4" 2919 // SWI: 0 "subs pc, lr, #0" 2920 // ABORT: +4 "subs pc, lr, #4" 2921 // UNDEF: +4/+2 "subs pc, lr, #0" 2922 // UNDEF varies depending on where the exception came from ARM or Thumb 2923 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2924 2925 int64_t LROffset; 2926 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2927 IntKind == "ABORT") 2928 LROffset = 4; 2929 else if (IntKind == "SWI" || IntKind == "UNDEF") 2930 LROffset = 0; 2931 else 2932 report_fatal_error("Unsupported interrupt attribute. If present, value " 2933 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2934 2935 RetOps.insert(RetOps.begin() + 1, 2936 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2937 2938 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2939 } 2940 2941 SDValue 2942 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2943 bool isVarArg, 2944 const SmallVectorImpl<ISD::OutputArg> &Outs, 2945 const SmallVectorImpl<SDValue> &OutVals, 2946 const SDLoc &dl, SelectionDAG &DAG) const { 2947 // CCValAssign - represent the assignment of the return value to a location. 2948 SmallVector<CCValAssign, 16> RVLocs; 2949 2950 // CCState - Info about the registers and stack slots. 2951 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2952 *DAG.getContext()); 2953 2954 // Analyze outgoing return values. 2955 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2956 2957 SDValue Flag; 2958 SmallVector<SDValue, 4> RetOps; 2959 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2960 bool isLittleEndian = Subtarget->isLittle(); 2961 2962 MachineFunction &MF = DAG.getMachineFunction(); 2963 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2964 AFI->setReturnRegsCount(RVLocs.size()); 2965 2966 // Report error if cmse entry function returns structure through first ptr arg. 2967 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) { 2968 // Note: using an empty SDLoc(), as the first line of the function is a 2969 // better place to report than the last line. 2970 DiagnosticInfoUnsupported Diag( 2971 DAG.getMachineFunction().getFunction(), 2972 "secure entry function would return value through pointer", 2973 SDLoc().getDebugLoc()); 2974 DAG.getContext()->diagnose(Diag); 2975 } 2976 2977 // Copy the result values into the output registers. 2978 for (unsigned i = 0, realRVLocIdx = 0; 2979 i != RVLocs.size(); 2980 ++i, ++realRVLocIdx) { 2981 CCValAssign &VA = RVLocs[i]; 2982 assert(VA.isRegLoc() && "Can only return in registers!"); 2983 2984 SDValue Arg = OutVals[realRVLocIdx]; 2985 bool ReturnF16 = false; 2986 2987 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2988 // Half-precision return values can be returned like this: 2989 // 2990 // t11 f16 = fadd ... 2991 // t12: i16 = bitcast t11 2992 // t13: i32 = zero_extend t12 2993 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2994 // 2995 // to avoid code generation for bitcasts, we simply set Arg to the node 2996 // that produces the f16 value, t11 in this case. 2997 // 2998 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2999 SDValue ZE = Arg.getOperand(0); 3000 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 3001 SDValue BC = ZE.getOperand(0); 3002 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 3003 Arg = BC.getOperand(0); 3004 ReturnF16 = true; 3005 } 3006 } 3007 } 3008 } 3009 3010 switch (VA.getLocInfo()) { 3011 default: llvm_unreachable("Unknown loc info!"); 3012 case CCValAssign::Full: break; 3013 case CCValAssign::BCvt: 3014 if (!ReturnF16) 3015 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 3016 break; 3017 } 3018 3019 // Mask f16 arguments if this is a CMSE nonsecure entry. 3020 auto RetVT = Outs[realRVLocIdx].ArgVT; 3021 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) { 3022 if (VA.needsCustom() && VA.getValVT() == MVT::f16) { 3023 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg); 3024 } else { 3025 auto LocBits = VA.getLocVT().getSizeInBits(); 3026 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits()); 3027 SDValue Mask = 3028 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits)); 3029 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg); 3030 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask); 3031 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 3032 } 3033 } 3034 3035 if (VA.needsCustom() && 3036 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) { 3037 if (VA.getLocVT() == MVT::v2f64) { 3038 // Extract the first half and return it in two registers. 3039 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 3040 DAG.getConstant(0, dl, MVT::i32)); 3041 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 3042 DAG.getVTList(MVT::i32, MVT::i32), Half); 3043 3044 Chain = 3045 DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3046 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag); 3047 Flag = Chain.getValue(1); 3048 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3049 VA = RVLocs[++i]; // skip ahead to next loc 3050 Chain = 3051 DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3052 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag); 3053 Flag = Chain.getValue(1); 3054 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3055 VA = RVLocs[++i]; // skip ahead to next loc 3056 3057 // Extract the 2nd half and fall through to handle it as an f64 value. 3058 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 3059 DAG.getConstant(1, dl, MVT::i32)); 3060 } 3061 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 3062 // available. 3063 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 3064 DAG.getVTList(MVT::i32, MVT::i32), Arg); 3065 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3066 fmrrd.getValue(isLittleEndian ? 0 : 1), Flag); 3067 Flag = Chain.getValue(1); 3068 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3069 VA = RVLocs[++i]; // skip ahead to next loc 3070 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3071 fmrrd.getValue(isLittleEndian ? 1 : 0), Flag); 3072 } else 3073 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 3074 3075 // Guarantee that all emitted copies are 3076 // stuck together, avoiding something bad. 3077 Flag = Chain.getValue(1); 3078 RetOps.push_back(DAG.getRegister( 3079 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT())); 3080 } 3081 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 3082 const MCPhysReg *I = 3083 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3084 if (I) { 3085 for (; *I; ++I) { 3086 if (ARM::GPRRegClass.contains(*I)) 3087 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 3088 else if (ARM::DPRRegClass.contains(*I)) 3089 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3090 else 3091 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3092 } 3093 } 3094 3095 // Update chain and glue. 3096 RetOps[0] = Chain; 3097 if (Flag.getNode()) 3098 RetOps.push_back(Flag); 3099 3100 // CPUs which aren't M-class use a special sequence to return from 3101 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 3102 // though we use "subs pc, lr, #N"). 3103 // 3104 // M-class CPUs actually use a normal return sequence with a special 3105 // (hardware-provided) value in LR, so the normal code path works. 3106 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 3107 !Subtarget->isMClass()) { 3108 if (Subtarget->isThumb1Only()) 3109 report_fatal_error("interrupt attribute is not supported in Thumb1"); 3110 return LowerInterruptReturn(RetOps, dl, DAG); 3111 } 3112 3113 ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG : 3114 ARMISD::RET_FLAG; 3115 return DAG.getNode(RetNode, dl, MVT::Other, RetOps); 3116 } 3117 3118 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 3119 if (N->getNumValues() != 1) 3120 return false; 3121 if (!N->hasNUsesOfValue(1, 0)) 3122 return false; 3123 3124 SDValue TCChain = Chain; 3125 SDNode *Copy = *N->use_begin(); 3126 if (Copy->getOpcode() == ISD::CopyToReg) { 3127 // If the copy has a glue operand, we conservatively assume it isn't safe to 3128 // perform a tail call. 3129 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 3130 return false; 3131 TCChain = Copy->getOperand(0); 3132 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 3133 SDNode *VMov = Copy; 3134 // f64 returned in a pair of GPRs. 3135 SmallPtrSet<SDNode*, 2> Copies; 3136 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 3137 UI != UE; ++UI) { 3138 if (UI->getOpcode() != ISD::CopyToReg) 3139 return false; 3140 Copies.insert(*UI); 3141 } 3142 if (Copies.size() > 2) 3143 return false; 3144 3145 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 3146 UI != UE; ++UI) { 3147 SDValue UseChain = UI->getOperand(0); 3148 if (Copies.count(UseChain.getNode())) 3149 // Second CopyToReg 3150 Copy = *UI; 3151 else { 3152 // We are at the top of this chain. 3153 // If the copy has a glue operand, we conservatively assume it 3154 // isn't safe to perform a tail call. 3155 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 3156 return false; 3157 // First CopyToReg 3158 TCChain = UseChain; 3159 } 3160 } 3161 } else if (Copy->getOpcode() == ISD::BITCAST) { 3162 // f32 returned in a single GPR. 3163 if (!Copy->hasOneUse()) 3164 return false; 3165 Copy = *Copy->use_begin(); 3166 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 3167 return false; 3168 // If the copy has a glue operand, we conservatively assume it isn't safe to 3169 // perform a tail call. 3170 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 3171 return false; 3172 TCChain = Copy->getOperand(0); 3173 } else { 3174 return false; 3175 } 3176 3177 bool HasRet = false; 3178 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 3179 UI != UE; ++UI) { 3180 if (UI->getOpcode() != ARMISD::RET_FLAG && 3181 UI->getOpcode() != ARMISD::INTRET_FLAG) 3182 return false; 3183 HasRet = true; 3184 } 3185 3186 if (!HasRet) 3187 return false; 3188 3189 Chain = TCChain; 3190 return true; 3191 } 3192 3193 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3194 if (!Subtarget->supportsTailCall()) 3195 return false; 3196 3197 if (!CI->isTailCall()) 3198 return false; 3199 3200 return true; 3201 } 3202 3203 // Trying to write a 64 bit value so need to split into two 32 bit values first, 3204 // and pass the lower and high parts through. 3205 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 3206 SDLoc DL(Op); 3207 SDValue WriteValue = Op->getOperand(2); 3208 3209 // This function is only supposed to be called for i64 type argument. 3210 assert(WriteValue.getValueType() == MVT::i64 3211 && "LowerWRITE_REGISTER called for non-i64 type argument."); 3212 3213 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3214 DAG.getConstant(0, DL, MVT::i32)); 3215 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3216 DAG.getConstant(1, DL, MVT::i32)); 3217 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 3218 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 3219 } 3220 3221 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 3222 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 3223 // one of the above mentioned nodes. It has to be wrapped because otherwise 3224 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 3225 // be used to form addressing mode. These wrapped nodes will be selected 3226 // into MOVi. 3227 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 3228 SelectionDAG &DAG) const { 3229 EVT PtrVT = Op.getValueType(); 3230 // FIXME there is no actual debug info here 3231 SDLoc dl(Op); 3232 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3233 SDValue Res; 3234 3235 // When generating execute-only code Constant Pools must be promoted to the 3236 // global data section. It's a bit ugly that we can't share them across basic 3237 // blocks, but this way we guarantee that execute-only behaves correct with 3238 // position-independent addressing modes. 3239 if (Subtarget->genExecuteOnly()) { 3240 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 3241 auto T = const_cast<Type*>(CP->getType()); 3242 auto C = const_cast<Constant*>(CP->getConstVal()); 3243 auto M = const_cast<Module*>(DAG.getMachineFunction(). 3244 getFunction().getParent()); 3245 auto GV = new GlobalVariable( 3246 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 3247 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 3248 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 3249 Twine(AFI->createPICLabelUId()) 3250 ); 3251 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 3252 dl, PtrVT); 3253 return LowerGlobalAddress(GA, DAG); 3254 } 3255 3256 if (CP->isMachineConstantPoolEntry()) 3257 Res = 3258 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign()); 3259 else 3260 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign()); 3261 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 3262 } 3263 3264 unsigned ARMTargetLowering::getJumpTableEncoding() const { 3265 return MachineJumpTableInfo::EK_Inline; 3266 } 3267 3268 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 3269 SelectionDAG &DAG) const { 3270 MachineFunction &MF = DAG.getMachineFunction(); 3271 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3272 unsigned ARMPCLabelIndex = 0; 3273 SDLoc DL(Op); 3274 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3275 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 3276 SDValue CPAddr; 3277 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 3278 if (!IsPositionIndependent) { 3279 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4)); 3280 } else { 3281 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3282 ARMPCLabelIndex = AFI->createPICLabelUId(); 3283 ARMConstantPoolValue *CPV = 3284 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 3285 ARMCP::CPBlockAddress, PCAdj); 3286 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3287 } 3288 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 3289 SDValue Result = DAG.getLoad( 3290 PtrVT, DL, DAG.getEntryNode(), CPAddr, 3291 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3292 if (!IsPositionIndependent) 3293 return Result; 3294 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 3295 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 3296 } 3297 3298 /// Convert a TLS address reference into the correct sequence of loads 3299 /// and calls to compute the variable's address for Darwin, and return an 3300 /// SDValue containing the final node. 3301 3302 /// Darwin only has one TLS scheme which must be capable of dealing with the 3303 /// fully general situation, in the worst case. This means: 3304 /// + "extern __thread" declaration. 3305 /// + Defined in a possibly unknown dynamic library. 3306 /// 3307 /// The general system is that each __thread variable has a [3 x i32] descriptor 3308 /// which contains information used by the runtime to calculate the address. The 3309 /// only part of this the compiler needs to know about is the first word, which 3310 /// contains a function pointer that must be called with the address of the 3311 /// entire descriptor in "r0". 3312 /// 3313 /// Since this descriptor may be in a different unit, in general access must 3314 /// proceed along the usual ARM rules. A common sequence to produce is: 3315 /// 3316 /// movw rT1, :lower16:_var$non_lazy_ptr 3317 /// movt rT1, :upper16:_var$non_lazy_ptr 3318 /// ldr r0, [rT1] 3319 /// ldr rT2, [r0] 3320 /// blx rT2 3321 /// [...address now in r0...] 3322 SDValue 3323 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3324 SelectionDAG &DAG) const { 3325 assert(Subtarget->isTargetDarwin() && 3326 "This function expects a Darwin target"); 3327 SDLoc DL(Op); 3328 3329 // First step is to get the address of the actua global symbol. This is where 3330 // the TLS descriptor lives. 3331 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3332 3333 // The first entry in the descriptor is a function pointer that we must call 3334 // to obtain the address of the variable. 3335 SDValue Chain = DAG.getEntryNode(); 3336 SDValue FuncTLVGet = DAG.getLoad( 3337 MVT::i32, DL, Chain, DescAddr, 3338 MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4), 3339 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3340 MachineMemOperand::MOInvariant); 3341 Chain = FuncTLVGet.getValue(1); 3342 3343 MachineFunction &F = DAG.getMachineFunction(); 3344 MachineFrameInfo &MFI = F.getFrameInfo(); 3345 MFI.setAdjustsStack(true); 3346 3347 // TLS calls preserve all registers except those that absolutely must be 3348 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3349 // silly). 3350 auto TRI = 3351 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3352 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3353 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3354 3355 // Finally, we can make the call. This is just a degenerate version of a 3356 // normal AArch64 call node: r0 takes the address of the descriptor, and 3357 // returns the address of the variable in this thread. 3358 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3359 Chain = 3360 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3361 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3362 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3363 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3364 } 3365 3366 SDValue 3367 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3368 SelectionDAG &DAG) const { 3369 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3370 3371 SDValue Chain = DAG.getEntryNode(); 3372 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3373 SDLoc DL(Op); 3374 3375 // Load the current TEB (thread environment block) 3376 SDValue Ops[] = {Chain, 3377 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3378 DAG.getTargetConstant(15, DL, MVT::i32), 3379 DAG.getTargetConstant(0, DL, MVT::i32), 3380 DAG.getTargetConstant(13, DL, MVT::i32), 3381 DAG.getTargetConstant(0, DL, MVT::i32), 3382 DAG.getTargetConstant(2, DL, MVT::i32)}; 3383 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3384 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3385 3386 SDValue TEB = CurrentTEB.getValue(0); 3387 Chain = CurrentTEB.getValue(1); 3388 3389 // Load the ThreadLocalStoragePointer from the TEB 3390 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3391 SDValue TLSArray = 3392 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3393 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3394 3395 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3396 // offset into the TLSArray. 3397 3398 // Load the TLS index from the C runtime 3399 SDValue TLSIndex = 3400 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3401 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3402 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3403 3404 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3405 DAG.getConstant(2, DL, MVT::i32)); 3406 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3407 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3408 MachinePointerInfo()); 3409 3410 // Get the offset of the start of the .tls section (section base) 3411 const auto *GA = cast<GlobalAddressSDNode>(Op); 3412 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3413 SDValue Offset = DAG.getLoad( 3414 PtrVT, DL, Chain, 3415 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3416 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))), 3417 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3418 3419 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3420 } 3421 3422 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3423 SDValue 3424 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3425 SelectionDAG &DAG) const { 3426 SDLoc dl(GA); 3427 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3428 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3429 MachineFunction &MF = DAG.getMachineFunction(); 3430 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3431 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3432 ARMConstantPoolValue *CPV = 3433 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3434 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3435 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3436 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3437 Argument = DAG.getLoad( 3438 PtrVT, dl, DAG.getEntryNode(), Argument, 3439 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3440 SDValue Chain = Argument.getValue(1); 3441 3442 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3443 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3444 3445 // call __tls_get_addr. 3446 ArgListTy Args; 3447 ArgListEntry Entry; 3448 Entry.Node = Argument; 3449 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3450 Args.push_back(Entry); 3451 3452 // FIXME: is there useful debug info available here? 3453 TargetLowering::CallLoweringInfo CLI(DAG); 3454 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3455 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3456 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3457 3458 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3459 return CallResult.first; 3460 } 3461 3462 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3463 // "local exec" model. 3464 SDValue 3465 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3466 SelectionDAG &DAG, 3467 TLSModel::Model model) const { 3468 const GlobalValue *GV = GA->getGlobal(); 3469 SDLoc dl(GA); 3470 SDValue Offset; 3471 SDValue Chain = DAG.getEntryNode(); 3472 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3473 // Get the Thread Pointer 3474 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3475 3476 if (model == TLSModel::InitialExec) { 3477 MachineFunction &MF = DAG.getMachineFunction(); 3478 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3479 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3480 // Initial exec model. 3481 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3482 ARMConstantPoolValue *CPV = 3483 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3484 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3485 true); 3486 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3487 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3488 Offset = DAG.getLoad( 3489 PtrVT, dl, Chain, Offset, 3490 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3491 Chain = Offset.getValue(1); 3492 3493 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3494 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3495 3496 Offset = DAG.getLoad( 3497 PtrVT, dl, Chain, Offset, 3498 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3499 } else { 3500 // local exec model 3501 assert(model == TLSModel::LocalExec); 3502 ARMConstantPoolValue *CPV = 3503 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3504 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3505 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3506 Offset = DAG.getLoad( 3507 PtrVT, dl, Chain, Offset, 3508 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3509 } 3510 3511 // The address of the thread local variable is the add of the thread 3512 // pointer with the offset of the variable. 3513 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3514 } 3515 3516 SDValue 3517 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3518 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3519 if (DAG.getTarget().useEmulatedTLS()) 3520 return LowerToTLSEmulatedModel(GA, DAG); 3521 3522 if (Subtarget->isTargetDarwin()) 3523 return LowerGlobalTLSAddressDarwin(Op, DAG); 3524 3525 if (Subtarget->isTargetWindows()) 3526 return LowerGlobalTLSAddressWindows(Op, DAG); 3527 3528 // TODO: implement the "local dynamic" model 3529 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3530 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3531 3532 switch (model) { 3533 case TLSModel::GeneralDynamic: 3534 case TLSModel::LocalDynamic: 3535 return LowerToTLSGeneralDynamicModel(GA, DAG); 3536 case TLSModel::InitialExec: 3537 case TLSModel::LocalExec: 3538 return LowerToTLSExecModels(GA, DAG, model); 3539 } 3540 llvm_unreachable("bogus TLS model"); 3541 } 3542 3543 /// Return true if all users of V are within function F, looking through 3544 /// ConstantExprs. 3545 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3546 SmallVector<const User*,4> Worklist; 3547 for (auto *U : V->users()) 3548 Worklist.push_back(U); 3549 while (!Worklist.empty()) { 3550 auto *U = Worklist.pop_back_val(); 3551 if (isa<ConstantExpr>(U)) { 3552 for (auto *UU : U->users()) 3553 Worklist.push_back(UU); 3554 continue; 3555 } 3556 3557 auto *I = dyn_cast<Instruction>(U); 3558 if (!I || I->getParent()->getParent() != F) 3559 return false; 3560 } 3561 return true; 3562 } 3563 3564 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3565 const GlobalValue *GV, SelectionDAG &DAG, 3566 EVT PtrVT, const SDLoc &dl) { 3567 // If we're creating a pool entry for a constant global with unnamed address, 3568 // and the global is small enough, we can emit it inline into the constant pool 3569 // to save ourselves an indirection. 3570 // 3571 // This is a win if the constant is only used in one function (so it doesn't 3572 // need to be duplicated) or duplicating the constant wouldn't increase code 3573 // size (implying the constant is no larger than 4 bytes). 3574 const Function &F = DAG.getMachineFunction().getFunction(); 3575 3576 // We rely on this decision to inline being idemopotent and unrelated to the 3577 // use-site. We know that if we inline a variable at one use site, we'll 3578 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3579 // doesn't know about this optimization, so bail out if it's enabled else 3580 // we could decide to inline here (and thus never emit the GV) but require 3581 // the GV from fast-isel generated code. 3582 if (!EnableConstpoolPromotion || 3583 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3584 return SDValue(); 3585 3586 auto *GVar = dyn_cast<GlobalVariable>(GV); 3587 if (!GVar || !GVar->hasInitializer() || 3588 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3589 !GVar->hasLocalLinkage()) 3590 return SDValue(); 3591 3592 // If we inline a value that contains relocations, we move the relocations 3593 // from .data to .text. This is not allowed in position-independent code. 3594 auto *Init = GVar->getInitializer(); 3595 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3596 Init->needsRelocation()) 3597 return SDValue(); 3598 3599 // The constant islands pass can only really deal with alignment requests 3600 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3601 // any type wanting greater alignment requirements than 4 bytes. We also 3602 // can only promote constants that are multiples of 4 bytes in size or 3603 // are paddable to a multiple of 4. Currently we only try and pad constants 3604 // that are strings for simplicity. 3605 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3606 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3607 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar); 3608 unsigned RequiredPadding = 4 - (Size % 4); 3609 bool PaddingPossible = 3610 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3611 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize || 3612 Size == 0) 3613 return SDValue(); 3614 3615 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3616 MachineFunction &MF = DAG.getMachineFunction(); 3617 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3618 3619 // We can't bloat the constant pool too much, else the ConstantIslands pass 3620 // may fail to converge. If we haven't promoted this global yet (it may have 3621 // multiple uses), and promoting it would increase the constant pool size (Sz 3622 // > 4), ensure we have space to do so up to MaxTotal. 3623 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3624 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3625 ConstpoolPromotionMaxTotal) 3626 return SDValue(); 3627 3628 // This is only valid if all users are in a single function; we can't clone 3629 // the constant in general. The LLVM IR unnamed_addr allows merging 3630 // constants, but not cloning them. 3631 // 3632 // We could potentially allow cloning if we could prove all uses of the 3633 // constant in the current function don't care about the address, like 3634 // printf format strings. But that isn't implemented for now. 3635 if (!allUsersAreInFunction(GVar, &F)) 3636 return SDValue(); 3637 3638 // We're going to inline this global. Pad it out if needed. 3639 if (RequiredPadding != 4) { 3640 StringRef S = CDAInit->getAsString(); 3641 3642 SmallVector<uint8_t,16> V(S.size()); 3643 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3644 while (RequiredPadding--) 3645 V.push_back(0); 3646 Init = ConstantDataArray::get(*DAG.getContext(), V); 3647 } 3648 3649 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3650 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4)); 3651 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3652 AFI->markGlobalAsPromotedToConstantPool(GVar); 3653 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3654 PaddedSize - 4); 3655 } 3656 ++NumConstpoolPromoted; 3657 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3658 } 3659 3660 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3661 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3662 if (!(GV = GA->getBaseObject())) 3663 return false; 3664 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3665 return V->isConstant(); 3666 return isa<Function>(GV); 3667 } 3668 3669 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3670 SelectionDAG &DAG) const { 3671 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3672 default: llvm_unreachable("unknown object format"); 3673 case Triple::COFF: 3674 return LowerGlobalAddressWindows(Op, DAG); 3675 case Triple::ELF: 3676 return LowerGlobalAddressELF(Op, DAG); 3677 case Triple::MachO: 3678 return LowerGlobalAddressDarwin(Op, DAG); 3679 } 3680 } 3681 3682 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3683 SelectionDAG &DAG) const { 3684 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3685 SDLoc dl(Op); 3686 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3687 const TargetMachine &TM = getTargetMachine(); 3688 bool IsRO = isReadOnly(GV); 3689 3690 // promoteToConstantPool only if not generating XO text section 3691 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3692 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3693 return V; 3694 3695 if (isPositionIndependent()) { 3696 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3697 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3698 UseGOT_PREL ? ARMII::MO_GOT : 0); 3699 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3700 if (UseGOT_PREL) 3701 Result = 3702 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3703 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3704 return Result; 3705 } else if (Subtarget->isROPI() && IsRO) { 3706 // PC-relative. 3707 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3708 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3709 return Result; 3710 } else if (Subtarget->isRWPI() && !IsRO) { 3711 // SB-relative. 3712 SDValue RelAddr; 3713 if (Subtarget->useMovt()) { 3714 ++NumMovwMovt; 3715 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3716 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3717 } else { // use literal pool for address constant 3718 ARMConstantPoolValue *CPV = 3719 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3720 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3721 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3722 RelAddr = DAG.getLoad( 3723 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3724 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3725 } 3726 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3727 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3728 return Result; 3729 } 3730 3731 // If we have T2 ops, we can materialize the address directly via movt/movw 3732 // pair. This is always cheaper. 3733 if (Subtarget->useMovt()) { 3734 ++NumMovwMovt; 3735 // FIXME: Once remat is capable of dealing with instructions with register 3736 // operands, expand this into two nodes. 3737 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3738 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3739 } else { 3740 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4)); 3741 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3742 return DAG.getLoad( 3743 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3744 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3745 } 3746 } 3747 3748 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3749 SelectionDAG &DAG) const { 3750 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3751 "ROPI/RWPI not currently supported for Darwin"); 3752 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3753 SDLoc dl(Op); 3754 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3755 3756 if (Subtarget->useMovt()) 3757 ++NumMovwMovt; 3758 3759 // FIXME: Once remat is capable of dealing with instructions with register 3760 // operands, expand this into multiple nodes 3761 unsigned Wrapper = 3762 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3763 3764 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3765 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3766 3767 if (Subtarget->isGVIndirectSymbol(GV)) 3768 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3769 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3770 return Result; 3771 } 3772 3773 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3774 SelectionDAG &DAG) const { 3775 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3776 assert(Subtarget->useMovt() && 3777 "Windows on ARM expects to use movw/movt"); 3778 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3779 "ROPI/RWPI not currently supported for Windows"); 3780 3781 const TargetMachine &TM = getTargetMachine(); 3782 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3783 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3784 if (GV->hasDLLImportStorageClass()) 3785 TargetFlags = ARMII::MO_DLLIMPORT; 3786 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3787 TargetFlags = ARMII::MO_COFFSTUB; 3788 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3789 SDValue Result; 3790 SDLoc DL(Op); 3791 3792 ++NumMovwMovt; 3793 3794 // FIXME: Once remat is capable of dealing with instructions with register 3795 // operands, expand this into two nodes. 3796 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3797 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3798 TargetFlags)); 3799 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3800 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3801 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3802 return Result; 3803 } 3804 3805 SDValue 3806 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3807 SDLoc dl(Op); 3808 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3809 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3810 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3811 Op.getOperand(1), Val); 3812 } 3813 3814 SDValue 3815 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3816 SDLoc dl(Op); 3817 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3818 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3819 } 3820 3821 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3822 SelectionDAG &DAG) const { 3823 SDLoc dl(Op); 3824 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3825 Op.getOperand(0)); 3826 } 3827 3828 SDValue ARMTargetLowering::LowerINTRINSIC_VOID( 3829 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const { 3830 unsigned IntNo = 3831 cast<ConstantSDNode>( 3832 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other)) 3833 ->getZExtValue(); 3834 switch (IntNo) { 3835 default: 3836 return SDValue(); // Don't custom lower most intrinsics. 3837 case Intrinsic::arm_gnu_eabi_mcount: { 3838 MachineFunction &MF = DAG.getMachineFunction(); 3839 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3840 SDLoc dl(Op); 3841 SDValue Chain = Op.getOperand(0); 3842 // call "\01__gnu_mcount_nc" 3843 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 3844 const uint32_t *Mask = 3845 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 3846 assert(Mask && "Missing call preserved mask for calling convention"); 3847 // Mark LR an implicit live-in. 3848 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 3849 SDValue ReturnAddress = 3850 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT); 3851 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue}; 3852 SDValue Callee = 3853 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0); 3854 SDValue RegisterMask = DAG.getRegisterMask(Mask); 3855 if (Subtarget->isThumb()) 3856 return SDValue( 3857 DAG.getMachineNode( 3858 ARM::tBL_PUSHLR, dl, ResultTys, 3859 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT), 3860 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}), 3861 0); 3862 return SDValue( 3863 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys, 3864 {ReturnAddress, Callee, RegisterMask, Chain}), 3865 0); 3866 } 3867 } 3868 } 3869 3870 SDValue 3871 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3872 const ARMSubtarget *Subtarget) const { 3873 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3874 SDLoc dl(Op); 3875 switch (IntNo) { 3876 default: return SDValue(); // Don't custom lower most intrinsics. 3877 case Intrinsic::thread_pointer: { 3878 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3879 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3880 } 3881 case Intrinsic::arm_cls: { 3882 const SDValue &Operand = Op.getOperand(1); 3883 const EVT VTy = Op.getValueType(); 3884 SDValue SRA = 3885 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy)); 3886 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand); 3887 SDValue SHL = 3888 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy)); 3889 SDValue OR = 3890 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy)); 3891 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR); 3892 return Result; 3893 } 3894 case Intrinsic::arm_cls64: { 3895 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x)) 3896 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x))) 3897 const SDValue &Operand = Op.getOperand(1); 3898 const EVT VTy = Op.getValueType(); 3899 3900 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3901 DAG.getConstant(1, dl, VTy)); 3902 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3903 DAG.getConstant(0, dl, VTy)); 3904 SDValue Constant0 = DAG.getConstant(0, dl, VTy); 3905 SDValue Constant1 = DAG.getConstant(1, dl, VTy); 3906 SDValue Constant31 = DAG.getConstant(31, dl, VTy); 3907 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31); 3908 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi); 3909 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1); 3910 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1); 3911 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi); 3912 SDValue CheckLo = 3913 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ); 3914 SDValue HiIsZero = 3915 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ); 3916 SDValue AdjustedLo = 3917 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy)); 3918 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo); 3919 SDValue Result = 3920 DAG.getSelect(dl, VTy, CheckLo, 3921 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi); 3922 return Result; 3923 } 3924 case Intrinsic::eh_sjlj_lsda: { 3925 MachineFunction &MF = DAG.getMachineFunction(); 3926 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3927 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3928 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3929 SDValue CPAddr; 3930 bool IsPositionIndependent = isPositionIndependent(); 3931 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3932 ARMConstantPoolValue *CPV = 3933 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3934 ARMCP::CPLSDA, PCAdj); 3935 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3936 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3937 SDValue Result = DAG.getLoad( 3938 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3939 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3940 3941 if (IsPositionIndependent) { 3942 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3943 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3944 } 3945 return Result; 3946 } 3947 case Intrinsic::arm_neon_vabs: 3948 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3949 Op.getOperand(1)); 3950 case Intrinsic::arm_neon_vmulls: 3951 case Intrinsic::arm_neon_vmullu: { 3952 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3953 ? ARMISD::VMULLs : ARMISD::VMULLu; 3954 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3955 Op.getOperand(1), Op.getOperand(2)); 3956 } 3957 case Intrinsic::arm_neon_vminnm: 3958 case Intrinsic::arm_neon_vmaxnm: { 3959 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3960 ? ISD::FMINNUM : ISD::FMAXNUM; 3961 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3962 Op.getOperand(1), Op.getOperand(2)); 3963 } 3964 case Intrinsic::arm_neon_vminu: 3965 case Intrinsic::arm_neon_vmaxu: { 3966 if (Op.getValueType().isFloatingPoint()) 3967 return SDValue(); 3968 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3969 ? ISD::UMIN : ISD::UMAX; 3970 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3971 Op.getOperand(1), Op.getOperand(2)); 3972 } 3973 case Intrinsic::arm_neon_vmins: 3974 case Intrinsic::arm_neon_vmaxs: { 3975 // v{min,max}s is overloaded between signed integers and floats. 3976 if (!Op.getValueType().isFloatingPoint()) { 3977 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3978 ? ISD::SMIN : ISD::SMAX; 3979 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3980 Op.getOperand(1), Op.getOperand(2)); 3981 } 3982 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3983 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3984 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3985 Op.getOperand(1), Op.getOperand(2)); 3986 } 3987 case Intrinsic::arm_neon_vtbl1: 3988 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3989 Op.getOperand(1), Op.getOperand(2)); 3990 case Intrinsic::arm_neon_vtbl2: 3991 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3992 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3993 case Intrinsic::arm_mve_pred_i2v: 3994 case Intrinsic::arm_mve_pred_v2i: 3995 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(), 3996 Op.getOperand(1)); 3997 case Intrinsic::arm_mve_vreinterpretq: 3998 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(), 3999 Op.getOperand(1)); 4000 case Intrinsic::arm_mve_lsll: 4001 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(), 4002 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4003 case Intrinsic::arm_mve_asrl: 4004 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(), 4005 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4006 } 4007 } 4008 4009 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 4010 const ARMSubtarget *Subtarget) { 4011 SDLoc dl(Op); 4012 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 4013 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 4014 if (SSID == SyncScope::SingleThread) 4015 return Op; 4016 4017 if (!Subtarget->hasDataBarrier()) { 4018 // Some ARMv6 cpus can support data barriers with an mcr instruction. 4019 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 4020 // here. 4021 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 4022 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 4023 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 4024 DAG.getConstant(0, dl, MVT::i32)); 4025 } 4026 4027 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 4028 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 4029 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 4030 if (Subtarget->isMClass()) { 4031 // Only a full system barrier exists in the M-class architectures. 4032 Domain = ARM_MB::SY; 4033 } else if (Subtarget->preferISHSTBarriers() && 4034 Ord == AtomicOrdering::Release) { 4035 // Swift happens to implement ISHST barriers in a way that's compatible with 4036 // Release semantics but weaker than ISH so we'd be fools not to use 4037 // it. Beware: other processors probably don't! 4038 Domain = ARM_MB::ISHST; 4039 } 4040 4041 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 4042 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 4043 DAG.getConstant(Domain, dl, MVT::i32)); 4044 } 4045 4046 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 4047 const ARMSubtarget *Subtarget) { 4048 // ARM pre v5TE and Thumb1 does not have preload instructions. 4049 if (!(Subtarget->isThumb2() || 4050 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 4051 // Just preserve the chain. 4052 return Op.getOperand(0); 4053 4054 SDLoc dl(Op); 4055 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 4056 if (!isRead && 4057 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 4058 // ARMv7 with MP extension has PLDW. 4059 return Op.getOperand(0); 4060 4061 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 4062 if (Subtarget->isThumb()) { 4063 // Invert the bits. 4064 isRead = ~isRead & 1; 4065 isData = ~isData & 1; 4066 } 4067 4068 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 4069 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 4070 DAG.getConstant(isData, dl, MVT::i32)); 4071 } 4072 4073 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 4074 MachineFunction &MF = DAG.getMachineFunction(); 4075 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 4076 4077 // vastart just stores the address of the VarArgsFrameIndex slot into the 4078 // memory location argument. 4079 SDLoc dl(Op); 4080 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4081 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4082 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4083 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 4084 MachinePointerInfo(SV)); 4085 } 4086 4087 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 4088 CCValAssign &NextVA, 4089 SDValue &Root, 4090 SelectionDAG &DAG, 4091 const SDLoc &dl) const { 4092 MachineFunction &MF = DAG.getMachineFunction(); 4093 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4094 4095 const TargetRegisterClass *RC; 4096 if (AFI->isThumb1OnlyFunction()) 4097 RC = &ARM::tGPRRegClass; 4098 else 4099 RC = &ARM::GPRRegClass; 4100 4101 // Transform the arguments stored in physical registers into virtual ones. 4102 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4103 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 4104 4105 SDValue ArgValue2; 4106 if (NextVA.isMemLoc()) { 4107 MachineFrameInfo &MFI = MF.getFrameInfo(); 4108 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 4109 4110 // Create load node to retrieve arguments from the stack. 4111 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4112 ArgValue2 = DAG.getLoad( 4113 MVT::i32, dl, Root, FIN, 4114 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4115 } else { 4116 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 4117 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 4118 } 4119 if (!Subtarget->isLittle()) 4120 std::swap (ArgValue, ArgValue2); 4121 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 4122 } 4123 4124 // The remaining GPRs hold either the beginning of variable-argument 4125 // data, or the beginning of an aggregate passed by value (usually 4126 // byval). Either way, we allocate stack slots adjacent to the data 4127 // provided by our caller, and store the unallocated registers there. 4128 // If this is a variadic function, the va_list pointer will begin with 4129 // these values; otherwise, this reassembles a (byval) structure that 4130 // was split between registers and memory. 4131 // Return: The frame index registers were stored into. 4132 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 4133 const SDLoc &dl, SDValue &Chain, 4134 const Value *OrigArg, 4135 unsigned InRegsParamRecordIdx, 4136 int ArgOffset, unsigned ArgSize) const { 4137 // Currently, two use-cases possible: 4138 // Case #1. Non-var-args function, and we meet first byval parameter. 4139 // Setup first unallocated register as first byval register; 4140 // eat all remained registers 4141 // (these two actions are performed by HandleByVal method). 4142 // Then, here, we initialize stack frame with 4143 // "store-reg" instructions. 4144 // Case #2. Var-args function, that doesn't contain byval parameters. 4145 // The same: eat all remained unallocated registers, 4146 // initialize stack frame. 4147 4148 MachineFunction &MF = DAG.getMachineFunction(); 4149 MachineFrameInfo &MFI = MF.getFrameInfo(); 4150 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4151 unsigned RBegin, REnd; 4152 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 4153 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 4154 } else { 4155 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4156 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 4157 REnd = ARM::R4; 4158 } 4159 4160 if (REnd != RBegin) 4161 ArgOffset = -4 * (ARM::R4 - RBegin); 4162 4163 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4164 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 4165 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 4166 4167 SmallVector<SDValue, 4> MemOps; 4168 const TargetRegisterClass *RC = 4169 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 4170 4171 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 4172 unsigned VReg = MF.addLiveIn(Reg, RC); 4173 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4174 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4175 MachinePointerInfo(OrigArg, 4 * i)); 4176 MemOps.push_back(Store); 4177 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 4178 } 4179 4180 if (!MemOps.empty()) 4181 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4182 return FrameIndex; 4183 } 4184 4185 // Setup stack frame, the va_list pointer will start from. 4186 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 4187 const SDLoc &dl, SDValue &Chain, 4188 unsigned ArgOffset, 4189 unsigned TotalArgRegsSaveSize, 4190 bool ForceMutable) const { 4191 MachineFunction &MF = DAG.getMachineFunction(); 4192 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4193 4194 // Try to store any remaining integer argument regs 4195 // to their spots on the stack so that they may be loaded by dereferencing 4196 // the result of va_next. 4197 // If there is no regs to be stored, just point address after last 4198 // argument passed via stack. 4199 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 4200 CCInfo.getInRegsParamsCount(), 4201 CCInfo.getNextStackOffset(), 4202 std::max(4U, TotalArgRegsSaveSize)); 4203 AFI->setVarArgsFrameIndex(FrameIndex); 4204 } 4205 4206 bool ARMTargetLowering::splitValueIntoRegisterParts( 4207 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 4208 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 4209 bool IsABIRegCopy = CC.hasValue(); 4210 EVT ValueVT = Val.getValueType(); 4211 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) && 4212 PartVT == MVT::f32) { 4213 unsigned ValueBits = ValueVT.getSizeInBits(); 4214 unsigned PartBits = PartVT.getSizeInBits(); 4215 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val); 4216 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val); 4217 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 4218 Parts[0] = Val; 4219 return true; 4220 } 4221 return false; 4222 } 4223 4224 SDValue ARMTargetLowering::joinRegisterPartsIntoValue( 4225 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 4226 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 4227 bool IsABIRegCopy = CC.hasValue(); 4228 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) && 4229 PartVT == MVT::f32) { 4230 unsigned ValueBits = ValueVT.getSizeInBits(); 4231 unsigned PartBits = PartVT.getSizeInBits(); 4232 SDValue Val = Parts[0]; 4233 4234 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val); 4235 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val); 4236 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 4237 return Val; 4238 } 4239 return SDValue(); 4240 } 4241 4242 SDValue ARMTargetLowering::LowerFormalArguments( 4243 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4244 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4245 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4246 MachineFunction &MF = DAG.getMachineFunction(); 4247 MachineFrameInfo &MFI = MF.getFrameInfo(); 4248 4249 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4250 4251 // Assign locations to all of the incoming arguments. 4252 SmallVector<CCValAssign, 16> ArgLocs; 4253 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4254 *DAG.getContext()); 4255 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 4256 4257 SmallVector<SDValue, 16> ArgValues; 4258 SDValue ArgValue; 4259 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 4260 unsigned CurArgIdx = 0; 4261 4262 // Initially ArgRegsSaveSize is zero. 4263 // Then we increase this value each time we meet byval parameter. 4264 // We also increase this value in case of varargs function. 4265 AFI->setArgRegsSaveSize(0); 4266 4267 // Calculate the amount of stack space that we need to allocate to store 4268 // byval and variadic arguments that are passed in registers. 4269 // We need to know this before we allocate the first byval or variadic 4270 // argument, as they will be allocated a stack slot below the CFA (Canonical 4271 // Frame Address, the stack pointer at entry to the function). 4272 unsigned ArgRegBegin = ARM::R4; 4273 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4274 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 4275 break; 4276 4277 CCValAssign &VA = ArgLocs[i]; 4278 unsigned Index = VA.getValNo(); 4279 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 4280 if (!Flags.isByVal()) 4281 continue; 4282 4283 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 4284 unsigned RBegin, REnd; 4285 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 4286 ArgRegBegin = std::min(ArgRegBegin, RBegin); 4287 4288 CCInfo.nextInRegsParam(); 4289 } 4290 CCInfo.rewindByValRegsInfo(); 4291 4292 int lastInsIndex = -1; 4293 if (isVarArg && MFI.hasVAStart()) { 4294 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4295 if (RegIdx != array_lengthof(GPRArgRegs)) 4296 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 4297 } 4298 4299 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 4300 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 4301 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4302 4303 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4304 CCValAssign &VA = ArgLocs[i]; 4305 if (Ins[VA.getValNo()].isOrigArg()) { 4306 std::advance(CurOrigArg, 4307 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 4308 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 4309 } 4310 // Arguments stored in registers. 4311 if (VA.isRegLoc()) { 4312 EVT RegVT = VA.getLocVT(); 4313 4314 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) { 4315 // f64 and vector types are split up into multiple registers or 4316 // combinations of registers and stack slots. 4317 SDValue ArgValue1 = 4318 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4319 VA = ArgLocs[++i]; // skip ahead to next loc 4320 SDValue ArgValue2; 4321 if (VA.isMemLoc()) { 4322 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 4323 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4324 ArgValue2 = DAG.getLoad( 4325 MVT::f64, dl, Chain, FIN, 4326 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4327 } else { 4328 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4329 } 4330 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 4331 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue, 4332 ArgValue1, DAG.getIntPtrConstant(0, dl)); 4333 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue, 4334 ArgValue2, DAG.getIntPtrConstant(1, dl)); 4335 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) { 4336 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4337 } else { 4338 const TargetRegisterClass *RC; 4339 4340 if (RegVT == MVT::f16 || RegVT == MVT::bf16) 4341 RC = &ARM::HPRRegClass; 4342 else if (RegVT == MVT::f32) 4343 RC = &ARM::SPRRegClass; 4344 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 || 4345 RegVT == MVT::v4bf16) 4346 RC = &ARM::DPRRegClass; 4347 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 || 4348 RegVT == MVT::v8bf16) 4349 RC = &ARM::QPRRegClass; 4350 else if (RegVT == MVT::i32) 4351 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 4352 : &ARM::GPRRegClass; 4353 else 4354 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4355 4356 // Transform the arguments in physical registers into virtual ones. 4357 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4358 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 4359 4360 // If this value is passed in r0 and has the returned attribute (e.g. 4361 // C++ 'structors), record this fact for later use. 4362 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 4363 AFI->setPreservesR0(); 4364 } 4365 } 4366 4367 // If this is an 8 or 16-bit value, it is really passed promoted 4368 // to 32 bits. Insert an assert[sz]ext to capture this, then 4369 // truncate to the right size. 4370 switch (VA.getLocInfo()) { 4371 default: llvm_unreachable("Unknown loc info!"); 4372 case CCValAssign::Full: break; 4373 case CCValAssign::BCvt: 4374 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 4375 break; 4376 case CCValAssign::SExt: 4377 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 4378 DAG.getValueType(VA.getValVT())); 4379 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4380 break; 4381 case CCValAssign::ZExt: 4382 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 4383 DAG.getValueType(VA.getValVT())); 4384 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4385 break; 4386 } 4387 4388 // f16 arguments have their size extended to 4 bytes and passed as if they 4389 // had been copied to the LSBs of a 32-bit register. 4390 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 4391 if (VA.needsCustom() && 4392 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) 4393 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue); 4394 4395 InVals.push_back(ArgValue); 4396 } else { // VA.isRegLoc() 4397 // sanity check 4398 assert(VA.isMemLoc()); 4399 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 4400 4401 int index = VA.getValNo(); 4402 4403 // Some Ins[] entries become multiple ArgLoc[] entries. 4404 // Process them only once. 4405 if (index != lastInsIndex) 4406 { 4407 ISD::ArgFlagsTy Flags = Ins[index].Flags; 4408 // FIXME: For now, all byval parameter objects are marked mutable. 4409 // This can be changed with more analysis. 4410 // In case of tail call optimization mark all arguments mutable. 4411 // Since they could be overwritten by lowering of arguments in case of 4412 // a tail call. 4413 if (Flags.isByVal()) { 4414 assert(Ins[index].isOrigArg() && 4415 "Byval arguments cannot be implicit"); 4416 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 4417 4418 int FrameIndex = StoreByValRegs( 4419 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 4420 VA.getLocMemOffset(), Flags.getByValSize()); 4421 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 4422 CCInfo.nextInRegsParam(); 4423 } else { 4424 unsigned FIOffset = VA.getLocMemOffset(); 4425 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 4426 FIOffset, true); 4427 4428 // Create load nodes to retrieve arguments from the stack. 4429 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4430 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 4431 MachinePointerInfo::getFixedStack( 4432 DAG.getMachineFunction(), FI))); 4433 } 4434 lastInsIndex = index; 4435 } 4436 } 4437 } 4438 4439 // varargs 4440 if (isVarArg && MFI.hasVAStart()) { 4441 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(), 4442 TotalArgRegsSaveSize); 4443 if (AFI->isCmseNSEntryFunction()) { 4444 DiagnosticInfoUnsupported Diag( 4445 DAG.getMachineFunction().getFunction(), 4446 "secure entry function must not be variadic", dl.getDebugLoc()); 4447 DAG.getContext()->diagnose(Diag); 4448 } 4449 } 4450 4451 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4452 4453 if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) { 4454 DiagnosticInfoUnsupported Diag( 4455 DAG.getMachineFunction().getFunction(), 4456 "secure entry function requires arguments on stack", dl.getDebugLoc()); 4457 DAG.getContext()->diagnose(Diag); 4458 } 4459 4460 return Chain; 4461 } 4462 4463 /// isFloatingPointZero - Return true if this is +0.0. 4464 static bool isFloatingPointZero(SDValue Op) { 4465 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4466 return CFP->getValueAPF().isPosZero(); 4467 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4468 // Maybe this has already been legalized into the constant pool? 4469 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4470 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4471 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4472 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4473 return CFP->getValueAPF().isPosZero(); 4474 } 4475 } else if (Op->getOpcode() == ISD::BITCAST && 4476 Op->getValueType(0) == MVT::f64) { 4477 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4478 // created by LowerConstantFP(). 4479 SDValue BitcastOp = Op->getOperand(0); 4480 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4481 isNullConstant(BitcastOp->getOperand(0))) 4482 return true; 4483 } 4484 return false; 4485 } 4486 4487 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4488 /// the given operands. 4489 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4490 SDValue &ARMcc, SelectionDAG &DAG, 4491 const SDLoc &dl) const { 4492 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4493 unsigned C = RHSC->getZExtValue(); 4494 if (!isLegalICmpImmediate((int32_t)C)) { 4495 // Constant does not fit, try adjusting it by one. 4496 switch (CC) { 4497 default: break; 4498 case ISD::SETLT: 4499 case ISD::SETGE: 4500 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4501 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4502 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4503 } 4504 break; 4505 case ISD::SETULT: 4506 case ISD::SETUGE: 4507 if (C != 0 && isLegalICmpImmediate(C-1)) { 4508 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4509 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4510 } 4511 break; 4512 case ISD::SETLE: 4513 case ISD::SETGT: 4514 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4515 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4516 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4517 } 4518 break; 4519 case ISD::SETULE: 4520 case ISD::SETUGT: 4521 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4522 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4523 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4524 } 4525 break; 4526 } 4527 } 4528 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4529 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4530 // In ARM and Thumb-2, the compare instructions can shift their second 4531 // operand. 4532 CC = ISD::getSetCCSwappedOperands(CC); 4533 std::swap(LHS, RHS); 4534 } 4535 4536 // Thumb1 has very limited immediate modes, so turning an "and" into a 4537 // shift can save multiple instructions. 4538 // 4539 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4540 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4541 // own. If it's the operand to an unsigned comparison with an immediate, 4542 // we can eliminate one of the shifts: we transform 4543 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4544 // 4545 // We avoid transforming cases which aren't profitable due to encoding 4546 // details: 4547 // 4548 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4549 // would not; in that case, we're essentially trading one immediate load for 4550 // another. 4551 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4552 // 3. C2 is zero; we have other code for this special case. 4553 // 4554 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4555 // instruction, since the AND is always one instruction anyway, but we could 4556 // use narrow instructions in some cases. 4557 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4558 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4559 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4560 !isSignedIntSetCC(CC)) { 4561 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4562 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4563 uint64_t RHSV = RHSC->getZExtValue(); 4564 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4565 unsigned ShiftBits = countLeadingZeros(Mask); 4566 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4567 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4568 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4569 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4570 } 4571 } 4572 } 4573 4574 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4575 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4576 // way a cmp would. 4577 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4578 // some tweaks to the heuristics for the previous and->shift transform. 4579 // FIXME: Optimize cases where the LHS isn't a shift. 4580 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4581 isa<ConstantSDNode>(RHS) && 4582 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4583 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4584 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4585 unsigned ShiftAmt = 4586 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4587 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4588 DAG.getVTList(MVT::i32, MVT::i32), 4589 LHS.getOperand(0), 4590 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4591 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4592 Shift.getValue(1), SDValue()); 4593 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4594 return Chain.getValue(1); 4595 } 4596 4597 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4598 4599 // If the RHS is a constant zero then the V (overflow) flag will never be 4600 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4601 // simpler for other passes (like the peephole optimiser) to deal with. 4602 if (isNullConstant(RHS)) { 4603 switch (CondCode) { 4604 default: break; 4605 case ARMCC::GE: 4606 CondCode = ARMCC::PL; 4607 break; 4608 case ARMCC::LT: 4609 CondCode = ARMCC::MI; 4610 break; 4611 } 4612 } 4613 4614 ARMISD::NodeType CompareType; 4615 switch (CondCode) { 4616 default: 4617 CompareType = ARMISD::CMP; 4618 break; 4619 case ARMCC::EQ: 4620 case ARMCC::NE: 4621 // Uses only Z Flag 4622 CompareType = ARMISD::CMPZ; 4623 break; 4624 } 4625 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4626 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4627 } 4628 4629 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4630 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4631 SelectionDAG &DAG, const SDLoc &dl, 4632 bool Signaling) const { 4633 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4634 SDValue Cmp; 4635 if (!isFloatingPointZero(RHS)) 4636 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, 4637 dl, MVT::Glue, LHS, RHS); 4638 else 4639 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, 4640 dl, MVT::Glue, LHS); 4641 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4642 } 4643 4644 /// duplicateCmp - Glue values can have only one use, so this function 4645 /// duplicates a comparison node. 4646 SDValue 4647 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4648 unsigned Opc = Cmp.getOpcode(); 4649 SDLoc DL(Cmp); 4650 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4651 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4652 4653 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4654 Cmp = Cmp.getOperand(0); 4655 Opc = Cmp.getOpcode(); 4656 if (Opc == ARMISD::CMPFP) 4657 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4658 else { 4659 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4660 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 4661 } 4662 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4663 } 4664 4665 // This function returns three things: the arithmetic computation itself 4666 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4667 // comparison and the condition code define the case in which the arithmetic 4668 // computation *does not* overflow. 4669 std::pair<SDValue, SDValue> 4670 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4671 SDValue &ARMcc) const { 4672 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4673 4674 SDValue Value, OverflowCmp; 4675 SDValue LHS = Op.getOperand(0); 4676 SDValue RHS = Op.getOperand(1); 4677 SDLoc dl(Op); 4678 4679 // FIXME: We are currently always generating CMPs because we don't support 4680 // generating CMN through the backend. This is not as good as the natural 4681 // CMP case because it causes a register dependency and cannot be folded 4682 // later. 4683 4684 switch (Op.getOpcode()) { 4685 default: 4686 llvm_unreachable("Unknown overflow instruction!"); 4687 case ISD::SADDO: 4688 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4689 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4690 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4691 break; 4692 case ISD::UADDO: 4693 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4694 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4695 // We do not use it in the USUBO case as Value may not be used. 4696 Value = DAG.getNode(ARMISD::ADDC, dl, 4697 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4698 .getValue(0); 4699 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4700 break; 4701 case ISD::SSUBO: 4702 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4703 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4704 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4705 break; 4706 case ISD::USUBO: 4707 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4708 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4709 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4710 break; 4711 case ISD::UMULO: 4712 // We generate a UMUL_LOHI and then check if the high word is 0. 4713 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4714 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4715 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4716 LHS, RHS); 4717 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4718 DAG.getConstant(0, dl, MVT::i32)); 4719 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4720 break; 4721 case ISD::SMULO: 4722 // We generate a SMUL_LOHI and then check if all the bits of the high word 4723 // are the same as the sign bit of the low word. 4724 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4725 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4726 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4727 LHS, RHS); 4728 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4729 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4730 Value.getValue(0), 4731 DAG.getConstant(31, dl, MVT::i32))); 4732 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4733 break; 4734 } // switch (...) 4735 4736 return std::make_pair(Value, OverflowCmp); 4737 } 4738 4739 SDValue 4740 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4741 // Let legalize expand this if it isn't a legal type yet. 4742 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4743 return SDValue(); 4744 4745 SDValue Value, OverflowCmp; 4746 SDValue ARMcc; 4747 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4748 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4749 SDLoc dl(Op); 4750 // We use 0 and 1 as false and true values. 4751 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4752 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4753 EVT VT = Op.getValueType(); 4754 4755 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4756 ARMcc, CCR, OverflowCmp); 4757 4758 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4759 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4760 } 4761 4762 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4763 SelectionDAG &DAG) { 4764 SDLoc DL(BoolCarry); 4765 EVT CarryVT = BoolCarry.getValueType(); 4766 4767 // This converts the boolean value carry into the carry flag by doing 4768 // ARMISD::SUBC Carry, 1 4769 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4770 DAG.getVTList(CarryVT, MVT::i32), 4771 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4772 return Carry.getValue(1); 4773 } 4774 4775 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4776 SelectionDAG &DAG) { 4777 SDLoc DL(Flags); 4778 4779 // Now convert the carry flag into a boolean carry. We do this 4780 // using ARMISD:ADDE 0, 0, Carry 4781 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4782 DAG.getConstant(0, DL, MVT::i32), 4783 DAG.getConstant(0, DL, MVT::i32), Flags); 4784 } 4785 4786 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4787 SelectionDAG &DAG) const { 4788 // Let legalize expand this if it isn't a legal type yet. 4789 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4790 return SDValue(); 4791 4792 SDValue LHS = Op.getOperand(0); 4793 SDValue RHS = Op.getOperand(1); 4794 SDLoc dl(Op); 4795 4796 EVT VT = Op.getValueType(); 4797 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4798 SDValue Value; 4799 SDValue Overflow; 4800 switch (Op.getOpcode()) { 4801 default: 4802 llvm_unreachable("Unknown overflow instruction!"); 4803 case ISD::UADDO: 4804 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4805 // Convert the carry flag into a boolean value. 4806 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4807 break; 4808 case ISD::USUBO: { 4809 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4810 // Convert the carry flag into a boolean value. 4811 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4812 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4813 // value. So compute 1 - C. 4814 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4815 DAG.getConstant(1, dl, MVT::i32), Overflow); 4816 break; 4817 } 4818 } 4819 4820 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4821 } 4822 4823 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG, 4824 const ARMSubtarget *Subtarget) { 4825 EVT VT = Op.getValueType(); 4826 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 4827 return SDValue(); 4828 if (!VT.isSimple()) 4829 return SDValue(); 4830 4831 unsigned NewOpcode; 4832 bool IsAdd = Op->getOpcode() == ISD::SADDSAT; 4833 switch (VT.getSimpleVT().SimpleTy) { 4834 default: 4835 return SDValue(); 4836 case MVT::i8: 4837 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b; 4838 break; 4839 case MVT::i16: 4840 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b; 4841 break; 4842 } 4843 4844 SDLoc dl(Op); 4845 SDValue Add = 4846 DAG.getNode(NewOpcode, dl, MVT::i32, 4847 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32), 4848 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32)); 4849 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add); 4850 } 4851 4852 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4853 SDValue Cond = Op.getOperand(0); 4854 SDValue SelectTrue = Op.getOperand(1); 4855 SDValue SelectFalse = Op.getOperand(2); 4856 SDLoc dl(Op); 4857 unsigned Opc = Cond.getOpcode(); 4858 4859 if (Cond.getResNo() == 1 && 4860 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4861 Opc == ISD::USUBO)) { 4862 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4863 return SDValue(); 4864 4865 SDValue Value, OverflowCmp; 4866 SDValue ARMcc; 4867 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4868 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4869 EVT VT = Op.getValueType(); 4870 4871 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4872 OverflowCmp, DAG); 4873 } 4874 4875 // Convert: 4876 // 4877 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4878 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4879 // 4880 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4881 const ConstantSDNode *CMOVTrue = 4882 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4883 const ConstantSDNode *CMOVFalse = 4884 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4885 4886 if (CMOVTrue && CMOVFalse) { 4887 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4888 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4889 4890 SDValue True; 4891 SDValue False; 4892 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4893 True = SelectTrue; 4894 False = SelectFalse; 4895 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4896 True = SelectFalse; 4897 False = SelectTrue; 4898 } 4899 4900 if (True.getNode() && False.getNode()) { 4901 EVT VT = Op.getValueType(); 4902 SDValue ARMcc = Cond.getOperand(2); 4903 SDValue CCR = Cond.getOperand(3); 4904 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4905 assert(True.getValueType() == VT); 4906 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4907 } 4908 } 4909 } 4910 4911 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4912 // undefined bits before doing a full-word comparison with zero. 4913 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4914 DAG.getConstant(1, dl, Cond.getValueType())); 4915 4916 return DAG.getSelectCC(dl, Cond, 4917 DAG.getConstant(0, dl, Cond.getValueType()), 4918 SelectTrue, SelectFalse, ISD::SETNE); 4919 } 4920 4921 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4922 bool &swpCmpOps, bool &swpVselOps) { 4923 // Start by selecting the GE condition code for opcodes that return true for 4924 // 'equality' 4925 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4926 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4927 CondCode = ARMCC::GE; 4928 4929 // and GT for opcodes that return false for 'equality'. 4930 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4931 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4932 CondCode = ARMCC::GT; 4933 4934 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4935 // to swap the compare operands. 4936 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4937 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4938 swpCmpOps = true; 4939 4940 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4941 // If we have an unordered opcode, we need to swap the operands to the VSEL 4942 // instruction (effectively negating the condition). 4943 // 4944 // This also has the effect of swapping which one of 'less' or 'greater' 4945 // returns true, so we also swap the compare operands. It also switches 4946 // whether we return true for 'equality', so we compensate by picking the 4947 // opposite condition code to our original choice. 4948 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4949 CC == ISD::SETUGT) { 4950 swpCmpOps = !swpCmpOps; 4951 swpVselOps = !swpVselOps; 4952 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4953 } 4954 4955 // 'ordered' is 'anything but unordered', so use the VS condition code and 4956 // swap the VSEL operands. 4957 if (CC == ISD::SETO) { 4958 CondCode = ARMCC::VS; 4959 swpVselOps = true; 4960 } 4961 4962 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4963 // code and swap the VSEL operands. Also do this if we don't care about the 4964 // unordered case. 4965 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4966 CondCode = ARMCC::EQ; 4967 swpVselOps = true; 4968 } 4969 } 4970 4971 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4972 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4973 SDValue Cmp, SelectionDAG &DAG) const { 4974 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4975 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4976 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4977 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4978 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4979 4980 SDValue TrueLow = TrueVal.getValue(0); 4981 SDValue TrueHigh = TrueVal.getValue(1); 4982 SDValue FalseLow = FalseVal.getValue(0); 4983 SDValue FalseHigh = FalseVal.getValue(1); 4984 4985 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4986 ARMcc, CCR, Cmp); 4987 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4988 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4989 4990 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4991 } else { 4992 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4993 Cmp); 4994 } 4995 } 4996 4997 static bool isGTorGE(ISD::CondCode CC) { 4998 return CC == ISD::SETGT || CC == ISD::SETGE; 4999 } 5000 5001 static bool isLTorLE(ISD::CondCode CC) { 5002 return CC == ISD::SETLT || CC == ISD::SETLE; 5003 } 5004 5005 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 5006 // All of these conditions (and their <= and >= counterparts) will do: 5007 // x < k ? k : x 5008 // x > k ? x : k 5009 // k < x ? x : k 5010 // k > x ? k : x 5011 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 5012 const SDValue TrueVal, const SDValue FalseVal, 5013 const ISD::CondCode CC, const SDValue K) { 5014 return (isGTorGE(CC) && 5015 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 5016 (isLTorLE(CC) && 5017 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 5018 } 5019 5020 // Check if two chained conditionals could be converted into SSAT or USAT. 5021 // 5022 // SSAT can replace a set of two conditional selectors that bound a number to an 5023 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 5024 // 5025 // x < -k ? -k : (x > k ? k : x) 5026 // x < -k ? -k : (x < k ? x : k) 5027 // x > -k ? (x > k ? k : x) : -k 5028 // x < k ? (x < -k ? -k : x) : k 5029 // etc. 5030 // 5031 // LLVM canonicalizes these to either a min(max()) or a max(min()) 5032 // pattern. This function tries to match one of these and will return true 5033 // if successful. 5034 // 5035 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 5036 // a power of 2. 5037 // 5038 // It returns true if the conversion can be done, false otherwise. 5039 // Additionally, the variable is returned in parameter V, the constant in K and 5040 // usat is set to true if the conditional represents an unsigned saturation 5041 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 5042 uint64_t &K, bool &Usat) { 5043 SDValue V1 = Op.getOperand(0); 5044 SDValue K1 = Op.getOperand(1); 5045 SDValue TrueVal1 = Op.getOperand(2); 5046 SDValue FalseVal1 = Op.getOperand(3); 5047 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5048 5049 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 5050 if (Op2.getOpcode() != ISD::SELECT_CC) 5051 return false; 5052 5053 SDValue V2 = Op2.getOperand(0); 5054 SDValue K2 = Op2.getOperand(1); 5055 SDValue TrueVal2 = Op2.getOperand(2); 5056 SDValue FalseVal2 = Op2.getOperand(3); 5057 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 5058 5059 SDValue V1Tmp = V1; 5060 SDValue V2Tmp = V2; 5061 5062 if (V1.getOpcode() == ISD::SIGN_EXTEND_INREG && 5063 V2.getOpcode() == ISD::SIGN_EXTEND_INREG) { 5064 V1Tmp = V1.getOperand(0); 5065 V2Tmp = V2.getOperand(0); 5066 } 5067 5068 // Check that the registers and the constants match a max(min()) or min(max()) 5069 // pattern 5070 if (V1Tmp == TrueVal1 && V2Tmp == TrueVal2 && K1 == FalseVal1 && 5071 K2 == FalseVal2 && 5072 ((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2)))) { 5073 5074 // Check that the constant in the lower-bound check is 5075 // the opposite of the constant in the upper-bound check 5076 // in 1's complement. 5077 if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2)) 5078 return false; 5079 5080 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue(); 5081 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue(); 5082 int64_t PosVal = std::max(Val1, Val2); 5083 int64_t NegVal = std::min(Val1, Val2); 5084 5085 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) || 5086 !isPowerOf2_64(PosVal + 1)) 5087 return false; 5088 5089 // Handle the difference between USAT (unsigned) and SSAT (signed) 5090 // saturation 5091 if (Val1 == ~Val2) 5092 Usat = false; 5093 else if (NegVal == 0) 5094 Usat = true; 5095 else 5096 return false; 5097 5098 V = V2Tmp; 5099 // At this point, PosVal is guaranteed to be positive 5100 K = (uint64_t) PosVal; 5101 5102 return true; 5103 } 5104 return false; 5105 } 5106 5107 // Check if a condition of the type x < k ? k : x can be converted into a 5108 // bit operation instead of conditional moves. 5109 // Currently this is allowed given: 5110 // - The conditions and values match up 5111 // - k is 0 or -1 (all ones) 5112 // This function will not check the last condition, thats up to the caller 5113 // It returns true if the transformation can be made, and in such case 5114 // returns x in V, and k in SatK. 5115 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 5116 SDValue &SatK) 5117 { 5118 SDValue LHS = Op.getOperand(0); 5119 SDValue RHS = Op.getOperand(1); 5120 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5121 SDValue TrueVal = Op.getOperand(2); 5122 SDValue FalseVal = Op.getOperand(3); 5123 5124 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 5125 ? &RHS 5126 : nullptr; 5127 5128 // No constant operation in comparison, early out 5129 if (!K) 5130 return false; 5131 5132 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 5133 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 5134 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 5135 5136 // If the constant on left and right side, or variable on left and right, 5137 // does not match, early out 5138 if (*K != KTmp || V != VTmp) 5139 return false; 5140 5141 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 5142 SatK = *K; 5143 return true; 5144 } 5145 5146 return false; 5147 } 5148 5149 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 5150 if (VT == MVT::f32) 5151 return !Subtarget->hasVFP2Base(); 5152 if (VT == MVT::f64) 5153 return !Subtarget->hasFP64(); 5154 if (VT == MVT::f16) 5155 return !Subtarget->hasFullFP16(); 5156 return false; 5157 } 5158 5159 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 5160 EVT VT = Op.getValueType(); 5161 SDLoc dl(Op); 5162 5163 // Try to convert two saturating conditional selects into a single SSAT 5164 SDValue SatValue; 5165 uint64_t SatConstant; 5166 bool SatUSat; 5167 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 5168 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 5169 if (SatUSat) 5170 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 5171 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 5172 else 5173 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 5174 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 5175 } 5176 5177 // Try to convert expressions of the form x < k ? k : x (and similar forms) 5178 // into more efficient bit operations, which is possible when k is 0 or -1 5179 // On ARM and Thumb-2 which have flexible operand 2 this will result in 5180 // single instructions. On Thumb the shift and the bit operation will be two 5181 // instructions. 5182 // Only allow this transformation on full-width (32-bit) operations 5183 SDValue LowerSatConstant; 5184 if (VT == MVT::i32 && 5185 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 5186 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 5187 DAG.getConstant(31, dl, VT)); 5188 if (isNullConstant(LowerSatConstant)) { 5189 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 5190 DAG.getAllOnesConstant(dl, VT)); 5191 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 5192 } else if (isAllOnesConstant(LowerSatConstant)) 5193 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 5194 } 5195 5196 SDValue LHS = Op.getOperand(0); 5197 SDValue RHS = Op.getOperand(1); 5198 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5199 SDValue TrueVal = Op.getOperand(2); 5200 SDValue FalseVal = Op.getOperand(3); 5201 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal); 5202 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal); 5203 5204 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal && 5205 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) { 5206 unsigned TVal = CTVal->getZExtValue(); 5207 unsigned FVal = CFVal->getZExtValue(); 5208 unsigned Opcode = 0; 5209 5210 if (TVal == ~FVal) { 5211 Opcode = ARMISD::CSINV; 5212 } else if (TVal == ~FVal + 1) { 5213 Opcode = ARMISD::CSNEG; 5214 } else if (TVal + 1 == FVal) { 5215 Opcode = ARMISD::CSINC; 5216 } else if (TVal == FVal + 1) { 5217 Opcode = ARMISD::CSINC; 5218 std::swap(TrueVal, FalseVal); 5219 std::swap(TVal, FVal); 5220 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5221 } 5222 5223 if (Opcode) { 5224 // If one of the constants is cheaper than another, materialise the 5225 // cheaper one and let the csel generate the other. 5226 if (Opcode != ARMISD::CSINC && 5227 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) { 5228 std::swap(TrueVal, FalseVal); 5229 std::swap(TVal, FVal); 5230 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5231 } 5232 5233 // Attempt to use ZR checking TVal is 0, possibly inverting the condition 5234 // to get there. CSINC not is invertable like the other two (~(~a) == a, 5235 // -(-a) == a, but (a+1)+1 != a). 5236 if (FVal == 0 && Opcode != ARMISD::CSINC) { 5237 std::swap(TrueVal, FalseVal); 5238 std::swap(TVal, FVal); 5239 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5240 } 5241 if (TVal == 0) 5242 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32); 5243 5244 // Drops F's value because we can get it by inverting/negating TVal. 5245 FalseVal = TrueVal; 5246 5247 SDValue ARMcc; 5248 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5249 EVT VT = TrueVal.getValueType(); 5250 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp); 5251 } 5252 } 5253 5254 if (isUnsupportedFloatingType(LHS.getValueType())) { 5255 DAG.getTargetLoweringInfo().softenSetCCOperands( 5256 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5257 5258 // If softenSetCCOperands only returned one value, we should compare it to 5259 // zero. 5260 if (!RHS.getNode()) { 5261 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5262 CC = ISD::SETNE; 5263 } 5264 } 5265 5266 if (LHS.getValueType() == MVT::i32) { 5267 // Try to generate VSEL on ARMv8. 5268 // The VSEL instruction can't use all the usual ARM condition 5269 // codes: it only has two bits to select the condition code, so it's 5270 // constrained to use only GE, GT, VS and EQ. 5271 // 5272 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 5273 // swap the operands of the previous compare instruction (effectively 5274 // inverting the compare condition, swapping 'less' and 'greater') and 5275 // sometimes need to swap the operands to the VSEL (which inverts the 5276 // condition in the sense of firing whenever the previous condition didn't) 5277 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 5278 TrueVal.getValueType() == MVT::f32 || 5279 TrueVal.getValueType() == MVT::f64)) { 5280 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5281 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 5282 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 5283 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5284 std::swap(TrueVal, FalseVal); 5285 } 5286 } 5287 5288 SDValue ARMcc; 5289 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5290 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5291 // Choose GE over PL, which vsel does now support 5292 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 5293 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 5294 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5295 } 5296 5297 ARMCC::CondCodes CondCode, CondCode2; 5298 FPCCToARMCC(CC, CondCode, CondCode2); 5299 5300 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 5301 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 5302 // must use VSEL (limited condition codes), due to not having conditional f16 5303 // moves. 5304 if (Subtarget->hasFPARMv8Base() && 5305 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 5306 (TrueVal.getValueType() == MVT::f16 || 5307 TrueVal.getValueType() == MVT::f32 || 5308 TrueVal.getValueType() == MVT::f64)) { 5309 bool swpCmpOps = false; 5310 bool swpVselOps = false; 5311 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 5312 5313 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 5314 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 5315 if (swpCmpOps) 5316 std::swap(LHS, RHS); 5317 if (swpVselOps) 5318 std::swap(TrueVal, FalseVal); 5319 } 5320 } 5321 5322 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5323 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5324 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5325 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5326 if (CondCode2 != ARMCC::AL) { 5327 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 5328 // FIXME: Needs another CMP because flag can have but one use. 5329 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 5330 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 5331 } 5332 return Result; 5333 } 5334 5335 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 5336 /// to morph to an integer compare sequence. 5337 static bool canChangeToInt(SDValue Op, bool &SeenZero, 5338 const ARMSubtarget *Subtarget) { 5339 SDNode *N = Op.getNode(); 5340 if (!N->hasOneUse()) 5341 // Otherwise it requires moving the value from fp to integer registers. 5342 return false; 5343 if (!N->getNumValues()) 5344 return false; 5345 EVT VT = Op.getValueType(); 5346 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 5347 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 5348 // vmrs are very slow, e.g. cortex-a8. 5349 return false; 5350 5351 if (isFloatingPointZero(Op)) { 5352 SeenZero = true; 5353 return true; 5354 } 5355 return ISD::isNormalLoad(N); 5356 } 5357 5358 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 5359 if (isFloatingPointZero(Op)) 5360 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 5361 5362 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 5363 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 5364 Ld->getPointerInfo(), Ld->getAlignment(), 5365 Ld->getMemOperand()->getFlags()); 5366 5367 llvm_unreachable("Unknown VFP cmp argument!"); 5368 } 5369 5370 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 5371 SDValue &RetVal1, SDValue &RetVal2) { 5372 SDLoc dl(Op); 5373 5374 if (isFloatingPointZero(Op)) { 5375 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 5376 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 5377 return; 5378 } 5379 5380 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 5381 SDValue Ptr = Ld->getBasePtr(); 5382 RetVal1 = 5383 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 5384 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 5385 5386 EVT PtrType = Ptr.getValueType(); 5387 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 5388 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 5389 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 5390 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 5391 Ld->getPointerInfo().getWithOffset(4), NewAlign, 5392 Ld->getMemOperand()->getFlags()); 5393 return; 5394 } 5395 5396 llvm_unreachable("Unknown VFP cmp argument!"); 5397 } 5398 5399 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 5400 /// f32 and even f64 comparisons to integer ones. 5401 SDValue 5402 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 5403 SDValue Chain = Op.getOperand(0); 5404 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5405 SDValue LHS = Op.getOperand(2); 5406 SDValue RHS = Op.getOperand(3); 5407 SDValue Dest = Op.getOperand(4); 5408 SDLoc dl(Op); 5409 5410 bool LHSSeenZero = false; 5411 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 5412 bool RHSSeenZero = false; 5413 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 5414 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 5415 // If unsafe fp math optimization is enabled and there are no other uses of 5416 // the CMP operands, and the condition code is EQ or NE, we can optimize it 5417 // to an integer comparison. 5418 if (CC == ISD::SETOEQ) 5419 CC = ISD::SETEQ; 5420 else if (CC == ISD::SETUNE) 5421 CC = ISD::SETNE; 5422 5423 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5424 SDValue ARMcc; 5425 if (LHS.getValueType() == MVT::f32) { 5426 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5427 bitcastf32Toi32(LHS, DAG), Mask); 5428 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5429 bitcastf32Toi32(RHS, DAG), Mask); 5430 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5431 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5432 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5433 Chain, Dest, ARMcc, CCR, Cmp); 5434 } 5435 5436 SDValue LHS1, LHS2; 5437 SDValue RHS1, RHS2; 5438 expandf64Toi32(LHS, DAG, LHS1, LHS2); 5439 expandf64Toi32(RHS, DAG, RHS1, RHS2); 5440 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 5441 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 5442 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5443 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5444 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5445 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 5446 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 5447 } 5448 5449 return SDValue(); 5450 } 5451 5452 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 5453 SDValue Chain = Op.getOperand(0); 5454 SDValue Cond = Op.getOperand(1); 5455 SDValue Dest = Op.getOperand(2); 5456 SDLoc dl(Op); 5457 5458 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5459 // instruction. 5460 unsigned Opc = Cond.getOpcode(); 5461 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5462 !Subtarget->isThumb1Only(); 5463 if (Cond.getResNo() == 1 && 5464 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5465 Opc == ISD::USUBO || OptimizeMul)) { 5466 // Only lower legal XALUO ops. 5467 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 5468 return SDValue(); 5469 5470 // The actual operation with overflow check. 5471 SDValue Value, OverflowCmp; 5472 SDValue ARMcc; 5473 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 5474 5475 // Reverse the condition code. 5476 ARMCC::CondCodes CondCode = 5477 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5478 CondCode = ARMCC::getOppositeCondition(CondCode); 5479 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5480 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5481 5482 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5483 OverflowCmp); 5484 } 5485 5486 return SDValue(); 5487 } 5488 5489 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5490 SDValue Chain = Op.getOperand(0); 5491 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5492 SDValue LHS = Op.getOperand(2); 5493 SDValue RHS = Op.getOperand(3); 5494 SDValue Dest = Op.getOperand(4); 5495 SDLoc dl(Op); 5496 5497 if (isUnsupportedFloatingType(LHS.getValueType())) { 5498 DAG.getTargetLoweringInfo().softenSetCCOperands( 5499 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5500 5501 // If softenSetCCOperands only returned one value, we should compare it to 5502 // zero. 5503 if (!RHS.getNode()) { 5504 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5505 CC = ISD::SETNE; 5506 } 5507 } 5508 5509 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5510 // instruction. 5511 unsigned Opc = LHS.getOpcode(); 5512 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5513 !Subtarget->isThumb1Only(); 5514 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5515 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5516 Opc == ISD::USUBO || OptimizeMul) && 5517 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5518 // Only lower legal XALUO ops. 5519 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5520 return SDValue(); 5521 5522 // The actual operation with overflow check. 5523 SDValue Value, OverflowCmp; 5524 SDValue ARMcc; 5525 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5526 5527 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5528 // Reverse the condition code. 5529 ARMCC::CondCodes CondCode = 5530 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5531 CondCode = ARMCC::getOppositeCondition(CondCode); 5532 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5533 } 5534 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5535 5536 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5537 OverflowCmp); 5538 } 5539 5540 if (LHS.getValueType() == MVT::i32) { 5541 SDValue ARMcc; 5542 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5543 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5544 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5545 Chain, Dest, ARMcc, CCR, Cmp); 5546 } 5547 5548 if (getTargetMachine().Options.UnsafeFPMath && 5549 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5550 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5551 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5552 return Result; 5553 } 5554 5555 ARMCC::CondCodes CondCode, CondCode2; 5556 FPCCToARMCC(CC, CondCode, CondCode2); 5557 5558 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5559 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5560 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5561 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5562 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5563 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5564 if (CondCode2 != ARMCC::AL) { 5565 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5566 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5567 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5568 } 5569 return Res; 5570 } 5571 5572 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5573 SDValue Chain = Op.getOperand(0); 5574 SDValue Table = Op.getOperand(1); 5575 SDValue Index = Op.getOperand(2); 5576 SDLoc dl(Op); 5577 5578 EVT PTy = getPointerTy(DAG.getDataLayout()); 5579 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5580 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5581 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5582 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5583 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5584 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5585 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5586 // which does another jump to the destination. This also makes it easier 5587 // to translate it to TBB / TBH later (Thumb2 only). 5588 // FIXME: This might not work if the function is extremely large. 5589 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5590 Addr, Op.getOperand(2), JTI); 5591 } 5592 if (isPositionIndependent() || Subtarget->isROPI()) { 5593 Addr = 5594 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5595 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5596 Chain = Addr.getValue(1); 5597 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5598 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5599 } else { 5600 Addr = 5601 DAG.getLoad(PTy, dl, Chain, Addr, 5602 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5603 Chain = Addr.getValue(1); 5604 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5605 } 5606 } 5607 5608 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5609 EVT VT = Op.getValueType(); 5610 SDLoc dl(Op); 5611 5612 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5613 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5614 return Op; 5615 return DAG.UnrollVectorOp(Op.getNode()); 5616 } 5617 5618 const bool HasFullFP16 = 5619 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5620 5621 EVT NewTy; 5622 const EVT OpTy = Op.getOperand(0).getValueType(); 5623 if (OpTy == MVT::v4f32) 5624 NewTy = MVT::v4i32; 5625 else if (OpTy == MVT::v4f16 && HasFullFP16) 5626 NewTy = MVT::v4i16; 5627 else if (OpTy == MVT::v8f16 && HasFullFP16) 5628 NewTy = MVT::v8i16; 5629 else 5630 llvm_unreachable("Invalid type for custom lowering!"); 5631 5632 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5633 return DAG.UnrollVectorOp(Op.getNode()); 5634 5635 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5636 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5637 } 5638 5639 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5640 EVT VT = Op.getValueType(); 5641 if (VT.isVector()) 5642 return LowerVectorFP_TO_INT(Op, DAG); 5643 5644 bool IsStrict = Op->isStrictFPOpcode(); 5645 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 5646 5647 if (isUnsupportedFloatingType(SrcVal.getValueType())) { 5648 RTLIB::Libcall LC; 5649 if (Op.getOpcode() == ISD::FP_TO_SINT || 5650 Op.getOpcode() == ISD::STRICT_FP_TO_SINT) 5651 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), 5652 Op.getValueType()); 5653 else 5654 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), 5655 Op.getValueType()); 5656 SDLoc Loc(Op); 5657 MakeLibCallOptions CallOptions; 5658 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 5659 SDValue Result; 5660 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal, 5661 CallOptions, Loc, Chain); 5662 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 5663 } 5664 5665 // FIXME: Remove this when we have strict fp instruction selection patterns 5666 if (IsStrict) { 5667 SDLoc Loc(Op); 5668 SDValue Result = 5669 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT 5670 : ISD::FP_TO_UINT, 5671 Loc, Op.getValueType(), SrcVal); 5672 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 5673 } 5674 5675 return Op; 5676 } 5677 5678 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5679 EVT VT = Op.getValueType(); 5680 SDLoc dl(Op); 5681 5682 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5683 if (VT.getVectorElementType() == MVT::f32) 5684 return Op; 5685 return DAG.UnrollVectorOp(Op.getNode()); 5686 } 5687 5688 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5689 Op.getOperand(0).getValueType() == MVT::v8i16) && 5690 "Invalid type for custom lowering!"); 5691 5692 const bool HasFullFP16 = 5693 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5694 5695 EVT DestVecType; 5696 if (VT == MVT::v4f32) 5697 DestVecType = MVT::v4i32; 5698 else if (VT == MVT::v4f16 && HasFullFP16) 5699 DestVecType = MVT::v4i16; 5700 else if (VT == MVT::v8f16 && HasFullFP16) 5701 DestVecType = MVT::v8i16; 5702 else 5703 return DAG.UnrollVectorOp(Op.getNode()); 5704 5705 unsigned CastOpc; 5706 unsigned Opc; 5707 switch (Op.getOpcode()) { 5708 default: llvm_unreachable("Invalid opcode!"); 5709 case ISD::SINT_TO_FP: 5710 CastOpc = ISD::SIGN_EXTEND; 5711 Opc = ISD::SINT_TO_FP; 5712 break; 5713 case ISD::UINT_TO_FP: 5714 CastOpc = ISD::ZERO_EXTEND; 5715 Opc = ISD::UINT_TO_FP; 5716 break; 5717 } 5718 5719 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5720 return DAG.getNode(Opc, dl, VT, Op); 5721 } 5722 5723 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5724 EVT VT = Op.getValueType(); 5725 if (VT.isVector()) 5726 return LowerVectorINT_TO_FP(Op, DAG); 5727 if (isUnsupportedFloatingType(VT)) { 5728 RTLIB::Libcall LC; 5729 if (Op.getOpcode() == ISD::SINT_TO_FP) 5730 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5731 Op.getValueType()); 5732 else 5733 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5734 Op.getValueType()); 5735 MakeLibCallOptions CallOptions; 5736 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5737 CallOptions, SDLoc(Op)).first; 5738 } 5739 5740 return Op; 5741 } 5742 5743 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5744 // Implement fcopysign with a fabs and a conditional fneg. 5745 SDValue Tmp0 = Op.getOperand(0); 5746 SDValue Tmp1 = Op.getOperand(1); 5747 SDLoc dl(Op); 5748 EVT VT = Op.getValueType(); 5749 EVT SrcVT = Tmp1.getValueType(); 5750 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5751 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5752 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5753 5754 if (UseNEON) { 5755 // Use VBSL to copy the sign bit. 5756 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5757 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5758 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5759 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5760 if (VT == MVT::f64) 5761 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5762 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5763 DAG.getConstant(32, dl, MVT::i32)); 5764 else /*if (VT == MVT::f32)*/ 5765 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5766 if (SrcVT == MVT::f32) { 5767 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5768 if (VT == MVT::f64) 5769 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5770 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5771 DAG.getConstant(32, dl, MVT::i32)); 5772 } else if (VT == MVT::f32) 5773 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5774 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5775 DAG.getConstant(32, dl, MVT::i32)); 5776 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5777 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5778 5779 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5780 dl, MVT::i32); 5781 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5782 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5783 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5784 5785 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5786 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5787 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5788 if (VT == MVT::f32) { 5789 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5790 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5791 DAG.getConstant(0, dl, MVT::i32)); 5792 } else { 5793 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5794 } 5795 5796 return Res; 5797 } 5798 5799 // Bitcast operand 1 to i32. 5800 if (SrcVT == MVT::f64) 5801 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5802 Tmp1).getValue(1); 5803 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5804 5805 // Or in the signbit with integer operations. 5806 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5807 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5808 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5809 if (VT == MVT::f32) { 5810 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5811 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5812 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5813 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5814 } 5815 5816 // f64: Or the high part with signbit and then combine two parts. 5817 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5818 Tmp0); 5819 SDValue Lo = Tmp0.getValue(0); 5820 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5821 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5822 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5823 } 5824 5825 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5826 MachineFunction &MF = DAG.getMachineFunction(); 5827 MachineFrameInfo &MFI = MF.getFrameInfo(); 5828 MFI.setReturnAddressIsTaken(true); 5829 5830 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5831 return SDValue(); 5832 5833 EVT VT = Op.getValueType(); 5834 SDLoc dl(Op); 5835 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5836 if (Depth) { 5837 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5838 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5839 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5840 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5841 MachinePointerInfo()); 5842 } 5843 5844 // Return LR, which contains the return address. Mark it an implicit live-in. 5845 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5846 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5847 } 5848 5849 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5850 const ARMBaseRegisterInfo &ARI = 5851 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5852 MachineFunction &MF = DAG.getMachineFunction(); 5853 MachineFrameInfo &MFI = MF.getFrameInfo(); 5854 MFI.setFrameAddressIsTaken(true); 5855 5856 EVT VT = Op.getValueType(); 5857 SDLoc dl(Op); // FIXME probably not meaningful 5858 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5859 Register FrameReg = ARI.getFrameRegister(MF); 5860 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5861 while (Depth--) 5862 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5863 MachinePointerInfo()); 5864 return FrameAddr; 5865 } 5866 5867 // FIXME? Maybe this could be a TableGen attribute on some registers and 5868 // this table could be generated automatically from RegInfo. 5869 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT, 5870 const MachineFunction &MF) const { 5871 Register Reg = StringSwitch<unsigned>(RegName) 5872 .Case("sp", ARM::SP) 5873 .Default(0); 5874 if (Reg) 5875 return Reg; 5876 report_fatal_error(Twine("Invalid register name \"" 5877 + StringRef(RegName) + "\".")); 5878 } 5879 5880 // Result is 64 bit value so split into two 32 bit values and return as a 5881 // pair of values. 5882 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5883 SelectionDAG &DAG) { 5884 SDLoc DL(N); 5885 5886 // This function is only supposed to be called for i64 type destination. 5887 assert(N->getValueType(0) == MVT::i64 5888 && "ExpandREAD_REGISTER called for non-i64 type result."); 5889 5890 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5891 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5892 N->getOperand(0), 5893 N->getOperand(1)); 5894 5895 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5896 Read.getValue(1))); 5897 Results.push_back(Read.getOperand(0)); 5898 } 5899 5900 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5901 /// When \p DstVT, the destination type of \p BC, is on the vector 5902 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5903 /// it might be possible to combine them, such that everything stays on the 5904 /// vector register bank. 5905 /// \p return The node that would replace \p BT, if the combine 5906 /// is possible. 5907 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5908 SelectionDAG &DAG) { 5909 SDValue Op = BC->getOperand(0); 5910 EVT DstVT = BC->getValueType(0); 5911 5912 // The only vector instruction that can produce a scalar (remember, 5913 // since the bitcast was about to be turned into VMOVDRR, the source 5914 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5915 // Moreover, we can do this combine only if there is one use. 5916 // Finally, if the destination type is not a vector, there is not 5917 // much point on forcing everything on the vector bank. 5918 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5919 !Op.hasOneUse()) 5920 return SDValue(); 5921 5922 // If the index is not constant, we will introduce an additional 5923 // multiply that will stick. 5924 // Give up in that case. 5925 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5926 if (!Index) 5927 return SDValue(); 5928 unsigned DstNumElt = DstVT.getVectorNumElements(); 5929 5930 // Compute the new index. 5931 const APInt &APIntIndex = Index->getAPIntValue(); 5932 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5933 NewIndex *= APIntIndex; 5934 // Check if the new constant index fits into i32. 5935 if (NewIndex.getBitWidth() > 32) 5936 return SDValue(); 5937 5938 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5939 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5940 SDLoc dl(Op); 5941 SDValue ExtractSrc = Op.getOperand(0); 5942 EVT VecVT = EVT::getVectorVT( 5943 *DAG.getContext(), DstVT.getScalarType(), 5944 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5945 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5946 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5947 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5948 } 5949 5950 /// ExpandBITCAST - If the target supports VFP, this function is called to 5951 /// expand a bit convert where either the source or destination type is i64 to 5952 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5953 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5954 /// vectors), since the legalizer won't know what to do with that. 5955 SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5956 const ARMSubtarget *Subtarget) const { 5957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5958 SDLoc dl(N); 5959 SDValue Op = N->getOperand(0); 5960 5961 // This function is only supposed to be called for i16 and i64 types, either 5962 // as the source or destination of the bit convert. 5963 EVT SrcVT = Op.getValueType(); 5964 EVT DstVT = N->getValueType(0); 5965 5966 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) && 5967 (DstVT == MVT::f16 || DstVT == MVT::bf16)) 5968 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(), 5969 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op)); 5970 5971 if ((DstVT == MVT::i16 || DstVT == MVT::i32) && 5972 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) 5973 return DAG.getNode( 5974 ISD::TRUNCATE, SDLoc(N), DstVT, 5975 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op)); 5976 5977 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5978 return SDValue(); 5979 5980 // Turn i64->f64 into VMOVDRR. 5981 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5982 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5983 // if we can combine the bitcast with its source. 5984 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5985 return Val; 5986 5987 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5988 DAG.getConstant(0, dl, MVT::i32)); 5989 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5990 DAG.getConstant(1, dl, MVT::i32)); 5991 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5992 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5993 } 5994 5995 // Turn f64->i64 into VMOVRRD. 5996 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5997 SDValue Cvt; 5998 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5999 SrcVT.getVectorNumElements() > 1) 6000 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 6001 DAG.getVTList(MVT::i32, MVT::i32), 6002 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 6003 else 6004 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 6005 DAG.getVTList(MVT::i32, MVT::i32), Op); 6006 // Merge the pieces into a single i64 value. 6007 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 6008 } 6009 6010 return SDValue(); 6011 } 6012 6013 /// getZeroVector - Returns a vector of specified type with all zero elements. 6014 /// Zero vectors are used to represent vector negation and in those cases 6015 /// will be implemented with the NEON VNEG instruction. However, VNEG does 6016 /// not support i64 elements, so sometimes the zero vectors will need to be 6017 /// explicitly constructed. Regardless, use a canonical VMOV to create the 6018 /// zero vector. 6019 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 6020 assert(VT.isVector() && "Expected a vector type"); 6021 // The canonical modified immediate encoding of a zero vector is....0! 6022 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 6023 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 6024 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 6025 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6026 } 6027 6028 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 6029 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 6030 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 6031 SelectionDAG &DAG) const { 6032 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6033 EVT VT = Op.getValueType(); 6034 unsigned VTBits = VT.getSizeInBits(); 6035 SDLoc dl(Op); 6036 SDValue ShOpLo = Op.getOperand(0); 6037 SDValue ShOpHi = Op.getOperand(1); 6038 SDValue ShAmt = Op.getOperand(2); 6039 SDValue ARMcc; 6040 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6041 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 6042 6043 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 6044 6045 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6046 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 6047 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 6048 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 6049 DAG.getConstant(VTBits, dl, MVT::i32)); 6050 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 6051 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 6052 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 6053 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6054 ISD::SETGE, ARMcc, DAG, dl); 6055 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 6056 ARMcc, CCR, CmpLo); 6057 6058 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 6059 SDValue HiBigShift = Opc == ISD::SRA 6060 ? DAG.getNode(Opc, dl, VT, ShOpHi, 6061 DAG.getConstant(VTBits - 1, dl, VT)) 6062 : DAG.getConstant(0, dl, VT); 6063 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6064 ISD::SETGE, ARMcc, DAG, dl); 6065 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 6066 ARMcc, CCR, CmpHi); 6067 6068 SDValue Ops[2] = { Lo, Hi }; 6069 return DAG.getMergeValues(Ops, dl); 6070 } 6071 6072 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 6073 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 6074 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 6075 SelectionDAG &DAG) const { 6076 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6077 EVT VT = Op.getValueType(); 6078 unsigned VTBits = VT.getSizeInBits(); 6079 SDLoc dl(Op); 6080 SDValue ShOpLo = Op.getOperand(0); 6081 SDValue ShOpHi = Op.getOperand(1); 6082 SDValue ShAmt = Op.getOperand(2); 6083 SDValue ARMcc; 6084 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6085 6086 assert(Op.getOpcode() == ISD::SHL_PARTS); 6087 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6088 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 6089 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 6090 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 6091 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 6092 6093 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 6094 DAG.getConstant(VTBits, dl, MVT::i32)); 6095 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 6096 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6097 ISD::SETGE, ARMcc, DAG, dl); 6098 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 6099 ARMcc, CCR, CmpHi); 6100 6101 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6102 ISD::SETGE, ARMcc, DAG, dl); 6103 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6104 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 6105 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 6106 6107 SDValue Ops[2] = { Lo, Hi }; 6108 return DAG.getMergeValues(Ops, dl); 6109 } 6110 6111 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 6112 SelectionDAG &DAG) const { 6113 // The rounding mode is in bits 23:22 of the FPSCR. 6114 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 6115 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 6116 // so that the shift + and get folded into a bitfield extract. 6117 SDLoc dl(Op); 6118 SDValue Chain = Op.getOperand(0); 6119 SDValue Ops[] = {Chain, 6120 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)}; 6121 6122 SDValue FPSCR = 6123 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops); 6124 Chain = FPSCR.getValue(1); 6125 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 6126 DAG.getConstant(1U << 22, dl, MVT::i32)); 6127 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 6128 DAG.getConstant(22, dl, MVT::i32)); 6129 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 6130 DAG.getConstant(3, dl, MVT::i32)); 6131 return DAG.getMergeValues({And, Chain}, dl); 6132 } 6133 6134 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 6135 const ARMSubtarget *ST) { 6136 SDLoc dl(N); 6137 EVT VT = N->getValueType(0); 6138 if (VT.isVector() && ST->hasNEON()) { 6139 6140 // Compute the least significant set bit: LSB = X & -X 6141 SDValue X = N->getOperand(0); 6142 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 6143 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 6144 6145 EVT ElemTy = VT.getVectorElementType(); 6146 6147 if (ElemTy == MVT::i8) { 6148 // Compute with: cttz(x) = ctpop(lsb - 1) 6149 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6150 DAG.getTargetConstant(1, dl, ElemTy)); 6151 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6152 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6153 } 6154 6155 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 6156 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 6157 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 6158 unsigned NumBits = ElemTy.getSizeInBits(); 6159 SDValue WidthMinus1 = 6160 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6161 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 6162 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 6163 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 6164 } 6165 6166 // Compute with: cttz(x) = ctpop(lsb - 1) 6167 6168 // Compute LSB - 1. 6169 SDValue Bits; 6170 if (ElemTy == MVT::i64) { 6171 // Load constant 0xffff'ffff'ffff'ffff to register. 6172 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6173 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 6174 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 6175 } else { 6176 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6177 DAG.getTargetConstant(1, dl, ElemTy)); 6178 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6179 } 6180 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6181 } 6182 6183 if (!ST->hasV6T2Ops()) 6184 return SDValue(); 6185 6186 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 6187 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 6188 } 6189 6190 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 6191 const ARMSubtarget *ST) { 6192 EVT VT = N->getValueType(0); 6193 SDLoc DL(N); 6194 6195 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 6196 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 6197 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 6198 "Unexpected type for custom ctpop lowering"); 6199 6200 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6201 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 6202 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 6203 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 6204 6205 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 6206 unsigned EltSize = 8; 6207 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 6208 while (EltSize != VT.getScalarSizeInBits()) { 6209 SmallVector<SDValue, 8> Ops; 6210 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 6211 TLI.getPointerTy(DAG.getDataLayout()))); 6212 Ops.push_back(Res); 6213 6214 EltSize *= 2; 6215 NumElts /= 2; 6216 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 6217 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 6218 } 6219 6220 return Res; 6221 } 6222 6223 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 6224 /// operand of a vector shift operation, where all the elements of the 6225 /// build_vector must have the same constant integer value. 6226 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6227 // Ignore bit_converts. 6228 while (Op.getOpcode() == ISD::BITCAST) 6229 Op = Op.getOperand(0); 6230 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6231 APInt SplatBits, SplatUndef; 6232 unsigned SplatBitSize; 6233 bool HasAnyUndefs; 6234 if (!BVN || 6235 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 6236 ElementBits) || 6237 SplatBitSize > ElementBits) 6238 return false; 6239 Cnt = SplatBits.getSExtValue(); 6240 return true; 6241 } 6242 6243 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6244 /// operand of a vector shift left operation. That value must be in the range: 6245 /// 0 <= Value < ElementBits for a left shift; or 6246 /// 0 <= Value <= ElementBits for a long left shift. 6247 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6248 assert(VT.isVector() && "vector shift count is not a vector type"); 6249 int64_t ElementBits = VT.getScalarSizeInBits(); 6250 if (!getVShiftImm(Op, ElementBits, Cnt)) 6251 return false; 6252 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6253 } 6254 6255 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6256 /// operand of a vector shift right operation. For a shift opcode, the value 6257 /// is positive, but for an intrinsic the value count must be negative. The 6258 /// absolute value must be in the range: 6259 /// 1 <= |Value| <= ElementBits for a right shift; or 6260 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 6261 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 6262 int64_t &Cnt) { 6263 assert(VT.isVector() && "vector shift count is not a vector type"); 6264 int64_t ElementBits = VT.getScalarSizeInBits(); 6265 if (!getVShiftImm(Op, ElementBits, Cnt)) 6266 return false; 6267 if (!isIntrinsic) 6268 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6269 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 6270 Cnt = -Cnt; 6271 return true; 6272 } 6273 return false; 6274 } 6275 6276 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 6277 const ARMSubtarget *ST) { 6278 EVT VT = N->getValueType(0); 6279 SDLoc dl(N); 6280 int64_t Cnt; 6281 6282 if (!VT.isVector()) 6283 return SDValue(); 6284 6285 // We essentially have two forms here. Shift by an immediate and shift by a 6286 // vector register (there are also shift by a gpr, but that is just handled 6287 // with a tablegen pattern). We cannot easily match shift by an immediate in 6288 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 6289 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 6290 // signed or unsigned, and a negative shift indicates a shift right). 6291 if (N->getOpcode() == ISD::SHL) { 6292 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 6293 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 6294 DAG.getConstant(Cnt, dl, MVT::i32)); 6295 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 6296 N->getOperand(1)); 6297 } 6298 6299 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 6300 "unexpected vector shift opcode"); 6301 6302 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 6303 unsigned VShiftOpc = 6304 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 6305 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 6306 DAG.getConstant(Cnt, dl, MVT::i32)); 6307 } 6308 6309 // Other right shifts we don't have operations for (we use a shift left by a 6310 // negative number). 6311 EVT ShiftVT = N->getOperand(1).getValueType(); 6312 SDValue NegatedCount = DAG.getNode( 6313 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 6314 unsigned VShiftOpc = 6315 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 6316 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 6317 } 6318 6319 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 6320 const ARMSubtarget *ST) { 6321 EVT VT = N->getValueType(0); 6322 SDLoc dl(N); 6323 6324 // We can get here for a node like i32 = ISD::SHL i32, i64 6325 if (VT != MVT::i64) 6326 return SDValue(); 6327 6328 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 6329 N->getOpcode() == ISD::SHL) && 6330 "Unknown shift to lower!"); 6331 6332 unsigned ShOpc = N->getOpcode(); 6333 if (ST->hasMVEIntegerOps()) { 6334 SDValue ShAmt = N->getOperand(1); 6335 unsigned ShPartsOpc = ARMISD::LSLL; 6336 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 6337 6338 // If the shift amount is greater than 32 or has a greater bitwidth than 64 6339 // then do the default optimisation 6340 if (ShAmt->getValueType(0).getSizeInBits() > 64 || 6341 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32))) 6342 return SDValue(); 6343 6344 // Extract the lower 32 bits of the shift amount if it's not an i32 6345 if (ShAmt->getValueType(0) != MVT::i32) 6346 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32); 6347 6348 if (ShOpc == ISD::SRL) { 6349 if (!Con) 6350 // There is no t2LSRLr instruction so negate and perform an lsll if the 6351 // shift amount is in a register, emulating a right shift. 6352 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6353 DAG.getConstant(0, dl, MVT::i32), ShAmt); 6354 else 6355 // Else generate an lsrl on the immediate shift amount 6356 ShPartsOpc = ARMISD::LSRL; 6357 } else if (ShOpc == ISD::SRA) 6358 ShPartsOpc = ARMISD::ASRL; 6359 6360 // Lower 32 bits of the destination/source 6361 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6362 DAG.getConstant(0, dl, MVT::i32)); 6363 // Upper 32 bits of the destination/source 6364 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6365 DAG.getConstant(1, dl, MVT::i32)); 6366 6367 // Generate the shift operation as computed above 6368 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 6369 ShAmt); 6370 // The upper 32 bits come from the second return value of lsll 6371 Hi = SDValue(Lo.getNode(), 1); 6372 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6373 } 6374 6375 // We only lower SRA, SRL of 1 here, all others use generic lowering. 6376 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 6377 return SDValue(); 6378 6379 // If we are in thumb mode, we don't have RRX. 6380 if (ST->isThumb1Only()) 6381 return SDValue(); 6382 6383 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 6384 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6385 DAG.getConstant(0, dl, MVT::i32)); 6386 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6387 DAG.getConstant(1, dl, MVT::i32)); 6388 6389 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 6390 // captures the result into a carry flag. 6391 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 6392 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 6393 6394 // The low part is an ARMISD::RRX operand, which shifts the carry in. 6395 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 6396 6397 // Merge the pieces into a single i64 value. 6398 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6399 } 6400 6401 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 6402 const ARMSubtarget *ST) { 6403 bool Invert = false; 6404 bool Swap = false; 6405 unsigned Opc = ARMCC::AL; 6406 6407 SDValue Op0 = Op.getOperand(0); 6408 SDValue Op1 = Op.getOperand(1); 6409 SDValue CC = Op.getOperand(2); 6410 EVT VT = Op.getValueType(); 6411 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 6412 SDLoc dl(Op); 6413 6414 EVT CmpVT; 6415 if (ST->hasNEON()) 6416 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 6417 else { 6418 assert(ST->hasMVEIntegerOps() && 6419 "No hardware support for integer vector comparison!"); 6420 6421 if (Op.getValueType().getVectorElementType() != MVT::i1) 6422 return SDValue(); 6423 6424 // Make sure we expand floating point setcc to scalar if we do not have 6425 // mve.fp, so that we can handle them from there. 6426 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 6427 return SDValue(); 6428 6429 CmpVT = VT; 6430 } 6431 6432 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 6433 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 6434 // Special-case integer 64-bit equality comparisons. They aren't legal, 6435 // but they can be lowered with a few vector instructions. 6436 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 6437 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 6438 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 6439 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 6440 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 6441 DAG.getCondCode(ISD::SETEQ)); 6442 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 6443 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 6444 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 6445 if (SetCCOpcode == ISD::SETNE) 6446 Merged = DAG.getNOT(dl, Merged, CmpVT); 6447 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 6448 return Merged; 6449 } 6450 6451 if (CmpVT.getVectorElementType() == MVT::i64) 6452 // 64-bit comparisons are not legal in general. 6453 return SDValue(); 6454 6455 if (Op1.getValueType().isFloatingPoint()) { 6456 switch (SetCCOpcode) { 6457 default: llvm_unreachable("Illegal FP comparison"); 6458 case ISD::SETUNE: 6459 case ISD::SETNE: 6460 if (ST->hasMVEFloatOps()) { 6461 Opc = ARMCC::NE; break; 6462 } else { 6463 Invert = true; LLVM_FALLTHROUGH; 6464 } 6465 case ISD::SETOEQ: 6466 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6467 case ISD::SETOLT: 6468 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6469 case ISD::SETOGT: 6470 case ISD::SETGT: Opc = ARMCC::GT; break; 6471 case ISD::SETOLE: 6472 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6473 case ISD::SETOGE: 6474 case ISD::SETGE: Opc = ARMCC::GE; break; 6475 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6476 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6477 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6478 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6479 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6480 case ISD::SETONE: { 6481 // Expand this to (OLT | OGT). 6482 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6483 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6484 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6485 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6486 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6487 if (Invert) 6488 Result = DAG.getNOT(dl, Result, VT); 6489 return Result; 6490 } 6491 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6492 case ISD::SETO: { 6493 // Expand this to (OLT | OGE). 6494 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6495 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6496 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6497 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6498 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6499 if (Invert) 6500 Result = DAG.getNOT(dl, Result, VT); 6501 return Result; 6502 } 6503 } 6504 } else { 6505 // Integer comparisons. 6506 switch (SetCCOpcode) { 6507 default: llvm_unreachable("Illegal integer comparison"); 6508 case ISD::SETNE: 6509 if (ST->hasMVEIntegerOps()) { 6510 Opc = ARMCC::NE; break; 6511 } else { 6512 Invert = true; LLVM_FALLTHROUGH; 6513 } 6514 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6515 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6516 case ISD::SETGT: Opc = ARMCC::GT; break; 6517 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6518 case ISD::SETGE: Opc = ARMCC::GE; break; 6519 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6520 case ISD::SETUGT: Opc = ARMCC::HI; break; 6521 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6522 case ISD::SETUGE: Opc = ARMCC::HS; break; 6523 } 6524 6525 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6526 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6527 SDValue AndOp; 6528 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6529 AndOp = Op0; 6530 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6531 AndOp = Op1; 6532 6533 // Ignore bitconvert. 6534 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6535 AndOp = AndOp.getOperand(0); 6536 6537 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6538 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6539 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6540 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6541 if (!Invert) 6542 Result = DAG.getNOT(dl, Result, VT); 6543 return Result; 6544 } 6545 } 6546 } 6547 6548 if (Swap) 6549 std::swap(Op0, Op1); 6550 6551 // If one of the operands is a constant vector zero, attempt to fold the 6552 // comparison to a specialized compare-against-zero form. 6553 SDValue SingleOp; 6554 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6555 SingleOp = Op0; 6556 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6557 if (Opc == ARMCC::GE) 6558 Opc = ARMCC::LE; 6559 else if (Opc == ARMCC::GT) 6560 Opc = ARMCC::LT; 6561 SingleOp = Op1; 6562 } 6563 6564 SDValue Result; 6565 if (SingleOp.getNode()) { 6566 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6567 DAG.getConstant(Opc, dl, MVT::i32)); 6568 } else { 6569 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6570 DAG.getConstant(Opc, dl, MVT::i32)); 6571 } 6572 6573 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6574 6575 if (Invert) 6576 Result = DAG.getNOT(dl, Result, VT); 6577 6578 return Result; 6579 } 6580 6581 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6582 SDValue LHS = Op.getOperand(0); 6583 SDValue RHS = Op.getOperand(1); 6584 SDValue Carry = Op.getOperand(2); 6585 SDValue Cond = Op.getOperand(3); 6586 SDLoc DL(Op); 6587 6588 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6589 6590 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6591 // have to invert the carry first. 6592 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6593 DAG.getConstant(1, DL, MVT::i32), Carry); 6594 // This converts the boolean value carry into the carry flag. 6595 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6596 6597 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6598 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6599 6600 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6601 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6602 SDValue ARMcc = DAG.getConstant( 6603 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6604 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6605 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6606 Cmp.getValue(1), SDValue()); 6607 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6608 CCR, Chain.getValue(1)); 6609 } 6610 6611 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6612 /// valid vector constant for a NEON or MVE instruction with a "modified 6613 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6614 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6615 unsigned SplatBitSize, SelectionDAG &DAG, 6616 const SDLoc &dl, EVT &VT, EVT VectorVT, 6617 VMOVModImmType type) { 6618 unsigned OpCmode, Imm; 6619 bool is128Bits = VectorVT.is128BitVector(); 6620 6621 // SplatBitSize is set to the smallest size that splats the vector, so a 6622 // zero vector will always have SplatBitSize == 8. However, NEON modified 6623 // immediate instructions others than VMOV do not support the 8-bit encoding 6624 // of a zero vector, and the default encoding of zero is supposed to be the 6625 // 32-bit version. 6626 if (SplatBits == 0) 6627 SplatBitSize = 32; 6628 6629 switch (SplatBitSize) { 6630 case 8: 6631 if (type != VMOVModImm) 6632 return SDValue(); 6633 // Any 1-byte value is OK. Op=0, Cmode=1110. 6634 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6635 OpCmode = 0xe; 6636 Imm = SplatBits; 6637 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6638 break; 6639 6640 case 16: 6641 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6642 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6643 if ((SplatBits & ~0xff) == 0) { 6644 // Value = 0x00nn: Op=x, Cmode=100x. 6645 OpCmode = 0x8; 6646 Imm = SplatBits; 6647 break; 6648 } 6649 if ((SplatBits & ~0xff00) == 0) { 6650 // Value = 0xnn00: Op=x, Cmode=101x. 6651 OpCmode = 0xa; 6652 Imm = SplatBits >> 8; 6653 break; 6654 } 6655 return SDValue(); 6656 6657 case 32: 6658 // NEON's 32-bit VMOV supports splat values where: 6659 // * only one byte is nonzero, or 6660 // * the least significant byte is 0xff and the second byte is nonzero, or 6661 // * the least significant 2 bytes are 0xff and the third is nonzero. 6662 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6663 if ((SplatBits & ~0xff) == 0) { 6664 // Value = 0x000000nn: Op=x, Cmode=000x. 6665 OpCmode = 0; 6666 Imm = SplatBits; 6667 break; 6668 } 6669 if ((SplatBits & ~0xff00) == 0) { 6670 // Value = 0x0000nn00: Op=x, Cmode=001x. 6671 OpCmode = 0x2; 6672 Imm = SplatBits >> 8; 6673 break; 6674 } 6675 if ((SplatBits & ~0xff0000) == 0) { 6676 // Value = 0x00nn0000: Op=x, Cmode=010x. 6677 OpCmode = 0x4; 6678 Imm = SplatBits >> 16; 6679 break; 6680 } 6681 if ((SplatBits & ~0xff000000) == 0) { 6682 // Value = 0xnn000000: Op=x, Cmode=011x. 6683 OpCmode = 0x6; 6684 Imm = SplatBits >> 24; 6685 break; 6686 } 6687 6688 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6689 if (type == OtherModImm) return SDValue(); 6690 6691 if ((SplatBits & ~0xffff) == 0 && 6692 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6693 // Value = 0x0000nnff: Op=x, Cmode=1100. 6694 OpCmode = 0xc; 6695 Imm = SplatBits >> 8; 6696 break; 6697 } 6698 6699 // cmode == 0b1101 is not supported for MVE VMVN 6700 if (type == MVEVMVNModImm) 6701 return SDValue(); 6702 6703 if ((SplatBits & ~0xffffff) == 0 && 6704 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6705 // Value = 0x00nnffff: Op=x, Cmode=1101. 6706 OpCmode = 0xd; 6707 Imm = SplatBits >> 16; 6708 break; 6709 } 6710 6711 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6712 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6713 // VMOV.I32. A (very) minor optimization would be to replicate the value 6714 // and fall through here to test for a valid 64-bit splat. But, then the 6715 // caller would also need to check and handle the change in size. 6716 return SDValue(); 6717 6718 case 64: { 6719 if (type != VMOVModImm) 6720 return SDValue(); 6721 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6722 uint64_t BitMask = 0xff; 6723 uint64_t Val = 0; 6724 unsigned ImmMask = 1; 6725 Imm = 0; 6726 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6727 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6728 Val |= BitMask; 6729 Imm |= ImmMask; 6730 } else if ((SplatBits & BitMask) != 0) { 6731 return SDValue(); 6732 } 6733 BitMask <<= 8; 6734 ImmMask <<= 1; 6735 } 6736 6737 if (DAG.getDataLayout().isBigEndian()) { 6738 // Reverse the order of elements within the vector. 6739 unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8; 6740 unsigned Mask = (1 << BytesPerElem) - 1; 6741 unsigned NumElems = 8 / BytesPerElem; 6742 unsigned NewImm = 0; 6743 for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) { 6744 unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask); 6745 NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem; 6746 } 6747 Imm = NewImm; 6748 } 6749 6750 // Op=1, Cmode=1110. 6751 OpCmode = 0x1e; 6752 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6753 break; 6754 } 6755 6756 default: 6757 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6758 } 6759 6760 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6761 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6762 } 6763 6764 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6765 const ARMSubtarget *ST) const { 6766 EVT VT = Op.getValueType(); 6767 bool IsDouble = (VT == MVT::f64); 6768 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6769 const APFloat &FPVal = CFP->getValueAPF(); 6770 6771 // Prevent floating-point constants from using literal loads 6772 // when execute-only is enabled. 6773 if (ST->genExecuteOnly()) { 6774 // If we can represent the constant as an immediate, don't lower it 6775 if (isFPImmLegal(FPVal, VT)) 6776 return Op; 6777 // Otherwise, construct as integer, and move to float register 6778 APInt INTVal = FPVal.bitcastToAPInt(); 6779 SDLoc DL(CFP); 6780 switch (VT.getSimpleVT().SimpleTy) { 6781 default: 6782 llvm_unreachable("Unknown floating point type!"); 6783 break; 6784 case MVT::f64: { 6785 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6786 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6787 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6788 } 6789 case MVT::f32: 6790 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6791 DAG.getConstant(INTVal, DL, MVT::i32)); 6792 } 6793 } 6794 6795 if (!ST->hasVFP3Base()) 6796 return SDValue(); 6797 6798 // Use the default (constant pool) lowering for double constants when we have 6799 // an SP-only FPU 6800 if (IsDouble && !Subtarget->hasFP64()) 6801 return SDValue(); 6802 6803 // Try splatting with a VMOV.f32... 6804 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6805 6806 if (ImmVal != -1) { 6807 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6808 // We have code in place to select a valid ConstantFP already, no need to 6809 // do any mangling. 6810 return Op; 6811 } 6812 6813 // It's a float and we are trying to use NEON operations where 6814 // possible. Lower it to a splat followed by an extract. 6815 SDLoc DL(Op); 6816 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6817 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6818 NewVal); 6819 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6820 DAG.getConstant(0, DL, MVT::i32)); 6821 } 6822 6823 // The rest of our options are NEON only, make sure that's allowed before 6824 // proceeding.. 6825 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6826 return SDValue(); 6827 6828 EVT VMovVT; 6829 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6830 6831 // It wouldn't really be worth bothering for doubles except for one very 6832 // important value, which does happen to match: 0.0. So make sure we don't do 6833 // anything stupid. 6834 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6835 return SDValue(); 6836 6837 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6838 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6839 VMovVT, VT, VMOVModImm); 6840 if (NewVal != SDValue()) { 6841 SDLoc DL(Op); 6842 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6843 NewVal); 6844 if (IsDouble) 6845 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6846 6847 // It's a float: cast and extract a vector element. 6848 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6849 VecConstant); 6850 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6851 DAG.getConstant(0, DL, MVT::i32)); 6852 } 6853 6854 // Finally, try a VMVN.i32 6855 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6856 VT, VMVNModImm); 6857 if (NewVal != SDValue()) { 6858 SDLoc DL(Op); 6859 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6860 6861 if (IsDouble) 6862 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6863 6864 // It's a float: cast and extract a vector element. 6865 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6866 VecConstant); 6867 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6868 DAG.getConstant(0, DL, MVT::i32)); 6869 } 6870 6871 return SDValue(); 6872 } 6873 6874 // check if an VEXT instruction can handle the shuffle mask when the 6875 // vector sources of the shuffle are the same. 6876 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6877 unsigned NumElts = VT.getVectorNumElements(); 6878 6879 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6880 if (M[0] < 0) 6881 return false; 6882 6883 Imm = M[0]; 6884 6885 // If this is a VEXT shuffle, the immediate value is the index of the first 6886 // element. The other shuffle indices must be the successive elements after 6887 // the first one. 6888 unsigned ExpectedElt = Imm; 6889 for (unsigned i = 1; i < NumElts; ++i) { 6890 // Increment the expected index. If it wraps around, just follow it 6891 // back to index zero and keep going. 6892 ++ExpectedElt; 6893 if (ExpectedElt == NumElts) 6894 ExpectedElt = 0; 6895 6896 if (M[i] < 0) continue; // ignore UNDEF indices 6897 if (ExpectedElt != static_cast<unsigned>(M[i])) 6898 return false; 6899 } 6900 6901 return true; 6902 } 6903 6904 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6905 bool &ReverseVEXT, unsigned &Imm) { 6906 unsigned NumElts = VT.getVectorNumElements(); 6907 ReverseVEXT = false; 6908 6909 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6910 if (M[0] < 0) 6911 return false; 6912 6913 Imm = M[0]; 6914 6915 // If this is a VEXT shuffle, the immediate value is the index of the first 6916 // element. The other shuffle indices must be the successive elements after 6917 // the first one. 6918 unsigned ExpectedElt = Imm; 6919 for (unsigned i = 1; i < NumElts; ++i) { 6920 // Increment the expected index. If it wraps around, it may still be 6921 // a VEXT but the source vectors must be swapped. 6922 ExpectedElt += 1; 6923 if (ExpectedElt == NumElts * 2) { 6924 ExpectedElt = 0; 6925 ReverseVEXT = true; 6926 } 6927 6928 if (M[i] < 0) continue; // ignore UNDEF indices 6929 if (ExpectedElt != static_cast<unsigned>(M[i])) 6930 return false; 6931 } 6932 6933 // Adjust the index value if the source operands will be swapped. 6934 if (ReverseVEXT) 6935 Imm -= NumElts; 6936 6937 return true; 6938 } 6939 6940 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6941 /// instruction with the specified blocksize. (The order of the elements 6942 /// within each block of the vector is reversed.) 6943 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6944 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6945 "Only possible block sizes for VREV are: 16, 32, 64"); 6946 6947 unsigned EltSz = VT.getScalarSizeInBits(); 6948 if (EltSz == 64) 6949 return false; 6950 6951 unsigned NumElts = VT.getVectorNumElements(); 6952 unsigned BlockElts = M[0] + 1; 6953 // If the first shuffle index is UNDEF, be optimistic. 6954 if (M[0] < 0) 6955 BlockElts = BlockSize / EltSz; 6956 6957 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6958 return false; 6959 6960 for (unsigned i = 0; i < NumElts; ++i) { 6961 if (M[i] < 0) continue; // ignore UNDEF indices 6962 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6963 return false; 6964 } 6965 6966 return true; 6967 } 6968 6969 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6970 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6971 // range, then 0 is placed into the resulting vector. So pretty much any mask 6972 // of 8 elements can work here. 6973 return VT == MVT::v8i8 && M.size() == 8; 6974 } 6975 6976 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6977 unsigned Index) { 6978 if (Mask.size() == Elements * 2) 6979 return Index / Elements; 6980 return Mask[Index] == 0 ? 0 : 1; 6981 } 6982 6983 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6984 // checking that pairs of elements in the shuffle mask represent the same index 6985 // in each vector, incrementing the expected index by 2 at each step. 6986 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6987 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6988 // v2={e,f,g,h} 6989 // WhichResult gives the offset for each element in the mask based on which 6990 // of the two results it belongs to. 6991 // 6992 // The transpose can be represented either as: 6993 // result1 = shufflevector v1, v2, result1_shuffle_mask 6994 // result2 = shufflevector v1, v2, result2_shuffle_mask 6995 // where v1/v2 and the shuffle masks have the same number of elements 6996 // (here WhichResult (see below) indicates which result is being checked) 6997 // 6998 // or as: 6999 // results = shufflevector v1, v2, shuffle_mask 7000 // where both results are returned in one vector and the shuffle mask has twice 7001 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 7002 // want to check the low half and high half of the shuffle mask as if it were 7003 // the other case 7004 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7005 unsigned EltSz = VT.getScalarSizeInBits(); 7006 if (EltSz == 64) 7007 return false; 7008 7009 unsigned NumElts = VT.getVectorNumElements(); 7010 if (M.size() != NumElts && M.size() != NumElts*2) 7011 return false; 7012 7013 // If the mask is twice as long as the input vector then we need to check the 7014 // upper and lower parts of the mask with a matching value for WhichResult 7015 // FIXME: A mask with only even values will be rejected in case the first 7016 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 7017 // M[0] is used to determine WhichResult 7018 for (unsigned i = 0; i < M.size(); i += NumElts) { 7019 WhichResult = SelectPairHalf(NumElts, M, i); 7020 for (unsigned j = 0; j < NumElts; j += 2) { 7021 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 7022 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 7023 return false; 7024 } 7025 } 7026 7027 if (M.size() == NumElts*2) 7028 WhichResult = 0; 7029 7030 return true; 7031 } 7032 7033 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 7034 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7035 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 7036 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7037 unsigned EltSz = VT.getScalarSizeInBits(); 7038 if (EltSz == 64) 7039 return false; 7040 7041 unsigned NumElts = VT.getVectorNumElements(); 7042 if (M.size() != NumElts && M.size() != NumElts*2) 7043 return false; 7044 7045 for (unsigned i = 0; i < M.size(); i += NumElts) { 7046 WhichResult = SelectPairHalf(NumElts, M, i); 7047 for (unsigned j = 0; j < NumElts; j += 2) { 7048 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 7049 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 7050 return false; 7051 } 7052 } 7053 7054 if (M.size() == NumElts*2) 7055 WhichResult = 0; 7056 7057 return true; 7058 } 7059 7060 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 7061 // that the mask elements are either all even and in steps of size 2 or all odd 7062 // and in steps of size 2. 7063 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 7064 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 7065 // v2={e,f,g,h} 7066 // Requires similar checks to that of isVTRNMask with 7067 // respect the how results are returned. 7068 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7069 unsigned EltSz = VT.getScalarSizeInBits(); 7070 if (EltSz == 64) 7071 return false; 7072 7073 unsigned NumElts = VT.getVectorNumElements(); 7074 if (M.size() != NumElts && M.size() != NumElts*2) 7075 return false; 7076 7077 for (unsigned i = 0; i < M.size(); i += NumElts) { 7078 WhichResult = SelectPairHalf(NumElts, M, i); 7079 for (unsigned j = 0; j < NumElts; ++j) { 7080 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 7081 return false; 7082 } 7083 } 7084 7085 if (M.size() == NumElts*2) 7086 WhichResult = 0; 7087 7088 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7089 if (VT.is64BitVector() && EltSz == 32) 7090 return false; 7091 7092 return true; 7093 } 7094 7095 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 7096 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7097 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 7098 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7099 unsigned EltSz = VT.getScalarSizeInBits(); 7100 if (EltSz == 64) 7101 return false; 7102 7103 unsigned NumElts = VT.getVectorNumElements(); 7104 if (M.size() != NumElts && M.size() != NumElts*2) 7105 return false; 7106 7107 unsigned Half = NumElts / 2; 7108 for (unsigned i = 0; i < M.size(); i += NumElts) { 7109 WhichResult = SelectPairHalf(NumElts, M, i); 7110 for (unsigned j = 0; j < NumElts; j += Half) { 7111 unsigned Idx = WhichResult; 7112 for (unsigned k = 0; k < Half; ++k) { 7113 int MIdx = M[i + j + k]; 7114 if (MIdx >= 0 && (unsigned) MIdx != Idx) 7115 return false; 7116 Idx += 2; 7117 } 7118 } 7119 } 7120 7121 if (M.size() == NumElts*2) 7122 WhichResult = 0; 7123 7124 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7125 if (VT.is64BitVector() && EltSz == 32) 7126 return false; 7127 7128 return true; 7129 } 7130 7131 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 7132 // that pairs of elements of the shufflemask represent the same index in each 7133 // vector incrementing sequentially through the vectors. 7134 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 7135 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 7136 // v2={e,f,g,h} 7137 // Requires similar checks to that of isVTRNMask with respect the how results 7138 // are returned. 7139 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7140 unsigned EltSz = VT.getScalarSizeInBits(); 7141 if (EltSz == 64) 7142 return false; 7143 7144 unsigned NumElts = VT.getVectorNumElements(); 7145 if (M.size() != NumElts && M.size() != NumElts*2) 7146 return false; 7147 7148 for (unsigned i = 0; i < M.size(); i += NumElts) { 7149 WhichResult = SelectPairHalf(NumElts, M, i); 7150 unsigned Idx = WhichResult * NumElts / 2; 7151 for (unsigned j = 0; j < NumElts; j += 2) { 7152 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7153 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 7154 return false; 7155 Idx += 1; 7156 } 7157 } 7158 7159 if (M.size() == NumElts*2) 7160 WhichResult = 0; 7161 7162 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7163 if (VT.is64BitVector() && EltSz == 32) 7164 return false; 7165 7166 return true; 7167 } 7168 7169 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 7170 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7171 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 7172 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7173 unsigned EltSz = VT.getScalarSizeInBits(); 7174 if (EltSz == 64) 7175 return false; 7176 7177 unsigned NumElts = VT.getVectorNumElements(); 7178 if (M.size() != NumElts && M.size() != NumElts*2) 7179 return false; 7180 7181 for (unsigned i = 0; i < M.size(); i += NumElts) { 7182 WhichResult = SelectPairHalf(NumElts, M, i); 7183 unsigned Idx = WhichResult * NumElts / 2; 7184 for (unsigned j = 0; j < NumElts; j += 2) { 7185 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7186 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 7187 return false; 7188 Idx += 1; 7189 } 7190 } 7191 7192 if (M.size() == NumElts*2) 7193 WhichResult = 0; 7194 7195 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7196 if (VT.is64BitVector() && EltSz == 32) 7197 return false; 7198 7199 return true; 7200 } 7201 7202 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 7203 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 7204 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 7205 unsigned &WhichResult, 7206 bool &isV_UNDEF) { 7207 isV_UNDEF = false; 7208 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 7209 return ARMISD::VTRN; 7210 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 7211 return ARMISD::VUZP; 7212 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 7213 return ARMISD::VZIP; 7214 7215 isV_UNDEF = true; 7216 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7217 return ARMISD::VTRN; 7218 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7219 return ARMISD::VUZP; 7220 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7221 return ARMISD::VZIP; 7222 7223 return 0; 7224 } 7225 7226 /// \return true if this is a reverse operation on an vector. 7227 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 7228 unsigned NumElts = VT.getVectorNumElements(); 7229 // Make sure the mask has the right size. 7230 if (NumElts != M.size()) 7231 return false; 7232 7233 // Look for <15, ..., 3, -1, 1, 0>. 7234 for (unsigned i = 0; i != NumElts; ++i) 7235 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 7236 return false; 7237 7238 return true; 7239 } 7240 7241 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) { 7242 unsigned NumElts = VT.getVectorNumElements(); 7243 // Make sure the mask has the right size. 7244 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8)) 7245 return false; 7246 7247 // If Top 7248 // Look for <0, N, 2, N+2, 4, N+4, ..>. 7249 // This inserts Input2 into Input1 7250 // else if not Top 7251 // Look for <0, N+1, 2, N+3, 4, N+5, ..> 7252 // This inserts Input1 into Input2 7253 unsigned Offset = Top ? 0 : 1; 7254 for (unsigned i = 0; i < NumElts; i+=2) { 7255 if (M[i] >= 0 && M[i] != (int)i) 7256 return false; 7257 if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset)) 7258 return false; 7259 } 7260 7261 return true; 7262 } 7263 7264 // Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted 7265 // from a pair of inputs. For example: 7266 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0), 7267 // FP_ROUND(EXTRACT_ELT(Y, 0), 7268 // FP_ROUND(EXTRACT_ELT(X, 1), 7269 // FP_ROUND(EXTRACT_ELT(Y, 1), ...) 7270 static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG, 7271 const ARMSubtarget *ST) { 7272 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7273 if (!ST->hasMVEFloatOps()) 7274 return SDValue(); 7275 7276 SDLoc dl(BV); 7277 EVT VT = BV.getValueType(); 7278 if (VT != MVT::v8f16) 7279 return SDValue(); 7280 7281 // We are looking for a buildvector of fptrunc elements, where all the 7282 // elements are interleavingly extracted from two sources. Check the first two 7283 // items are valid enough and extract some info from them (they are checked 7284 // properly in the loop below). 7285 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND || 7286 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7287 BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0) 7288 return SDValue(); 7289 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND || 7290 BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7291 BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0) 7292 return SDValue(); 7293 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0); 7294 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0); 7295 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32) 7296 return SDValue(); 7297 7298 // Check all the values in the BuildVector line up with our expectations. 7299 for (unsigned i = 1; i < 4; i++) { 7300 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) { 7301 return Trunc.getOpcode() == ISD::FP_ROUND && 7302 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7303 Trunc.getOperand(0).getOperand(0) == Op && 7304 Trunc.getOperand(0).getConstantOperandVal(1) == Idx; 7305 }; 7306 if (!Check(BV.getOperand(i * 2 + 0), Op0, i)) 7307 return SDValue(); 7308 if (!Check(BV.getOperand(i * 2 + 1), Op1, i)) 7309 return SDValue(); 7310 } 7311 7312 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0, 7313 DAG.getConstant(0, dl, MVT::i32)); 7314 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1, 7315 DAG.getConstant(1, dl, MVT::i32)); 7316 } 7317 7318 // Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted 7319 // from a single input on alternating lanes. For example: 7320 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0), 7321 // FP_ROUND(EXTRACT_ELT(X, 2), 7322 // FP_ROUND(EXTRACT_ELT(X, 4), ...) 7323 static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG, 7324 const ARMSubtarget *ST) { 7325 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7326 if (!ST->hasMVEFloatOps()) 7327 return SDValue(); 7328 7329 SDLoc dl(BV); 7330 EVT VT = BV.getValueType(); 7331 if (VT != MVT::v4f32) 7332 return SDValue(); 7333 7334 // We are looking for a buildvector of fptext elements, where all the 7335 // elements are alternating lanes from a single source. For example <0,2,4,6> 7336 // or <1,3,5,7>. Check the first two items are valid enough and extract some 7337 // info from them (they are checked properly in the loop below). 7338 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND || 7339 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT) 7340 return SDValue(); 7341 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0); 7342 int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1); 7343 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1)) 7344 return SDValue(); 7345 7346 // Check all the values in the BuildVector line up with our expectations. 7347 for (unsigned i = 1; i < 4; i++) { 7348 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) { 7349 return Trunc.getOpcode() == ISD::FP_EXTEND && 7350 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7351 Trunc.getOperand(0).getOperand(0) == Op && 7352 Trunc.getOperand(0).getConstantOperandVal(1) == Idx; 7353 }; 7354 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset)) 7355 return SDValue(); 7356 } 7357 7358 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0, 7359 DAG.getConstant(Offset, dl, MVT::i32)); 7360 } 7361 7362 // If N is an integer constant that can be moved into a register in one 7363 // instruction, return an SDValue of such a constant (will become a MOV 7364 // instruction). Otherwise return null. 7365 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 7366 const ARMSubtarget *ST, const SDLoc &dl) { 7367 uint64_t Val; 7368 if (!isa<ConstantSDNode>(N)) 7369 return SDValue(); 7370 Val = cast<ConstantSDNode>(N)->getZExtValue(); 7371 7372 if (ST->isThumb1Only()) { 7373 if (Val <= 255 || ~Val <= 255) 7374 return DAG.getConstant(Val, dl, MVT::i32); 7375 } else { 7376 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 7377 return DAG.getConstant(Val, dl, MVT::i32); 7378 } 7379 return SDValue(); 7380 } 7381 7382 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 7383 const ARMSubtarget *ST) { 7384 SDLoc dl(Op); 7385 EVT VT = Op.getValueType(); 7386 7387 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 7388 7389 unsigned NumElts = VT.getVectorNumElements(); 7390 unsigned BoolMask; 7391 unsigned BitsPerBool; 7392 if (NumElts == 4) { 7393 BitsPerBool = 4; 7394 BoolMask = 0xf; 7395 } else if (NumElts == 8) { 7396 BitsPerBool = 2; 7397 BoolMask = 0x3; 7398 } else if (NumElts == 16) { 7399 BitsPerBool = 1; 7400 BoolMask = 0x1; 7401 } else 7402 return SDValue(); 7403 7404 // If this is a single value copied into all lanes (a splat), we can just sign 7405 // extend that single value 7406 SDValue FirstOp = Op.getOperand(0); 7407 if (!isa<ConstantSDNode>(FirstOp) && 7408 std::all_of(std::next(Op->op_begin()), Op->op_end(), 7409 [&FirstOp](SDUse &U) { 7410 return U.get().isUndef() || U.get() == FirstOp; 7411 })) { 7412 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp, 7413 DAG.getValueType(MVT::i1)); 7414 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext); 7415 } 7416 7417 // First create base with bits set where known 7418 unsigned Bits32 = 0; 7419 for (unsigned i = 0; i < NumElts; ++i) { 7420 SDValue V = Op.getOperand(i); 7421 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 7422 continue; 7423 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 7424 if (BitSet) 7425 Bits32 |= BoolMask << (i * BitsPerBool); 7426 } 7427 7428 // Add in unknown nodes 7429 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 7430 DAG.getConstant(Bits32, dl, MVT::i32)); 7431 for (unsigned i = 0; i < NumElts; ++i) { 7432 SDValue V = Op.getOperand(i); 7433 if (isa<ConstantSDNode>(V) || V.isUndef()) 7434 continue; 7435 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 7436 DAG.getConstant(i, dl, MVT::i32)); 7437 } 7438 7439 return Base; 7440 } 7441 7442 // If this is a case we can't handle, return null and let the default 7443 // expansion code take care of it. 7444 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 7445 const ARMSubtarget *ST) const { 7446 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7447 SDLoc dl(Op); 7448 EVT VT = Op.getValueType(); 7449 7450 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7451 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 7452 7453 APInt SplatBits, SplatUndef; 7454 unsigned SplatBitSize; 7455 bool HasAnyUndefs; 7456 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7457 if (SplatUndef.isAllOnesValue()) 7458 return DAG.getUNDEF(VT); 7459 7460 if ((ST->hasNEON() && SplatBitSize <= 64) || 7461 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) { 7462 // Check if an immediate VMOV works. 7463 EVT VmovVT; 7464 SDValue Val = 7465 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 7466 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm); 7467 7468 if (Val.getNode()) { 7469 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 7470 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7471 } 7472 7473 // Try an immediate VMVN. 7474 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 7475 Val = isVMOVModifiedImm( 7476 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT, 7477 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 7478 if (Val.getNode()) { 7479 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 7480 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7481 } 7482 7483 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 7484 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 7485 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 7486 if (ImmVal != -1) { 7487 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 7488 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 7489 } 7490 } 7491 } 7492 } 7493 7494 // Scan through the operands to see if only one value is used. 7495 // 7496 // As an optimisation, even if more than one value is used it may be more 7497 // profitable to splat with one value then change some lanes. 7498 // 7499 // Heuristically we decide to do this if the vector has a "dominant" value, 7500 // defined as splatted to more than half of the lanes. 7501 unsigned NumElts = VT.getVectorNumElements(); 7502 bool isOnlyLowElement = true; 7503 bool usesOnlyOneValue = true; 7504 bool hasDominantValue = false; 7505 bool isConstant = true; 7506 7507 // Map of the number of times a particular SDValue appears in the 7508 // element list. 7509 DenseMap<SDValue, unsigned> ValueCounts; 7510 SDValue Value; 7511 for (unsigned i = 0; i < NumElts; ++i) { 7512 SDValue V = Op.getOperand(i); 7513 if (V.isUndef()) 7514 continue; 7515 if (i > 0) 7516 isOnlyLowElement = false; 7517 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 7518 isConstant = false; 7519 7520 ValueCounts.insert(std::make_pair(V, 0)); 7521 unsigned &Count = ValueCounts[V]; 7522 7523 // Is this value dominant? (takes up more than half of the lanes) 7524 if (++Count > (NumElts / 2)) { 7525 hasDominantValue = true; 7526 Value = V; 7527 } 7528 } 7529 if (ValueCounts.size() != 1) 7530 usesOnlyOneValue = false; 7531 if (!Value.getNode() && !ValueCounts.empty()) 7532 Value = ValueCounts.begin()->first; 7533 7534 if (ValueCounts.empty()) 7535 return DAG.getUNDEF(VT); 7536 7537 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 7538 // Keep going if we are hitting this case. 7539 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 7540 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7541 7542 unsigned EltSize = VT.getScalarSizeInBits(); 7543 7544 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 7545 // i32 and try again. 7546 if (hasDominantValue && EltSize <= 32) { 7547 if (!isConstant) { 7548 SDValue N; 7549 7550 // If we are VDUPing a value that comes directly from a vector, that will 7551 // cause an unnecessary move to and from a GPR, where instead we could 7552 // just use VDUPLANE. We can only do this if the lane being extracted 7553 // is at a constant index, as the VDUP from lane instructions only have 7554 // constant-index forms. 7555 ConstantSDNode *constIndex; 7556 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7557 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 7558 // We need to create a new undef vector to use for the VDUPLANE if the 7559 // size of the vector from which we get the value is different than the 7560 // size of the vector that we need to create. We will insert the element 7561 // such that the register coalescer will remove unnecessary copies. 7562 if (VT != Value->getOperand(0).getValueType()) { 7563 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 7564 VT.getVectorNumElements(); 7565 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7566 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 7567 Value, DAG.getConstant(index, dl, MVT::i32)), 7568 DAG.getConstant(index, dl, MVT::i32)); 7569 } else 7570 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7571 Value->getOperand(0), Value->getOperand(1)); 7572 } else 7573 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 7574 7575 if (!usesOnlyOneValue) { 7576 // The dominant value was splatted as 'N', but we now have to insert 7577 // all differing elements. 7578 for (unsigned I = 0; I < NumElts; ++I) { 7579 if (Op.getOperand(I) == Value) 7580 continue; 7581 SmallVector<SDValue, 3> Ops; 7582 Ops.push_back(N); 7583 Ops.push_back(Op.getOperand(I)); 7584 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 7585 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 7586 } 7587 } 7588 return N; 7589 } 7590 if (VT.getVectorElementType().isFloatingPoint()) { 7591 SmallVector<SDValue, 8> Ops; 7592 MVT FVT = VT.getVectorElementType().getSimpleVT(); 7593 assert(FVT == MVT::f32 || FVT == MVT::f16); 7594 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 7595 for (unsigned i = 0; i < NumElts; ++i) 7596 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 7597 Op.getOperand(i))); 7598 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 7599 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7600 Val = LowerBUILD_VECTOR(Val, DAG, ST); 7601 if (Val.getNode()) 7602 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7603 } 7604 if (usesOnlyOneValue) { 7605 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 7606 if (isConstant && Val.getNode()) 7607 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 7608 } 7609 } 7610 7611 // If all elements are constants and the case above didn't get hit, fall back 7612 // to the default expansion, which will generate a load from the constant 7613 // pool. 7614 if (isConstant) 7615 return SDValue(); 7616 7617 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and 7618 // vmovn). Empirical tests suggest this is rarely worth it for vectors of 7619 // length <= 2. 7620 if (NumElts >= 4) 7621 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 7622 return shuffle; 7623 7624 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into 7625 // VCVT's 7626 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget)) 7627 return VCVT; 7628 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget)) 7629 return VCVT; 7630 7631 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7632 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7633 // into two 64-bit vectors; we might discover a better way to lower it. 7634 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7635 EVT ExtVT = VT.getVectorElementType(); 7636 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7637 SDValue Lower = 7638 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7639 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7640 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7641 SDValue Upper = DAG.getBuildVector( 7642 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7643 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7644 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7645 if (Lower && Upper) 7646 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7647 } 7648 7649 // Vectors with 32- or 64-bit elements can be built by directly assigning 7650 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7651 // will be legalized. 7652 if (EltSize >= 32) { 7653 // Do the expansion with floating-point types, since that is what the VFP 7654 // registers are defined to use, and since i64 is not legal. 7655 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7656 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7657 SmallVector<SDValue, 8> Ops; 7658 for (unsigned i = 0; i < NumElts; ++i) 7659 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7660 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7661 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7662 } 7663 7664 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7665 // know the default expansion would otherwise fall back on something even 7666 // worse. For a vector with one or two non-undef values, that's 7667 // scalar_to_vector for the elements followed by a shuffle (provided the 7668 // shuffle is valid for the target) and materialization element by element 7669 // on the stack followed by a load for everything else. 7670 if (!isConstant && !usesOnlyOneValue) { 7671 SDValue Vec = DAG.getUNDEF(VT); 7672 for (unsigned i = 0 ; i < NumElts; ++i) { 7673 SDValue V = Op.getOperand(i); 7674 if (V.isUndef()) 7675 continue; 7676 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7677 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7678 } 7679 return Vec; 7680 } 7681 7682 return SDValue(); 7683 } 7684 7685 // Gather data to see if the operation can be modelled as a 7686 // shuffle in combination with VEXTs. 7687 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7688 SelectionDAG &DAG) const { 7689 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7690 SDLoc dl(Op); 7691 EVT VT = Op.getValueType(); 7692 unsigned NumElts = VT.getVectorNumElements(); 7693 7694 struct ShuffleSourceInfo { 7695 SDValue Vec; 7696 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7697 unsigned MaxElt = 0; 7698 7699 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7700 // be compatible with the shuffle we intend to construct. As a result 7701 // ShuffleVec will be some sliding window into the original Vec. 7702 SDValue ShuffleVec; 7703 7704 // Code should guarantee that element i in Vec starts at element "WindowBase 7705 // + i * WindowScale in ShuffleVec". 7706 int WindowBase = 0; 7707 int WindowScale = 1; 7708 7709 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7710 7711 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7712 }; 7713 7714 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7715 // node. 7716 SmallVector<ShuffleSourceInfo, 2> Sources; 7717 for (unsigned i = 0; i < NumElts; ++i) { 7718 SDValue V = Op.getOperand(i); 7719 if (V.isUndef()) 7720 continue; 7721 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7722 // A shuffle can only come from building a vector from various 7723 // elements of other vectors. 7724 return SDValue(); 7725 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7726 // Furthermore, shuffles require a constant mask, whereas extractelts 7727 // accept variable indices. 7728 return SDValue(); 7729 } 7730 7731 // Add this element source to the list if it's not already there. 7732 SDValue SourceVec = V.getOperand(0); 7733 auto Source = llvm::find(Sources, SourceVec); 7734 if (Source == Sources.end()) 7735 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7736 7737 // Update the minimum and maximum lane number seen. 7738 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7739 Source->MinElt = std::min(Source->MinElt, EltNo); 7740 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7741 } 7742 7743 // Currently only do something sane when at most two source vectors 7744 // are involved. 7745 if (Sources.size() > 2) 7746 return SDValue(); 7747 7748 // Find out the smallest element size among result and two sources, and use 7749 // it as element size to build the shuffle_vector. 7750 EVT SmallestEltTy = VT.getVectorElementType(); 7751 for (auto &Source : Sources) { 7752 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7753 if (SrcEltTy.bitsLT(SmallestEltTy)) 7754 SmallestEltTy = SrcEltTy; 7755 } 7756 unsigned ResMultiplier = 7757 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7758 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7759 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7760 7761 // If the source vector is too wide or too narrow, we may nevertheless be able 7762 // to construct a compatible shuffle either by concatenating it with UNDEF or 7763 // extracting a suitable range of elements. 7764 for (auto &Src : Sources) { 7765 EVT SrcVT = Src.ShuffleVec.getValueType(); 7766 7767 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits(); 7768 uint64_t VTSize = VT.getFixedSizeInBits(); 7769 if (SrcVTSize == VTSize) 7770 continue; 7771 7772 // This stage of the search produces a source with the same element type as 7773 // the original, but with a total width matching the BUILD_VECTOR output. 7774 EVT EltVT = SrcVT.getVectorElementType(); 7775 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits(); 7776 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7777 7778 if (SrcVTSize < VTSize) { 7779 if (2 * SrcVTSize != VTSize) 7780 return SDValue(); 7781 // We can pad out the smaller vector for free, so if it's part of a 7782 // shuffle... 7783 Src.ShuffleVec = 7784 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7785 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7786 continue; 7787 } 7788 7789 if (SrcVTSize != 2 * VTSize) 7790 return SDValue(); 7791 7792 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7793 // Span too large for a VEXT to cope 7794 return SDValue(); 7795 } 7796 7797 if (Src.MinElt >= NumSrcElts) { 7798 // The extraction can just take the second half 7799 Src.ShuffleVec = 7800 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7801 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7802 Src.WindowBase = -NumSrcElts; 7803 } else if (Src.MaxElt < NumSrcElts) { 7804 // The extraction can just take the first half 7805 Src.ShuffleVec = 7806 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7807 DAG.getConstant(0, dl, MVT::i32)); 7808 } else { 7809 // An actual VEXT is needed 7810 SDValue VEXTSrc1 = 7811 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7812 DAG.getConstant(0, dl, MVT::i32)); 7813 SDValue VEXTSrc2 = 7814 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7815 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7816 7817 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7818 VEXTSrc2, 7819 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7820 Src.WindowBase = -Src.MinElt; 7821 } 7822 } 7823 7824 // Another possible incompatibility occurs from the vector element types. We 7825 // can fix this by bitcasting the source vectors to the same type we intend 7826 // for the shuffle. 7827 for (auto &Src : Sources) { 7828 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7829 if (SrcEltTy == SmallestEltTy) 7830 continue; 7831 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7832 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec); 7833 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7834 Src.WindowBase *= Src.WindowScale; 7835 } 7836 7837 // Final sanity check before we try to actually produce a shuffle. 7838 LLVM_DEBUG(for (auto Src 7839 : Sources) 7840 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7841 7842 // The stars all align, our next step is to produce the mask for the shuffle. 7843 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7844 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7845 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7846 SDValue Entry = Op.getOperand(i); 7847 if (Entry.isUndef()) 7848 continue; 7849 7850 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7851 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7852 7853 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7854 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7855 // segment. 7856 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7857 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(), 7858 VT.getScalarSizeInBits()); 7859 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7860 7861 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7862 // starting at the appropriate offset. 7863 int *LaneMask = &Mask[i * ResMultiplier]; 7864 7865 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7866 ExtractBase += NumElts * (Src - Sources.begin()); 7867 for (int j = 0; j < LanesDefined; ++j) 7868 LaneMask[j] = ExtractBase + j; 7869 } 7870 7871 7872 // We can't handle more than two sources. This should have already 7873 // been checked before this point. 7874 assert(Sources.size() <= 2 && "Too many sources!"); 7875 7876 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7877 for (unsigned i = 0; i < Sources.size(); ++i) 7878 ShuffleOps[i] = Sources[i].ShuffleVec; 7879 7880 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7881 ShuffleOps[1], Mask, DAG); 7882 if (!Shuffle) 7883 return SDValue(); 7884 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle); 7885 } 7886 7887 enum ShuffleOpCodes { 7888 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7889 OP_VREV, 7890 OP_VDUP0, 7891 OP_VDUP1, 7892 OP_VDUP2, 7893 OP_VDUP3, 7894 OP_VEXT1, 7895 OP_VEXT2, 7896 OP_VEXT3, 7897 OP_VUZPL, // VUZP, left result 7898 OP_VUZPR, // VUZP, right result 7899 OP_VZIPL, // VZIP, left result 7900 OP_VZIPR, // VZIP, right result 7901 OP_VTRNL, // VTRN, left result 7902 OP_VTRNR // VTRN, right result 7903 }; 7904 7905 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7906 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7907 switch (OpNum) { 7908 case OP_COPY: 7909 case OP_VREV: 7910 case OP_VDUP0: 7911 case OP_VDUP1: 7912 case OP_VDUP2: 7913 case OP_VDUP3: 7914 return true; 7915 } 7916 return false; 7917 } 7918 7919 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7920 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7921 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7922 /// are assumed to be legal. 7923 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7924 if (VT.getVectorNumElements() == 4 && 7925 (VT.is128BitVector() || VT.is64BitVector())) { 7926 unsigned PFIndexes[4]; 7927 for (unsigned i = 0; i != 4; ++i) { 7928 if (M[i] < 0) 7929 PFIndexes[i] = 8; 7930 else 7931 PFIndexes[i] = M[i]; 7932 } 7933 7934 // Compute the index in the perfect shuffle table. 7935 unsigned PFTableIndex = 7936 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7937 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7938 unsigned Cost = (PFEntry >> 30); 7939 7940 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7941 return true; 7942 } 7943 7944 bool ReverseVEXT, isV_UNDEF; 7945 unsigned Imm, WhichResult; 7946 7947 unsigned EltSize = VT.getScalarSizeInBits(); 7948 if (EltSize >= 32 || 7949 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7950 ShuffleVectorInst::isIdentityMask(M) || 7951 isVREVMask(M, VT, 64) || 7952 isVREVMask(M, VT, 32) || 7953 isVREVMask(M, VT, 16)) 7954 return true; 7955 else if (Subtarget->hasNEON() && 7956 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7957 isVTBLMask(M, VT) || 7958 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7959 return true; 7960 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7961 isReverseMask(M, VT)) 7962 return true; 7963 else if (Subtarget->hasMVEIntegerOps() && 7964 (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1))) 7965 return true; 7966 else 7967 return false; 7968 } 7969 7970 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7971 /// the specified operations to build the shuffle. 7972 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7973 SDValue RHS, SelectionDAG &DAG, 7974 const SDLoc &dl) { 7975 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7976 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7977 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7978 7979 if (OpNum == OP_COPY) { 7980 if (LHSID == (1*9+2)*9+3) return LHS; 7981 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7982 return RHS; 7983 } 7984 7985 SDValue OpLHS, OpRHS; 7986 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7987 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7988 EVT VT = OpLHS.getValueType(); 7989 7990 switch (OpNum) { 7991 default: llvm_unreachable("Unknown shuffle opcode!"); 7992 case OP_VREV: 7993 // VREV divides the vector in half and swaps within the half. 7994 if (VT.getVectorElementType() == MVT::i32 || 7995 VT.getVectorElementType() == MVT::f32) 7996 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7997 // vrev <4 x i16> -> VREV32 7998 if (VT.getVectorElementType() == MVT::i16) 7999 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 8000 // vrev <4 x i8> -> VREV16 8001 assert(VT.getVectorElementType() == MVT::i8); 8002 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 8003 case OP_VDUP0: 8004 case OP_VDUP1: 8005 case OP_VDUP2: 8006 case OP_VDUP3: 8007 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 8008 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 8009 case OP_VEXT1: 8010 case OP_VEXT2: 8011 case OP_VEXT3: 8012 return DAG.getNode(ARMISD::VEXT, dl, VT, 8013 OpLHS, OpRHS, 8014 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 8015 case OP_VUZPL: 8016 case OP_VUZPR: 8017 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 8018 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 8019 case OP_VZIPL: 8020 case OP_VZIPR: 8021 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 8022 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 8023 case OP_VTRNL: 8024 case OP_VTRNR: 8025 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 8026 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 8027 } 8028 } 8029 8030 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 8031 ArrayRef<int> ShuffleMask, 8032 SelectionDAG &DAG) { 8033 // Check to see if we can use the VTBL instruction. 8034 SDValue V1 = Op.getOperand(0); 8035 SDValue V2 = Op.getOperand(1); 8036 SDLoc DL(Op); 8037 8038 SmallVector<SDValue, 8> VTBLMask; 8039 for (ArrayRef<int>::iterator 8040 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 8041 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 8042 8043 if (V2.getNode()->isUndef()) 8044 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 8045 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 8046 8047 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 8048 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 8049 } 8050 8051 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 8052 SelectionDAG &DAG) { 8053 SDLoc DL(Op); 8054 SDValue OpLHS = Op.getOperand(0); 8055 EVT VT = OpLHS.getValueType(); 8056 8057 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 8058 "Expect an v8i16/v16i8 type"); 8059 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 8060 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 8061 // extract the first 8 bytes into the top double word and the last 8 bytes 8062 // into the bottom double word. The v8i16 case is similar. 8063 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 8064 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 8065 DAG.getConstant(ExtractNum, DL, MVT::i32)); 8066 } 8067 8068 static EVT getVectorTyFromPredicateVector(EVT VT) { 8069 switch (VT.getSimpleVT().SimpleTy) { 8070 case MVT::v4i1: 8071 return MVT::v4i32; 8072 case MVT::v8i1: 8073 return MVT::v8i16; 8074 case MVT::v16i1: 8075 return MVT::v16i8; 8076 default: 8077 llvm_unreachable("Unexpected vector predicate type"); 8078 } 8079 } 8080 8081 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 8082 SelectionDAG &DAG) { 8083 // Converting from boolean predicates to integers involves creating a vector 8084 // of all ones or all zeroes and selecting the lanes based upon the real 8085 // predicate. 8086 SDValue AllOnes = 8087 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 8088 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 8089 8090 SDValue AllZeroes = 8091 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 8092 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 8093 8094 // Get full vector type from predicate type 8095 EVT NewVT = getVectorTyFromPredicateVector(VT); 8096 8097 SDValue RecastV1; 8098 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 8099 // this to a v16i1. This cannot be done with an ordinary bitcast because the 8100 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 8101 // since we know in hardware the sizes are really the same. 8102 if (VT != MVT::v16i1) 8103 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 8104 else 8105 RecastV1 = Pred; 8106 8107 // Select either all ones or zeroes depending upon the real predicate bits. 8108 SDValue PredAsVector = 8109 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 8110 8111 // Recast our new predicate-as-integer v16i8 vector into something 8112 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 8113 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 8114 } 8115 8116 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 8117 const ARMSubtarget *ST) { 8118 EVT VT = Op.getValueType(); 8119 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8120 ArrayRef<int> ShuffleMask = SVN->getMask(); 8121 8122 assert(ST->hasMVEIntegerOps() && 8123 "No support for vector shuffle of boolean predicates"); 8124 8125 SDValue V1 = Op.getOperand(0); 8126 SDLoc dl(Op); 8127 if (isReverseMask(ShuffleMask, VT)) { 8128 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 8129 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 8130 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 8131 DAG.getConstant(16, dl, MVT::i32)); 8132 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 8133 } 8134 8135 // Until we can come up with optimised cases for every single vector 8136 // shuffle in existence we have chosen the least painful strategy. This is 8137 // to essentially promote the boolean predicate to a 8-bit integer, where 8138 // each predicate represents a byte. Then we fall back on a normal integer 8139 // vector shuffle and convert the result back into a predicate vector. In 8140 // many cases the generated code might be even better than scalar code 8141 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 8142 // fields in a register into 8 other arbitrary 2-bit fields! 8143 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 8144 EVT NewVT = PredAsVector.getValueType(); 8145 8146 // Do the shuffle! 8147 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 8148 DAG.getUNDEF(NewVT), ShuffleMask); 8149 8150 // Now return the result of comparing the shuffled vector with zero, 8151 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8152 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 8153 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8154 } 8155 8156 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op, 8157 ArrayRef<int> ShuffleMask, 8158 SelectionDAG &DAG) { 8159 // Attempt to lower the vector shuffle using as many whole register movs as 8160 // possible. This is useful for types smaller than 32bits, which would 8161 // often otherwise become a series for grp movs. 8162 SDLoc dl(Op); 8163 EVT VT = Op.getValueType(); 8164 if (VT.getScalarSizeInBits() >= 32) 8165 return SDValue(); 8166 8167 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && 8168 "Unexpected vector type"); 8169 int NumElts = VT.getVectorNumElements(); 8170 int QuarterSize = NumElts / 4; 8171 // The four final parts of the vector, as i32's 8172 SDValue Parts[4]; 8173 8174 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not 8175 // <u,u,u,u>), returning the vmov lane index 8176 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) { 8177 // Detect which mov lane this would be from the first non-undef element. 8178 int MovIdx = -1; 8179 for (int i = 0; i < Length; i++) { 8180 if (ShuffleMask[Start + i] >= 0) { 8181 if (ShuffleMask[Start + i] % Length != i) 8182 return -1; 8183 MovIdx = ShuffleMask[Start + i] / Length; 8184 break; 8185 } 8186 } 8187 // If all items are undef, leave this for other combines 8188 if (MovIdx == -1) 8189 return -1; 8190 // Check the remaining values are the correct part of the same mov 8191 for (int i = 1; i < Length; i++) { 8192 if (ShuffleMask[Start + i] >= 0 && 8193 (ShuffleMask[Start + i] / Length != MovIdx || 8194 ShuffleMask[Start + i] % Length != i)) 8195 return -1; 8196 } 8197 return MovIdx; 8198 }; 8199 8200 for (int Part = 0; Part < 4; ++Part) { 8201 // Does this part look like a mov 8202 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize); 8203 if (Elt != -1) { 8204 SDValue Input = Op->getOperand(0); 8205 if (Elt >= 4) { 8206 Input = Op->getOperand(1); 8207 Elt -= 4; 8208 } 8209 SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input); 8210 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast, 8211 DAG.getConstant(Elt, dl, MVT::i32)); 8212 } 8213 } 8214 8215 // Nothing interesting found, just return 8216 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3]) 8217 return SDValue(); 8218 8219 // The other parts need to be built with the old shuffle vector, cast to a 8220 // v4i32 and extract_vector_elts 8221 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) { 8222 SmallVector<int, 16> NewShuffleMask; 8223 for (int Part = 0; Part < 4; ++Part) 8224 for (int i = 0; i < QuarterSize; i++) 8225 NewShuffleMask.push_back( 8226 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]); 8227 SDValue NewShuffle = DAG.getVectorShuffle( 8228 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask); 8229 SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle); 8230 8231 for (int Part = 0; Part < 4; ++Part) 8232 if (!Parts[Part]) 8233 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 8234 BitCast, DAG.getConstant(Part, dl, MVT::i32)); 8235 } 8236 // Build a vector out of the various parts and bitcast it back to the original 8237 // type. 8238 SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts); 8239 return DAG.getBitcast(VT, NewVec); 8240 } 8241 8242 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 8243 const ARMSubtarget *ST) { 8244 SDValue V1 = Op.getOperand(0); 8245 SDValue V2 = Op.getOperand(1); 8246 SDLoc dl(Op); 8247 EVT VT = Op.getValueType(); 8248 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8249 unsigned EltSize = VT.getScalarSizeInBits(); 8250 8251 if (ST->hasMVEIntegerOps() && EltSize == 1) 8252 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 8253 8254 // Convert shuffles that are directly supported on NEON to target-specific 8255 // DAG nodes, instead of keeping them as shuffles and matching them again 8256 // during code selection. This is more efficient and avoids the possibility 8257 // of inconsistencies between legalization and selection. 8258 // FIXME: floating-point vectors should be canonicalized to integer vectors 8259 // of the same time so that they get CSEd properly. 8260 ArrayRef<int> ShuffleMask = SVN->getMask(); 8261 8262 if (EltSize <= 32) { 8263 if (SVN->isSplat()) { 8264 int Lane = SVN->getSplatIndex(); 8265 // If this is undef splat, generate it via "just" vdup, if possible. 8266 if (Lane == -1) Lane = 0; 8267 8268 // Test if V1 is a SCALAR_TO_VECTOR. 8269 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 8270 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8271 } 8272 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 8273 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 8274 // reaches it). 8275 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 8276 !isa<ConstantSDNode>(V1.getOperand(0))) { 8277 bool IsScalarToVector = true; 8278 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 8279 if (!V1.getOperand(i).isUndef()) { 8280 IsScalarToVector = false; 8281 break; 8282 } 8283 if (IsScalarToVector) 8284 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8285 } 8286 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 8287 DAG.getConstant(Lane, dl, MVT::i32)); 8288 } 8289 8290 bool ReverseVEXT = false; 8291 unsigned Imm = 0; 8292 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 8293 if (ReverseVEXT) 8294 std::swap(V1, V2); 8295 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 8296 DAG.getConstant(Imm, dl, MVT::i32)); 8297 } 8298 8299 if (isVREVMask(ShuffleMask, VT, 64)) 8300 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 8301 if (isVREVMask(ShuffleMask, VT, 32)) 8302 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 8303 if (isVREVMask(ShuffleMask, VT, 16)) 8304 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 8305 8306 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 8307 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 8308 DAG.getConstant(Imm, dl, MVT::i32)); 8309 } 8310 8311 // Check for Neon shuffles that modify both input vectors in place. 8312 // If both results are used, i.e., if there are two shuffles with the same 8313 // source operands and with masks corresponding to both results of one of 8314 // these operations, DAG memoization will ensure that a single node is 8315 // used for both shuffles. 8316 unsigned WhichResult = 0; 8317 bool isV_UNDEF = false; 8318 if (ST->hasNEON()) { 8319 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8320 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 8321 if (isV_UNDEF) 8322 V2 = V1; 8323 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 8324 .getValue(WhichResult); 8325 } 8326 } 8327 if (ST->hasMVEIntegerOps()) { 8328 if (isVMOVNMask(ShuffleMask, VT, 0)) 8329 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1, 8330 DAG.getConstant(0, dl, MVT::i32)); 8331 if (isVMOVNMask(ShuffleMask, VT, 1)) 8332 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2, 8333 DAG.getConstant(1, dl, MVT::i32)); 8334 } 8335 8336 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 8337 // shuffles that produce a result larger than their operands with: 8338 // shuffle(concat(v1, undef), concat(v2, undef)) 8339 // -> 8340 // shuffle(concat(v1, v2), undef) 8341 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 8342 // 8343 // This is useful in the general case, but there are special cases where 8344 // native shuffles produce larger results: the two-result ops. 8345 // 8346 // Look through the concat when lowering them: 8347 // shuffle(concat(v1, v2), undef) 8348 // -> 8349 // concat(VZIP(v1, v2):0, :1) 8350 // 8351 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 8352 SDValue SubV1 = V1->getOperand(0); 8353 SDValue SubV2 = V1->getOperand(1); 8354 EVT SubVT = SubV1.getValueType(); 8355 8356 // We expect these to have been canonicalized to -1. 8357 assert(llvm::all_of(ShuffleMask, [&](int i) { 8358 return i < (int)VT.getVectorNumElements(); 8359 }) && "Unexpected shuffle index into UNDEF operand!"); 8360 8361 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8362 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 8363 if (isV_UNDEF) 8364 SubV2 = SubV1; 8365 assert((WhichResult == 0) && 8366 "In-place shuffle of concat can only have one result!"); 8367 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 8368 SubV1, SubV2); 8369 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 8370 Res.getValue(1)); 8371 } 8372 } 8373 } 8374 8375 // If the shuffle is not directly supported and it has 4 elements, use 8376 // the PerfectShuffle-generated table to synthesize it from other shuffles. 8377 unsigned NumElts = VT.getVectorNumElements(); 8378 if (NumElts == 4) { 8379 unsigned PFIndexes[4]; 8380 for (unsigned i = 0; i != 4; ++i) { 8381 if (ShuffleMask[i] < 0) 8382 PFIndexes[i] = 8; 8383 else 8384 PFIndexes[i] = ShuffleMask[i]; 8385 } 8386 8387 // Compute the index in the perfect shuffle table. 8388 unsigned PFTableIndex = 8389 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8390 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8391 unsigned Cost = (PFEntry >> 30); 8392 8393 if (Cost <= 4) { 8394 if (ST->hasNEON()) 8395 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8396 else if (isLegalMVEShuffleOp(PFEntry)) { 8397 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8398 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8399 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 8400 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 8401 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 8402 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8403 } 8404 } 8405 } 8406 8407 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 8408 if (EltSize >= 32) { 8409 // Do the expansion with floating-point types, since that is what the VFP 8410 // registers are defined to use, and since i64 is not legal. 8411 EVT EltVT = EVT::getFloatingPointVT(EltSize); 8412 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 8413 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 8414 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 8415 SmallVector<SDValue, 8> Ops; 8416 for (unsigned i = 0; i < NumElts; ++i) { 8417 if (ShuffleMask[i] < 0) 8418 Ops.push_back(DAG.getUNDEF(EltVT)); 8419 else 8420 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 8421 ShuffleMask[i] < (int)NumElts ? V1 : V2, 8422 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 8423 dl, MVT::i32))); 8424 } 8425 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 8426 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8427 } 8428 8429 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 8430 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 8431 8432 if (ST->hasNEON() && VT == MVT::v8i8) 8433 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 8434 return NewOp; 8435 8436 if (ST->hasMVEIntegerOps()) 8437 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG)) 8438 return NewOp; 8439 8440 return SDValue(); 8441 } 8442 8443 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8444 const ARMSubtarget *ST) { 8445 EVT VecVT = Op.getOperand(0).getValueType(); 8446 SDLoc dl(Op); 8447 8448 assert(ST->hasMVEIntegerOps() && 8449 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8450 8451 SDValue Conv = 8452 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8453 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8454 unsigned LaneWidth = 8455 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8456 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 8457 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 8458 Op.getOperand(1), DAG.getValueType(MVT::i1)); 8459 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 8460 DAG.getConstant(~Mask, dl, MVT::i32)); 8461 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 8462 } 8463 8464 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8465 SelectionDAG &DAG) const { 8466 // INSERT_VECTOR_ELT is legal only for immediate indexes. 8467 SDValue Lane = Op.getOperand(2); 8468 if (!isa<ConstantSDNode>(Lane)) 8469 return SDValue(); 8470 8471 SDValue Elt = Op.getOperand(1); 8472 EVT EltVT = Elt.getValueType(); 8473 8474 if (Subtarget->hasMVEIntegerOps() && 8475 Op.getValueType().getScalarSizeInBits() == 1) 8476 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 8477 8478 if (getTypeAction(*DAG.getContext(), EltVT) == 8479 TargetLowering::TypePromoteFloat) { 8480 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 8481 // but the type system will try to do that if we don't intervene. 8482 // Reinterpret any such vector-element insertion as one with the 8483 // corresponding integer types. 8484 8485 SDLoc dl(Op); 8486 8487 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 8488 assert(getTypeAction(*DAG.getContext(), IEltVT) != 8489 TargetLowering::TypePromoteFloat); 8490 8491 SDValue VecIn = Op.getOperand(0); 8492 EVT VecVT = VecIn.getValueType(); 8493 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 8494 VecVT.getVectorNumElements()); 8495 8496 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 8497 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 8498 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 8499 IVecIn, IElt, Lane); 8500 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 8501 } 8502 8503 return Op; 8504 } 8505 8506 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8507 const ARMSubtarget *ST) { 8508 EVT VecVT = Op.getOperand(0).getValueType(); 8509 SDLoc dl(Op); 8510 8511 assert(ST->hasMVEIntegerOps() && 8512 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8513 8514 SDValue Conv = 8515 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8516 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8517 unsigned LaneWidth = 8518 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8519 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 8520 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 8521 return Shift; 8522 } 8523 8524 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 8525 const ARMSubtarget *ST) { 8526 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 8527 SDValue Lane = Op.getOperand(1); 8528 if (!isa<ConstantSDNode>(Lane)) 8529 return SDValue(); 8530 8531 SDValue Vec = Op.getOperand(0); 8532 EVT VT = Vec.getValueType(); 8533 8534 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8535 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 8536 8537 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 8538 SDLoc dl(Op); 8539 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 8540 } 8541 8542 return Op; 8543 } 8544 8545 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 8546 const ARMSubtarget *ST) { 8547 SDValue V1 = Op.getOperand(0); 8548 SDValue V2 = Op.getOperand(1); 8549 SDLoc dl(Op); 8550 EVT VT = Op.getValueType(); 8551 EVT Op1VT = V1.getValueType(); 8552 EVT Op2VT = V2.getValueType(); 8553 unsigned NumElts = VT.getVectorNumElements(); 8554 8555 assert(Op1VT == Op2VT && "Operand types don't match!"); 8556 assert(VT.getScalarSizeInBits() == 1 && 8557 "Unexpected custom CONCAT_VECTORS lowering"); 8558 assert(ST->hasMVEIntegerOps() && 8559 "CONCAT_VECTORS lowering only supported for MVE"); 8560 8561 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8562 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 8563 8564 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 8565 // promoted to v8i16, etc. 8566 8567 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8568 8569 // Extract the vector elements from Op1 and Op2 one by one and truncate them 8570 // to be the right size for the destination. For example, if Op1 is v4i1 then 8571 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 8572 // which when promoted is v8i16. That means each i32 element from Op1 needs 8573 // truncating to i16 and inserting in the result. 8574 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 8575 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 8576 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 8577 EVT NewVT = NewV.getValueType(); 8578 EVT ConcatVT = ConVec.getValueType(); 8579 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 8580 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 8581 DAG.getIntPtrConstant(i, dl)); 8582 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 8583 DAG.getConstant(j, dl, MVT::i32)); 8584 } 8585 return ConVec; 8586 }; 8587 unsigned j = 0; 8588 ConVec = ExractInto(NewV1, ConVec, j); 8589 ConVec = ExractInto(NewV2, ConVec, j); 8590 8591 // Now return the result of comparing the subvector with zero, 8592 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8593 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 8594 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8595 } 8596 8597 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 8598 const ARMSubtarget *ST) { 8599 EVT VT = Op->getValueType(0); 8600 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8601 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 8602 8603 // The only time a CONCAT_VECTORS operation can have legal types is when 8604 // two 64-bit vectors are concatenated to a 128-bit vector. 8605 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 8606 "unexpected CONCAT_VECTORS"); 8607 SDLoc dl(Op); 8608 SDValue Val = DAG.getUNDEF(MVT::v2f64); 8609 SDValue Op0 = Op.getOperand(0); 8610 SDValue Op1 = Op.getOperand(1); 8611 if (!Op0.isUndef()) 8612 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8613 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 8614 DAG.getIntPtrConstant(0, dl)); 8615 if (!Op1.isUndef()) 8616 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8617 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 8618 DAG.getIntPtrConstant(1, dl)); 8619 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 8620 } 8621 8622 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 8623 const ARMSubtarget *ST) { 8624 SDValue V1 = Op.getOperand(0); 8625 SDValue V2 = Op.getOperand(1); 8626 SDLoc dl(Op); 8627 EVT VT = Op.getValueType(); 8628 EVT Op1VT = V1.getValueType(); 8629 unsigned NumElts = VT.getVectorNumElements(); 8630 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 8631 8632 assert(VT.getScalarSizeInBits() == 1 && 8633 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 8634 assert(ST->hasMVEIntegerOps() && 8635 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 8636 8637 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8638 8639 // We now have Op1 promoted to a vector of integers, where v8i1 gets 8640 // promoted to v8i16, etc. 8641 8642 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8643 8644 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 8645 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 8646 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 8647 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 8648 DAG.getIntPtrConstant(i, dl)); 8649 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 8650 DAG.getConstant(j, dl, MVT::i32)); 8651 } 8652 8653 // Now return the result of comparing the subvector with zero, 8654 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8655 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 8656 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8657 } 8658 8659 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 8660 /// element has been zero/sign-extended, depending on the isSigned parameter, 8661 /// from an integer type half its size. 8662 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 8663 bool isSigned) { 8664 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 8665 EVT VT = N->getValueType(0); 8666 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 8667 SDNode *BVN = N->getOperand(0).getNode(); 8668 if (BVN->getValueType(0) != MVT::v4i32 || 8669 BVN->getOpcode() != ISD::BUILD_VECTOR) 8670 return false; 8671 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8672 unsigned HiElt = 1 - LoElt; 8673 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 8674 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 8675 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 8676 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 8677 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 8678 return false; 8679 if (isSigned) { 8680 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 8681 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 8682 return true; 8683 } else { 8684 if (Hi0->isNullValue() && Hi1->isNullValue()) 8685 return true; 8686 } 8687 return false; 8688 } 8689 8690 if (N->getOpcode() != ISD::BUILD_VECTOR) 8691 return false; 8692 8693 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 8694 SDNode *Elt = N->getOperand(i).getNode(); 8695 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 8696 unsigned EltSize = VT.getScalarSizeInBits(); 8697 unsigned HalfSize = EltSize / 2; 8698 if (isSigned) { 8699 if (!isIntN(HalfSize, C->getSExtValue())) 8700 return false; 8701 } else { 8702 if (!isUIntN(HalfSize, C->getZExtValue())) 8703 return false; 8704 } 8705 continue; 8706 } 8707 return false; 8708 } 8709 8710 return true; 8711 } 8712 8713 /// isSignExtended - Check if a node is a vector value that is sign-extended 8714 /// or a constant BUILD_VECTOR with sign-extended elements. 8715 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 8716 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 8717 return true; 8718 if (isExtendedBUILD_VECTOR(N, DAG, true)) 8719 return true; 8720 return false; 8721 } 8722 8723 /// isZeroExtended - Check if a node is a vector value that is zero-extended 8724 /// or a constant BUILD_VECTOR with zero-extended elements. 8725 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8726 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 8727 return true; 8728 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8729 return true; 8730 return false; 8731 } 8732 8733 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8734 if (OrigVT.getSizeInBits() >= 64) 8735 return OrigVT; 8736 8737 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8738 8739 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8740 switch (OrigSimpleTy) { 8741 default: llvm_unreachable("Unexpected Vector Type"); 8742 case MVT::v2i8: 8743 case MVT::v2i16: 8744 return MVT::v2i32; 8745 case MVT::v4i8: 8746 return MVT::v4i16; 8747 } 8748 } 8749 8750 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8751 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8752 /// We insert the required extension here to get the vector to fill a D register. 8753 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8754 const EVT &OrigTy, 8755 const EVT &ExtTy, 8756 unsigned ExtOpcode) { 8757 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8758 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8759 // 64-bits we need to insert a new extension so that it will be 64-bits. 8760 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8761 if (OrigTy.getSizeInBits() >= 64) 8762 return N; 8763 8764 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8765 EVT NewVT = getExtensionTo64Bits(OrigTy); 8766 8767 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8768 } 8769 8770 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8771 /// does not do any sign/zero extension. If the original vector is less 8772 /// than 64 bits, an appropriate extension will be added after the load to 8773 /// reach a total size of 64 bits. We have to add the extension separately 8774 /// because ARM does not have a sign/zero extending load for vectors. 8775 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8776 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8777 8778 // The load already has the right type. 8779 if (ExtendedTy == LD->getMemoryVT()) 8780 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8781 LD->getBasePtr(), LD->getPointerInfo(), 8782 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8783 8784 // We need to create a zextload/sextload. We cannot just create a load 8785 // followed by a zext/zext node because LowerMUL is also run during normal 8786 // operation legalization where we can't create illegal types. 8787 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8788 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8789 LD->getMemoryVT(), LD->getAlignment(), 8790 LD->getMemOperand()->getFlags()); 8791 } 8792 8793 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8794 /// extending load, or BUILD_VECTOR with extended elements, return the 8795 /// unextended value. The unextended vector should be 64 bits so that it can 8796 /// be used as an operand to a VMULL instruction. If the original vector size 8797 /// before extension is less than 64 bits we add a an extension to resize 8798 /// the vector to 64 bits. 8799 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8800 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 8801 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8802 N->getOperand(0)->getValueType(0), 8803 N->getValueType(0), 8804 N->getOpcode()); 8805 8806 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8807 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8808 "Expected extending load"); 8809 8810 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8811 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8812 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8813 SDValue extLoad = 8814 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8815 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8816 8817 return newLoad; 8818 } 8819 8820 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8821 // have been legalized as a BITCAST from v4i32. 8822 if (N->getOpcode() == ISD::BITCAST) { 8823 SDNode *BVN = N->getOperand(0).getNode(); 8824 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8825 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8826 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8827 return DAG.getBuildVector( 8828 MVT::v2i32, SDLoc(N), 8829 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8830 } 8831 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8832 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8833 EVT VT = N->getValueType(0); 8834 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8835 unsigned NumElts = VT.getVectorNumElements(); 8836 MVT TruncVT = MVT::getIntegerVT(EltSize); 8837 SmallVector<SDValue, 8> Ops; 8838 SDLoc dl(N); 8839 for (unsigned i = 0; i != NumElts; ++i) { 8840 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8841 const APInt &CInt = C->getAPIntValue(); 8842 // Element types smaller than 32 bits are not legal, so use i32 elements. 8843 // The values are implicitly truncated so sext vs. zext doesn't matter. 8844 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8845 } 8846 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8847 } 8848 8849 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8850 unsigned Opcode = N->getOpcode(); 8851 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8852 SDNode *N0 = N->getOperand(0).getNode(); 8853 SDNode *N1 = N->getOperand(1).getNode(); 8854 return N0->hasOneUse() && N1->hasOneUse() && 8855 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8856 } 8857 return false; 8858 } 8859 8860 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8861 unsigned Opcode = N->getOpcode(); 8862 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8863 SDNode *N0 = N->getOperand(0).getNode(); 8864 SDNode *N1 = N->getOperand(1).getNode(); 8865 return N0->hasOneUse() && N1->hasOneUse() && 8866 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8867 } 8868 return false; 8869 } 8870 8871 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8872 // Multiplications are only custom-lowered for 128-bit vectors so that 8873 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8874 EVT VT = Op.getValueType(); 8875 assert(VT.is128BitVector() && VT.isInteger() && 8876 "unexpected type for custom-lowering ISD::MUL"); 8877 SDNode *N0 = Op.getOperand(0).getNode(); 8878 SDNode *N1 = Op.getOperand(1).getNode(); 8879 unsigned NewOpc = 0; 8880 bool isMLA = false; 8881 bool isN0SExt = isSignExtended(N0, DAG); 8882 bool isN1SExt = isSignExtended(N1, DAG); 8883 if (isN0SExt && isN1SExt) 8884 NewOpc = ARMISD::VMULLs; 8885 else { 8886 bool isN0ZExt = isZeroExtended(N0, DAG); 8887 bool isN1ZExt = isZeroExtended(N1, DAG); 8888 if (isN0ZExt && isN1ZExt) 8889 NewOpc = ARMISD::VMULLu; 8890 else if (isN1SExt || isN1ZExt) { 8891 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8892 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8893 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8894 NewOpc = ARMISD::VMULLs; 8895 isMLA = true; 8896 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8897 NewOpc = ARMISD::VMULLu; 8898 isMLA = true; 8899 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8900 std::swap(N0, N1); 8901 NewOpc = ARMISD::VMULLu; 8902 isMLA = true; 8903 } 8904 } 8905 8906 if (!NewOpc) { 8907 if (VT == MVT::v2i64) 8908 // Fall through to expand this. It is not legal. 8909 return SDValue(); 8910 else 8911 // Other vector multiplications are legal. 8912 return Op; 8913 } 8914 } 8915 8916 // Legalize to a VMULL instruction. 8917 SDLoc DL(Op); 8918 SDValue Op0; 8919 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8920 if (!isMLA) { 8921 Op0 = SkipExtensionForVMULL(N0, DAG); 8922 assert(Op0.getValueType().is64BitVector() && 8923 Op1.getValueType().is64BitVector() && 8924 "unexpected types for extended operands to VMULL"); 8925 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8926 } 8927 8928 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8929 // isel lowering to take advantage of no-stall back to back vmul + vmla. 8930 // vmull q0, d4, d6 8931 // vmlal q0, d5, d6 8932 // is faster than 8933 // vaddl q0, d4, d5 8934 // vmovl q1, d6 8935 // vmul q0, q0, q1 8936 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 8937 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 8938 EVT Op1VT = Op1.getValueType(); 8939 return DAG.getNode(N0->getOpcode(), DL, VT, 8940 DAG.getNode(NewOpc, DL, VT, 8941 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 8942 DAG.getNode(NewOpc, DL, VT, 8943 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 8944 } 8945 8946 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 8947 SelectionDAG &DAG) { 8948 // TODO: Should this propagate fast-math-flags? 8949 8950 // Convert to float 8951 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 8952 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 8953 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 8954 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 8955 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 8956 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 8957 // Get reciprocal estimate. 8958 // float4 recip = vrecpeq_f32(yf); 8959 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8960 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8961 Y); 8962 // Because char has a smaller range than uchar, we can actually get away 8963 // without any newton steps. This requires that we use a weird bias 8964 // of 0xb000, however (again, this has been exhaustively tested). 8965 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 8966 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 8967 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 8968 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 8969 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 8970 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 8971 // Convert back to short. 8972 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 8973 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 8974 return X; 8975 } 8976 8977 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 8978 SelectionDAG &DAG) { 8979 // TODO: Should this propagate fast-math-flags? 8980 8981 SDValue N2; 8982 // Convert to float. 8983 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 8984 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 8985 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 8986 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 8987 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8988 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8989 8990 // Use reciprocal estimate and one refinement step. 8991 // float4 recip = vrecpeq_f32(yf); 8992 // recip *= vrecpsq_f32(yf, recip); 8993 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8994 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8995 N1); 8996 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8997 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8998 N1, N2); 8999 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9000 // Because short has a smaller range than ushort, we can actually get away 9001 // with only a single newton step. This requires that we use a weird bias 9002 // of 89, however (again, this has been exhaustively tested). 9003 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 9004 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 9005 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 9006 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 9007 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 9008 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 9009 // Convert back to integer and return. 9010 // return vmovn_s32(vcvt_s32_f32(result)); 9011 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 9012 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 9013 return N0; 9014 } 9015 9016 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 9017 const ARMSubtarget *ST) { 9018 EVT VT = Op.getValueType(); 9019 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 9020 "unexpected type for custom-lowering ISD::SDIV"); 9021 9022 SDLoc dl(Op); 9023 SDValue N0 = Op.getOperand(0); 9024 SDValue N1 = Op.getOperand(1); 9025 SDValue N2, N3; 9026 9027 if (VT == MVT::v8i8) { 9028 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 9029 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 9030 9031 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9032 DAG.getIntPtrConstant(4, dl)); 9033 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9034 DAG.getIntPtrConstant(4, dl)); 9035 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9036 DAG.getIntPtrConstant(0, dl)); 9037 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9038 DAG.getIntPtrConstant(0, dl)); 9039 9040 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 9041 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 9042 9043 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 9044 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 9045 9046 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 9047 return N0; 9048 } 9049 return LowerSDIV_v4i16(N0, N1, dl, DAG); 9050 } 9051 9052 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 9053 const ARMSubtarget *ST) { 9054 // TODO: Should this propagate fast-math-flags? 9055 EVT VT = Op.getValueType(); 9056 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 9057 "unexpected type for custom-lowering ISD::UDIV"); 9058 9059 SDLoc dl(Op); 9060 SDValue N0 = Op.getOperand(0); 9061 SDValue N1 = Op.getOperand(1); 9062 SDValue N2, N3; 9063 9064 if (VT == MVT::v8i8) { 9065 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 9066 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 9067 9068 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9069 DAG.getIntPtrConstant(4, dl)); 9070 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9071 DAG.getIntPtrConstant(4, dl)); 9072 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9073 DAG.getIntPtrConstant(0, dl)); 9074 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9075 DAG.getIntPtrConstant(0, dl)); 9076 9077 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 9078 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 9079 9080 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 9081 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 9082 9083 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 9084 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 9085 MVT::i32), 9086 N0); 9087 return N0; 9088 } 9089 9090 // v4i16 sdiv ... Convert to float. 9091 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 9092 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 9093 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 9094 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 9095 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 9096 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 9097 9098 // Use reciprocal estimate and two refinement steps. 9099 // float4 recip = vrecpeq_f32(yf); 9100 // recip *= vrecpsq_f32(yf, recip); 9101 // recip *= vrecpsq_f32(yf, recip); 9102 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9103 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 9104 BN1); 9105 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9106 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9107 BN1, N2); 9108 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9109 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9110 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9111 BN1, N2); 9112 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9113 // Simply multiplying by the reciprocal estimate can leave us a few ulps 9114 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 9115 // and that it will never cause us to return an answer too large). 9116 // float4 result = as_float4(as_int4(xf*recip) + 2); 9117 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 9118 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 9119 N1 = DAG.getConstant(2, dl, MVT::v4i32); 9120 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 9121 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 9122 // Convert back to integer and return. 9123 // return vmovn_u32(vcvt_s32_f32(result)); 9124 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 9125 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 9126 return N0; 9127 } 9128 9129 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 9130 SDNode *N = Op.getNode(); 9131 EVT VT = N->getValueType(0); 9132 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 9133 9134 SDValue Carry = Op.getOperand(2); 9135 9136 SDLoc DL(Op); 9137 9138 SDValue Result; 9139 if (Op.getOpcode() == ISD::ADDCARRY) { 9140 // This converts the boolean value carry into the carry flag. 9141 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 9142 9143 // Do the addition proper using the carry flag we wanted. 9144 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 9145 Op.getOperand(1), Carry); 9146 9147 // Now convert the carry flag into a boolean value. 9148 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 9149 } else { 9150 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 9151 // have to invert the carry first. 9152 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 9153 DAG.getConstant(1, DL, MVT::i32), Carry); 9154 // This converts the boolean value carry into the carry flag. 9155 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 9156 9157 // Do the subtraction proper using the carry flag we wanted. 9158 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 9159 Op.getOperand(1), Carry); 9160 9161 // Now convert the carry flag into a boolean value. 9162 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 9163 // But the carry returned by ARMISD::SUBE is not a borrow as expected 9164 // by ISD::SUBCARRY, so compute 1 - C. 9165 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 9166 DAG.getConstant(1, DL, MVT::i32), Carry); 9167 } 9168 9169 // Return both values. 9170 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 9171 } 9172 9173 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 9174 assert(Subtarget->isTargetDarwin()); 9175 9176 // For iOS, we want to call an alternative entry point: __sincos_stret, 9177 // return values are passed via sret. 9178 SDLoc dl(Op); 9179 SDValue Arg = Op.getOperand(0); 9180 EVT ArgVT = Arg.getValueType(); 9181 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 9182 auto PtrVT = getPointerTy(DAG.getDataLayout()); 9183 9184 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9185 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9186 9187 // Pair of floats / doubles used to pass the result. 9188 Type *RetTy = StructType::get(ArgTy, ArgTy); 9189 auto &DL = DAG.getDataLayout(); 9190 9191 ArgListTy Args; 9192 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 9193 SDValue SRet; 9194 if (ShouldUseSRet) { 9195 // Create stack object for sret. 9196 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 9197 const Align StackAlign = DL.getPrefTypeAlign(RetTy); 9198 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 9199 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 9200 9201 ArgListEntry Entry; 9202 Entry.Node = SRet; 9203 Entry.Ty = RetTy->getPointerTo(); 9204 Entry.IsSExt = false; 9205 Entry.IsZExt = false; 9206 Entry.IsSRet = true; 9207 Args.push_back(Entry); 9208 RetTy = Type::getVoidTy(*DAG.getContext()); 9209 } 9210 9211 ArgListEntry Entry; 9212 Entry.Node = Arg; 9213 Entry.Ty = ArgTy; 9214 Entry.IsSExt = false; 9215 Entry.IsZExt = false; 9216 Args.push_back(Entry); 9217 9218 RTLIB::Libcall LC = 9219 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 9220 const char *LibcallName = getLibcallName(LC); 9221 CallingConv::ID CC = getLibcallCallingConv(LC); 9222 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 9223 9224 TargetLowering::CallLoweringInfo CLI(DAG); 9225 CLI.setDebugLoc(dl) 9226 .setChain(DAG.getEntryNode()) 9227 .setCallee(CC, RetTy, Callee, std::move(Args)) 9228 .setDiscardResult(ShouldUseSRet); 9229 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 9230 9231 if (!ShouldUseSRet) 9232 return CallResult.first; 9233 9234 SDValue LoadSin = 9235 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 9236 9237 // Address of cos field. 9238 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 9239 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 9240 SDValue LoadCos = 9241 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 9242 9243 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 9244 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 9245 LoadSin.getValue(0), LoadCos.getValue(0)); 9246 } 9247 9248 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 9249 bool Signed, 9250 SDValue &Chain) const { 9251 EVT VT = Op.getValueType(); 9252 assert((VT == MVT::i32 || VT == MVT::i64) && 9253 "unexpected type for custom lowering DIV"); 9254 SDLoc dl(Op); 9255 9256 const auto &DL = DAG.getDataLayout(); 9257 const auto &TLI = DAG.getTargetLoweringInfo(); 9258 9259 const char *Name = nullptr; 9260 if (Signed) 9261 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 9262 else 9263 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 9264 9265 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 9266 9267 ARMTargetLowering::ArgListTy Args; 9268 9269 for (auto AI : {1, 0}) { 9270 ArgListEntry Arg; 9271 Arg.Node = Op.getOperand(AI); 9272 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 9273 Args.push_back(Arg); 9274 } 9275 9276 CallLoweringInfo CLI(DAG); 9277 CLI.setDebugLoc(dl) 9278 .setChain(Chain) 9279 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 9280 ES, std::move(Args)); 9281 9282 return LowerCallTo(CLI).first; 9283 } 9284 9285 // This is a code size optimisation: return the original SDIV node to 9286 // DAGCombiner when we don't want to expand SDIV into a sequence of 9287 // instructions, and an empty node otherwise which will cause the 9288 // SDIV to be expanded in DAGCombine. 9289 SDValue 9290 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 9291 SelectionDAG &DAG, 9292 SmallVectorImpl<SDNode *> &Created) const { 9293 // TODO: Support SREM 9294 if (N->getOpcode() != ISD::SDIV) 9295 return SDValue(); 9296 9297 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 9298 const bool MinSize = ST.hasMinSize(); 9299 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 9300 : ST.hasDivideInARMMode(); 9301 9302 // Don't touch vector types; rewriting this may lead to scalarizing 9303 // the int divs. 9304 if (N->getOperand(0).getValueType().isVector()) 9305 return SDValue(); 9306 9307 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 9308 // hwdiv support for this to be really profitable. 9309 if (!(MinSize && HasDivide)) 9310 return SDValue(); 9311 9312 // ARM mode is a bit simpler than Thumb: we can handle large power 9313 // of 2 immediates with 1 mov instruction; no further checks required, 9314 // just return the sdiv node. 9315 if (!ST.isThumb()) 9316 return SDValue(N, 0); 9317 9318 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 9319 // and thus lose the code size benefits of a MOVS that requires only 2. 9320 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 9321 // but as it's doing exactly this, it's not worth the trouble to get TTI. 9322 if (Divisor.sgt(128)) 9323 return SDValue(); 9324 9325 return SDValue(N, 0); 9326 } 9327 9328 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 9329 bool Signed) const { 9330 assert(Op.getValueType() == MVT::i32 && 9331 "unexpected type for custom lowering DIV"); 9332 SDLoc dl(Op); 9333 9334 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 9335 DAG.getEntryNode(), Op.getOperand(1)); 9336 9337 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9338 } 9339 9340 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 9341 SDLoc DL(N); 9342 SDValue Op = N->getOperand(1); 9343 if (N->getValueType(0) == MVT::i32) 9344 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 9345 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9346 DAG.getConstant(0, DL, MVT::i32)); 9347 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9348 DAG.getConstant(1, DL, MVT::i32)); 9349 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 9350 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 9351 } 9352 9353 void ARMTargetLowering::ExpandDIV_Windows( 9354 SDValue Op, SelectionDAG &DAG, bool Signed, 9355 SmallVectorImpl<SDValue> &Results) const { 9356 const auto &DL = DAG.getDataLayout(); 9357 const auto &TLI = DAG.getTargetLoweringInfo(); 9358 9359 assert(Op.getValueType() == MVT::i64 && 9360 "unexpected type for custom lowering DIV"); 9361 SDLoc dl(Op); 9362 9363 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 9364 9365 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9366 9367 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 9368 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 9369 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 9370 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 9371 9372 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper)); 9373 } 9374 9375 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) { 9376 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode()); 9377 EVT MemVT = LD->getMemoryVT(); 9378 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9379 "Expected a predicate type!"); 9380 assert(MemVT == Op.getValueType()); 9381 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && 9382 "Expected a non-extending load"); 9383 assert(LD->isUnindexed() && "Expected a unindexed load"); 9384 9385 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit 9386 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We 9387 // need to make sure that 8/4 bits are actually loaded into the correct 9388 // place, which means loading the value and then shuffling the values into 9389 // the bottom bits of the predicate. 9390 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect 9391 // for BE). 9392 9393 SDLoc dl(Op); 9394 SDValue Load = DAG.getExtLoad( 9395 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(), 9396 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9397 LD->getMemOperand()); 9398 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load); 9399 if (MemVT != MVT::v16i1) 9400 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred, 9401 DAG.getConstant(0, dl, MVT::i32)); 9402 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl); 9403 } 9404 9405 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results, 9406 SelectionDAG &DAG) const { 9407 LoadSDNode *LD = cast<LoadSDNode>(N); 9408 EVT MemVT = LD->getMemoryVT(); 9409 assert(LD->isUnindexed() && "Loads should be unindexed at this point."); 9410 9411 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9412 !Subtarget->isThumb1Only() && LD->isVolatile()) { 9413 SDLoc dl(N); 9414 SDValue Result = DAG.getMemIntrinsicNode( 9415 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}), 9416 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand()); 9417 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1); 9418 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0); 9419 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 9420 Results.append({Pair, Result.getValue(2)}); 9421 } 9422 } 9423 9424 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) { 9425 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9426 EVT MemVT = ST->getMemoryVT(); 9427 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9428 "Expected a predicate type!"); 9429 assert(MemVT == ST->getValue().getValueType()); 9430 assert(!ST->isTruncatingStore() && "Expected a non-extending store"); 9431 assert(ST->isUnindexed() && "Expected a unindexed store"); 9432 9433 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits 9434 // unset and a scalar store. 9435 SDLoc dl(Op); 9436 SDValue Build = ST->getValue(); 9437 if (MemVT != MVT::v16i1) { 9438 SmallVector<SDValue, 16> Ops; 9439 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) 9440 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build, 9441 DAG.getConstant(I, dl, MVT::i32))); 9442 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++) 9443 Ops.push_back(DAG.getUNDEF(MVT::i32)); 9444 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops); 9445 } 9446 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build); 9447 return DAG.getTruncStore( 9448 ST->getChain(), dl, GRP, ST->getBasePtr(), 9449 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9450 ST->getMemOperand()); 9451 } 9452 9453 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG, 9454 const ARMSubtarget *Subtarget) { 9455 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9456 EVT MemVT = ST->getMemoryVT(); 9457 assert(ST->isUnindexed() && "Stores should be unindexed at this point."); 9458 9459 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9460 !Subtarget->isThumb1Only() && ST->isVolatile()) { 9461 SDNode *N = Op.getNode(); 9462 SDLoc dl(N); 9463 9464 SDValue Lo = DAG.getNode( 9465 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9466 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl, 9467 MVT::i32)); 9468 SDValue Hi = DAG.getNode( 9469 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9470 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl, 9471 MVT::i32)); 9472 9473 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other), 9474 {ST->getChain(), Lo, Hi, ST->getBasePtr()}, 9475 MemVT, ST->getMemOperand()); 9476 } else if (Subtarget->hasMVEIntegerOps() && 9477 ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || 9478 MemVT == MVT::v16i1))) { 9479 return LowerPredicateStore(Op, DAG); 9480 } 9481 9482 return SDValue(); 9483 } 9484 9485 static bool isZeroVector(SDValue N) { 9486 return (ISD::isBuildVectorAllZeros(N.getNode()) || 9487 (N->getOpcode() == ARMISD::VMOVIMM && 9488 isNullConstant(N->getOperand(0)))); 9489 } 9490 9491 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) { 9492 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode()); 9493 MVT VT = Op.getSimpleValueType(); 9494 SDValue Mask = N->getMask(); 9495 SDValue PassThru = N->getPassThru(); 9496 SDLoc dl(Op); 9497 9498 if (isZeroVector(PassThru)) 9499 return Op; 9500 9501 // MVE Masked loads use zero as the passthru value. Here we convert undef to 9502 // zero too, and other values are lowered to a select. 9503 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 9504 DAG.getTargetConstant(0, dl, MVT::i32)); 9505 SDValue NewLoad = DAG.getMaskedLoad( 9506 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec, 9507 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(), 9508 N->getExtensionType(), N->isExpandingLoad()); 9509 SDValue Combo = NewLoad; 9510 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST || 9511 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) && 9512 isZeroVector(PassThru->getOperand(0)); 9513 if (!PassThru.isUndef() && !PassThruIsCastZero) 9514 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru); 9515 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl); 9516 } 9517 9518 static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG, 9519 const ARMSubtarget *ST) { 9520 if (!ST->hasMVEIntegerOps()) 9521 return SDValue(); 9522 9523 SDLoc dl(Op); 9524 unsigned BaseOpcode = 0; 9525 switch (Op->getOpcode()) { 9526 default: llvm_unreachable("Expected VECREDUCE opcode"); 9527 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break; 9528 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break; 9529 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break; 9530 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break; 9531 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break; 9532 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break; 9533 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break; 9534 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break; 9535 } 9536 9537 SDValue Op0 = Op->getOperand(0); 9538 EVT VT = Op0.getValueType(); 9539 EVT EltVT = VT.getVectorElementType(); 9540 unsigned NumElts = VT.getVectorNumElements(); 9541 unsigned NumActiveLanes = NumElts; 9542 9543 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || 9544 NumActiveLanes == 2) && 9545 "Only expected a power 2 vector size"); 9546 9547 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements 9548 // allows us to easily extract vector elements from the lanes. 9549 while (NumActiveLanes > 4) { 9550 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32; 9551 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0); 9552 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev); 9553 NumActiveLanes /= 2; 9554 } 9555 9556 SDValue Res; 9557 if (NumActiveLanes == 4) { 9558 // The remaining 4 elements are summed sequentially 9559 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9560 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32)); 9561 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9562 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32)); 9563 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9564 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32)); 9565 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9566 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32)); 9567 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags()); 9568 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags()); 9569 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags()); 9570 } else { 9571 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9572 DAG.getConstant(0, dl, MVT::i32)); 9573 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9574 DAG.getConstant(1, dl, MVT::i32)); 9575 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags()); 9576 } 9577 9578 // Result type may be wider than element type. 9579 if (EltVT != Op->getValueType(0)) 9580 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res); 9581 return Res; 9582 } 9583 9584 static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG, 9585 const ARMSubtarget *ST) { 9586 if (!ST->hasMVEFloatOps()) 9587 return SDValue(); 9588 return LowerVecReduce(Op, DAG, ST); 9589 } 9590 9591 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 9592 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 9593 // Acquire/Release load/store is not legal for targets without a dmb or 9594 // equivalent available. 9595 return SDValue(); 9596 9597 // Monotonic load/store is legal for all targets. 9598 return Op; 9599 } 9600 9601 static void ReplaceREADCYCLECOUNTER(SDNode *N, 9602 SmallVectorImpl<SDValue> &Results, 9603 SelectionDAG &DAG, 9604 const ARMSubtarget *Subtarget) { 9605 SDLoc DL(N); 9606 // Under Power Management extensions, the cycle-count is: 9607 // mrc p15, #0, <Rt>, c9, c13, #0 9608 SDValue Ops[] = { N->getOperand(0), // Chain 9609 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 9610 DAG.getTargetConstant(15, DL, MVT::i32), 9611 DAG.getTargetConstant(0, DL, MVT::i32), 9612 DAG.getTargetConstant(9, DL, MVT::i32), 9613 DAG.getTargetConstant(13, DL, MVT::i32), 9614 DAG.getTargetConstant(0, DL, MVT::i32) 9615 }; 9616 9617 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 9618 DAG.getVTList(MVT::i32, MVT::Other), Ops); 9619 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 9620 DAG.getConstant(0, DL, MVT::i32))); 9621 Results.push_back(Cycles32.getValue(1)); 9622 } 9623 9624 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 9625 SDLoc dl(V.getNode()); 9626 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 9627 SDValue VHi = DAG.getAnyExtOrTrunc( 9628 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 9629 dl, MVT::i32); 9630 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9631 if (isBigEndian) 9632 std::swap (VLo, VHi); 9633 SDValue RegClass = 9634 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 9635 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 9636 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 9637 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 9638 return SDValue( 9639 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 9640 } 9641 9642 static void ReplaceCMP_SWAP_64Results(SDNode *N, 9643 SmallVectorImpl<SDValue> & Results, 9644 SelectionDAG &DAG) { 9645 assert(N->getValueType(0) == MVT::i64 && 9646 "AtomicCmpSwap on types less than 64 should be legal"); 9647 SDValue Ops[] = {N->getOperand(1), 9648 createGPRPairNode(DAG, N->getOperand(2)), 9649 createGPRPairNode(DAG, N->getOperand(3)), 9650 N->getOperand(0)}; 9651 SDNode *CmpSwap = DAG.getMachineNode( 9652 ARM::CMP_SWAP_64, SDLoc(N), 9653 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 9654 9655 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 9656 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 9657 9658 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9659 9660 SDValue Lo = 9661 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 9662 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9663 SDValue Hi = 9664 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 9665 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9666 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi)); 9667 Results.push_back(SDValue(CmpSwap, 2)); 9668 } 9669 9670 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const { 9671 SDLoc dl(Op); 9672 EVT VT = Op.getValueType(); 9673 SDValue Chain = Op.getOperand(0); 9674 SDValue LHS = Op.getOperand(1); 9675 SDValue RHS = Op.getOperand(2); 9676 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get(); 9677 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 9678 9679 // If we don't have instructions of this float type then soften to a libcall 9680 // and use SETCC instead. 9681 if (isUnsupportedFloatingType(LHS.getValueType())) { 9682 DAG.getTargetLoweringInfo().softenSetCCOperands( 9683 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling); 9684 if (!RHS.getNode()) { 9685 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 9686 CC = ISD::SETNE; 9687 } 9688 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS, 9689 DAG.getCondCode(CC)); 9690 return DAG.getMergeValues({Result, Chain}, dl); 9691 } 9692 9693 ARMCC::CondCodes CondCode, CondCode2; 9694 FPCCToARMCC(CC, CondCode, CondCode2); 9695 9696 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit 9697 // in CMPFP and CMPFPE, but instead it should be made explicit by these 9698 // instructions using a chain instead of glue. This would also fix the problem 9699 // here (and also in LowerSELECT_CC) where we generate two comparisons when 9700 // CondCode2 != AL. 9701 SDValue True = DAG.getConstant(1, dl, VT); 9702 SDValue False = DAG.getConstant(0, dl, VT); 9703 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 9704 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 9705 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9706 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG); 9707 if (CondCode2 != ARMCC::AL) { 9708 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 9709 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9710 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG); 9711 } 9712 return DAG.getMergeValues({Result, Chain}, dl); 9713 } 9714 9715 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9716 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 9717 switch (Op.getOpcode()) { 9718 default: llvm_unreachable("Don't know how to custom lower this!"); 9719 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 9720 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9721 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9722 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9723 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9724 case ISD::SELECT: return LowerSELECT(Op, DAG); 9725 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9726 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9727 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 9728 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 9729 case ISD::VASTART: return LowerVASTART(Op, DAG); 9730 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 9731 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 9732 case ISD::SINT_TO_FP: 9733 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9734 case ISD::STRICT_FP_TO_SINT: 9735 case ISD::STRICT_FP_TO_UINT: 9736 case ISD::FP_TO_SINT: 9737 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 9738 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9739 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9740 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9741 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 9742 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 9743 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 9744 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget); 9745 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 9746 Subtarget); 9747 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 9748 case ISD::SHL: 9749 case ISD::SRL: 9750 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 9751 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 9752 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 9753 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 9754 case ISD::SRL_PARTS: 9755 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 9756 case ISD::CTTZ: 9757 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 9758 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 9759 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 9760 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 9761 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 9762 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 9763 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 9764 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 9765 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9766 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 9767 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 9768 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9769 case ISD::MUL: return LowerMUL(Op, DAG); 9770 case ISD::SDIV: 9771 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9772 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 9773 return LowerSDIV(Op, DAG, Subtarget); 9774 case ISD::UDIV: 9775 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9776 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 9777 return LowerUDIV(Op, DAG, Subtarget); 9778 case ISD::ADDCARRY: 9779 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 9780 case ISD::SADDO: 9781 case ISD::SSUBO: 9782 return LowerSignedALUO(Op, DAG); 9783 case ISD::UADDO: 9784 case ISD::USUBO: 9785 return LowerUnsignedALUO(Op, DAG); 9786 case ISD::SADDSAT: 9787 case ISD::SSUBSAT: 9788 return LowerSADDSUBSAT(Op, DAG, Subtarget); 9789 case ISD::LOAD: 9790 return LowerPredicateLoad(Op, DAG); 9791 case ISD::STORE: 9792 return LowerSTORE(Op, DAG, Subtarget); 9793 case ISD::MLOAD: 9794 return LowerMLOAD(Op, DAG); 9795 case ISD::VECREDUCE_MUL: 9796 case ISD::VECREDUCE_AND: 9797 case ISD::VECREDUCE_OR: 9798 case ISD::VECREDUCE_XOR: 9799 return LowerVecReduce(Op, DAG, Subtarget); 9800 case ISD::VECREDUCE_FADD: 9801 case ISD::VECREDUCE_FMUL: 9802 case ISD::VECREDUCE_FMIN: 9803 case ISD::VECREDUCE_FMAX: 9804 return LowerVecReduceF(Op, DAG, Subtarget); 9805 case ISD::ATOMIC_LOAD: 9806 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 9807 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 9808 case ISD::SDIVREM: 9809 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 9810 case ISD::DYNAMIC_STACKALLOC: 9811 if (Subtarget->isTargetWindows()) 9812 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9813 llvm_unreachable("Don't know how to custom lower this!"); 9814 case ISD::STRICT_FP_ROUND: 9815 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 9816 case ISD::STRICT_FP_EXTEND: 9817 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9818 case ISD::STRICT_FSETCC: 9819 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG); 9820 case ARMISD::WIN__DBZCHK: return SDValue(); 9821 } 9822 } 9823 9824 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 9825 SelectionDAG &DAG) { 9826 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9827 unsigned Opc = 0; 9828 if (IntNo == Intrinsic::arm_smlald) 9829 Opc = ARMISD::SMLALD; 9830 else if (IntNo == Intrinsic::arm_smlaldx) 9831 Opc = ARMISD::SMLALDX; 9832 else if (IntNo == Intrinsic::arm_smlsld) 9833 Opc = ARMISD::SMLSLD; 9834 else if (IntNo == Intrinsic::arm_smlsldx) 9835 Opc = ARMISD::SMLSLDX; 9836 else 9837 return; 9838 9839 SDLoc dl(N); 9840 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9841 N->getOperand(3), 9842 DAG.getConstant(0, dl, MVT::i32)); 9843 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9844 N->getOperand(3), 9845 DAG.getConstant(1, dl, MVT::i32)); 9846 9847 SDValue LongMul = DAG.getNode(Opc, dl, 9848 DAG.getVTList(MVT::i32, MVT::i32), 9849 N->getOperand(1), N->getOperand(2), 9850 Lo, Hi); 9851 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, 9852 LongMul.getValue(0), LongMul.getValue(1))); 9853 } 9854 9855 /// ReplaceNodeResults - Replace the results of node with an illegal result 9856 /// type with new values built out of custom code. 9857 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 9858 SmallVectorImpl<SDValue> &Results, 9859 SelectionDAG &DAG) const { 9860 SDValue Res; 9861 switch (N->getOpcode()) { 9862 default: 9863 llvm_unreachable("Don't know how to custom expand this!"); 9864 case ISD::READ_REGISTER: 9865 ExpandREAD_REGISTER(N, Results, DAG); 9866 break; 9867 case ISD::BITCAST: 9868 Res = ExpandBITCAST(N, DAG, Subtarget); 9869 break; 9870 case ISD::SRL: 9871 case ISD::SRA: 9872 case ISD::SHL: 9873 Res = Expand64BitShift(N, DAG, Subtarget); 9874 break; 9875 case ISD::SREM: 9876 case ISD::UREM: 9877 Res = LowerREM(N, DAG); 9878 break; 9879 case ISD::SDIVREM: 9880 case ISD::UDIVREM: 9881 Res = LowerDivRem(SDValue(N, 0), DAG); 9882 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 9883 Results.push_back(Res.getValue(0)); 9884 Results.push_back(Res.getValue(1)); 9885 return; 9886 case ISD::SADDSAT: 9887 case ISD::SSUBSAT: 9888 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget); 9889 break; 9890 case ISD::READCYCLECOUNTER: 9891 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 9892 return; 9893 case ISD::UDIV: 9894 case ISD::SDIV: 9895 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 9896 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 9897 Results); 9898 case ISD::ATOMIC_CMP_SWAP: 9899 ReplaceCMP_SWAP_64Results(N, Results, DAG); 9900 return; 9901 case ISD::INTRINSIC_WO_CHAIN: 9902 return ReplaceLongIntrinsic(N, Results, DAG); 9903 case ISD::ABS: 9904 lowerABS(N, Results, DAG); 9905 return ; 9906 case ISD::LOAD: 9907 LowerLOAD(N, Results, DAG); 9908 break; 9909 } 9910 if (Res.getNode()) 9911 Results.push_back(Res); 9912 } 9913 9914 //===----------------------------------------------------------------------===// 9915 // ARM Scheduler Hooks 9916 //===----------------------------------------------------------------------===// 9917 9918 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 9919 /// registers the function context. 9920 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 9921 MachineBasicBlock *MBB, 9922 MachineBasicBlock *DispatchBB, 9923 int FI) const { 9924 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 9925 "ROPI/RWPI not currently supported with SjLj"); 9926 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9927 DebugLoc dl = MI.getDebugLoc(); 9928 MachineFunction *MF = MBB->getParent(); 9929 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9930 MachineConstantPool *MCP = MF->getConstantPool(); 9931 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 9932 const Function &F = MF->getFunction(); 9933 9934 bool isThumb = Subtarget->isThumb(); 9935 bool isThumb2 = Subtarget->isThumb2(); 9936 9937 unsigned PCLabelId = AFI->createPICLabelUId(); 9938 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 9939 ARMConstantPoolValue *CPV = 9940 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 9941 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4)); 9942 9943 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 9944 : &ARM::GPRRegClass; 9945 9946 // Grab constant pool and fixed stack memory operands. 9947 MachineMemOperand *CPMMO = 9948 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9949 MachineMemOperand::MOLoad, 4, Align(4)); 9950 9951 MachineMemOperand *FIMMOSt = 9952 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 9953 MachineMemOperand::MOStore, 4, Align(4)); 9954 9955 // Load the address of the dispatch MBB into the jump buffer. 9956 if (isThumb2) { 9957 // Incoming value: jbuf 9958 // ldr.n r5, LCPI1_1 9959 // orr r5, r5, #1 9960 // add r5, pc 9961 // str r5, [$jbuf, #+4] ; &jbuf[1] 9962 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9963 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 9964 .addConstantPoolIndex(CPI) 9965 .addMemOperand(CPMMO) 9966 .add(predOps(ARMCC::AL)); 9967 // Set the low bit because of thumb mode. 9968 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9969 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 9970 .addReg(NewVReg1, RegState::Kill) 9971 .addImm(0x01) 9972 .add(predOps(ARMCC::AL)) 9973 .add(condCodeOp()); 9974 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9975 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 9976 .addReg(NewVReg2, RegState::Kill) 9977 .addImm(PCLabelId); 9978 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 9979 .addReg(NewVReg3, RegState::Kill) 9980 .addFrameIndex(FI) 9981 .addImm(36) // &jbuf[1] :: pc 9982 .addMemOperand(FIMMOSt) 9983 .add(predOps(ARMCC::AL)); 9984 } else if (isThumb) { 9985 // Incoming value: jbuf 9986 // ldr.n r1, LCPI1_4 9987 // add r1, pc 9988 // mov r2, #1 9989 // orrs r1, r2 9990 // add r2, $jbuf, #+4 ; &jbuf[1] 9991 // str r1, [r2] 9992 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9993 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 9994 .addConstantPoolIndex(CPI) 9995 .addMemOperand(CPMMO) 9996 .add(predOps(ARMCC::AL)); 9997 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9998 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 9999 .addReg(NewVReg1, RegState::Kill) 10000 .addImm(PCLabelId); 10001 // Set the low bit because of thumb mode. 10002 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10003 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 10004 .addReg(ARM::CPSR, RegState::Define) 10005 .addImm(1) 10006 .add(predOps(ARMCC::AL)); 10007 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10008 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 10009 .addReg(ARM::CPSR, RegState::Define) 10010 .addReg(NewVReg2, RegState::Kill) 10011 .addReg(NewVReg3, RegState::Kill) 10012 .add(predOps(ARMCC::AL)); 10013 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10014 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 10015 .addFrameIndex(FI) 10016 .addImm(36); // &jbuf[1] :: pc 10017 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 10018 .addReg(NewVReg4, RegState::Kill) 10019 .addReg(NewVReg5, RegState::Kill) 10020 .addImm(0) 10021 .addMemOperand(FIMMOSt) 10022 .add(predOps(ARMCC::AL)); 10023 } else { 10024 // Incoming value: jbuf 10025 // ldr r1, LCPI1_1 10026 // add r1, pc, r1 10027 // str r1, [$jbuf, #+4] ; &jbuf[1] 10028 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10029 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 10030 .addConstantPoolIndex(CPI) 10031 .addImm(0) 10032 .addMemOperand(CPMMO) 10033 .add(predOps(ARMCC::AL)); 10034 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10035 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 10036 .addReg(NewVReg1, RegState::Kill) 10037 .addImm(PCLabelId) 10038 .add(predOps(ARMCC::AL)); 10039 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 10040 .addReg(NewVReg2, RegState::Kill) 10041 .addFrameIndex(FI) 10042 .addImm(36) // &jbuf[1] :: pc 10043 .addMemOperand(FIMMOSt) 10044 .add(predOps(ARMCC::AL)); 10045 } 10046 } 10047 10048 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 10049 MachineBasicBlock *MBB) const { 10050 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10051 DebugLoc dl = MI.getDebugLoc(); 10052 MachineFunction *MF = MBB->getParent(); 10053 MachineRegisterInfo *MRI = &MF->getRegInfo(); 10054 MachineFrameInfo &MFI = MF->getFrameInfo(); 10055 int FI = MFI.getFunctionContextIndex(); 10056 10057 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 10058 : &ARM::GPRnopcRegClass; 10059 10060 // Get a mapping of the call site numbers to all of the landing pads they're 10061 // associated with. 10062 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 10063 unsigned MaxCSNum = 0; 10064 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 10065 ++BB) { 10066 if (!BB->isEHPad()) continue; 10067 10068 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 10069 // pad. 10070 for (MachineBasicBlock::iterator 10071 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 10072 if (!II->isEHLabel()) continue; 10073 10074 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 10075 if (!MF->hasCallSiteLandingPad(Sym)) continue; 10076 10077 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 10078 for (SmallVectorImpl<unsigned>::iterator 10079 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 10080 CSI != CSE; ++CSI) { 10081 CallSiteNumToLPad[*CSI].push_back(&*BB); 10082 MaxCSNum = std::max(MaxCSNum, *CSI); 10083 } 10084 break; 10085 } 10086 } 10087 10088 // Get an ordered list of the machine basic blocks for the jump table. 10089 std::vector<MachineBasicBlock*> LPadList; 10090 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 10091 LPadList.reserve(CallSiteNumToLPad.size()); 10092 for (unsigned I = 1; I <= MaxCSNum; ++I) { 10093 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 10094 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10095 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 10096 LPadList.push_back(*II); 10097 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 10098 } 10099 } 10100 10101 assert(!LPadList.empty() && 10102 "No landing pad destinations for the dispatch jump table!"); 10103 10104 // Create the jump table and associated information. 10105 MachineJumpTableInfo *JTI = 10106 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 10107 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 10108 10109 // Create the MBBs for the dispatch code. 10110 10111 // Shove the dispatch's address into the return slot in the function context. 10112 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 10113 DispatchBB->setIsEHPad(); 10114 10115 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10116 unsigned trap_opcode; 10117 if (Subtarget->isThumb()) 10118 trap_opcode = ARM::tTRAP; 10119 else 10120 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 10121 10122 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 10123 DispatchBB->addSuccessor(TrapBB); 10124 10125 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 10126 DispatchBB->addSuccessor(DispContBB); 10127 10128 // Insert and MBBs. 10129 MF->insert(MF->end(), DispatchBB); 10130 MF->insert(MF->end(), DispContBB); 10131 MF->insert(MF->end(), TrapBB); 10132 10133 // Insert code into the entry block that creates and registers the function 10134 // context. 10135 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 10136 10137 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 10138 MachinePointerInfo::getFixedStack(*MF, FI), 10139 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4)); 10140 10141 MachineInstrBuilder MIB; 10142 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 10143 10144 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 10145 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 10146 10147 // Add a register mask with no preserved registers. This results in all 10148 // registers being marked as clobbered. This can't work if the dispatch block 10149 // is in a Thumb1 function and is linked with ARM code which uses the FP 10150 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 10151 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 10152 10153 bool IsPositionIndependent = isPositionIndependent(); 10154 unsigned NumLPads = LPadList.size(); 10155 if (Subtarget->isThumb2()) { 10156 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10157 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 10158 .addFrameIndex(FI) 10159 .addImm(4) 10160 .addMemOperand(FIMMOLd) 10161 .add(predOps(ARMCC::AL)); 10162 10163 if (NumLPads < 256) { 10164 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 10165 .addReg(NewVReg1) 10166 .addImm(LPadList.size()) 10167 .add(predOps(ARMCC::AL)); 10168 } else { 10169 Register VReg1 = MRI->createVirtualRegister(TRC); 10170 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 10171 .addImm(NumLPads & 0xFFFF) 10172 .add(predOps(ARMCC::AL)); 10173 10174 unsigned VReg2 = VReg1; 10175 if ((NumLPads & 0xFFFF0000) != 0) { 10176 VReg2 = MRI->createVirtualRegister(TRC); 10177 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 10178 .addReg(VReg1) 10179 .addImm(NumLPads >> 16) 10180 .add(predOps(ARMCC::AL)); 10181 } 10182 10183 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 10184 .addReg(NewVReg1) 10185 .addReg(VReg2) 10186 .add(predOps(ARMCC::AL)); 10187 } 10188 10189 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 10190 .addMBB(TrapBB) 10191 .addImm(ARMCC::HI) 10192 .addReg(ARM::CPSR); 10193 10194 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10195 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 10196 .addJumpTableIndex(MJTI) 10197 .add(predOps(ARMCC::AL)); 10198 10199 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10200 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 10201 .addReg(NewVReg3, RegState::Kill) 10202 .addReg(NewVReg1) 10203 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10204 .add(predOps(ARMCC::AL)) 10205 .add(condCodeOp()); 10206 10207 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 10208 .addReg(NewVReg4, RegState::Kill) 10209 .addReg(NewVReg1) 10210 .addJumpTableIndex(MJTI); 10211 } else if (Subtarget->isThumb()) { 10212 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10213 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 10214 .addFrameIndex(FI) 10215 .addImm(1) 10216 .addMemOperand(FIMMOLd) 10217 .add(predOps(ARMCC::AL)); 10218 10219 if (NumLPads < 256) { 10220 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 10221 .addReg(NewVReg1) 10222 .addImm(NumLPads) 10223 .add(predOps(ARMCC::AL)); 10224 } else { 10225 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10226 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10227 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 10228 10229 // MachineConstantPool wants an explicit alignment. 10230 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10231 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10232 10233 Register VReg1 = MRI->createVirtualRegister(TRC); 10234 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 10235 .addReg(VReg1, RegState::Define) 10236 .addConstantPoolIndex(Idx) 10237 .add(predOps(ARMCC::AL)); 10238 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 10239 .addReg(NewVReg1) 10240 .addReg(VReg1) 10241 .add(predOps(ARMCC::AL)); 10242 } 10243 10244 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 10245 .addMBB(TrapBB) 10246 .addImm(ARMCC::HI) 10247 .addReg(ARM::CPSR); 10248 10249 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10250 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 10251 .addReg(ARM::CPSR, RegState::Define) 10252 .addReg(NewVReg1) 10253 .addImm(2) 10254 .add(predOps(ARMCC::AL)); 10255 10256 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10257 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 10258 .addJumpTableIndex(MJTI) 10259 .add(predOps(ARMCC::AL)); 10260 10261 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10262 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 10263 .addReg(ARM::CPSR, RegState::Define) 10264 .addReg(NewVReg2, RegState::Kill) 10265 .addReg(NewVReg3) 10266 .add(predOps(ARMCC::AL)); 10267 10268 MachineMemOperand *JTMMOLd = 10269 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10270 MachineMemOperand::MOLoad, 4, Align(4)); 10271 10272 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10273 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 10274 .addReg(NewVReg4, RegState::Kill) 10275 .addImm(0) 10276 .addMemOperand(JTMMOLd) 10277 .add(predOps(ARMCC::AL)); 10278 10279 unsigned NewVReg6 = NewVReg5; 10280 if (IsPositionIndependent) { 10281 NewVReg6 = MRI->createVirtualRegister(TRC); 10282 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 10283 .addReg(ARM::CPSR, RegState::Define) 10284 .addReg(NewVReg5, RegState::Kill) 10285 .addReg(NewVReg3) 10286 .add(predOps(ARMCC::AL)); 10287 } 10288 10289 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 10290 .addReg(NewVReg6, RegState::Kill) 10291 .addJumpTableIndex(MJTI); 10292 } else { 10293 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10294 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 10295 .addFrameIndex(FI) 10296 .addImm(4) 10297 .addMemOperand(FIMMOLd) 10298 .add(predOps(ARMCC::AL)); 10299 10300 if (NumLPads < 256) { 10301 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 10302 .addReg(NewVReg1) 10303 .addImm(NumLPads) 10304 .add(predOps(ARMCC::AL)); 10305 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 10306 Register VReg1 = MRI->createVirtualRegister(TRC); 10307 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 10308 .addImm(NumLPads & 0xFFFF) 10309 .add(predOps(ARMCC::AL)); 10310 10311 unsigned VReg2 = VReg1; 10312 if ((NumLPads & 0xFFFF0000) != 0) { 10313 VReg2 = MRI->createVirtualRegister(TRC); 10314 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 10315 .addReg(VReg1) 10316 .addImm(NumLPads >> 16) 10317 .add(predOps(ARMCC::AL)); 10318 } 10319 10320 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 10321 .addReg(NewVReg1) 10322 .addReg(VReg2) 10323 .add(predOps(ARMCC::AL)); 10324 } else { 10325 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10326 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10327 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 10328 10329 // MachineConstantPool wants an explicit alignment. 10330 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10331 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10332 10333 Register VReg1 = MRI->createVirtualRegister(TRC); 10334 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 10335 .addReg(VReg1, RegState::Define) 10336 .addConstantPoolIndex(Idx) 10337 .addImm(0) 10338 .add(predOps(ARMCC::AL)); 10339 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 10340 .addReg(NewVReg1) 10341 .addReg(VReg1, RegState::Kill) 10342 .add(predOps(ARMCC::AL)); 10343 } 10344 10345 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 10346 .addMBB(TrapBB) 10347 .addImm(ARMCC::HI) 10348 .addReg(ARM::CPSR); 10349 10350 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10351 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 10352 .addReg(NewVReg1) 10353 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10354 .add(predOps(ARMCC::AL)) 10355 .add(condCodeOp()); 10356 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10357 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 10358 .addJumpTableIndex(MJTI) 10359 .add(predOps(ARMCC::AL)); 10360 10361 MachineMemOperand *JTMMOLd = 10362 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10363 MachineMemOperand::MOLoad, 4, Align(4)); 10364 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10365 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 10366 .addReg(NewVReg3, RegState::Kill) 10367 .addReg(NewVReg4) 10368 .addImm(0) 10369 .addMemOperand(JTMMOLd) 10370 .add(predOps(ARMCC::AL)); 10371 10372 if (IsPositionIndependent) { 10373 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 10374 .addReg(NewVReg5, RegState::Kill) 10375 .addReg(NewVReg4) 10376 .addJumpTableIndex(MJTI); 10377 } else { 10378 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 10379 .addReg(NewVReg5, RegState::Kill) 10380 .addJumpTableIndex(MJTI); 10381 } 10382 } 10383 10384 // Add the jump table entries as successors to the MBB. 10385 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 10386 for (std::vector<MachineBasicBlock*>::iterator 10387 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 10388 MachineBasicBlock *CurMBB = *I; 10389 if (SeenMBBs.insert(CurMBB).second) 10390 DispContBB->addSuccessor(CurMBB); 10391 } 10392 10393 // N.B. the order the invoke BBs are processed in doesn't matter here. 10394 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 10395 SmallVector<MachineBasicBlock*, 64> MBBLPads; 10396 for (MachineBasicBlock *BB : InvokeBBs) { 10397 10398 // Remove the landing pad successor from the invoke block and replace it 10399 // with the new dispatch block. 10400 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 10401 BB->succ_end()); 10402 while (!Successors.empty()) { 10403 MachineBasicBlock *SMBB = Successors.pop_back_val(); 10404 if (SMBB->isEHPad()) { 10405 BB->removeSuccessor(SMBB); 10406 MBBLPads.push_back(SMBB); 10407 } 10408 } 10409 10410 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 10411 BB->normalizeSuccProbs(); 10412 10413 // Find the invoke call and mark all of the callee-saved registers as 10414 // 'implicit defined' so that they're spilled. This prevents code from 10415 // moving instructions to before the EH block, where they will never be 10416 // executed. 10417 for (MachineBasicBlock::reverse_iterator 10418 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 10419 if (!II->isCall()) continue; 10420 10421 DenseMap<unsigned, bool> DefRegs; 10422 for (MachineInstr::mop_iterator 10423 OI = II->operands_begin(), OE = II->operands_end(); 10424 OI != OE; ++OI) { 10425 if (!OI->isReg()) continue; 10426 DefRegs[OI->getReg()] = true; 10427 } 10428 10429 MachineInstrBuilder MIB(*MF, &*II); 10430 10431 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 10432 unsigned Reg = SavedRegs[i]; 10433 if (Subtarget->isThumb2() && 10434 !ARM::tGPRRegClass.contains(Reg) && 10435 !ARM::hGPRRegClass.contains(Reg)) 10436 continue; 10437 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 10438 continue; 10439 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 10440 continue; 10441 if (!DefRegs[Reg]) 10442 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 10443 } 10444 10445 break; 10446 } 10447 } 10448 10449 // Mark all former landing pads as non-landing pads. The dispatch is the only 10450 // landing pad now. 10451 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10452 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 10453 (*I)->setIsEHPad(false); 10454 10455 // The instruction is gone now. 10456 MI.eraseFromParent(); 10457 } 10458 10459 static 10460 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 10461 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 10462 E = MBB->succ_end(); I != E; ++I) 10463 if (*I != Succ) 10464 return *I; 10465 llvm_unreachable("Expecting a BB with two successors!"); 10466 } 10467 10468 /// Return the load opcode for a given load size. If load size >= 8, 10469 /// neon opcode will be returned. 10470 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 10471 if (LdSize >= 8) 10472 return LdSize == 16 ? ARM::VLD1q32wb_fixed 10473 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 10474 if (IsThumb1) 10475 return LdSize == 4 ? ARM::tLDRi 10476 : LdSize == 2 ? ARM::tLDRHi 10477 : LdSize == 1 ? ARM::tLDRBi : 0; 10478 if (IsThumb2) 10479 return LdSize == 4 ? ARM::t2LDR_POST 10480 : LdSize == 2 ? ARM::t2LDRH_POST 10481 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 10482 return LdSize == 4 ? ARM::LDR_POST_IMM 10483 : LdSize == 2 ? ARM::LDRH_POST 10484 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 10485 } 10486 10487 /// Return the store opcode for a given store size. If store size >= 8, 10488 /// neon opcode will be returned. 10489 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 10490 if (StSize >= 8) 10491 return StSize == 16 ? ARM::VST1q32wb_fixed 10492 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 10493 if (IsThumb1) 10494 return StSize == 4 ? ARM::tSTRi 10495 : StSize == 2 ? ARM::tSTRHi 10496 : StSize == 1 ? ARM::tSTRBi : 0; 10497 if (IsThumb2) 10498 return StSize == 4 ? ARM::t2STR_POST 10499 : StSize == 2 ? ARM::t2STRH_POST 10500 : StSize == 1 ? ARM::t2STRB_POST : 0; 10501 return StSize == 4 ? ARM::STR_POST_IMM 10502 : StSize == 2 ? ARM::STRH_POST 10503 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 10504 } 10505 10506 /// Emit a post-increment load operation with given size. The instructions 10507 /// will be added to BB at Pos. 10508 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10509 const TargetInstrInfo *TII, const DebugLoc &dl, 10510 unsigned LdSize, unsigned Data, unsigned AddrIn, 10511 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10512 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 10513 assert(LdOpc != 0 && "Should have a load opcode"); 10514 if (LdSize >= 8) { 10515 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10516 .addReg(AddrOut, RegState::Define) 10517 .addReg(AddrIn) 10518 .addImm(0) 10519 .add(predOps(ARMCC::AL)); 10520 } else if (IsThumb1) { 10521 // load + update AddrIn 10522 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10523 .addReg(AddrIn) 10524 .addImm(0) 10525 .add(predOps(ARMCC::AL)); 10526 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10527 .add(t1CondCodeOp()) 10528 .addReg(AddrIn) 10529 .addImm(LdSize) 10530 .add(predOps(ARMCC::AL)); 10531 } else if (IsThumb2) { 10532 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10533 .addReg(AddrOut, RegState::Define) 10534 .addReg(AddrIn) 10535 .addImm(LdSize) 10536 .add(predOps(ARMCC::AL)); 10537 } else { // arm 10538 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10539 .addReg(AddrOut, RegState::Define) 10540 .addReg(AddrIn) 10541 .addReg(0) 10542 .addImm(LdSize) 10543 .add(predOps(ARMCC::AL)); 10544 } 10545 } 10546 10547 /// Emit a post-increment store operation with given size. The instructions 10548 /// will be added to BB at Pos. 10549 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10550 const TargetInstrInfo *TII, const DebugLoc &dl, 10551 unsigned StSize, unsigned Data, unsigned AddrIn, 10552 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10553 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 10554 assert(StOpc != 0 && "Should have a store opcode"); 10555 if (StSize >= 8) { 10556 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10557 .addReg(AddrIn) 10558 .addImm(0) 10559 .addReg(Data) 10560 .add(predOps(ARMCC::AL)); 10561 } else if (IsThumb1) { 10562 // store + update AddrIn 10563 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 10564 .addReg(Data) 10565 .addReg(AddrIn) 10566 .addImm(0) 10567 .add(predOps(ARMCC::AL)); 10568 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10569 .add(t1CondCodeOp()) 10570 .addReg(AddrIn) 10571 .addImm(StSize) 10572 .add(predOps(ARMCC::AL)); 10573 } else if (IsThumb2) { 10574 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10575 .addReg(Data) 10576 .addReg(AddrIn) 10577 .addImm(StSize) 10578 .add(predOps(ARMCC::AL)); 10579 } else { // arm 10580 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10581 .addReg(Data) 10582 .addReg(AddrIn) 10583 .addReg(0) 10584 .addImm(StSize) 10585 .add(predOps(ARMCC::AL)); 10586 } 10587 } 10588 10589 MachineBasicBlock * 10590 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 10591 MachineBasicBlock *BB) const { 10592 // This pseudo instruction has 3 operands: dst, src, size 10593 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 10594 // Otherwise, we will generate unrolled scalar copies. 10595 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10596 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10597 MachineFunction::iterator It = ++BB->getIterator(); 10598 10599 Register dest = MI.getOperand(0).getReg(); 10600 Register src = MI.getOperand(1).getReg(); 10601 unsigned SizeVal = MI.getOperand(2).getImm(); 10602 unsigned Alignment = MI.getOperand(3).getImm(); 10603 DebugLoc dl = MI.getDebugLoc(); 10604 10605 MachineFunction *MF = BB->getParent(); 10606 MachineRegisterInfo &MRI = MF->getRegInfo(); 10607 unsigned UnitSize = 0; 10608 const TargetRegisterClass *TRC = nullptr; 10609 const TargetRegisterClass *VecTRC = nullptr; 10610 10611 bool IsThumb1 = Subtarget->isThumb1Only(); 10612 bool IsThumb2 = Subtarget->isThumb2(); 10613 bool IsThumb = Subtarget->isThumb(); 10614 10615 if (Alignment & 1) { 10616 UnitSize = 1; 10617 } else if (Alignment & 2) { 10618 UnitSize = 2; 10619 } else { 10620 // Check whether we can use NEON instructions. 10621 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 10622 Subtarget->hasNEON()) { 10623 if ((Alignment % 16 == 0) && SizeVal >= 16) 10624 UnitSize = 16; 10625 else if ((Alignment % 8 == 0) && SizeVal >= 8) 10626 UnitSize = 8; 10627 } 10628 // Can't use NEON instructions. 10629 if (UnitSize == 0) 10630 UnitSize = 4; 10631 } 10632 10633 // Select the correct opcode and register class for unit size load/store 10634 bool IsNeon = UnitSize >= 8; 10635 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 10636 if (IsNeon) 10637 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 10638 : UnitSize == 8 ? &ARM::DPRRegClass 10639 : nullptr; 10640 10641 unsigned BytesLeft = SizeVal % UnitSize; 10642 unsigned LoopSize = SizeVal - BytesLeft; 10643 10644 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 10645 // Use LDR and STR to copy. 10646 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 10647 // [destOut] = STR_POST(scratch, destIn, UnitSize) 10648 unsigned srcIn = src; 10649 unsigned destIn = dest; 10650 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 10651 Register srcOut = MRI.createVirtualRegister(TRC); 10652 Register destOut = MRI.createVirtualRegister(TRC); 10653 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10654 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 10655 IsThumb1, IsThumb2); 10656 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 10657 IsThumb1, IsThumb2); 10658 srcIn = srcOut; 10659 destIn = destOut; 10660 } 10661 10662 // Handle the leftover bytes with LDRB and STRB. 10663 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 10664 // [destOut] = STRB_POST(scratch, destIn, 1) 10665 for (unsigned i = 0; i < BytesLeft; i++) { 10666 Register srcOut = MRI.createVirtualRegister(TRC); 10667 Register destOut = MRI.createVirtualRegister(TRC); 10668 Register scratch = MRI.createVirtualRegister(TRC); 10669 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 10670 IsThumb1, IsThumb2); 10671 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 10672 IsThumb1, IsThumb2); 10673 srcIn = srcOut; 10674 destIn = destOut; 10675 } 10676 MI.eraseFromParent(); // The instruction is gone now. 10677 return BB; 10678 } 10679 10680 // Expand the pseudo op to a loop. 10681 // thisMBB: 10682 // ... 10683 // movw varEnd, # --> with thumb2 10684 // movt varEnd, # 10685 // ldrcp varEnd, idx --> without thumb2 10686 // fallthrough --> loopMBB 10687 // loopMBB: 10688 // PHI varPhi, varEnd, varLoop 10689 // PHI srcPhi, src, srcLoop 10690 // PHI destPhi, dst, destLoop 10691 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10692 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 10693 // subs varLoop, varPhi, #UnitSize 10694 // bne loopMBB 10695 // fallthrough --> exitMBB 10696 // exitMBB: 10697 // epilogue to handle left-over bytes 10698 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10699 // [destOut] = STRB_POST(scratch, destLoop, 1) 10700 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10701 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10702 MF->insert(It, loopMBB); 10703 MF->insert(It, exitMBB); 10704 10705 // Transfer the remainder of BB and its successor edges to exitMBB. 10706 exitMBB->splice(exitMBB->begin(), BB, 10707 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10708 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10709 10710 // Load an immediate to varEnd. 10711 Register varEnd = MRI.createVirtualRegister(TRC); 10712 if (Subtarget->useMovt()) { 10713 unsigned Vtmp = varEnd; 10714 if ((LoopSize & 0xFFFF0000) != 0) 10715 Vtmp = MRI.createVirtualRegister(TRC); 10716 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 10717 .addImm(LoopSize & 0xFFFF) 10718 .add(predOps(ARMCC::AL)); 10719 10720 if ((LoopSize & 0xFFFF0000) != 0) 10721 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 10722 .addReg(Vtmp) 10723 .addImm(LoopSize >> 16) 10724 .add(predOps(ARMCC::AL)); 10725 } else { 10726 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10727 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10728 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 10729 10730 // MachineConstantPool wants an explicit alignment. 10731 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10732 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10733 MachineMemOperand *CPMMO = 10734 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 10735 MachineMemOperand::MOLoad, 4, Align(4)); 10736 10737 if (IsThumb) 10738 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 10739 .addReg(varEnd, RegState::Define) 10740 .addConstantPoolIndex(Idx) 10741 .add(predOps(ARMCC::AL)) 10742 .addMemOperand(CPMMO); 10743 else 10744 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 10745 .addReg(varEnd, RegState::Define) 10746 .addConstantPoolIndex(Idx) 10747 .addImm(0) 10748 .add(predOps(ARMCC::AL)) 10749 .addMemOperand(CPMMO); 10750 } 10751 BB->addSuccessor(loopMBB); 10752 10753 // Generate the loop body: 10754 // varPhi = PHI(varLoop, varEnd) 10755 // srcPhi = PHI(srcLoop, src) 10756 // destPhi = PHI(destLoop, dst) 10757 MachineBasicBlock *entryBB = BB; 10758 BB = loopMBB; 10759 Register varLoop = MRI.createVirtualRegister(TRC); 10760 Register varPhi = MRI.createVirtualRegister(TRC); 10761 Register srcLoop = MRI.createVirtualRegister(TRC); 10762 Register srcPhi = MRI.createVirtualRegister(TRC); 10763 Register destLoop = MRI.createVirtualRegister(TRC); 10764 Register destPhi = MRI.createVirtualRegister(TRC); 10765 10766 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 10767 .addReg(varLoop).addMBB(loopMBB) 10768 .addReg(varEnd).addMBB(entryBB); 10769 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 10770 .addReg(srcLoop).addMBB(loopMBB) 10771 .addReg(src).addMBB(entryBB); 10772 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 10773 .addReg(destLoop).addMBB(loopMBB) 10774 .addReg(dest).addMBB(entryBB); 10775 10776 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10777 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 10778 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10779 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 10780 IsThumb1, IsThumb2); 10781 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 10782 IsThumb1, IsThumb2); 10783 10784 // Decrement loop variable by UnitSize. 10785 if (IsThumb1) { 10786 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 10787 .add(t1CondCodeOp()) 10788 .addReg(varPhi) 10789 .addImm(UnitSize) 10790 .add(predOps(ARMCC::AL)); 10791 } else { 10792 MachineInstrBuilder MIB = 10793 BuildMI(*BB, BB->end(), dl, 10794 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 10795 MIB.addReg(varPhi) 10796 .addImm(UnitSize) 10797 .add(predOps(ARMCC::AL)) 10798 .add(condCodeOp()); 10799 MIB->getOperand(5).setReg(ARM::CPSR); 10800 MIB->getOperand(5).setIsDef(true); 10801 } 10802 BuildMI(*BB, BB->end(), dl, 10803 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10804 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 10805 10806 // loopMBB can loop back to loopMBB or fall through to exitMBB. 10807 BB->addSuccessor(loopMBB); 10808 BB->addSuccessor(exitMBB); 10809 10810 // Add epilogue to handle BytesLeft. 10811 BB = exitMBB; 10812 auto StartOfExit = exitMBB->begin(); 10813 10814 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10815 // [destOut] = STRB_POST(scratch, destLoop, 1) 10816 unsigned srcIn = srcLoop; 10817 unsigned destIn = destLoop; 10818 for (unsigned i = 0; i < BytesLeft; i++) { 10819 Register srcOut = MRI.createVirtualRegister(TRC); 10820 Register destOut = MRI.createVirtualRegister(TRC); 10821 Register scratch = MRI.createVirtualRegister(TRC); 10822 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 10823 IsThumb1, IsThumb2); 10824 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 10825 IsThumb1, IsThumb2); 10826 srcIn = srcOut; 10827 destIn = destOut; 10828 } 10829 10830 MI.eraseFromParent(); // The instruction is gone now. 10831 return BB; 10832 } 10833 10834 MachineBasicBlock * 10835 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 10836 MachineBasicBlock *MBB) const { 10837 const TargetMachine &TM = getTargetMachine(); 10838 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 10839 DebugLoc DL = MI.getDebugLoc(); 10840 10841 assert(Subtarget->isTargetWindows() && 10842 "__chkstk is only supported on Windows"); 10843 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 10844 10845 // __chkstk takes the number of words to allocate on the stack in R4, and 10846 // returns the stack adjustment in number of bytes in R4. This will not 10847 // clober any other registers (other than the obvious lr). 10848 // 10849 // Although, technically, IP should be considered a register which may be 10850 // clobbered, the call itself will not touch it. Windows on ARM is a pure 10851 // thumb-2 environment, so there is no interworking required. As a result, we 10852 // do not expect a veneer to be emitted by the linker, clobbering IP. 10853 // 10854 // Each module receives its own copy of __chkstk, so no import thunk is 10855 // required, again, ensuring that IP is not clobbered. 10856 // 10857 // Finally, although some linkers may theoretically provide a trampoline for 10858 // out of range calls (which is quite common due to a 32M range limitation of 10859 // branches for Thumb), we can generate the long-call version via 10860 // -mcmodel=large, alleviating the need for the trampoline which may clobber 10861 // IP. 10862 10863 switch (TM.getCodeModel()) { 10864 case CodeModel::Tiny: 10865 llvm_unreachable("Tiny code model not available on ARM."); 10866 case CodeModel::Small: 10867 case CodeModel::Medium: 10868 case CodeModel::Kernel: 10869 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 10870 .add(predOps(ARMCC::AL)) 10871 .addExternalSymbol("__chkstk") 10872 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10873 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10874 .addReg(ARM::R12, 10875 RegState::Implicit | RegState::Define | RegState::Dead) 10876 .addReg(ARM::CPSR, 10877 RegState::Implicit | RegState::Define | RegState::Dead); 10878 break; 10879 case CodeModel::Large: { 10880 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 10881 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 10882 10883 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 10884 .addExternalSymbol("__chkstk"); 10885 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 10886 .add(predOps(ARMCC::AL)) 10887 .addReg(Reg, RegState::Kill) 10888 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10889 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10890 .addReg(ARM::R12, 10891 RegState::Implicit | RegState::Define | RegState::Dead) 10892 .addReg(ARM::CPSR, 10893 RegState::Implicit | RegState::Define | RegState::Dead); 10894 break; 10895 } 10896 } 10897 10898 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 10899 .addReg(ARM::SP, RegState::Kill) 10900 .addReg(ARM::R4, RegState::Kill) 10901 .setMIFlags(MachineInstr::FrameSetup) 10902 .add(predOps(ARMCC::AL)) 10903 .add(condCodeOp()); 10904 10905 MI.eraseFromParent(); 10906 return MBB; 10907 } 10908 10909 MachineBasicBlock * 10910 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 10911 MachineBasicBlock *MBB) const { 10912 DebugLoc DL = MI.getDebugLoc(); 10913 MachineFunction *MF = MBB->getParent(); 10914 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10915 10916 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 10917 MF->insert(++MBB->getIterator(), ContBB); 10918 ContBB->splice(ContBB->begin(), MBB, 10919 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10920 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 10921 MBB->addSuccessor(ContBB); 10922 10923 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10924 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 10925 MF->push_back(TrapBB); 10926 MBB->addSuccessor(TrapBB); 10927 10928 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 10929 .addReg(MI.getOperand(0).getReg()) 10930 .addImm(0) 10931 .add(predOps(ARMCC::AL)); 10932 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 10933 .addMBB(TrapBB) 10934 .addImm(ARMCC::EQ) 10935 .addReg(ARM::CPSR); 10936 10937 MI.eraseFromParent(); 10938 return ContBB; 10939 } 10940 10941 // The CPSR operand of SelectItr might be missing a kill marker 10942 // because there were multiple uses of CPSR, and ISel didn't know 10943 // which to mark. Figure out whether SelectItr should have had a 10944 // kill marker, and set it if it should. Returns the correct kill 10945 // marker value. 10946 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 10947 MachineBasicBlock* BB, 10948 const TargetRegisterInfo* TRI) { 10949 // Scan forward through BB for a use/def of CPSR. 10950 MachineBasicBlock::iterator miI(std::next(SelectItr)); 10951 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 10952 const MachineInstr& mi = *miI; 10953 if (mi.readsRegister(ARM::CPSR)) 10954 return false; 10955 if (mi.definesRegister(ARM::CPSR)) 10956 break; // Should have kill-flag - update below. 10957 } 10958 10959 // If we hit the end of the block, check whether CPSR is live into a 10960 // successor. 10961 if (miI == BB->end()) { 10962 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 10963 sEnd = BB->succ_end(); 10964 sItr != sEnd; ++sItr) { 10965 MachineBasicBlock* succ = *sItr; 10966 if (succ->isLiveIn(ARM::CPSR)) 10967 return false; 10968 } 10969 } 10970 10971 // We found a def, or hit the end of the basic block and CPSR wasn't live 10972 // out. SelectMI should have a kill flag on CPSR. 10973 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 10974 return true; 10975 } 10976 10977 MachineBasicBlock * 10978 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10979 MachineBasicBlock *BB) const { 10980 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10981 DebugLoc dl = MI.getDebugLoc(); 10982 bool isThumb2 = Subtarget->isThumb2(); 10983 switch (MI.getOpcode()) { 10984 default: { 10985 MI.print(errs()); 10986 llvm_unreachable("Unexpected instr type to insert"); 10987 } 10988 10989 // Thumb1 post-indexed loads are really just single-register LDMs. 10990 case ARM::tLDR_postidx: { 10991 MachineOperand Def(MI.getOperand(1)); 10992 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 10993 .add(Def) // Rn_wb 10994 .add(MI.getOperand(2)) // Rn 10995 .add(MI.getOperand(3)) // PredImm 10996 .add(MI.getOperand(4)) // PredReg 10997 .add(MI.getOperand(0)) // Rt 10998 .cloneMemRefs(MI); 10999 MI.eraseFromParent(); 11000 return BB; 11001 } 11002 11003 // The Thumb2 pre-indexed stores have the same MI operands, they just 11004 // define them differently in the .td files from the isel patterns, so 11005 // they need pseudos. 11006 case ARM::t2STR_preidx: 11007 MI.setDesc(TII->get(ARM::t2STR_PRE)); 11008 return BB; 11009 case ARM::t2STRB_preidx: 11010 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 11011 return BB; 11012 case ARM::t2STRH_preidx: 11013 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 11014 return BB; 11015 11016 case ARM::STRi_preidx: 11017 case ARM::STRBi_preidx: { 11018 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 11019 : ARM::STRB_PRE_IMM; 11020 // Decode the offset. 11021 unsigned Offset = MI.getOperand(4).getImm(); 11022 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 11023 Offset = ARM_AM::getAM2Offset(Offset); 11024 if (isSub) 11025 Offset = -Offset; 11026 11027 MachineMemOperand *MMO = *MI.memoperands_begin(); 11028 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 11029 .add(MI.getOperand(0)) // Rn_wb 11030 .add(MI.getOperand(1)) // Rt 11031 .add(MI.getOperand(2)) // Rn 11032 .addImm(Offset) // offset (skip GPR==zero_reg) 11033 .add(MI.getOperand(5)) // pred 11034 .add(MI.getOperand(6)) 11035 .addMemOperand(MMO); 11036 MI.eraseFromParent(); 11037 return BB; 11038 } 11039 case ARM::STRr_preidx: 11040 case ARM::STRBr_preidx: 11041 case ARM::STRH_preidx: { 11042 unsigned NewOpc; 11043 switch (MI.getOpcode()) { 11044 default: llvm_unreachable("unexpected opcode!"); 11045 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 11046 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 11047 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 11048 } 11049 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 11050 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 11051 MIB.add(MI.getOperand(i)); 11052 MI.eraseFromParent(); 11053 return BB; 11054 } 11055 11056 case ARM::tMOVCCr_pseudo: { 11057 // To "insert" a SELECT_CC instruction, we actually have to insert the 11058 // diamond control-flow pattern. The incoming instruction knows the 11059 // destination vreg to set, the condition code register to branch on, the 11060 // true/false values to select between, and a branch opcode to use. 11061 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11062 MachineFunction::iterator It = ++BB->getIterator(); 11063 11064 // thisMBB: 11065 // ... 11066 // TrueVal = ... 11067 // cmpTY ccX, r1, r2 11068 // bCC copy1MBB 11069 // fallthrough --> copy0MBB 11070 MachineBasicBlock *thisMBB = BB; 11071 MachineFunction *F = BB->getParent(); 11072 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11073 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11074 F->insert(It, copy0MBB); 11075 F->insert(It, sinkMBB); 11076 11077 // Check whether CPSR is live past the tMOVCCr_pseudo. 11078 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11079 if (!MI.killsRegister(ARM::CPSR) && 11080 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 11081 copy0MBB->addLiveIn(ARM::CPSR); 11082 sinkMBB->addLiveIn(ARM::CPSR); 11083 } 11084 11085 // Transfer the remainder of BB and its successor edges to sinkMBB. 11086 sinkMBB->splice(sinkMBB->begin(), BB, 11087 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11088 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11089 11090 BB->addSuccessor(copy0MBB); 11091 BB->addSuccessor(sinkMBB); 11092 11093 BuildMI(BB, dl, TII->get(ARM::tBcc)) 11094 .addMBB(sinkMBB) 11095 .addImm(MI.getOperand(3).getImm()) 11096 .addReg(MI.getOperand(4).getReg()); 11097 11098 // copy0MBB: 11099 // %FalseValue = ... 11100 // # fallthrough to sinkMBB 11101 BB = copy0MBB; 11102 11103 // Update machine-CFG edges 11104 BB->addSuccessor(sinkMBB); 11105 11106 // sinkMBB: 11107 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11108 // ... 11109 BB = sinkMBB; 11110 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 11111 .addReg(MI.getOperand(1).getReg()) 11112 .addMBB(copy0MBB) 11113 .addReg(MI.getOperand(2).getReg()) 11114 .addMBB(thisMBB); 11115 11116 MI.eraseFromParent(); // The pseudo instruction is gone now. 11117 return BB; 11118 } 11119 11120 case ARM::BCCi64: 11121 case ARM::BCCZi64: { 11122 // If there is an unconditional branch to the other successor, remove it. 11123 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11124 11125 // Compare both parts that make up the double comparison separately for 11126 // equality. 11127 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 11128 11129 Register LHS1 = MI.getOperand(1).getReg(); 11130 Register LHS2 = MI.getOperand(2).getReg(); 11131 if (RHSisZero) { 11132 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11133 .addReg(LHS1) 11134 .addImm(0) 11135 .add(predOps(ARMCC::AL)); 11136 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11137 .addReg(LHS2).addImm(0) 11138 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 11139 } else { 11140 Register RHS1 = MI.getOperand(3).getReg(); 11141 Register RHS2 = MI.getOperand(4).getReg(); 11142 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 11143 .addReg(LHS1) 11144 .addReg(RHS1) 11145 .add(predOps(ARMCC::AL)); 11146 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 11147 .addReg(LHS2).addReg(RHS2) 11148 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 11149 } 11150 11151 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 11152 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 11153 if (MI.getOperand(0).getImm() == ARMCC::NE) 11154 std::swap(destMBB, exitMBB); 11155 11156 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 11157 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 11158 if (isThumb2) 11159 BuildMI(BB, dl, TII->get(ARM::t2B)) 11160 .addMBB(exitMBB) 11161 .add(predOps(ARMCC::AL)); 11162 else 11163 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 11164 11165 MI.eraseFromParent(); // The pseudo instruction is gone now. 11166 return BB; 11167 } 11168 11169 case ARM::Int_eh_sjlj_setjmp: 11170 case ARM::Int_eh_sjlj_setjmp_nofp: 11171 case ARM::tInt_eh_sjlj_setjmp: 11172 case ARM::t2Int_eh_sjlj_setjmp: 11173 case ARM::t2Int_eh_sjlj_setjmp_nofp: 11174 return BB; 11175 11176 case ARM::Int_eh_sjlj_setup_dispatch: 11177 EmitSjLjDispatchBlock(MI, BB); 11178 return BB; 11179 11180 case ARM::ABS: 11181 case ARM::t2ABS: { 11182 // To insert an ABS instruction, we have to insert the 11183 // diamond control-flow pattern. The incoming instruction knows the 11184 // source vreg to test against 0, the destination vreg to set, 11185 // the condition code register to branch on, the 11186 // true/false values to select between, and a branch opcode to use. 11187 // It transforms 11188 // V1 = ABS V0 11189 // into 11190 // V2 = MOVS V0 11191 // BCC (branch to SinkBB if V0 >= 0) 11192 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 11193 // SinkBB: V1 = PHI(V2, V3) 11194 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11195 MachineFunction::iterator BBI = ++BB->getIterator(); 11196 MachineFunction *Fn = BB->getParent(); 11197 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 11198 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 11199 Fn->insert(BBI, RSBBB); 11200 Fn->insert(BBI, SinkBB); 11201 11202 Register ABSSrcReg = MI.getOperand(1).getReg(); 11203 Register ABSDstReg = MI.getOperand(0).getReg(); 11204 bool ABSSrcKIll = MI.getOperand(1).isKill(); 11205 bool isThumb2 = Subtarget->isThumb2(); 11206 MachineRegisterInfo &MRI = Fn->getRegInfo(); 11207 // In Thumb mode S must not be specified if source register is the SP or 11208 // PC and if destination register is the SP, so restrict register class 11209 Register NewRsbDstReg = MRI.createVirtualRegister( 11210 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 11211 11212 // Transfer the remainder of BB and its successor edges to sinkMBB. 11213 SinkBB->splice(SinkBB->begin(), BB, 11214 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11215 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 11216 11217 BB->addSuccessor(RSBBB); 11218 BB->addSuccessor(SinkBB); 11219 11220 // fall through to SinkMBB 11221 RSBBB->addSuccessor(SinkBB); 11222 11223 // insert a cmp at the end of BB 11224 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11225 .addReg(ABSSrcReg) 11226 .addImm(0) 11227 .add(predOps(ARMCC::AL)); 11228 11229 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 11230 BuildMI(BB, dl, 11231 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 11232 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 11233 11234 // insert rsbri in RSBBB 11235 // Note: BCC and rsbri will be converted into predicated rsbmi 11236 // by if-conversion pass 11237 BuildMI(*RSBBB, RSBBB->begin(), dl, 11238 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 11239 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 11240 .addImm(0) 11241 .add(predOps(ARMCC::AL)) 11242 .add(condCodeOp()); 11243 11244 // insert PHI in SinkBB, 11245 // reuse ABSDstReg to not change uses of ABS instruction 11246 BuildMI(*SinkBB, SinkBB->begin(), dl, 11247 TII->get(ARM::PHI), ABSDstReg) 11248 .addReg(NewRsbDstReg).addMBB(RSBBB) 11249 .addReg(ABSSrcReg).addMBB(BB); 11250 11251 // remove ABS instruction 11252 MI.eraseFromParent(); 11253 11254 // return last added BB 11255 return SinkBB; 11256 } 11257 case ARM::COPY_STRUCT_BYVAL_I32: 11258 ++NumLoopByVals; 11259 return EmitStructByval(MI, BB); 11260 case ARM::WIN__CHKSTK: 11261 return EmitLowered__chkstk(MI, BB); 11262 case ARM::WIN__DBZCHK: 11263 return EmitLowered__dbzchk(MI, BB); 11264 case ARM::t2DoLoopStart: 11265 // We are just here to set a register allocation hint, prefering lr for the 11266 // input register to make it more likely to be movable and removable, later 11267 // in the pipeline. 11268 Register R = MI.getOperand(1).getReg(); 11269 MachineFunction *MF = MI.getParent()->getParent(); 11270 MF->getRegInfo().setRegAllocationHint(R, ARMRI::RegLR, 0); 11271 return BB; 11272 } 11273 } 11274 11275 /// Attaches vregs to MEMCPY that it will use as scratch registers 11276 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 11277 /// instead of as a custom inserter because we need the use list from the SDNode. 11278 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 11279 MachineInstr &MI, const SDNode *Node) { 11280 bool isThumb1 = Subtarget->isThumb1Only(); 11281 11282 DebugLoc DL = MI.getDebugLoc(); 11283 MachineFunction *MF = MI.getParent()->getParent(); 11284 MachineRegisterInfo &MRI = MF->getRegInfo(); 11285 MachineInstrBuilder MIB(*MF, MI); 11286 11287 // If the new dst/src is unused mark it as dead. 11288 if (!Node->hasAnyUseOfValue(0)) { 11289 MI.getOperand(0).setIsDead(true); 11290 } 11291 if (!Node->hasAnyUseOfValue(1)) { 11292 MI.getOperand(1).setIsDead(true); 11293 } 11294 11295 // The MEMCPY both defines and kills the scratch registers. 11296 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 11297 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 11298 : &ARM::GPRRegClass); 11299 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 11300 } 11301 } 11302 11303 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11304 SDNode *Node) const { 11305 if (MI.getOpcode() == ARM::MEMCPY) { 11306 attachMEMCPYScratchRegs(Subtarget, MI, Node); 11307 return; 11308 } 11309 11310 const MCInstrDesc *MCID = &MI.getDesc(); 11311 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 11312 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 11313 // operand is still set to noreg. If needed, set the optional operand's 11314 // register to CPSR, and remove the redundant implicit def. 11315 // 11316 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 11317 11318 // Rename pseudo opcodes. 11319 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 11320 unsigned ccOutIdx; 11321 if (NewOpc) { 11322 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 11323 MCID = &TII->get(NewOpc); 11324 11325 assert(MCID->getNumOperands() == 11326 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 11327 && "converted opcode should be the same except for cc_out" 11328 " (and, on Thumb1, pred)"); 11329 11330 MI.setDesc(*MCID); 11331 11332 // Add the optional cc_out operand 11333 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 11334 11335 // On Thumb1, move all input operands to the end, then add the predicate 11336 if (Subtarget->isThumb1Only()) { 11337 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 11338 MI.addOperand(MI.getOperand(1)); 11339 MI.RemoveOperand(1); 11340 } 11341 11342 // Restore the ties 11343 for (unsigned i = MI.getNumOperands(); i--;) { 11344 const MachineOperand& op = MI.getOperand(i); 11345 if (op.isReg() && op.isUse()) { 11346 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 11347 if (DefIdx != -1) 11348 MI.tieOperands(DefIdx, i); 11349 } 11350 } 11351 11352 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 11353 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 11354 ccOutIdx = 1; 11355 } else 11356 ccOutIdx = MCID->getNumOperands() - 1; 11357 } else 11358 ccOutIdx = MCID->getNumOperands() - 1; 11359 11360 // Any ARM instruction that sets the 's' bit should specify an optional 11361 // "cc_out" operand in the last operand position. 11362 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 11363 assert(!NewOpc && "Optional cc_out operand required"); 11364 return; 11365 } 11366 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 11367 // since we already have an optional CPSR def. 11368 bool definesCPSR = false; 11369 bool deadCPSR = false; 11370 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 11371 ++i) { 11372 const MachineOperand &MO = MI.getOperand(i); 11373 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 11374 definesCPSR = true; 11375 if (MO.isDead()) 11376 deadCPSR = true; 11377 MI.RemoveOperand(i); 11378 break; 11379 } 11380 } 11381 if (!definesCPSR) { 11382 assert(!NewOpc && "Optional cc_out operand required"); 11383 return; 11384 } 11385 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 11386 if (deadCPSR) { 11387 assert(!MI.getOperand(ccOutIdx).getReg() && 11388 "expect uninitialized optional cc_out operand"); 11389 // Thumb1 instructions must have the S bit even if the CPSR is dead. 11390 if (!Subtarget->isThumb1Only()) 11391 return; 11392 } 11393 11394 // If this instruction was defined with an optional CPSR def and its dag node 11395 // had a live implicit CPSR def, then activate the optional CPSR def. 11396 MachineOperand &MO = MI.getOperand(ccOutIdx); 11397 MO.setReg(ARM::CPSR); 11398 MO.setIsDef(true); 11399 } 11400 11401 //===----------------------------------------------------------------------===// 11402 // ARM Optimization Hooks 11403 //===----------------------------------------------------------------------===// 11404 11405 // Helper function that checks if N is a null or all ones constant. 11406 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 11407 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 11408 } 11409 11410 // Return true if N is conditionally 0 or all ones. 11411 // Detects these expressions where cc is an i1 value: 11412 // 11413 // (select cc 0, y) [AllOnes=0] 11414 // (select cc y, 0) [AllOnes=0] 11415 // (zext cc) [AllOnes=0] 11416 // (sext cc) [AllOnes=0/1] 11417 // (select cc -1, y) [AllOnes=1] 11418 // (select cc y, -1) [AllOnes=1] 11419 // 11420 // Invert is set when N is the null/all ones constant when CC is false. 11421 // OtherOp is set to the alternative value of N. 11422 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 11423 SDValue &CC, bool &Invert, 11424 SDValue &OtherOp, 11425 SelectionDAG &DAG) { 11426 switch (N->getOpcode()) { 11427 default: return false; 11428 case ISD::SELECT: { 11429 CC = N->getOperand(0); 11430 SDValue N1 = N->getOperand(1); 11431 SDValue N2 = N->getOperand(2); 11432 if (isZeroOrAllOnes(N1, AllOnes)) { 11433 Invert = false; 11434 OtherOp = N2; 11435 return true; 11436 } 11437 if (isZeroOrAllOnes(N2, AllOnes)) { 11438 Invert = true; 11439 OtherOp = N1; 11440 return true; 11441 } 11442 return false; 11443 } 11444 case ISD::ZERO_EXTEND: 11445 // (zext cc) can never be the all ones value. 11446 if (AllOnes) 11447 return false; 11448 LLVM_FALLTHROUGH; 11449 case ISD::SIGN_EXTEND: { 11450 SDLoc dl(N); 11451 EVT VT = N->getValueType(0); 11452 CC = N->getOperand(0); 11453 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 11454 return false; 11455 Invert = !AllOnes; 11456 if (AllOnes) 11457 // When looking for an AllOnes constant, N is an sext, and the 'other' 11458 // value is 0. 11459 OtherOp = DAG.getConstant(0, dl, VT); 11460 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11461 // When looking for a 0 constant, N can be zext or sext. 11462 OtherOp = DAG.getConstant(1, dl, VT); 11463 else 11464 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 11465 VT); 11466 return true; 11467 } 11468 } 11469 } 11470 11471 // Combine a constant select operand into its use: 11472 // 11473 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11474 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11475 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 11476 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11477 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11478 // 11479 // The transform is rejected if the select doesn't have a constant operand that 11480 // is null, or all ones when AllOnes is set. 11481 // 11482 // Also recognize sext/zext from i1: 11483 // 11484 // (add (zext cc), x) -> (select cc (add x, 1), x) 11485 // (add (sext cc), x) -> (select cc (add x, -1), x) 11486 // 11487 // These transformations eventually create predicated instructions. 11488 // 11489 // @param N The node to transform. 11490 // @param Slct The N operand that is a select. 11491 // @param OtherOp The other N operand (x above). 11492 // @param DCI Context. 11493 // @param AllOnes Require the select constant to be all ones instead of null. 11494 // @returns The new node, or SDValue() on failure. 11495 static 11496 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 11497 TargetLowering::DAGCombinerInfo &DCI, 11498 bool AllOnes = false) { 11499 SelectionDAG &DAG = DCI.DAG; 11500 EVT VT = N->getValueType(0); 11501 SDValue NonConstantVal; 11502 SDValue CCOp; 11503 bool SwapSelectOps; 11504 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 11505 NonConstantVal, DAG)) 11506 return SDValue(); 11507 11508 // Slct is now know to be the desired identity constant when CC is true. 11509 SDValue TrueVal = OtherOp; 11510 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 11511 OtherOp, NonConstantVal); 11512 // Unless SwapSelectOps says CC should be false. 11513 if (SwapSelectOps) 11514 std::swap(TrueVal, FalseVal); 11515 11516 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 11517 CCOp, TrueVal, FalseVal); 11518 } 11519 11520 // Attempt combineSelectAndUse on each operand of a commutative operator N. 11521 static 11522 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 11523 TargetLowering::DAGCombinerInfo &DCI) { 11524 SDValue N0 = N->getOperand(0); 11525 SDValue N1 = N->getOperand(1); 11526 if (N0.getNode()->hasOneUse()) 11527 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 11528 return Result; 11529 if (N1.getNode()->hasOneUse()) 11530 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 11531 return Result; 11532 return SDValue(); 11533 } 11534 11535 static bool IsVUZPShuffleNode(SDNode *N) { 11536 // VUZP shuffle node. 11537 if (N->getOpcode() == ARMISD::VUZP) 11538 return true; 11539 11540 // "VUZP" on i32 is an alias for VTRN. 11541 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 11542 return true; 11543 11544 return false; 11545 } 11546 11547 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 11548 TargetLowering::DAGCombinerInfo &DCI, 11549 const ARMSubtarget *Subtarget) { 11550 // Look for ADD(VUZP.0, VUZP.1). 11551 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 11552 N0 == N1) 11553 return SDValue(); 11554 11555 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 11556 if (!N->getValueType(0).is64BitVector()) 11557 return SDValue(); 11558 11559 // Generate vpadd. 11560 SelectionDAG &DAG = DCI.DAG; 11561 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11562 SDLoc dl(N); 11563 SDNode *Unzip = N0.getNode(); 11564 EVT VT = N->getValueType(0); 11565 11566 SmallVector<SDValue, 8> Ops; 11567 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 11568 TLI.getPointerTy(DAG.getDataLayout()))); 11569 Ops.push_back(Unzip->getOperand(0)); 11570 Ops.push_back(Unzip->getOperand(1)); 11571 11572 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11573 } 11574 11575 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11576 TargetLowering::DAGCombinerInfo &DCI, 11577 const ARMSubtarget *Subtarget) { 11578 // Check for two extended operands. 11579 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 11580 N1.getOpcode() == ISD::SIGN_EXTEND) && 11581 !(N0.getOpcode() == ISD::ZERO_EXTEND && 11582 N1.getOpcode() == ISD::ZERO_EXTEND)) 11583 return SDValue(); 11584 11585 SDValue N00 = N0.getOperand(0); 11586 SDValue N10 = N1.getOperand(0); 11587 11588 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 11589 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 11590 N00 == N10) 11591 return SDValue(); 11592 11593 // We only recognize Q register paddl here; this can't be reached until 11594 // after type legalization. 11595 if (!N00.getValueType().is64BitVector() || 11596 !N0.getValueType().is128BitVector()) 11597 return SDValue(); 11598 11599 // Generate vpaddl. 11600 SelectionDAG &DAG = DCI.DAG; 11601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11602 SDLoc dl(N); 11603 EVT VT = N->getValueType(0); 11604 11605 SmallVector<SDValue, 8> Ops; 11606 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 11607 unsigned Opcode; 11608 if (N0.getOpcode() == ISD::SIGN_EXTEND) 11609 Opcode = Intrinsic::arm_neon_vpaddls; 11610 else 11611 Opcode = Intrinsic::arm_neon_vpaddlu; 11612 Ops.push_back(DAG.getConstant(Opcode, dl, 11613 TLI.getPointerTy(DAG.getDataLayout()))); 11614 EVT ElemTy = N00.getValueType().getVectorElementType(); 11615 unsigned NumElts = VT.getVectorNumElements(); 11616 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 11617 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 11618 N00.getOperand(0), N00.getOperand(1)); 11619 Ops.push_back(Concat); 11620 11621 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11622 } 11623 11624 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 11625 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 11626 // much easier to match. 11627 static SDValue 11628 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11629 TargetLowering::DAGCombinerInfo &DCI, 11630 const ARMSubtarget *Subtarget) { 11631 // Only perform optimization if after legalize, and if NEON is available. We 11632 // also expected both operands to be BUILD_VECTORs. 11633 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 11634 || N0.getOpcode() != ISD::BUILD_VECTOR 11635 || N1.getOpcode() != ISD::BUILD_VECTOR) 11636 return SDValue(); 11637 11638 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 11639 EVT VT = N->getValueType(0); 11640 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 11641 return SDValue(); 11642 11643 // Check that the vector operands are of the right form. 11644 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 11645 // operands, where N is the size of the formed vector. 11646 // Each EXTRACT_VECTOR should have the same input vector and odd or even 11647 // index such that we have a pair wise add pattern. 11648 11649 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 11650 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11651 return SDValue(); 11652 SDValue Vec = N0->getOperand(0)->getOperand(0); 11653 SDNode *V = Vec.getNode(); 11654 unsigned nextIndex = 0; 11655 11656 // For each operands to the ADD which are BUILD_VECTORs, 11657 // check to see if each of their operands are an EXTRACT_VECTOR with 11658 // the same vector and appropriate index. 11659 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 11660 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 11661 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11662 11663 SDValue ExtVec0 = N0->getOperand(i); 11664 SDValue ExtVec1 = N1->getOperand(i); 11665 11666 // First operand is the vector, verify its the same. 11667 if (V != ExtVec0->getOperand(0).getNode() || 11668 V != ExtVec1->getOperand(0).getNode()) 11669 return SDValue(); 11670 11671 // Second is the constant, verify its correct. 11672 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 11673 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 11674 11675 // For the constant, we want to see all the even or all the odd. 11676 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 11677 || C1->getZExtValue() != nextIndex+1) 11678 return SDValue(); 11679 11680 // Increment index. 11681 nextIndex+=2; 11682 } else 11683 return SDValue(); 11684 } 11685 11686 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 11687 // we're using the entire input vector, otherwise there's a size/legality 11688 // mismatch somewhere. 11689 if (nextIndex != Vec.getValueType().getVectorNumElements() || 11690 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 11691 return SDValue(); 11692 11693 // Create VPADDL node. 11694 SelectionDAG &DAG = DCI.DAG; 11695 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11696 11697 SDLoc dl(N); 11698 11699 // Build operand list. 11700 SmallVector<SDValue, 8> Ops; 11701 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 11702 TLI.getPointerTy(DAG.getDataLayout()))); 11703 11704 // Input is the vector. 11705 Ops.push_back(Vec); 11706 11707 // Get widened type and narrowed type. 11708 MVT widenType; 11709 unsigned numElem = VT.getVectorNumElements(); 11710 11711 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 11712 switch (inputLaneType.getSimpleVT().SimpleTy) { 11713 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 11714 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 11715 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 11716 default: 11717 llvm_unreachable("Invalid vector element type for padd optimization."); 11718 } 11719 11720 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 11721 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 11722 return DAG.getNode(ExtOp, dl, VT, tmp); 11723 } 11724 11725 static SDValue findMUL_LOHI(SDValue V) { 11726 if (V->getOpcode() == ISD::UMUL_LOHI || 11727 V->getOpcode() == ISD::SMUL_LOHI) 11728 return V; 11729 return SDValue(); 11730 } 11731 11732 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 11733 TargetLowering::DAGCombinerInfo &DCI, 11734 const ARMSubtarget *Subtarget) { 11735 if (!Subtarget->hasBaseDSP()) 11736 return SDValue(); 11737 11738 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 11739 // accumulates the product into a 64-bit value. The 16-bit values will 11740 // be sign extended somehow or SRA'd into 32-bit values 11741 // (addc (adde (mul 16bit, 16bit), lo), hi) 11742 SDValue Mul = AddcNode->getOperand(0); 11743 SDValue Lo = AddcNode->getOperand(1); 11744 if (Mul.getOpcode() != ISD::MUL) { 11745 Lo = AddcNode->getOperand(0); 11746 Mul = AddcNode->getOperand(1); 11747 if (Mul.getOpcode() != ISD::MUL) 11748 return SDValue(); 11749 } 11750 11751 SDValue SRA = AddeNode->getOperand(0); 11752 SDValue Hi = AddeNode->getOperand(1); 11753 if (SRA.getOpcode() != ISD::SRA) { 11754 SRA = AddeNode->getOperand(1); 11755 Hi = AddeNode->getOperand(0); 11756 if (SRA.getOpcode() != ISD::SRA) 11757 return SDValue(); 11758 } 11759 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 11760 if (Const->getZExtValue() != 31) 11761 return SDValue(); 11762 } else 11763 return SDValue(); 11764 11765 if (SRA.getOperand(0) != Mul) 11766 return SDValue(); 11767 11768 SelectionDAG &DAG = DCI.DAG; 11769 SDLoc dl(AddcNode); 11770 unsigned Opcode = 0; 11771 SDValue Op0; 11772 SDValue Op1; 11773 11774 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 11775 Opcode = ARMISD::SMLALBB; 11776 Op0 = Mul.getOperand(0); 11777 Op1 = Mul.getOperand(1); 11778 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 11779 Opcode = ARMISD::SMLALBT; 11780 Op0 = Mul.getOperand(0); 11781 Op1 = Mul.getOperand(1).getOperand(0); 11782 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 11783 Opcode = ARMISD::SMLALTB; 11784 Op0 = Mul.getOperand(0).getOperand(0); 11785 Op1 = Mul.getOperand(1); 11786 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 11787 Opcode = ARMISD::SMLALTT; 11788 Op0 = Mul->getOperand(0).getOperand(0); 11789 Op1 = Mul->getOperand(1).getOperand(0); 11790 } 11791 11792 if (!Op0 || !Op1) 11793 return SDValue(); 11794 11795 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 11796 Op0, Op1, Lo, Hi); 11797 // Replace the ADDs' nodes uses by the MLA node's values. 11798 SDValue HiMLALResult(SMLAL.getNode(), 1); 11799 SDValue LoMLALResult(SMLAL.getNode(), 0); 11800 11801 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 11802 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 11803 11804 // Return original node to notify the driver to stop replacing. 11805 SDValue resNode(AddcNode, 0); 11806 return resNode; 11807 } 11808 11809 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 11810 TargetLowering::DAGCombinerInfo &DCI, 11811 const ARMSubtarget *Subtarget) { 11812 // Look for multiply add opportunities. 11813 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 11814 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 11815 // a glue link from the first add to the second add. 11816 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 11817 // a S/UMLAL instruction. 11818 // UMUL_LOHI 11819 // / :lo \ :hi 11820 // V \ [no multiline comment] 11821 // loAdd -> ADDC | 11822 // \ :carry / 11823 // V V 11824 // ADDE <- hiAdd 11825 // 11826 // In the special case where only the higher part of a signed result is used 11827 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 11828 // a constant with the exact value of 0x80000000, we recognize we are dealing 11829 // with a "rounded multiply and add" (or subtract) and transform it into 11830 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 11831 11832 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 11833 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 11834 "Expect an ADDE or SUBE"); 11835 11836 assert(AddeSubeNode->getNumOperands() == 3 && 11837 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 11838 "ADDE node has the wrong inputs"); 11839 11840 // Check that we are chained to the right ADDC or SUBC node. 11841 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 11842 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 11843 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 11844 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 11845 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 11846 return SDValue(); 11847 11848 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 11849 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 11850 11851 // Check if the two operands are from the same mul_lohi node. 11852 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 11853 return SDValue(); 11854 11855 assert(AddcSubcNode->getNumValues() == 2 && 11856 AddcSubcNode->getValueType(0) == MVT::i32 && 11857 "Expect ADDC with two result values. First: i32"); 11858 11859 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 11860 // maybe a SMLAL which multiplies two 16-bit values. 11861 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 11862 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 11863 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 11864 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 11865 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 11866 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 11867 11868 // Check for the triangle shape. 11869 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 11870 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 11871 11872 // Make sure that the ADDE/SUBE operands are not coming from the same node. 11873 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 11874 return SDValue(); 11875 11876 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 11877 bool IsLeftOperandMUL = false; 11878 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 11879 if (MULOp == SDValue()) 11880 MULOp = findMUL_LOHI(AddeSubeOp1); 11881 else 11882 IsLeftOperandMUL = true; 11883 if (MULOp == SDValue()) 11884 return SDValue(); 11885 11886 // Figure out the right opcode. 11887 unsigned Opc = MULOp->getOpcode(); 11888 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 11889 11890 // Figure out the high and low input values to the MLAL node. 11891 SDValue *HiAddSub = nullptr; 11892 SDValue *LoMul = nullptr; 11893 SDValue *LowAddSub = nullptr; 11894 11895 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 11896 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 11897 return SDValue(); 11898 11899 if (IsLeftOperandMUL) 11900 HiAddSub = &AddeSubeOp1; 11901 else 11902 HiAddSub = &AddeSubeOp0; 11903 11904 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 11905 // whose low result is fed to the ADDC/SUBC we are checking. 11906 11907 if (AddcSubcOp0 == MULOp.getValue(0)) { 11908 LoMul = &AddcSubcOp0; 11909 LowAddSub = &AddcSubcOp1; 11910 } 11911 if (AddcSubcOp1 == MULOp.getValue(0)) { 11912 LoMul = &AddcSubcOp1; 11913 LowAddSub = &AddcSubcOp0; 11914 } 11915 11916 if (!LoMul) 11917 return SDValue(); 11918 11919 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 11920 // the replacement below will create a cycle. 11921 if (AddcSubcNode == HiAddSub->getNode() || 11922 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 11923 return SDValue(); 11924 11925 // Create the merged node. 11926 SelectionDAG &DAG = DCI.DAG; 11927 11928 // Start building operand list. 11929 SmallVector<SDValue, 8> Ops; 11930 Ops.push_back(LoMul->getOperand(0)); 11931 Ops.push_back(LoMul->getOperand(1)); 11932 11933 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 11934 // the case, we must be doing signed multiplication and only use the higher 11935 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 11936 // addition or subtraction with the value of 0x800000. 11937 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 11938 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 11939 LowAddSub->getNode()->getOpcode() == ISD::Constant && 11940 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 11941 0x80000000) { 11942 Ops.push_back(*HiAddSub); 11943 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 11944 FinalOpc = ARMISD::SMMLSR; 11945 } else { 11946 FinalOpc = ARMISD::SMMLAR; 11947 } 11948 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 11949 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 11950 11951 return SDValue(AddeSubeNode, 0); 11952 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 11953 // SMMLS is generated during instruction selection and the rest of this 11954 // function can not handle the case where AddcSubcNode is a SUBC. 11955 return SDValue(); 11956 11957 // Finish building the operand list for {U/S}MLAL 11958 Ops.push_back(*LowAddSub); 11959 Ops.push_back(*HiAddSub); 11960 11961 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 11962 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11963 11964 // Replace the ADDs' nodes uses by the MLA node's values. 11965 SDValue HiMLALResult(MLALNode.getNode(), 1); 11966 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 11967 11968 SDValue LoMLALResult(MLALNode.getNode(), 0); 11969 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 11970 11971 // Return original node to notify the driver to stop replacing. 11972 return SDValue(AddeSubeNode, 0); 11973 } 11974 11975 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 11976 TargetLowering::DAGCombinerInfo &DCI, 11977 const ARMSubtarget *Subtarget) { 11978 // UMAAL is similar to UMLAL except that it adds two unsigned values. 11979 // While trying to combine for the other MLAL nodes, first search for the 11980 // chance to use UMAAL. Check if Addc uses a node which has already 11981 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 11982 // as the addend, and it's handled in PerformUMLALCombine. 11983 11984 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11985 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11986 11987 // Check that we have a glued ADDC node. 11988 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 11989 if (AddcNode->getOpcode() != ARMISD::ADDC) 11990 return SDValue(); 11991 11992 // Find the converted UMAAL or quit if it doesn't exist. 11993 SDNode *UmlalNode = nullptr; 11994 SDValue AddHi; 11995 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 11996 UmlalNode = AddcNode->getOperand(0).getNode(); 11997 AddHi = AddcNode->getOperand(1); 11998 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 11999 UmlalNode = AddcNode->getOperand(1).getNode(); 12000 AddHi = AddcNode->getOperand(0); 12001 } else { 12002 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 12003 } 12004 12005 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 12006 // the ADDC as well as Zero. 12007 if (!isNullConstant(UmlalNode->getOperand(3))) 12008 return SDValue(); 12009 12010 if ((isNullConstant(AddeNode->getOperand(0)) && 12011 AddeNode->getOperand(1).getNode() == UmlalNode) || 12012 (AddeNode->getOperand(0).getNode() == UmlalNode && 12013 isNullConstant(AddeNode->getOperand(1)))) { 12014 SelectionDAG &DAG = DCI.DAG; 12015 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 12016 UmlalNode->getOperand(2), AddHi }; 12017 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 12018 DAG.getVTList(MVT::i32, MVT::i32), Ops); 12019 12020 // Replace the ADDs' nodes uses by the UMAAL node's values. 12021 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 12022 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 12023 12024 // Return original node to notify the driver to stop replacing. 12025 return SDValue(AddeNode, 0); 12026 } 12027 return SDValue(); 12028 } 12029 12030 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 12031 const ARMSubtarget *Subtarget) { 12032 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 12033 return SDValue(); 12034 12035 // Check that we have a pair of ADDC and ADDE as operands. 12036 // Both addends of the ADDE must be zero. 12037 SDNode* AddcNode = N->getOperand(2).getNode(); 12038 SDNode* AddeNode = N->getOperand(3).getNode(); 12039 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 12040 (AddeNode->getOpcode() == ARMISD::ADDE) && 12041 isNullConstant(AddeNode->getOperand(0)) && 12042 isNullConstant(AddeNode->getOperand(1)) && 12043 (AddeNode->getOperand(2).getNode() == AddcNode)) 12044 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 12045 DAG.getVTList(MVT::i32, MVT::i32), 12046 {N->getOperand(0), N->getOperand(1), 12047 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 12048 else 12049 return SDValue(); 12050 } 12051 12052 static SDValue PerformAddcSubcCombine(SDNode *N, 12053 TargetLowering::DAGCombinerInfo &DCI, 12054 const ARMSubtarget *Subtarget) { 12055 SelectionDAG &DAG(DCI.DAG); 12056 12057 if (N->getOpcode() == ARMISD::SUBC) { 12058 // (SUBC (ADDE 0, 0, C), 1) -> C 12059 SDValue LHS = N->getOperand(0); 12060 SDValue RHS = N->getOperand(1); 12061 if (LHS->getOpcode() == ARMISD::ADDE && 12062 isNullConstant(LHS->getOperand(0)) && 12063 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 12064 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 12065 } 12066 } 12067 12068 if (Subtarget->isThumb1Only()) { 12069 SDValue RHS = N->getOperand(1); 12070 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 12071 int32_t imm = C->getSExtValue(); 12072 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 12073 SDLoc DL(N); 12074 RHS = DAG.getConstant(-imm, DL, MVT::i32); 12075 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 12076 : ARMISD::ADDC; 12077 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 12078 } 12079 } 12080 } 12081 12082 return SDValue(); 12083 } 12084 12085 static SDValue PerformAddeSubeCombine(SDNode *N, 12086 TargetLowering::DAGCombinerInfo &DCI, 12087 const ARMSubtarget *Subtarget) { 12088 if (Subtarget->isThumb1Only()) { 12089 SelectionDAG &DAG = DCI.DAG; 12090 SDValue RHS = N->getOperand(1); 12091 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 12092 int64_t imm = C->getSExtValue(); 12093 if (imm < 0) { 12094 SDLoc DL(N); 12095 12096 // The with-carry-in form matches bitwise not instead of the negation. 12097 // Effectively, the inverse interpretation of the carry flag already 12098 // accounts for part of the negation. 12099 RHS = DAG.getConstant(~imm, DL, MVT::i32); 12100 12101 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 12102 : ARMISD::ADDE; 12103 return DAG.getNode(Opcode, DL, N->getVTList(), 12104 N->getOperand(0), RHS, N->getOperand(2)); 12105 } 12106 } 12107 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 12108 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 12109 } 12110 return SDValue(); 12111 } 12112 12113 static SDValue PerformSELECTCombine(SDNode *N, 12114 TargetLowering::DAGCombinerInfo &DCI, 12115 const ARMSubtarget *Subtarget) { 12116 if (!Subtarget->hasMVEIntegerOps()) 12117 return SDValue(); 12118 12119 SDLoc dl(N); 12120 SDValue SetCC; 12121 SDValue LHS; 12122 SDValue RHS; 12123 ISD::CondCode CC; 12124 SDValue TrueVal; 12125 SDValue FalseVal; 12126 12127 if (N->getOpcode() == ISD::SELECT && 12128 N->getOperand(0)->getOpcode() == ISD::SETCC) { 12129 SetCC = N->getOperand(0); 12130 LHS = SetCC->getOperand(0); 12131 RHS = SetCC->getOperand(1); 12132 CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 12133 TrueVal = N->getOperand(1); 12134 FalseVal = N->getOperand(2); 12135 } else if (N->getOpcode() == ISD::SELECT_CC) { 12136 LHS = N->getOperand(0); 12137 RHS = N->getOperand(1); 12138 CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 12139 TrueVal = N->getOperand(2); 12140 FalseVal = N->getOperand(3); 12141 } else { 12142 return SDValue(); 12143 } 12144 12145 unsigned int Opcode = 0; 12146 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN || 12147 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) && 12148 (CC == ISD::SETULT || CC == ISD::SETUGT)) { 12149 Opcode = ARMISD::VMINVu; 12150 if (CC == ISD::SETUGT) 12151 std::swap(TrueVal, FalseVal); 12152 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN || 12153 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) && 12154 (CC == ISD::SETLT || CC == ISD::SETGT)) { 12155 Opcode = ARMISD::VMINVs; 12156 if (CC == ISD::SETGT) 12157 std::swap(TrueVal, FalseVal); 12158 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX || 12159 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) && 12160 (CC == ISD::SETUGT || CC == ISD::SETULT)) { 12161 Opcode = ARMISD::VMAXVu; 12162 if (CC == ISD::SETULT) 12163 std::swap(TrueVal, FalseVal); 12164 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX || 12165 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) && 12166 (CC == ISD::SETGT || CC == ISD::SETLT)) { 12167 Opcode = ARMISD::VMAXVs; 12168 if (CC == ISD::SETLT) 12169 std::swap(TrueVal, FalseVal); 12170 } else 12171 return SDValue(); 12172 12173 // Normalise to the right hand side being the vector reduction 12174 switch (TrueVal->getOpcode()) { 12175 case ISD::VECREDUCE_UMIN: 12176 case ISD::VECREDUCE_SMIN: 12177 case ISD::VECREDUCE_UMAX: 12178 case ISD::VECREDUCE_SMAX: 12179 std::swap(LHS, RHS); 12180 std::swap(TrueVal, FalseVal); 12181 break; 12182 } 12183 12184 EVT VectorType = FalseVal->getOperand(0).getValueType(); 12185 12186 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 && 12187 VectorType != MVT::v4i32) 12188 return SDValue(); 12189 12190 EVT VectorScalarType = VectorType.getVectorElementType(); 12191 12192 // The values being selected must also be the ones being compared 12193 if (TrueVal != LHS || FalseVal != RHS) 12194 return SDValue(); 12195 12196 EVT LeftType = LHS->getValueType(0); 12197 EVT RightType = RHS->getValueType(0); 12198 12199 // The types must match the reduced type too 12200 if (LeftType != VectorScalarType || RightType != VectorScalarType) 12201 return SDValue(); 12202 12203 // Legalise the scalar to an i32 12204 if (VectorScalarType != MVT::i32) 12205 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 12206 12207 // Generate the reduction as an i32 for legalisation purposes 12208 auto Reduction = 12209 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0)); 12210 12211 // The result isn't actually an i32 so truncate it back to its original type 12212 if (VectorScalarType != MVT::i32) 12213 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction); 12214 12215 return Reduction; 12216 } 12217 12218 // A special combine for the vqdmulh family of instructions. This is one of the 12219 // potential set of patterns that could patch this instruction. The base pattern 12220 // you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))). 12221 // This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))), 12222 // which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as 12223 // the max is unnecessary. 12224 static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) { 12225 EVT VT = N->getValueType(0); 12226 SDValue Shft; 12227 ConstantSDNode *Clamp; 12228 12229 if (N->getOpcode() == ISD::SMIN) { 12230 Shft = N->getOperand(0); 12231 Clamp = isConstOrConstSplat(N->getOperand(1)); 12232 } else if (N->getOpcode() == ISD::VSELECT) { 12233 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin. 12234 SDValue Cmp = N->getOperand(0); 12235 if (Cmp.getOpcode() != ISD::SETCC || 12236 cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT || 12237 Cmp.getOperand(0) != N->getOperand(1) || 12238 Cmp.getOperand(1) != N->getOperand(2)) 12239 return SDValue(); 12240 Shft = N->getOperand(1); 12241 Clamp = isConstOrConstSplat(N->getOperand(2)); 12242 } else 12243 return SDValue(); 12244 12245 if (!Clamp) 12246 return SDValue(); 12247 12248 MVT ScalarType; 12249 int ShftAmt = 0; 12250 switch (Clamp->getSExtValue()) { 12251 case (1 << 7) - 1: 12252 ScalarType = MVT::i8; 12253 ShftAmt = 7; 12254 break; 12255 case (1 << 15) - 1: 12256 ScalarType = MVT::i16; 12257 ShftAmt = 15; 12258 break; 12259 case (1ULL << 31) - 1: 12260 ScalarType = MVT::i32; 12261 ShftAmt = 31; 12262 break; 12263 default: 12264 return SDValue(); 12265 } 12266 12267 if (Shft.getOpcode() != ISD::SRA) 12268 return SDValue(); 12269 ConstantSDNode *N1 = isConstOrConstSplat(Shft.getOperand(1)); 12270 if (!N1 || N1->getSExtValue() != ShftAmt) 12271 return SDValue(); 12272 12273 SDValue Mul = Shft.getOperand(0); 12274 if (Mul.getOpcode() != ISD::MUL) 12275 return SDValue(); 12276 12277 SDValue Ext0 = Mul.getOperand(0); 12278 SDValue Ext1 = Mul.getOperand(1); 12279 if (Ext0.getOpcode() != ISD::SIGN_EXTEND || 12280 Ext1.getOpcode() != ISD::SIGN_EXTEND) 12281 return SDValue(); 12282 EVT VecVT = Ext0.getOperand(0).getValueType(); 12283 if (VecVT != MVT::v4i32 && VecVT != MVT::v8i16 && VecVT != MVT::v16i8) 12284 return SDValue(); 12285 if (Ext1.getOperand(0).getValueType() != VecVT || 12286 VecVT.getScalarType() != ScalarType || 12287 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2) 12288 return SDValue(); 12289 12290 SDLoc DL(Mul); 12291 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, VecVT, Ext0.getOperand(0), 12292 Ext1.getOperand(0)); 12293 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, VQDMULH); 12294 } 12295 12296 static SDValue PerformVSELECTCombine(SDNode *N, 12297 TargetLowering::DAGCombinerInfo &DCI, 12298 const ARMSubtarget *Subtarget) { 12299 if (!Subtarget->hasMVEIntegerOps()) 12300 return SDValue(); 12301 12302 if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG)) 12303 return V; 12304 12305 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs). 12306 // 12307 // We need to re-implement this optimization here as the implementation in the 12308 // Target-Independent DAGCombiner does not handle the kind of constant we make 12309 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for 12310 // good reason, allowing truncation there would break other targets). 12311 // 12312 // Currently, this is only done for MVE, as it's the only target that benefits 12313 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL). 12314 if (N->getOperand(0).getOpcode() != ISD::XOR) 12315 return SDValue(); 12316 SDValue XOR = N->getOperand(0); 12317 12318 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s. 12319 // It is important to check with truncation allowed as the BUILD_VECTORs we 12320 // generate in those situations will truncate their operands. 12321 ConstantSDNode *Const = 12322 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false, 12323 /*AllowTruncation*/ true); 12324 if (!Const || !Const->isOne()) 12325 return SDValue(); 12326 12327 // Rewrite into vselect(cond, rhs, lhs). 12328 SDValue Cond = XOR->getOperand(0); 12329 SDValue LHS = N->getOperand(1); 12330 SDValue RHS = N->getOperand(2); 12331 EVT Type = N->getValueType(0); 12332 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS); 12333 } 12334 12335 static SDValue PerformABSCombine(SDNode *N, 12336 TargetLowering::DAGCombinerInfo &DCI, 12337 const ARMSubtarget *Subtarget) { 12338 SDValue res; 12339 SelectionDAG &DAG = DCI.DAG; 12340 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12341 12342 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 12343 return SDValue(); 12344 12345 if (!TLI.expandABS(N, res, DAG)) 12346 return SDValue(); 12347 12348 return res; 12349 } 12350 12351 /// PerformADDECombine - Target-specific dag combine transform from 12352 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 12353 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 12354 static SDValue PerformADDECombine(SDNode *N, 12355 TargetLowering::DAGCombinerInfo &DCI, 12356 const ARMSubtarget *Subtarget) { 12357 // Only ARM and Thumb2 support UMLAL/SMLAL. 12358 if (Subtarget->isThumb1Only()) 12359 return PerformAddeSubeCombine(N, DCI, Subtarget); 12360 12361 // Only perform the checks after legalize when the pattern is available. 12362 if (DCI.isBeforeLegalize()) return SDValue(); 12363 12364 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 12365 } 12366 12367 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 12368 /// operands N0 and N1. This is a helper for PerformADDCombine that is 12369 /// called with the default operands, and if that fails, with commuted 12370 /// operands. 12371 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 12372 TargetLowering::DAGCombinerInfo &DCI, 12373 const ARMSubtarget *Subtarget){ 12374 // Attempt to create vpadd for this add. 12375 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 12376 return Result; 12377 12378 // Attempt to create vpaddl for this add. 12379 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 12380 return Result; 12381 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 12382 Subtarget)) 12383 return Result; 12384 12385 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 12386 if (N0.getNode()->hasOneUse()) 12387 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 12388 return Result; 12389 return SDValue(); 12390 } 12391 12392 static SDValue PerformADDVecReduce(SDNode *N, 12393 TargetLowering::DAGCombinerInfo &DCI, 12394 const ARMSubtarget *Subtarget) { 12395 if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64) 12396 return SDValue(); 12397 12398 SDValue N0 = N->getOperand(0); 12399 SDValue N1 = N->getOperand(1); 12400 12401 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this 12402 // will look like: 12403 // t1: i32,i32 = ARMISD::VADDLVs x 12404 // t2: i64 = build_pair t1, t1:1 12405 // t3: i64 = add t2, y 12406 // We also need to check for sext / zext and commutitive adds. 12407 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA, 12408 SDValue NB) { 12409 if (NB->getOpcode() != ISD::BUILD_PAIR) 12410 return SDValue(); 12411 SDValue VecRed = NB->getOperand(0); 12412 if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 || 12413 NB->getOperand(1) != SDValue(VecRed.getNode(), 1)) 12414 return SDValue(); 12415 12416 SDLoc dl(N); 12417 SmallVector<SDValue, 4> Ops; 12418 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 12419 DCI.DAG.getConstant(0, dl, MVT::i32))); 12420 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 12421 DCI.DAG.getConstant(1, dl, MVT::i32))); 12422 for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++) 12423 Ops.push_back(VecRed->getOperand(i)); 12424 SDValue Red = DCI.DAG.getNode(OpcodeA, dl, 12425 DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops); 12426 return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red, 12427 SDValue(Red.getNode(), 1)); 12428 }; 12429 12430 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1)) 12431 return M; 12432 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1)) 12433 return M; 12434 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0)) 12435 return M; 12436 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0)) 12437 return M; 12438 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1)) 12439 return M; 12440 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1)) 12441 return M; 12442 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0)) 12443 return M; 12444 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0)) 12445 return M; 12446 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1)) 12447 return M; 12448 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1)) 12449 return M; 12450 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0)) 12451 return M; 12452 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0)) 12453 return M; 12454 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1)) 12455 return M; 12456 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1)) 12457 return M; 12458 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0)) 12459 return M; 12460 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0)) 12461 return M; 12462 return SDValue(); 12463 } 12464 12465 bool 12466 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 12467 CombineLevel Level) const { 12468 if (Level == BeforeLegalizeTypes) 12469 return true; 12470 12471 if (N->getOpcode() != ISD::SHL) 12472 return true; 12473 12474 if (Subtarget->isThumb1Only()) { 12475 // Avoid making expensive immediates by commuting shifts. (This logic 12476 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 12477 // for free.) 12478 if (N->getOpcode() != ISD::SHL) 12479 return true; 12480 SDValue N1 = N->getOperand(0); 12481 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 12482 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 12483 return true; 12484 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 12485 if (Const->getAPIntValue().ult(256)) 12486 return false; 12487 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 12488 Const->getAPIntValue().sgt(-256)) 12489 return false; 12490 } 12491 return true; 12492 } 12493 12494 // Turn off commute-with-shift transform after legalization, so it doesn't 12495 // conflict with PerformSHLSimplify. (We could try to detect when 12496 // PerformSHLSimplify would trigger more precisely, but it isn't 12497 // really necessary.) 12498 return false; 12499 } 12500 12501 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 12502 const SDNode *N, CombineLevel Level) const { 12503 if (!Subtarget->isThumb1Only()) 12504 return true; 12505 12506 if (Level == BeforeLegalizeTypes) 12507 return true; 12508 12509 return false; 12510 } 12511 12512 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 12513 if (!Subtarget->hasNEON()) { 12514 if (Subtarget->isThumb1Only()) 12515 return VT.getScalarSizeInBits() <= 32; 12516 return true; 12517 } 12518 return VT.isScalarInteger(); 12519 } 12520 12521 static SDValue PerformSHLSimplify(SDNode *N, 12522 TargetLowering::DAGCombinerInfo &DCI, 12523 const ARMSubtarget *ST) { 12524 // Allow the generic combiner to identify potential bswaps. 12525 if (DCI.isBeforeLegalize()) 12526 return SDValue(); 12527 12528 // DAG combiner will fold: 12529 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 12530 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 12531 // Other code patterns that can be also be modified have the following form: 12532 // b + ((a << 1) | 510) 12533 // b + ((a << 1) & 510) 12534 // b + ((a << 1) ^ 510) 12535 // b + ((a << 1) + 510) 12536 12537 // Many instructions can perform the shift for free, but it requires both 12538 // the operands to be registers. If c1 << c2 is too large, a mov immediate 12539 // instruction will needed. So, unfold back to the original pattern if: 12540 // - if c1 and c2 are small enough that they don't require mov imms. 12541 // - the user(s) of the node can perform an shl 12542 12543 // No shifted operands for 16-bit instructions. 12544 if (ST->isThumb() && ST->isThumb1Only()) 12545 return SDValue(); 12546 12547 // Check that all the users could perform the shl themselves. 12548 for (auto U : N->uses()) { 12549 switch(U->getOpcode()) { 12550 default: 12551 return SDValue(); 12552 case ISD::SUB: 12553 case ISD::ADD: 12554 case ISD::AND: 12555 case ISD::OR: 12556 case ISD::XOR: 12557 case ISD::SETCC: 12558 case ARMISD::CMP: 12559 // Check that the user isn't already using a constant because there 12560 // aren't any instructions that support an immediate operand and a 12561 // shifted operand. 12562 if (isa<ConstantSDNode>(U->getOperand(0)) || 12563 isa<ConstantSDNode>(U->getOperand(1))) 12564 return SDValue(); 12565 12566 // Check that it's not already using a shift. 12567 if (U->getOperand(0).getOpcode() == ISD::SHL || 12568 U->getOperand(1).getOpcode() == ISD::SHL) 12569 return SDValue(); 12570 break; 12571 } 12572 } 12573 12574 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 12575 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 12576 return SDValue(); 12577 12578 if (N->getOperand(0).getOpcode() != ISD::SHL) 12579 return SDValue(); 12580 12581 SDValue SHL = N->getOperand(0); 12582 12583 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12584 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 12585 if (!C1ShlC2 || !C2) 12586 return SDValue(); 12587 12588 APInt C2Int = C2->getAPIntValue(); 12589 APInt C1Int = C1ShlC2->getAPIntValue(); 12590 12591 // Check that performing a lshr will not lose any information. 12592 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 12593 C2Int.getBitWidth() - C2->getZExtValue()); 12594 if ((C1Int & Mask) != C1Int) 12595 return SDValue(); 12596 12597 // Shift the first constant. 12598 C1Int.lshrInPlace(C2Int); 12599 12600 // The immediates are encoded as an 8-bit value that can be rotated. 12601 auto LargeImm = [](const APInt &Imm) { 12602 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 12603 return Imm.getBitWidth() - Zeros > 8; 12604 }; 12605 12606 if (LargeImm(C1Int) || LargeImm(C2Int)) 12607 return SDValue(); 12608 12609 SelectionDAG &DAG = DCI.DAG; 12610 SDLoc dl(N); 12611 SDValue X = SHL.getOperand(0); 12612 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 12613 DAG.getConstant(C1Int, dl, MVT::i32)); 12614 // Shift left to compensate for the lshr of C1Int. 12615 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 12616 12617 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 12618 SHL.dump(); N->dump()); 12619 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 12620 return Res; 12621 } 12622 12623 12624 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 12625 /// 12626 static SDValue PerformADDCombine(SDNode *N, 12627 TargetLowering::DAGCombinerInfo &DCI, 12628 const ARMSubtarget *Subtarget) { 12629 SDValue N0 = N->getOperand(0); 12630 SDValue N1 = N->getOperand(1); 12631 12632 // Only works one way, because it needs an immediate operand. 12633 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12634 return Result; 12635 12636 if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget)) 12637 return Result; 12638 12639 // First try with the default operand order. 12640 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 12641 return Result; 12642 12643 // If that didn't work, try again with the operands commuted. 12644 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 12645 } 12646 12647 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 12648 /// 12649 static SDValue PerformSUBCombine(SDNode *N, 12650 TargetLowering::DAGCombinerInfo &DCI, 12651 const ARMSubtarget *Subtarget) { 12652 SDValue N0 = N->getOperand(0); 12653 SDValue N1 = N->getOperand(1); 12654 12655 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 12656 if (N1.getNode()->hasOneUse()) 12657 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 12658 return Result; 12659 12660 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector()) 12661 return SDValue(); 12662 12663 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x)) 12664 // so that we can readily pattern match more mve instructions which can use 12665 // a scalar operand. 12666 SDValue VDup = N->getOperand(1); 12667 if (VDup->getOpcode() != ARMISD::VDUP) 12668 return SDValue(); 12669 12670 SDValue VMov = N->getOperand(0); 12671 if (VMov->getOpcode() == ISD::BITCAST) 12672 VMov = VMov->getOperand(0); 12673 12674 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov)) 12675 return SDValue(); 12676 12677 SDLoc dl(N); 12678 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32, 12679 DCI.DAG.getConstant(0, dl, MVT::i32), 12680 VDup->getOperand(0)); 12681 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate); 12682 } 12683 12684 /// PerformVMULCombine 12685 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 12686 /// special multiplier accumulator forwarding. 12687 /// vmul d3, d0, d2 12688 /// vmla d3, d1, d2 12689 /// is faster than 12690 /// vadd d3, d0, d1 12691 /// vmul d3, d3, d2 12692 // However, for (A + B) * (A + B), 12693 // vadd d2, d0, d1 12694 // vmul d3, d0, d2 12695 // vmla d3, d1, d2 12696 // is slower than 12697 // vadd d2, d0, d1 12698 // vmul d3, d2, d2 12699 static SDValue PerformVMULCombine(SDNode *N, 12700 TargetLowering::DAGCombinerInfo &DCI, 12701 const ARMSubtarget *Subtarget) { 12702 if (!Subtarget->hasVMLxForwarding()) 12703 return SDValue(); 12704 12705 SelectionDAG &DAG = DCI.DAG; 12706 SDValue N0 = N->getOperand(0); 12707 SDValue N1 = N->getOperand(1); 12708 unsigned Opcode = N0.getOpcode(); 12709 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12710 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 12711 Opcode = N1.getOpcode(); 12712 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12713 Opcode != ISD::FADD && Opcode != ISD::FSUB) 12714 return SDValue(); 12715 std::swap(N0, N1); 12716 } 12717 12718 if (N0 == N1) 12719 return SDValue(); 12720 12721 EVT VT = N->getValueType(0); 12722 SDLoc DL(N); 12723 SDValue N00 = N0->getOperand(0); 12724 SDValue N01 = N0->getOperand(1); 12725 return DAG.getNode(Opcode, DL, VT, 12726 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 12727 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 12728 } 12729 12730 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG, 12731 const ARMSubtarget *Subtarget) { 12732 EVT VT = N->getValueType(0); 12733 if (VT != MVT::v2i64) 12734 return SDValue(); 12735 12736 SDValue N0 = N->getOperand(0); 12737 SDValue N1 = N->getOperand(1); 12738 12739 auto IsSignExt = [&](SDValue Op) { 12740 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG) 12741 return SDValue(); 12742 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT(); 12743 if (VT.getScalarSizeInBits() == 32) 12744 return Op->getOperand(0); 12745 return SDValue(); 12746 }; 12747 auto IsZeroExt = [&](SDValue Op) { 12748 // Zero extends are a little more awkward. At the point we are matching 12749 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask. 12750 // That might be before of after a bitcast depending on how the and is 12751 // placed. Because this has to look through bitcasts, it is currently only 12752 // supported on LE. 12753 if (!Subtarget->isLittle()) 12754 return SDValue(); 12755 12756 SDValue And = Op; 12757 if (And->getOpcode() == ISD::BITCAST) 12758 And = And->getOperand(0); 12759 if (And->getOpcode() != ISD::AND) 12760 return SDValue(); 12761 SDValue Mask = And->getOperand(1); 12762 if (Mask->getOpcode() == ISD::BITCAST) 12763 Mask = Mask->getOperand(0); 12764 12765 if (Mask->getOpcode() != ISD::BUILD_VECTOR || 12766 Mask.getValueType() != MVT::v4i32) 12767 return SDValue(); 12768 if (isAllOnesConstant(Mask->getOperand(0)) && 12769 isNullConstant(Mask->getOperand(1)) && 12770 isAllOnesConstant(Mask->getOperand(2)) && 12771 isNullConstant(Mask->getOperand(3))) 12772 return And->getOperand(0); 12773 return SDValue(); 12774 }; 12775 12776 SDLoc dl(N); 12777 if (SDValue Op0 = IsSignExt(N0)) { 12778 if (SDValue Op1 = IsSignExt(N1)) { 12779 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12780 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12781 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a); 12782 } 12783 } 12784 if (SDValue Op0 = IsZeroExt(N0)) { 12785 if (SDValue Op1 = IsZeroExt(N1)) { 12786 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12787 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12788 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a); 12789 } 12790 } 12791 12792 return SDValue(); 12793 } 12794 12795 static SDValue PerformMULCombine(SDNode *N, 12796 TargetLowering::DAGCombinerInfo &DCI, 12797 const ARMSubtarget *Subtarget) { 12798 SelectionDAG &DAG = DCI.DAG; 12799 12800 EVT VT = N->getValueType(0); 12801 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64) 12802 return PerformMVEVMULLCombine(N, DAG, Subtarget); 12803 12804 if (Subtarget->isThumb1Only()) 12805 return SDValue(); 12806 12807 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12808 return SDValue(); 12809 12810 if (VT.is64BitVector() || VT.is128BitVector()) 12811 return PerformVMULCombine(N, DCI, Subtarget); 12812 if (VT != MVT::i32) 12813 return SDValue(); 12814 12815 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12816 if (!C) 12817 return SDValue(); 12818 12819 int64_t MulAmt = C->getSExtValue(); 12820 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 12821 12822 ShiftAmt = ShiftAmt & (32 - 1); 12823 SDValue V = N->getOperand(0); 12824 SDLoc DL(N); 12825 12826 SDValue Res; 12827 MulAmt >>= ShiftAmt; 12828 12829 if (MulAmt >= 0) { 12830 if (isPowerOf2_32(MulAmt - 1)) { 12831 // (mul x, 2^N + 1) => (add (shl x, N), x) 12832 Res = DAG.getNode(ISD::ADD, DL, VT, 12833 V, 12834 DAG.getNode(ISD::SHL, DL, VT, 12835 V, 12836 DAG.getConstant(Log2_32(MulAmt - 1), DL, 12837 MVT::i32))); 12838 } else if (isPowerOf2_32(MulAmt + 1)) { 12839 // (mul x, 2^N - 1) => (sub (shl x, N), x) 12840 Res = DAG.getNode(ISD::SUB, DL, VT, 12841 DAG.getNode(ISD::SHL, DL, VT, 12842 V, 12843 DAG.getConstant(Log2_32(MulAmt + 1), DL, 12844 MVT::i32)), 12845 V); 12846 } else 12847 return SDValue(); 12848 } else { 12849 uint64_t MulAmtAbs = -MulAmt; 12850 if (isPowerOf2_32(MulAmtAbs + 1)) { 12851 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 12852 Res = DAG.getNode(ISD::SUB, DL, VT, 12853 V, 12854 DAG.getNode(ISD::SHL, DL, VT, 12855 V, 12856 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 12857 MVT::i32))); 12858 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 12859 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 12860 Res = DAG.getNode(ISD::ADD, DL, VT, 12861 V, 12862 DAG.getNode(ISD::SHL, DL, VT, 12863 V, 12864 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 12865 MVT::i32))); 12866 Res = DAG.getNode(ISD::SUB, DL, VT, 12867 DAG.getConstant(0, DL, MVT::i32), Res); 12868 } else 12869 return SDValue(); 12870 } 12871 12872 if (ShiftAmt != 0) 12873 Res = DAG.getNode(ISD::SHL, DL, VT, 12874 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 12875 12876 // Do not add new nodes to DAG combiner worklist. 12877 DCI.CombineTo(N, Res, false); 12878 return SDValue(); 12879 } 12880 12881 static SDValue CombineANDShift(SDNode *N, 12882 TargetLowering::DAGCombinerInfo &DCI, 12883 const ARMSubtarget *Subtarget) { 12884 // Allow DAGCombine to pattern-match before we touch the canonical form. 12885 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12886 return SDValue(); 12887 12888 if (N->getValueType(0) != MVT::i32) 12889 return SDValue(); 12890 12891 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12892 if (!N1C) 12893 return SDValue(); 12894 12895 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 12896 // Don't transform uxtb/uxth. 12897 if (C1 == 255 || C1 == 65535) 12898 return SDValue(); 12899 12900 SDNode *N0 = N->getOperand(0).getNode(); 12901 if (!N0->hasOneUse()) 12902 return SDValue(); 12903 12904 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 12905 return SDValue(); 12906 12907 bool LeftShift = N0->getOpcode() == ISD::SHL; 12908 12909 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12910 if (!N01C) 12911 return SDValue(); 12912 12913 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 12914 if (!C2 || C2 >= 32) 12915 return SDValue(); 12916 12917 // Clear irrelevant bits in the mask. 12918 if (LeftShift) 12919 C1 &= (-1U << C2); 12920 else 12921 C1 &= (-1U >> C2); 12922 12923 SelectionDAG &DAG = DCI.DAG; 12924 SDLoc DL(N); 12925 12926 // We have a pattern of the form "(and (shl x, c2) c1)" or 12927 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 12928 // transform to a pair of shifts, to save materializing c1. 12929 12930 // First pattern: right shift, then mask off leading bits. 12931 // FIXME: Use demanded bits? 12932 if (!LeftShift && isMask_32(C1)) { 12933 uint32_t C3 = countLeadingZeros(C1); 12934 if (C2 < C3) { 12935 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12936 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12937 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12938 DAG.getConstant(C3, DL, MVT::i32)); 12939 } 12940 } 12941 12942 // First pattern, reversed: left shift, then mask off trailing bits. 12943 if (LeftShift && isMask_32(~C1)) { 12944 uint32_t C3 = countTrailingZeros(C1); 12945 if (C2 < C3) { 12946 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12947 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12948 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12949 DAG.getConstant(C3, DL, MVT::i32)); 12950 } 12951 } 12952 12953 // Second pattern: left shift, then mask off leading bits. 12954 // FIXME: Use demanded bits? 12955 if (LeftShift && isShiftedMask_32(C1)) { 12956 uint32_t Trailing = countTrailingZeros(C1); 12957 uint32_t C3 = countLeadingZeros(C1); 12958 if (Trailing == C2 && C2 + C3 < 32) { 12959 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12960 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12961 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12962 DAG.getConstant(C3, DL, MVT::i32)); 12963 } 12964 } 12965 12966 // Second pattern, reversed: right shift, then mask off trailing bits. 12967 // FIXME: Handle other patterns of known/demanded bits. 12968 if (!LeftShift && isShiftedMask_32(C1)) { 12969 uint32_t Leading = countLeadingZeros(C1); 12970 uint32_t C3 = countTrailingZeros(C1); 12971 if (Leading == C2 && C2 + C3 < 32) { 12972 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12973 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12974 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12975 DAG.getConstant(C3, DL, MVT::i32)); 12976 } 12977 } 12978 12979 // FIXME: Transform "(and (shl x, c2) c1)" -> 12980 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 12981 // c1. 12982 return SDValue(); 12983 } 12984 12985 static SDValue PerformANDCombine(SDNode *N, 12986 TargetLowering::DAGCombinerInfo &DCI, 12987 const ARMSubtarget *Subtarget) { 12988 // Attempt to use immediate-form VBIC 12989 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12990 SDLoc dl(N); 12991 EVT VT = N->getValueType(0); 12992 SelectionDAG &DAG = DCI.DAG; 12993 12994 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 || 12995 VT == MVT::v8i1 || VT == MVT::v16i1) 12996 return SDValue(); 12997 12998 APInt SplatBits, SplatUndef; 12999 unsigned SplatBitSize; 13000 bool HasAnyUndefs; 13001 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 13002 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 13003 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 || 13004 SplatBitSize == 64) { 13005 EVT VbicVT; 13006 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 13007 SplatUndef.getZExtValue(), SplatBitSize, 13008 DAG, dl, VbicVT, VT, OtherModImm); 13009 if (Val.getNode()) { 13010 SDValue Input = 13011 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 13012 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 13013 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 13014 } 13015 } 13016 } 13017 13018 if (!Subtarget->isThumb1Only()) { 13019 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 13020 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 13021 return Result; 13022 13023 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13024 return Result; 13025 } 13026 13027 if (Subtarget->isThumb1Only()) 13028 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 13029 return Result; 13030 13031 return SDValue(); 13032 } 13033 13034 // Try combining OR nodes to SMULWB, SMULWT. 13035 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 13036 TargetLowering::DAGCombinerInfo &DCI, 13037 const ARMSubtarget *Subtarget) { 13038 if (!Subtarget->hasV6Ops() || 13039 (Subtarget->isThumb() && 13040 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 13041 return SDValue(); 13042 13043 SDValue SRL = OR->getOperand(0); 13044 SDValue SHL = OR->getOperand(1); 13045 13046 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 13047 SRL = OR->getOperand(1); 13048 SHL = OR->getOperand(0); 13049 } 13050 if (!isSRL16(SRL) || !isSHL16(SHL)) 13051 return SDValue(); 13052 13053 // The first operands to the shifts need to be the two results from the 13054 // same smul_lohi node. 13055 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 13056 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 13057 return SDValue(); 13058 13059 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 13060 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 13061 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 13062 return SDValue(); 13063 13064 // Now we have: 13065 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 13066 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 13067 // For SMUWB the 16-bit value will signed extended somehow. 13068 // For SMULWT only the SRA is required. 13069 // Check both sides of SMUL_LOHI 13070 SDValue OpS16 = SMULLOHI->getOperand(0); 13071 SDValue OpS32 = SMULLOHI->getOperand(1); 13072 13073 SelectionDAG &DAG = DCI.DAG; 13074 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 13075 OpS16 = OpS32; 13076 OpS32 = SMULLOHI->getOperand(0); 13077 } 13078 13079 SDLoc dl(OR); 13080 unsigned Opcode = 0; 13081 if (isS16(OpS16, DAG)) 13082 Opcode = ARMISD::SMULWB; 13083 else if (isSRA16(OpS16)) { 13084 Opcode = ARMISD::SMULWT; 13085 OpS16 = OpS16->getOperand(0); 13086 } 13087 else 13088 return SDValue(); 13089 13090 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 13091 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 13092 return SDValue(OR, 0); 13093 } 13094 13095 static SDValue PerformORCombineToBFI(SDNode *N, 13096 TargetLowering::DAGCombinerInfo &DCI, 13097 const ARMSubtarget *Subtarget) { 13098 // BFI is only available on V6T2+ 13099 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 13100 return SDValue(); 13101 13102 EVT VT = N->getValueType(0); 13103 SDValue N0 = N->getOperand(0); 13104 SDValue N1 = N->getOperand(1); 13105 SelectionDAG &DAG = DCI.DAG; 13106 SDLoc DL(N); 13107 // 1) or (and A, mask), val => ARMbfi A, val, mask 13108 // iff (val & mask) == val 13109 // 13110 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 13111 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 13112 // && mask == ~mask2 13113 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 13114 // && ~mask == mask2 13115 // (i.e., copy a bitfield value into another bitfield of the same width) 13116 13117 if (VT != MVT::i32) 13118 return SDValue(); 13119 13120 SDValue N00 = N0.getOperand(0); 13121 13122 // The value and the mask need to be constants so we can verify this is 13123 // actually a bitfield set. If the mask is 0xffff, we can do better 13124 // via a movt instruction, so don't use BFI in that case. 13125 SDValue MaskOp = N0.getOperand(1); 13126 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 13127 if (!MaskC) 13128 return SDValue(); 13129 unsigned Mask = MaskC->getZExtValue(); 13130 if (Mask == 0xffff) 13131 return SDValue(); 13132 SDValue Res; 13133 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 13134 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 13135 if (N1C) { 13136 unsigned Val = N1C->getZExtValue(); 13137 if ((Val & ~Mask) != Val) 13138 return SDValue(); 13139 13140 if (ARM::isBitFieldInvertedMask(Mask)) { 13141 Val >>= countTrailingZeros(~Mask); 13142 13143 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 13144 DAG.getConstant(Val, DL, MVT::i32), 13145 DAG.getConstant(Mask, DL, MVT::i32)); 13146 13147 DCI.CombineTo(N, Res, false); 13148 // Return value from the original node to inform the combiner than N is 13149 // now dead. 13150 return SDValue(N, 0); 13151 } 13152 } else if (N1.getOpcode() == ISD::AND) { 13153 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 13154 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 13155 if (!N11C) 13156 return SDValue(); 13157 unsigned Mask2 = N11C->getZExtValue(); 13158 13159 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 13160 // as is to match. 13161 if (ARM::isBitFieldInvertedMask(Mask) && 13162 (Mask == ~Mask2)) { 13163 // The pack halfword instruction works better for masks that fit it, 13164 // so use that when it's available. 13165 if (Subtarget->hasDSP() && 13166 (Mask == 0xffff || Mask == 0xffff0000)) 13167 return SDValue(); 13168 // 2a 13169 unsigned amt = countTrailingZeros(Mask2); 13170 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 13171 DAG.getConstant(amt, DL, MVT::i32)); 13172 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 13173 DAG.getConstant(Mask, DL, MVT::i32)); 13174 DCI.CombineTo(N, Res, false); 13175 // Return value from the original node to inform the combiner than N is 13176 // now dead. 13177 return SDValue(N, 0); 13178 } else if (ARM::isBitFieldInvertedMask(~Mask) && 13179 (~Mask == Mask2)) { 13180 // The pack halfword instruction works better for masks that fit it, 13181 // so use that when it's available. 13182 if (Subtarget->hasDSP() && 13183 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 13184 return SDValue(); 13185 // 2b 13186 unsigned lsb = countTrailingZeros(Mask); 13187 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 13188 DAG.getConstant(lsb, DL, MVT::i32)); 13189 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 13190 DAG.getConstant(Mask2, DL, MVT::i32)); 13191 DCI.CombineTo(N, Res, false); 13192 // Return value from the original node to inform the combiner than N is 13193 // now dead. 13194 return SDValue(N, 0); 13195 } 13196 } 13197 13198 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 13199 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 13200 ARM::isBitFieldInvertedMask(~Mask)) { 13201 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 13202 // where lsb(mask) == #shamt and masked bits of B are known zero. 13203 SDValue ShAmt = N00.getOperand(1); 13204 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 13205 unsigned LSB = countTrailingZeros(Mask); 13206 if (ShAmtC != LSB) 13207 return SDValue(); 13208 13209 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 13210 DAG.getConstant(~Mask, DL, MVT::i32)); 13211 13212 DCI.CombineTo(N, Res, false); 13213 // Return value from the original node to inform the combiner than N is 13214 // now dead. 13215 return SDValue(N, 0); 13216 } 13217 13218 return SDValue(); 13219 } 13220 13221 static bool isValidMVECond(unsigned CC, bool IsFloat) { 13222 switch (CC) { 13223 case ARMCC::EQ: 13224 case ARMCC::NE: 13225 case ARMCC::LE: 13226 case ARMCC::GT: 13227 case ARMCC::GE: 13228 case ARMCC::LT: 13229 return true; 13230 case ARMCC::HS: 13231 case ARMCC::HI: 13232 return !IsFloat; 13233 default: 13234 return false; 13235 }; 13236 } 13237 13238 static ARMCC::CondCodes getVCMPCondCode(SDValue N) { 13239 if (N->getOpcode() == ARMISD::VCMP) 13240 return (ARMCC::CondCodes)N->getConstantOperandVal(2); 13241 else if (N->getOpcode() == ARMISD::VCMPZ) 13242 return (ARMCC::CondCodes)N->getConstantOperandVal(1); 13243 else 13244 llvm_unreachable("Not a VCMP/VCMPZ!"); 13245 } 13246 13247 static bool CanInvertMVEVCMP(SDValue N) { 13248 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N)); 13249 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint()); 13250 } 13251 13252 static SDValue PerformORCombine_i1(SDNode *N, 13253 TargetLowering::DAGCombinerInfo &DCI, 13254 const ARMSubtarget *Subtarget) { 13255 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 13256 // together with predicates 13257 EVT VT = N->getValueType(0); 13258 SDLoc DL(N); 13259 SDValue N0 = N->getOperand(0); 13260 SDValue N1 = N->getOperand(1); 13261 13262 auto IsFreelyInvertable = [&](SDValue V) { 13263 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ) 13264 return CanInvertMVEVCMP(V); 13265 return false; 13266 }; 13267 13268 // At least one operand must be freely invertable. 13269 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1))) 13270 return SDValue(); 13271 13272 SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT); 13273 SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT); 13274 SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1); 13275 return DCI.DAG.getLogicalNOT(DL, And, VT); 13276 } 13277 13278 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 13279 static SDValue PerformORCombine(SDNode *N, 13280 TargetLowering::DAGCombinerInfo &DCI, 13281 const ARMSubtarget *Subtarget) { 13282 // Attempt to use immediate-form VORR 13283 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 13284 SDLoc dl(N); 13285 EVT VT = N->getValueType(0); 13286 SelectionDAG &DAG = DCI.DAG; 13287 13288 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13289 return SDValue(); 13290 13291 if (Subtarget->hasMVEIntegerOps() && 13292 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 13293 return PerformORCombine_i1(N, DCI, Subtarget); 13294 13295 APInt SplatBits, SplatUndef; 13296 unsigned SplatBitSize; 13297 bool HasAnyUndefs; 13298 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 13299 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 13300 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 || 13301 SplatBitSize == 64) { 13302 EVT VorrVT; 13303 SDValue Val = 13304 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 13305 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm); 13306 if (Val.getNode()) { 13307 SDValue Input = 13308 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 13309 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 13310 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 13311 } 13312 } 13313 } 13314 13315 if (!Subtarget->isThumb1Only()) { 13316 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 13317 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 13318 return Result; 13319 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 13320 return Result; 13321 } 13322 13323 SDValue N0 = N->getOperand(0); 13324 SDValue N1 = N->getOperand(1); 13325 13326 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 13327 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 13328 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 13329 13330 // The code below optimizes (or (and X, Y), Z). 13331 // The AND operand needs to have a single user to make these optimizations 13332 // profitable. 13333 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 13334 return SDValue(); 13335 13336 APInt SplatUndef; 13337 unsigned SplatBitSize; 13338 bool HasAnyUndefs; 13339 13340 APInt SplatBits0, SplatBits1; 13341 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 13342 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 13343 // Ensure that the second operand of both ands are constants 13344 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 13345 HasAnyUndefs) && !HasAnyUndefs) { 13346 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 13347 HasAnyUndefs) && !HasAnyUndefs) { 13348 // Ensure that the bit width of the constants are the same and that 13349 // the splat arguments are logical inverses as per the pattern we 13350 // are trying to simplify. 13351 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 13352 SplatBits0 == ~SplatBits1) { 13353 // Canonicalize the vector type to make instruction selection 13354 // simpler. 13355 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 13356 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT, 13357 N0->getOperand(1), 13358 N0->getOperand(0), 13359 N1->getOperand(0)); 13360 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 13361 } 13362 } 13363 } 13364 } 13365 13366 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 13367 // reasonable. 13368 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 13369 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 13370 return Res; 13371 } 13372 13373 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13374 return Result; 13375 13376 return SDValue(); 13377 } 13378 13379 static SDValue PerformXORCombine(SDNode *N, 13380 TargetLowering::DAGCombinerInfo &DCI, 13381 const ARMSubtarget *Subtarget) { 13382 EVT VT = N->getValueType(0); 13383 SelectionDAG &DAG = DCI.DAG; 13384 13385 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13386 return SDValue(); 13387 13388 if (!Subtarget->isThumb1Only()) { 13389 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 13390 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 13391 return Result; 13392 13393 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13394 return Result; 13395 } 13396 13397 if (Subtarget->hasMVEIntegerOps()) { 13398 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition. 13399 SDValue N0 = N->getOperand(0); 13400 SDValue N1 = N->getOperand(1); 13401 const TargetLowering *TLI = Subtarget->getTargetLowering(); 13402 if (TLI->isConstTrueVal(N1.getNode()) && 13403 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) { 13404 if (CanInvertMVEVCMP(N0)) { 13405 SDLoc DL(N0); 13406 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0)); 13407 13408 SmallVector<SDValue, 4> Ops; 13409 Ops.push_back(N0->getOperand(0)); 13410 if (N0->getOpcode() == ARMISD::VCMP) 13411 Ops.push_back(N0->getOperand(1)); 13412 Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32)); 13413 return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops); 13414 } 13415 } 13416 } 13417 13418 return SDValue(); 13419 } 13420 13421 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 13422 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 13423 // their position in "to" (Rd). 13424 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 13425 assert(N->getOpcode() == ARMISD::BFI); 13426 13427 SDValue From = N->getOperand(1); 13428 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 13429 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 13430 13431 // If the Base came from a SHR #C, we can deduce that it is really testing bit 13432 // #C in the base of the SHR. 13433 if (From->getOpcode() == ISD::SRL && 13434 isa<ConstantSDNode>(From->getOperand(1))) { 13435 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 13436 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 13437 FromMask <<= Shift.getLimitedValue(31); 13438 From = From->getOperand(0); 13439 } 13440 13441 return From; 13442 } 13443 13444 // If A and B contain one contiguous set of bits, does A | B == A . B? 13445 // 13446 // Neither A nor B must be zero. 13447 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 13448 unsigned LastActiveBitInA = A.countTrailingZeros(); 13449 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 13450 return LastActiveBitInA - 1 == FirstActiveBitInB; 13451 } 13452 13453 static SDValue FindBFIToCombineWith(SDNode *N) { 13454 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 13455 // if one exists. 13456 APInt ToMask, FromMask; 13457 SDValue From = ParseBFI(N, ToMask, FromMask); 13458 SDValue To = N->getOperand(0); 13459 13460 // Now check for a compatible BFI to merge with. We can pass through BFIs that 13461 // aren't compatible, but not if they set the same bit in their destination as 13462 // we do (or that of any BFI we're going to combine with). 13463 SDValue V = To; 13464 APInt CombinedToMask = ToMask; 13465 while (V.getOpcode() == ARMISD::BFI) { 13466 APInt NewToMask, NewFromMask; 13467 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 13468 if (NewFrom != From) { 13469 // This BFI has a different base. Keep going. 13470 CombinedToMask |= NewToMask; 13471 V = V.getOperand(0); 13472 continue; 13473 } 13474 13475 // Do the written bits conflict with any we've seen so far? 13476 if ((NewToMask & CombinedToMask).getBoolValue()) 13477 // Conflicting bits - bail out because going further is unsafe. 13478 return SDValue(); 13479 13480 // Are the new bits contiguous when combined with the old bits? 13481 if (BitsProperlyConcatenate(ToMask, NewToMask) && 13482 BitsProperlyConcatenate(FromMask, NewFromMask)) 13483 return V; 13484 if (BitsProperlyConcatenate(NewToMask, ToMask) && 13485 BitsProperlyConcatenate(NewFromMask, FromMask)) 13486 return V; 13487 13488 // We've seen a write to some bits, so track it. 13489 CombinedToMask |= NewToMask; 13490 // Keep going... 13491 V = V.getOperand(0); 13492 } 13493 13494 return SDValue(); 13495 } 13496 13497 static SDValue PerformBFICombine(SDNode *N, 13498 TargetLowering::DAGCombinerInfo &DCI) { 13499 SDValue N1 = N->getOperand(1); 13500 if (N1.getOpcode() == ISD::AND) { 13501 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 13502 // the bits being cleared by the AND are not demanded by the BFI. 13503 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 13504 if (!N11C) 13505 return SDValue(); 13506 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 13507 unsigned LSB = countTrailingZeros(~InvMask); 13508 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 13509 assert(Width < 13510 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 13511 "undefined behavior"); 13512 unsigned Mask = (1u << Width) - 1; 13513 unsigned Mask2 = N11C->getZExtValue(); 13514 if ((Mask & (~Mask2)) == 0) 13515 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 13516 N->getOperand(0), N1.getOperand(0), 13517 N->getOperand(2)); 13518 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 13519 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 13520 // Keep track of any consecutive bits set that all come from the same base 13521 // value. We can combine these together into a single BFI. 13522 SDValue CombineBFI = FindBFIToCombineWith(N); 13523 if (CombineBFI == SDValue()) 13524 return SDValue(); 13525 13526 // We've found a BFI. 13527 APInt ToMask1, FromMask1; 13528 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 13529 13530 APInt ToMask2, FromMask2; 13531 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 13532 assert(From1 == From2); 13533 (void)From2; 13534 13535 // First, unlink CombineBFI. 13536 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 13537 // Then create a new BFI, combining the two together. 13538 APInt NewFromMask = FromMask1 | FromMask2; 13539 APInt NewToMask = ToMask1 | ToMask2; 13540 13541 EVT VT = N->getValueType(0); 13542 SDLoc dl(N); 13543 13544 if (NewFromMask[0] == 0) 13545 From1 = DCI.DAG.getNode( 13546 ISD::SRL, dl, VT, From1, 13547 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 13548 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 13549 DCI.DAG.getConstant(~NewToMask, dl, VT)); 13550 } 13551 return SDValue(); 13552 } 13553 13554 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 13555 /// ARMISD::VMOVRRD. 13556 static SDValue PerformVMOVRRDCombine(SDNode *N, 13557 TargetLowering::DAGCombinerInfo &DCI, 13558 const ARMSubtarget *Subtarget) { 13559 // vmovrrd(vmovdrr x, y) -> x,y 13560 SDValue InDouble = N->getOperand(0); 13561 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 13562 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 13563 13564 // vmovrrd(load f64) -> (load i32), (load i32) 13565 SDNode *InNode = InDouble.getNode(); 13566 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 13567 InNode->getValueType(0) == MVT::f64 && 13568 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 13569 !cast<LoadSDNode>(InNode)->isVolatile()) { 13570 // TODO: Should this be done for non-FrameIndex operands? 13571 LoadSDNode *LD = cast<LoadSDNode>(InNode); 13572 13573 SelectionDAG &DAG = DCI.DAG; 13574 SDLoc DL(LD); 13575 SDValue BasePtr = LD->getBasePtr(); 13576 SDValue NewLD1 = 13577 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 13578 LD->getAlignment(), LD->getMemOperand()->getFlags()); 13579 13580 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 13581 DAG.getConstant(4, DL, MVT::i32)); 13582 13583 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 13584 LD->getPointerInfo().getWithOffset(4), 13585 std::min(4U, LD->getAlignment()), 13586 LD->getMemOperand()->getFlags()); 13587 13588 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 13589 if (DCI.DAG.getDataLayout().isBigEndian()) 13590 std::swap (NewLD1, NewLD2); 13591 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 13592 return Result; 13593 } 13594 13595 return SDValue(); 13596 } 13597 13598 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 13599 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 13600 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 13601 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 13602 SDValue Op0 = N->getOperand(0); 13603 SDValue Op1 = N->getOperand(1); 13604 if (Op0.getOpcode() == ISD::BITCAST) 13605 Op0 = Op0.getOperand(0); 13606 if (Op1.getOpcode() == ISD::BITCAST) 13607 Op1 = Op1.getOperand(0); 13608 if (Op0.getOpcode() == ARMISD::VMOVRRD && 13609 Op0.getNode() == Op1.getNode() && 13610 Op0.getResNo() == 0 && Op1.getResNo() == 1) 13611 return DAG.getNode(ISD::BITCAST, SDLoc(N), 13612 N->getValueType(0), Op0.getOperand(0)); 13613 return SDValue(); 13614 } 13615 13616 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13617 SDValue Op0 = N->getOperand(0); 13618 13619 // VMOVhr (VMOVrh (X)) -> X 13620 if (Op0->getOpcode() == ARMISD::VMOVrh) 13621 return Op0->getOperand(0); 13622 13623 // FullFP16: half values are passed in S-registers, and we don't 13624 // need any of the bitcast and moves: 13625 // 13626 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 13627 // t5: i32 = bitcast t2 13628 // t18: f16 = ARMISD::VMOVhr t5 13629 if (Op0->getOpcode() == ISD::BITCAST) { 13630 SDValue Copy = Op0->getOperand(0); 13631 if (Copy.getValueType() == MVT::f32 && 13632 Copy->getOpcode() == ISD::CopyFromReg) { 13633 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)}; 13634 SDValue NewCopy = 13635 DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops); 13636 return NewCopy; 13637 } 13638 } 13639 13640 // fold (VMOVhr (load x)) -> (load (f16*)x) 13641 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) { 13642 if (LN0->hasOneUse() && LN0->isUnindexed() && 13643 LN0->getMemoryVT() == MVT::i16) { 13644 SDValue Load = 13645 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(), 13646 LN0->getBasePtr(), LN0->getMemOperand()); 13647 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13648 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1)); 13649 return Load; 13650 } 13651 } 13652 13653 // Only the bottom 16 bits of the source register are used. 13654 APInt DemandedMask = APInt::getLowBitsSet(32, 16); 13655 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 13656 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI)) 13657 return SDValue(N, 0); 13658 13659 return SDValue(); 13660 } 13661 13662 static SDValue PerformVMOVrhCombine(SDNode *N, 13663 TargetLowering::DAGCombinerInfo &DCI) { 13664 SDValue N0 = N->getOperand(0); 13665 EVT VT = N->getValueType(0); 13666 13667 // fold (VMOVrh (fpconst x)) -> const x 13668 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) { 13669 APFloat V = C->getValueAPF(); 13670 return DCI.DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT); 13671 } 13672 13673 // fold (VMOVrh (load x)) -> (zextload (i16*)x) 13674 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) { 13675 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 13676 13677 SDValue Load = 13678 DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(), 13679 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand()); 13680 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13681 DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 13682 return Load; 13683 } 13684 13685 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n) 13686 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 13687 isa<ConstantSDNode>(N0->getOperand(1))) 13688 return DCI.DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0), 13689 N0->getOperand(1)); 13690 13691 return SDValue(); 13692 } 13693 13694 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 13695 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 13696 /// i64 vector to have f64 elements, since the value can then be loaded 13697 /// directly into a VFP register. 13698 static bool hasNormalLoadOperand(SDNode *N) { 13699 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 13700 for (unsigned i = 0; i < NumElts; ++i) { 13701 SDNode *Elt = N->getOperand(i).getNode(); 13702 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 13703 return true; 13704 } 13705 return false; 13706 } 13707 13708 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 13709 /// ISD::BUILD_VECTOR. 13710 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 13711 TargetLowering::DAGCombinerInfo &DCI, 13712 const ARMSubtarget *Subtarget) { 13713 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 13714 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 13715 // into a pair of GPRs, which is fine when the value is used as a scalar, 13716 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 13717 SelectionDAG &DAG = DCI.DAG; 13718 if (N->getNumOperands() == 2) 13719 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 13720 return RV; 13721 13722 // Load i64 elements as f64 values so that type legalization does not split 13723 // them up into i32 values. 13724 EVT VT = N->getValueType(0); 13725 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 13726 return SDValue(); 13727 SDLoc dl(N); 13728 SmallVector<SDValue, 8> Ops; 13729 unsigned NumElts = VT.getVectorNumElements(); 13730 for (unsigned i = 0; i < NumElts; ++i) { 13731 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 13732 Ops.push_back(V); 13733 // Make the DAGCombiner fold the bitcast. 13734 DCI.AddToWorklist(V.getNode()); 13735 } 13736 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 13737 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 13738 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 13739 } 13740 13741 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 13742 static SDValue 13743 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13744 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 13745 // At that time, we may have inserted bitcasts from integer to float. 13746 // If these bitcasts have survived DAGCombine, change the lowering of this 13747 // BUILD_VECTOR in something more vector friendly, i.e., that does not 13748 // force to use floating point types. 13749 13750 // Make sure we can change the type of the vector. 13751 // This is possible iff: 13752 // 1. The vector is only used in a bitcast to a integer type. I.e., 13753 // 1.1. Vector is used only once. 13754 // 1.2. Use is a bit convert to an integer type. 13755 // 2. The size of its operands are 32-bits (64-bits are not legal). 13756 EVT VT = N->getValueType(0); 13757 EVT EltVT = VT.getVectorElementType(); 13758 13759 // Check 1.1. and 2. 13760 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 13761 return SDValue(); 13762 13763 // By construction, the input type must be float. 13764 assert(EltVT == MVT::f32 && "Unexpected type!"); 13765 13766 // Check 1.2. 13767 SDNode *Use = *N->use_begin(); 13768 if (Use->getOpcode() != ISD::BITCAST || 13769 Use->getValueType(0).isFloatingPoint()) 13770 return SDValue(); 13771 13772 // Check profitability. 13773 // Model is, if more than half of the relevant operands are bitcast from 13774 // i32, turn the build_vector into a sequence of insert_vector_elt. 13775 // Relevant operands are everything that is not statically 13776 // (i.e., at compile time) bitcasted. 13777 unsigned NumOfBitCastedElts = 0; 13778 unsigned NumElts = VT.getVectorNumElements(); 13779 unsigned NumOfRelevantElts = NumElts; 13780 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 13781 SDValue Elt = N->getOperand(Idx); 13782 if (Elt->getOpcode() == ISD::BITCAST) { 13783 // Assume only bit cast to i32 will go away. 13784 if (Elt->getOperand(0).getValueType() == MVT::i32) 13785 ++NumOfBitCastedElts; 13786 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 13787 // Constants are statically casted, thus do not count them as 13788 // relevant operands. 13789 --NumOfRelevantElts; 13790 } 13791 13792 // Check if more than half of the elements require a non-free bitcast. 13793 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 13794 return SDValue(); 13795 13796 SelectionDAG &DAG = DCI.DAG; 13797 // Create the new vector type. 13798 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 13799 // Check if the type is legal. 13800 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13801 if (!TLI.isTypeLegal(VecVT)) 13802 return SDValue(); 13803 13804 // Combine: 13805 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 13806 // => BITCAST INSERT_VECTOR_ELT 13807 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 13808 // (BITCAST EN), N. 13809 SDValue Vec = DAG.getUNDEF(VecVT); 13810 SDLoc dl(N); 13811 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 13812 SDValue V = N->getOperand(Idx); 13813 if (V.isUndef()) 13814 continue; 13815 if (V.getOpcode() == ISD::BITCAST && 13816 V->getOperand(0).getValueType() == MVT::i32) 13817 // Fold obvious case. 13818 V = V.getOperand(0); 13819 else { 13820 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 13821 // Make the DAGCombiner fold the bitcasts. 13822 DCI.AddToWorklist(V.getNode()); 13823 } 13824 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 13825 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 13826 } 13827 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 13828 // Make the DAGCombiner fold the bitcasts. 13829 DCI.AddToWorklist(Vec.getNode()); 13830 return Vec; 13831 } 13832 13833 static SDValue 13834 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13835 EVT VT = N->getValueType(0); 13836 SDValue Op = N->getOperand(0); 13837 SDLoc dl(N); 13838 13839 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x) 13840 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) { 13841 // If the valuetypes are the same, we can remove the cast entirely. 13842 if (Op->getOperand(0).getValueType() == VT) 13843 return Op->getOperand(0); 13844 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0)); 13845 } 13846 13847 return SDValue(); 13848 } 13849 13850 static SDValue 13851 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 13852 const ARMSubtarget *ST) { 13853 EVT VT = N->getValueType(0); 13854 SDValue Op = N->getOperand(0); 13855 SDLoc dl(N); 13856 13857 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST 13858 if (ST->isLittle()) 13859 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op); 13860 13861 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x) 13862 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) { 13863 // If the valuetypes are the same, we can remove the cast entirely. 13864 if (Op->getOperand(0).getValueType() == VT) 13865 return Op->getOperand(0); 13866 return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0)); 13867 } 13868 13869 return SDValue(); 13870 } 13871 13872 static SDValue PerformVCMPCombine(SDNode *N, 13873 TargetLowering::DAGCombinerInfo &DCI, 13874 const ARMSubtarget *Subtarget) { 13875 if (!Subtarget->hasMVEIntegerOps()) 13876 return SDValue(); 13877 13878 EVT VT = N->getValueType(0); 13879 SDValue Op0 = N->getOperand(0); 13880 SDValue Op1 = N->getOperand(1); 13881 ARMCC::CondCodes Cond = 13882 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 13883 SDLoc dl(N); 13884 13885 // vcmp X, 0, cc -> vcmpz X, cc 13886 if (isZeroVector(Op1)) 13887 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, 13888 N->getOperand(2)); 13889 13890 unsigned SwappedCond = getSwappedCondition(Cond); 13891 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) { 13892 // vcmp 0, X, cc -> vcmpz X, reversed(cc) 13893 if (isZeroVector(Op0)) 13894 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1, 13895 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13896 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc) 13897 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP) 13898 return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0, 13899 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13900 } 13901 13902 return SDValue(); 13903 } 13904 13905 /// PerformInsertEltCombine - Target-specific dag combine xforms for 13906 /// ISD::INSERT_VECTOR_ELT. 13907 static SDValue PerformInsertEltCombine(SDNode *N, 13908 TargetLowering::DAGCombinerInfo &DCI) { 13909 // Bitcast an i64 load inserted into a vector to f64. 13910 // Otherwise, the i64 value will be legalized to a pair of i32 values. 13911 EVT VT = N->getValueType(0); 13912 SDNode *Elt = N->getOperand(1).getNode(); 13913 if (VT.getVectorElementType() != MVT::i64 || 13914 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 13915 return SDValue(); 13916 13917 SelectionDAG &DAG = DCI.DAG; 13918 SDLoc dl(N); 13919 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 13920 VT.getVectorNumElements()); 13921 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 13922 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 13923 // Make the DAGCombiner fold the bitcasts. 13924 DCI.AddToWorklist(Vec.getNode()); 13925 DCI.AddToWorklist(V.getNode()); 13926 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 13927 Vec, V, N->getOperand(2)); 13928 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 13929 } 13930 13931 static SDValue PerformExtractEltCombine(SDNode *N, 13932 TargetLowering::DAGCombinerInfo &DCI) { 13933 SDValue Op0 = N->getOperand(0); 13934 EVT VT = N->getValueType(0); 13935 SDLoc dl(N); 13936 13937 // extract (vdup x) -> x 13938 if (Op0->getOpcode() == ARMISD::VDUP) { 13939 SDValue X = Op0->getOperand(0); 13940 if (VT == MVT::f16 && X.getValueType() == MVT::i32) 13941 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X); 13942 if (VT == MVT::i32 && X.getValueType() == MVT::f16) 13943 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X); 13944 13945 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST) 13946 X = X->getOperand(0); 13947 if (X.getValueType() == VT) 13948 return X; 13949 } 13950 13951 return SDValue(); 13952 } 13953 13954 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 13955 /// ISD::VECTOR_SHUFFLE. 13956 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 13957 // The LLVM shufflevector instruction does not require the shuffle mask 13958 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 13959 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 13960 // operands do not match the mask length, they are extended by concatenating 13961 // them with undef vectors. That is probably the right thing for other 13962 // targets, but for NEON it is better to concatenate two double-register 13963 // size vector operands into a single quad-register size vector. Do that 13964 // transformation here: 13965 // shuffle(concat(v1, undef), concat(v2, undef)) -> 13966 // shuffle(concat(v1, v2), undef) 13967 SDValue Op0 = N->getOperand(0); 13968 SDValue Op1 = N->getOperand(1); 13969 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 13970 Op1.getOpcode() != ISD::CONCAT_VECTORS || 13971 Op0.getNumOperands() != 2 || 13972 Op1.getNumOperands() != 2) 13973 return SDValue(); 13974 SDValue Concat0Op1 = Op0.getOperand(1); 13975 SDValue Concat1Op1 = Op1.getOperand(1); 13976 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 13977 return SDValue(); 13978 // Skip the transformation if any of the types are illegal. 13979 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13980 EVT VT = N->getValueType(0); 13981 if (!TLI.isTypeLegal(VT) || 13982 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 13983 !TLI.isTypeLegal(Concat1Op1.getValueType())) 13984 return SDValue(); 13985 13986 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13987 Op0.getOperand(0), Op1.getOperand(0)); 13988 // Translate the shuffle mask. 13989 SmallVector<int, 16> NewMask; 13990 unsigned NumElts = VT.getVectorNumElements(); 13991 unsigned HalfElts = NumElts/2; 13992 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13993 for (unsigned n = 0; n < NumElts; ++n) { 13994 int MaskElt = SVN->getMaskElt(n); 13995 int NewElt = -1; 13996 if (MaskElt < (int)HalfElts) 13997 NewElt = MaskElt; 13998 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 13999 NewElt = HalfElts + MaskElt - NumElts; 14000 NewMask.push_back(NewElt); 14001 } 14002 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 14003 DAG.getUNDEF(VT), NewMask); 14004 } 14005 14006 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 14007 /// NEON load/store intrinsics, and generic vector load/stores, to merge 14008 /// base address updates. 14009 /// For generic load/stores, the memory type is assumed to be a vector. 14010 /// The caller is assumed to have checked legality. 14011 static SDValue CombineBaseUpdate(SDNode *N, 14012 TargetLowering::DAGCombinerInfo &DCI) { 14013 SelectionDAG &DAG = DCI.DAG; 14014 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 14015 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 14016 const bool isStore = N->getOpcode() == ISD::STORE; 14017 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 14018 SDValue Addr = N->getOperand(AddrOpIdx); 14019 MemSDNode *MemN = cast<MemSDNode>(N); 14020 SDLoc dl(N); 14021 14022 // Search for a use of the address operand that is an increment. 14023 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 14024 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 14025 SDNode *User = *UI; 14026 if (User->getOpcode() != ISD::ADD || 14027 UI.getUse().getResNo() != Addr.getResNo()) 14028 continue; 14029 14030 // Check that the add is independent of the load/store. Otherwise, folding 14031 // it would create a cycle. We can avoid searching through Addr as it's a 14032 // predecessor to both. 14033 SmallPtrSet<const SDNode *, 32> Visited; 14034 SmallVector<const SDNode *, 16> Worklist; 14035 Visited.insert(Addr.getNode()); 14036 Worklist.push_back(N); 14037 Worklist.push_back(User); 14038 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 14039 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14040 continue; 14041 14042 // Find the new opcode for the updating load/store. 14043 bool isLoadOp = true; 14044 bool isLaneOp = false; 14045 unsigned NewOpc = 0; 14046 unsigned NumVecs = 0; 14047 if (isIntrinsic) { 14048 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 14049 switch (IntNo) { 14050 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 14051 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 14052 NumVecs = 1; break; 14053 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 14054 NumVecs = 2; break; 14055 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 14056 NumVecs = 3; break; 14057 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 14058 NumVecs = 4; break; 14059 case Intrinsic::arm_neon_vld1x2: 14060 case Intrinsic::arm_neon_vld1x3: 14061 case Intrinsic::arm_neon_vld1x4: 14062 case Intrinsic::arm_neon_vld2dup: 14063 case Intrinsic::arm_neon_vld3dup: 14064 case Intrinsic::arm_neon_vld4dup: 14065 // TODO: Support updating VLD1x and VLDxDUP nodes. For now, we just skip 14066 // combining base updates for such intrinsics. 14067 continue; 14068 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 14069 NumVecs = 2; isLaneOp = true; break; 14070 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 14071 NumVecs = 3; isLaneOp = true; break; 14072 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 14073 NumVecs = 4; isLaneOp = true; break; 14074 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 14075 NumVecs = 1; isLoadOp = false; break; 14076 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 14077 NumVecs = 2; isLoadOp = false; break; 14078 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 14079 NumVecs = 3; isLoadOp = false; break; 14080 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 14081 NumVecs = 4; isLoadOp = false; break; 14082 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 14083 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 14084 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 14085 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 14086 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 14087 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 14088 } 14089 } else { 14090 isLaneOp = true; 14091 switch (N->getOpcode()) { 14092 default: llvm_unreachable("unexpected opcode for Neon base update"); 14093 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 14094 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 14095 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 14096 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 14097 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 14098 NumVecs = 1; isLaneOp = false; break; 14099 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 14100 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 14101 } 14102 } 14103 14104 // Find the size of memory referenced by the load/store. 14105 EVT VecTy; 14106 if (isLoadOp) { 14107 VecTy = N->getValueType(0); 14108 } else if (isIntrinsic) { 14109 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 14110 } else { 14111 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 14112 VecTy = N->getOperand(1).getValueType(); 14113 } 14114 14115 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14116 if (isLaneOp) 14117 NumBytes /= VecTy.getVectorNumElements(); 14118 14119 // If the increment is a constant, it must match the memory ref size. 14120 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14121 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 14122 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 14123 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 14124 // separate instructions that make it harder to use a non-constant update. 14125 continue; 14126 } 14127 14128 // OK, we found an ADD we can fold into the base update. 14129 // Now, create a _UPD node, taking care of not breaking alignment. 14130 14131 EVT AlignedVecTy = VecTy; 14132 unsigned Alignment = MemN->getAlignment(); 14133 14134 // If this is a less-than-standard-aligned load/store, change the type to 14135 // match the standard alignment. 14136 // The alignment is overlooked when selecting _UPD variants; and it's 14137 // easier to introduce bitcasts here than fix that. 14138 // There are 3 ways to get to this base-update combine: 14139 // - intrinsics: they are assumed to be properly aligned (to the standard 14140 // alignment of the memory type), so we don't need to do anything. 14141 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 14142 // intrinsics, so, likewise, there's nothing to do. 14143 // - generic load/store instructions: the alignment is specified as an 14144 // explicit operand, rather than implicitly as the standard alignment 14145 // of the memory type (like the intrisics). We need to change the 14146 // memory type to match the explicit alignment. That way, we don't 14147 // generate non-standard-aligned ARMISD::VLDx nodes. 14148 if (isa<LSBaseSDNode>(N)) { 14149 if (Alignment == 0) 14150 Alignment = 1; 14151 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 14152 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 14153 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 14154 assert(!isLaneOp && "Unexpected generic load/store lane."); 14155 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 14156 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 14157 } 14158 // Don't set an explicit alignment on regular load/stores that we want 14159 // to transform to VLD/VST 1_UPD nodes. 14160 // This matches the behavior of regular load/stores, which only get an 14161 // explicit alignment if the MMO alignment is larger than the standard 14162 // alignment of the memory type. 14163 // Intrinsics, however, always get an explicit alignment, set to the 14164 // alignment of the MMO. 14165 Alignment = 1; 14166 } 14167 14168 // Create the new updating load/store node. 14169 // First, create an SDVTList for the new updating node's results. 14170 EVT Tys[6]; 14171 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 14172 unsigned n; 14173 for (n = 0; n < NumResultVecs; ++n) 14174 Tys[n] = AlignedVecTy; 14175 Tys[n++] = MVT::i32; 14176 Tys[n] = MVT::Other; 14177 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 14178 14179 // Then, gather the new node's operands. 14180 SmallVector<SDValue, 8> Ops; 14181 Ops.push_back(N->getOperand(0)); // incoming chain 14182 Ops.push_back(N->getOperand(AddrOpIdx)); 14183 Ops.push_back(Inc); 14184 14185 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 14186 // Try to match the intrinsic's signature 14187 Ops.push_back(StN->getValue()); 14188 } else { 14189 // Loads (and of course intrinsics) match the intrinsics' signature, 14190 // so just add all but the alignment operand. 14191 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 14192 Ops.push_back(N->getOperand(i)); 14193 } 14194 14195 // For all node types, the alignment operand is always the last one. 14196 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 14197 14198 // If this is a non-standard-aligned STORE, the penultimate operand is the 14199 // stored value. Bitcast it to the aligned type. 14200 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 14201 SDValue &StVal = Ops[Ops.size()-2]; 14202 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 14203 } 14204 14205 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 14206 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 14207 MemN->getMemOperand()); 14208 14209 // Update the uses. 14210 SmallVector<SDValue, 5> NewResults; 14211 for (unsigned i = 0; i < NumResultVecs; ++i) 14212 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14213 14214 // If this is an non-standard-aligned LOAD, the first result is the loaded 14215 // value. Bitcast it to the expected result type. 14216 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 14217 SDValue &LdVal = NewResults[0]; 14218 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 14219 } 14220 14221 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 14222 DCI.CombineTo(N, NewResults); 14223 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14224 14225 break; 14226 } 14227 return SDValue(); 14228 } 14229 14230 static SDValue PerformVLDCombine(SDNode *N, 14231 TargetLowering::DAGCombinerInfo &DCI) { 14232 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14233 return SDValue(); 14234 14235 return CombineBaseUpdate(N, DCI); 14236 } 14237 14238 static SDValue PerformMVEVLDCombine(SDNode *N, 14239 TargetLowering::DAGCombinerInfo &DCI) { 14240 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14241 return SDValue(); 14242 14243 SelectionDAG &DAG = DCI.DAG; 14244 SDValue Addr = N->getOperand(2); 14245 MemSDNode *MemN = cast<MemSDNode>(N); 14246 SDLoc dl(N); 14247 14248 // For the stores, where there are multiple intrinsics we only actually want 14249 // to post-inc the last of the them. 14250 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 14251 if (IntNo == Intrinsic::arm_mve_vst2q && 14252 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1) 14253 return SDValue(); 14254 if (IntNo == Intrinsic::arm_mve_vst4q && 14255 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3) 14256 return SDValue(); 14257 14258 // Search for a use of the address operand that is an increment. 14259 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 14260 UE = Addr.getNode()->use_end(); 14261 UI != UE; ++UI) { 14262 SDNode *User = *UI; 14263 if (User->getOpcode() != ISD::ADD || 14264 UI.getUse().getResNo() != Addr.getResNo()) 14265 continue; 14266 14267 // Check that the add is independent of the load/store. Otherwise, folding 14268 // it would create a cycle. We can avoid searching through Addr as it's a 14269 // predecessor to both. 14270 SmallPtrSet<const SDNode *, 32> Visited; 14271 SmallVector<const SDNode *, 16> Worklist; 14272 Visited.insert(Addr.getNode()); 14273 Worklist.push_back(N); 14274 Worklist.push_back(User); 14275 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 14276 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14277 continue; 14278 14279 // Find the new opcode for the updating load/store. 14280 bool isLoadOp = true; 14281 unsigned NewOpc = 0; 14282 unsigned NumVecs = 0; 14283 switch (IntNo) { 14284 default: 14285 llvm_unreachable("unexpected intrinsic for MVE VLDn combine"); 14286 case Intrinsic::arm_mve_vld2q: 14287 NewOpc = ARMISD::VLD2_UPD; 14288 NumVecs = 2; 14289 break; 14290 case Intrinsic::arm_mve_vld4q: 14291 NewOpc = ARMISD::VLD4_UPD; 14292 NumVecs = 4; 14293 break; 14294 case Intrinsic::arm_mve_vst2q: 14295 NewOpc = ARMISD::VST2_UPD; 14296 NumVecs = 2; 14297 isLoadOp = false; 14298 break; 14299 case Intrinsic::arm_mve_vst4q: 14300 NewOpc = ARMISD::VST4_UPD; 14301 NumVecs = 4; 14302 isLoadOp = false; 14303 break; 14304 } 14305 14306 // Find the size of memory referenced by the load/store. 14307 EVT VecTy; 14308 if (isLoadOp) { 14309 VecTy = N->getValueType(0); 14310 } else { 14311 VecTy = N->getOperand(3).getValueType(); 14312 } 14313 14314 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14315 14316 // If the increment is a constant, it must match the memory ref size. 14317 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14318 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 14319 if (!CInc || CInc->getZExtValue() != NumBytes) 14320 continue; 14321 14322 // Create the new updating load/store node. 14323 // First, create an SDVTList for the new updating node's results. 14324 EVT Tys[6]; 14325 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 14326 unsigned n; 14327 for (n = 0; n < NumResultVecs; ++n) 14328 Tys[n] = VecTy; 14329 Tys[n++] = MVT::i32; 14330 Tys[n] = MVT::Other; 14331 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 14332 14333 // Then, gather the new node's operands. 14334 SmallVector<SDValue, 8> Ops; 14335 Ops.push_back(N->getOperand(0)); // incoming chain 14336 Ops.push_back(N->getOperand(2)); // ptr 14337 Ops.push_back(Inc); 14338 14339 for (unsigned i = 3; i < N->getNumOperands(); ++i) 14340 Ops.push_back(N->getOperand(i)); 14341 14342 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy, 14343 MemN->getMemOperand()); 14344 14345 // Update the uses. 14346 SmallVector<SDValue, 5> NewResults; 14347 for (unsigned i = 0; i < NumResultVecs; ++i) 14348 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14349 14350 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain 14351 DCI.CombineTo(N, NewResults); 14352 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14353 14354 break; 14355 } 14356 14357 return SDValue(); 14358 } 14359 14360 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 14361 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 14362 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 14363 /// return true. 14364 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 14365 SelectionDAG &DAG = DCI.DAG; 14366 EVT VT = N->getValueType(0); 14367 // vldN-dup instructions only support 64-bit vectors for N > 1. 14368 if (!VT.is64BitVector()) 14369 return false; 14370 14371 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 14372 SDNode *VLD = N->getOperand(0).getNode(); 14373 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 14374 return false; 14375 unsigned NumVecs = 0; 14376 unsigned NewOpc = 0; 14377 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 14378 if (IntNo == Intrinsic::arm_neon_vld2lane) { 14379 NumVecs = 2; 14380 NewOpc = ARMISD::VLD2DUP; 14381 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 14382 NumVecs = 3; 14383 NewOpc = ARMISD::VLD3DUP; 14384 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 14385 NumVecs = 4; 14386 NewOpc = ARMISD::VLD4DUP; 14387 } else { 14388 return false; 14389 } 14390 14391 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 14392 // numbers match the load. 14393 unsigned VLDLaneNo = 14394 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 14395 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 14396 UI != UE; ++UI) { 14397 // Ignore uses of the chain result. 14398 if (UI.getUse().getResNo() == NumVecs) 14399 continue; 14400 SDNode *User = *UI; 14401 if (User->getOpcode() != ARMISD::VDUPLANE || 14402 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 14403 return false; 14404 } 14405 14406 // Create the vldN-dup node. 14407 EVT Tys[5]; 14408 unsigned n; 14409 for (n = 0; n < NumVecs; ++n) 14410 Tys[n] = VT; 14411 Tys[n] = MVT::Other; 14412 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 14413 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 14414 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 14415 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 14416 Ops, VLDMemInt->getMemoryVT(), 14417 VLDMemInt->getMemOperand()); 14418 14419 // Update the uses. 14420 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 14421 UI != UE; ++UI) { 14422 unsigned ResNo = UI.getUse().getResNo(); 14423 // Ignore uses of the chain result. 14424 if (ResNo == NumVecs) 14425 continue; 14426 SDNode *User = *UI; 14427 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 14428 } 14429 14430 // Now the vldN-lane intrinsic is dead except for its chain result. 14431 // Update uses of the chain. 14432 std::vector<SDValue> VLDDupResults; 14433 for (unsigned n = 0; n < NumVecs; ++n) 14434 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 14435 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 14436 DCI.CombineTo(VLD, VLDDupResults); 14437 14438 return true; 14439 } 14440 14441 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 14442 /// ARMISD::VDUPLANE. 14443 static SDValue PerformVDUPLANECombine(SDNode *N, 14444 TargetLowering::DAGCombinerInfo &DCI, 14445 const ARMSubtarget *Subtarget) { 14446 SDValue Op = N->getOperand(0); 14447 EVT VT = N->getValueType(0); 14448 14449 // On MVE, we just convert the VDUPLANE to a VDUP with an extract. 14450 if (Subtarget->hasMVEIntegerOps()) { 14451 EVT ExtractVT = VT.getVectorElementType(); 14452 // We need to ensure we are creating a legal type. 14453 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT)) 14454 ExtractVT = MVT::i32; 14455 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT, 14456 N->getOperand(0), N->getOperand(1)); 14457 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract); 14458 } 14459 14460 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 14461 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 14462 if (CombineVLDDUP(N, DCI)) 14463 return SDValue(N, 0); 14464 14465 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 14466 // redundant. Ignore bit_converts for now; element sizes are checked below. 14467 while (Op.getOpcode() == ISD::BITCAST) 14468 Op = Op.getOperand(0); 14469 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 14470 return SDValue(); 14471 14472 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 14473 unsigned EltSize = Op.getScalarValueSizeInBits(); 14474 // The canonical VMOV for a zero vector uses a 32-bit element size. 14475 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14476 unsigned EltBits; 14477 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 14478 EltSize = 8; 14479 if (EltSize > VT.getScalarSizeInBits()) 14480 return SDValue(); 14481 14482 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 14483 } 14484 14485 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 14486 static SDValue PerformVDUPCombine(SDNode *N, 14487 TargetLowering::DAGCombinerInfo &DCI, 14488 const ARMSubtarget *Subtarget) { 14489 SelectionDAG &DAG = DCI.DAG; 14490 SDValue Op = N->getOperand(0); 14491 SDLoc dl(N); 14492 14493 if (Subtarget->hasMVEIntegerOps()) { 14494 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will 14495 // need to come from a GPR. 14496 if (Op.getValueType() == MVT::f32) 14497 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 14498 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op)); 14499 else if (Op.getValueType() == MVT::f16) 14500 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 14501 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op)); 14502 } 14503 14504 if (!Subtarget->hasNEON()) 14505 return SDValue(); 14506 14507 // Match VDUP(LOAD) -> VLD1DUP. 14508 // We match this pattern here rather than waiting for isel because the 14509 // transform is only legal for unindexed loads. 14510 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 14511 if (LD && Op.hasOneUse() && LD->isUnindexed() && 14512 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 14513 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 14514 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 14515 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 14516 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 14517 Ops, LD->getMemoryVT(), 14518 LD->getMemOperand()); 14519 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 14520 return VLDDup; 14521 } 14522 14523 return SDValue(); 14524 } 14525 14526 static SDValue PerformLOADCombine(SDNode *N, 14527 TargetLowering::DAGCombinerInfo &DCI) { 14528 EVT VT = N->getValueType(0); 14529 14530 // If this is a legal vector load, try to combine it into a VLD1_UPD. 14531 if (ISD::isNormalLoad(N) && VT.isVector() && 14532 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 14533 return CombineBaseUpdate(N, DCI); 14534 14535 return SDValue(); 14536 } 14537 14538 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 14539 // pack all of the elements in one place. Next, store to memory in fewer 14540 // chunks. 14541 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St, 14542 SelectionDAG &DAG) { 14543 SDValue StVal = St->getValue(); 14544 EVT VT = StVal.getValueType(); 14545 if (!St->isTruncatingStore() || !VT.isVector()) 14546 return SDValue(); 14547 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14548 EVT StVT = St->getMemoryVT(); 14549 unsigned NumElems = VT.getVectorNumElements(); 14550 assert(StVT != VT && "Cannot truncate to the same type"); 14551 unsigned FromEltSz = VT.getScalarSizeInBits(); 14552 unsigned ToEltSz = StVT.getScalarSizeInBits(); 14553 14554 // From, To sizes and ElemCount must be pow of two 14555 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) 14556 return SDValue(); 14557 14558 // We are going to use the original vector elt for storing. 14559 // Accumulated smaller vector elements must be a multiple of the store size. 14560 if (0 != (NumElems * FromEltSz) % ToEltSz) 14561 return SDValue(); 14562 14563 unsigned SizeRatio = FromEltSz / ToEltSz; 14564 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 14565 14566 // Create a type on which we perform the shuffle. 14567 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 14568 NumElems * SizeRatio); 14569 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 14570 14571 SDLoc DL(St); 14572 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 14573 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14574 for (unsigned i = 0; i < NumElems; ++i) 14575 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1 14576 : i * SizeRatio; 14577 14578 // Can't shuffle using an illegal type. 14579 if (!TLI.isTypeLegal(WideVecVT)) 14580 return SDValue(); 14581 14582 SDValue Shuff = DAG.getVectorShuffle( 14583 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec); 14584 // At this point all of the data is stored at the bottom of the 14585 // register. We now need to save it to mem. 14586 14587 // Find the largest store unit 14588 MVT StoreType = MVT::i8; 14589 for (MVT Tp : MVT::integer_valuetypes()) { 14590 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 14591 StoreType = Tp; 14592 } 14593 // Didn't find a legal store type. 14594 if (!TLI.isTypeLegal(StoreType)) 14595 return SDValue(); 14596 14597 // Bitcast the original vector into a vector of store-size units 14598 EVT StoreVecVT = 14599 EVT::getVectorVT(*DAG.getContext(), StoreType, 14600 VT.getSizeInBits() / EVT(StoreType).getSizeInBits()); 14601 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 14602 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 14603 SmallVector<SDValue, 8> Chains; 14604 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 14605 TLI.getPointerTy(DAG.getDataLayout())); 14606 SDValue BasePtr = St->getBasePtr(); 14607 14608 // Perform one or more big stores into memory. 14609 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits(); 14610 for (unsigned I = 0; I < E; I++) { 14611 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType, 14612 ShuffWide, DAG.getIntPtrConstant(I, DL)); 14613 SDValue Ch = 14614 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(), 14615 St->getAlignment(), St->getMemOperand()->getFlags()); 14616 BasePtr = 14617 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment); 14618 Chains.push_back(Ch); 14619 } 14620 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 14621 } 14622 14623 // Try taking a single vector store from an truncate (which would otherwise turn 14624 // into an expensive buildvector) and splitting it into a series of narrowing 14625 // stores. 14626 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St, 14627 SelectionDAG &DAG) { 14628 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed()) 14629 return SDValue(); 14630 SDValue Trunc = St->getValue(); 14631 if (Trunc->getOpcode() != ISD::TRUNCATE && Trunc->getOpcode() != ISD::FP_ROUND) 14632 return SDValue(); 14633 EVT FromVT = Trunc->getOperand(0).getValueType(); 14634 EVT ToVT = Trunc.getValueType(); 14635 if (!ToVT.isVector()) 14636 return SDValue(); 14637 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 14638 EVT ToEltVT = ToVT.getVectorElementType(); 14639 EVT FromEltVT = FromVT.getVectorElementType(); 14640 14641 unsigned NumElements = 0; 14642 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8)) 14643 NumElements = 4; 14644 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8) 14645 NumElements = 8; 14646 if (FromEltVT == MVT::f32 && ToEltVT == MVT::f16) 14647 NumElements = 4; 14648 if (NumElements == 0 || 14649 (FromEltVT != MVT::f32 && FromVT.getVectorNumElements() == NumElements) || 14650 FromVT.getVectorNumElements() % NumElements != 0) 14651 return SDValue(); 14652 14653 // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so 14654 // use the VMOVN over splitting the store. We are looking for patterns of: 14655 // !rev: 0 N 1 N+1 2 N+2 ... 14656 // rev: N 0 N+1 1 N+2 2 ... 14657 auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) { 14658 unsigned NumElts = ToVT.getVectorNumElements(); 14659 if (NumElts != M.size()) 14660 return false; 14661 14662 unsigned Off0 = rev ? NumElts : 0; 14663 unsigned Off1 = rev ? 0 : NumElts; 14664 14665 for (unsigned i = 0; i < NumElts; i += 2) { 14666 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2)) 14667 return false; 14668 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2)) 14669 return false; 14670 } 14671 14672 return true; 14673 }; 14674 14675 // It may be preferable to keep the store unsplit as the trunc may end up 14676 // being removed. Check that here. 14677 if (Trunc.getOperand(0).getOpcode() == ISD::SMIN) { 14678 if (SDValue U = PerformVQDMULHCombine(Trunc.getOperand(0).getNode(), DAG)) { 14679 DAG.ReplaceAllUsesWith(Trunc.getOperand(0), U); 14680 return SDValue(); 14681 } 14682 } 14683 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0))) 14684 if (isVMOVNOriginalMask(Shuffle->getMask(), false) || 14685 isVMOVNOriginalMask(Shuffle->getMask(), true)) 14686 return SDValue(); 14687 14688 LLVMContext &C = *DAG.getContext(); 14689 SDLoc DL(St); 14690 // Details about the old store 14691 SDValue Ch = St->getChain(); 14692 SDValue BasePtr = St->getBasePtr(); 14693 Align Alignment = St->getOriginalAlign(); 14694 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags(); 14695 AAMDNodes AAInfo = St->getAAInfo(); 14696 14697 // We split the store into slices of NumElements. fp16 trunc stores are vcvt 14698 // and then stored as truncating integer stores. 14699 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements); 14700 EVT NewToVT = EVT::getVectorVT( 14701 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements); 14702 14703 SmallVector<SDValue, 4> Stores; 14704 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 14705 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8; 14706 SDValue NewPtr = 14707 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset)); 14708 14709 SDValue Extract = 14710 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0), 14711 DAG.getConstant(i * NumElements, DL, MVT::i32)); 14712 14713 if (ToEltVT == MVT::f16) { 14714 SDValue FPTrunc = 14715 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16), 14716 Extract, DAG.getConstant(0, DL, MVT::i32)); 14717 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc); 14718 } 14719 14720 SDValue Store = DAG.getTruncStore( 14721 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset), 14722 NewToVT, Alignment.value(), MMOFlags, AAInfo); 14723 Stores.push_back(Store); 14724 } 14725 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores); 14726 } 14727 14728 /// PerformSTORECombine - Target-specific dag combine xforms for 14729 /// ISD::STORE. 14730 static SDValue PerformSTORECombine(SDNode *N, 14731 TargetLowering::DAGCombinerInfo &DCI, 14732 const ARMSubtarget *Subtarget) { 14733 StoreSDNode *St = cast<StoreSDNode>(N); 14734 if (St->isVolatile()) 14735 return SDValue(); 14736 SDValue StVal = St->getValue(); 14737 EVT VT = StVal.getValueType(); 14738 14739 if (Subtarget->hasNEON()) 14740 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG)) 14741 return Store; 14742 14743 if (Subtarget->hasMVEIntegerOps()) 14744 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG)) 14745 return NewToken; 14746 14747 if (!ISD::isNormalStore(St)) 14748 return SDValue(); 14749 14750 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 14751 // ARM stores of arguments in the same cache line. 14752 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 14753 StVal.getNode()->hasOneUse()) { 14754 SelectionDAG &DAG = DCI.DAG; 14755 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 14756 SDLoc DL(St); 14757 SDValue BasePtr = St->getBasePtr(); 14758 SDValue NewST1 = DAG.getStore( 14759 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 14760 BasePtr, St->getPointerInfo(), St->getOriginalAlign(), 14761 St->getMemOperand()->getFlags()); 14762 14763 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 14764 DAG.getConstant(4, DL, MVT::i32)); 14765 return DAG.getStore(NewST1.getValue(0), DL, 14766 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 14767 OffsetPtr, St->getPointerInfo().getWithOffset(4), 14768 St->getOriginalAlign(), 14769 St->getMemOperand()->getFlags()); 14770 } 14771 14772 if (StVal.getValueType() == MVT::i64 && 14773 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14774 14775 // Bitcast an i64 store extracted from a vector to f64. 14776 // Otherwise, the i64 value will be legalized to a pair of i32 values. 14777 SelectionDAG &DAG = DCI.DAG; 14778 SDLoc dl(StVal); 14779 SDValue IntVec = StVal.getOperand(0); 14780 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 14781 IntVec.getValueType().getVectorNumElements()); 14782 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 14783 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 14784 Vec, StVal.getOperand(1)); 14785 dl = SDLoc(N); 14786 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 14787 // Make the DAGCombiner fold the bitcasts. 14788 DCI.AddToWorklist(Vec.getNode()); 14789 DCI.AddToWorklist(ExtElt.getNode()); 14790 DCI.AddToWorklist(V.getNode()); 14791 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 14792 St->getPointerInfo(), St->getAlignment(), 14793 St->getMemOperand()->getFlags(), St->getAAInfo()); 14794 } 14795 14796 // If this is a legal vector store, try to combine it into a VST1_UPD. 14797 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() && 14798 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 14799 return CombineBaseUpdate(N, DCI); 14800 14801 return SDValue(); 14802 } 14803 14804 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 14805 /// can replace combinations of VMUL and VCVT (floating-point to integer) 14806 /// when the VMUL has a constant operand that is a power of 2. 14807 /// 14808 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 14809 /// vmul.f32 d16, d17, d16 14810 /// vcvt.s32.f32 d16, d16 14811 /// becomes: 14812 /// vcvt.s32.f32 d16, d16, #3 14813 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 14814 const ARMSubtarget *Subtarget) { 14815 if (!Subtarget->hasNEON()) 14816 return SDValue(); 14817 14818 SDValue Op = N->getOperand(0); 14819 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 14820 Op.getOpcode() != ISD::FMUL) 14821 return SDValue(); 14822 14823 SDValue ConstVec = Op->getOperand(1); 14824 if (!isa<BuildVectorSDNode>(ConstVec)) 14825 return SDValue(); 14826 14827 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 14828 uint32_t FloatBits = FloatTy.getSizeInBits(); 14829 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 14830 uint32_t IntBits = IntTy.getSizeInBits(); 14831 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 14832 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 14833 // These instructions only exist converting from f32 to i32. We can handle 14834 // smaller integers by generating an extra truncate, but larger ones would 14835 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 14836 // these intructions only support v2i32/v4i32 types. 14837 return SDValue(); 14838 } 14839 14840 BitVector UndefElements; 14841 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 14842 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 14843 if (C == -1 || C == 0 || C > 32) 14844 return SDValue(); 14845 14846 SDLoc dl(N); 14847 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 14848 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 14849 Intrinsic::arm_neon_vcvtfp2fxu; 14850 SDValue FixConv = DAG.getNode( 14851 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 14852 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 14853 DAG.getConstant(C, dl, MVT::i32)); 14854 14855 if (IntBits < FloatBits) 14856 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 14857 14858 return FixConv; 14859 } 14860 14861 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 14862 /// can replace combinations of VCVT (integer to floating-point) and VDIV 14863 /// when the VDIV has a constant operand that is a power of 2. 14864 /// 14865 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 14866 /// vcvt.f32.s32 d16, d16 14867 /// vdiv.f32 d16, d17, d16 14868 /// becomes: 14869 /// vcvt.f32.s32 d16, d16, #3 14870 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 14871 const ARMSubtarget *Subtarget) { 14872 if (!Subtarget->hasNEON()) 14873 return SDValue(); 14874 14875 SDValue Op = N->getOperand(0); 14876 unsigned OpOpcode = Op.getNode()->getOpcode(); 14877 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 14878 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 14879 return SDValue(); 14880 14881 SDValue ConstVec = N->getOperand(1); 14882 if (!isa<BuildVectorSDNode>(ConstVec)) 14883 return SDValue(); 14884 14885 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 14886 uint32_t FloatBits = FloatTy.getSizeInBits(); 14887 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 14888 uint32_t IntBits = IntTy.getSizeInBits(); 14889 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 14890 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 14891 // These instructions only exist converting from i32 to f32. We can handle 14892 // smaller integers by generating an extra extend, but larger ones would 14893 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 14894 // these intructions only support v2i32/v4i32 types. 14895 return SDValue(); 14896 } 14897 14898 BitVector UndefElements; 14899 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 14900 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 14901 if (C == -1 || C == 0 || C > 32) 14902 return SDValue(); 14903 14904 SDLoc dl(N); 14905 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 14906 SDValue ConvInput = Op.getOperand(0); 14907 if (IntBits < FloatBits) 14908 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 14909 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 14910 ConvInput); 14911 14912 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 14913 Intrinsic::arm_neon_vcvtfxu2fp; 14914 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 14915 Op.getValueType(), 14916 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 14917 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 14918 } 14919 14920 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG, 14921 const ARMSubtarget *ST) { 14922 if (!ST->hasMVEIntegerOps()) 14923 return SDValue(); 14924 14925 assert(N->getOpcode() == ISD::VECREDUCE_ADD); 14926 EVT ResVT = N->getValueType(0); 14927 SDValue N0 = N->getOperand(0); 14928 SDLoc dl(N); 14929 14930 // We are looking for something that will have illegal types if left alone, 14931 // but that we can convert to a single instruction undef MVE. For example 14932 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A 14933 // or 14934 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B 14935 14936 // Cases: 14937 // VADDV u/s 8/16/32 14938 // VMLAV u/s 8/16/32 14939 // VADDLV u/s 32 14940 // VMLALV u/s 16/32 14941 14942 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) { 14943 if (ResVT != RetTy || N0->getOpcode() != ExtendCode) 14944 return SDValue(); 14945 SDValue A = N0->getOperand(0); 14946 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14947 return A; 14948 return SDValue(); 14949 }; 14950 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode, 14951 ArrayRef<MVT> ExtTypes, SDValue &Mask) { 14952 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT || 14953 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode())) 14954 return SDValue(); 14955 Mask = N0->getOperand(0); 14956 SDValue Ext = N0->getOperand(1); 14957 if (Ext->getOpcode() != ExtendCode) 14958 return SDValue(); 14959 SDValue A = Ext->getOperand(0); 14960 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14961 return A; 14962 return SDValue(); 14963 }; 14964 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 14965 SDValue &A, SDValue &B) { 14966 // For a vmla we are trying to match a larger pattern: 14967 // ExtA = sext/zext A 14968 // ExtB = sext/zext B 14969 // Mul = mul ExtA, ExtB 14970 // vecreduce.add Mul 14971 // There might also be en extra extend between the mul and the addreduce, so 14972 // long as the bitwidth is high enough to make them equivalent (for example 14973 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64). 14974 if (ResVT != RetTy) 14975 return false; 14976 SDValue Mul = N0; 14977 if (Mul->getOpcode() == ExtendCode && 14978 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >= 14979 ResVT.getScalarSizeInBits()) 14980 Mul = Mul->getOperand(0); 14981 if (Mul->getOpcode() != ISD::MUL) 14982 return false; 14983 SDValue ExtA = Mul->getOperand(0); 14984 SDValue ExtB = Mul->getOperand(1); 14985 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 14986 return false; 14987 A = ExtA->getOperand(0); 14988 B = ExtB->getOperand(0); 14989 if (A.getValueType() == B.getValueType() && 14990 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14991 return true; 14992 return false; 14993 }; 14994 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 14995 SDValue &A, SDValue &B, SDValue &Mask) { 14996 // Same as the pattern above with a select for the zero predicated lanes 14997 // ExtA = sext/zext A 14998 // ExtB = sext/zext B 14999 // Mul = mul ExtA, ExtB 15000 // N0 = select Mask, Mul, 0 15001 // vecreduce.add N0 15002 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT || 15003 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode())) 15004 return false; 15005 Mask = N0->getOperand(0); 15006 SDValue Mul = N0->getOperand(1); 15007 if (Mul->getOpcode() == ExtendCode && 15008 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >= 15009 ResVT.getScalarSizeInBits()) 15010 Mul = Mul->getOperand(0); 15011 if (Mul->getOpcode() != ISD::MUL) 15012 return false; 15013 SDValue ExtA = Mul->getOperand(0); 15014 SDValue ExtB = Mul->getOperand(1); 15015 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 15016 return false; 15017 A = ExtA->getOperand(0); 15018 B = ExtB->getOperand(0); 15019 if (A.getValueType() == B.getValueType() && 15020 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 15021 return true; 15022 return false; 15023 }; 15024 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) { 15025 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops); 15026 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node, 15027 SDValue(Node.getNode(), 1)); 15028 }; 15029 15030 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8})) 15031 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A); 15032 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8})) 15033 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A); 15034 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32})) 15035 return Create64bitNode(ARMISD::VADDLVs, {A}); 15036 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32})) 15037 return Create64bitNode(ARMISD::VADDLVu, {A}); 15038 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8})) 15039 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15040 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A)); 15041 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8})) 15042 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15043 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A)); 15044 15045 SDValue Mask; 15046 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask)) 15047 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask); 15048 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask)) 15049 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask); 15050 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask)) 15051 return Create64bitNode(ARMISD::VADDLVps, {A, Mask}); 15052 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask)) 15053 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask}); 15054 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask)) 15055 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15056 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask)); 15057 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask)) 15058 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15059 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask)); 15060 15061 SDValue A, B; 15062 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 15063 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B); 15064 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 15065 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B); 15066 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B)) 15067 return Create64bitNode(ARMISD::VMLALVs, {A, B}); 15068 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B)) 15069 return Create64bitNode(ARMISD::VMLALVu, {A, B}); 15070 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B)) 15071 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15072 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B)); 15073 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B)) 15074 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15075 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B)); 15076 15077 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask)) 15078 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask); 15079 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask)) 15080 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask); 15081 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask)) 15082 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask}); 15083 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask)) 15084 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask}); 15085 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask)) 15086 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15087 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask)); 15088 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask)) 15089 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15090 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask)); 15091 15092 // Some complications. We can get a case where the two inputs of the mul are 15093 // the same, then the output sext will have been helpfully converted to a 15094 // zext. Turn it back. 15095 SDValue Op = N0; 15096 if (Op->getOpcode() == ISD::VSELECT) 15097 Op = Op->getOperand(1); 15098 if (Op->getOpcode() == ISD::ZERO_EXTEND && 15099 Op->getOperand(0)->getOpcode() == ISD::MUL) { 15100 SDValue Mul = Op->getOperand(0); 15101 if (Mul->getOperand(0) == Mul->getOperand(1) && 15102 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) { 15103 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul); 15104 if (Op != N0) 15105 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0), 15106 N0->getOperand(0), Ext, N0->getOperand(2)); 15107 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext); 15108 } 15109 } 15110 15111 return SDValue(); 15112 } 15113 15114 static SDValue PerformVMOVNCombine(SDNode *N, 15115 TargetLowering::DAGCombinerInfo &DCI) { 15116 SDValue Op0 = N->getOperand(0); 15117 SDValue Op1 = N->getOperand(1); 15118 unsigned IsTop = N->getConstantOperandVal(2); 15119 15120 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b) 15121 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b) 15122 if ((Op1->getOpcode() == ARMISD::VQMOVNs || 15123 Op1->getOpcode() == ARMISD::VQMOVNu) && 15124 Op1->getConstantOperandVal(2) == 0) 15125 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0), 15126 Op0, Op1->getOperand(1), N->getOperand(2)); 15127 15128 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from 15129 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting 15130 // into the top or bottom lanes. 15131 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 15132 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1)); 15133 APInt Op0DemandedElts = 15134 IsTop ? Op1DemandedElts 15135 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1)); 15136 15137 APInt KnownUndef, KnownZero; 15138 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 15139 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef, 15140 KnownZero, DCI)) 15141 return SDValue(N, 0); 15142 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef, 15143 KnownZero, DCI)) 15144 return SDValue(N, 0); 15145 15146 return SDValue(); 15147 } 15148 15149 static SDValue PerformVQMOVNCombine(SDNode *N, 15150 TargetLowering::DAGCombinerInfo &DCI) { 15151 SDValue Op0 = N->getOperand(0); 15152 unsigned IsTop = N->getConstantOperandVal(2); 15153 15154 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 15155 APInt Op0DemandedElts = 15156 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1) 15157 : APInt::getHighBitsSet(2, 1)); 15158 15159 APInt KnownUndef, KnownZero; 15160 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 15161 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef, 15162 KnownZero, DCI)) 15163 return SDValue(N, 0); 15164 return SDValue(); 15165 } 15166 15167 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) { 15168 SDLoc DL(N); 15169 SDValue Op0 = N->getOperand(0); 15170 SDValue Op1 = N->getOperand(1); 15171 15172 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from 15173 // uses of the intrinsics. 15174 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 15175 int ShiftAmt = C->getSExtValue(); 15176 if (ShiftAmt == 0) { 15177 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL); 15178 DAG.ReplaceAllUsesWith(N, Merge.getNode()); 15179 return SDValue(); 15180 } 15181 15182 if (ShiftAmt >= -32 && ShiftAmt < 0) { 15183 unsigned NewOpcode = 15184 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL; 15185 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1, 15186 DAG.getConstant(-ShiftAmt, DL, MVT::i32)); 15187 DAG.ReplaceAllUsesWith(N, NewShift.getNode()); 15188 return NewShift; 15189 } 15190 } 15191 15192 return SDValue(); 15193 } 15194 15195 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 15196 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N, 15197 DAGCombinerInfo &DCI) const { 15198 SelectionDAG &DAG = DCI.DAG; 15199 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15200 switch (IntNo) { 15201 default: 15202 // Don't do anything for most intrinsics. 15203 break; 15204 15205 // Vector shifts: check for immediate versions and lower them. 15206 // Note: This is done during DAG combining instead of DAG legalizing because 15207 // the build_vectors for 64-bit vector element shift counts are generally 15208 // not legal, and it is hard to see their values after they get legalized to 15209 // loads from a constant pool. 15210 case Intrinsic::arm_neon_vshifts: 15211 case Intrinsic::arm_neon_vshiftu: 15212 case Intrinsic::arm_neon_vrshifts: 15213 case Intrinsic::arm_neon_vrshiftu: 15214 case Intrinsic::arm_neon_vrshiftn: 15215 case Intrinsic::arm_neon_vqshifts: 15216 case Intrinsic::arm_neon_vqshiftu: 15217 case Intrinsic::arm_neon_vqshiftsu: 15218 case Intrinsic::arm_neon_vqshiftns: 15219 case Intrinsic::arm_neon_vqshiftnu: 15220 case Intrinsic::arm_neon_vqshiftnsu: 15221 case Intrinsic::arm_neon_vqrshiftns: 15222 case Intrinsic::arm_neon_vqrshiftnu: 15223 case Intrinsic::arm_neon_vqrshiftnsu: { 15224 EVT VT = N->getOperand(1).getValueType(); 15225 int64_t Cnt; 15226 unsigned VShiftOpc = 0; 15227 15228 switch (IntNo) { 15229 case Intrinsic::arm_neon_vshifts: 15230 case Intrinsic::arm_neon_vshiftu: 15231 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 15232 VShiftOpc = ARMISD::VSHLIMM; 15233 break; 15234 } 15235 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 15236 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 15237 : ARMISD::VSHRuIMM); 15238 break; 15239 } 15240 return SDValue(); 15241 15242 case Intrinsic::arm_neon_vrshifts: 15243 case Intrinsic::arm_neon_vrshiftu: 15244 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 15245 break; 15246 return SDValue(); 15247 15248 case Intrinsic::arm_neon_vqshifts: 15249 case Intrinsic::arm_neon_vqshiftu: 15250 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 15251 break; 15252 return SDValue(); 15253 15254 case Intrinsic::arm_neon_vqshiftsu: 15255 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 15256 break; 15257 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 15258 15259 case Intrinsic::arm_neon_vrshiftn: 15260 case Intrinsic::arm_neon_vqshiftns: 15261 case Intrinsic::arm_neon_vqshiftnu: 15262 case Intrinsic::arm_neon_vqshiftnsu: 15263 case Intrinsic::arm_neon_vqrshiftns: 15264 case Intrinsic::arm_neon_vqrshiftnu: 15265 case Intrinsic::arm_neon_vqrshiftnsu: 15266 // Narrowing shifts require an immediate right shift. 15267 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 15268 break; 15269 llvm_unreachable("invalid shift count for narrowing vector shift " 15270 "intrinsic"); 15271 15272 default: 15273 llvm_unreachable("unhandled vector shift"); 15274 } 15275 15276 switch (IntNo) { 15277 case Intrinsic::arm_neon_vshifts: 15278 case Intrinsic::arm_neon_vshiftu: 15279 // Opcode already set above. 15280 break; 15281 case Intrinsic::arm_neon_vrshifts: 15282 VShiftOpc = ARMISD::VRSHRsIMM; 15283 break; 15284 case Intrinsic::arm_neon_vrshiftu: 15285 VShiftOpc = ARMISD::VRSHRuIMM; 15286 break; 15287 case Intrinsic::arm_neon_vrshiftn: 15288 VShiftOpc = ARMISD::VRSHRNIMM; 15289 break; 15290 case Intrinsic::arm_neon_vqshifts: 15291 VShiftOpc = ARMISD::VQSHLsIMM; 15292 break; 15293 case Intrinsic::arm_neon_vqshiftu: 15294 VShiftOpc = ARMISD::VQSHLuIMM; 15295 break; 15296 case Intrinsic::arm_neon_vqshiftsu: 15297 VShiftOpc = ARMISD::VQSHLsuIMM; 15298 break; 15299 case Intrinsic::arm_neon_vqshiftns: 15300 VShiftOpc = ARMISD::VQSHRNsIMM; 15301 break; 15302 case Intrinsic::arm_neon_vqshiftnu: 15303 VShiftOpc = ARMISD::VQSHRNuIMM; 15304 break; 15305 case Intrinsic::arm_neon_vqshiftnsu: 15306 VShiftOpc = ARMISD::VQSHRNsuIMM; 15307 break; 15308 case Intrinsic::arm_neon_vqrshiftns: 15309 VShiftOpc = ARMISD::VQRSHRNsIMM; 15310 break; 15311 case Intrinsic::arm_neon_vqrshiftnu: 15312 VShiftOpc = ARMISD::VQRSHRNuIMM; 15313 break; 15314 case Intrinsic::arm_neon_vqrshiftnsu: 15315 VShiftOpc = ARMISD::VQRSHRNsuIMM; 15316 break; 15317 } 15318 15319 SDLoc dl(N); 15320 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 15321 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 15322 } 15323 15324 case Intrinsic::arm_neon_vshiftins: { 15325 EVT VT = N->getOperand(1).getValueType(); 15326 int64_t Cnt; 15327 unsigned VShiftOpc = 0; 15328 15329 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 15330 VShiftOpc = ARMISD::VSLIIMM; 15331 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 15332 VShiftOpc = ARMISD::VSRIIMM; 15333 else { 15334 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 15335 } 15336 15337 SDLoc dl(N); 15338 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 15339 N->getOperand(1), N->getOperand(2), 15340 DAG.getConstant(Cnt, dl, MVT::i32)); 15341 } 15342 15343 case Intrinsic::arm_neon_vqrshifts: 15344 case Intrinsic::arm_neon_vqrshiftu: 15345 // No immediate versions of these to check for. 15346 break; 15347 15348 case Intrinsic::arm_mve_vqdmlah: 15349 case Intrinsic::arm_mve_vqdmlash: 15350 case Intrinsic::arm_mve_vqrdmlah: 15351 case Intrinsic::arm_mve_vqrdmlash: 15352 case Intrinsic::arm_mve_vmla_n_predicated: 15353 case Intrinsic::arm_mve_vmlas_n_predicated: 15354 case Intrinsic::arm_mve_vqdmlah_predicated: 15355 case Intrinsic::arm_mve_vqdmlash_predicated: 15356 case Intrinsic::arm_mve_vqrdmlah_predicated: 15357 case Intrinsic::arm_mve_vqrdmlash_predicated: { 15358 // These intrinsics all take an i32 scalar operand which is narrowed to the 15359 // size of a single lane of the vector type they return. So we don't need 15360 // any bits of that operand above that point, which allows us to eliminate 15361 // uxth/sxth. 15362 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits(); 15363 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 15364 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI)) 15365 return SDValue(); 15366 break; 15367 } 15368 15369 case Intrinsic::arm_mve_minv: 15370 case Intrinsic::arm_mve_maxv: 15371 case Intrinsic::arm_mve_minav: 15372 case Intrinsic::arm_mve_maxav: 15373 case Intrinsic::arm_mve_minv_predicated: 15374 case Intrinsic::arm_mve_maxv_predicated: 15375 case Intrinsic::arm_mve_minav_predicated: 15376 case Intrinsic::arm_mve_maxav_predicated: { 15377 // These intrinsics all take an i32 scalar operand which is narrowed to the 15378 // size of a single lane of the vector type they take as the other input. 15379 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits(); 15380 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 15381 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 15382 return SDValue(); 15383 break; 15384 } 15385 15386 case Intrinsic::arm_mve_addv: { 15387 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node, 15388 // which allow PerformADDVecReduce to turn it into VADDLV when possible. 15389 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15390 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs; 15391 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1)); 15392 } 15393 15394 case Intrinsic::arm_mve_addlv: 15395 case Intrinsic::arm_mve_addlv_predicated: { 15396 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR 15397 // which recombines the two outputs into an i64 15398 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15399 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ? 15400 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) : 15401 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps); 15402 15403 SmallVector<SDValue, 4> Ops; 15404 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++) 15405 if (i != 2) // skip the unsigned flag 15406 Ops.push_back(N->getOperand(i)); 15407 15408 SDLoc dl(N); 15409 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops); 15410 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0), 15411 val.getValue(1)); 15412 } 15413 } 15414 15415 return SDValue(); 15416 } 15417 15418 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 15419 /// lowers them. As with the vector shift intrinsics, this is done during DAG 15420 /// combining instead of DAG legalizing because the build_vectors for 64-bit 15421 /// vector element shift counts are generally not legal, and it is hard to see 15422 /// their values after they get legalized to loads from a constant pool. 15423 static SDValue PerformShiftCombine(SDNode *N, 15424 TargetLowering::DAGCombinerInfo &DCI, 15425 const ARMSubtarget *ST) { 15426 SelectionDAG &DAG = DCI.DAG; 15427 EVT VT = N->getValueType(0); 15428 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 15429 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 15430 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 15431 SDValue N1 = N->getOperand(1); 15432 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 15433 SDValue N0 = N->getOperand(0); 15434 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 15435 DAG.MaskedValueIsZero(N0.getOperand(0), 15436 APInt::getHighBitsSet(32, 16))) 15437 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 15438 } 15439 } 15440 15441 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 15442 N->getOperand(0)->getOpcode() == ISD::AND && 15443 N->getOperand(0)->hasOneUse()) { 15444 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 15445 return SDValue(); 15446 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 15447 // usually show up because instcombine prefers to canonicalize it to 15448 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 15449 // out of GEP lowering in some cases. 15450 SDValue N0 = N->getOperand(0); 15451 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15452 if (!ShiftAmtNode) 15453 return SDValue(); 15454 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 15455 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 15456 if (!AndMaskNode) 15457 return SDValue(); 15458 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 15459 // Don't transform uxtb/uxth. 15460 if (AndMask == 255 || AndMask == 65535) 15461 return SDValue(); 15462 if (isMask_32(AndMask)) { 15463 uint32_t MaskedBits = countLeadingZeros(AndMask); 15464 if (MaskedBits > ShiftAmt) { 15465 SDLoc DL(N); 15466 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 15467 DAG.getConstant(MaskedBits, DL, MVT::i32)); 15468 return DAG.getNode( 15469 ISD::SRL, DL, MVT::i32, SHL, 15470 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 15471 } 15472 } 15473 } 15474 15475 // Nothing to be done for scalar shifts. 15476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15477 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 15478 return SDValue(); 15479 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 15480 return SDValue(); 15481 15482 int64_t Cnt; 15483 15484 switch (N->getOpcode()) { 15485 default: llvm_unreachable("unexpected shift opcode"); 15486 15487 case ISD::SHL: 15488 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 15489 SDLoc dl(N); 15490 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 15491 DAG.getConstant(Cnt, dl, MVT::i32)); 15492 } 15493 break; 15494 15495 case ISD::SRA: 15496 case ISD::SRL: 15497 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 15498 unsigned VShiftOpc = 15499 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 15500 SDLoc dl(N); 15501 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 15502 DAG.getConstant(Cnt, dl, MVT::i32)); 15503 } 15504 } 15505 return SDValue(); 15506 } 15507 15508 // Look for a sign/zero/fpextend extend of a larger than legal load. This can be 15509 // split into multiple extending loads, which are simpler to deal with than an 15510 // arbitrary extend. For fp extends we use an integer extending load and a VCVTL 15511 // to convert the type to an f32. 15512 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) { 15513 SDValue N0 = N->getOperand(0); 15514 if (N0.getOpcode() != ISD::LOAD) 15515 return SDValue(); 15516 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode()); 15517 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() || 15518 LD->getExtensionType() != ISD::NON_EXTLOAD) 15519 return SDValue(); 15520 EVT FromVT = LD->getValueType(0); 15521 EVT ToVT = N->getValueType(0); 15522 if (!ToVT.isVector()) 15523 return SDValue(); 15524 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 15525 EVT ToEltVT = ToVT.getVectorElementType(); 15526 EVT FromEltVT = FromVT.getVectorElementType(); 15527 15528 unsigned NumElements = 0; 15529 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8)) 15530 NumElements = 4; 15531 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8) 15532 NumElements = 8; 15533 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16) 15534 NumElements = 4; 15535 if (NumElements == 0 || 15536 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) || 15537 FromVT.getVectorNumElements() % NumElements != 0 || 15538 !isPowerOf2_32(NumElements)) 15539 return SDValue(); 15540 15541 LLVMContext &C = *DAG.getContext(); 15542 SDLoc DL(LD); 15543 // Details about the old load 15544 SDValue Ch = LD->getChain(); 15545 SDValue BasePtr = LD->getBasePtr(); 15546 Align Alignment = LD->getOriginalAlign(); 15547 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 15548 AAMDNodes AAInfo = LD->getAAInfo(); 15549 15550 ISD::LoadExtType NewExtType = 15551 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 15552 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType()); 15553 EVT NewFromVT = EVT::getVectorVT( 15554 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements); 15555 EVT NewToVT = EVT::getVectorVT( 15556 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements); 15557 15558 SmallVector<SDValue, 4> Loads; 15559 SmallVector<SDValue, 4> Chains; 15560 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 15561 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8; 15562 SDValue NewPtr = 15563 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset)); 15564 15565 SDValue NewLoad = 15566 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset, 15567 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT, 15568 Alignment, MMOFlags, AAInfo); 15569 Loads.push_back(NewLoad); 15570 Chains.push_back(SDValue(NewLoad.getNode(), 1)); 15571 } 15572 15573 // Float truncs need to extended with VCVTB's into their floating point types. 15574 if (FromEltVT == MVT::f16) { 15575 SmallVector<SDValue, 4> Extends; 15576 15577 for (unsigned i = 0; i < Loads.size(); i++) { 15578 SDValue LoadBC = 15579 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]); 15580 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC, 15581 DAG.getConstant(0, DL, MVT::i32)); 15582 Extends.push_back(FPExt); 15583 } 15584 15585 Loads = Extends; 15586 } 15587 15588 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 15589 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain); 15590 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads); 15591 } 15592 15593 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 15594 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 15595 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 15596 const ARMSubtarget *ST) { 15597 SDValue N0 = N->getOperand(0); 15598 15599 // Check for sign- and zero-extensions of vector extract operations of 8- and 15600 // 16-bit vector elements. NEON and MVE support these directly. They are 15601 // handled during DAG combining because type legalization will promote them 15602 // to 32-bit types and it is messy to recognize the operations after that. 15603 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) && 15604 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 15605 SDValue Vec = N0.getOperand(0); 15606 SDValue Lane = N0.getOperand(1); 15607 EVT VT = N->getValueType(0); 15608 EVT EltVT = N0.getValueType(); 15609 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15610 15611 if (VT == MVT::i32 && 15612 (EltVT == MVT::i8 || EltVT == MVT::i16) && 15613 TLI.isTypeLegal(Vec.getValueType()) && 15614 isa<ConstantSDNode>(Lane)) { 15615 15616 unsigned Opc = 0; 15617 switch (N->getOpcode()) { 15618 default: llvm_unreachable("unexpected opcode"); 15619 case ISD::SIGN_EXTEND: 15620 Opc = ARMISD::VGETLANEs; 15621 break; 15622 case ISD::ZERO_EXTEND: 15623 case ISD::ANY_EXTEND: 15624 Opc = ARMISD::VGETLANEu; 15625 break; 15626 } 15627 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 15628 } 15629 } 15630 15631 if (ST->hasMVEIntegerOps()) 15632 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 15633 return NewLoad; 15634 15635 return SDValue(); 15636 } 15637 15638 static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG, 15639 const ARMSubtarget *ST) { 15640 if (ST->hasMVEFloatOps()) 15641 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 15642 return NewLoad; 15643 15644 return SDValue(); 15645 } 15646 15647 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating 15648 /// saturates. 15649 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG, 15650 const ARMSubtarget *ST) { 15651 EVT VT = N->getValueType(0); 15652 SDValue N0 = N->getOperand(0); 15653 if (!ST->hasMVEIntegerOps()) 15654 return SDValue(); 15655 15656 if (SDValue V = PerformVQDMULHCombine(N, DAG)) 15657 return V; 15658 15659 if (VT != MVT::v4i32 && VT != MVT::v8i16) 15660 return SDValue(); 15661 15662 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) { 15663 // Check one is a smin and the other is a smax 15664 if (Min->getOpcode() != ISD::SMIN) 15665 std::swap(Min, Max); 15666 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX) 15667 return false; 15668 15669 APInt SaturateC; 15670 if (VT == MVT::v4i32) 15671 SaturateC = APInt(32, (1 << 15) - 1, true); 15672 else //if (VT == MVT::v8i16) 15673 SaturateC = APInt(16, (1 << 7) - 1, true); 15674 15675 APInt MinC, MaxC; 15676 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) || 15677 MinC != SaturateC) 15678 return false; 15679 if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) || 15680 MaxC != ~SaturateC) 15681 return false; 15682 return true; 15683 }; 15684 15685 if (IsSignedSaturate(N, N0.getNode())) { 15686 SDLoc DL(N); 15687 MVT ExtVT, HalfVT; 15688 if (VT == MVT::v4i32) { 15689 HalfVT = MVT::v8i16; 15690 ExtVT = MVT::v4i16; 15691 } else { // if (VT == MVT::v8i16) 15692 HalfVT = MVT::v16i8; 15693 ExtVT = MVT::v8i8; 15694 } 15695 15696 // Create a VQMOVNB with undef top lanes, then signed extended into the top 15697 // half. That extend will hopefully be removed if only the bottom bits are 15698 // demanded (though a truncating store, for example). 15699 SDValue VQMOVN = 15700 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT), 15701 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32)); 15702 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN); 15703 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast, 15704 DAG.getValueType(ExtVT)); 15705 } 15706 15707 auto IsUnsignedSaturate = [&](SDNode *Min) { 15708 // For unsigned, we just need to check for <= 0xffff 15709 if (Min->getOpcode() != ISD::UMIN) 15710 return false; 15711 15712 APInt SaturateC; 15713 if (VT == MVT::v4i32) 15714 SaturateC = APInt(32, (1 << 16) - 1, true); 15715 else //if (VT == MVT::v8i16) 15716 SaturateC = APInt(16, (1 << 8) - 1, true); 15717 15718 APInt MinC; 15719 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) || 15720 MinC != SaturateC) 15721 return false; 15722 return true; 15723 }; 15724 15725 if (IsUnsignedSaturate(N)) { 15726 SDLoc DL(N); 15727 MVT HalfVT; 15728 unsigned ExtConst; 15729 if (VT == MVT::v4i32) { 15730 HalfVT = MVT::v8i16; 15731 ExtConst = 0x0000FFFF; 15732 } else { //if (VT == MVT::v8i16) 15733 HalfVT = MVT::v16i8; 15734 ExtConst = 0x00FF; 15735 } 15736 15737 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with 15738 // an AND. That extend will hopefully be removed if only the bottom bits are 15739 // demanded (though a truncating store, for example). 15740 SDValue VQMOVN = 15741 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0, 15742 DAG.getConstant(0, DL, MVT::i32)); 15743 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN); 15744 return DAG.getNode(ISD::AND, DL, VT, Bitcast, 15745 DAG.getConstant(ExtConst, DL, VT)); 15746 } 15747 15748 return SDValue(); 15749 } 15750 15751 static const APInt *isPowerOf2Constant(SDValue V) { 15752 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 15753 if (!C) 15754 return nullptr; 15755 const APInt *CV = &C->getAPIntValue(); 15756 return CV->isPowerOf2() ? CV : nullptr; 15757 } 15758 15759 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 15760 // If we have a CMOV, OR and AND combination such as: 15761 // if (x & CN) 15762 // y |= CM; 15763 // 15764 // And: 15765 // * CN is a single bit; 15766 // * All bits covered by CM are known zero in y 15767 // 15768 // Then we can convert this into a sequence of BFI instructions. This will 15769 // always be a win if CM is a single bit, will always be no worse than the 15770 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 15771 // three bits (due to the extra IT instruction). 15772 15773 SDValue Op0 = CMOV->getOperand(0); 15774 SDValue Op1 = CMOV->getOperand(1); 15775 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 15776 auto CC = CCNode->getAPIntValue().getLimitedValue(); 15777 SDValue CmpZ = CMOV->getOperand(4); 15778 15779 // The compare must be against zero. 15780 if (!isNullConstant(CmpZ->getOperand(1))) 15781 return SDValue(); 15782 15783 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 15784 SDValue And = CmpZ->getOperand(0); 15785 if (And->getOpcode() != ISD::AND) 15786 return SDValue(); 15787 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 15788 if (!AndC) 15789 return SDValue(); 15790 SDValue X = And->getOperand(0); 15791 15792 if (CC == ARMCC::EQ) { 15793 // We're performing an "equal to zero" compare. Swap the operands so we 15794 // canonicalize on a "not equal to zero" compare. 15795 std::swap(Op0, Op1); 15796 } else { 15797 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 15798 } 15799 15800 if (Op1->getOpcode() != ISD::OR) 15801 return SDValue(); 15802 15803 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 15804 if (!OrC) 15805 return SDValue(); 15806 SDValue Y = Op1->getOperand(0); 15807 15808 if (Op0 != Y) 15809 return SDValue(); 15810 15811 // Now, is it profitable to continue? 15812 APInt OrCI = OrC->getAPIntValue(); 15813 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 15814 if (OrCI.countPopulation() > Heuristic) 15815 return SDValue(); 15816 15817 // Lastly, can we determine that the bits defined by OrCI 15818 // are zero in Y? 15819 KnownBits Known = DAG.computeKnownBits(Y); 15820 if ((OrCI & Known.Zero) != OrCI) 15821 return SDValue(); 15822 15823 // OK, we can do the combine. 15824 SDValue V = Y; 15825 SDLoc dl(X); 15826 EVT VT = X.getValueType(); 15827 unsigned BitInX = AndC->logBase2(); 15828 15829 if (BitInX != 0) { 15830 // We must shift X first. 15831 X = DAG.getNode(ISD::SRL, dl, VT, X, 15832 DAG.getConstant(BitInX, dl, VT)); 15833 } 15834 15835 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 15836 BitInY < NumActiveBits; ++BitInY) { 15837 if (OrCI[BitInY] == 0) 15838 continue; 15839 APInt Mask(VT.getSizeInBits(), 0); 15840 Mask.setBit(BitInY); 15841 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 15842 // Confusingly, the operand is an *inverted* mask. 15843 DAG.getConstant(~Mask, dl, VT)); 15844 } 15845 15846 return V; 15847 } 15848 15849 // Given N, the value controlling the conditional branch, search for the loop 15850 // intrinsic, returning it, along with how the value is used. We need to handle 15851 // patterns such as the following: 15852 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 15853 // (brcond (setcc (loop.decrement), 0, eq), exit) 15854 // (brcond (setcc (loop.decrement), 0, ne), header) 15855 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 15856 bool &Negate) { 15857 switch (N->getOpcode()) { 15858 default: 15859 break; 15860 case ISD::XOR: { 15861 if (!isa<ConstantSDNode>(N.getOperand(1))) 15862 return SDValue(); 15863 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 15864 return SDValue(); 15865 Negate = !Negate; 15866 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 15867 } 15868 case ISD::SETCC: { 15869 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 15870 if (!Const) 15871 return SDValue(); 15872 if (Const->isNullValue()) 15873 Imm = 0; 15874 else if (Const->isOne()) 15875 Imm = 1; 15876 else 15877 return SDValue(); 15878 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 15879 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 15880 } 15881 case ISD::INTRINSIC_W_CHAIN: { 15882 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 15883 if (IntOp != Intrinsic::test_set_loop_iterations && 15884 IntOp != Intrinsic::loop_decrement_reg) 15885 return SDValue(); 15886 return N; 15887 } 15888 } 15889 return SDValue(); 15890 } 15891 15892 static SDValue PerformHWLoopCombine(SDNode *N, 15893 TargetLowering::DAGCombinerInfo &DCI, 15894 const ARMSubtarget *ST) { 15895 15896 // The hwloop intrinsics that we're interested are used for control-flow, 15897 // either for entering or exiting the loop: 15898 // - test.set.loop.iterations will test whether its operand is zero. If it 15899 // is zero, the proceeding branch should not enter the loop. 15900 // - loop.decrement.reg also tests whether its operand is zero. If it is 15901 // zero, the proceeding branch should not branch back to the beginning of 15902 // the loop. 15903 // So here, we need to check that how the brcond is using the result of each 15904 // of the intrinsics to ensure that we're branching to the right place at the 15905 // right time. 15906 15907 ISD::CondCode CC; 15908 SDValue Cond; 15909 int Imm = 1; 15910 bool Negate = false; 15911 SDValue Chain = N->getOperand(0); 15912 SDValue Dest; 15913 15914 if (N->getOpcode() == ISD::BRCOND) { 15915 CC = ISD::SETEQ; 15916 Cond = N->getOperand(1); 15917 Dest = N->getOperand(2); 15918 } else { 15919 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 15920 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15921 Cond = N->getOperand(2); 15922 Dest = N->getOperand(4); 15923 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 15924 if (!Const->isOne() && !Const->isNullValue()) 15925 return SDValue(); 15926 Imm = Const->getZExtValue(); 15927 } else 15928 return SDValue(); 15929 } 15930 15931 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 15932 if (!Int) 15933 return SDValue(); 15934 15935 if (Negate) 15936 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32); 15937 15938 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 15939 return (CC == ISD::SETEQ && Imm == 0) || 15940 (CC == ISD::SETNE && Imm == 1) || 15941 (CC == ISD::SETLT && Imm == 1) || 15942 (CC == ISD::SETULT && Imm == 1); 15943 }; 15944 15945 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 15946 return (CC == ISD::SETEQ && Imm == 1) || 15947 (CC == ISD::SETNE && Imm == 0) || 15948 (CC == ISD::SETGT && Imm == 0) || 15949 (CC == ISD::SETUGT && Imm == 0) || 15950 (CC == ISD::SETGE && Imm == 1) || 15951 (CC == ISD::SETUGE && Imm == 1); 15952 }; 15953 15954 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 15955 "unsupported condition"); 15956 15957 SDLoc dl(Int); 15958 SelectionDAG &DAG = DCI.DAG; 15959 SDValue Elements = Int.getOperand(2); 15960 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 15961 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 15962 && "expected single br user"); 15963 SDNode *Br = *N->use_begin(); 15964 SDValue OtherTarget = Br->getOperand(1); 15965 15966 // Update the unconditional branch to branch to the given Dest. 15967 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 15968 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 15969 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 15970 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 15971 }; 15972 15973 if (IntOp == Intrinsic::test_set_loop_iterations) { 15974 SDValue Res; 15975 // We expect this 'instruction' to branch when the counter is zero. 15976 if (IsTrueIfZero(CC, Imm)) { 15977 SDValue Ops[] = { Chain, Elements, Dest }; 15978 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 15979 } else { 15980 // The logic is the reverse of what we need for WLS, so find the other 15981 // basic block target: the target of the proceeding br. 15982 UpdateUncondBr(Br, Dest, DAG); 15983 15984 SDValue Ops[] = { Chain, Elements, OtherTarget }; 15985 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 15986 } 15987 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 15988 return Res; 15989 } else { 15990 SDValue Size = DAG.getTargetConstant( 15991 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 15992 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 15993 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 15994 DAG.getVTList(MVT::i32, MVT::Other), Args); 15995 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 15996 15997 // We expect this instruction to branch when the count is not zero. 15998 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 15999 16000 // Update the unconditional branch to target the loop preheader if we've 16001 // found the condition has been reversed. 16002 if (Target == OtherTarget) 16003 UpdateUncondBr(Br, Dest, DAG); 16004 16005 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 16006 SDValue(LoopDec.getNode(), 1), Chain); 16007 16008 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 16009 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 16010 } 16011 return SDValue(); 16012 } 16013 16014 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 16015 SDValue 16016 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 16017 SDValue Cmp = N->getOperand(4); 16018 if (Cmp.getOpcode() != ARMISD::CMPZ) 16019 // Only looking at NE cases. 16020 return SDValue(); 16021 16022 EVT VT = N->getValueType(0); 16023 SDLoc dl(N); 16024 SDValue LHS = Cmp.getOperand(0); 16025 SDValue RHS = Cmp.getOperand(1); 16026 SDValue Chain = N->getOperand(0); 16027 SDValue BB = N->getOperand(1); 16028 SDValue ARMcc = N->getOperand(2); 16029 ARMCC::CondCodes CC = 16030 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 16031 16032 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 16033 // -> (brcond Chain BB CC CPSR Cmp) 16034 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 16035 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 16036 LHS->getOperand(0)->hasOneUse()) { 16037 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 16038 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 16039 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 16040 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 16041 if ((LHS00C && LHS00C->getZExtValue() == 0) && 16042 (LHS01C && LHS01C->getZExtValue() == 1) && 16043 (LHS1C && LHS1C->getZExtValue() == 1) && 16044 (RHSC && RHSC->getZExtValue() == 0)) { 16045 return DAG.getNode( 16046 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 16047 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 16048 } 16049 } 16050 16051 return SDValue(); 16052 } 16053 16054 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 16055 SDValue 16056 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 16057 SDValue Cmp = N->getOperand(4); 16058 if (Cmp.getOpcode() != ARMISD::CMPZ) 16059 // Only looking at EQ and NE cases. 16060 return SDValue(); 16061 16062 EVT VT = N->getValueType(0); 16063 SDLoc dl(N); 16064 SDValue LHS = Cmp.getOperand(0); 16065 SDValue RHS = Cmp.getOperand(1); 16066 SDValue FalseVal = N->getOperand(0); 16067 SDValue TrueVal = N->getOperand(1); 16068 SDValue ARMcc = N->getOperand(2); 16069 ARMCC::CondCodes CC = 16070 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 16071 16072 // BFI is only available on V6T2+. 16073 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 16074 SDValue R = PerformCMOVToBFICombine(N, DAG); 16075 if (R) 16076 return R; 16077 } 16078 16079 // Simplify 16080 // mov r1, r0 16081 // cmp r1, x 16082 // mov r0, y 16083 // moveq r0, x 16084 // to 16085 // cmp r0, x 16086 // movne r0, y 16087 // 16088 // mov r1, r0 16089 // cmp r1, x 16090 // mov r0, x 16091 // movne r0, y 16092 // to 16093 // cmp r0, x 16094 // movne r0, y 16095 /// FIXME: Turn this into a target neutral optimization? 16096 SDValue Res; 16097 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 16098 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 16099 N->getOperand(3), Cmp); 16100 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 16101 SDValue ARMcc; 16102 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 16103 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 16104 N->getOperand(3), NewCmp); 16105 } 16106 16107 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 16108 // -> (cmov F T CC CPSR Cmp) 16109 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 16110 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 16111 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 16112 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 16113 if ((LHS0C && LHS0C->getZExtValue() == 0) && 16114 (LHS1C && LHS1C->getZExtValue() == 1) && 16115 (RHSC && RHSC->getZExtValue() == 0)) { 16116 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 16117 LHS->getOperand(2), LHS->getOperand(3), 16118 LHS->getOperand(4)); 16119 } 16120 } 16121 16122 if (!VT.isInteger()) 16123 return SDValue(); 16124 16125 // Materialize a boolean comparison for integers so we can avoid branching. 16126 if (isNullConstant(FalseVal)) { 16127 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 16128 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 16129 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 16130 // right 5 bits will make that 32 be 1, otherwise it will be 0. 16131 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 16132 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 16133 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 16134 DAG.getConstant(5, dl, MVT::i32)); 16135 } else { 16136 // CMOV 0, 1, ==, (CMPZ x, y) -> 16137 // (ADDCARRY (SUB x, y), t:0, t:1) 16138 // where t = (SUBCARRY 0, (SUB x, y), 0) 16139 // 16140 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 16141 // x != y. In other words, a carry C == 1 when x == y, C == 0 16142 // otherwise. 16143 // The final ADDCARRY computes 16144 // x - y + (0 - (x - y)) + C == C 16145 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 16146 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 16147 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 16148 // ISD::SUBCARRY returns a borrow but we want the carry here 16149 // actually. 16150 SDValue Carry = 16151 DAG.getNode(ISD::SUB, dl, MVT::i32, 16152 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 16153 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 16154 } 16155 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 16156 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 16157 // This seems pointless but will allow us to combine it further below. 16158 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 16159 SDValue Sub = 16160 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 16161 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 16162 Sub.getValue(1), SDValue()); 16163 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 16164 N->getOperand(3), CPSRGlue.getValue(1)); 16165 FalseVal = Sub; 16166 } 16167 } else if (isNullConstant(TrueVal)) { 16168 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 16169 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 16170 // This seems pointless but will allow us to combine it further below 16171 // Note that we change == for != as this is the dual for the case above. 16172 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 16173 SDValue Sub = 16174 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 16175 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 16176 Sub.getValue(1), SDValue()); 16177 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 16178 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 16179 N->getOperand(3), CPSRGlue.getValue(1)); 16180 FalseVal = Sub; 16181 } 16182 } 16183 16184 // On Thumb1, the DAG above may be further combined if z is a power of 2 16185 // (z == 2 ^ K). 16186 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 16187 // t1 = (USUBO (SUB x, y), 1) 16188 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 16189 // Result = if K != 0 then (SHL t2:0, K) else t2:0 16190 // 16191 // This also handles the special case of comparing against zero; it's 16192 // essentially, the same pattern, except there's no SUBS: 16193 // CMOV x, z, !=, (CMPZ x, 0) -> 16194 // t1 = (USUBO x, 1) 16195 // t2 = (SUBCARRY x, t1:0, t1:1) 16196 // Result = if K != 0 then (SHL t2:0, K) else t2:0 16197 const APInt *TrueConst; 16198 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 16199 ((FalseVal.getOpcode() == ARMISD::SUBS && 16200 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 16201 (FalseVal == LHS && isNullConstant(RHS))) && 16202 (TrueConst = isPowerOf2Constant(TrueVal))) { 16203 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 16204 unsigned ShiftAmount = TrueConst->logBase2(); 16205 if (ShiftAmount) 16206 TrueVal = DAG.getConstant(1, dl, VT); 16207 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 16208 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 16209 16210 if (ShiftAmount) 16211 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 16212 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 16213 } 16214 16215 if (Res.getNode()) { 16216 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 16217 // Capture demanded bits information that would be otherwise lost. 16218 if (Known.Zero == 0xfffffffe) 16219 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16220 DAG.getValueType(MVT::i1)); 16221 else if (Known.Zero == 0xffffff00) 16222 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16223 DAG.getValueType(MVT::i8)); 16224 else if (Known.Zero == 0xffff0000) 16225 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16226 DAG.getValueType(MVT::i16)); 16227 } 16228 16229 return Res; 16230 } 16231 16232 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG, 16233 const ARMSubtarget *ST) { 16234 SDValue Src = N->getOperand(0); 16235 EVT DstVT = N->getValueType(0); 16236 16237 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE. 16238 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) { 16239 EVT SrcVT = Src.getValueType(); 16240 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits()) 16241 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0)); 16242 } 16243 16244 // We may have a bitcast of something that has already had this bitcast 16245 // combine performed on it, so skip past any VECTOR_REG_CASTs. 16246 while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST) 16247 Src = Src.getOperand(0); 16248 16249 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that 16250 // would be generated is at least the width of the element type. 16251 EVT SrcVT = Src.getValueType(); 16252 if ((Src.getOpcode() == ARMISD::VMOVIMM || 16253 Src.getOpcode() == ARMISD::VMVNIMM || 16254 Src.getOpcode() == ARMISD::VMOVFPIMM) && 16255 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() && 16256 DAG.getDataLayout().isBigEndian()) 16257 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src); 16258 16259 return SDValue(); 16260 } 16261 16262 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 16263 DAGCombinerInfo &DCI) const { 16264 switch (N->getOpcode()) { 16265 default: break; 16266 case ISD::SELECT_CC: 16267 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget); 16268 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget); 16269 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 16270 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 16271 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 16272 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 16273 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget); 16274 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 16275 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 16276 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 16277 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 16278 case ISD::BRCOND: 16279 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 16280 case ARMISD::ADDC: 16281 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 16282 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 16283 case ARMISD::BFI: return PerformBFICombine(N, DCI); 16284 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 16285 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 16286 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI); 16287 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI); 16288 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget); 16289 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 16290 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 16291 case ISD::EXTRACT_VECTOR_ELT: return PerformExtractEltCombine(N, DCI); 16292 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 16293 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget); 16294 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 16295 case ISD::FP_TO_SINT: 16296 case ISD::FP_TO_UINT: 16297 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 16298 case ISD::FDIV: 16299 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 16300 case ISD::INTRINSIC_WO_CHAIN: 16301 return PerformIntrinsicCombine(N, DCI); 16302 case ISD::SHL: 16303 case ISD::SRA: 16304 case ISD::SRL: 16305 return PerformShiftCombine(N, DCI, Subtarget); 16306 case ISD::SIGN_EXTEND: 16307 case ISD::ZERO_EXTEND: 16308 case ISD::ANY_EXTEND: 16309 return PerformExtendCombine(N, DCI.DAG, Subtarget); 16310 case ISD::FP_EXTEND: 16311 return PerformFPExtendCombine(N, DCI.DAG, Subtarget); 16312 case ISD::SMIN: 16313 case ISD::UMIN: 16314 case ISD::SMAX: 16315 case ISD::UMAX: 16316 return PerformMinMaxCombine(N, DCI.DAG, Subtarget); 16317 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 16318 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 16319 case ISD::LOAD: return PerformLOADCombine(N, DCI); 16320 case ARMISD::VLD1DUP: 16321 case ARMISD::VLD2DUP: 16322 case ARMISD::VLD3DUP: 16323 case ARMISD::VLD4DUP: 16324 return PerformVLDCombine(N, DCI); 16325 case ARMISD::BUILD_VECTOR: 16326 return PerformARMBUILD_VECTORCombine(N, DCI); 16327 case ISD::BITCAST: 16328 return PerformBITCASTCombine(N, DCI.DAG, Subtarget); 16329 case ARMISD::PREDICATE_CAST: 16330 return PerformPREDICATE_CASTCombine(N, DCI); 16331 case ARMISD::VECTOR_REG_CAST: 16332 return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget); 16333 case ARMISD::VCMP: 16334 return PerformVCMPCombine(N, DCI, Subtarget); 16335 case ISD::VECREDUCE_ADD: 16336 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget); 16337 case ARMISD::VMOVN: 16338 return PerformVMOVNCombine(N, DCI); 16339 case ARMISD::VQMOVNs: 16340 case ARMISD::VQMOVNu: 16341 return PerformVQMOVNCombine(N, DCI); 16342 case ARMISD::ASRL: 16343 case ARMISD::LSRL: 16344 case ARMISD::LSLL: 16345 return PerformLongShiftCombine(N, DCI.DAG); 16346 case ARMISD::SMULWB: { 16347 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16348 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 16349 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 16350 return SDValue(); 16351 break; 16352 } 16353 case ARMISD::SMULWT: { 16354 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16355 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 16356 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 16357 return SDValue(); 16358 break; 16359 } 16360 case ARMISD::SMLALBB: 16361 case ARMISD::QADD16b: 16362 case ARMISD::QSUB16b: { 16363 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16364 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 16365 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16366 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16367 return SDValue(); 16368 break; 16369 } 16370 case ARMISD::SMLALBT: { 16371 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 16372 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 16373 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 16374 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 16375 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 16376 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 16377 return SDValue(); 16378 break; 16379 } 16380 case ARMISD::SMLALTB: { 16381 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 16382 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 16383 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 16384 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 16385 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 16386 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 16387 return SDValue(); 16388 break; 16389 } 16390 case ARMISD::SMLALTT: { 16391 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16392 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 16393 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16394 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16395 return SDValue(); 16396 break; 16397 } 16398 case ARMISD::QADD8b: 16399 case ARMISD::QSUB8b: { 16400 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16401 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8); 16402 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16403 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16404 return SDValue(); 16405 break; 16406 } 16407 case ISD::INTRINSIC_VOID: 16408 case ISD::INTRINSIC_W_CHAIN: 16409 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 16410 case Intrinsic::arm_neon_vld1: 16411 case Intrinsic::arm_neon_vld1x2: 16412 case Intrinsic::arm_neon_vld1x3: 16413 case Intrinsic::arm_neon_vld1x4: 16414 case Intrinsic::arm_neon_vld2: 16415 case Intrinsic::arm_neon_vld3: 16416 case Intrinsic::arm_neon_vld4: 16417 case Intrinsic::arm_neon_vld2lane: 16418 case Intrinsic::arm_neon_vld3lane: 16419 case Intrinsic::arm_neon_vld4lane: 16420 case Intrinsic::arm_neon_vld2dup: 16421 case Intrinsic::arm_neon_vld3dup: 16422 case Intrinsic::arm_neon_vld4dup: 16423 case Intrinsic::arm_neon_vst1: 16424 case Intrinsic::arm_neon_vst1x2: 16425 case Intrinsic::arm_neon_vst1x3: 16426 case Intrinsic::arm_neon_vst1x4: 16427 case Intrinsic::arm_neon_vst2: 16428 case Intrinsic::arm_neon_vst3: 16429 case Intrinsic::arm_neon_vst4: 16430 case Intrinsic::arm_neon_vst2lane: 16431 case Intrinsic::arm_neon_vst3lane: 16432 case Intrinsic::arm_neon_vst4lane: 16433 return PerformVLDCombine(N, DCI); 16434 case Intrinsic::arm_mve_vld2q: 16435 case Intrinsic::arm_mve_vld4q: 16436 case Intrinsic::arm_mve_vst2q: 16437 case Intrinsic::arm_mve_vst4q: 16438 return PerformMVEVLDCombine(N, DCI); 16439 default: break; 16440 } 16441 break; 16442 } 16443 return SDValue(); 16444 } 16445 16446 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 16447 EVT VT) const { 16448 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 16449 } 16450 16451 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 16452 unsigned Alignment, 16453 MachineMemOperand::Flags, 16454 bool *Fast) const { 16455 // Depends what it gets converted into if the type is weird. 16456 if (!VT.isSimple()) 16457 return false; 16458 16459 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus 16460 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 16461 auto Ty = VT.getSimpleVT().SimpleTy; 16462 16463 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 16464 // Unaligned access can use (for example) LRDB, LRDH, LDR 16465 if (AllowsUnaligned) { 16466 if (Fast) 16467 *Fast = Subtarget->hasV7Ops(); 16468 return true; 16469 } 16470 } 16471 16472 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 16473 // For any little-endian targets with neon, we can support unaligned ld/st 16474 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 16475 // A big-endian target may also explicitly support unaligned accesses 16476 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 16477 if (Fast) 16478 *Fast = true; 16479 return true; 16480 } 16481 } 16482 16483 if (!Subtarget->hasMVEIntegerOps()) 16484 return false; 16485 16486 // These are for predicates 16487 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 16488 if (Fast) 16489 *Fast = true; 16490 return true; 16491 } 16492 16493 // These are for truncated stores/narrowing loads. They are fine so long as 16494 // the alignment is at least the size of the item being loaded 16495 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) && 16496 Alignment >= VT.getScalarSizeInBits() / 8) { 16497 if (Fast) 16498 *Fast = true; 16499 return true; 16500 } 16501 16502 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and 16503 // VSTRW.U32 all store the vector register in exactly the same format, and 16504 // differ only in the range of their immediate offset field and the required 16505 // alignment. So there is always a store that can be used, regardless of 16506 // actual type. 16507 // 16508 // For big endian, that is not the case. But can still emit a (VSTRB.U8; 16509 // VREV64.8) pair and get the same effect. This will likely be better than 16510 // aligning the vector through the stack. 16511 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 || 16512 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 || 16513 Ty == MVT::v2f64) { 16514 if (Fast) 16515 *Fast = true; 16516 return true; 16517 } 16518 16519 return false; 16520 } 16521 16522 16523 EVT ARMTargetLowering::getOptimalMemOpType( 16524 const MemOp &Op, const AttributeList &FuncAttributes) const { 16525 // See if we can use NEON instructions for this... 16526 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() && 16527 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 16528 bool Fast; 16529 if (Op.size() >= 16 && 16530 (Op.isAligned(Align(16)) || 16531 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 16532 MachineMemOperand::MONone, &Fast) && 16533 Fast))) { 16534 return MVT::v2f64; 16535 } else if (Op.size() >= 8 && 16536 (Op.isAligned(Align(8)) || 16537 (allowsMisalignedMemoryAccesses( 16538 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 16539 Fast))) { 16540 return MVT::f64; 16541 } 16542 } 16543 16544 // Let the target-independent logic figure it out. 16545 return MVT::Other; 16546 } 16547 16548 // 64-bit integers are split into their high and low parts and held in two 16549 // different registers, so the trunc is free since the low register can just 16550 // be used. 16551 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 16552 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 16553 return false; 16554 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 16555 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 16556 return (SrcBits == 64 && DestBits == 32); 16557 } 16558 16559 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 16560 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 16561 !DstVT.isInteger()) 16562 return false; 16563 unsigned SrcBits = SrcVT.getSizeInBits(); 16564 unsigned DestBits = DstVT.getSizeInBits(); 16565 return (SrcBits == 64 && DestBits == 32); 16566 } 16567 16568 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16569 if (Val.getOpcode() != ISD::LOAD) 16570 return false; 16571 16572 EVT VT1 = Val.getValueType(); 16573 if (!VT1.isSimple() || !VT1.isInteger() || 16574 !VT2.isSimple() || !VT2.isInteger()) 16575 return false; 16576 16577 switch (VT1.getSimpleVT().SimpleTy) { 16578 default: break; 16579 case MVT::i1: 16580 case MVT::i8: 16581 case MVT::i16: 16582 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 16583 return true; 16584 } 16585 16586 return false; 16587 } 16588 16589 bool ARMTargetLowering::isFNegFree(EVT VT) const { 16590 if (!VT.isSimple()) 16591 return false; 16592 16593 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 16594 // negate values directly (fneg is free). So, we don't want to let the DAG 16595 // combiner rewrite fneg into xors and some other instructions. For f16 and 16596 // FullFP16 argument passing, some bitcast nodes may be introduced, 16597 // triggering this DAG combine rewrite, so we are avoiding that with this. 16598 switch (VT.getSimpleVT().SimpleTy) { 16599 default: break; 16600 case MVT::f16: 16601 return Subtarget->hasFullFP16(); 16602 } 16603 16604 return false; 16605 } 16606 16607 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 16608 /// of the vector elements. 16609 static bool areExtractExts(Value *Ext1, Value *Ext2) { 16610 auto areExtDoubled = [](Instruction *Ext) { 16611 return Ext->getType()->getScalarSizeInBits() == 16612 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 16613 }; 16614 16615 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 16616 !match(Ext2, m_ZExtOrSExt(m_Value())) || 16617 !areExtDoubled(cast<Instruction>(Ext1)) || 16618 !areExtDoubled(cast<Instruction>(Ext2))) 16619 return false; 16620 16621 return true; 16622 } 16623 16624 /// Check if sinking \p I's operands to I's basic block is profitable, because 16625 /// the operands can be folded into a target instruction, e.g. 16626 /// sext/zext can be folded into vsubl. 16627 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 16628 SmallVectorImpl<Use *> &Ops) const { 16629 if (!I->getType()->isVectorTy()) 16630 return false; 16631 16632 if (Subtarget->hasNEON()) { 16633 switch (I->getOpcode()) { 16634 case Instruction::Sub: 16635 case Instruction::Add: { 16636 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 16637 return false; 16638 Ops.push_back(&I->getOperandUse(0)); 16639 Ops.push_back(&I->getOperandUse(1)); 16640 return true; 16641 } 16642 default: 16643 return false; 16644 } 16645 } 16646 16647 if (!Subtarget->hasMVEIntegerOps()) 16648 return false; 16649 16650 auto IsFMSMul = [&](Instruction *I) { 16651 if (!I->hasOneUse()) 16652 return false; 16653 auto *Sub = cast<Instruction>(*I->users().begin()); 16654 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I; 16655 }; 16656 auto IsFMS = [&](Instruction *I) { 16657 if (match(I->getOperand(0), m_FNeg(m_Value())) || 16658 match(I->getOperand(1), m_FNeg(m_Value()))) 16659 return true; 16660 return false; 16661 }; 16662 16663 auto IsSinker = [&](Instruction *I, int Operand) { 16664 switch (I->getOpcode()) { 16665 case Instruction::Add: 16666 case Instruction::Mul: 16667 case Instruction::FAdd: 16668 case Instruction::ICmp: 16669 case Instruction::FCmp: 16670 return true; 16671 case Instruction::FMul: 16672 return !IsFMSMul(I); 16673 case Instruction::Sub: 16674 case Instruction::FSub: 16675 case Instruction::Shl: 16676 case Instruction::LShr: 16677 case Instruction::AShr: 16678 return Operand == 1; 16679 case Instruction::Call: 16680 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 16681 switch (II->getIntrinsicID()) { 16682 case Intrinsic::fma: 16683 return !IsFMS(I); 16684 case Intrinsic::arm_mve_add_predicated: 16685 case Intrinsic::arm_mve_mul_predicated: 16686 case Intrinsic::arm_mve_qadd_predicated: 16687 case Intrinsic::arm_mve_hadd_predicated: 16688 case Intrinsic::arm_mve_vqdmull_predicated: 16689 case Intrinsic::arm_mve_qdmulh_predicated: 16690 case Intrinsic::arm_mve_qrdmulh_predicated: 16691 case Intrinsic::arm_mve_fma_predicated: 16692 return true; 16693 case Intrinsic::arm_mve_sub_predicated: 16694 case Intrinsic::arm_mve_qsub_predicated: 16695 case Intrinsic::arm_mve_hsub_predicated: 16696 return Operand == 1; 16697 default: 16698 return false; 16699 } 16700 } 16701 return false; 16702 default: 16703 return false; 16704 } 16705 }; 16706 16707 for (auto OpIdx : enumerate(I->operands())) { 16708 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 16709 // Make sure we are not already sinking this operand 16710 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 16711 continue; 16712 16713 Instruction *Shuffle = Op; 16714 if (Shuffle->getOpcode() == Instruction::BitCast) 16715 Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0)); 16716 // We are looking for a splat that can be sunk. 16717 if (!Shuffle || 16718 !match(Shuffle, m_Shuffle( 16719 m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 16720 m_Undef(), m_ZeroMask()))) 16721 continue; 16722 if (!IsSinker(I, OpIdx.index())) 16723 continue; 16724 16725 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 16726 // and vector registers 16727 for (Use &U : Op->uses()) { 16728 Instruction *Insn = cast<Instruction>(U.getUser()); 16729 if (!IsSinker(Insn, U.getOperandNo())) 16730 return false; 16731 } 16732 16733 Ops.push_back(&Shuffle->getOperandUse(0)); 16734 if (Shuffle != Op) 16735 Ops.push_back(&Op->getOperandUse(0)); 16736 Ops.push_back(&OpIdx.value()); 16737 } 16738 return true; 16739 } 16740 16741 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const { 16742 if (!Subtarget->hasMVEIntegerOps()) 16743 return nullptr; 16744 Type *SVIType = SVI->getType(); 16745 Type *ScalarType = SVIType->getScalarType(); 16746 16747 if (ScalarType->isFloatTy()) 16748 return Type::getInt32Ty(SVIType->getContext()); 16749 if (ScalarType->isHalfTy()) 16750 return Type::getInt16Ty(SVIType->getContext()); 16751 return nullptr; 16752 } 16753 16754 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 16755 EVT VT = ExtVal.getValueType(); 16756 16757 if (!isTypeLegal(VT)) 16758 return false; 16759 16760 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) { 16761 if (Ld->isExpandingLoad()) 16762 return false; 16763 } 16764 16765 if (Subtarget->hasMVEIntegerOps()) 16766 return true; 16767 16768 // Don't create a loadext if we can fold the extension into a wide/long 16769 // instruction. 16770 // If there's more than one user instruction, the loadext is desirable no 16771 // matter what. There can be two uses by the same instruction. 16772 if (ExtVal->use_empty() || 16773 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 16774 return true; 16775 16776 SDNode *U = *ExtVal->use_begin(); 16777 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 16778 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 16779 return false; 16780 16781 return true; 16782 } 16783 16784 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 16785 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16786 return false; 16787 16788 if (!isTypeLegal(EVT::getEVT(Ty1))) 16789 return false; 16790 16791 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 16792 16793 // Assuming the caller doesn't have a zeroext or signext return parameter, 16794 // truncation all the way down to i1 is valid. 16795 return true; 16796 } 16797 16798 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 16799 const AddrMode &AM, Type *Ty, 16800 unsigned AS) const { 16801 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 16802 if (Subtarget->hasFPAO()) 16803 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 16804 return 0; 16805 } 16806 return -1; 16807 } 16808 16809 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster 16810 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be 16811 /// expanded to FMAs when this method returns true, otherwise fmuladd is 16812 /// expanded to fmul + fadd. 16813 /// 16814 /// ARM supports both fused and unfused multiply-add operations; we already 16815 /// lower a pair of fmul and fadd to the latter so it's not clear that there 16816 /// would be a gain or that the gain would be worthwhile enough to risk 16817 /// correctness bugs. 16818 /// 16819 /// For MVE, we set this to true as it helps simplify the need for some 16820 /// patterns (and we don't have the non-fused floating point instruction). 16821 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16822 EVT VT) const { 16823 if (!VT.isSimple()) 16824 return false; 16825 16826 switch (VT.getSimpleVT().SimpleTy) { 16827 case MVT::v4f32: 16828 case MVT::v8f16: 16829 return Subtarget->hasMVEFloatOps(); 16830 case MVT::f16: 16831 return Subtarget->useFPVFMx16(); 16832 case MVT::f32: 16833 return Subtarget->useFPVFMx(); 16834 case MVT::f64: 16835 return Subtarget->useFPVFMx64(); 16836 default: 16837 break; 16838 } 16839 16840 return false; 16841 } 16842 16843 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 16844 if (V < 0) 16845 return false; 16846 16847 unsigned Scale = 1; 16848 switch (VT.getSimpleVT().SimpleTy) { 16849 case MVT::i1: 16850 case MVT::i8: 16851 // Scale == 1; 16852 break; 16853 case MVT::i16: 16854 // Scale == 2; 16855 Scale = 2; 16856 break; 16857 default: 16858 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 16859 // Scale == 4; 16860 Scale = 4; 16861 break; 16862 } 16863 16864 if ((V & (Scale - 1)) != 0) 16865 return false; 16866 return isUInt<5>(V / Scale); 16867 } 16868 16869 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 16870 const ARMSubtarget *Subtarget) { 16871 if (!VT.isInteger() && !VT.isFloatingPoint()) 16872 return false; 16873 if (VT.isVector() && Subtarget->hasNEON()) 16874 return false; 16875 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 16876 !Subtarget->hasMVEFloatOps()) 16877 return false; 16878 16879 bool IsNeg = false; 16880 if (V < 0) { 16881 IsNeg = true; 16882 V = -V; 16883 } 16884 16885 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U); 16886 16887 // MVE: size * imm7 16888 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 16889 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 16890 case MVT::i32: 16891 case MVT::f32: 16892 return isShiftedUInt<7,2>(V); 16893 case MVT::i16: 16894 case MVT::f16: 16895 return isShiftedUInt<7,1>(V); 16896 case MVT::i8: 16897 return isUInt<7>(V); 16898 default: 16899 return false; 16900 } 16901 } 16902 16903 // half VLDR: 2 * imm8 16904 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 16905 return isShiftedUInt<8, 1>(V); 16906 // VLDR and LDRD: 4 * imm8 16907 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 16908 return isShiftedUInt<8, 2>(V); 16909 16910 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 16911 // + imm12 or - imm8 16912 if (IsNeg) 16913 return isUInt<8>(V); 16914 return isUInt<12>(V); 16915 } 16916 16917 return false; 16918 } 16919 16920 /// isLegalAddressImmediate - Return true if the integer value can be used 16921 /// as the offset of the target addressing mode for load / store of the 16922 /// given type. 16923 static bool isLegalAddressImmediate(int64_t V, EVT VT, 16924 const ARMSubtarget *Subtarget) { 16925 if (V == 0) 16926 return true; 16927 16928 if (!VT.isSimple()) 16929 return false; 16930 16931 if (Subtarget->isThumb1Only()) 16932 return isLegalT1AddressImmediate(V, VT); 16933 else if (Subtarget->isThumb2()) 16934 return isLegalT2AddressImmediate(V, VT, Subtarget); 16935 16936 // ARM mode. 16937 if (V < 0) 16938 V = - V; 16939 switch (VT.getSimpleVT().SimpleTy) { 16940 default: return false; 16941 case MVT::i1: 16942 case MVT::i8: 16943 case MVT::i32: 16944 // +- imm12 16945 return isUInt<12>(V); 16946 case MVT::i16: 16947 // +- imm8 16948 return isUInt<8>(V); 16949 case MVT::f32: 16950 case MVT::f64: 16951 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 16952 return false; 16953 return isShiftedUInt<8, 2>(V); 16954 } 16955 } 16956 16957 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 16958 EVT VT) const { 16959 int Scale = AM.Scale; 16960 if (Scale < 0) 16961 return false; 16962 16963 switch (VT.getSimpleVT().SimpleTy) { 16964 default: return false; 16965 case MVT::i1: 16966 case MVT::i8: 16967 case MVT::i16: 16968 case MVT::i32: 16969 if (Scale == 1) 16970 return true; 16971 // r + r << imm 16972 Scale = Scale & ~1; 16973 return Scale == 2 || Scale == 4 || Scale == 8; 16974 case MVT::i64: 16975 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 16976 // version in Thumb mode. 16977 // r + r 16978 if (Scale == 1) 16979 return true; 16980 // r * 2 (this can be lowered to r + r). 16981 if (!AM.HasBaseReg && Scale == 2) 16982 return true; 16983 return false; 16984 case MVT::isVoid: 16985 // Note, we allow "void" uses (basically, uses that aren't loads or 16986 // stores), because arm allows folding a scale into many arithmetic 16987 // operations. This should be made more precise and revisited later. 16988 16989 // Allow r << imm, but the imm has to be a multiple of two. 16990 if (Scale & 1) return false; 16991 return isPowerOf2_32(Scale); 16992 } 16993 } 16994 16995 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 16996 EVT VT) const { 16997 const int Scale = AM.Scale; 16998 16999 // Negative scales are not supported in Thumb1. 17000 if (Scale < 0) 17001 return false; 17002 17003 // Thumb1 addressing modes do not support register scaling excepting the 17004 // following cases: 17005 // 1. Scale == 1 means no scaling. 17006 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 17007 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 17008 } 17009 17010 /// isLegalAddressingMode - Return true if the addressing mode represented 17011 /// by AM is legal for this target, for a load/store of the specified type. 17012 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 17013 const AddrMode &AM, Type *Ty, 17014 unsigned AS, Instruction *I) const { 17015 EVT VT = getValueType(DL, Ty, true); 17016 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 17017 return false; 17018 17019 // Can never fold addr of global into load/store. 17020 if (AM.BaseGV) 17021 return false; 17022 17023 switch (AM.Scale) { 17024 case 0: // no scale reg, must be "r+i" or "r", or "i". 17025 break; 17026 default: 17027 // ARM doesn't support any R+R*scale+imm addr modes. 17028 if (AM.BaseOffs) 17029 return false; 17030 17031 if (!VT.isSimple()) 17032 return false; 17033 17034 if (Subtarget->isThumb1Only()) 17035 return isLegalT1ScaledAddressingMode(AM, VT); 17036 17037 if (Subtarget->isThumb2()) 17038 return isLegalT2ScaledAddressingMode(AM, VT); 17039 17040 int Scale = AM.Scale; 17041 switch (VT.getSimpleVT().SimpleTy) { 17042 default: return false; 17043 case MVT::i1: 17044 case MVT::i8: 17045 case MVT::i32: 17046 if (Scale < 0) Scale = -Scale; 17047 if (Scale == 1) 17048 return true; 17049 // r + r << imm 17050 return isPowerOf2_32(Scale & ~1); 17051 case MVT::i16: 17052 case MVT::i64: 17053 // r +/- r 17054 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 17055 return true; 17056 // r * 2 (this can be lowered to r + r). 17057 if (!AM.HasBaseReg && Scale == 2) 17058 return true; 17059 return false; 17060 17061 case MVT::isVoid: 17062 // Note, we allow "void" uses (basically, uses that aren't loads or 17063 // stores), because arm allows folding a scale into many arithmetic 17064 // operations. This should be made more precise and revisited later. 17065 17066 // Allow r << imm, but the imm has to be a multiple of two. 17067 if (Scale & 1) return false; 17068 return isPowerOf2_32(Scale); 17069 } 17070 } 17071 return true; 17072 } 17073 17074 /// isLegalICmpImmediate - Return true if the specified immediate is legal 17075 /// icmp immediate, that is the target has icmp instructions which can compare 17076 /// a register against the immediate without having to materialize the 17077 /// immediate into a register. 17078 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 17079 // Thumb2 and ARM modes can use cmn for negative immediates. 17080 if (!Subtarget->isThumb()) 17081 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 17082 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 17083 if (Subtarget->isThumb2()) 17084 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 17085 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 17086 // Thumb1 doesn't have cmn, and only 8-bit immediates. 17087 return Imm >= 0 && Imm <= 255; 17088 } 17089 17090 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 17091 /// *or sub* immediate, that is the target has add or sub instructions which can 17092 /// add a register with the immediate without having to materialize the 17093 /// immediate into a register. 17094 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 17095 // Same encoding for add/sub, just flip the sign. 17096 int64_t AbsImm = std::abs(Imm); 17097 if (!Subtarget->isThumb()) 17098 return ARM_AM::getSOImmVal(AbsImm) != -1; 17099 if (Subtarget->isThumb2()) 17100 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 17101 // Thumb1 only has 8-bit unsigned immediate. 17102 return AbsImm >= 0 && AbsImm <= 255; 17103 } 17104 17105 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 17106 bool isSEXTLoad, SDValue &Base, 17107 SDValue &Offset, bool &isInc, 17108 SelectionDAG &DAG) { 17109 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17110 return false; 17111 17112 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 17113 // AddressingMode 3 17114 Base = Ptr->getOperand(0); 17115 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17116 int RHSC = (int)RHS->getZExtValue(); 17117 if (RHSC < 0 && RHSC > -256) { 17118 assert(Ptr->getOpcode() == ISD::ADD); 17119 isInc = false; 17120 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17121 return true; 17122 } 17123 } 17124 isInc = (Ptr->getOpcode() == ISD::ADD); 17125 Offset = Ptr->getOperand(1); 17126 return true; 17127 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 17128 // AddressingMode 2 17129 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17130 int RHSC = (int)RHS->getZExtValue(); 17131 if (RHSC < 0 && RHSC > -0x1000) { 17132 assert(Ptr->getOpcode() == ISD::ADD); 17133 isInc = false; 17134 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17135 Base = Ptr->getOperand(0); 17136 return true; 17137 } 17138 } 17139 17140 if (Ptr->getOpcode() == ISD::ADD) { 17141 isInc = true; 17142 ARM_AM::ShiftOpc ShOpcVal= 17143 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 17144 if (ShOpcVal != ARM_AM::no_shift) { 17145 Base = Ptr->getOperand(1); 17146 Offset = Ptr->getOperand(0); 17147 } else { 17148 Base = Ptr->getOperand(0); 17149 Offset = Ptr->getOperand(1); 17150 } 17151 return true; 17152 } 17153 17154 isInc = (Ptr->getOpcode() == ISD::ADD); 17155 Base = Ptr->getOperand(0); 17156 Offset = Ptr->getOperand(1); 17157 return true; 17158 } 17159 17160 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 17161 return false; 17162 } 17163 17164 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 17165 bool isSEXTLoad, SDValue &Base, 17166 SDValue &Offset, bool &isInc, 17167 SelectionDAG &DAG) { 17168 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17169 return false; 17170 17171 Base = Ptr->getOperand(0); 17172 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17173 int RHSC = (int)RHS->getZExtValue(); 17174 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 17175 assert(Ptr->getOpcode() == ISD::ADD); 17176 isInc = false; 17177 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17178 return true; 17179 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 17180 isInc = Ptr->getOpcode() == ISD::ADD; 17181 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17182 return true; 17183 } 17184 } 17185 17186 return false; 17187 } 17188 17189 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment, 17190 bool isSEXTLoad, bool IsMasked, bool isLE, 17191 SDValue &Base, SDValue &Offset, 17192 bool &isInc, SelectionDAG &DAG) { 17193 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17194 return false; 17195 if (!isa<ConstantSDNode>(Ptr->getOperand(1))) 17196 return false; 17197 17198 // We allow LE non-masked loads to change the type (for example use a vldrb.8 17199 // as opposed to a vldrw.32). This can allow extra addressing modes or 17200 // alignments for what is otherwise an equivalent instruction. 17201 bool CanChangeType = isLE && !IsMasked; 17202 17203 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1)); 17204 int RHSC = (int)RHS->getZExtValue(); 17205 17206 auto IsInRange = [&](int RHSC, int Limit, int Scale) { 17207 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) { 17208 assert(Ptr->getOpcode() == ISD::ADD); 17209 isInc = false; 17210 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17211 return true; 17212 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) { 17213 isInc = Ptr->getOpcode() == ISD::ADD; 17214 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17215 return true; 17216 } 17217 return false; 17218 }; 17219 17220 // Try to find a matching instruction based on s/zext, Alignment, Offset and 17221 // (in BE/masked) type. 17222 Base = Ptr->getOperand(0); 17223 if (VT == MVT::v4i16) { 17224 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2)) 17225 return true; 17226 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) { 17227 if (IsInRange(RHSC, 0x80, 1)) 17228 return true; 17229 } else if (Alignment >= 4 && 17230 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) && 17231 IsInRange(RHSC, 0x80, 4)) 17232 return true; 17233 else if (Alignment >= 2 && 17234 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) && 17235 IsInRange(RHSC, 0x80, 2)) 17236 return true; 17237 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1)) 17238 return true; 17239 return false; 17240 } 17241 17242 /// getPreIndexedAddressParts - returns true by value, base pointer and 17243 /// offset pointer and addressing mode by reference if the node's address 17244 /// can be legally represented as pre-indexed load / store address. 17245 bool 17246 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 17247 SDValue &Offset, 17248 ISD::MemIndexedMode &AM, 17249 SelectionDAG &DAG) const { 17250 if (Subtarget->isThumb1Only()) 17251 return false; 17252 17253 EVT VT; 17254 SDValue Ptr; 17255 Align Alignment; 17256 bool isSEXTLoad = false; 17257 bool IsMasked = false; 17258 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 17259 Ptr = LD->getBasePtr(); 17260 VT = LD->getMemoryVT(); 17261 Alignment = LD->getAlign(); 17262 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17263 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 17264 Ptr = ST->getBasePtr(); 17265 VT = ST->getMemoryVT(); 17266 Alignment = ST->getAlign(); 17267 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 17268 Ptr = LD->getBasePtr(); 17269 VT = LD->getMemoryVT(); 17270 Alignment = LD->getAlign(); 17271 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17272 IsMasked = true; 17273 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 17274 Ptr = ST->getBasePtr(); 17275 VT = ST->getMemoryVT(); 17276 Alignment = ST->getAlign(); 17277 IsMasked = true; 17278 } else 17279 return false; 17280 17281 bool isInc; 17282 bool isLegal = false; 17283 if (VT.isVector()) 17284 isLegal = Subtarget->hasMVEIntegerOps() && 17285 getMVEIndexedAddressParts( 17286 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked, 17287 Subtarget->isLittle(), Base, Offset, isInc, DAG); 17288 else { 17289 if (Subtarget->isThumb2()) 17290 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 17291 Offset, isInc, DAG); 17292 else 17293 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 17294 Offset, isInc, DAG); 17295 } 17296 if (!isLegal) 17297 return false; 17298 17299 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 17300 return true; 17301 } 17302 17303 /// getPostIndexedAddressParts - returns true by value, base pointer and 17304 /// offset pointer and addressing mode by reference if this node can be 17305 /// combined with a load / store to form a post-indexed load / store. 17306 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 17307 SDValue &Base, 17308 SDValue &Offset, 17309 ISD::MemIndexedMode &AM, 17310 SelectionDAG &DAG) const { 17311 EVT VT; 17312 SDValue Ptr; 17313 Align Alignment; 17314 bool isSEXTLoad = false, isNonExt; 17315 bool IsMasked = false; 17316 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 17317 VT = LD->getMemoryVT(); 17318 Ptr = LD->getBasePtr(); 17319 Alignment = LD->getAlign(); 17320 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17321 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 17322 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 17323 VT = ST->getMemoryVT(); 17324 Ptr = ST->getBasePtr(); 17325 Alignment = ST->getAlign(); 17326 isNonExt = !ST->isTruncatingStore(); 17327 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 17328 VT = LD->getMemoryVT(); 17329 Ptr = LD->getBasePtr(); 17330 Alignment = LD->getAlign(); 17331 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17332 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 17333 IsMasked = true; 17334 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 17335 VT = ST->getMemoryVT(); 17336 Ptr = ST->getBasePtr(); 17337 Alignment = ST->getAlign(); 17338 isNonExt = !ST->isTruncatingStore(); 17339 IsMasked = true; 17340 } else 17341 return false; 17342 17343 if (Subtarget->isThumb1Only()) { 17344 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 17345 // must be non-extending/truncating, i32, with an offset of 4. 17346 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 17347 if (Op->getOpcode() != ISD::ADD || !isNonExt) 17348 return false; 17349 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 17350 if (!RHS || RHS->getZExtValue() != 4) 17351 return false; 17352 17353 Offset = Op->getOperand(1); 17354 Base = Op->getOperand(0); 17355 AM = ISD::POST_INC; 17356 return true; 17357 } 17358 17359 bool isInc; 17360 bool isLegal = false; 17361 if (VT.isVector()) 17362 isLegal = Subtarget->hasMVEIntegerOps() && 17363 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked, 17364 Subtarget->isLittle(), Base, Offset, 17365 isInc, DAG); 17366 else { 17367 if (Subtarget->isThumb2()) 17368 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 17369 isInc, DAG); 17370 else 17371 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 17372 isInc, DAG); 17373 } 17374 if (!isLegal) 17375 return false; 17376 17377 if (Ptr != Base) { 17378 // Swap base ptr and offset to catch more post-index load / store when 17379 // it's legal. In Thumb2 mode, offset must be an immediate. 17380 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 17381 !Subtarget->isThumb2()) 17382 std::swap(Base, Offset); 17383 17384 // Post-indexed load / store update the base pointer. 17385 if (Ptr != Base) 17386 return false; 17387 } 17388 17389 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 17390 return true; 17391 } 17392 17393 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 17394 KnownBits &Known, 17395 const APInt &DemandedElts, 17396 const SelectionDAG &DAG, 17397 unsigned Depth) const { 17398 unsigned BitWidth = Known.getBitWidth(); 17399 Known.resetAll(); 17400 switch (Op.getOpcode()) { 17401 default: break; 17402 case ARMISD::ADDC: 17403 case ARMISD::ADDE: 17404 case ARMISD::SUBC: 17405 case ARMISD::SUBE: 17406 // Special cases when we convert a carry to a boolean. 17407 if (Op.getResNo() == 0) { 17408 SDValue LHS = Op.getOperand(0); 17409 SDValue RHS = Op.getOperand(1); 17410 // (ADDE 0, 0, C) will give us a single bit. 17411 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 17412 isNullConstant(RHS)) { 17413 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 17414 return; 17415 } 17416 } 17417 break; 17418 case ARMISD::CMOV: { 17419 // Bits are known zero/one if known on the LHS and RHS. 17420 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 17421 if (Known.isUnknown()) 17422 return; 17423 17424 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 17425 Known = KnownBits::commonBits(Known, KnownRHS); 17426 return; 17427 } 17428 case ISD::INTRINSIC_W_CHAIN: { 17429 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 17430 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 17431 switch (IntID) { 17432 default: return; 17433 case Intrinsic::arm_ldaex: 17434 case Intrinsic::arm_ldrex: { 17435 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 17436 unsigned MemBits = VT.getScalarSizeInBits(); 17437 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 17438 return; 17439 } 17440 } 17441 } 17442 case ARMISD::BFI: { 17443 // Conservatively, we can recurse down the first operand 17444 // and just mask out all affected bits. 17445 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 17446 17447 // The operand to BFI is already a mask suitable for removing the bits it 17448 // sets. 17449 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 17450 const APInt &Mask = CI->getAPIntValue(); 17451 Known.Zero &= Mask; 17452 Known.One &= Mask; 17453 return; 17454 } 17455 case ARMISD::VGETLANEs: 17456 case ARMISD::VGETLANEu: { 17457 const SDValue &SrcSV = Op.getOperand(0); 17458 EVT VecVT = SrcSV.getValueType(); 17459 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 17460 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 17461 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 17462 assert(Pos->getAPIntValue().ult(NumSrcElts) && 17463 "VGETLANE index out of bounds"); 17464 unsigned Idx = Pos->getZExtValue(); 17465 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 17466 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 17467 17468 EVT VT = Op.getValueType(); 17469 const unsigned DstSz = VT.getScalarSizeInBits(); 17470 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 17471 (void)SrcSz; 17472 assert(SrcSz == Known.getBitWidth()); 17473 assert(DstSz > SrcSz); 17474 if (Op.getOpcode() == ARMISD::VGETLANEs) 17475 Known = Known.sext(DstSz); 17476 else { 17477 Known = Known.zext(DstSz); 17478 } 17479 assert(DstSz == Known.getBitWidth()); 17480 break; 17481 } 17482 case ARMISD::VMOVrh: { 17483 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 17484 assert(KnownOp.getBitWidth() == 16); 17485 Known = KnownOp.zext(32); 17486 break; 17487 } 17488 } 17489 } 17490 17491 bool ARMTargetLowering::targetShrinkDemandedConstant( 17492 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 17493 TargetLoweringOpt &TLO) const { 17494 // Delay optimization, so we don't have to deal with illegal types, or block 17495 // optimizations. 17496 if (!TLO.LegalOps) 17497 return false; 17498 17499 // Only optimize AND for now. 17500 if (Op.getOpcode() != ISD::AND) 17501 return false; 17502 17503 EVT VT = Op.getValueType(); 17504 17505 // Ignore vectors. 17506 if (VT.isVector()) 17507 return false; 17508 17509 assert(VT == MVT::i32 && "Unexpected integer type"); 17510 17511 // Make sure the RHS really is a constant. 17512 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 17513 if (!C) 17514 return false; 17515 17516 unsigned Mask = C->getZExtValue(); 17517 17518 unsigned Demanded = DemandedBits.getZExtValue(); 17519 unsigned ShrunkMask = Mask & Demanded; 17520 unsigned ExpandedMask = Mask | ~Demanded; 17521 17522 // If the mask is all zeros, let the target-independent code replace the 17523 // result with zero. 17524 if (ShrunkMask == 0) 17525 return false; 17526 17527 // If the mask is all ones, erase the AND. (Currently, the target-independent 17528 // code won't do this, so we have to do it explicitly to avoid an infinite 17529 // loop in obscure cases.) 17530 if (ExpandedMask == ~0U) 17531 return TLO.CombineTo(Op, Op.getOperand(0)); 17532 17533 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 17534 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 17535 }; 17536 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 17537 if (NewMask == Mask) 17538 return true; 17539 SDLoc DL(Op); 17540 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 17541 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 17542 return TLO.CombineTo(Op, NewOp); 17543 }; 17544 17545 // Prefer uxtb mask. 17546 if (IsLegalMask(0xFF)) 17547 return UseMask(0xFF); 17548 17549 // Prefer uxth mask. 17550 if (IsLegalMask(0xFFFF)) 17551 return UseMask(0xFFFF); 17552 17553 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 17554 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 17555 if (ShrunkMask < 256) 17556 return UseMask(ShrunkMask); 17557 17558 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 17559 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 17560 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 17561 return UseMask(ExpandedMask); 17562 17563 // Potential improvements: 17564 // 17565 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 17566 // We could try to prefer Thumb1 immediates which can be lowered to a 17567 // two-instruction sequence. 17568 // We could try to recognize more legal ARM/Thumb2 immediates here. 17569 17570 return false; 17571 } 17572 17573 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode( 17574 SDValue Op, const APInt &OriginalDemandedBits, 17575 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 17576 unsigned Depth) const { 17577 unsigned Opc = Op.getOpcode(); 17578 17579 switch (Opc) { 17580 case ARMISD::ASRL: 17581 case ARMISD::LSRL: { 17582 // If this is result 0 and the other result is unused, see if the demand 17583 // bits allow us to shrink this long shift into a standard small shift in 17584 // the opposite direction. 17585 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) && 17586 isa<ConstantSDNode>(Op->getOperand(2))) { 17587 unsigned ShAmt = Op->getConstantOperandVal(2); 17588 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf( 17589 APInt::getAllOnesValue(32) << (32 - ShAmt))) 17590 return TLO.CombineTo( 17591 Op, TLO.DAG.getNode( 17592 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1), 17593 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32))); 17594 } 17595 break; 17596 } 17597 } 17598 17599 return TargetLowering::SimplifyDemandedBitsForTargetNode( 17600 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth); 17601 } 17602 17603 //===----------------------------------------------------------------------===// 17604 // ARM Inline Assembly Support 17605 //===----------------------------------------------------------------------===// 17606 17607 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 17608 // Looking for "rev" which is V6+. 17609 if (!Subtarget->hasV6Ops()) 17610 return false; 17611 17612 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand()); 17613 std::string AsmStr = IA->getAsmString(); 17614 SmallVector<StringRef, 4> AsmPieces; 17615 SplitString(AsmStr, AsmPieces, ";\n"); 17616 17617 switch (AsmPieces.size()) { 17618 default: return false; 17619 case 1: 17620 AsmStr = std::string(AsmPieces[0]); 17621 AsmPieces.clear(); 17622 SplitString(AsmStr, AsmPieces, " \t,"); 17623 17624 // rev $0, $1 17625 if (AsmPieces.size() == 3 && 17626 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 17627 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 17628 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 17629 if (Ty && Ty->getBitWidth() == 32) 17630 return IntrinsicLowering::LowerToByteSwap(CI); 17631 } 17632 break; 17633 } 17634 17635 return false; 17636 } 17637 17638 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 17639 // At this point, we have to lower this constraint to something else, so we 17640 // lower it to an "r" or "w". However, by doing this we will force the result 17641 // to be in register, while the X constraint is much more permissive. 17642 // 17643 // Although we are correct (we are free to emit anything, without 17644 // constraints), we might break use cases that would expect us to be more 17645 // efficient and emit something else. 17646 if (!Subtarget->hasVFP2Base()) 17647 return "r"; 17648 if (ConstraintVT.isFloatingPoint()) 17649 return "w"; 17650 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 17651 (ConstraintVT.getSizeInBits() == 64 || 17652 ConstraintVT.getSizeInBits() == 128)) 17653 return "w"; 17654 17655 return "r"; 17656 } 17657 17658 /// getConstraintType - Given a constraint letter, return the type of 17659 /// constraint it is for this target. 17660 ARMTargetLowering::ConstraintType 17661 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 17662 unsigned S = Constraint.size(); 17663 if (S == 1) { 17664 switch (Constraint[0]) { 17665 default: break; 17666 case 'l': return C_RegisterClass; 17667 case 'w': return C_RegisterClass; 17668 case 'h': return C_RegisterClass; 17669 case 'x': return C_RegisterClass; 17670 case 't': return C_RegisterClass; 17671 case 'j': return C_Immediate; // Constant for movw. 17672 // An address with a single base register. Due to the way we 17673 // currently handle addresses it is the same as an 'r' memory constraint. 17674 case 'Q': return C_Memory; 17675 } 17676 } else if (S == 2) { 17677 switch (Constraint[0]) { 17678 default: break; 17679 case 'T': return C_RegisterClass; 17680 // All 'U+' constraints are addresses. 17681 case 'U': return C_Memory; 17682 } 17683 } 17684 return TargetLowering::getConstraintType(Constraint); 17685 } 17686 17687 /// Examine constraint type and operand type and determine a weight value. 17688 /// This object must already have been set up with the operand type 17689 /// and the current alternative constraint selected. 17690 TargetLowering::ConstraintWeight 17691 ARMTargetLowering::getSingleConstraintMatchWeight( 17692 AsmOperandInfo &info, const char *constraint) const { 17693 ConstraintWeight weight = CW_Invalid; 17694 Value *CallOperandVal = info.CallOperandVal; 17695 // If we don't have a value, we can't do a match, 17696 // but allow it at the lowest weight. 17697 if (!CallOperandVal) 17698 return CW_Default; 17699 Type *type = CallOperandVal->getType(); 17700 // Look at the constraint type. 17701 switch (*constraint) { 17702 default: 17703 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 17704 break; 17705 case 'l': 17706 if (type->isIntegerTy()) { 17707 if (Subtarget->isThumb()) 17708 weight = CW_SpecificReg; 17709 else 17710 weight = CW_Register; 17711 } 17712 break; 17713 case 'w': 17714 if (type->isFloatingPointTy()) 17715 weight = CW_Register; 17716 break; 17717 } 17718 return weight; 17719 } 17720 17721 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 17722 17723 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 17724 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 17725 switch (Constraint.size()) { 17726 case 1: 17727 // GCC ARM Constraint Letters 17728 switch (Constraint[0]) { 17729 case 'l': // Low regs or general regs. 17730 if (Subtarget->isThumb()) 17731 return RCPair(0U, &ARM::tGPRRegClass); 17732 return RCPair(0U, &ARM::GPRRegClass); 17733 case 'h': // High regs or no regs. 17734 if (Subtarget->isThumb()) 17735 return RCPair(0U, &ARM::hGPRRegClass); 17736 break; 17737 case 'r': 17738 if (Subtarget->isThumb1Only()) 17739 return RCPair(0U, &ARM::tGPRRegClass); 17740 return RCPair(0U, &ARM::GPRRegClass); 17741 case 'w': 17742 if (VT == MVT::Other) 17743 break; 17744 if (VT == MVT::f32) 17745 return RCPair(0U, &ARM::SPRRegClass); 17746 if (VT.getSizeInBits() == 64) 17747 return RCPair(0U, &ARM::DPRRegClass); 17748 if (VT.getSizeInBits() == 128) 17749 return RCPair(0U, &ARM::QPRRegClass); 17750 break; 17751 case 'x': 17752 if (VT == MVT::Other) 17753 break; 17754 if (VT == MVT::f32) 17755 return RCPair(0U, &ARM::SPR_8RegClass); 17756 if (VT.getSizeInBits() == 64) 17757 return RCPair(0U, &ARM::DPR_8RegClass); 17758 if (VT.getSizeInBits() == 128) 17759 return RCPair(0U, &ARM::QPR_8RegClass); 17760 break; 17761 case 't': 17762 if (VT == MVT::Other) 17763 break; 17764 if (VT == MVT::f32 || VT == MVT::i32) 17765 return RCPair(0U, &ARM::SPRRegClass); 17766 if (VT.getSizeInBits() == 64) 17767 return RCPair(0U, &ARM::DPR_VFP2RegClass); 17768 if (VT.getSizeInBits() == 128) 17769 return RCPair(0U, &ARM::QPR_VFP2RegClass); 17770 break; 17771 } 17772 break; 17773 17774 case 2: 17775 if (Constraint[0] == 'T') { 17776 switch (Constraint[1]) { 17777 default: 17778 break; 17779 case 'e': 17780 return RCPair(0U, &ARM::tGPREvenRegClass); 17781 case 'o': 17782 return RCPair(0U, &ARM::tGPROddRegClass); 17783 } 17784 } 17785 break; 17786 17787 default: 17788 break; 17789 } 17790 17791 if (StringRef("{cc}").equals_lower(Constraint)) 17792 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 17793 17794 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 17795 } 17796 17797 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 17798 /// vector. If it is invalid, don't add anything to Ops. 17799 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 17800 std::string &Constraint, 17801 std::vector<SDValue>&Ops, 17802 SelectionDAG &DAG) const { 17803 SDValue Result; 17804 17805 // Currently only support length 1 constraints. 17806 if (Constraint.length() != 1) return; 17807 17808 char ConstraintLetter = Constraint[0]; 17809 switch (ConstraintLetter) { 17810 default: break; 17811 case 'j': 17812 case 'I': case 'J': case 'K': case 'L': 17813 case 'M': case 'N': case 'O': 17814 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 17815 if (!C) 17816 return; 17817 17818 int64_t CVal64 = C->getSExtValue(); 17819 int CVal = (int) CVal64; 17820 // None of these constraints allow values larger than 32 bits. Check 17821 // that the value fits in an int. 17822 if (CVal != CVal64) 17823 return; 17824 17825 switch (ConstraintLetter) { 17826 case 'j': 17827 // Constant suitable for movw, must be between 0 and 17828 // 65535. 17829 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps())) 17830 if (CVal >= 0 && CVal <= 65535) 17831 break; 17832 return; 17833 case 'I': 17834 if (Subtarget->isThumb1Only()) { 17835 // This must be a constant between 0 and 255, for ADD 17836 // immediates. 17837 if (CVal >= 0 && CVal <= 255) 17838 break; 17839 } else if (Subtarget->isThumb2()) { 17840 // A constant that can be used as an immediate value in a 17841 // data-processing instruction. 17842 if (ARM_AM::getT2SOImmVal(CVal) != -1) 17843 break; 17844 } else { 17845 // A constant that can be used as an immediate value in a 17846 // data-processing instruction. 17847 if (ARM_AM::getSOImmVal(CVal) != -1) 17848 break; 17849 } 17850 return; 17851 17852 case 'J': 17853 if (Subtarget->isThumb1Only()) { 17854 // This must be a constant between -255 and -1, for negated ADD 17855 // immediates. This can be used in GCC with an "n" modifier that 17856 // prints the negated value, for use with SUB instructions. It is 17857 // not useful otherwise but is implemented for compatibility. 17858 if (CVal >= -255 && CVal <= -1) 17859 break; 17860 } else { 17861 // This must be a constant between -4095 and 4095. It is not clear 17862 // what this constraint is intended for. Implemented for 17863 // compatibility with GCC. 17864 if (CVal >= -4095 && CVal <= 4095) 17865 break; 17866 } 17867 return; 17868 17869 case 'K': 17870 if (Subtarget->isThumb1Only()) { 17871 // A 32-bit value where only one byte has a nonzero value. Exclude 17872 // zero to match GCC. This constraint is used by GCC internally for 17873 // constants that can be loaded with a move/shift combination. 17874 // It is not useful otherwise but is implemented for compatibility. 17875 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 17876 break; 17877 } else if (Subtarget->isThumb2()) { 17878 // A constant whose bitwise inverse can be used as an immediate 17879 // value in a data-processing instruction. This can be used in GCC 17880 // with a "B" modifier that prints the inverted value, for use with 17881 // BIC and MVN instructions. It is not useful otherwise but is 17882 // implemented for compatibility. 17883 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 17884 break; 17885 } else { 17886 // A constant whose bitwise inverse can be used as an immediate 17887 // value in a data-processing instruction. This can be used in GCC 17888 // with a "B" modifier that prints the inverted value, for use with 17889 // BIC and MVN instructions. It is not useful otherwise but is 17890 // implemented for compatibility. 17891 if (ARM_AM::getSOImmVal(~CVal) != -1) 17892 break; 17893 } 17894 return; 17895 17896 case 'L': 17897 if (Subtarget->isThumb1Only()) { 17898 // This must be a constant between -7 and 7, 17899 // for 3-operand ADD/SUB immediate instructions. 17900 if (CVal >= -7 && CVal < 7) 17901 break; 17902 } else if (Subtarget->isThumb2()) { 17903 // A constant whose negation can be used as an immediate value in a 17904 // data-processing instruction. This can be used in GCC with an "n" 17905 // modifier that prints the negated value, for use with SUB 17906 // instructions. It is not useful otherwise but is implemented for 17907 // compatibility. 17908 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 17909 break; 17910 } else { 17911 // A constant whose negation can be used as an immediate value in a 17912 // data-processing instruction. This can be used in GCC with an "n" 17913 // modifier that prints the negated value, for use with SUB 17914 // instructions. It is not useful otherwise but is implemented for 17915 // compatibility. 17916 if (ARM_AM::getSOImmVal(-CVal) != -1) 17917 break; 17918 } 17919 return; 17920 17921 case 'M': 17922 if (Subtarget->isThumb1Only()) { 17923 // This must be a multiple of 4 between 0 and 1020, for 17924 // ADD sp + immediate. 17925 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 17926 break; 17927 } else { 17928 // A power of two or a constant between 0 and 32. This is used in 17929 // GCC for the shift amount on shifted register operands, but it is 17930 // useful in general for any shift amounts. 17931 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 17932 break; 17933 } 17934 return; 17935 17936 case 'N': 17937 if (Subtarget->isThumb1Only()) { 17938 // This must be a constant between 0 and 31, for shift amounts. 17939 if (CVal >= 0 && CVal <= 31) 17940 break; 17941 } 17942 return; 17943 17944 case 'O': 17945 if (Subtarget->isThumb1Only()) { 17946 // This must be a multiple of 4 between -508 and 508, for 17947 // ADD/SUB sp = sp + immediate. 17948 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 17949 break; 17950 } 17951 return; 17952 } 17953 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 17954 break; 17955 } 17956 17957 if (Result.getNode()) { 17958 Ops.push_back(Result); 17959 return; 17960 } 17961 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 17962 } 17963 17964 static RTLIB::Libcall getDivRemLibcall( 17965 const SDNode *N, MVT::SimpleValueType SVT) { 17966 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 17967 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 17968 "Unhandled Opcode in getDivRemLibcall"); 17969 bool isSigned = N->getOpcode() == ISD::SDIVREM || 17970 N->getOpcode() == ISD::SREM; 17971 RTLIB::Libcall LC; 17972 switch (SVT) { 17973 default: llvm_unreachable("Unexpected request for libcall!"); 17974 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 17975 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 17976 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 17977 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 17978 } 17979 return LC; 17980 } 17981 17982 static TargetLowering::ArgListTy getDivRemArgList( 17983 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 17984 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 17985 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 17986 "Unhandled Opcode in getDivRemArgList"); 17987 bool isSigned = N->getOpcode() == ISD::SDIVREM || 17988 N->getOpcode() == ISD::SREM; 17989 TargetLowering::ArgListTy Args; 17990 TargetLowering::ArgListEntry Entry; 17991 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 17992 EVT ArgVT = N->getOperand(i).getValueType(); 17993 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 17994 Entry.Node = N->getOperand(i); 17995 Entry.Ty = ArgTy; 17996 Entry.IsSExt = isSigned; 17997 Entry.IsZExt = !isSigned; 17998 Args.push_back(Entry); 17999 } 18000 if (Subtarget->isTargetWindows() && Args.size() >= 2) 18001 std::swap(Args[0], Args[1]); 18002 return Args; 18003 } 18004 18005 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 18006 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 18007 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 18008 Subtarget->isTargetWindows()) && 18009 "Register-based DivRem lowering only"); 18010 unsigned Opcode = Op->getOpcode(); 18011 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 18012 "Invalid opcode for Div/Rem lowering"); 18013 bool isSigned = (Opcode == ISD::SDIVREM); 18014 EVT VT = Op->getValueType(0); 18015 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 18016 SDLoc dl(Op); 18017 18018 // If the target has hardware divide, use divide + multiply + subtract: 18019 // div = a / b 18020 // rem = a - b * div 18021 // return {div, rem} 18022 // This should be lowered into UDIV/SDIV + MLS later on. 18023 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 18024 : Subtarget->hasDivideInARMMode(); 18025 if (hasDivide && Op->getValueType(0).isSimple() && 18026 Op->getSimpleValueType(0) == MVT::i32) { 18027 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 18028 const SDValue Dividend = Op->getOperand(0); 18029 const SDValue Divisor = Op->getOperand(1); 18030 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 18031 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 18032 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 18033 18034 SDValue Values[2] = {Div, Rem}; 18035 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 18036 } 18037 18038 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 18039 VT.getSimpleVT().SimpleTy); 18040 SDValue InChain = DAG.getEntryNode(); 18041 18042 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 18043 DAG.getContext(), 18044 Subtarget); 18045 18046 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 18047 getPointerTy(DAG.getDataLayout())); 18048 18049 Type *RetTy = StructType::get(Ty, Ty); 18050 18051 if (Subtarget->isTargetWindows()) 18052 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 18053 18054 TargetLowering::CallLoweringInfo CLI(DAG); 18055 CLI.setDebugLoc(dl).setChain(InChain) 18056 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 18057 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 18058 18059 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 18060 return CallInfo.first; 18061 } 18062 18063 // Lowers REM using divmod helpers 18064 // see RTABI section 4.2/4.3 18065 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 18066 // Build return types (div and rem) 18067 std::vector<Type*> RetTyParams; 18068 Type *RetTyElement; 18069 18070 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 18071 default: llvm_unreachable("Unexpected request for libcall!"); 18072 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 18073 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 18074 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 18075 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 18076 } 18077 18078 RetTyParams.push_back(RetTyElement); 18079 RetTyParams.push_back(RetTyElement); 18080 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 18081 Type *RetTy = StructType::get(*DAG.getContext(), ret); 18082 18083 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 18084 SimpleTy); 18085 SDValue InChain = DAG.getEntryNode(); 18086 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 18087 Subtarget); 18088 bool isSigned = N->getOpcode() == ISD::SREM; 18089 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 18090 getPointerTy(DAG.getDataLayout())); 18091 18092 if (Subtarget->isTargetWindows()) 18093 InChain = WinDBZCheckDenominator(DAG, N, InChain); 18094 18095 // Lower call 18096 CallLoweringInfo CLI(DAG); 18097 CLI.setChain(InChain) 18098 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 18099 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 18100 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 18101 18102 // Return second (rem) result operand (first contains div) 18103 SDNode *ResNode = CallResult.first.getNode(); 18104 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 18105 return ResNode->getOperand(1); 18106 } 18107 18108 SDValue 18109 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 18110 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 18111 SDLoc DL(Op); 18112 18113 // Get the inputs. 18114 SDValue Chain = Op.getOperand(0); 18115 SDValue Size = Op.getOperand(1); 18116 18117 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 18118 "no-stack-arg-probe")) { 18119 MaybeAlign Align = 18120 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue(); 18121 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 18122 Chain = SP.getValue(1); 18123 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 18124 if (Align) 18125 SP = 18126 DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 18127 DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32)); 18128 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 18129 SDValue Ops[2] = { SP, Chain }; 18130 return DAG.getMergeValues(Ops, DL); 18131 } 18132 18133 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 18134 DAG.getConstant(2, DL, MVT::i32)); 18135 18136 SDValue Flag; 18137 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 18138 Flag = Chain.getValue(1); 18139 18140 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 18141 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 18142 18143 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 18144 Chain = NewSP.getValue(1); 18145 18146 SDValue Ops[2] = { NewSP, Chain }; 18147 return DAG.getMergeValues(Ops, DL); 18148 } 18149 18150 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 18151 bool IsStrict = Op->isStrictFPOpcode(); 18152 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 18153 const unsigned DstSz = Op.getValueType().getSizeInBits(); 18154 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 18155 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 18156 "Unexpected type for custom-lowering FP_EXTEND"); 18157 18158 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 18159 "With both FP DP and 16, any FP conversion is legal!"); 18160 18161 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 18162 "With FP16, 16 to 32 conversion is legal!"); 18163 18164 // Converting from 32 -> 64 is valid if we have FP64. 18165 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) { 18166 // FIXME: Remove this when we have strict fp instruction selection patterns 18167 if (IsStrict) { 18168 SDLoc Loc(Op); 18169 SDValue Result = DAG.getNode(ISD::FP_EXTEND, 18170 Loc, Op.getValueType(), SrcVal); 18171 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 18172 } 18173 return Op; 18174 } 18175 18176 // Either we are converting from 16 -> 64, without FP16 and/or 18177 // FP.double-precision or without Armv8-fp. So we must do it in two 18178 // steps. 18179 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 18180 // without FP16. So we must do a function call. 18181 SDLoc Loc(Op); 18182 RTLIB::Libcall LC; 18183 MakeLibCallOptions CallOptions; 18184 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 18185 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) { 18186 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64()); 18187 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32); 18188 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64); 18189 if (Supported) { 18190 if (IsStrict) { 18191 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc, 18192 {DstVT, MVT::Other}, {Chain, SrcVal}); 18193 Chain = SrcVal.getValue(1); 18194 } else { 18195 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal); 18196 } 18197 } else { 18198 LC = RTLIB::getFPEXT(SrcVT, DstVT); 18199 assert(LC != RTLIB::UNKNOWN_LIBCALL && 18200 "Unexpected type for custom-lowering FP_EXTEND"); 18201 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 18202 Loc, Chain); 18203 } 18204 } 18205 18206 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal; 18207 } 18208 18209 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 18210 bool IsStrict = Op->isStrictFPOpcode(); 18211 18212 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 18213 EVT SrcVT = SrcVal.getValueType(); 18214 EVT DstVT = Op.getValueType(); 18215 const unsigned DstSz = Op.getValueType().getSizeInBits(); 18216 const unsigned SrcSz = SrcVT.getSizeInBits(); 18217 (void)DstSz; 18218 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 18219 "Unexpected type for custom-lowering FP_ROUND"); 18220 18221 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 18222 "With both FP DP and 16, any FP conversion is legal!"); 18223 18224 SDLoc Loc(Op); 18225 18226 // Instruction from 32 -> 16 if hasFP16 is valid 18227 if (SrcSz == 32 && Subtarget->hasFP16()) 18228 return Op; 18229 18230 // Lib call from 32 -> 16 / 64 -> [32, 16] 18231 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 18232 assert(LC != RTLIB::UNKNOWN_LIBCALL && 18233 "Unexpected type for custom-lowering FP_ROUND"); 18234 MakeLibCallOptions CallOptions; 18235 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 18236 SDValue Result; 18237 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 18238 Loc, Chain); 18239 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 18240 } 18241 18242 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 18243 SelectionDAG &DAG) const { 18244 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 18245 MVT HalfT = MVT::i32; 18246 SDLoc dl(N); 18247 SDValue Hi, Lo, Tmp; 18248 18249 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 18250 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 18251 return ; 18252 18253 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 18254 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 18255 18256 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 18257 DAG.getConstant(0, dl, HalfT)); 18258 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 18259 DAG.getConstant(1, dl, HalfT)); 18260 18261 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 18262 DAG.getConstant(OpTypeBits - 1, dl, 18263 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 18264 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 18265 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 18266 SDValue(Lo.getNode(), 1)); 18267 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 18268 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 18269 18270 Results.push_back(Lo); 18271 Results.push_back(Hi); 18272 } 18273 18274 bool 18275 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 18276 // The ARM target isn't yet aware of offsets. 18277 return false; 18278 } 18279 18280 bool ARM::isBitFieldInvertedMask(unsigned v) { 18281 if (v == 0xffffffff) 18282 return false; 18283 18284 // there can be 1's on either or both "outsides", all the "inside" 18285 // bits must be 0's 18286 return isShiftedMask_32(~v); 18287 } 18288 18289 /// isFPImmLegal - Returns true if the target can instruction select the 18290 /// specified FP immediate natively. If false, the legalizer will 18291 /// materialize the FP immediate as a load from a constant pool. 18292 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 18293 bool ForCodeSize) const { 18294 if (!Subtarget->hasVFP3Base()) 18295 return false; 18296 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 18297 return ARM_AM::getFP16Imm(Imm) != -1; 18298 if (VT == MVT::f32 && Subtarget->hasFullFP16() && 18299 ARM_AM::getFP32FP16Imm(Imm) != -1) 18300 return true; 18301 if (VT == MVT::f32) 18302 return ARM_AM::getFP32Imm(Imm) != -1; 18303 if (VT == MVT::f64 && Subtarget->hasFP64()) 18304 return ARM_AM::getFP64Imm(Imm) != -1; 18305 return false; 18306 } 18307 18308 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 18309 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 18310 /// specified in the intrinsic calls. 18311 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 18312 const CallInst &I, 18313 MachineFunction &MF, 18314 unsigned Intrinsic) const { 18315 switch (Intrinsic) { 18316 case Intrinsic::arm_neon_vld1: 18317 case Intrinsic::arm_neon_vld2: 18318 case Intrinsic::arm_neon_vld3: 18319 case Intrinsic::arm_neon_vld4: 18320 case Intrinsic::arm_neon_vld2lane: 18321 case Intrinsic::arm_neon_vld3lane: 18322 case Intrinsic::arm_neon_vld4lane: 18323 case Intrinsic::arm_neon_vld2dup: 18324 case Intrinsic::arm_neon_vld3dup: 18325 case Intrinsic::arm_neon_vld4dup: { 18326 Info.opc = ISD::INTRINSIC_W_CHAIN; 18327 // Conservatively set memVT to the entire set of vectors loaded. 18328 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18329 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 18330 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18331 Info.ptrVal = I.getArgOperand(0); 18332 Info.offset = 0; 18333 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 18334 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue(); 18335 // volatile loads with NEON intrinsics not supported 18336 Info.flags = MachineMemOperand::MOLoad; 18337 return true; 18338 } 18339 case Intrinsic::arm_neon_vld1x2: 18340 case Intrinsic::arm_neon_vld1x3: 18341 case Intrinsic::arm_neon_vld1x4: { 18342 Info.opc = ISD::INTRINSIC_W_CHAIN; 18343 // Conservatively set memVT to the entire set of vectors loaded. 18344 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18345 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 18346 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18347 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 18348 Info.offset = 0; 18349 Info.align.reset(); 18350 // volatile loads with NEON intrinsics not supported 18351 Info.flags = MachineMemOperand::MOLoad; 18352 return true; 18353 } 18354 case Intrinsic::arm_neon_vst1: 18355 case Intrinsic::arm_neon_vst2: 18356 case Intrinsic::arm_neon_vst3: 18357 case Intrinsic::arm_neon_vst4: 18358 case Intrinsic::arm_neon_vst2lane: 18359 case Intrinsic::arm_neon_vst3lane: 18360 case Intrinsic::arm_neon_vst4lane: { 18361 Info.opc = ISD::INTRINSIC_VOID; 18362 // Conservatively set memVT to the entire set of vectors stored. 18363 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18364 unsigned NumElts = 0; 18365 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 18366 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 18367 if (!ArgTy->isVectorTy()) 18368 break; 18369 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 18370 } 18371 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18372 Info.ptrVal = I.getArgOperand(0); 18373 Info.offset = 0; 18374 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 18375 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue(); 18376 // volatile stores with NEON intrinsics not supported 18377 Info.flags = MachineMemOperand::MOStore; 18378 return true; 18379 } 18380 case Intrinsic::arm_neon_vst1x2: 18381 case Intrinsic::arm_neon_vst1x3: 18382 case Intrinsic::arm_neon_vst1x4: { 18383 Info.opc = ISD::INTRINSIC_VOID; 18384 // Conservatively set memVT to the entire set of vectors stored. 18385 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18386 unsigned NumElts = 0; 18387 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 18388 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 18389 if (!ArgTy->isVectorTy()) 18390 break; 18391 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 18392 } 18393 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18394 Info.ptrVal = I.getArgOperand(0); 18395 Info.offset = 0; 18396 Info.align.reset(); 18397 // volatile stores with NEON intrinsics not supported 18398 Info.flags = MachineMemOperand::MOStore; 18399 return true; 18400 } 18401 case Intrinsic::arm_mve_vld2q: 18402 case Intrinsic::arm_mve_vld4q: { 18403 Info.opc = ISD::INTRINSIC_W_CHAIN; 18404 // Conservatively set memVT to the entire set of vectors loaded. 18405 Type *VecTy = cast<StructType>(I.getType())->getElementType(1); 18406 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4; 18407 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 18408 Info.ptrVal = I.getArgOperand(0); 18409 Info.offset = 0; 18410 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 18411 // volatile loads with MVE intrinsics not supported 18412 Info.flags = MachineMemOperand::MOLoad; 18413 return true; 18414 } 18415 case Intrinsic::arm_mve_vst2q: 18416 case Intrinsic::arm_mve_vst4q: { 18417 Info.opc = ISD::INTRINSIC_VOID; 18418 // Conservatively set memVT to the entire set of vectors stored. 18419 Type *VecTy = I.getArgOperand(1)->getType(); 18420 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4; 18421 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 18422 Info.ptrVal = I.getArgOperand(0); 18423 Info.offset = 0; 18424 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 18425 // volatile stores with MVE intrinsics not supported 18426 Info.flags = MachineMemOperand::MOStore; 18427 return true; 18428 } 18429 case Intrinsic::arm_ldaex: 18430 case Intrinsic::arm_ldrex: { 18431 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18432 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 18433 Info.opc = ISD::INTRINSIC_W_CHAIN; 18434 Info.memVT = MVT::getVT(PtrTy->getElementType()); 18435 Info.ptrVal = I.getArgOperand(0); 18436 Info.offset = 0; 18437 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 18438 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 18439 return true; 18440 } 18441 case Intrinsic::arm_stlex: 18442 case Intrinsic::arm_strex: { 18443 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18444 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 18445 Info.opc = ISD::INTRINSIC_W_CHAIN; 18446 Info.memVT = MVT::getVT(PtrTy->getElementType()); 18447 Info.ptrVal = I.getArgOperand(1); 18448 Info.offset = 0; 18449 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 18450 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 18451 return true; 18452 } 18453 case Intrinsic::arm_stlexd: 18454 case Intrinsic::arm_strexd: 18455 Info.opc = ISD::INTRINSIC_W_CHAIN; 18456 Info.memVT = MVT::i64; 18457 Info.ptrVal = I.getArgOperand(2); 18458 Info.offset = 0; 18459 Info.align = Align(8); 18460 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 18461 return true; 18462 18463 case Intrinsic::arm_ldaexd: 18464 case Intrinsic::arm_ldrexd: 18465 Info.opc = ISD::INTRINSIC_W_CHAIN; 18466 Info.memVT = MVT::i64; 18467 Info.ptrVal = I.getArgOperand(0); 18468 Info.offset = 0; 18469 Info.align = Align(8); 18470 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 18471 return true; 18472 18473 default: 18474 break; 18475 } 18476 18477 return false; 18478 } 18479 18480 /// Returns true if it is beneficial to convert a load of a constant 18481 /// to just the constant itself. 18482 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 18483 Type *Ty) const { 18484 assert(Ty->isIntegerTy()); 18485 18486 unsigned Bits = Ty->getPrimitiveSizeInBits(); 18487 if (Bits == 0 || Bits > 32) 18488 return false; 18489 return true; 18490 } 18491 18492 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 18493 unsigned Index) const { 18494 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 18495 return false; 18496 18497 return (Index == 0 || Index == ResVT.getVectorNumElements()); 18498 } 18499 18500 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 18501 ARM_MB::MemBOpt Domain) const { 18502 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18503 18504 // First, if the target has no DMB, see what fallback we can use. 18505 if (!Subtarget->hasDataBarrier()) { 18506 // Some ARMv6 cpus can support data barriers with an mcr instruction. 18507 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 18508 // here. 18509 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 18510 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 18511 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 18512 Builder.getInt32(0), Builder.getInt32(7), 18513 Builder.getInt32(10), Builder.getInt32(5)}; 18514 return Builder.CreateCall(MCR, args); 18515 } else { 18516 // Instead of using barriers, atomic accesses on these subtargets use 18517 // libcalls. 18518 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 18519 } 18520 } else { 18521 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 18522 // Only a full system barrier exists in the M-class architectures. 18523 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 18524 Constant *CDomain = Builder.getInt32(Domain); 18525 return Builder.CreateCall(DMB, CDomain); 18526 } 18527 } 18528 18529 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 18530 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 18531 Instruction *Inst, 18532 AtomicOrdering Ord) const { 18533 switch (Ord) { 18534 case AtomicOrdering::NotAtomic: 18535 case AtomicOrdering::Unordered: 18536 llvm_unreachable("Invalid fence: unordered/non-atomic"); 18537 case AtomicOrdering::Monotonic: 18538 case AtomicOrdering::Acquire: 18539 return nullptr; // Nothing to do 18540 case AtomicOrdering::SequentiallyConsistent: 18541 if (!Inst->hasAtomicStore()) 18542 return nullptr; // Nothing to do 18543 LLVM_FALLTHROUGH; 18544 case AtomicOrdering::Release: 18545 case AtomicOrdering::AcquireRelease: 18546 if (Subtarget->preferISHSTBarriers()) 18547 return makeDMB(Builder, ARM_MB::ISHST); 18548 // FIXME: add a comment with a link to documentation justifying this. 18549 else 18550 return makeDMB(Builder, ARM_MB::ISH); 18551 } 18552 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 18553 } 18554 18555 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 18556 Instruction *Inst, 18557 AtomicOrdering Ord) const { 18558 switch (Ord) { 18559 case AtomicOrdering::NotAtomic: 18560 case AtomicOrdering::Unordered: 18561 llvm_unreachable("Invalid fence: unordered/not-atomic"); 18562 case AtomicOrdering::Monotonic: 18563 case AtomicOrdering::Release: 18564 return nullptr; // Nothing to do 18565 case AtomicOrdering::Acquire: 18566 case AtomicOrdering::AcquireRelease: 18567 case AtomicOrdering::SequentiallyConsistent: 18568 return makeDMB(Builder, ARM_MB::ISH); 18569 } 18570 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 18571 } 18572 18573 // Loads and stores less than 64-bits are already atomic; ones above that 18574 // are doomed anyway, so defer to the default libcall and blame the OS when 18575 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 18576 // anything for those. 18577 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 18578 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 18579 return (Size == 64) && !Subtarget->isMClass(); 18580 } 18581 18582 // Loads and stores less than 64-bits are already atomic; ones above that 18583 // are doomed anyway, so defer to the default libcall and blame the OS when 18584 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 18585 // anything for those. 18586 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 18587 // guarantee, see DDI0406C ARM architecture reference manual, 18588 // sections A8.8.72-74 LDRD) 18589 TargetLowering::AtomicExpansionKind 18590 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 18591 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 18592 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 18593 : AtomicExpansionKind::None; 18594 } 18595 18596 // For the real atomic operations, we have ldrex/strex up to 32 bits, 18597 // and up to 64 bits on the non-M profiles 18598 TargetLowering::AtomicExpansionKind 18599 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 18600 if (AI->isFloatingPointOperation()) 18601 return AtomicExpansionKind::CmpXChg; 18602 18603 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 18604 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 18605 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 18606 ? AtomicExpansionKind::LLSC 18607 : AtomicExpansionKind::None; 18608 } 18609 18610 TargetLowering::AtomicExpansionKind 18611 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 18612 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 18613 // implement cmpxchg without spilling. If the address being exchanged is also 18614 // on the stack and close enough to the spill slot, this can lead to a 18615 // situation where the monitor always gets cleared and the atomic operation 18616 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 18617 bool HasAtomicCmpXchg = 18618 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 18619 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 18620 return AtomicExpansionKind::LLSC; 18621 return AtomicExpansionKind::None; 18622 } 18623 18624 bool ARMTargetLowering::shouldInsertFencesForAtomic( 18625 const Instruction *I) const { 18626 return InsertFencesForAtomic; 18627 } 18628 18629 // This has so far only been implemented for MachO. 18630 bool ARMTargetLowering::useLoadStackGuardNode() const { 18631 return Subtarget->isTargetMachO(); 18632 } 18633 18634 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 18635 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18636 return TargetLowering::insertSSPDeclarations(M); 18637 18638 // MSVC CRT has a global variable holding security cookie. 18639 M.getOrInsertGlobal("__security_cookie", 18640 Type::getInt8PtrTy(M.getContext())); 18641 18642 // MSVC CRT has a function to validate security cookie. 18643 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 18644 "__security_check_cookie", Type::getVoidTy(M.getContext()), 18645 Type::getInt8PtrTy(M.getContext())); 18646 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 18647 F->addAttribute(1, Attribute::AttrKind::InReg); 18648 } 18649 18650 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 18651 // MSVC CRT has a global variable holding security cookie. 18652 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18653 return M.getGlobalVariable("__security_cookie"); 18654 return TargetLowering::getSDagStackGuard(M); 18655 } 18656 18657 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 18658 // MSVC CRT has a function to validate security cookie. 18659 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18660 return M.getFunction("__security_check_cookie"); 18661 return TargetLowering::getSSPStackGuardCheck(M); 18662 } 18663 18664 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 18665 unsigned &Cost) const { 18666 // If we do not have NEON, vector types are not natively supported. 18667 if (!Subtarget->hasNEON()) 18668 return false; 18669 18670 // Floating point values and vector values map to the same register file. 18671 // Therefore, although we could do a store extract of a vector type, this is 18672 // better to leave at float as we have more freedom in the addressing mode for 18673 // those. 18674 if (VectorTy->isFPOrFPVectorTy()) 18675 return false; 18676 18677 // If the index is unknown at compile time, this is very expensive to lower 18678 // and it is not possible to combine the store with the extract. 18679 if (!isa<ConstantInt>(Idx)) 18680 return false; 18681 18682 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 18683 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize(); 18684 // We can do a store + vector extract on any vector that fits perfectly in a D 18685 // or Q register. 18686 if (BitWidth == 64 || BitWidth == 128) { 18687 Cost = 0; 18688 return true; 18689 } 18690 return false; 18691 } 18692 18693 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 18694 return Subtarget->hasV6T2Ops(); 18695 } 18696 18697 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 18698 return Subtarget->hasV6T2Ops(); 18699 } 18700 18701 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 18702 return !Subtarget->hasMinSize() || Subtarget->isTargetWindows(); 18703 } 18704 18705 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 18706 AtomicOrdering Ord) const { 18707 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18708 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 18709 bool IsAcquire = isAcquireOrStronger(Ord); 18710 18711 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 18712 // intrinsic must return {i32, i32} and we have to recombine them into a 18713 // single i64 here. 18714 if (ValTy->getPrimitiveSizeInBits() == 64) { 18715 Intrinsic::ID Int = 18716 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 18717 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 18718 18719 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 18720 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 18721 18722 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18723 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18724 if (!Subtarget->isLittle()) 18725 std::swap (Lo, Hi); 18726 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18727 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18728 return Builder.CreateOr( 18729 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 18730 } 18731 18732 Type *Tys[] = { Addr->getType() }; 18733 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 18734 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 18735 18736 return Builder.CreateTruncOrBitCast( 18737 Builder.CreateCall(Ldrex, Addr), 18738 cast<PointerType>(Addr->getType())->getElementType()); 18739 } 18740 18741 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 18742 IRBuilder<> &Builder) const { 18743 if (!Subtarget->hasV7Ops()) 18744 return; 18745 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18746 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 18747 } 18748 18749 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 18750 Value *Addr, 18751 AtomicOrdering Ord) const { 18752 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18753 bool IsRelease = isReleaseOrStronger(Ord); 18754 18755 // Since the intrinsics must have legal type, the i64 intrinsics take two 18756 // parameters: "i32, i32". We must marshal Val into the appropriate form 18757 // before the call. 18758 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 18759 Intrinsic::ID Int = 18760 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 18761 Function *Strex = Intrinsic::getDeclaration(M, Int); 18762 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 18763 18764 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 18765 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 18766 if (!Subtarget->isLittle()) 18767 std::swap(Lo, Hi); 18768 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 18769 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 18770 } 18771 18772 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 18773 Type *Tys[] = { Addr->getType() }; 18774 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 18775 18776 return Builder.CreateCall( 18777 Strex, {Builder.CreateZExtOrBitCast( 18778 Val, Strex->getFunctionType()->getParamType(0)), 18779 Addr}); 18780 } 18781 18782 18783 bool ARMTargetLowering::alignLoopsWithOptSize() const { 18784 return Subtarget->isMClass(); 18785 } 18786 18787 /// A helper function for determining the number of interleaved accesses we 18788 /// will generate when lowering accesses of the given type. 18789 unsigned 18790 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 18791 const DataLayout &DL) const { 18792 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 18793 } 18794 18795 bool ARMTargetLowering::isLegalInterleavedAccessType( 18796 unsigned Factor, FixedVectorType *VecTy, const DataLayout &DL) const { 18797 18798 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 18799 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 18800 18801 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) 18802 return false; 18803 18804 // Ensure the vector doesn't have f16 elements. Even though we could do an 18805 // i16 vldN, we can't hold the f16 vectors and will end up converting via 18806 // f32. 18807 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy()) 18808 return false; 18809 if (Subtarget->hasMVEIntegerOps() && Factor == 3) 18810 return false; 18811 18812 // Ensure the number of vector elements is greater than 1. 18813 if (VecTy->getNumElements() < 2) 18814 return false; 18815 18816 // Ensure the element type is legal. 18817 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 18818 return false; 18819 18820 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 18821 // 128 will be split into multiple interleaved accesses. 18822 if (Subtarget->hasNEON() && VecSize == 64) 18823 return true; 18824 return VecSize % 128 == 0; 18825 } 18826 18827 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const { 18828 if (Subtarget->hasNEON()) 18829 return 4; 18830 if (Subtarget->hasMVEIntegerOps()) 18831 return MVEMaxSupportedInterleaveFactor; 18832 return TargetLoweringBase::getMaxSupportedInterleaveFactor(); 18833 } 18834 18835 /// Lower an interleaved load into a vldN intrinsic. 18836 /// 18837 /// E.g. Lower an interleaved load (Factor = 2): 18838 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 18839 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 18840 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 18841 /// 18842 /// Into: 18843 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 18844 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 18845 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 18846 bool ARMTargetLowering::lowerInterleavedLoad( 18847 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 18848 ArrayRef<unsigned> Indices, unsigned Factor) const { 18849 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 18850 "Invalid interleave factor"); 18851 assert(!Shuffles.empty() && "Empty shufflevector input"); 18852 assert(Shuffles.size() == Indices.size() && 18853 "Unmatched number of shufflevectors and indices"); 18854 18855 auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType()); 18856 Type *EltTy = VecTy->getElementType(); 18857 18858 const DataLayout &DL = LI->getModule()->getDataLayout(); 18859 18860 // Skip if we do not have NEON and skip illegal vector types. We can 18861 // "legalize" wide vector types into multiple interleaved accesses as long as 18862 // the vector types are divisible by 128. 18863 if (!isLegalInterleavedAccessType(Factor, VecTy, DL)) 18864 return false; 18865 18866 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 18867 18868 // A pointer vector can not be the return type of the ldN intrinsics. Need to 18869 // load integer vectors first and then convert to pointer vectors. 18870 if (EltTy->isPointerTy()) 18871 VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy); 18872 18873 IRBuilder<> Builder(LI); 18874 18875 // The base address of the load. 18876 Value *BaseAddr = LI->getPointerOperand(); 18877 18878 if (NumLoads > 1) { 18879 // If we're going to generate more than one load, reset the sub-vector type 18880 // to something legal. 18881 VecTy = FixedVectorType::get(VecTy->getElementType(), 18882 VecTy->getNumElements() / NumLoads); 18883 18884 // We will compute the pointer operand of each load from the original base 18885 // address using GEPs. Cast the base address to a pointer to the scalar 18886 // element type. 18887 BaseAddr = Builder.CreateBitCast( 18888 BaseAddr, 18889 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())); 18890 } 18891 18892 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 18893 18894 auto createLoadIntrinsic = [&](Value *BaseAddr) { 18895 if (Subtarget->hasNEON()) { 18896 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 18897 Type *Tys[] = {VecTy, Int8Ptr}; 18898 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 18899 Intrinsic::arm_neon_vld3, 18900 Intrinsic::arm_neon_vld4}; 18901 Function *VldnFunc = 18902 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 18903 18904 SmallVector<Value *, 2> Ops; 18905 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 18906 Ops.push_back(Builder.getInt32(LI->getAlignment())); 18907 18908 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 18909 } else { 18910 assert((Factor == 2 || Factor == 4) && 18911 "expected interleave factor of 2 or 4 for MVE"); 18912 Intrinsic::ID LoadInts = 18913 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q; 18914 Type *VecEltTy = 18915 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()); 18916 Type *Tys[] = {VecTy, VecEltTy}; 18917 Function *VldnFunc = 18918 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys); 18919 18920 SmallVector<Value *, 2> Ops; 18921 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy)); 18922 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 18923 } 18924 }; 18925 18926 // Holds sub-vectors extracted from the load intrinsic return values. The 18927 // sub-vectors are associated with the shufflevector instructions they will 18928 // replace. 18929 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 18930 18931 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 18932 // If we're generating more than one load, compute the base address of 18933 // subsequent loads as an offset from the previous. 18934 if (LoadCount > 0) 18935 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr, 18936 VecTy->getNumElements() * Factor); 18937 18938 CallInst *VldN = createLoadIntrinsic(BaseAddr); 18939 18940 // Replace uses of each shufflevector with the corresponding vector loaded 18941 // by ldN. 18942 for (unsigned i = 0; i < Shuffles.size(); i++) { 18943 ShuffleVectorInst *SV = Shuffles[i]; 18944 unsigned Index = Indices[i]; 18945 18946 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 18947 18948 // Convert the integer vector to pointer vector if the element is pointer. 18949 if (EltTy->isPointerTy()) 18950 SubVec = Builder.CreateIntToPtr( 18951 SubVec, 18952 FixedVectorType::get(SV->getType()->getElementType(), VecTy)); 18953 18954 SubVecs[SV].push_back(SubVec); 18955 } 18956 } 18957 18958 // Replace uses of the shufflevector instructions with the sub-vectors 18959 // returned by the load intrinsic. If a shufflevector instruction is 18960 // associated with more than one sub-vector, those sub-vectors will be 18961 // concatenated into a single wide vector. 18962 for (ShuffleVectorInst *SVI : Shuffles) { 18963 auto &SubVec = SubVecs[SVI]; 18964 auto *WideVec = 18965 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 18966 SVI->replaceAllUsesWith(WideVec); 18967 } 18968 18969 return true; 18970 } 18971 18972 /// Lower an interleaved store into a vstN intrinsic. 18973 /// 18974 /// E.g. Lower an interleaved store (Factor = 3): 18975 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 18976 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 18977 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 18978 /// 18979 /// Into: 18980 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 18981 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 18982 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 18983 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 18984 /// 18985 /// Note that the new shufflevectors will be removed and we'll only generate one 18986 /// vst3 instruction in CodeGen. 18987 /// 18988 /// Example for a more general valid mask (Factor 3). Lower: 18989 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 18990 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 18991 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 18992 /// 18993 /// Into: 18994 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 18995 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 18996 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 18997 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 18998 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 18999 ShuffleVectorInst *SVI, 19000 unsigned Factor) const { 19001 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 19002 "Invalid interleave factor"); 19003 19004 auto *VecTy = cast<FixedVectorType>(SVI->getType()); 19005 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store"); 19006 19007 unsigned LaneLen = VecTy->getNumElements() / Factor; 19008 Type *EltTy = VecTy->getElementType(); 19009 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen); 19010 19011 const DataLayout &DL = SI->getModule()->getDataLayout(); 19012 19013 // Skip if we do not have NEON and skip illegal vector types. We can 19014 // "legalize" wide vector types into multiple interleaved accesses as long as 19015 // the vector types are divisible by 128. 19016 if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL)) 19017 return false; 19018 19019 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 19020 19021 Value *Op0 = SVI->getOperand(0); 19022 Value *Op1 = SVI->getOperand(1); 19023 IRBuilder<> Builder(SI); 19024 19025 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 19026 // vectors to integer vectors. 19027 if (EltTy->isPointerTy()) { 19028 Type *IntTy = DL.getIntPtrType(EltTy); 19029 19030 // Convert to the corresponding integer vector. 19031 auto *IntVecTy = 19032 FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType())); 19033 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 19034 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 19035 19036 SubVecTy = FixedVectorType::get(IntTy, LaneLen); 19037 } 19038 19039 // The base address of the store. 19040 Value *BaseAddr = SI->getPointerOperand(); 19041 19042 if (NumStores > 1) { 19043 // If we're going to generate more than one store, reset the lane length 19044 // and sub-vector type to something legal. 19045 LaneLen /= NumStores; 19046 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen); 19047 19048 // We will compute the pointer operand of each store from the original base 19049 // address using GEPs. Cast the base address to a pointer to the scalar 19050 // element type. 19051 BaseAddr = Builder.CreateBitCast( 19052 BaseAddr, 19053 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())); 19054 } 19055 19056 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 19057 19058 auto Mask = SVI->getShuffleMask(); 19059 19060 auto createStoreIntrinsic = [&](Value *BaseAddr, 19061 SmallVectorImpl<Value *> &Shuffles) { 19062 if (Subtarget->hasNEON()) { 19063 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 19064 Intrinsic::arm_neon_vst3, 19065 Intrinsic::arm_neon_vst4}; 19066 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 19067 Type *Tys[] = {Int8Ptr, SubVecTy}; 19068 19069 Function *VstNFunc = Intrinsic::getDeclaration( 19070 SI->getModule(), StoreInts[Factor - 2], Tys); 19071 19072 SmallVector<Value *, 6> Ops; 19073 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 19074 for (auto S : Shuffles) 19075 Ops.push_back(S); 19076 Ops.push_back(Builder.getInt32(SI->getAlignment())); 19077 Builder.CreateCall(VstNFunc, Ops); 19078 } else { 19079 assert((Factor == 2 || Factor == 4) && 19080 "expected interleave factor of 2 or 4 for MVE"); 19081 Intrinsic::ID StoreInts = 19082 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q; 19083 Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo( 19084 SI->getPointerAddressSpace()); 19085 Type *Tys[] = {EltPtrTy, SubVecTy}; 19086 Function *VstNFunc = 19087 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys); 19088 19089 SmallVector<Value *, 6> Ops; 19090 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy)); 19091 for (auto S : Shuffles) 19092 Ops.push_back(S); 19093 for (unsigned F = 0; F < Factor; F++) { 19094 Ops.push_back(Builder.getInt32(F)); 19095 Builder.CreateCall(VstNFunc, Ops); 19096 Ops.pop_back(); 19097 } 19098 } 19099 }; 19100 19101 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 19102 // If we generating more than one store, we compute the base address of 19103 // subsequent stores as an offset from the previous. 19104 if (StoreCount > 0) 19105 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(), 19106 BaseAddr, LaneLen * Factor); 19107 19108 SmallVector<Value *, 4> Shuffles; 19109 19110 // Split the shufflevector operands into sub vectors for the new vstN call. 19111 for (unsigned i = 0; i < Factor; i++) { 19112 unsigned IdxI = StoreCount * LaneLen * Factor + i; 19113 if (Mask[IdxI] >= 0) { 19114 Shuffles.push_back(Builder.CreateShuffleVector( 19115 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0))); 19116 } else { 19117 unsigned StartMask = 0; 19118 for (unsigned j = 1; j < LaneLen; j++) { 19119 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 19120 if (Mask[IdxJ * Factor + IdxI] >= 0) { 19121 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 19122 break; 19123 } 19124 } 19125 // Note: If all elements in a chunk are undefs, StartMask=0! 19126 // Note: Filling undef gaps with random elements is ok, since 19127 // those elements were being written anyway (with undefs). 19128 // In the case of all undefs we're defaulting to using elems from 0 19129 // Note: StartMask cannot be negative, it's checked in 19130 // isReInterleaveMask 19131 Shuffles.push_back(Builder.CreateShuffleVector( 19132 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0))); 19133 } 19134 } 19135 19136 createStoreIntrinsic(BaseAddr, Shuffles); 19137 } 19138 return true; 19139 } 19140 19141 enum HABaseType { 19142 HA_UNKNOWN = 0, 19143 HA_FLOAT, 19144 HA_DOUBLE, 19145 HA_VECT64, 19146 HA_VECT128 19147 }; 19148 19149 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 19150 uint64_t &Members) { 19151 if (auto *ST = dyn_cast<StructType>(Ty)) { 19152 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 19153 uint64_t SubMembers = 0; 19154 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 19155 return false; 19156 Members += SubMembers; 19157 } 19158 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 19159 uint64_t SubMembers = 0; 19160 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 19161 return false; 19162 Members += SubMembers * AT->getNumElements(); 19163 } else if (Ty->isFloatTy()) { 19164 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 19165 return false; 19166 Members = 1; 19167 Base = HA_FLOAT; 19168 } else if (Ty->isDoubleTy()) { 19169 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 19170 return false; 19171 Members = 1; 19172 Base = HA_DOUBLE; 19173 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 19174 Members = 1; 19175 switch (Base) { 19176 case HA_FLOAT: 19177 case HA_DOUBLE: 19178 return false; 19179 case HA_VECT64: 19180 return VT->getPrimitiveSizeInBits().getFixedSize() == 64; 19181 case HA_VECT128: 19182 return VT->getPrimitiveSizeInBits().getFixedSize() == 128; 19183 case HA_UNKNOWN: 19184 switch (VT->getPrimitiveSizeInBits().getFixedSize()) { 19185 case 64: 19186 Base = HA_VECT64; 19187 return true; 19188 case 128: 19189 Base = HA_VECT128; 19190 return true; 19191 default: 19192 return false; 19193 } 19194 } 19195 } 19196 19197 return (Members > 0 && Members <= 4); 19198 } 19199 19200 /// Return the correct alignment for the current calling convention. 19201 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 19202 DataLayout DL) const { 19203 const Align ABITypeAlign = DL.getABITypeAlign(ArgTy); 19204 if (!ArgTy->isVectorTy()) 19205 return ABITypeAlign; 19206 19207 // Avoid over-aligning vector parameters. It would require realigning the 19208 // stack and waste space for no real benefit. 19209 return std::min(ABITypeAlign, DL.getStackAlignment()); 19210 } 19211 19212 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 19213 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 19214 /// passing according to AAPCS rules. 19215 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 19216 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 19217 if (getEffectiveCallingConv(CallConv, isVarArg) != 19218 CallingConv::ARM_AAPCS_VFP) 19219 return false; 19220 19221 HABaseType Base = HA_UNKNOWN; 19222 uint64_t Members = 0; 19223 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 19224 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 19225 19226 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 19227 return IsHA || IsIntArray; 19228 } 19229 19230 Register ARMTargetLowering::getExceptionPointerRegister( 19231 const Constant *PersonalityFn) const { 19232 // Platforms which do not use SjLj EH may return values in these registers 19233 // via the personality function. 19234 return Subtarget->useSjLjEH() ? Register() : ARM::R0; 19235 } 19236 19237 Register ARMTargetLowering::getExceptionSelectorRegister( 19238 const Constant *PersonalityFn) const { 19239 // Platforms which do not use SjLj EH may return values in these registers 19240 // via the personality function. 19241 return Subtarget->useSjLjEH() ? Register() : ARM::R1; 19242 } 19243 19244 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 19245 // Update IsSplitCSR in ARMFunctionInfo. 19246 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 19247 AFI->setIsSplitCSR(true); 19248 } 19249 19250 void ARMTargetLowering::insertCopiesSplitCSR( 19251 MachineBasicBlock *Entry, 19252 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 19253 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 19254 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 19255 if (!IStart) 19256 return; 19257 19258 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 19259 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 19260 MachineBasicBlock::iterator MBBI = Entry->begin(); 19261 for (const MCPhysReg *I = IStart; *I; ++I) { 19262 const TargetRegisterClass *RC = nullptr; 19263 if (ARM::GPRRegClass.contains(*I)) 19264 RC = &ARM::GPRRegClass; 19265 else if (ARM::DPRRegClass.contains(*I)) 19266 RC = &ARM::DPRRegClass; 19267 else 19268 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 19269 19270 Register NewVR = MRI->createVirtualRegister(RC); 19271 // Create copy from CSR to a virtual register. 19272 // FIXME: this currently does not emit CFI pseudo-instructions, it works 19273 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 19274 // nounwind. If we want to generalize this later, we may need to emit 19275 // CFI pseudo-instructions. 19276 assert(Entry->getParent()->getFunction().hasFnAttribute( 19277 Attribute::NoUnwind) && 19278 "Function should be nounwind in insertCopiesSplitCSR!"); 19279 Entry->addLiveIn(*I); 19280 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 19281 .addReg(*I); 19282 19283 // Insert the copy-back instructions right before the terminator. 19284 for (auto *Exit : Exits) 19285 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 19286 TII->get(TargetOpcode::COPY), *I) 19287 .addReg(NewVR); 19288 } 19289 } 19290 19291 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 19292 MF.getFrameInfo().computeMaxCallFrameSize(MF); 19293 TargetLoweringBase::finalizeLowering(MF); 19294 } 19295