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::VADDVs: return "ARMISD::VADDVs"; 1722 case ARMISD::VADDVu: return "ARMISD::VADDVu"; 1723 case ARMISD::VADDVps: return "ARMISD::VADDVps"; 1724 case ARMISD::VADDVpu: return "ARMISD::VADDVpu"; 1725 case ARMISD::VADDLVs: return "ARMISD::VADDLVs"; 1726 case ARMISD::VADDLVu: return "ARMISD::VADDLVu"; 1727 case ARMISD::VADDLVAs: return "ARMISD::VADDLVAs"; 1728 case ARMISD::VADDLVAu: return "ARMISD::VADDLVAu"; 1729 case ARMISD::VADDLVps: return "ARMISD::VADDLVps"; 1730 case ARMISD::VADDLVpu: return "ARMISD::VADDLVpu"; 1731 case ARMISD::VADDLVAps: return "ARMISD::VADDLVAps"; 1732 case ARMISD::VADDLVApu: return "ARMISD::VADDLVApu"; 1733 case ARMISD::VMLAVs: return "ARMISD::VMLAVs"; 1734 case ARMISD::VMLAVu: return "ARMISD::VMLAVu"; 1735 case ARMISD::VMLAVps: return "ARMISD::VMLAVps"; 1736 case ARMISD::VMLAVpu: return "ARMISD::VMLAVpu"; 1737 case ARMISD::VMLALVs: return "ARMISD::VMLALVs"; 1738 case ARMISD::VMLALVu: return "ARMISD::VMLALVu"; 1739 case ARMISD::VMLALVps: return "ARMISD::VMLALVps"; 1740 case ARMISD::VMLALVpu: return "ARMISD::VMLALVpu"; 1741 case ARMISD::VMLALVAs: return "ARMISD::VMLALVAs"; 1742 case ARMISD::VMLALVAu: return "ARMISD::VMLALVAu"; 1743 case ARMISD::VMLALVAps: return "ARMISD::VMLALVAps"; 1744 case ARMISD::VMLALVApu: return "ARMISD::VMLALVApu"; 1745 case ARMISD::VMINVu: return "ARMISD::VMINVu"; 1746 case ARMISD::VMINVs: return "ARMISD::VMINVs"; 1747 case ARMISD::VMAXVu: return "ARMISD::VMAXVu"; 1748 case ARMISD::VMAXVs: return "ARMISD::VMAXVs"; 1749 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1750 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1751 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1752 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1753 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1754 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1755 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1756 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1757 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1758 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1759 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1760 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1761 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1762 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1763 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1764 case ARMISD::QADD16b: return "ARMISD::QADD16b"; 1765 case ARMISD::QSUB16b: return "ARMISD::QSUB16b"; 1766 case ARMISD::QADD8b: return "ARMISD::QADD8b"; 1767 case ARMISD::QSUB8b: return "ARMISD::QSUB8b"; 1768 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1769 case ARMISD::BFI: return "ARMISD::BFI"; 1770 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1771 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1772 case ARMISD::VBSP: return "ARMISD::VBSP"; 1773 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1774 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1775 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1776 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1777 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1778 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1779 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1780 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1781 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1782 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1783 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1784 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1785 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1786 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1787 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1788 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1789 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1790 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1791 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1792 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1793 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1794 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1795 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1796 case ARMISD::WLS: return "ARMISD::WLS"; 1797 case ARMISD::LE: return "ARMISD::LE"; 1798 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1799 case ARMISD::CSINV: return "ARMISD::CSINV"; 1800 case ARMISD::CSNEG: return "ARMISD::CSNEG"; 1801 case ARMISD::CSINC: return "ARMISD::CSINC"; 1802 } 1803 return nullptr; 1804 } 1805 1806 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1807 EVT VT) const { 1808 if (!VT.isVector()) 1809 return getPointerTy(DL); 1810 1811 // MVE has a predicate register. 1812 if (Subtarget->hasMVEIntegerOps() && 1813 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1814 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1815 return VT.changeVectorElementTypeToInteger(); 1816 } 1817 1818 /// getRegClassFor - Return the register class that should be used for the 1819 /// specified value type. 1820 const TargetRegisterClass * 1821 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1822 (void)isDivergent; 1823 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1824 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1825 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1826 // MVE Q registers. 1827 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1828 if (VT == MVT::v4i64) 1829 return &ARM::QQPRRegClass; 1830 if (VT == MVT::v8i64) 1831 return &ARM::QQQQPRRegClass; 1832 } 1833 return TargetLowering::getRegClassFor(VT); 1834 } 1835 1836 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1837 // source/dest is aligned and the copy size is large enough. We therefore want 1838 // to align such objects passed to memory intrinsics. 1839 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1840 unsigned &PrefAlign) const { 1841 if (!isa<MemIntrinsic>(CI)) 1842 return false; 1843 MinSize = 8; 1844 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1845 // cycle faster than 4-byte aligned LDM. 1846 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1847 return true; 1848 } 1849 1850 // Create a fast isel object. 1851 FastISel * 1852 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1853 const TargetLibraryInfo *libInfo) const { 1854 return ARM::createFastISel(funcInfo, libInfo); 1855 } 1856 1857 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1858 unsigned NumVals = N->getNumValues(); 1859 if (!NumVals) 1860 return Sched::RegPressure; 1861 1862 for (unsigned i = 0; i != NumVals; ++i) { 1863 EVT VT = N->getValueType(i); 1864 if (VT == MVT::Glue || VT == MVT::Other) 1865 continue; 1866 if (VT.isFloatingPoint() || VT.isVector()) 1867 return Sched::ILP; 1868 } 1869 1870 if (!N->isMachineOpcode()) 1871 return Sched::RegPressure; 1872 1873 // Load are scheduled for latency even if there instruction itinerary 1874 // is not available. 1875 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1876 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1877 1878 if (MCID.getNumDefs() == 0) 1879 return Sched::RegPressure; 1880 if (!Itins->isEmpty() && 1881 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1882 return Sched::ILP; 1883 1884 return Sched::RegPressure; 1885 } 1886 1887 //===----------------------------------------------------------------------===// 1888 // Lowering Code 1889 //===----------------------------------------------------------------------===// 1890 1891 static bool isSRL16(const SDValue &Op) { 1892 if (Op.getOpcode() != ISD::SRL) 1893 return false; 1894 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1895 return Const->getZExtValue() == 16; 1896 return false; 1897 } 1898 1899 static bool isSRA16(const SDValue &Op) { 1900 if (Op.getOpcode() != ISD::SRA) 1901 return false; 1902 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1903 return Const->getZExtValue() == 16; 1904 return false; 1905 } 1906 1907 static bool isSHL16(const SDValue &Op) { 1908 if (Op.getOpcode() != ISD::SHL) 1909 return false; 1910 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1911 return Const->getZExtValue() == 16; 1912 return false; 1913 } 1914 1915 // Check for a signed 16-bit value. We special case SRA because it makes it 1916 // more simple when also looking for SRAs that aren't sign extending a 1917 // smaller value. Without the check, we'd need to take extra care with 1918 // checking order for some operations. 1919 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1920 if (isSRA16(Op)) 1921 return isSHL16(Op.getOperand(0)); 1922 return DAG.ComputeNumSignBits(Op) == 17; 1923 } 1924 1925 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1926 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1927 switch (CC) { 1928 default: llvm_unreachable("Unknown condition code!"); 1929 case ISD::SETNE: return ARMCC::NE; 1930 case ISD::SETEQ: return ARMCC::EQ; 1931 case ISD::SETGT: return ARMCC::GT; 1932 case ISD::SETGE: return ARMCC::GE; 1933 case ISD::SETLT: return ARMCC::LT; 1934 case ISD::SETLE: return ARMCC::LE; 1935 case ISD::SETUGT: return ARMCC::HI; 1936 case ISD::SETUGE: return ARMCC::HS; 1937 case ISD::SETULT: return ARMCC::LO; 1938 case ISD::SETULE: return ARMCC::LS; 1939 } 1940 } 1941 1942 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1943 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1944 ARMCC::CondCodes &CondCode2) { 1945 CondCode2 = ARMCC::AL; 1946 switch (CC) { 1947 default: llvm_unreachable("Unknown FP condition!"); 1948 case ISD::SETEQ: 1949 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1950 case ISD::SETGT: 1951 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1952 case ISD::SETGE: 1953 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1954 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1955 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1956 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1957 case ISD::SETO: CondCode = ARMCC::VC; break; 1958 case ISD::SETUO: CondCode = ARMCC::VS; break; 1959 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1960 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1961 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1962 case ISD::SETLT: 1963 case ISD::SETULT: CondCode = ARMCC::LT; break; 1964 case ISD::SETLE: 1965 case ISD::SETULE: CondCode = ARMCC::LE; break; 1966 case ISD::SETNE: 1967 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1968 } 1969 } 1970 1971 //===----------------------------------------------------------------------===// 1972 // Calling Convention Implementation 1973 //===----------------------------------------------------------------------===// 1974 1975 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1976 /// account presence of floating point hardware and calling convention 1977 /// limitations, such as support for variadic functions. 1978 CallingConv::ID 1979 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1980 bool isVarArg) const { 1981 switch (CC) { 1982 default: 1983 report_fatal_error("Unsupported calling convention"); 1984 case CallingConv::ARM_AAPCS: 1985 case CallingConv::ARM_APCS: 1986 case CallingConv::GHC: 1987 case CallingConv::CFGuard_Check: 1988 return CC; 1989 case CallingConv::PreserveMost: 1990 return CallingConv::PreserveMost; 1991 case CallingConv::ARM_AAPCS_VFP: 1992 case CallingConv::Swift: 1993 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1994 case CallingConv::C: 1995 if (!Subtarget->isAAPCS_ABI()) 1996 return CallingConv::ARM_APCS; 1997 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1998 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1999 !isVarArg) 2000 return CallingConv::ARM_AAPCS_VFP; 2001 else 2002 return CallingConv::ARM_AAPCS; 2003 case CallingConv::Fast: 2004 case CallingConv::CXX_FAST_TLS: 2005 if (!Subtarget->isAAPCS_ABI()) { 2006 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 2007 return CallingConv::Fast; 2008 return CallingConv::ARM_APCS; 2009 } else if (Subtarget->hasVFP2Base() && 2010 !Subtarget->isThumb1Only() && !isVarArg) 2011 return CallingConv::ARM_AAPCS_VFP; 2012 else 2013 return CallingConv::ARM_AAPCS; 2014 } 2015 } 2016 2017 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2018 bool isVarArg) const { 2019 return CCAssignFnForNode(CC, false, isVarArg); 2020 } 2021 2022 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 2023 bool isVarArg) const { 2024 return CCAssignFnForNode(CC, true, isVarArg); 2025 } 2026 2027 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 2028 /// CallingConvention. 2029 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 2030 bool Return, 2031 bool isVarArg) const { 2032 switch (getEffectiveCallingConv(CC, isVarArg)) { 2033 default: 2034 report_fatal_error("Unsupported calling convention"); 2035 case CallingConv::ARM_APCS: 2036 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 2037 case CallingConv::ARM_AAPCS: 2038 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 2039 case CallingConv::ARM_AAPCS_VFP: 2040 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 2041 case CallingConv::Fast: 2042 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 2043 case CallingConv::GHC: 2044 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 2045 case CallingConv::PreserveMost: 2046 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 2047 case CallingConv::CFGuard_Check: 2048 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check); 2049 } 2050 } 2051 2052 SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG, 2053 MVT LocVT, MVT ValVT, SDValue Val) const { 2054 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()), 2055 Val); 2056 if (Subtarget->hasFullFP16()) { 2057 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val); 2058 } else { 2059 Val = DAG.getNode(ISD::TRUNCATE, dl, 2060 MVT::getIntegerVT(ValVT.getSizeInBits()), Val); 2061 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val); 2062 } 2063 return Val; 2064 } 2065 2066 SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG, 2067 MVT LocVT, MVT ValVT, 2068 SDValue Val) const { 2069 if (Subtarget->hasFullFP16()) { 2070 Val = DAG.getNode(ARMISD::VMOVrh, dl, 2071 MVT::getIntegerVT(LocVT.getSizeInBits()), Val); 2072 } else { 2073 Val = DAG.getNode(ISD::BITCAST, dl, 2074 MVT::getIntegerVT(ValVT.getSizeInBits()), Val); 2075 Val = DAG.getNode(ISD::ZERO_EXTEND, dl, 2076 MVT::getIntegerVT(LocVT.getSizeInBits()), Val); 2077 } 2078 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val); 2079 } 2080 2081 /// LowerCallResult - Lower the result values of a call into the 2082 /// appropriate copies out of appropriate physical registers. 2083 SDValue ARMTargetLowering::LowerCallResult( 2084 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2085 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 2086 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2087 SDValue ThisVal) const { 2088 // Assign locations to each value returned by this call. 2089 SmallVector<CCValAssign, 16> RVLocs; 2090 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2091 *DAG.getContext()); 2092 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 2093 2094 // Copy all of the result registers out of their specified physreg. 2095 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2096 CCValAssign VA = RVLocs[i]; 2097 2098 // Pass 'this' value directly from the argument to return value, to avoid 2099 // reg unit interference 2100 if (i == 0 && isThisReturn) { 2101 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 2102 "unexpected return calling convention register assignment"); 2103 InVals.push_back(ThisVal); 2104 continue; 2105 } 2106 2107 SDValue Val; 2108 if (VA.needsCustom() && 2109 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) { 2110 // Handle f64 or half of a v2f64. 2111 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2112 InFlag); 2113 Chain = Lo.getValue(1); 2114 InFlag = Lo.getValue(2); 2115 VA = RVLocs[++i]; // skip ahead to next loc 2116 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2117 InFlag); 2118 Chain = Hi.getValue(1); 2119 InFlag = Hi.getValue(2); 2120 if (!Subtarget->isLittle()) 2121 std::swap (Lo, Hi); 2122 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2123 2124 if (VA.getLocVT() == MVT::v2f64) { 2125 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 2126 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2127 DAG.getConstant(0, dl, MVT::i32)); 2128 2129 VA = RVLocs[++i]; // skip ahead to next loc 2130 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2131 Chain = Lo.getValue(1); 2132 InFlag = Lo.getValue(2); 2133 VA = RVLocs[++i]; // skip ahead to next loc 2134 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2135 Chain = Hi.getValue(1); 2136 InFlag = Hi.getValue(2); 2137 if (!Subtarget->isLittle()) 2138 std::swap (Lo, Hi); 2139 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2140 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2141 DAG.getConstant(1, dl, MVT::i32)); 2142 } 2143 } else { 2144 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 2145 InFlag); 2146 Chain = Val.getValue(1); 2147 InFlag = Val.getValue(2); 2148 } 2149 2150 switch (VA.getLocInfo()) { 2151 default: llvm_unreachable("Unknown loc info!"); 2152 case CCValAssign::Full: break; 2153 case CCValAssign::BCvt: 2154 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 2155 break; 2156 } 2157 2158 // f16 arguments have their size extended to 4 bytes and passed as if they 2159 // had been copied to the LSBs of a 32-bit register. 2160 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 2161 if (VA.needsCustom() && 2162 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) 2163 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val); 2164 2165 InVals.push_back(Val); 2166 } 2167 2168 return Chain; 2169 } 2170 2171 /// LowerMemOpCallTo - Store the argument to the stack. 2172 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 2173 SDValue Arg, const SDLoc &dl, 2174 SelectionDAG &DAG, 2175 const CCValAssign &VA, 2176 ISD::ArgFlagsTy Flags) const { 2177 unsigned LocMemOffset = VA.getLocMemOffset(); 2178 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2179 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 2180 StackPtr, PtrOff); 2181 return DAG.getStore( 2182 Chain, dl, Arg, PtrOff, 2183 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 2184 } 2185 2186 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 2187 SDValue Chain, SDValue &Arg, 2188 RegsToPassVector &RegsToPass, 2189 CCValAssign &VA, CCValAssign &NextVA, 2190 SDValue &StackPtr, 2191 SmallVectorImpl<SDValue> &MemOpChains, 2192 ISD::ArgFlagsTy Flags) const { 2193 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2194 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2195 unsigned id = Subtarget->isLittle() ? 0 : 1; 2196 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 2197 2198 if (NextVA.isRegLoc()) 2199 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 2200 else { 2201 assert(NextVA.isMemLoc()); 2202 if (!StackPtr.getNode()) 2203 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 2204 getPointerTy(DAG.getDataLayout())); 2205 2206 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 2207 dl, DAG, NextVA, 2208 Flags)); 2209 } 2210 } 2211 2212 /// LowerCall - Lowering a call into a callseq_start <- 2213 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 2214 /// nodes. 2215 SDValue 2216 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2217 SmallVectorImpl<SDValue> &InVals) const { 2218 SelectionDAG &DAG = CLI.DAG; 2219 SDLoc &dl = CLI.DL; 2220 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2221 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2222 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2223 SDValue Chain = CLI.Chain; 2224 SDValue Callee = CLI.Callee; 2225 bool &isTailCall = CLI.IsTailCall; 2226 CallingConv::ID CallConv = CLI.CallConv; 2227 bool doesNotRet = CLI.DoesNotReturn; 2228 bool isVarArg = CLI.IsVarArg; 2229 2230 MachineFunction &MF = DAG.getMachineFunction(); 2231 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2232 MachineFunction::CallSiteInfo CSInfo; 2233 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2234 bool isThisReturn = false; 2235 bool isCmseNSCall = false; 2236 bool PreferIndirect = false; 2237 2238 // Determine whether this is a non-secure function call. 2239 if (CLI.CB && CLI.CB->getAttributes().hasFnAttribute("cmse_nonsecure_call")) 2240 isCmseNSCall = true; 2241 2242 // Disable tail calls if they're not supported. 2243 if (!Subtarget->supportsTailCall()) 2244 isTailCall = false; 2245 2246 // For both the non-secure calls and the returns from a CMSE entry function, 2247 // the function needs to do some extra work afte r the call, or before the 2248 // return, respectively, thus it cannot end with atail call 2249 if (isCmseNSCall || AFI->isCmseNSEntryFunction()) 2250 isTailCall = false; 2251 2252 if (isa<GlobalAddressSDNode>(Callee)) { 2253 // If we're optimizing for minimum size and the function is called three or 2254 // more times in this block, we can improve codesize by calling indirectly 2255 // as BLXr has a 16-bit encoding. 2256 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2257 if (CLI.CB) { 2258 auto *BB = CLI.CB->getParent(); 2259 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2260 count_if(GV->users(), [&BB](const User *U) { 2261 return isa<Instruction>(U) && 2262 cast<Instruction>(U)->getParent() == BB; 2263 }) > 2; 2264 } 2265 } 2266 if (isTailCall) { 2267 // Check if it's really possible to do a tail call. 2268 isTailCall = IsEligibleForTailCallOptimization( 2269 Callee, CallConv, isVarArg, isStructRet, 2270 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2271 PreferIndirect); 2272 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall()) 2273 report_fatal_error("failed to perform tail call elimination on a call " 2274 "site marked musttail"); 2275 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2276 // detected sibcalls. 2277 if (isTailCall) 2278 ++NumTailCalls; 2279 } 2280 2281 // Analyze operands of the call, assigning locations to each operand. 2282 SmallVector<CCValAssign, 16> ArgLocs; 2283 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2284 *DAG.getContext()); 2285 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2286 2287 // Get a count of how many bytes are to be pushed on the stack. 2288 unsigned NumBytes = CCInfo.getNextStackOffset(); 2289 2290 if (isTailCall) { 2291 // For tail calls, memory operands are available in our caller's stack. 2292 NumBytes = 0; 2293 } else { 2294 // Adjust the stack pointer for the new arguments... 2295 // These operations are automatically eliminated by the prolog/epilog pass 2296 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2297 } 2298 2299 SDValue StackPtr = 2300 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2301 2302 RegsToPassVector RegsToPass; 2303 SmallVector<SDValue, 8> MemOpChains; 2304 2305 // Walk the register/memloc assignments, inserting copies/loads. In the case 2306 // of tail call optimization, arguments are handled later. 2307 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2308 i != e; 2309 ++i, ++realArgIdx) { 2310 CCValAssign &VA = ArgLocs[i]; 2311 SDValue Arg = OutVals[realArgIdx]; 2312 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2313 bool isByVal = Flags.isByVal(); 2314 2315 // Promote the value if needed. 2316 switch (VA.getLocInfo()) { 2317 default: llvm_unreachable("Unknown loc info!"); 2318 case CCValAssign::Full: break; 2319 case CCValAssign::SExt: 2320 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2321 break; 2322 case CCValAssign::ZExt: 2323 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2324 break; 2325 case CCValAssign::AExt: 2326 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2327 break; 2328 case CCValAssign::BCvt: 2329 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2330 break; 2331 } 2332 2333 // f16 arguments have their size extended to 4 bytes and passed as if they 2334 // had been copied to the LSBs of a 32-bit register. 2335 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 2336 if (VA.needsCustom() && 2337 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) { 2338 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg); 2339 } else { 2340 // f16 arguments could have been extended prior to argument lowering. 2341 // Mask them arguments if this is a CMSE nonsecure call. 2342 auto ArgVT = Outs[realArgIdx].ArgVT; 2343 if (isCmseNSCall && (ArgVT == MVT::f16)) { 2344 auto LocBits = VA.getLocVT().getSizeInBits(); 2345 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits()); 2346 SDValue Mask = 2347 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits)); 2348 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg); 2349 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask); 2350 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2351 } 2352 } 2353 2354 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2355 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) { 2356 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2357 DAG.getConstant(0, dl, MVT::i32)); 2358 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2359 DAG.getConstant(1, dl, MVT::i32)); 2360 2361 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i], 2362 StackPtr, MemOpChains, Flags); 2363 2364 VA = ArgLocs[++i]; // skip ahead to next loc 2365 if (VA.isRegLoc()) { 2366 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i], 2367 StackPtr, MemOpChains, Flags); 2368 } else { 2369 assert(VA.isMemLoc()); 2370 2371 MemOpChains.push_back( 2372 LowerMemOpCallTo(Chain, StackPtr, Op1, dl, DAG, VA, Flags)); 2373 } 2374 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) { 2375 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2376 StackPtr, MemOpChains, Flags); 2377 } else if (VA.isRegLoc()) { 2378 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2379 Outs[0].VT == MVT::i32) { 2380 assert(VA.getLocVT() == MVT::i32 && 2381 "unexpected calling convention register assignment"); 2382 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2383 "unexpected use of 'returned'"); 2384 isThisReturn = true; 2385 } 2386 const TargetOptions &Options = DAG.getTarget().Options; 2387 if (Options.EmitCallSiteInfo) 2388 CSInfo.emplace_back(VA.getLocReg(), i); 2389 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2390 } else if (isByVal) { 2391 assert(VA.isMemLoc()); 2392 unsigned offset = 0; 2393 2394 // True if this byval aggregate will be split between registers 2395 // and memory. 2396 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2397 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2398 2399 if (CurByValIdx < ByValArgsCount) { 2400 2401 unsigned RegBegin, RegEnd; 2402 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2403 2404 EVT PtrVT = 2405 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2406 unsigned int i, j; 2407 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2408 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2409 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2410 SDValue Load = 2411 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(), 2412 DAG.InferPtrAlign(AddArg)); 2413 MemOpChains.push_back(Load.getValue(1)); 2414 RegsToPass.push_back(std::make_pair(j, Load)); 2415 } 2416 2417 // If parameter size outsides register area, "offset" value 2418 // helps us to calculate stack slot for remained part properly. 2419 offset = RegEnd - RegBegin; 2420 2421 CCInfo.nextInRegsParam(); 2422 } 2423 2424 if (Flags.getByValSize() > 4*offset) { 2425 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2426 unsigned LocMemOffset = VA.getLocMemOffset(); 2427 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2428 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2429 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2430 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2431 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2432 MVT::i32); 2433 SDValue AlignNode = 2434 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32); 2435 2436 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2437 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2438 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2439 Ops)); 2440 } 2441 } else if (!isTailCall) { 2442 assert(VA.isMemLoc()); 2443 2444 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2445 dl, DAG, VA, Flags)); 2446 } 2447 } 2448 2449 if (!MemOpChains.empty()) 2450 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2451 2452 // Build a sequence of copy-to-reg nodes chained together with token chain 2453 // and flag operands which copy the outgoing args into the appropriate regs. 2454 SDValue InFlag; 2455 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2456 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2457 RegsToPass[i].second, InFlag); 2458 InFlag = Chain.getValue(1); 2459 } 2460 2461 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2462 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2463 // node so that legalize doesn't hack it. 2464 bool isDirect = false; 2465 2466 const TargetMachine &TM = getTargetMachine(); 2467 const Module *Mod = MF.getFunction().getParent(); 2468 const GlobalValue *GV = nullptr; 2469 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2470 GV = G->getGlobal(); 2471 bool isStub = 2472 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2473 2474 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2475 bool isLocalARMFunc = false; 2476 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2477 2478 if (Subtarget->genLongCalls()) { 2479 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2480 "long-calls codegen is not position independent!"); 2481 // Handle a global address or an external symbol. If it's not one of 2482 // those, the target's already in a register, so we don't need to do 2483 // anything extra. 2484 if (isa<GlobalAddressSDNode>(Callee)) { 2485 // Create a constant pool entry for the callee address 2486 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2487 ARMConstantPoolValue *CPV = 2488 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2489 2490 // Get the address of the callee into a register 2491 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2492 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2493 Callee = DAG.getLoad( 2494 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2495 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2496 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2497 const char *Sym = S->getSymbol(); 2498 2499 // Create a constant pool entry for the callee address 2500 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2501 ARMConstantPoolValue *CPV = 2502 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2503 ARMPCLabelIndex, 0); 2504 // Get the address of the callee into a register 2505 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2506 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2507 Callee = DAG.getLoad( 2508 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2509 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2510 } 2511 } else if (isa<GlobalAddressSDNode>(Callee)) { 2512 if (!PreferIndirect) { 2513 isDirect = true; 2514 bool isDef = GV->isStrongDefinitionForLinker(); 2515 2516 // ARM call to a local ARM function is predicable. 2517 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2518 // tBX takes a register source operand. 2519 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2520 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2521 Callee = DAG.getNode( 2522 ARMISD::WrapperPIC, dl, PtrVt, 2523 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2524 Callee = DAG.getLoad( 2525 PtrVt, dl, DAG.getEntryNode(), Callee, 2526 MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(), 2527 MachineMemOperand::MODereferenceable | 2528 MachineMemOperand::MOInvariant); 2529 } else if (Subtarget->isTargetCOFF()) { 2530 assert(Subtarget->isTargetWindows() && 2531 "Windows is the only supported COFF target"); 2532 unsigned TargetFlags = ARMII::MO_NO_FLAG; 2533 if (GV->hasDLLImportStorageClass()) 2534 TargetFlags = ARMII::MO_DLLIMPORT; 2535 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 2536 TargetFlags = ARMII::MO_COFFSTUB; 2537 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2538 TargetFlags); 2539 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 2540 Callee = 2541 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2542 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2543 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2544 } else { 2545 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2546 } 2547 } 2548 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2549 isDirect = true; 2550 // tBX takes a register source operand. 2551 const char *Sym = S->getSymbol(); 2552 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2553 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2554 ARMConstantPoolValue *CPV = 2555 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2556 ARMPCLabelIndex, 4); 2557 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2558 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2559 Callee = DAG.getLoad( 2560 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2561 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2562 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2563 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2564 } else { 2565 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2566 } 2567 } 2568 2569 if (isCmseNSCall) { 2570 assert(!isARMFunc && !isDirect && 2571 "Cannot handle call to ARM function or direct call"); 2572 if (NumBytes > 0) { 2573 DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(), 2574 "call to non-secure function would " 2575 "require passing arguments on stack", 2576 dl.getDebugLoc()); 2577 DAG.getContext()->diagnose(Diag); 2578 } 2579 if (isStructRet) { 2580 DiagnosticInfoUnsupported Diag( 2581 DAG.getMachineFunction().getFunction(), 2582 "call to non-secure function would return value through pointer", 2583 dl.getDebugLoc()); 2584 DAG.getContext()->diagnose(Diag); 2585 } 2586 } 2587 2588 // FIXME: handle tail calls differently. 2589 unsigned CallOpc; 2590 if (Subtarget->isThumb()) { 2591 if (isCmseNSCall) 2592 CallOpc = ARMISD::tSECALL; 2593 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2594 CallOpc = ARMISD::CALL_NOLINK; 2595 else 2596 CallOpc = ARMISD::CALL; 2597 } else { 2598 if (!isDirect && !Subtarget->hasV5TOps()) 2599 CallOpc = ARMISD::CALL_NOLINK; 2600 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2601 // Emit regular call when code size is the priority 2602 !Subtarget->hasMinSize()) 2603 // "mov lr, pc; b _foo" to avoid confusing the RSP 2604 CallOpc = ARMISD::CALL_NOLINK; 2605 else 2606 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2607 } 2608 2609 std::vector<SDValue> Ops; 2610 Ops.push_back(Chain); 2611 Ops.push_back(Callee); 2612 2613 // Add argument registers to the end of the list so that they are known live 2614 // into the call. 2615 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2616 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2617 RegsToPass[i].second.getValueType())); 2618 2619 // Add a register mask operand representing the call-preserved registers. 2620 if (!isTailCall) { 2621 const uint32_t *Mask; 2622 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2623 if (isThisReturn) { 2624 // For 'this' returns, use the R0-preserving mask if applicable 2625 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2626 if (!Mask) { 2627 // Set isThisReturn to false if the calling convention is not one that 2628 // allows 'returned' to be modeled in this way, so LowerCallResult does 2629 // not try to pass 'this' straight through 2630 isThisReturn = false; 2631 Mask = ARI->getCallPreservedMask(MF, CallConv); 2632 } 2633 } else 2634 Mask = ARI->getCallPreservedMask(MF, CallConv); 2635 2636 assert(Mask && "Missing call preserved mask for calling convention"); 2637 Ops.push_back(DAG.getRegisterMask(Mask)); 2638 } 2639 2640 if (InFlag.getNode()) 2641 Ops.push_back(InFlag); 2642 2643 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2644 if (isTailCall) { 2645 MF.getFrameInfo().setHasTailCall(); 2646 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2647 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 2648 return Ret; 2649 } 2650 2651 // Returns a chain and a flag for retval copy to use. 2652 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2653 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 2654 InFlag = Chain.getValue(1); 2655 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 2656 2657 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2658 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2659 if (!Ins.empty()) 2660 InFlag = Chain.getValue(1); 2661 2662 // Handle result values, copying them out of physregs into vregs that we 2663 // return. 2664 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2665 InVals, isThisReturn, 2666 isThisReturn ? OutVals[0] : SDValue()); 2667 } 2668 2669 /// HandleByVal - Every parameter *after* a byval parameter is passed 2670 /// on the stack. Remember the next parameter register to allocate, 2671 /// and then confiscate the rest of the parameter registers to insure 2672 /// this. 2673 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2674 Align Alignment) const { 2675 // Byval (as with any stack) slots are always at least 4 byte aligned. 2676 Alignment = std::max(Alignment, Align(4)); 2677 2678 unsigned Reg = State->AllocateReg(GPRArgRegs); 2679 if (!Reg) 2680 return; 2681 2682 unsigned AlignInRegs = Alignment.value() / 4; 2683 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2684 for (unsigned i = 0; i < Waste; ++i) 2685 Reg = State->AllocateReg(GPRArgRegs); 2686 2687 if (!Reg) 2688 return; 2689 2690 unsigned Excess = 4 * (ARM::R4 - Reg); 2691 2692 // Special case when NSAA != SP and parameter size greater than size of 2693 // all remained GPR regs. In that case we can't split parameter, we must 2694 // send it to stack. We also must set NCRN to R4, so waste all 2695 // remained registers. 2696 const unsigned NSAAOffset = State->getNextStackOffset(); 2697 if (NSAAOffset != 0 && Size > Excess) { 2698 while (State->AllocateReg(GPRArgRegs)) 2699 ; 2700 return; 2701 } 2702 2703 // First register for byval parameter is the first register that wasn't 2704 // allocated before this method call, so it would be "reg". 2705 // If parameter is small enough to be saved in range [reg, r4), then 2706 // the end (first after last) register would be reg + param-size-in-regs, 2707 // else parameter would be splitted between registers and stack, 2708 // end register would be r4 in this case. 2709 unsigned ByValRegBegin = Reg; 2710 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2711 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2712 // Note, first register is allocated in the beginning of function already, 2713 // allocate remained amount of registers we need. 2714 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2715 State->AllocateReg(GPRArgRegs); 2716 // A byval parameter that is split between registers and memory needs its 2717 // size truncated here. 2718 // In the case where the entire structure fits in registers, we set the 2719 // size in memory to zero. 2720 Size = std::max<int>(Size - Excess, 0); 2721 } 2722 2723 /// MatchingStackOffset - Return true if the given stack call argument is 2724 /// already available in the same position (relatively) of the caller's 2725 /// incoming argument stack. 2726 static 2727 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2728 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2729 const TargetInstrInfo *TII) { 2730 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2731 int FI = std::numeric_limits<int>::max(); 2732 if (Arg.getOpcode() == ISD::CopyFromReg) { 2733 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2734 if (!Register::isVirtualRegister(VR)) 2735 return false; 2736 MachineInstr *Def = MRI->getVRegDef(VR); 2737 if (!Def) 2738 return false; 2739 if (!Flags.isByVal()) { 2740 if (!TII->isLoadFromStackSlot(*Def, FI)) 2741 return false; 2742 } else { 2743 return false; 2744 } 2745 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2746 if (Flags.isByVal()) 2747 // ByVal argument is passed in as a pointer but it's now being 2748 // dereferenced. e.g. 2749 // define @foo(%struct.X* %A) { 2750 // tail call @bar(%struct.X* byval %A) 2751 // } 2752 return false; 2753 SDValue Ptr = Ld->getBasePtr(); 2754 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2755 if (!FINode) 2756 return false; 2757 FI = FINode->getIndex(); 2758 } else 2759 return false; 2760 2761 assert(FI != std::numeric_limits<int>::max()); 2762 if (!MFI.isFixedObjectIndex(FI)) 2763 return false; 2764 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2765 } 2766 2767 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2768 /// for tail call optimization. Targets which want to do tail call 2769 /// optimization should implement this function. 2770 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2771 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2772 bool isCalleeStructRet, bool isCallerStructRet, 2773 const SmallVectorImpl<ISD::OutputArg> &Outs, 2774 const SmallVectorImpl<SDValue> &OutVals, 2775 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2776 const bool isIndirect) const { 2777 MachineFunction &MF = DAG.getMachineFunction(); 2778 const Function &CallerF = MF.getFunction(); 2779 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2780 2781 assert(Subtarget->supportsTailCall()); 2782 2783 // Indirect tail calls cannot be optimized for Thumb1 if the args 2784 // to the call take up r0-r3. The reason is that there are no legal registers 2785 // left to hold the pointer to the function to be called. 2786 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2787 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2788 return false; 2789 2790 // Look for obvious safe cases to perform tail call optimization that do not 2791 // require ABI changes. This is what gcc calls sibcall. 2792 2793 // Exception-handling functions need a special set of instructions to indicate 2794 // a return to the hardware. Tail-calling another function would probably 2795 // break this. 2796 if (CallerF.hasFnAttribute("interrupt")) 2797 return false; 2798 2799 // Also avoid sibcall optimization if either caller or callee uses struct 2800 // return semantics. 2801 if (isCalleeStructRet || isCallerStructRet) 2802 return false; 2803 2804 // Externally-defined functions with weak linkage should not be 2805 // tail-called on ARM when the OS does not support dynamic 2806 // pre-emption of symbols, as the AAELF spec requires normal calls 2807 // to undefined weak functions to be replaced with a NOP or jump to the 2808 // next instruction. The behaviour of branch instructions in this 2809 // situation (as used for tail calls) is implementation-defined, so we 2810 // cannot rely on the linker replacing the tail call with a return. 2811 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2812 const GlobalValue *GV = G->getGlobal(); 2813 const Triple &TT = getTargetMachine().getTargetTriple(); 2814 if (GV->hasExternalWeakLinkage() && 2815 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2816 return false; 2817 } 2818 2819 // Check that the call results are passed in the same way. 2820 LLVMContext &C = *DAG.getContext(); 2821 if (!CCState::resultsCompatible( 2822 getEffectiveCallingConv(CalleeCC, isVarArg), 2823 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins, 2824 CCAssignFnForReturn(CalleeCC, isVarArg), 2825 CCAssignFnForReturn(CallerCC, CallerF.isVarArg()))) 2826 return false; 2827 // The callee has to preserve all registers the caller needs to preserve. 2828 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2829 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2830 if (CalleeCC != CallerCC) { 2831 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2832 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2833 return false; 2834 } 2835 2836 // If Caller's vararg or byval argument has been split between registers and 2837 // stack, do not perform tail call, since part of the argument is in caller's 2838 // local frame. 2839 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2840 if (AFI_Caller->getArgRegsSaveSize()) 2841 return false; 2842 2843 // If the callee takes no arguments then go on to check the results of the 2844 // call. 2845 if (!Outs.empty()) { 2846 // Check if stack adjustment is needed. For now, do not do this if any 2847 // argument is passed on the stack. 2848 SmallVector<CCValAssign, 16> ArgLocs; 2849 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2850 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2851 if (CCInfo.getNextStackOffset()) { 2852 // Check if the arguments are already laid out in the right way as 2853 // the caller's fixed stack objects. 2854 MachineFrameInfo &MFI = MF.getFrameInfo(); 2855 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2856 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2857 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2858 i != e; 2859 ++i, ++realArgIdx) { 2860 CCValAssign &VA = ArgLocs[i]; 2861 EVT RegVT = VA.getLocVT(); 2862 SDValue Arg = OutVals[realArgIdx]; 2863 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2864 if (VA.getLocInfo() == CCValAssign::Indirect) 2865 return false; 2866 if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) { 2867 // f64 and vector types are split into multiple registers or 2868 // register/stack-slot combinations. The types will not match 2869 // the registers; give up on memory f64 refs until we figure 2870 // out what to do about this. 2871 if (!VA.isRegLoc()) 2872 return false; 2873 if (!ArgLocs[++i].isRegLoc()) 2874 return false; 2875 if (RegVT == MVT::v2f64) { 2876 if (!ArgLocs[++i].isRegLoc()) 2877 return false; 2878 if (!ArgLocs[++i].isRegLoc()) 2879 return false; 2880 } 2881 } else if (!VA.isRegLoc()) { 2882 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2883 MFI, MRI, TII)) 2884 return false; 2885 } 2886 } 2887 } 2888 2889 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2890 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2891 return false; 2892 } 2893 2894 return true; 2895 } 2896 2897 bool 2898 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2899 MachineFunction &MF, bool isVarArg, 2900 const SmallVectorImpl<ISD::OutputArg> &Outs, 2901 LLVMContext &Context) const { 2902 SmallVector<CCValAssign, 16> RVLocs; 2903 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2904 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2905 } 2906 2907 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2908 const SDLoc &DL, SelectionDAG &DAG) { 2909 const MachineFunction &MF = DAG.getMachineFunction(); 2910 const Function &F = MF.getFunction(); 2911 2912 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2913 2914 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2915 // version of the "preferred return address". These offsets affect the return 2916 // instruction if this is a return from PL1 without hypervisor extensions. 2917 // IRQ/FIQ: +4 "subs pc, lr, #4" 2918 // SWI: 0 "subs pc, lr, #0" 2919 // ABORT: +4 "subs pc, lr, #4" 2920 // UNDEF: +4/+2 "subs pc, lr, #0" 2921 // UNDEF varies depending on where the exception came from ARM or Thumb 2922 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2923 2924 int64_t LROffset; 2925 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2926 IntKind == "ABORT") 2927 LROffset = 4; 2928 else if (IntKind == "SWI" || IntKind == "UNDEF") 2929 LROffset = 0; 2930 else 2931 report_fatal_error("Unsupported interrupt attribute. If present, value " 2932 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2933 2934 RetOps.insert(RetOps.begin() + 1, 2935 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2936 2937 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2938 } 2939 2940 SDValue 2941 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2942 bool isVarArg, 2943 const SmallVectorImpl<ISD::OutputArg> &Outs, 2944 const SmallVectorImpl<SDValue> &OutVals, 2945 const SDLoc &dl, SelectionDAG &DAG) const { 2946 // CCValAssign - represent the assignment of the return value to a location. 2947 SmallVector<CCValAssign, 16> RVLocs; 2948 2949 // CCState - Info about the registers and stack slots. 2950 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2951 *DAG.getContext()); 2952 2953 // Analyze outgoing return values. 2954 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2955 2956 SDValue Flag; 2957 SmallVector<SDValue, 4> RetOps; 2958 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2959 bool isLittleEndian = Subtarget->isLittle(); 2960 2961 MachineFunction &MF = DAG.getMachineFunction(); 2962 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2963 AFI->setReturnRegsCount(RVLocs.size()); 2964 2965 // Report error if cmse entry function returns structure through first ptr arg. 2966 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) { 2967 // Note: using an empty SDLoc(), as the first line of the function is a 2968 // better place to report than the last line. 2969 DiagnosticInfoUnsupported Diag( 2970 DAG.getMachineFunction().getFunction(), 2971 "secure entry function would return value through pointer", 2972 SDLoc().getDebugLoc()); 2973 DAG.getContext()->diagnose(Diag); 2974 } 2975 2976 // Copy the result values into the output registers. 2977 for (unsigned i = 0, realRVLocIdx = 0; 2978 i != RVLocs.size(); 2979 ++i, ++realRVLocIdx) { 2980 CCValAssign &VA = RVLocs[i]; 2981 assert(VA.isRegLoc() && "Can only return in registers!"); 2982 2983 SDValue Arg = OutVals[realRVLocIdx]; 2984 bool ReturnF16 = false; 2985 2986 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2987 // Half-precision return values can be returned like this: 2988 // 2989 // t11 f16 = fadd ... 2990 // t12: i16 = bitcast t11 2991 // t13: i32 = zero_extend t12 2992 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2993 // 2994 // to avoid code generation for bitcasts, we simply set Arg to the node 2995 // that produces the f16 value, t11 in this case. 2996 // 2997 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2998 SDValue ZE = Arg.getOperand(0); 2999 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 3000 SDValue BC = ZE.getOperand(0); 3001 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 3002 Arg = BC.getOperand(0); 3003 ReturnF16 = true; 3004 } 3005 } 3006 } 3007 } 3008 3009 switch (VA.getLocInfo()) { 3010 default: llvm_unreachable("Unknown loc info!"); 3011 case CCValAssign::Full: break; 3012 case CCValAssign::BCvt: 3013 if (!ReturnF16) 3014 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 3015 break; 3016 } 3017 3018 // Mask f16 arguments if this is a CMSE nonsecure entry. 3019 auto RetVT = Outs[realRVLocIdx].ArgVT; 3020 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) { 3021 if (VA.needsCustom() && VA.getValVT() == MVT::f16) { 3022 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg); 3023 } else { 3024 auto LocBits = VA.getLocVT().getSizeInBits(); 3025 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits()); 3026 SDValue Mask = 3027 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits)); 3028 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg); 3029 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask); 3030 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 3031 } 3032 } 3033 3034 if (VA.needsCustom() && 3035 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) { 3036 if (VA.getLocVT() == MVT::v2f64) { 3037 // Extract the first half and return it in two registers. 3038 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 3039 DAG.getConstant(0, dl, MVT::i32)); 3040 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 3041 DAG.getVTList(MVT::i32, MVT::i32), Half); 3042 3043 Chain = 3044 DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3045 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag); 3046 Flag = Chain.getValue(1); 3047 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3048 VA = RVLocs[++i]; // skip ahead to next loc 3049 Chain = 3050 DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3051 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag); 3052 Flag = Chain.getValue(1); 3053 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3054 VA = RVLocs[++i]; // skip ahead to next loc 3055 3056 // Extract the 2nd half and fall through to handle it as an f64 value. 3057 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 3058 DAG.getConstant(1, dl, MVT::i32)); 3059 } 3060 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 3061 // available. 3062 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 3063 DAG.getVTList(MVT::i32, MVT::i32), Arg); 3064 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3065 fmrrd.getValue(isLittleEndian ? 0 : 1), Flag); 3066 Flag = Chain.getValue(1); 3067 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3068 VA = RVLocs[++i]; // skip ahead to next loc 3069 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3070 fmrrd.getValue(isLittleEndian ? 1 : 0), Flag); 3071 } else 3072 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 3073 3074 // Guarantee that all emitted copies are 3075 // stuck together, avoiding something bad. 3076 Flag = Chain.getValue(1); 3077 RetOps.push_back(DAG.getRegister( 3078 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT())); 3079 } 3080 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 3081 const MCPhysReg *I = 3082 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3083 if (I) { 3084 for (; *I; ++I) { 3085 if (ARM::GPRRegClass.contains(*I)) 3086 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 3087 else if (ARM::DPRRegClass.contains(*I)) 3088 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3089 else 3090 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3091 } 3092 } 3093 3094 // Update chain and glue. 3095 RetOps[0] = Chain; 3096 if (Flag.getNode()) 3097 RetOps.push_back(Flag); 3098 3099 // CPUs which aren't M-class use a special sequence to return from 3100 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 3101 // though we use "subs pc, lr, #N"). 3102 // 3103 // M-class CPUs actually use a normal return sequence with a special 3104 // (hardware-provided) value in LR, so the normal code path works. 3105 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 3106 !Subtarget->isMClass()) { 3107 if (Subtarget->isThumb1Only()) 3108 report_fatal_error("interrupt attribute is not supported in Thumb1"); 3109 return LowerInterruptReturn(RetOps, dl, DAG); 3110 } 3111 3112 ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG : 3113 ARMISD::RET_FLAG; 3114 return DAG.getNode(RetNode, dl, MVT::Other, RetOps); 3115 } 3116 3117 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 3118 if (N->getNumValues() != 1) 3119 return false; 3120 if (!N->hasNUsesOfValue(1, 0)) 3121 return false; 3122 3123 SDValue TCChain = Chain; 3124 SDNode *Copy = *N->use_begin(); 3125 if (Copy->getOpcode() == ISD::CopyToReg) { 3126 // If the copy has a glue operand, we conservatively assume it isn't safe to 3127 // perform a tail call. 3128 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 3129 return false; 3130 TCChain = Copy->getOperand(0); 3131 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 3132 SDNode *VMov = Copy; 3133 // f64 returned in a pair of GPRs. 3134 SmallPtrSet<SDNode*, 2> Copies; 3135 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 3136 UI != UE; ++UI) { 3137 if (UI->getOpcode() != ISD::CopyToReg) 3138 return false; 3139 Copies.insert(*UI); 3140 } 3141 if (Copies.size() > 2) 3142 return false; 3143 3144 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 3145 UI != UE; ++UI) { 3146 SDValue UseChain = UI->getOperand(0); 3147 if (Copies.count(UseChain.getNode())) 3148 // Second CopyToReg 3149 Copy = *UI; 3150 else { 3151 // We are at the top of this chain. 3152 // If the copy has a glue operand, we conservatively assume it 3153 // isn't safe to perform a tail call. 3154 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 3155 return false; 3156 // First CopyToReg 3157 TCChain = UseChain; 3158 } 3159 } 3160 } else if (Copy->getOpcode() == ISD::BITCAST) { 3161 // f32 returned in a single GPR. 3162 if (!Copy->hasOneUse()) 3163 return false; 3164 Copy = *Copy->use_begin(); 3165 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 3166 return false; 3167 // If the copy has a glue operand, we conservatively assume it isn't safe to 3168 // perform a tail call. 3169 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 3170 return false; 3171 TCChain = Copy->getOperand(0); 3172 } else { 3173 return false; 3174 } 3175 3176 bool HasRet = false; 3177 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 3178 UI != UE; ++UI) { 3179 if (UI->getOpcode() != ARMISD::RET_FLAG && 3180 UI->getOpcode() != ARMISD::INTRET_FLAG) 3181 return false; 3182 HasRet = true; 3183 } 3184 3185 if (!HasRet) 3186 return false; 3187 3188 Chain = TCChain; 3189 return true; 3190 } 3191 3192 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3193 if (!Subtarget->supportsTailCall()) 3194 return false; 3195 3196 if (!CI->isTailCall()) 3197 return false; 3198 3199 return true; 3200 } 3201 3202 // Trying to write a 64 bit value so need to split into two 32 bit values first, 3203 // and pass the lower and high parts through. 3204 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 3205 SDLoc DL(Op); 3206 SDValue WriteValue = Op->getOperand(2); 3207 3208 // This function is only supposed to be called for i64 type argument. 3209 assert(WriteValue.getValueType() == MVT::i64 3210 && "LowerWRITE_REGISTER called for non-i64 type argument."); 3211 3212 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3213 DAG.getConstant(0, DL, MVT::i32)); 3214 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3215 DAG.getConstant(1, DL, MVT::i32)); 3216 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 3217 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 3218 } 3219 3220 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 3221 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 3222 // one of the above mentioned nodes. It has to be wrapped because otherwise 3223 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 3224 // be used to form addressing mode. These wrapped nodes will be selected 3225 // into MOVi. 3226 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 3227 SelectionDAG &DAG) const { 3228 EVT PtrVT = Op.getValueType(); 3229 // FIXME there is no actual debug info here 3230 SDLoc dl(Op); 3231 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3232 SDValue Res; 3233 3234 // When generating execute-only code Constant Pools must be promoted to the 3235 // global data section. It's a bit ugly that we can't share them across basic 3236 // blocks, but this way we guarantee that execute-only behaves correct with 3237 // position-independent addressing modes. 3238 if (Subtarget->genExecuteOnly()) { 3239 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 3240 auto T = const_cast<Type*>(CP->getType()); 3241 auto C = const_cast<Constant*>(CP->getConstVal()); 3242 auto M = const_cast<Module*>(DAG.getMachineFunction(). 3243 getFunction().getParent()); 3244 auto GV = new GlobalVariable( 3245 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 3246 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 3247 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 3248 Twine(AFI->createPICLabelUId()) 3249 ); 3250 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 3251 dl, PtrVT); 3252 return LowerGlobalAddress(GA, DAG); 3253 } 3254 3255 if (CP->isMachineConstantPoolEntry()) 3256 Res = 3257 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign()); 3258 else 3259 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign()); 3260 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 3261 } 3262 3263 unsigned ARMTargetLowering::getJumpTableEncoding() const { 3264 return MachineJumpTableInfo::EK_Inline; 3265 } 3266 3267 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 3268 SelectionDAG &DAG) const { 3269 MachineFunction &MF = DAG.getMachineFunction(); 3270 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3271 unsigned ARMPCLabelIndex = 0; 3272 SDLoc DL(Op); 3273 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3274 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 3275 SDValue CPAddr; 3276 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 3277 if (!IsPositionIndependent) { 3278 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4)); 3279 } else { 3280 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3281 ARMPCLabelIndex = AFI->createPICLabelUId(); 3282 ARMConstantPoolValue *CPV = 3283 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 3284 ARMCP::CPBlockAddress, PCAdj); 3285 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3286 } 3287 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 3288 SDValue Result = DAG.getLoad( 3289 PtrVT, DL, DAG.getEntryNode(), CPAddr, 3290 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3291 if (!IsPositionIndependent) 3292 return Result; 3293 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 3294 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 3295 } 3296 3297 /// Convert a TLS address reference into the correct sequence of loads 3298 /// and calls to compute the variable's address for Darwin, and return an 3299 /// SDValue containing the final node. 3300 3301 /// Darwin only has one TLS scheme which must be capable of dealing with the 3302 /// fully general situation, in the worst case. This means: 3303 /// + "extern __thread" declaration. 3304 /// + Defined in a possibly unknown dynamic library. 3305 /// 3306 /// The general system is that each __thread variable has a [3 x i32] descriptor 3307 /// which contains information used by the runtime to calculate the address. The 3308 /// only part of this the compiler needs to know about is the first word, which 3309 /// contains a function pointer that must be called with the address of the 3310 /// entire descriptor in "r0". 3311 /// 3312 /// Since this descriptor may be in a different unit, in general access must 3313 /// proceed along the usual ARM rules. A common sequence to produce is: 3314 /// 3315 /// movw rT1, :lower16:_var$non_lazy_ptr 3316 /// movt rT1, :upper16:_var$non_lazy_ptr 3317 /// ldr r0, [rT1] 3318 /// ldr rT2, [r0] 3319 /// blx rT2 3320 /// [...address now in r0...] 3321 SDValue 3322 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3323 SelectionDAG &DAG) const { 3324 assert(Subtarget->isTargetDarwin() && 3325 "This function expects a Darwin target"); 3326 SDLoc DL(Op); 3327 3328 // First step is to get the address of the actua global symbol. This is where 3329 // the TLS descriptor lives. 3330 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3331 3332 // The first entry in the descriptor is a function pointer that we must call 3333 // to obtain the address of the variable. 3334 SDValue Chain = DAG.getEntryNode(); 3335 SDValue FuncTLVGet = DAG.getLoad( 3336 MVT::i32, DL, Chain, DescAddr, 3337 MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4), 3338 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3339 MachineMemOperand::MOInvariant); 3340 Chain = FuncTLVGet.getValue(1); 3341 3342 MachineFunction &F = DAG.getMachineFunction(); 3343 MachineFrameInfo &MFI = F.getFrameInfo(); 3344 MFI.setAdjustsStack(true); 3345 3346 // TLS calls preserve all registers except those that absolutely must be 3347 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3348 // silly). 3349 auto TRI = 3350 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3351 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3352 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3353 3354 // Finally, we can make the call. This is just a degenerate version of a 3355 // normal AArch64 call node: r0 takes the address of the descriptor, and 3356 // returns the address of the variable in this thread. 3357 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3358 Chain = 3359 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3360 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3361 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3362 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3363 } 3364 3365 SDValue 3366 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3367 SelectionDAG &DAG) const { 3368 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3369 3370 SDValue Chain = DAG.getEntryNode(); 3371 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3372 SDLoc DL(Op); 3373 3374 // Load the current TEB (thread environment block) 3375 SDValue Ops[] = {Chain, 3376 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3377 DAG.getTargetConstant(15, DL, MVT::i32), 3378 DAG.getTargetConstant(0, DL, MVT::i32), 3379 DAG.getTargetConstant(13, DL, MVT::i32), 3380 DAG.getTargetConstant(0, DL, MVT::i32), 3381 DAG.getTargetConstant(2, DL, MVT::i32)}; 3382 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3383 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3384 3385 SDValue TEB = CurrentTEB.getValue(0); 3386 Chain = CurrentTEB.getValue(1); 3387 3388 // Load the ThreadLocalStoragePointer from the TEB 3389 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3390 SDValue TLSArray = 3391 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3392 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3393 3394 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3395 // offset into the TLSArray. 3396 3397 // Load the TLS index from the C runtime 3398 SDValue TLSIndex = 3399 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3400 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3401 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3402 3403 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3404 DAG.getConstant(2, DL, MVT::i32)); 3405 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3406 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3407 MachinePointerInfo()); 3408 3409 // Get the offset of the start of the .tls section (section base) 3410 const auto *GA = cast<GlobalAddressSDNode>(Op); 3411 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3412 SDValue Offset = DAG.getLoad( 3413 PtrVT, DL, Chain, 3414 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3415 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))), 3416 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3417 3418 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3419 } 3420 3421 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3422 SDValue 3423 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3424 SelectionDAG &DAG) const { 3425 SDLoc dl(GA); 3426 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3427 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3428 MachineFunction &MF = DAG.getMachineFunction(); 3429 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3430 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3431 ARMConstantPoolValue *CPV = 3432 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3433 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3434 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3435 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3436 Argument = DAG.getLoad( 3437 PtrVT, dl, DAG.getEntryNode(), Argument, 3438 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3439 SDValue Chain = Argument.getValue(1); 3440 3441 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3442 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3443 3444 // call __tls_get_addr. 3445 ArgListTy Args; 3446 ArgListEntry Entry; 3447 Entry.Node = Argument; 3448 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3449 Args.push_back(Entry); 3450 3451 // FIXME: is there useful debug info available here? 3452 TargetLowering::CallLoweringInfo CLI(DAG); 3453 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3454 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3455 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3456 3457 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3458 return CallResult.first; 3459 } 3460 3461 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3462 // "local exec" model. 3463 SDValue 3464 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3465 SelectionDAG &DAG, 3466 TLSModel::Model model) const { 3467 const GlobalValue *GV = GA->getGlobal(); 3468 SDLoc dl(GA); 3469 SDValue Offset; 3470 SDValue Chain = DAG.getEntryNode(); 3471 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3472 // Get the Thread Pointer 3473 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3474 3475 if (model == TLSModel::InitialExec) { 3476 MachineFunction &MF = DAG.getMachineFunction(); 3477 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3478 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3479 // Initial exec model. 3480 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3481 ARMConstantPoolValue *CPV = 3482 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3483 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3484 true); 3485 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3486 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3487 Offset = DAG.getLoad( 3488 PtrVT, dl, Chain, Offset, 3489 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3490 Chain = Offset.getValue(1); 3491 3492 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3493 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3494 3495 Offset = DAG.getLoad( 3496 PtrVT, dl, Chain, Offset, 3497 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3498 } else { 3499 // local exec model 3500 assert(model == TLSModel::LocalExec); 3501 ARMConstantPoolValue *CPV = 3502 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3503 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3504 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3505 Offset = DAG.getLoad( 3506 PtrVT, dl, Chain, Offset, 3507 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3508 } 3509 3510 // The address of the thread local variable is the add of the thread 3511 // pointer with the offset of the variable. 3512 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3513 } 3514 3515 SDValue 3516 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3517 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3518 if (DAG.getTarget().useEmulatedTLS()) 3519 return LowerToTLSEmulatedModel(GA, DAG); 3520 3521 if (Subtarget->isTargetDarwin()) 3522 return LowerGlobalTLSAddressDarwin(Op, DAG); 3523 3524 if (Subtarget->isTargetWindows()) 3525 return LowerGlobalTLSAddressWindows(Op, DAG); 3526 3527 // TODO: implement the "local dynamic" model 3528 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3529 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3530 3531 switch (model) { 3532 case TLSModel::GeneralDynamic: 3533 case TLSModel::LocalDynamic: 3534 return LowerToTLSGeneralDynamicModel(GA, DAG); 3535 case TLSModel::InitialExec: 3536 case TLSModel::LocalExec: 3537 return LowerToTLSExecModels(GA, DAG, model); 3538 } 3539 llvm_unreachable("bogus TLS model"); 3540 } 3541 3542 /// Return true if all users of V are within function F, looking through 3543 /// ConstantExprs. 3544 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3545 SmallVector<const User*,4> Worklist; 3546 for (auto *U : V->users()) 3547 Worklist.push_back(U); 3548 while (!Worklist.empty()) { 3549 auto *U = Worklist.pop_back_val(); 3550 if (isa<ConstantExpr>(U)) { 3551 for (auto *UU : U->users()) 3552 Worklist.push_back(UU); 3553 continue; 3554 } 3555 3556 auto *I = dyn_cast<Instruction>(U); 3557 if (!I || I->getParent()->getParent() != F) 3558 return false; 3559 } 3560 return true; 3561 } 3562 3563 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3564 const GlobalValue *GV, SelectionDAG &DAG, 3565 EVT PtrVT, const SDLoc &dl) { 3566 // If we're creating a pool entry for a constant global with unnamed address, 3567 // and the global is small enough, we can emit it inline into the constant pool 3568 // to save ourselves an indirection. 3569 // 3570 // This is a win if the constant is only used in one function (so it doesn't 3571 // need to be duplicated) or duplicating the constant wouldn't increase code 3572 // size (implying the constant is no larger than 4 bytes). 3573 const Function &F = DAG.getMachineFunction().getFunction(); 3574 3575 // We rely on this decision to inline being idemopotent and unrelated to the 3576 // use-site. We know that if we inline a variable at one use site, we'll 3577 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3578 // doesn't know about this optimization, so bail out if it's enabled else 3579 // we could decide to inline here (and thus never emit the GV) but require 3580 // the GV from fast-isel generated code. 3581 if (!EnableConstpoolPromotion || 3582 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3583 return SDValue(); 3584 3585 auto *GVar = dyn_cast<GlobalVariable>(GV); 3586 if (!GVar || !GVar->hasInitializer() || 3587 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3588 !GVar->hasLocalLinkage()) 3589 return SDValue(); 3590 3591 // If we inline a value that contains relocations, we move the relocations 3592 // from .data to .text. This is not allowed in position-independent code. 3593 auto *Init = GVar->getInitializer(); 3594 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3595 Init->needsRelocation()) 3596 return SDValue(); 3597 3598 // The constant islands pass can only really deal with alignment requests 3599 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3600 // any type wanting greater alignment requirements than 4 bytes. We also 3601 // can only promote constants that are multiples of 4 bytes in size or 3602 // are paddable to a multiple of 4. Currently we only try and pad constants 3603 // that are strings for simplicity. 3604 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3605 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3606 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar); 3607 unsigned RequiredPadding = 4 - (Size % 4); 3608 bool PaddingPossible = 3609 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3610 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize || 3611 Size == 0) 3612 return SDValue(); 3613 3614 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3615 MachineFunction &MF = DAG.getMachineFunction(); 3616 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3617 3618 // We can't bloat the constant pool too much, else the ConstantIslands pass 3619 // may fail to converge. If we haven't promoted this global yet (it may have 3620 // multiple uses), and promoting it would increase the constant pool size (Sz 3621 // > 4), ensure we have space to do so up to MaxTotal. 3622 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3623 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3624 ConstpoolPromotionMaxTotal) 3625 return SDValue(); 3626 3627 // This is only valid if all users are in a single function; we can't clone 3628 // the constant in general. The LLVM IR unnamed_addr allows merging 3629 // constants, but not cloning them. 3630 // 3631 // We could potentially allow cloning if we could prove all uses of the 3632 // constant in the current function don't care about the address, like 3633 // printf format strings. But that isn't implemented for now. 3634 if (!allUsersAreInFunction(GVar, &F)) 3635 return SDValue(); 3636 3637 // We're going to inline this global. Pad it out if needed. 3638 if (RequiredPadding != 4) { 3639 StringRef S = CDAInit->getAsString(); 3640 3641 SmallVector<uint8_t,16> V(S.size()); 3642 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3643 while (RequiredPadding--) 3644 V.push_back(0); 3645 Init = ConstantDataArray::get(*DAG.getContext(), V); 3646 } 3647 3648 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3649 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4)); 3650 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3651 AFI->markGlobalAsPromotedToConstantPool(GVar); 3652 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3653 PaddedSize - 4); 3654 } 3655 ++NumConstpoolPromoted; 3656 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3657 } 3658 3659 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3660 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3661 if (!(GV = GA->getBaseObject())) 3662 return false; 3663 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3664 return V->isConstant(); 3665 return isa<Function>(GV); 3666 } 3667 3668 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3669 SelectionDAG &DAG) const { 3670 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3671 default: llvm_unreachable("unknown object format"); 3672 case Triple::COFF: 3673 return LowerGlobalAddressWindows(Op, DAG); 3674 case Triple::ELF: 3675 return LowerGlobalAddressELF(Op, DAG); 3676 case Triple::MachO: 3677 return LowerGlobalAddressDarwin(Op, DAG); 3678 } 3679 } 3680 3681 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3682 SelectionDAG &DAG) const { 3683 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3684 SDLoc dl(Op); 3685 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3686 const TargetMachine &TM = getTargetMachine(); 3687 bool IsRO = isReadOnly(GV); 3688 3689 // promoteToConstantPool only if not generating XO text section 3690 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3691 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3692 return V; 3693 3694 if (isPositionIndependent()) { 3695 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3696 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3697 UseGOT_PREL ? ARMII::MO_GOT : 0); 3698 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3699 if (UseGOT_PREL) 3700 Result = 3701 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3702 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3703 return Result; 3704 } else if (Subtarget->isROPI() && IsRO) { 3705 // PC-relative. 3706 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3707 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3708 return Result; 3709 } else if (Subtarget->isRWPI() && !IsRO) { 3710 // SB-relative. 3711 SDValue RelAddr; 3712 if (Subtarget->useMovt()) { 3713 ++NumMovwMovt; 3714 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3715 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3716 } else { // use literal pool for address constant 3717 ARMConstantPoolValue *CPV = 3718 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3719 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3720 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3721 RelAddr = DAG.getLoad( 3722 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3723 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3724 } 3725 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3726 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3727 return Result; 3728 } 3729 3730 // If we have T2 ops, we can materialize the address directly via movt/movw 3731 // pair. This is always cheaper. 3732 if (Subtarget->useMovt()) { 3733 ++NumMovwMovt; 3734 // FIXME: Once remat is capable of dealing with instructions with register 3735 // operands, expand this into two nodes. 3736 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3737 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3738 } else { 3739 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4)); 3740 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3741 return DAG.getLoad( 3742 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3743 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3744 } 3745 } 3746 3747 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3748 SelectionDAG &DAG) const { 3749 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3750 "ROPI/RWPI not currently supported for Darwin"); 3751 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3752 SDLoc dl(Op); 3753 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3754 3755 if (Subtarget->useMovt()) 3756 ++NumMovwMovt; 3757 3758 // FIXME: Once remat is capable of dealing with instructions with register 3759 // operands, expand this into multiple nodes 3760 unsigned Wrapper = 3761 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3762 3763 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3764 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3765 3766 if (Subtarget->isGVIndirectSymbol(GV)) 3767 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3768 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3769 return Result; 3770 } 3771 3772 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3773 SelectionDAG &DAG) const { 3774 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3775 assert(Subtarget->useMovt() && 3776 "Windows on ARM expects to use movw/movt"); 3777 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3778 "ROPI/RWPI not currently supported for Windows"); 3779 3780 const TargetMachine &TM = getTargetMachine(); 3781 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3782 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3783 if (GV->hasDLLImportStorageClass()) 3784 TargetFlags = ARMII::MO_DLLIMPORT; 3785 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3786 TargetFlags = ARMII::MO_COFFSTUB; 3787 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3788 SDValue Result; 3789 SDLoc DL(Op); 3790 3791 ++NumMovwMovt; 3792 3793 // FIXME: Once remat is capable of dealing with instructions with register 3794 // operands, expand this into two nodes. 3795 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3796 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3797 TargetFlags)); 3798 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3799 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3800 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3801 return Result; 3802 } 3803 3804 SDValue 3805 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3806 SDLoc dl(Op); 3807 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3808 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3809 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3810 Op.getOperand(1), Val); 3811 } 3812 3813 SDValue 3814 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3815 SDLoc dl(Op); 3816 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3817 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3818 } 3819 3820 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3821 SelectionDAG &DAG) const { 3822 SDLoc dl(Op); 3823 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3824 Op.getOperand(0)); 3825 } 3826 3827 SDValue ARMTargetLowering::LowerINTRINSIC_VOID( 3828 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const { 3829 unsigned IntNo = 3830 cast<ConstantSDNode>( 3831 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other)) 3832 ->getZExtValue(); 3833 switch (IntNo) { 3834 default: 3835 return SDValue(); // Don't custom lower most intrinsics. 3836 case Intrinsic::arm_gnu_eabi_mcount: { 3837 MachineFunction &MF = DAG.getMachineFunction(); 3838 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3839 SDLoc dl(Op); 3840 SDValue Chain = Op.getOperand(0); 3841 // call "\01__gnu_mcount_nc" 3842 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 3843 const uint32_t *Mask = 3844 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 3845 assert(Mask && "Missing call preserved mask for calling convention"); 3846 // Mark LR an implicit live-in. 3847 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 3848 SDValue ReturnAddress = 3849 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT); 3850 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue}; 3851 SDValue Callee = 3852 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0); 3853 SDValue RegisterMask = DAG.getRegisterMask(Mask); 3854 if (Subtarget->isThumb()) 3855 return SDValue( 3856 DAG.getMachineNode( 3857 ARM::tBL_PUSHLR, dl, ResultTys, 3858 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT), 3859 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}), 3860 0); 3861 return SDValue( 3862 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys, 3863 {ReturnAddress, Callee, RegisterMask, Chain}), 3864 0); 3865 } 3866 } 3867 } 3868 3869 SDValue 3870 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3871 const ARMSubtarget *Subtarget) const { 3872 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3873 SDLoc dl(Op); 3874 switch (IntNo) { 3875 default: return SDValue(); // Don't custom lower most intrinsics. 3876 case Intrinsic::thread_pointer: { 3877 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3878 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3879 } 3880 case Intrinsic::arm_cls: { 3881 const SDValue &Operand = Op.getOperand(1); 3882 const EVT VTy = Op.getValueType(); 3883 SDValue SRA = 3884 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy)); 3885 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand); 3886 SDValue SHL = 3887 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy)); 3888 SDValue OR = 3889 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy)); 3890 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR); 3891 return Result; 3892 } 3893 case Intrinsic::arm_cls64: { 3894 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x)) 3895 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x))) 3896 const SDValue &Operand = Op.getOperand(1); 3897 const EVT VTy = Op.getValueType(); 3898 3899 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3900 DAG.getConstant(1, dl, VTy)); 3901 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3902 DAG.getConstant(0, dl, VTy)); 3903 SDValue Constant0 = DAG.getConstant(0, dl, VTy); 3904 SDValue Constant1 = DAG.getConstant(1, dl, VTy); 3905 SDValue Constant31 = DAG.getConstant(31, dl, VTy); 3906 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31); 3907 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi); 3908 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1); 3909 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1); 3910 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi); 3911 SDValue CheckLo = 3912 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ); 3913 SDValue HiIsZero = 3914 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ); 3915 SDValue AdjustedLo = 3916 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy)); 3917 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo); 3918 SDValue Result = 3919 DAG.getSelect(dl, VTy, CheckLo, 3920 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi); 3921 return Result; 3922 } 3923 case Intrinsic::eh_sjlj_lsda: { 3924 MachineFunction &MF = DAG.getMachineFunction(); 3925 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3926 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3927 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3928 SDValue CPAddr; 3929 bool IsPositionIndependent = isPositionIndependent(); 3930 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3931 ARMConstantPoolValue *CPV = 3932 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3933 ARMCP::CPLSDA, PCAdj); 3934 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3935 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3936 SDValue Result = DAG.getLoad( 3937 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3938 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3939 3940 if (IsPositionIndependent) { 3941 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3942 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3943 } 3944 return Result; 3945 } 3946 case Intrinsic::arm_neon_vabs: 3947 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3948 Op.getOperand(1)); 3949 case Intrinsic::arm_neon_vmulls: 3950 case Intrinsic::arm_neon_vmullu: { 3951 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3952 ? ARMISD::VMULLs : ARMISD::VMULLu; 3953 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3954 Op.getOperand(1), Op.getOperand(2)); 3955 } 3956 case Intrinsic::arm_neon_vminnm: 3957 case Intrinsic::arm_neon_vmaxnm: { 3958 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3959 ? ISD::FMINNUM : ISD::FMAXNUM; 3960 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3961 Op.getOperand(1), Op.getOperand(2)); 3962 } 3963 case Intrinsic::arm_neon_vminu: 3964 case Intrinsic::arm_neon_vmaxu: { 3965 if (Op.getValueType().isFloatingPoint()) 3966 return SDValue(); 3967 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3968 ? ISD::UMIN : ISD::UMAX; 3969 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3970 Op.getOperand(1), Op.getOperand(2)); 3971 } 3972 case Intrinsic::arm_neon_vmins: 3973 case Intrinsic::arm_neon_vmaxs: { 3974 // v{min,max}s is overloaded between signed integers and floats. 3975 if (!Op.getValueType().isFloatingPoint()) { 3976 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3977 ? ISD::SMIN : ISD::SMAX; 3978 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3979 Op.getOperand(1), Op.getOperand(2)); 3980 } 3981 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3982 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3983 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3984 Op.getOperand(1), Op.getOperand(2)); 3985 } 3986 case Intrinsic::arm_neon_vtbl1: 3987 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3988 Op.getOperand(1), Op.getOperand(2)); 3989 case Intrinsic::arm_neon_vtbl2: 3990 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3991 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3992 case Intrinsic::arm_mve_pred_i2v: 3993 case Intrinsic::arm_mve_pred_v2i: 3994 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(), 3995 Op.getOperand(1)); 3996 case Intrinsic::arm_mve_vreinterpretq: 3997 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(), 3998 Op.getOperand(1)); 3999 case Intrinsic::arm_mve_lsll: 4000 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(), 4001 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4002 case Intrinsic::arm_mve_asrl: 4003 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(), 4004 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4005 } 4006 } 4007 4008 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 4009 const ARMSubtarget *Subtarget) { 4010 SDLoc dl(Op); 4011 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 4012 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 4013 if (SSID == SyncScope::SingleThread) 4014 return Op; 4015 4016 if (!Subtarget->hasDataBarrier()) { 4017 // Some ARMv6 cpus can support data barriers with an mcr instruction. 4018 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 4019 // here. 4020 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 4021 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 4022 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 4023 DAG.getConstant(0, dl, MVT::i32)); 4024 } 4025 4026 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 4027 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 4028 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 4029 if (Subtarget->isMClass()) { 4030 // Only a full system barrier exists in the M-class architectures. 4031 Domain = ARM_MB::SY; 4032 } else if (Subtarget->preferISHSTBarriers() && 4033 Ord == AtomicOrdering::Release) { 4034 // Swift happens to implement ISHST barriers in a way that's compatible with 4035 // Release semantics but weaker than ISH so we'd be fools not to use 4036 // it. Beware: other processors probably don't! 4037 Domain = ARM_MB::ISHST; 4038 } 4039 4040 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 4041 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 4042 DAG.getConstant(Domain, dl, MVT::i32)); 4043 } 4044 4045 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 4046 const ARMSubtarget *Subtarget) { 4047 // ARM pre v5TE and Thumb1 does not have preload instructions. 4048 if (!(Subtarget->isThumb2() || 4049 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 4050 // Just preserve the chain. 4051 return Op.getOperand(0); 4052 4053 SDLoc dl(Op); 4054 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 4055 if (!isRead && 4056 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 4057 // ARMv7 with MP extension has PLDW. 4058 return Op.getOperand(0); 4059 4060 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 4061 if (Subtarget->isThumb()) { 4062 // Invert the bits. 4063 isRead = ~isRead & 1; 4064 isData = ~isData & 1; 4065 } 4066 4067 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 4068 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 4069 DAG.getConstant(isData, dl, MVT::i32)); 4070 } 4071 4072 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 4073 MachineFunction &MF = DAG.getMachineFunction(); 4074 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 4075 4076 // vastart just stores the address of the VarArgsFrameIndex slot into the 4077 // memory location argument. 4078 SDLoc dl(Op); 4079 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4080 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4081 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4082 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 4083 MachinePointerInfo(SV)); 4084 } 4085 4086 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 4087 CCValAssign &NextVA, 4088 SDValue &Root, 4089 SelectionDAG &DAG, 4090 const SDLoc &dl) const { 4091 MachineFunction &MF = DAG.getMachineFunction(); 4092 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4093 4094 const TargetRegisterClass *RC; 4095 if (AFI->isThumb1OnlyFunction()) 4096 RC = &ARM::tGPRRegClass; 4097 else 4098 RC = &ARM::GPRRegClass; 4099 4100 // Transform the arguments stored in physical registers into virtual ones. 4101 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4102 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 4103 4104 SDValue ArgValue2; 4105 if (NextVA.isMemLoc()) { 4106 MachineFrameInfo &MFI = MF.getFrameInfo(); 4107 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 4108 4109 // Create load node to retrieve arguments from the stack. 4110 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4111 ArgValue2 = DAG.getLoad( 4112 MVT::i32, dl, Root, FIN, 4113 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4114 } else { 4115 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 4116 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 4117 } 4118 if (!Subtarget->isLittle()) 4119 std::swap (ArgValue, ArgValue2); 4120 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 4121 } 4122 4123 // The remaining GPRs hold either the beginning of variable-argument 4124 // data, or the beginning of an aggregate passed by value (usually 4125 // byval). Either way, we allocate stack slots adjacent to the data 4126 // provided by our caller, and store the unallocated registers there. 4127 // If this is a variadic function, the va_list pointer will begin with 4128 // these values; otherwise, this reassembles a (byval) structure that 4129 // was split between registers and memory. 4130 // Return: The frame index registers were stored into. 4131 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 4132 const SDLoc &dl, SDValue &Chain, 4133 const Value *OrigArg, 4134 unsigned InRegsParamRecordIdx, 4135 int ArgOffset, unsigned ArgSize) const { 4136 // Currently, two use-cases possible: 4137 // Case #1. Non-var-args function, and we meet first byval parameter. 4138 // Setup first unallocated register as first byval register; 4139 // eat all remained registers 4140 // (these two actions are performed by HandleByVal method). 4141 // Then, here, we initialize stack frame with 4142 // "store-reg" instructions. 4143 // Case #2. Var-args function, that doesn't contain byval parameters. 4144 // The same: eat all remained unallocated registers, 4145 // initialize stack frame. 4146 4147 MachineFunction &MF = DAG.getMachineFunction(); 4148 MachineFrameInfo &MFI = MF.getFrameInfo(); 4149 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4150 unsigned RBegin, REnd; 4151 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 4152 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 4153 } else { 4154 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4155 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 4156 REnd = ARM::R4; 4157 } 4158 4159 if (REnd != RBegin) 4160 ArgOffset = -4 * (ARM::R4 - RBegin); 4161 4162 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4163 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 4164 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 4165 4166 SmallVector<SDValue, 4> MemOps; 4167 const TargetRegisterClass *RC = 4168 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 4169 4170 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 4171 unsigned VReg = MF.addLiveIn(Reg, RC); 4172 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4173 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4174 MachinePointerInfo(OrigArg, 4 * i)); 4175 MemOps.push_back(Store); 4176 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 4177 } 4178 4179 if (!MemOps.empty()) 4180 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4181 return FrameIndex; 4182 } 4183 4184 // Setup stack frame, the va_list pointer will start from. 4185 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 4186 const SDLoc &dl, SDValue &Chain, 4187 unsigned ArgOffset, 4188 unsigned TotalArgRegsSaveSize, 4189 bool ForceMutable) const { 4190 MachineFunction &MF = DAG.getMachineFunction(); 4191 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4192 4193 // Try to store any remaining integer argument regs 4194 // to their spots on the stack so that they may be loaded by dereferencing 4195 // the result of va_next. 4196 // If there is no regs to be stored, just point address after last 4197 // argument passed via stack. 4198 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 4199 CCInfo.getInRegsParamsCount(), 4200 CCInfo.getNextStackOffset(), 4201 std::max(4U, TotalArgRegsSaveSize)); 4202 AFI->setVarArgsFrameIndex(FrameIndex); 4203 } 4204 4205 bool ARMTargetLowering::splitValueIntoRegisterParts( 4206 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 4207 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 4208 bool IsABIRegCopy = CC.hasValue(); 4209 EVT ValueVT = Val.getValueType(); 4210 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) && 4211 PartVT == MVT::f32) { 4212 unsigned ValueBits = ValueVT.getSizeInBits(); 4213 unsigned PartBits = PartVT.getSizeInBits(); 4214 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val); 4215 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val); 4216 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 4217 Parts[0] = Val; 4218 return true; 4219 } 4220 return false; 4221 } 4222 4223 SDValue ARMTargetLowering::joinRegisterPartsIntoValue( 4224 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 4225 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 4226 bool IsABIRegCopy = CC.hasValue(); 4227 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) && 4228 PartVT == MVT::f32) { 4229 unsigned ValueBits = ValueVT.getSizeInBits(); 4230 unsigned PartBits = PartVT.getSizeInBits(); 4231 SDValue Val = Parts[0]; 4232 4233 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val); 4234 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val); 4235 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 4236 return Val; 4237 } 4238 return SDValue(); 4239 } 4240 4241 SDValue ARMTargetLowering::LowerFormalArguments( 4242 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4243 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4244 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4245 MachineFunction &MF = DAG.getMachineFunction(); 4246 MachineFrameInfo &MFI = MF.getFrameInfo(); 4247 4248 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4249 4250 // Assign locations to all of the incoming arguments. 4251 SmallVector<CCValAssign, 16> ArgLocs; 4252 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4253 *DAG.getContext()); 4254 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 4255 4256 SmallVector<SDValue, 16> ArgValues; 4257 SDValue ArgValue; 4258 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 4259 unsigned CurArgIdx = 0; 4260 4261 // Initially ArgRegsSaveSize is zero. 4262 // Then we increase this value each time we meet byval parameter. 4263 // We also increase this value in case of varargs function. 4264 AFI->setArgRegsSaveSize(0); 4265 4266 // Calculate the amount of stack space that we need to allocate to store 4267 // byval and variadic arguments that are passed in registers. 4268 // We need to know this before we allocate the first byval or variadic 4269 // argument, as they will be allocated a stack slot below the CFA (Canonical 4270 // Frame Address, the stack pointer at entry to the function). 4271 unsigned ArgRegBegin = ARM::R4; 4272 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4273 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 4274 break; 4275 4276 CCValAssign &VA = ArgLocs[i]; 4277 unsigned Index = VA.getValNo(); 4278 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 4279 if (!Flags.isByVal()) 4280 continue; 4281 4282 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 4283 unsigned RBegin, REnd; 4284 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 4285 ArgRegBegin = std::min(ArgRegBegin, RBegin); 4286 4287 CCInfo.nextInRegsParam(); 4288 } 4289 CCInfo.rewindByValRegsInfo(); 4290 4291 int lastInsIndex = -1; 4292 if (isVarArg && MFI.hasVAStart()) { 4293 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4294 if (RegIdx != array_lengthof(GPRArgRegs)) 4295 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 4296 } 4297 4298 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 4299 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 4300 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4301 4302 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4303 CCValAssign &VA = ArgLocs[i]; 4304 if (Ins[VA.getValNo()].isOrigArg()) { 4305 std::advance(CurOrigArg, 4306 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 4307 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 4308 } 4309 // Arguments stored in registers. 4310 if (VA.isRegLoc()) { 4311 EVT RegVT = VA.getLocVT(); 4312 4313 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) { 4314 // f64 and vector types are split up into multiple registers or 4315 // combinations of registers and stack slots. 4316 SDValue ArgValue1 = 4317 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4318 VA = ArgLocs[++i]; // skip ahead to next loc 4319 SDValue ArgValue2; 4320 if (VA.isMemLoc()) { 4321 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 4322 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4323 ArgValue2 = DAG.getLoad( 4324 MVT::f64, dl, Chain, FIN, 4325 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4326 } else { 4327 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4328 } 4329 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 4330 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue, 4331 ArgValue1, DAG.getIntPtrConstant(0, dl)); 4332 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue, 4333 ArgValue2, DAG.getIntPtrConstant(1, dl)); 4334 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) { 4335 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4336 } else { 4337 const TargetRegisterClass *RC; 4338 4339 if (RegVT == MVT::f16 || RegVT == MVT::bf16) 4340 RC = &ARM::HPRRegClass; 4341 else if (RegVT == MVT::f32) 4342 RC = &ARM::SPRRegClass; 4343 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 || 4344 RegVT == MVT::v4bf16) 4345 RC = &ARM::DPRRegClass; 4346 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 || 4347 RegVT == MVT::v8bf16) 4348 RC = &ARM::QPRRegClass; 4349 else if (RegVT == MVT::i32) 4350 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 4351 : &ARM::GPRRegClass; 4352 else 4353 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4354 4355 // Transform the arguments in physical registers into virtual ones. 4356 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4357 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 4358 4359 // If this value is passed in r0 and has the returned attribute (e.g. 4360 // C++ 'structors), record this fact for later use. 4361 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 4362 AFI->setPreservesR0(); 4363 } 4364 } 4365 4366 // If this is an 8 or 16-bit value, it is really passed promoted 4367 // to 32 bits. Insert an assert[sz]ext to capture this, then 4368 // truncate to the right size. 4369 switch (VA.getLocInfo()) { 4370 default: llvm_unreachable("Unknown loc info!"); 4371 case CCValAssign::Full: break; 4372 case CCValAssign::BCvt: 4373 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 4374 break; 4375 case CCValAssign::SExt: 4376 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 4377 DAG.getValueType(VA.getValVT())); 4378 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4379 break; 4380 case CCValAssign::ZExt: 4381 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 4382 DAG.getValueType(VA.getValVT())); 4383 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4384 break; 4385 } 4386 4387 // f16 arguments have their size extended to 4 bytes and passed as if they 4388 // had been copied to the LSBs of a 32-bit register. 4389 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 4390 if (VA.needsCustom() && 4391 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) 4392 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue); 4393 4394 InVals.push_back(ArgValue); 4395 } else { // VA.isRegLoc() 4396 // sanity check 4397 assert(VA.isMemLoc()); 4398 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 4399 4400 int index = VA.getValNo(); 4401 4402 // Some Ins[] entries become multiple ArgLoc[] entries. 4403 // Process them only once. 4404 if (index != lastInsIndex) 4405 { 4406 ISD::ArgFlagsTy Flags = Ins[index].Flags; 4407 // FIXME: For now, all byval parameter objects are marked mutable. 4408 // This can be changed with more analysis. 4409 // In case of tail call optimization mark all arguments mutable. 4410 // Since they could be overwritten by lowering of arguments in case of 4411 // a tail call. 4412 if (Flags.isByVal()) { 4413 assert(Ins[index].isOrigArg() && 4414 "Byval arguments cannot be implicit"); 4415 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 4416 4417 int FrameIndex = StoreByValRegs( 4418 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 4419 VA.getLocMemOffset(), Flags.getByValSize()); 4420 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 4421 CCInfo.nextInRegsParam(); 4422 } else { 4423 unsigned FIOffset = VA.getLocMemOffset(); 4424 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 4425 FIOffset, true); 4426 4427 // Create load nodes to retrieve arguments from the stack. 4428 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4429 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 4430 MachinePointerInfo::getFixedStack( 4431 DAG.getMachineFunction(), FI))); 4432 } 4433 lastInsIndex = index; 4434 } 4435 } 4436 } 4437 4438 // varargs 4439 if (isVarArg && MFI.hasVAStart()) { 4440 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(), 4441 TotalArgRegsSaveSize); 4442 if (AFI->isCmseNSEntryFunction()) { 4443 DiagnosticInfoUnsupported Diag( 4444 DAG.getMachineFunction().getFunction(), 4445 "secure entry function must not be variadic", dl.getDebugLoc()); 4446 DAG.getContext()->diagnose(Diag); 4447 } 4448 } 4449 4450 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4451 4452 if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) { 4453 DiagnosticInfoUnsupported Diag( 4454 DAG.getMachineFunction().getFunction(), 4455 "secure entry function requires arguments on stack", dl.getDebugLoc()); 4456 DAG.getContext()->diagnose(Diag); 4457 } 4458 4459 return Chain; 4460 } 4461 4462 /// isFloatingPointZero - Return true if this is +0.0. 4463 static bool isFloatingPointZero(SDValue Op) { 4464 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4465 return CFP->getValueAPF().isPosZero(); 4466 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4467 // Maybe this has already been legalized into the constant pool? 4468 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4469 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4470 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4471 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4472 return CFP->getValueAPF().isPosZero(); 4473 } 4474 } else if (Op->getOpcode() == ISD::BITCAST && 4475 Op->getValueType(0) == MVT::f64) { 4476 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4477 // created by LowerConstantFP(). 4478 SDValue BitcastOp = Op->getOperand(0); 4479 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4480 isNullConstant(BitcastOp->getOperand(0))) 4481 return true; 4482 } 4483 return false; 4484 } 4485 4486 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4487 /// the given operands. 4488 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4489 SDValue &ARMcc, SelectionDAG &DAG, 4490 const SDLoc &dl) const { 4491 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4492 unsigned C = RHSC->getZExtValue(); 4493 if (!isLegalICmpImmediate((int32_t)C)) { 4494 // Constant does not fit, try adjusting it by one. 4495 switch (CC) { 4496 default: break; 4497 case ISD::SETLT: 4498 case ISD::SETGE: 4499 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4500 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4501 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4502 } 4503 break; 4504 case ISD::SETULT: 4505 case ISD::SETUGE: 4506 if (C != 0 && isLegalICmpImmediate(C-1)) { 4507 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4508 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4509 } 4510 break; 4511 case ISD::SETLE: 4512 case ISD::SETGT: 4513 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4514 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4515 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4516 } 4517 break; 4518 case ISD::SETULE: 4519 case ISD::SETUGT: 4520 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4521 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4522 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4523 } 4524 break; 4525 } 4526 } 4527 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4528 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4529 // In ARM and Thumb-2, the compare instructions can shift their second 4530 // operand. 4531 CC = ISD::getSetCCSwappedOperands(CC); 4532 std::swap(LHS, RHS); 4533 } 4534 4535 // Thumb1 has very limited immediate modes, so turning an "and" into a 4536 // shift can save multiple instructions. 4537 // 4538 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4539 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4540 // own. If it's the operand to an unsigned comparison with an immediate, 4541 // we can eliminate one of the shifts: we transform 4542 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4543 // 4544 // We avoid transforming cases which aren't profitable due to encoding 4545 // details: 4546 // 4547 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4548 // would not; in that case, we're essentially trading one immediate load for 4549 // another. 4550 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4551 // 3. C2 is zero; we have other code for this special case. 4552 // 4553 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4554 // instruction, since the AND is always one instruction anyway, but we could 4555 // use narrow instructions in some cases. 4556 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4557 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4558 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4559 !isSignedIntSetCC(CC)) { 4560 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4561 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4562 uint64_t RHSV = RHSC->getZExtValue(); 4563 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4564 unsigned ShiftBits = countLeadingZeros(Mask); 4565 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4566 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4567 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4568 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4569 } 4570 } 4571 } 4572 4573 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4574 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4575 // way a cmp would. 4576 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4577 // some tweaks to the heuristics for the previous and->shift transform. 4578 // FIXME: Optimize cases where the LHS isn't a shift. 4579 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4580 isa<ConstantSDNode>(RHS) && 4581 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4582 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4583 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4584 unsigned ShiftAmt = 4585 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4586 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4587 DAG.getVTList(MVT::i32, MVT::i32), 4588 LHS.getOperand(0), 4589 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4590 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4591 Shift.getValue(1), SDValue()); 4592 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4593 return Chain.getValue(1); 4594 } 4595 4596 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4597 4598 // If the RHS is a constant zero then the V (overflow) flag will never be 4599 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4600 // simpler for other passes (like the peephole optimiser) to deal with. 4601 if (isNullConstant(RHS)) { 4602 switch (CondCode) { 4603 default: break; 4604 case ARMCC::GE: 4605 CondCode = ARMCC::PL; 4606 break; 4607 case ARMCC::LT: 4608 CondCode = ARMCC::MI; 4609 break; 4610 } 4611 } 4612 4613 ARMISD::NodeType CompareType; 4614 switch (CondCode) { 4615 default: 4616 CompareType = ARMISD::CMP; 4617 break; 4618 case ARMCC::EQ: 4619 case ARMCC::NE: 4620 // Uses only Z Flag 4621 CompareType = ARMISD::CMPZ; 4622 break; 4623 } 4624 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4625 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4626 } 4627 4628 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4629 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4630 SelectionDAG &DAG, const SDLoc &dl, 4631 bool Signaling) const { 4632 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4633 SDValue Cmp; 4634 if (!isFloatingPointZero(RHS)) 4635 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, 4636 dl, MVT::Glue, LHS, RHS); 4637 else 4638 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, 4639 dl, MVT::Glue, LHS); 4640 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4641 } 4642 4643 /// duplicateCmp - Glue values can have only one use, so this function 4644 /// duplicates a comparison node. 4645 SDValue 4646 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4647 unsigned Opc = Cmp.getOpcode(); 4648 SDLoc DL(Cmp); 4649 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4650 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4651 4652 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4653 Cmp = Cmp.getOperand(0); 4654 Opc = Cmp.getOpcode(); 4655 if (Opc == ARMISD::CMPFP) 4656 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4657 else { 4658 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4659 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 4660 } 4661 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4662 } 4663 4664 // This function returns three things: the arithmetic computation itself 4665 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4666 // comparison and the condition code define the case in which the arithmetic 4667 // computation *does not* overflow. 4668 std::pair<SDValue, SDValue> 4669 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4670 SDValue &ARMcc) const { 4671 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4672 4673 SDValue Value, OverflowCmp; 4674 SDValue LHS = Op.getOperand(0); 4675 SDValue RHS = Op.getOperand(1); 4676 SDLoc dl(Op); 4677 4678 // FIXME: We are currently always generating CMPs because we don't support 4679 // generating CMN through the backend. This is not as good as the natural 4680 // CMP case because it causes a register dependency and cannot be folded 4681 // later. 4682 4683 switch (Op.getOpcode()) { 4684 default: 4685 llvm_unreachable("Unknown overflow instruction!"); 4686 case ISD::SADDO: 4687 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4688 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4689 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4690 break; 4691 case ISD::UADDO: 4692 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4693 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4694 // We do not use it in the USUBO case as Value may not be used. 4695 Value = DAG.getNode(ARMISD::ADDC, dl, 4696 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4697 .getValue(0); 4698 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4699 break; 4700 case ISD::SSUBO: 4701 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4702 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4703 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4704 break; 4705 case ISD::USUBO: 4706 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4707 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4708 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4709 break; 4710 case ISD::UMULO: 4711 // We generate a UMUL_LOHI and then check if the high word is 0. 4712 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4713 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4714 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4715 LHS, RHS); 4716 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4717 DAG.getConstant(0, dl, MVT::i32)); 4718 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4719 break; 4720 case ISD::SMULO: 4721 // We generate a SMUL_LOHI and then check if all the bits of the high word 4722 // are the same as the sign bit of the low word. 4723 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4724 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4725 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4726 LHS, RHS); 4727 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4728 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4729 Value.getValue(0), 4730 DAG.getConstant(31, dl, MVT::i32))); 4731 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4732 break; 4733 } // switch (...) 4734 4735 return std::make_pair(Value, OverflowCmp); 4736 } 4737 4738 SDValue 4739 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4740 // Let legalize expand this if it isn't a legal type yet. 4741 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4742 return SDValue(); 4743 4744 SDValue Value, OverflowCmp; 4745 SDValue ARMcc; 4746 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4747 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4748 SDLoc dl(Op); 4749 // We use 0 and 1 as false and true values. 4750 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4751 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4752 EVT VT = Op.getValueType(); 4753 4754 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4755 ARMcc, CCR, OverflowCmp); 4756 4757 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4758 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4759 } 4760 4761 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4762 SelectionDAG &DAG) { 4763 SDLoc DL(BoolCarry); 4764 EVT CarryVT = BoolCarry.getValueType(); 4765 4766 // This converts the boolean value carry into the carry flag by doing 4767 // ARMISD::SUBC Carry, 1 4768 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4769 DAG.getVTList(CarryVT, MVT::i32), 4770 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4771 return Carry.getValue(1); 4772 } 4773 4774 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4775 SelectionDAG &DAG) { 4776 SDLoc DL(Flags); 4777 4778 // Now convert the carry flag into a boolean carry. We do this 4779 // using ARMISD:ADDE 0, 0, Carry 4780 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4781 DAG.getConstant(0, DL, MVT::i32), 4782 DAG.getConstant(0, DL, MVT::i32), Flags); 4783 } 4784 4785 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4786 SelectionDAG &DAG) const { 4787 // Let legalize expand this if it isn't a legal type yet. 4788 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4789 return SDValue(); 4790 4791 SDValue LHS = Op.getOperand(0); 4792 SDValue RHS = Op.getOperand(1); 4793 SDLoc dl(Op); 4794 4795 EVT VT = Op.getValueType(); 4796 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4797 SDValue Value; 4798 SDValue Overflow; 4799 switch (Op.getOpcode()) { 4800 default: 4801 llvm_unreachable("Unknown overflow instruction!"); 4802 case ISD::UADDO: 4803 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4804 // Convert the carry flag into a boolean value. 4805 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4806 break; 4807 case ISD::USUBO: { 4808 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4809 // Convert the carry flag into a boolean value. 4810 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4811 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4812 // value. So compute 1 - C. 4813 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4814 DAG.getConstant(1, dl, MVT::i32), Overflow); 4815 break; 4816 } 4817 } 4818 4819 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4820 } 4821 4822 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG, 4823 const ARMSubtarget *Subtarget) { 4824 EVT VT = Op.getValueType(); 4825 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 4826 return SDValue(); 4827 if (!VT.isSimple()) 4828 return SDValue(); 4829 4830 unsigned NewOpcode; 4831 bool IsAdd = Op->getOpcode() == ISD::SADDSAT; 4832 switch (VT.getSimpleVT().SimpleTy) { 4833 default: 4834 return SDValue(); 4835 case MVT::i8: 4836 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b; 4837 break; 4838 case MVT::i16: 4839 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b; 4840 break; 4841 } 4842 4843 SDLoc dl(Op); 4844 SDValue Add = 4845 DAG.getNode(NewOpcode, dl, MVT::i32, 4846 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32), 4847 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32)); 4848 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add); 4849 } 4850 4851 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4852 SDValue Cond = Op.getOperand(0); 4853 SDValue SelectTrue = Op.getOperand(1); 4854 SDValue SelectFalse = Op.getOperand(2); 4855 SDLoc dl(Op); 4856 unsigned Opc = Cond.getOpcode(); 4857 4858 if (Cond.getResNo() == 1 && 4859 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4860 Opc == ISD::USUBO)) { 4861 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4862 return SDValue(); 4863 4864 SDValue Value, OverflowCmp; 4865 SDValue ARMcc; 4866 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4867 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4868 EVT VT = Op.getValueType(); 4869 4870 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4871 OverflowCmp, DAG); 4872 } 4873 4874 // Convert: 4875 // 4876 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4877 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4878 // 4879 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4880 const ConstantSDNode *CMOVTrue = 4881 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4882 const ConstantSDNode *CMOVFalse = 4883 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4884 4885 if (CMOVTrue && CMOVFalse) { 4886 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4887 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4888 4889 SDValue True; 4890 SDValue False; 4891 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4892 True = SelectTrue; 4893 False = SelectFalse; 4894 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4895 True = SelectFalse; 4896 False = SelectTrue; 4897 } 4898 4899 if (True.getNode() && False.getNode()) { 4900 EVT VT = Op.getValueType(); 4901 SDValue ARMcc = Cond.getOperand(2); 4902 SDValue CCR = Cond.getOperand(3); 4903 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4904 assert(True.getValueType() == VT); 4905 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4906 } 4907 } 4908 } 4909 4910 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4911 // undefined bits before doing a full-word comparison with zero. 4912 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4913 DAG.getConstant(1, dl, Cond.getValueType())); 4914 4915 return DAG.getSelectCC(dl, Cond, 4916 DAG.getConstant(0, dl, Cond.getValueType()), 4917 SelectTrue, SelectFalse, ISD::SETNE); 4918 } 4919 4920 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4921 bool &swpCmpOps, bool &swpVselOps) { 4922 // Start by selecting the GE condition code for opcodes that return true for 4923 // 'equality' 4924 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4925 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4926 CondCode = ARMCC::GE; 4927 4928 // and GT for opcodes that return false for 'equality'. 4929 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4930 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4931 CondCode = ARMCC::GT; 4932 4933 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4934 // to swap the compare operands. 4935 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4936 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4937 swpCmpOps = true; 4938 4939 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4940 // If we have an unordered opcode, we need to swap the operands to the VSEL 4941 // instruction (effectively negating the condition). 4942 // 4943 // This also has the effect of swapping which one of 'less' or 'greater' 4944 // returns true, so we also swap the compare operands. It also switches 4945 // whether we return true for 'equality', so we compensate by picking the 4946 // opposite condition code to our original choice. 4947 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4948 CC == ISD::SETUGT) { 4949 swpCmpOps = !swpCmpOps; 4950 swpVselOps = !swpVselOps; 4951 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4952 } 4953 4954 // 'ordered' is 'anything but unordered', so use the VS condition code and 4955 // swap the VSEL operands. 4956 if (CC == ISD::SETO) { 4957 CondCode = ARMCC::VS; 4958 swpVselOps = true; 4959 } 4960 4961 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4962 // code and swap the VSEL operands. Also do this if we don't care about the 4963 // unordered case. 4964 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4965 CondCode = ARMCC::EQ; 4966 swpVselOps = true; 4967 } 4968 } 4969 4970 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4971 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4972 SDValue Cmp, SelectionDAG &DAG) const { 4973 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4974 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4975 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4976 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4977 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4978 4979 SDValue TrueLow = TrueVal.getValue(0); 4980 SDValue TrueHigh = TrueVal.getValue(1); 4981 SDValue FalseLow = FalseVal.getValue(0); 4982 SDValue FalseHigh = FalseVal.getValue(1); 4983 4984 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4985 ARMcc, CCR, Cmp); 4986 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4987 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4988 4989 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4990 } else { 4991 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4992 Cmp); 4993 } 4994 } 4995 4996 static bool isGTorGE(ISD::CondCode CC) { 4997 return CC == ISD::SETGT || CC == ISD::SETGE; 4998 } 4999 5000 static bool isLTorLE(ISD::CondCode CC) { 5001 return CC == ISD::SETLT || CC == ISD::SETLE; 5002 } 5003 5004 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 5005 // All of these conditions (and their <= and >= counterparts) will do: 5006 // x < k ? k : x 5007 // x > k ? x : k 5008 // k < x ? x : k 5009 // k > x ? k : x 5010 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 5011 const SDValue TrueVal, const SDValue FalseVal, 5012 const ISD::CondCode CC, const SDValue K) { 5013 return (isGTorGE(CC) && 5014 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 5015 (isLTorLE(CC) && 5016 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 5017 } 5018 5019 // Check if two chained conditionals could be converted into SSAT or USAT. 5020 // 5021 // SSAT can replace a set of two conditional selectors that bound a number to an 5022 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 5023 // 5024 // x < -k ? -k : (x > k ? k : x) 5025 // x < -k ? -k : (x < k ? x : k) 5026 // x > -k ? (x > k ? k : x) : -k 5027 // x < k ? (x < -k ? -k : x) : k 5028 // etc. 5029 // 5030 // LLVM canonicalizes these to either a min(max()) or a max(min()) 5031 // pattern. This function tries to match one of these and will return true 5032 // if successful. 5033 // 5034 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 5035 // a power of 2. 5036 // 5037 // It returns true if the conversion can be done, false otherwise. 5038 // Additionally, the variable is returned in parameter V, the constant in K and 5039 // usat is set to true if the conditional represents an unsigned saturation 5040 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 5041 uint64_t &K, bool &Usat) { 5042 SDValue V1 = Op.getOperand(0); 5043 SDValue K1 = Op.getOperand(1); 5044 SDValue TrueVal1 = Op.getOperand(2); 5045 SDValue FalseVal1 = Op.getOperand(3); 5046 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5047 5048 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 5049 if (Op2.getOpcode() != ISD::SELECT_CC) 5050 return false; 5051 5052 SDValue V2 = Op2.getOperand(0); 5053 SDValue K2 = Op2.getOperand(1); 5054 SDValue TrueVal2 = Op2.getOperand(2); 5055 SDValue FalseVal2 = Op2.getOperand(3); 5056 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 5057 5058 SDValue V1Tmp = V1; 5059 SDValue V2Tmp = V2; 5060 5061 if (V1.getOpcode() == ISD::SIGN_EXTEND_INREG && 5062 V2.getOpcode() == ISD::SIGN_EXTEND_INREG) { 5063 V1Tmp = V1.getOperand(0); 5064 V2Tmp = V2.getOperand(0); 5065 } 5066 5067 // Check that the registers and the constants match a max(min()) or min(max()) 5068 // pattern 5069 if (V1Tmp == TrueVal1 && V2Tmp == TrueVal2 && K1 == FalseVal1 && 5070 K2 == FalseVal2 && 5071 ((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2)))) { 5072 5073 // Check that the constant in the lower-bound check is 5074 // the opposite of the constant in the upper-bound check 5075 // in 1's complement. 5076 if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2)) 5077 return false; 5078 5079 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue(); 5080 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue(); 5081 int64_t PosVal = std::max(Val1, Val2); 5082 int64_t NegVal = std::min(Val1, Val2); 5083 5084 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) || 5085 !isPowerOf2_64(PosVal + 1)) 5086 return false; 5087 5088 // Handle the difference between USAT (unsigned) and SSAT (signed) 5089 // saturation 5090 if (Val1 == ~Val2) 5091 Usat = false; 5092 else if (NegVal == 0) 5093 Usat = true; 5094 else 5095 return false; 5096 5097 V = V2Tmp; 5098 // At this point, PosVal is guaranteed to be positive 5099 K = (uint64_t) PosVal; 5100 5101 return true; 5102 } 5103 return false; 5104 } 5105 5106 // Check if a condition of the type x < k ? k : x can be converted into a 5107 // bit operation instead of conditional moves. 5108 // Currently this is allowed given: 5109 // - The conditions and values match up 5110 // - k is 0 or -1 (all ones) 5111 // This function will not check the last condition, thats up to the caller 5112 // It returns true if the transformation can be made, and in such case 5113 // returns x in V, and k in SatK. 5114 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 5115 SDValue &SatK) 5116 { 5117 SDValue LHS = Op.getOperand(0); 5118 SDValue RHS = Op.getOperand(1); 5119 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5120 SDValue TrueVal = Op.getOperand(2); 5121 SDValue FalseVal = Op.getOperand(3); 5122 5123 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 5124 ? &RHS 5125 : nullptr; 5126 5127 // No constant operation in comparison, early out 5128 if (!K) 5129 return false; 5130 5131 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 5132 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 5133 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 5134 5135 // If the constant on left and right side, or variable on left and right, 5136 // does not match, early out 5137 if (*K != KTmp || V != VTmp) 5138 return false; 5139 5140 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 5141 SatK = *K; 5142 return true; 5143 } 5144 5145 return false; 5146 } 5147 5148 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 5149 if (VT == MVT::f32) 5150 return !Subtarget->hasVFP2Base(); 5151 if (VT == MVT::f64) 5152 return !Subtarget->hasFP64(); 5153 if (VT == MVT::f16) 5154 return !Subtarget->hasFullFP16(); 5155 return false; 5156 } 5157 5158 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 5159 EVT VT = Op.getValueType(); 5160 SDLoc dl(Op); 5161 5162 // Try to convert two saturating conditional selects into a single SSAT 5163 SDValue SatValue; 5164 uint64_t SatConstant; 5165 bool SatUSat; 5166 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 5167 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 5168 if (SatUSat) 5169 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 5170 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 5171 else 5172 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 5173 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 5174 } 5175 5176 // Try to convert expressions of the form x < k ? k : x (and similar forms) 5177 // into more efficient bit operations, which is possible when k is 0 or -1 5178 // On ARM and Thumb-2 which have flexible operand 2 this will result in 5179 // single instructions. On Thumb the shift and the bit operation will be two 5180 // instructions. 5181 // Only allow this transformation on full-width (32-bit) operations 5182 SDValue LowerSatConstant; 5183 if (VT == MVT::i32 && 5184 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 5185 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 5186 DAG.getConstant(31, dl, VT)); 5187 if (isNullConstant(LowerSatConstant)) { 5188 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 5189 DAG.getAllOnesConstant(dl, VT)); 5190 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 5191 } else if (isAllOnesConstant(LowerSatConstant)) 5192 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 5193 } 5194 5195 SDValue LHS = Op.getOperand(0); 5196 SDValue RHS = Op.getOperand(1); 5197 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5198 SDValue TrueVal = Op.getOperand(2); 5199 SDValue FalseVal = Op.getOperand(3); 5200 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal); 5201 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal); 5202 5203 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal && 5204 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) { 5205 unsigned TVal = CTVal->getZExtValue(); 5206 unsigned FVal = CFVal->getZExtValue(); 5207 unsigned Opcode = 0; 5208 5209 if (TVal == ~FVal) { 5210 Opcode = ARMISD::CSINV; 5211 } else if (TVal == ~FVal + 1) { 5212 Opcode = ARMISD::CSNEG; 5213 } else if (TVal + 1 == FVal) { 5214 Opcode = ARMISD::CSINC; 5215 } else if (TVal == FVal + 1) { 5216 Opcode = ARMISD::CSINC; 5217 std::swap(TrueVal, FalseVal); 5218 std::swap(TVal, FVal); 5219 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5220 } 5221 5222 if (Opcode) { 5223 // If one of the constants is cheaper than another, materialise the 5224 // cheaper one and let the csel generate the other. 5225 if (Opcode != ARMISD::CSINC && 5226 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) { 5227 std::swap(TrueVal, FalseVal); 5228 std::swap(TVal, FVal); 5229 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5230 } 5231 5232 // Attempt to use ZR checking TVal is 0, possibly inverting the condition 5233 // to get there. CSINC not is invertable like the other two (~(~a) == a, 5234 // -(-a) == a, but (a+1)+1 != a). 5235 if (FVal == 0 && Opcode != ARMISD::CSINC) { 5236 std::swap(TrueVal, FalseVal); 5237 std::swap(TVal, FVal); 5238 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5239 } 5240 if (TVal == 0) 5241 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32); 5242 5243 // Drops F's value because we can get it by inverting/negating TVal. 5244 FalseVal = TrueVal; 5245 5246 SDValue ARMcc; 5247 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5248 EVT VT = TrueVal.getValueType(); 5249 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp); 5250 } 5251 } 5252 5253 if (isUnsupportedFloatingType(LHS.getValueType())) { 5254 DAG.getTargetLoweringInfo().softenSetCCOperands( 5255 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5256 5257 // If softenSetCCOperands only returned one value, we should compare it to 5258 // zero. 5259 if (!RHS.getNode()) { 5260 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5261 CC = ISD::SETNE; 5262 } 5263 } 5264 5265 if (LHS.getValueType() == MVT::i32) { 5266 // Try to generate VSEL on ARMv8. 5267 // The VSEL instruction can't use all the usual ARM condition 5268 // codes: it only has two bits to select the condition code, so it's 5269 // constrained to use only GE, GT, VS and EQ. 5270 // 5271 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 5272 // swap the operands of the previous compare instruction (effectively 5273 // inverting the compare condition, swapping 'less' and 'greater') and 5274 // sometimes need to swap the operands to the VSEL (which inverts the 5275 // condition in the sense of firing whenever the previous condition didn't) 5276 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 5277 TrueVal.getValueType() == MVT::f32 || 5278 TrueVal.getValueType() == MVT::f64)) { 5279 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5280 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 5281 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 5282 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5283 std::swap(TrueVal, FalseVal); 5284 } 5285 } 5286 5287 SDValue ARMcc; 5288 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5289 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5290 // Choose GE over PL, which vsel does now support 5291 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 5292 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 5293 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5294 } 5295 5296 ARMCC::CondCodes CondCode, CondCode2; 5297 FPCCToARMCC(CC, CondCode, CondCode2); 5298 5299 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 5300 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 5301 // must use VSEL (limited condition codes), due to not having conditional f16 5302 // moves. 5303 if (Subtarget->hasFPARMv8Base() && 5304 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 5305 (TrueVal.getValueType() == MVT::f16 || 5306 TrueVal.getValueType() == MVT::f32 || 5307 TrueVal.getValueType() == MVT::f64)) { 5308 bool swpCmpOps = false; 5309 bool swpVselOps = false; 5310 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 5311 5312 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 5313 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 5314 if (swpCmpOps) 5315 std::swap(LHS, RHS); 5316 if (swpVselOps) 5317 std::swap(TrueVal, FalseVal); 5318 } 5319 } 5320 5321 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5322 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5323 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5324 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5325 if (CondCode2 != ARMCC::AL) { 5326 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 5327 // FIXME: Needs another CMP because flag can have but one use. 5328 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 5329 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 5330 } 5331 return Result; 5332 } 5333 5334 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 5335 /// to morph to an integer compare sequence. 5336 static bool canChangeToInt(SDValue Op, bool &SeenZero, 5337 const ARMSubtarget *Subtarget) { 5338 SDNode *N = Op.getNode(); 5339 if (!N->hasOneUse()) 5340 // Otherwise it requires moving the value from fp to integer registers. 5341 return false; 5342 if (!N->getNumValues()) 5343 return false; 5344 EVT VT = Op.getValueType(); 5345 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 5346 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 5347 // vmrs are very slow, e.g. cortex-a8. 5348 return false; 5349 5350 if (isFloatingPointZero(Op)) { 5351 SeenZero = true; 5352 return true; 5353 } 5354 return ISD::isNormalLoad(N); 5355 } 5356 5357 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 5358 if (isFloatingPointZero(Op)) 5359 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 5360 5361 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 5362 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 5363 Ld->getPointerInfo(), Ld->getAlignment(), 5364 Ld->getMemOperand()->getFlags()); 5365 5366 llvm_unreachable("Unknown VFP cmp argument!"); 5367 } 5368 5369 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 5370 SDValue &RetVal1, SDValue &RetVal2) { 5371 SDLoc dl(Op); 5372 5373 if (isFloatingPointZero(Op)) { 5374 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 5375 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 5376 return; 5377 } 5378 5379 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 5380 SDValue Ptr = Ld->getBasePtr(); 5381 RetVal1 = 5382 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 5383 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 5384 5385 EVT PtrType = Ptr.getValueType(); 5386 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 5387 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 5388 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 5389 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 5390 Ld->getPointerInfo().getWithOffset(4), NewAlign, 5391 Ld->getMemOperand()->getFlags()); 5392 return; 5393 } 5394 5395 llvm_unreachable("Unknown VFP cmp argument!"); 5396 } 5397 5398 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 5399 /// f32 and even f64 comparisons to integer ones. 5400 SDValue 5401 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 5402 SDValue Chain = Op.getOperand(0); 5403 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5404 SDValue LHS = Op.getOperand(2); 5405 SDValue RHS = Op.getOperand(3); 5406 SDValue Dest = Op.getOperand(4); 5407 SDLoc dl(Op); 5408 5409 bool LHSSeenZero = false; 5410 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 5411 bool RHSSeenZero = false; 5412 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 5413 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 5414 // If unsafe fp math optimization is enabled and there are no other uses of 5415 // the CMP operands, and the condition code is EQ or NE, we can optimize it 5416 // to an integer comparison. 5417 if (CC == ISD::SETOEQ) 5418 CC = ISD::SETEQ; 5419 else if (CC == ISD::SETUNE) 5420 CC = ISD::SETNE; 5421 5422 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5423 SDValue ARMcc; 5424 if (LHS.getValueType() == MVT::f32) { 5425 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5426 bitcastf32Toi32(LHS, DAG), Mask); 5427 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5428 bitcastf32Toi32(RHS, DAG), Mask); 5429 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5430 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5431 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5432 Chain, Dest, ARMcc, CCR, Cmp); 5433 } 5434 5435 SDValue LHS1, LHS2; 5436 SDValue RHS1, RHS2; 5437 expandf64Toi32(LHS, DAG, LHS1, LHS2); 5438 expandf64Toi32(RHS, DAG, RHS1, RHS2); 5439 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 5440 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 5441 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5442 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5443 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5444 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 5445 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 5446 } 5447 5448 return SDValue(); 5449 } 5450 5451 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 5452 SDValue Chain = Op.getOperand(0); 5453 SDValue Cond = Op.getOperand(1); 5454 SDValue Dest = Op.getOperand(2); 5455 SDLoc dl(Op); 5456 5457 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5458 // instruction. 5459 unsigned Opc = Cond.getOpcode(); 5460 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5461 !Subtarget->isThumb1Only(); 5462 if (Cond.getResNo() == 1 && 5463 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5464 Opc == ISD::USUBO || OptimizeMul)) { 5465 // Only lower legal XALUO ops. 5466 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 5467 return SDValue(); 5468 5469 // The actual operation with overflow check. 5470 SDValue Value, OverflowCmp; 5471 SDValue ARMcc; 5472 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 5473 5474 // Reverse the condition code. 5475 ARMCC::CondCodes CondCode = 5476 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5477 CondCode = ARMCC::getOppositeCondition(CondCode); 5478 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5479 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5480 5481 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5482 OverflowCmp); 5483 } 5484 5485 return SDValue(); 5486 } 5487 5488 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5489 SDValue Chain = Op.getOperand(0); 5490 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5491 SDValue LHS = Op.getOperand(2); 5492 SDValue RHS = Op.getOperand(3); 5493 SDValue Dest = Op.getOperand(4); 5494 SDLoc dl(Op); 5495 5496 if (isUnsupportedFloatingType(LHS.getValueType())) { 5497 DAG.getTargetLoweringInfo().softenSetCCOperands( 5498 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5499 5500 // If softenSetCCOperands only returned one value, we should compare it to 5501 // zero. 5502 if (!RHS.getNode()) { 5503 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5504 CC = ISD::SETNE; 5505 } 5506 } 5507 5508 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5509 // instruction. 5510 unsigned Opc = LHS.getOpcode(); 5511 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5512 !Subtarget->isThumb1Only(); 5513 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5514 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5515 Opc == ISD::USUBO || OptimizeMul) && 5516 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5517 // Only lower legal XALUO ops. 5518 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5519 return SDValue(); 5520 5521 // The actual operation with overflow check. 5522 SDValue Value, OverflowCmp; 5523 SDValue ARMcc; 5524 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5525 5526 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5527 // Reverse the condition code. 5528 ARMCC::CondCodes CondCode = 5529 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5530 CondCode = ARMCC::getOppositeCondition(CondCode); 5531 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5532 } 5533 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5534 5535 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5536 OverflowCmp); 5537 } 5538 5539 if (LHS.getValueType() == MVT::i32) { 5540 SDValue ARMcc; 5541 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5542 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5543 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5544 Chain, Dest, ARMcc, CCR, Cmp); 5545 } 5546 5547 if (getTargetMachine().Options.UnsafeFPMath && 5548 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5549 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5550 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5551 return Result; 5552 } 5553 5554 ARMCC::CondCodes CondCode, CondCode2; 5555 FPCCToARMCC(CC, CondCode, CondCode2); 5556 5557 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5558 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5559 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5560 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5561 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5562 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5563 if (CondCode2 != ARMCC::AL) { 5564 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5565 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5566 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5567 } 5568 return Res; 5569 } 5570 5571 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5572 SDValue Chain = Op.getOperand(0); 5573 SDValue Table = Op.getOperand(1); 5574 SDValue Index = Op.getOperand(2); 5575 SDLoc dl(Op); 5576 5577 EVT PTy = getPointerTy(DAG.getDataLayout()); 5578 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5579 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5580 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5581 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5582 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5583 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5584 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5585 // which does another jump to the destination. This also makes it easier 5586 // to translate it to TBB / TBH later (Thumb2 only). 5587 // FIXME: This might not work if the function is extremely large. 5588 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5589 Addr, Op.getOperand(2), JTI); 5590 } 5591 if (isPositionIndependent() || Subtarget->isROPI()) { 5592 Addr = 5593 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5594 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5595 Chain = Addr.getValue(1); 5596 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5597 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5598 } else { 5599 Addr = 5600 DAG.getLoad(PTy, dl, Chain, Addr, 5601 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5602 Chain = Addr.getValue(1); 5603 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5604 } 5605 } 5606 5607 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5608 EVT VT = Op.getValueType(); 5609 SDLoc dl(Op); 5610 5611 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5612 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5613 return Op; 5614 return DAG.UnrollVectorOp(Op.getNode()); 5615 } 5616 5617 const bool HasFullFP16 = 5618 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5619 5620 EVT NewTy; 5621 const EVT OpTy = Op.getOperand(0).getValueType(); 5622 if (OpTy == MVT::v4f32) 5623 NewTy = MVT::v4i32; 5624 else if (OpTy == MVT::v4f16 && HasFullFP16) 5625 NewTy = MVT::v4i16; 5626 else if (OpTy == MVT::v8f16 && HasFullFP16) 5627 NewTy = MVT::v8i16; 5628 else 5629 llvm_unreachable("Invalid type for custom lowering!"); 5630 5631 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5632 return DAG.UnrollVectorOp(Op.getNode()); 5633 5634 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5635 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5636 } 5637 5638 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5639 EVT VT = Op.getValueType(); 5640 if (VT.isVector()) 5641 return LowerVectorFP_TO_INT(Op, DAG); 5642 5643 bool IsStrict = Op->isStrictFPOpcode(); 5644 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 5645 5646 if (isUnsupportedFloatingType(SrcVal.getValueType())) { 5647 RTLIB::Libcall LC; 5648 if (Op.getOpcode() == ISD::FP_TO_SINT || 5649 Op.getOpcode() == ISD::STRICT_FP_TO_SINT) 5650 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), 5651 Op.getValueType()); 5652 else 5653 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), 5654 Op.getValueType()); 5655 SDLoc Loc(Op); 5656 MakeLibCallOptions CallOptions; 5657 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 5658 SDValue Result; 5659 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal, 5660 CallOptions, Loc, Chain); 5661 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 5662 } 5663 5664 // FIXME: Remove this when we have strict fp instruction selection patterns 5665 if (IsStrict) { 5666 SDLoc Loc(Op); 5667 SDValue Result = 5668 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT 5669 : ISD::FP_TO_UINT, 5670 Loc, Op.getValueType(), SrcVal); 5671 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 5672 } 5673 5674 return Op; 5675 } 5676 5677 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5678 EVT VT = Op.getValueType(); 5679 SDLoc dl(Op); 5680 5681 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5682 if (VT.getVectorElementType() == MVT::f32) 5683 return Op; 5684 return DAG.UnrollVectorOp(Op.getNode()); 5685 } 5686 5687 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5688 Op.getOperand(0).getValueType() == MVT::v8i16) && 5689 "Invalid type for custom lowering!"); 5690 5691 const bool HasFullFP16 = 5692 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5693 5694 EVT DestVecType; 5695 if (VT == MVT::v4f32) 5696 DestVecType = MVT::v4i32; 5697 else if (VT == MVT::v4f16 && HasFullFP16) 5698 DestVecType = MVT::v4i16; 5699 else if (VT == MVT::v8f16 && HasFullFP16) 5700 DestVecType = MVT::v8i16; 5701 else 5702 return DAG.UnrollVectorOp(Op.getNode()); 5703 5704 unsigned CastOpc; 5705 unsigned Opc; 5706 switch (Op.getOpcode()) { 5707 default: llvm_unreachable("Invalid opcode!"); 5708 case ISD::SINT_TO_FP: 5709 CastOpc = ISD::SIGN_EXTEND; 5710 Opc = ISD::SINT_TO_FP; 5711 break; 5712 case ISD::UINT_TO_FP: 5713 CastOpc = ISD::ZERO_EXTEND; 5714 Opc = ISD::UINT_TO_FP; 5715 break; 5716 } 5717 5718 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5719 return DAG.getNode(Opc, dl, VT, Op); 5720 } 5721 5722 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5723 EVT VT = Op.getValueType(); 5724 if (VT.isVector()) 5725 return LowerVectorINT_TO_FP(Op, DAG); 5726 if (isUnsupportedFloatingType(VT)) { 5727 RTLIB::Libcall LC; 5728 if (Op.getOpcode() == ISD::SINT_TO_FP) 5729 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5730 Op.getValueType()); 5731 else 5732 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5733 Op.getValueType()); 5734 MakeLibCallOptions CallOptions; 5735 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5736 CallOptions, SDLoc(Op)).first; 5737 } 5738 5739 return Op; 5740 } 5741 5742 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5743 // Implement fcopysign with a fabs and a conditional fneg. 5744 SDValue Tmp0 = Op.getOperand(0); 5745 SDValue Tmp1 = Op.getOperand(1); 5746 SDLoc dl(Op); 5747 EVT VT = Op.getValueType(); 5748 EVT SrcVT = Tmp1.getValueType(); 5749 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5750 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5751 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5752 5753 if (UseNEON) { 5754 // Use VBSL to copy the sign bit. 5755 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5756 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5757 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5758 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5759 if (VT == MVT::f64) 5760 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5761 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5762 DAG.getConstant(32, dl, MVT::i32)); 5763 else /*if (VT == MVT::f32)*/ 5764 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5765 if (SrcVT == MVT::f32) { 5766 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5767 if (VT == MVT::f64) 5768 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5769 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5770 DAG.getConstant(32, dl, MVT::i32)); 5771 } else if (VT == MVT::f32) 5772 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5773 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5774 DAG.getConstant(32, dl, MVT::i32)); 5775 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5776 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5777 5778 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5779 dl, MVT::i32); 5780 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5781 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5782 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5783 5784 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5785 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5786 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5787 if (VT == MVT::f32) { 5788 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5789 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5790 DAG.getConstant(0, dl, MVT::i32)); 5791 } else { 5792 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5793 } 5794 5795 return Res; 5796 } 5797 5798 // Bitcast operand 1 to i32. 5799 if (SrcVT == MVT::f64) 5800 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5801 Tmp1).getValue(1); 5802 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5803 5804 // Or in the signbit with integer operations. 5805 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5806 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5807 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5808 if (VT == MVT::f32) { 5809 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5810 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5811 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5812 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5813 } 5814 5815 // f64: Or the high part with signbit and then combine two parts. 5816 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5817 Tmp0); 5818 SDValue Lo = Tmp0.getValue(0); 5819 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5820 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5821 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5822 } 5823 5824 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5825 MachineFunction &MF = DAG.getMachineFunction(); 5826 MachineFrameInfo &MFI = MF.getFrameInfo(); 5827 MFI.setReturnAddressIsTaken(true); 5828 5829 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5830 return SDValue(); 5831 5832 EVT VT = Op.getValueType(); 5833 SDLoc dl(Op); 5834 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5835 if (Depth) { 5836 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5837 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5838 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5839 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5840 MachinePointerInfo()); 5841 } 5842 5843 // Return LR, which contains the return address. Mark it an implicit live-in. 5844 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5845 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5846 } 5847 5848 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5849 const ARMBaseRegisterInfo &ARI = 5850 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5851 MachineFunction &MF = DAG.getMachineFunction(); 5852 MachineFrameInfo &MFI = MF.getFrameInfo(); 5853 MFI.setFrameAddressIsTaken(true); 5854 5855 EVT VT = Op.getValueType(); 5856 SDLoc dl(Op); // FIXME probably not meaningful 5857 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5858 Register FrameReg = ARI.getFrameRegister(MF); 5859 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5860 while (Depth--) 5861 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5862 MachinePointerInfo()); 5863 return FrameAddr; 5864 } 5865 5866 // FIXME? Maybe this could be a TableGen attribute on some registers and 5867 // this table could be generated automatically from RegInfo. 5868 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT, 5869 const MachineFunction &MF) const { 5870 Register Reg = StringSwitch<unsigned>(RegName) 5871 .Case("sp", ARM::SP) 5872 .Default(0); 5873 if (Reg) 5874 return Reg; 5875 report_fatal_error(Twine("Invalid register name \"" 5876 + StringRef(RegName) + "\".")); 5877 } 5878 5879 // Result is 64 bit value so split into two 32 bit values and return as a 5880 // pair of values. 5881 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5882 SelectionDAG &DAG) { 5883 SDLoc DL(N); 5884 5885 // This function is only supposed to be called for i64 type destination. 5886 assert(N->getValueType(0) == MVT::i64 5887 && "ExpandREAD_REGISTER called for non-i64 type result."); 5888 5889 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5890 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5891 N->getOperand(0), 5892 N->getOperand(1)); 5893 5894 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5895 Read.getValue(1))); 5896 Results.push_back(Read.getOperand(0)); 5897 } 5898 5899 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5900 /// When \p DstVT, the destination type of \p BC, is on the vector 5901 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5902 /// it might be possible to combine them, such that everything stays on the 5903 /// vector register bank. 5904 /// \p return The node that would replace \p BT, if the combine 5905 /// is possible. 5906 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5907 SelectionDAG &DAG) { 5908 SDValue Op = BC->getOperand(0); 5909 EVT DstVT = BC->getValueType(0); 5910 5911 // The only vector instruction that can produce a scalar (remember, 5912 // since the bitcast was about to be turned into VMOVDRR, the source 5913 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5914 // Moreover, we can do this combine only if there is one use. 5915 // Finally, if the destination type is not a vector, there is not 5916 // much point on forcing everything on the vector bank. 5917 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5918 !Op.hasOneUse()) 5919 return SDValue(); 5920 5921 // If the index is not constant, we will introduce an additional 5922 // multiply that will stick. 5923 // Give up in that case. 5924 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5925 if (!Index) 5926 return SDValue(); 5927 unsigned DstNumElt = DstVT.getVectorNumElements(); 5928 5929 // Compute the new index. 5930 const APInt &APIntIndex = Index->getAPIntValue(); 5931 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5932 NewIndex *= APIntIndex; 5933 // Check if the new constant index fits into i32. 5934 if (NewIndex.getBitWidth() > 32) 5935 return SDValue(); 5936 5937 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5938 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5939 SDLoc dl(Op); 5940 SDValue ExtractSrc = Op.getOperand(0); 5941 EVT VecVT = EVT::getVectorVT( 5942 *DAG.getContext(), DstVT.getScalarType(), 5943 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5944 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5945 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5946 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5947 } 5948 5949 /// ExpandBITCAST - If the target supports VFP, this function is called to 5950 /// expand a bit convert where either the source or destination type is i64 to 5951 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5952 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5953 /// vectors), since the legalizer won't know what to do with that. 5954 SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5955 const ARMSubtarget *Subtarget) const { 5956 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5957 SDLoc dl(N); 5958 SDValue Op = N->getOperand(0); 5959 5960 // This function is only supposed to be called for i16 and i64 types, either 5961 // as the source or destination of the bit convert. 5962 EVT SrcVT = Op.getValueType(); 5963 EVT DstVT = N->getValueType(0); 5964 5965 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) && 5966 (DstVT == MVT::f16 || DstVT == MVT::bf16)) 5967 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(), 5968 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op)); 5969 5970 if ((DstVT == MVT::i16 || DstVT == MVT::i32) && 5971 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) 5972 return DAG.getNode( 5973 ISD::TRUNCATE, SDLoc(N), DstVT, 5974 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op)); 5975 5976 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5977 return SDValue(); 5978 5979 // Turn i64->f64 into VMOVDRR. 5980 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5981 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5982 // if we can combine the bitcast with its source. 5983 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5984 return Val; 5985 5986 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5987 DAG.getConstant(0, dl, MVT::i32)); 5988 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5989 DAG.getConstant(1, dl, MVT::i32)); 5990 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5991 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5992 } 5993 5994 // Turn f64->i64 into VMOVRRD. 5995 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5996 SDValue Cvt; 5997 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5998 SrcVT.getVectorNumElements() > 1) 5999 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 6000 DAG.getVTList(MVT::i32, MVT::i32), 6001 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 6002 else 6003 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 6004 DAG.getVTList(MVT::i32, MVT::i32), Op); 6005 // Merge the pieces into a single i64 value. 6006 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 6007 } 6008 6009 return SDValue(); 6010 } 6011 6012 /// getZeroVector - Returns a vector of specified type with all zero elements. 6013 /// Zero vectors are used to represent vector negation and in those cases 6014 /// will be implemented with the NEON VNEG instruction. However, VNEG does 6015 /// not support i64 elements, so sometimes the zero vectors will need to be 6016 /// explicitly constructed. Regardless, use a canonical VMOV to create the 6017 /// zero vector. 6018 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 6019 assert(VT.isVector() && "Expected a vector type"); 6020 // The canonical modified immediate encoding of a zero vector is....0! 6021 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 6022 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 6023 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 6024 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6025 } 6026 6027 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 6028 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 6029 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 6030 SelectionDAG &DAG) const { 6031 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6032 EVT VT = Op.getValueType(); 6033 unsigned VTBits = VT.getSizeInBits(); 6034 SDLoc dl(Op); 6035 SDValue ShOpLo = Op.getOperand(0); 6036 SDValue ShOpHi = Op.getOperand(1); 6037 SDValue ShAmt = Op.getOperand(2); 6038 SDValue ARMcc; 6039 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6040 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 6041 6042 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 6043 6044 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6045 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 6046 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 6047 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 6048 DAG.getConstant(VTBits, dl, MVT::i32)); 6049 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 6050 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 6051 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 6052 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6053 ISD::SETGE, ARMcc, DAG, dl); 6054 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 6055 ARMcc, CCR, CmpLo); 6056 6057 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 6058 SDValue HiBigShift = Opc == ISD::SRA 6059 ? DAG.getNode(Opc, dl, VT, ShOpHi, 6060 DAG.getConstant(VTBits - 1, dl, VT)) 6061 : DAG.getConstant(0, dl, VT); 6062 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6063 ISD::SETGE, ARMcc, DAG, dl); 6064 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 6065 ARMcc, CCR, CmpHi); 6066 6067 SDValue Ops[2] = { Lo, Hi }; 6068 return DAG.getMergeValues(Ops, dl); 6069 } 6070 6071 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 6072 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 6073 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 6074 SelectionDAG &DAG) const { 6075 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6076 EVT VT = Op.getValueType(); 6077 unsigned VTBits = VT.getSizeInBits(); 6078 SDLoc dl(Op); 6079 SDValue ShOpLo = Op.getOperand(0); 6080 SDValue ShOpHi = Op.getOperand(1); 6081 SDValue ShAmt = Op.getOperand(2); 6082 SDValue ARMcc; 6083 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6084 6085 assert(Op.getOpcode() == ISD::SHL_PARTS); 6086 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6087 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 6088 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 6089 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 6090 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 6091 6092 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 6093 DAG.getConstant(VTBits, dl, MVT::i32)); 6094 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 6095 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6096 ISD::SETGE, ARMcc, DAG, dl); 6097 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 6098 ARMcc, CCR, CmpHi); 6099 6100 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6101 ISD::SETGE, ARMcc, DAG, dl); 6102 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6103 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 6104 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 6105 6106 SDValue Ops[2] = { Lo, Hi }; 6107 return DAG.getMergeValues(Ops, dl); 6108 } 6109 6110 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 6111 SelectionDAG &DAG) const { 6112 // The rounding mode is in bits 23:22 of the FPSCR. 6113 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 6114 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 6115 // so that the shift + and get folded into a bitfield extract. 6116 SDLoc dl(Op); 6117 SDValue Chain = Op.getOperand(0); 6118 SDValue Ops[] = {Chain, 6119 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)}; 6120 6121 SDValue FPSCR = 6122 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops); 6123 Chain = FPSCR.getValue(1); 6124 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 6125 DAG.getConstant(1U << 22, dl, MVT::i32)); 6126 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 6127 DAG.getConstant(22, dl, MVT::i32)); 6128 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 6129 DAG.getConstant(3, dl, MVT::i32)); 6130 return DAG.getMergeValues({And, Chain}, dl); 6131 } 6132 6133 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 6134 const ARMSubtarget *ST) { 6135 SDLoc dl(N); 6136 EVT VT = N->getValueType(0); 6137 if (VT.isVector() && ST->hasNEON()) { 6138 6139 // Compute the least significant set bit: LSB = X & -X 6140 SDValue X = N->getOperand(0); 6141 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 6142 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 6143 6144 EVT ElemTy = VT.getVectorElementType(); 6145 6146 if (ElemTy == MVT::i8) { 6147 // Compute with: cttz(x) = ctpop(lsb - 1) 6148 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6149 DAG.getTargetConstant(1, dl, ElemTy)); 6150 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6151 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6152 } 6153 6154 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 6155 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 6156 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 6157 unsigned NumBits = ElemTy.getSizeInBits(); 6158 SDValue WidthMinus1 = 6159 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6160 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 6161 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 6162 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 6163 } 6164 6165 // Compute with: cttz(x) = ctpop(lsb - 1) 6166 6167 // Compute LSB - 1. 6168 SDValue Bits; 6169 if (ElemTy == MVT::i64) { 6170 // Load constant 0xffff'ffff'ffff'ffff to register. 6171 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6172 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 6173 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 6174 } else { 6175 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6176 DAG.getTargetConstant(1, dl, ElemTy)); 6177 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6178 } 6179 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6180 } 6181 6182 if (!ST->hasV6T2Ops()) 6183 return SDValue(); 6184 6185 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 6186 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 6187 } 6188 6189 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 6190 const ARMSubtarget *ST) { 6191 EVT VT = N->getValueType(0); 6192 SDLoc DL(N); 6193 6194 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 6195 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 6196 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 6197 "Unexpected type for custom ctpop lowering"); 6198 6199 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6200 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 6201 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 6202 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 6203 6204 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 6205 unsigned EltSize = 8; 6206 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 6207 while (EltSize != VT.getScalarSizeInBits()) { 6208 SmallVector<SDValue, 8> Ops; 6209 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 6210 TLI.getPointerTy(DAG.getDataLayout()))); 6211 Ops.push_back(Res); 6212 6213 EltSize *= 2; 6214 NumElts /= 2; 6215 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 6216 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 6217 } 6218 6219 return Res; 6220 } 6221 6222 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 6223 /// operand of a vector shift operation, where all the elements of the 6224 /// build_vector must have the same constant integer value. 6225 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6226 // Ignore bit_converts. 6227 while (Op.getOpcode() == ISD::BITCAST) 6228 Op = Op.getOperand(0); 6229 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6230 APInt SplatBits, SplatUndef; 6231 unsigned SplatBitSize; 6232 bool HasAnyUndefs; 6233 if (!BVN || 6234 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 6235 ElementBits) || 6236 SplatBitSize > ElementBits) 6237 return false; 6238 Cnt = SplatBits.getSExtValue(); 6239 return true; 6240 } 6241 6242 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6243 /// operand of a vector shift left operation. That value must be in the range: 6244 /// 0 <= Value < ElementBits for a left shift; or 6245 /// 0 <= Value <= ElementBits for a long left shift. 6246 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6247 assert(VT.isVector() && "vector shift count is not a vector type"); 6248 int64_t ElementBits = VT.getScalarSizeInBits(); 6249 if (!getVShiftImm(Op, ElementBits, Cnt)) 6250 return false; 6251 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6252 } 6253 6254 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6255 /// operand of a vector shift right operation. For a shift opcode, the value 6256 /// is positive, but for an intrinsic the value count must be negative. The 6257 /// absolute value must be in the range: 6258 /// 1 <= |Value| <= ElementBits for a right shift; or 6259 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 6260 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 6261 int64_t &Cnt) { 6262 assert(VT.isVector() && "vector shift count is not a vector type"); 6263 int64_t ElementBits = VT.getScalarSizeInBits(); 6264 if (!getVShiftImm(Op, ElementBits, Cnt)) 6265 return false; 6266 if (!isIntrinsic) 6267 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6268 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 6269 Cnt = -Cnt; 6270 return true; 6271 } 6272 return false; 6273 } 6274 6275 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 6276 const ARMSubtarget *ST) { 6277 EVT VT = N->getValueType(0); 6278 SDLoc dl(N); 6279 int64_t Cnt; 6280 6281 if (!VT.isVector()) 6282 return SDValue(); 6283 6284 // We essentially have two forms here. Shift by an immediate and shift by a 6285 // vector register (there are also shift by a gpr, but that is just handled 6286 // with a tablegen pattern). We cannot easily match shift by an immediate in 6287 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 6288 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 6289 // signed or unsigned, and a negative shift indicates a shift right). 6290 if (N->getOpcode() == ISD::SHL) { 6291 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 6292 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 6293 DAG.getConstant(Cnt, dl, MVT::i32)); 6294 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 6295 N->getOperand(1)); 6296 } 6297 6298 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 6299 "unexpected vector shift opcode"); 6300 6301 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 6302 unsigned VShiftOpc = 6303 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 6304 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 6305 DAG.getConstant(Cnt, dl, MVT::i32)); 6306 } 6307 6308 // Other right shifts we don't have operations for (we use a shift left by a 6309 // negative number). 6310 EVT ShiftVT = N->getOperand(1).getValueType(); 6311 SDValue NegatedCount = DAG.getNode( 6312 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 6313 unsigned VShiftOpc = 6314 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 6315 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 6316 } 6317 6318 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 6319 const ARMSubtarget *ST) { 6320 EVT VT = N->getValueType(0); 6321 SDLoc dl(N); 6322 6323 // We can get here for a node like i32 = ISD::SHL i32, i64 6324 if (VT != MVT::i64) 6325 return SDValue(); 6326 6327 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 6328 N->getOpcode() == ISD::SHL) && 6329 "Unknown shift to lower!"); 6330 6331 unsigned ShOpc = N->getOpcode(); 6332 if (ST->hasMVEIntegerOps()) { 6333 SDValue ShAmt = N->getOperand(1); 6334 unsigned ShPartsOpc = ARMISD::LSLL; 6335 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 6336 6337 // If the shift amount is greater than 32 or has a greater bitwidth than 64 6338 // then do the default optimisation 6339 if (ShAmt->getValueType(0).getSizeInBits() > 64 || 6340 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32))) 6341 return SDValue(); 6342 6343 // Extract the lower 32 bits of the shift amount if it's not an i32 6344 if (ShAmt->getValueType(0) != MVT::i32) 6345 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32); 6346 6347 if (ShOpc == ISD::SRL) { 6348 if (!Con) 6349 // There is no t2LSRLr instruction so negate and perform an lsll if the 6350 // shift amount is in a register, emulating a right shift. 6351 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6352 DAG.getConstant(0, dl, MVT::i32), ShAmt); 6353 else 6354 // Else generate an lsrl on the immediate shift amount 6355 ShPartsOpc = ARMISD::LSRL; 6356 } else if (ShOpc == ISD::SRA) 6357 ShPartsOpc = ARMISD::ASRL; 6358 6359 // Lower 32 bits of the destination/source 6360 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6361 DAG.getConstant(0, dl, MVT::i32)); 6362 // Upper 32 bits of the destination/source 6363 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6364 DAG.getConstant(1, dl, MVT::i32)); 6365 6366 // Generate the shift operation as computed above 6367 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 6368 ShAmt); 6369 // The upper 32 bits come from the second return value of lsll 6370 Hi = SDValue(Lo.getNode(), 1); 6371 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6372 } 6373 6374 // We only lower SRA, SRL of 1 here, all others use generic lowering. 6375 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 6376 return SDValue(); 6377 6378 // If we are in thumb mode, we don't have RRX. 6379 if (ST->isThumb1Only()) 6380 return SDValue(); 6381 6382 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 6383 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6384 DAG.getConstant(0, dl, MVT::i32)); 6385 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6386 DAG.getConstant(1, dl, MVT::i32)); 6387 6388 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 6389 // captures the result into a carry flag. 6390 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 6391 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 6392 6393 // The low part is an ARMISD::RRX operand, which shifts the carry in. 6394 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 6395 6396 // Merge the pieces into a single i64 value. 6397 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6398 } 6399 6400 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 6401 const ARMSubtarget *ST) { 6402 bool Invert = false; 6403 bool Swap = false; 6404 unsigned Opc = ARMCC::AL; 6405 6406 SDValue Op0 = Op.getOperand(0); 6407 SDValue Op1 = Op.getOperand(1); 6408 SDValue CC = Op.getOperand(2); 6409 EVT VT = Op.getValueType(); 6410 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 6411 SDLoc dl(Op); 6412 6413 EVT CmpVT; 6414 if (ST->hasNEON()) 6415 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 6416 else { 6417 assert(ST->hasMVEIntegerOps() && 6418 "No hardware support for integer vector comparison!"); 6419 6420 if (Op.getValueType().getVectorElementType() != MVT::i1) 6421 return SDValue(); 6422 6423 // Make sure we expand floating point setcc to scalar if we do not have 6424 // mve.fp, so that we can handle them from there. 6425 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 6426 return SDValue(); 6427 6428 CmpVT = VT; 6429 } 6430 6431 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 6432 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 6433 // Special-case integer 64-bit equality comparisons. They aren't legal, 6434 // but they can be lowered with a few vector instructions. 6435 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 6436 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 6437 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 6438 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 6439 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 6440 DAG.getCondCode(ISD::SETEQ)); 6441 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 6442 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 6443 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 6444 if (SetCCOpcode == ISD::SETNE) 6445 Merged = DAG.getNOT(dl, Merged, CmpVT); 6446 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 6447 return Merged; 6448 } 6449 6450 if (CmpVT.getVectorElementType() == MVT::i64) 6451 // 64-bit comparisons are not legal in general. 6452 return SDValue(); 6453 6454 if (Op1.getValueType().isFloatingPoint()) { 6455 switch (SetCCOpcode) { 6456 default: llvm_unreachable("Illegal FP comparison"); 6457 case ISD::SETUNE: 6458 case ISD::SETNE: 6459 if (ST->hasMVEFloatOps()) { 6460 Opc = ARMCC::NE; break; 6461 } else { 6462 Invert = true; LLVM_FALLTHROUGH; 6463 } 6464 case ISD::SETOEQ: 6465 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6466 case ISD::SETOLT: 6467 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6468 case ISD::SETOGT: 6469 case ISD::SETGT: Opc = ARMCC::GT; break; 6470 case ISD::SETOLE: 6471 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6472 case ISD::SETOGE: 6473 case ISD::SETGE: Opc = ARMCC::GE; break; 6474 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6475 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6476 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6477 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6478 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6479 case ISD::SETONE: { 6480 // Expand this to (OLT | OGT). 6481 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6482 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6483 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6484 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6485 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6486 if (Invert) 6487 Result = DAG.getNOT(dl, Result, VT); 6488 return Result; 6489 } 6490 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6491 case ISD::SETO: { 6492 // Expand this to (OLT | OGE). 6493 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6494 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6495 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6496 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6497 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6498 if (Invert) 6499 Result = DAG.getNOT(dl, Result, VT); 6500 return Result; 6501 } 6502 } 6503 } else { 6504 // Integer comparisons. 6505 switch (SetCCOpcode) { 6506 default: llvm_unreachable("Illegal integer comparison"); 6507 case ISD::SETNE: 6508 if (ST->hasMVEIntegerOps()) { 6509 Opc = ARMCC::NE; break; 6510 } else { 6511 Invert = true; LLVM_FALLTHROUGH; 6512 } 6513 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6514 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6515 case ISD::SETGT: Opc = ARMCC::GT; break; 6516 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6517 case ISD::SETGE: Opc = ARMCC::GE; break; 6518 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6519 case ISD::SETUGT: Opc = ARMCC::HI; break; 6520 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6521 case ISD::SETUGE: Opc = ARMCC::HS; break; 6522 } 6523 6524 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6525 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6526 SDValue AndOp; 6527 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6528 AndOp = Op0; 6529 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6530 AndOp = Op1; 6531 6532 // Ignore bitconvert. 6533 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6534 AndOp = AndOp.getOperand(0); 6535 6536 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6537 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6538 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6539 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6540 if (!Invert) 6541 Result = DAG.getNOT(dl, Result, VT); 6542 return Result; 6543 } 6544 } 6545 } 6546 6547 if (Swap) 6548 std::swap(Op0, Op1); 6549 6550 // If one of the operands is a constant vector zero, attempt to fold the 6551 // comparison to a specialized compare-against-zero form. 6552 SDValue SingleOp; 6553 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6554 SingleOp = Op0; 6555 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6556 if (Opc == ARMCC::GE) 6557 Opc = ARMCC::LE; 6558 else if (Opc == ARMCC::GT) 6559 Opc = ARMCC::LT; 6560 SingleOp = Op1; 6561 } 6562 6563 SDValue Result; 6564 if (SingleOp.getNode()) { 6565 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6566 DAG.getConstant(Opc, dl, MVT::i32)); 6567 } else { 6568 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6569 DAG.getConstant(Opc, dl, MVT::i32)); 6570 } 6571 6572 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6573 6574 if (Invert) 6575 Result = DAG.getNOT(dl, Result, VT); 6576 6577 return Result; 6578 } 6579 6580 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6581 SDValue LHS = Op.getOperand(0); 6582 SDValue RHS = Op.getOperand(1); 6583 SDValue Carry = Op.getOperand(2); 6584 SDValue Cond = Op.getOperand(3); 6585 SDLoc DL(Op); 6586 6587 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6588 6589 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6590 // have to invert the carry first. 6591 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6592 DAG.getConstant(1, DL, MVT::i32), Carry); 6593 // This converts the boolean value carry into the carry flag. 6594 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6595 6596 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6597 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6598 6599 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6600 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6601 SDValue ARMcc = DAG.getConstant( 6602 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6603 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6604 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6605 Cmp.getValue(1), SDValue()); 6606 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6607 CCR, Chain.getValue(1)); 6608 } 6609 6610 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6611 /// valid vector constant for a NEON or MVE instruction with a "modified 6612 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6613 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6614 unsigned SplatBitSize, SelectionDAG &DAG, 6615 const SDLoc &dl, EVT &VT, EVT VectorVT, 6616 VMOVModImmType type) { 6617 unsigned OpCmode, Imm; 6618 bool is128Bits = VectorVT.is128BitVector(); 6619 6620 // SplatBitSize is set to the smallest size that splats the vector, so a 6621 // zero vector will always have SplatBitSize == 8. However, NEON modified 6622 // immediate instructions others than VMOV do not support the 8-bit encoding 6623 // of a zero vector, and the default encoding of zero is supposed to be the 6624 // 32-bit version. 6625 if (SplatBits == 0) 6626 SplatBitSize = 32; 6627 6628 switch (SplatBitSize) { 6629 case 8: 6630 if (type != VMOVModImm) 6631 return SDValue(); 6632 // Any 1-byte value is OK. Op=0, Cmode=1110. 6633 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6634 OpCmode = 0xe; 6635 Imm = SplatBits; 6636 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6637 break; 6638 6639 case 16: 6640 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6641 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6642 if ((SplatBits & ~0xff) == 0) { 6643 // Value = 0x00nn: Op=x, Cmode=100x. 6644 OpCmode = 0x8; 6645 Imm = SplatBits; 6646 break; 6647 } 6648 if ((SplatBits & ~0xff00) == 0) { 6649 // Value = 0xnn00: Op=x, Cmode=101x. 6650 OpCmode = 0xa; 6651 Imm = SplatBits >> 8; 6652 break; 6653 } 6654 return SDValue(); 6655 6656 case 32: 6657 // NEON's 32-bit VMOV supports splat values where: 6658 // * only one byte is nonzero, or 6659 // * the least significant byte is 0xff and the second byte is nonzero, or 6660 // * the least significant 2 bytes are 0xff and the third is nonzero. 6661 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6662 if ((SplatBits & ~0xff) == 0) { 6663 // Value = 0x000000nn: Op=x, Cmode=000x. 6664 OpCmode = 0; 6665 Imm = SplatBits; 6666 break; 6667 } 6668 if ((SplatBits & ~0xff00) == 0) { 6669 // Value = 0x0000nn00: Op=x, Cmode=001x. 6670 OpCmode = 0x2; 6671 Imm = SplatBits >> 8; 6672 break; 6673 } 6674 if ((SplatBits & ~0xff0000) == 0) { 6675 // Value = 0x00nn0000: Op=x, Cmode=010x. 6676 OpCmode = 0x4; 6677 Imm = SplatBits >> 16; 6678 break; 6679 } 6680 if ((SplatBits & ~0xff000000) == 0) { 6681 // Value = 0xnn000000: Op=x, Cmode=011x. 6682 OpCmode = 0x6; 6683 Imm = SplatBits >> 24; 6684 break; 6685 } 6686 6687 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6688 if (type == OtherModImm) return SDValue(); 6689 6690 if ((SplatBits & ~0xffff) == 0 && 6691 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6692 // Value = 0x0000nnff: Op=x, Cmode=1100. 6693 OpCmode = 0xc; 6694 Imm = SplatBits >> 8; 6695 break; 6696 } 6697 6698 // cmode == 0b1101 is not supported for MVE VMVN 6699 if (type == MVEVMVNModImm) 6700 return SDValue(); 6701 6702 if ((SplatBits & ~0xffffff) == 0 && 6703 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6704 // Value = 0x00nnffff: Op=x, Cmode=1101. 6705 OpCmode = 0xd; 6706 Imm = SplatBits >> 16; 6707 break; 6708 } 6709 6710 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6711 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6712 // VMOV.I32. A (very) minor optimization would be to replicate the value 6713 // and fall through here to test for a valid 64-bit splat. But, then the 6714 // caller would also need to check and handle the change in size. 6715 return SDValue(); 6716 6717 case 64: { 6718 if (type != VMOVModImm) 6719 return SDValue(); 6720 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6721 uint64_t BitMask = 0xff; 6722 uint64_t Val = 0; 6723 unsigned ImmMask = 1; 6724 Imm = 0; 6725 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6726 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6727 Val |= BitMask; 6728 Imm |= ImmMask; 6729 } else if ((SplatBits & BitMask) != 0) { 6730 return SDValue(); 6731 } 6732 BitMask <<= 8; 6733 ImmMask <<= 1; 6734 } 6735 6736 if (DAG.getDataLayout().isBigEndian()) { 6737 // Reverse the order of elements within the vector. 6738 unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8; 6739 unsigned Mask = (1 << BytesPerElem) - 1; 6740 unsigned NumElems = 8 / BytesPerElem; 6741 unsigned NewImm = 0; 6742 for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) { 6743 unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask); 6744 NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem; 6745 } 6746 Imm = NewImm; 6747 } 6748 6749 // Op=1, Cmode=1110. 6750 OpCmode = 0x1e; 6751 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6752 break; 6753 } 6754 6755 default: 6756 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6757 } 6758 6759 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6760 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6761 } 6762 6763 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6764 const ARMSubtarget *ST) const { 6765 EVT VT = Op.getValueType(); 6766 bool IsDouble = (VT == MVT::f64); 6767 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6768 const APFloat &FPVal = CFP->getValueAPF(); 6769 6770 // Prevent floating-point constants from using literal loads 6771 // when execute-only is enabled. 6772 if (ST->genExecuteOnly()) { 6773 // If we can represent the constant as an immediate, don't lower it 6774 if (isFPImmLegal(FPVal, VT)) 6775 return Op; 6776 // Otherwise, construct as integer, and move to float register 6777 APInt INTVal = FPVal.bitcastToAPInt(); 6778 SDLoc DL(CFP); 6779 switch (VT.getSimpleVT().SimpleTy) { 6780 default: 6781 llvm_unreachable("Unknown floating point type!"); 6782 break; 6783 case MVT::f64: { 6784 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6785 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6786 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6787 } 6788 case MVT::f32: 6789 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6790 DAG.getConstant(INTVal, DL, MVT::i32)); 6791 } 6792 } 6793 6794 if (!ST->hasVFP3Base()) 6795 return SDValue(); 6796 6797 // Use the default (constant pool) lowering for double constants when we have 6798 // an SP-only FPU 6799 if (IsDouble && !Subtarget->hasFP64()) 6800 return SDValue(); 6801 6802 // Try splatting with a VMOV.f32... 6803 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6804 6805 if (ImmVal != -1) { 6806 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6807 // We have code in place to select a valid ConstantFP already, no need to 6808 // do any mangling. 6809 return Op; 6810 } 6811 6812 // It's a float and we are trying to use NEON operations where 6813 // possible. Lower it to a splat followed by an extract. 6814 SDLoc DL(Op); 6815 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6816 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6817 NewVal); 6818 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6819 DAG.getConstant(0, DL, MVT::i32)); 6820 } 6821 6822 // The rest of our options are NEON only, make sure that's allowed before 6823 // proceeding.. 6824 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6825 return SDValue(); 6826 6827 EVT VMovVT; 6828 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6829 6830 // It wouldn't really be worth bothering for doubles except for one very 6831 // important value, which does happen to match: 0.0. So make sure we don't do 6832 // anything stupid. 6833 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6834 return SDValue(); 6835 6836 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6837 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6838 VMovVT, VT, VMOVModImm); 6839 if (NewVal != SDValue()) { 6840 SDLoc DL(Op); 6841 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6842 NewVal); 6843 if (IsDouble) 6844 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6845 6846 // It's a float: cast and extract a vector element. 6847 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6848 VecConstant); 6849 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6850 DAG.getConstant(0, DL, MVT::i32)); 6851 } 6852 6853 // Finally, try a VMVN.i32 6854 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6855 VT, VMVNModImm); 6856 if (NewVal != SDValue()) { 6857 SDLoc DL(Op); 6858 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6859 6860 if (IsDouble) 6861 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6862 6863 // It's a float: cast and extract a vector element. 6864 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6865 VecConstant); 6866 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6867 DAG.getConstant(0, DL, MVT::i32)); 6868 } 6869 6870 return SDValue(); 6871 } 6872 6873 // check if an VEXT instruction can handle the shuffle mask when the 6874 // vector sources of the shuffle are the same. 6875 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6876 unsigned NumElts = VT.getVectorNumElements(); 6877 6878 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6879 if (M[0] < 0) 6880 return false; 6881 6882 Imm = M[0]; 6883 6884 // If this is a VEXT shuffle, the immediate value is the index of the first 6885 // element. The other shuffle indices must be the successive elements after 6886 // the first one. 6887 unsigned ExpectedElt = Imm; 6888 for (unsigned i = 1; i < NumElts; ++i) { 6889 // Increment the expected index. If it wraps around, just follow it 6890 // back to index zero and keep going. 6891 ++ExpectedElt; 6892 if (ExpectedElt == NumElts) 6893 ExpectedElt = 0; 6894 6895 if (M[i] < 0) continue; // ignore UNDEF indices 6896 if (ExpectedElt != static_cast<unsigned>(M[i])) 6897 return false; 6898 } 6899 6900 return true; 6901 } 6902 6903 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6904 bool &ReverseVEXT, unsigned &Imm) { 6905 unsigned NumElts = VT.getVectorNumElements(); 6906 ReverseVEXT = false; 6907 6908 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6909 if (M[0] < 0) 6910 return false; 6911 6912 Imm = M[0]; 6913 6914 // If this is a VEXT shuffle, the immediate value is the index of the first 6915 // element. The other shuffle indices must be the successive elements after 6916 // the first one. 6917 unsigned ExpectedElt = Imm; 6918 for (unsigned i = 1; i < NumElts; ++i) { 6919 // Increment the expected index. If it wraps around, it may still be 6920 // a VEXT but the source vectors must be swapped. 6921 ExpectedElt += 1; 6922 if (ExpectedElt == NumElts * 2) { 6923 ExpectedElt = 0; 6924 ReverseVEXT = true; 6925 } 6926 6927 if (M[i] < 0) continue; // ignore UNDEF indices 6928 if (ExpectedElt != static_cast<unsigned>(M[i])) 6929 return false; 6930 } 6931 6932 // Adjust the index value if the source operands will be swapped. 6933 if (ReverseVEXT) 6934 Imm -= NumElts; 6935 6936 return true; 6937 } 6938 6939 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6940 /// instruction with the specified blocksize. (The order of the elements 6941 /// within each block of the vector is reversed.) 6942 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6943 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6944 "Only possible block sizes for VREV are: 16, 32, 64"); 6945 6946 unsigned EltSz = VT.getScalarSizeInBits(); 6947 if (EltSz == 64) 6948 return false; 6949 6950 unsigned NumElts = VT.getVectorNumElements(); 6951 unsigned BlockElts = M[0] + 1; 6952 // If the first shuffle index is UNDEF, be optimistic. 6953 if (M[0] < 0) 6954 BlockElts = BlockSize / EltSz; 6955 6956 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6957 return false; 6958 6959 for (unsigned i = 0; i < NumElts; ++i) { 6960 if (M[i] < 0) continue; // ignore UNDEF indices 6961 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6962 return false; 6963 } 6964 6965 return true; 6966 } 6967 6968 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6969 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6970 // range, then 0 is placed into the resulting vector. So pretty much any mask 6971 // of 8 elements can work here. 6972 return VT == MVT::v8i8 && M.size() == 8; 6973 } 6974 6975 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6976 unsigned Index) { 6977 if (Mask.size() == Elements * 2) 6978 return Index / Elements; 6979 return Mask[Index] == 0 ? 0 : 1; 6980 } 6981 6982 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6983 // checking that pairs of elements in the shuffle mask represent the same index 6984 // in each vector, incrementing the expected index by 2 at each step. 6985 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6986 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6987 // v2={e,f,g,h} 6988 // WhichResult gives the offset for each element in the mask based on which 6989 // of the two results it belongs to. 6990 // 6991 // The transpose can be represented either as: 6992 // result1 = shufflevector v1, v2, result1_shuffle_mask 6993 // result2 = shufflevector v1, v2, result2_shuffle_mask 6994 // where v1/v2 and the shuffle masks have the same number of elements 6995 // (here WhichResult (see below) indicates which result is being checked) 6996 // 6997 // or as: 6998 // results = shufflevector v1, v2, shuffle_mask 6999 // where both results are returned in one vector and the shuffle mask has twice 7000 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 7001 // want to check the low half and high half of the shuffle mask as if it were 7002 // the other case 7003 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7004 unsigned EltSz = VT.getScalarSizeInBits(); 7005 if (EltSz == 64) 7006 return false; 7007 7008 unsigned NumElts = VT.getVectorNumElements(); 7009 if (M.size() != NumElts && M.size() != NumElts*2) 7010 return false; 7011 7012 // If the mask is twice as long as the input vector then we need to check the 7013 // upper and lower parts of the mask with a matching value for WhichResult 7014 // FIXME: A mask with only even values will be rejected in case the first 7015 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 7016 // M[0] is used to determine WhichResult 7017 for (unsigned i = 0; i < M.size(); i += NumElts) { 7018 WhichResult = SelectPairHalf(NumElts, M, i); 7019 for (unsigned j = 0; j < NumElts; j += 2) { 7020 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 7021 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 7022 return false; 7023 } 7024 } 7025 7026 if (M.size() == NumElts*2) 7027 WhichResult = 0; 7028 7029 return true; 7030 } 7031 7032 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 7033 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7034 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 7035 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7036 unsigned EltSz = VT.getScalarSizeInBits(); 7037 if (EltSz == 64) 7038 return false; 7039 7040 unsigned NumElts = VT.getVectorNumElements(); 7041 if (M.size() != NumElts && M.size() != NumElts*2) 7042 return false; 7043 7044 for (unsigned i = 0; i < M.size(); i += NumElts) { 7045 WhichResult = SelectPairHalf(NumElts, M, i); 7046 for (unsigned j = 0; j < NumElts; j += 2) { 7047 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 7048 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 7049 return false; 7050 } 7051 } 7052 7053 if (M.size() == NumElts*2) 7054 WhichResult = 0; 7055 7056 return true; 7057 } 7058 7059 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 7060 // that the mask elements are either all even and in steps of size 2 or all odd 7061 // and in steps of size 2. 7062 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 7063 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 7064 // v2={e,f,g,h} 7065 // Requires similar checks to that of isVTRNMask with 7066 // respect the how results are returned. 7067 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7068 unsigned EltSz = VT.getScalarSizeInBits(); 7069 if (EltSz == 64) 7070 return false; 7071 7072 unsigned NumElts = VT.getVectorNumElements(); 7073 if (M.size() != NumElts && M.size() != NumElts*2) 7074 return false; 7075 7076 for (unsigned i = 0; i < M.size(); i += NumElts) { 7077 WhichResult = SelectPairHalf(NumElts, M, i); 7078 for (unsigned j = 0; j < NumElts; ++j) { 7079 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 7080 return false; 7081 } 7082 } 7083 7084 if (M.size() == NumElts*2) 7085 WhichResult = 0; 7086 7087 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7088 if (VT.is64BitVector() && EltSz == 32) 7089 return false; 7090 7091 return true; 7092 } 7093 7094 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 7095 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7096 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 7097 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7098 unsigned EltSz = VT.getScalarSizeInBits(); 7099 if (EltSz == 64) 7100 return false; 7101 7102 unsigned NumElts = VT.getVectorNumElements(); 7103 if (M.size() != NumElts && M.size() != NumElts*2) 7104 return false; 7105 7106 unsigned Half = NumElts / 2; 7107 for (unsigned i = 0; i < M.size(); i += NumElts) { 7108 WhichResult = SelectPairHalf(NumElts, M, i); 7109 for (unsigned j = 0; j < NumElts; j += Half) { 7110 unsigned Idx = WhichResult; 7111 for (unsigned k = 0; k < Half; ++k) { 7112 int MIdx = M[i + j + k]; 7113 if (MIdx >= 0 && (unsigned) MIdx != Idx) 7114 return false; 7115 Idx += 2; 7116 } 7117 } 7118 } 7119 7120 if (M.size() == NumElts*2) 7121 WhichResult = 0; 7122 7123 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7124 if (VT.is64BitVector() && EltSz == 32) 7125 return false; 7126 7127 return true; 7128 } 7129 7130 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 7131 // that pairs of elements of the shufflemask represent the same index in each 7132 // vector incrementing sequentially through the vectors. 7133 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 7134 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 7135 // v2={e,f,g,h} 7136 // Requires similar checks to that of isVTRNMask with respect the how results 7137 // are returned. 7138 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7139 unsigned EltSz = VT.getScalarSizeInBits(); 7140 if (EltSz == 64) 7141 return false; 7142 7143 unsigned NumElts = VT.getVectorNumElements(); 7144 if (M.size() != NumElts && M.size() != NumElts*2) 7145 return false; 7146 7147 for (unsigned i = 0; i < M.size(); i += NumElts) { 7148 WhichResult = SelectPairHalf(NumElts, M, i); 7149 unsigned Idx = WhichResult * NumElts / 2; 7150 for (unsigned j = 0; j < NumElts; j += 2) { 7151 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7152 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 7153 return false; 7154 Idx += 1; 7155 } 7156 } 7157 7158 if (M.size() == NumElts*2) 7159 WhichResult = 0; 7160 7161 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7162 if (VT.is64BitVector() && EltSz == 32) 7163 return false; 7164 7165 return true; 7166 } 7167 7168 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 7169 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7170 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 7171 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7172 unsigned EltSz = VT.getScalarSizeInBits(); 7173 if (EltSz == 64) 7174 return false; 7175 7176 unsigned NumElts = VT.getVectorNumElements(); 7177 if (M.size() != NumElts && M.size() != NumElts*2) 7178 return false; 7179 7180 for (unsigned i = 0; i < M.size(); i += NumElts) { 7181 WhichResult = SelectPairHalf(NumElts, M, i); 7182 unsigned Idx = WhichResult * NumElts / 2; 7183 for (unsigned j = 0; j < NumElts; j += 2) { 7184 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7185 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 7186 return false; 7187 Idx += 1; 7188 } 7189 } 7190 7191 if (M.size() == NumElts*2) 7192 WhichResult = 0; 7193 7194 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7195 if (VT.is64BitVector() && EltSz == 32) 7196 return false; 7197 7198 return true; 7199 } 7200 7201 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 7202 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 7203 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 7204 unsigned &WhichResult, 7205 bool &isV_UNDEF) { 7206 isV_UNDEF = false; 7207 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 7208 return ARMISD::VTRN; 7209 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 7210 return ARMISD::VUZP; 7211 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 7212 return ARMISD::VZIP; 7213 7214 isV_UNDEF = true; 7215 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7216 return ARMISD::VTRN; 7217 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7218 return ARMISD::VUZP; 7219 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7220 return ARMISD::VZIP; 7221 7222 return 0; 7223 } 7224 7225 /// \return true if this is a reverse operation on an vector. 7226 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 7227 unsigned NumElts = VT.getVectorNumElements(); 7228 // Make sure the mask has the right size. 7229 if (NumElts != M.size()) 7230 return false; 7231 7232 // Look for <15, ..., 3, -1, 1, 0>. 7233 for (unsigned i = 0; i != NumElts; ++i) 7234 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 7235 return false; 7236 7237 return true; 7238 } 7239 7240 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) { 7241 unsigned NumElts = VT.getVectorNumElements(); 7242 // Make sure the mask has the right size. 7243 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8)) 7244 return false; 7245 7246 // If Top 7247 // Look for <0, N, 2, N+2, 4, N+4, ..>. 7248 // This inserts Input2 into Input1 7249 // else if not Top 7250 // Look for <0, N+1, 2, N+3, 4, N+5, ..> 7251 // This inserts Input1 into Input2 7252 unsigned Offset = Top ? 0 : 1; 7253 for (unsigned i = 0; i < NumElts; i+=2) { 7254 if (M[i] >= 0 && M[i] != (int)i) 7255 return false; 7256 if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset)) 7257 return false; 7258 } 7259 7260 return true; 7261 } 7262 7263 // Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted 7264 // from a pair of inputs. For example: 7265 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0), 7266 // FP_ROUND(EXTRACT_ELT(Y, 0), 7267 // FP_ROUND(EXTRACT_ELT(X, 1), 7268 // FP_ROUND(EXTRACT_ELT(Y, 1), ...) 7269 static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG, 7270 const ARMSubtarget *ST) { 7271 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7272 if (!ST->hasMVEFloatOps()) 7273 return SDValue(); 7274 7275 SDLoc dl(BV); 7276 EVT VT = BV.getValueType(); 7277 if (VT != MVT::v8f16) 7278 return SDValue(); 7279 7280 // We are looking for a buildvector of fptrunc elements, where all the 7281 // elements are interleavingly extracted from two sources. Check the first two 7282 // items are valid enough and extract some info from them (they are checked 7283 // properly in the loop below). 7284 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND || 7285 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7286 BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0) 7287 return SDValue(); 7288 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND || 7289 BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7290 BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0) 7291 return SDValue(); 7292 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0); 7293 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0); 7294 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32) 7295 return SDValue(); 7296 7297 // Check all the values in the BuildVector line up with our expectations. 7298 for (unsigned i = 1; i < 4; i++) { 7299 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) { 7300 return Trunc.getOpcode() == ISD::FP_ROUND && 7301 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7302 Trunc.getOperand(0).getOperand(0) == Op && 7303 Trunc.getOperand(0).getConstantOperandVal(1) == Idx; 7304 }; 7305 if (!Check(BV.getOperand(i * 2 + 0), Op0, i)) 7306 return SDValue(); 7307 if (!Check(BV.getOperand(i * 2 + 1), Op1, i)) 7308 return SDValue(); 7309 } 7310 7311 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0, 7312 DAG.getConstant(0, dl, MVT::i32)); 7313 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1, 7314 DAG.getConstant(1, dl, MVT::i32)); 7315 } 7316 7317 // Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted 7318 // from a single input on alternating lanes. For example: 7319 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0), 7320 // FP_ROUND(EXTRACT_ELT(X, 2), 7321 // FP_ROUND(EXTRACT_ELT(X, 4), ...) 7322 static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG, 7323 const ARMSubtarget *ST) { 7324 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7325 if (!ST->hasMVEFloatOps()) 7326 return SDValue(); 7327 7328 SDLoc dl(BV); 7329 EVT VT = BV.getValueType(); 7330 if (VT != MVT::v4f32) 7331 return SDValue(); 7332 7333 // We are looking for a buildvector of fptext elements, where all the 7334 // elements are alternating lanes from a single source. For example <0,2,4,6> 7335 // or <1,3,5,7>. Check the first two items are valid enough and extract some 7336 // info from them (they are checked properly in the loop below). 7337 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND || 7338 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT) 7339 return SDValue(); 7340 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0); 7341 int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1); 7342 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1)) 7343 return SDValue(); 7344 7345 // Check all the values in the BuildVector line up with our expectations. 7346 for (unsigned i = 1; i < 4; i++) { 7347 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) { 7348 return Trunc.getOpcode() == ISD::FP_EXTEND && 7349 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7350 Trunc.getOperand(0).getOperand(0) == Op && 7351 Trunc.getOperand(0).getConstantOperandVal(1) == Idx; 7352 }; 7353 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset)) 7354 return SDValue(); 7355 } 7356 7357 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0, 7358 DAG.getConstant(Offset, dl, MVT::i32)); 7359 } 7360 7361 // If N is an integer constant that can be moved into a register in one 7362 // instruction, return an SDValue of such a constant (will become a MOV 7363 // instruction). Otherwise return null. 7364 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 7365 const ARMSubtarget *ST, const SDLoc &dl) { 7366 uint64_t Val; 7367 if (!isa<ConstantSDNode>(N)) 7368 return SDValue(); 7369 Val = cast<ConstantSDNode>(N)->getZExtValue(); 7370 7371 if (ST->isThumb1Only()) { 7372 if (Val <= 255 || ~Val <= 255) 7373 return DAG.getConstant(Val, dl, MVT::i32); 7374 } else { 7375 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 7376 return DAG.getConstant(Val, dl, MVT::i32); 7377 } 7378 return SDValue(); 7379 } 7380 7381 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 7382 const ARMSubtarget *ST) { 7383 SDLoc dl(Op); 7384 EVT VT = Op.getValueType(); 7385 7386 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 7387 7388 unsigned NumElts = VT.getVectorNumElements(); 7389 unsigned BoolMask; 7390 unsigned BitsPerBool; 7391 if (NumElts == 4) { 7392 BitsPerBool = 4; 7393 BoolMask = 0xf; 7394 } else if (NumElts == 8) { 7395 BitsPerBool = 2; 7396 BoolMask = 0x3; 7397 } else if (NumElts == 16) { 7398 BitsPerBool = 1; 7399 BoolMask = 0x1; 7400 } else 7401 return SDValue(); 7402 7403 // If this is a single value copied into all lanes (a splat), we can just sign 7404 // extend that single value 7405 SDValue FirstOp = Op.getOperand(0); 7406 if (!isa<ConstantSDNode>(FirstOp) && 7407 std::all_of(std::next(Op->op_begin()), Op->op_end(), 7408 [&FirstOp](SDUse &U) { 7409 return U.get().isUndef() || U.get() == FirstOp; 7410 })) { 7411 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp, 7412 DAG.getValueType(MVT::i1)); 7413 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext); 7414 } 7415 7416 // First create base with bits set where known 7417 unsigned Bits32 = 0; 7418 for (unsigned i = 0; i < NumElts; ++i) { 7419 SDValue V = Op.getOperand(i); 7420 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 7421 continue; 7422 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 7423 if (BitSet) 7424 Bits32 |= BoolMask << (i * BitsPerBool); 7425 } 7426 7427 // Add in unknown nodes 7428 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 7429 DAG.getConstant(Bits32, dl, MVT::i32)); 7430 for (unsigned i = 0; i < NumElts; ++i) { 7431 SDValue V = Op.getOperand(i); 7432 if (isa<ConstantSDNode>(V) || V.isUndef()) 7433 continue; 7434 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 7435 DAG.getConstant(i, dl, MVT::i32)); 7436 } 7437 7438 return Base; 7439 } 7440 7441 // If this is a case we can't handle, return null and let the default 7442 // expansion code take care of it. 7443 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 7444 const ARMSubtarget *ST) const { 7445 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7446 SDLoc dl(Op); 7447 EVT VT = Op.getValueType(); 7448 7449 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7450 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 7451 7452 APInt SplatBits, SplatUndef; 7453 unsigned SplatBitSize; 7454 bool HasAnyUndefs; 7455 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7456 if (SplatUndef.isAllOnesValue()) 7457 return DAG.getUNDEF(VT); 7458 7459 if ((ST->hasNEON() && SplatBitSize <= 64) || 7460 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) { 7461 // Check if an immediate VMOV works. 7462 EVT VmovVT; 7463 SDValue Val = 7464 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 7465 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm); 7466 7467 if (Val.getNode()) { 7468 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 7469 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7470 } 7471 7472 // Try an immediate VMVN. 7473 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 7474 Val = isVMOVModifiedImm( 7475 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT, 7476 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 7477 if (Val.getNode()) { 7478 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 7479 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7480 } 7481 7482 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 7483 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 7484 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 7485 if (ImmVal != -1) { 7486 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 7487 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 7488 } 7489 } 7490 } 7491 } 7492 7493 // Scan through the operands to see if only one value is used. 7494 // 7495 // As an optimisation, even if more than one value is used it may be more 7496 // profitable to splat with one value then change some lanes. 7497 // 7498 // Heuristically we decide to do this if the vector has a "dominant" value, 7499 // defined as splatted to more than half of the lanes. 7500 unsigned NumElts = VT.getVectorNumElements(); 7501 bool isOnlyLowElement = true; 7502 bool usesOnlyOneValue = true; 7503 bool hasDominantValue = false; 7504 bool isConstant = true; 7505 7506 // Map of the number of times a particular SDValue appears in the 7507 // element list. 7508 DenseMap<SDValue, unsigned> ValueCounts; 7509 SDValue Value; 7510 for (unsigned i = 0; i < NumElts; ++i) { 7511 SDValue V = Op.getOperand(i); 7512 if (V.isUndef()) 7513 continue; 7514 if (i > 0) 7515 isOnlyLowElement = false; 7516 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 7517 isConstant = false; 7518 7519 ValueCounts.insert(std::make_pair(V, 0)); 7520 unsigned &Count = ValueCounts[V]; 7521 7522 // Is this value dominant? (takes up more than half of the lanes) 7523 if (++Count > (NumElts / 2)) { 7524 hasDominantValue = true; 7525 Value = V; 7526 } 7527 } 7528 if (ValueCounts.size() != 1) 7529 usesOnlyOneValue = false; 7530 if (!Value.getNode() && !ValueCounts.empty()) 7531 Value = ValueCounts.begin()->first; 7532 7533 if (ValueCounts.empty()) 7534 return DAG.getUNDEF(VT); 7535 7536 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 7537 // Keep going if we are hitting this case. 7538 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 7539 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7540 7541 unsigned EltSize = VT.getScalarSizeInBits(); 7542 7543 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 7544 // i32 and try again. 7545 if (hasDominantValue && EltSize <= 32) { 7546 if (!isConstant) { 7547 SDValue N; 7548 7549 // If we are VDUPing a value that comes directly from a vector, that will 7550 // cause an unnecessary move to and from a GPR, where instead we could 7551 // just use VDUPLANE. We can only do this if the lane being extracted 7552 // is at a constant index, as the VDUP from lane instructions only have 7553 // constant-index forms. 7554 ConstantSDNode *constIndex; 7555 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7556 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 7557 // We need to create a new undef vector to use for the VDUPLANE if the 7558 // size of the vector from which we get the value is different than the 7559 // size of the vector that we need to create. We will insert the element 7560 // such that the register coalescer will remove unnecessary copies. 7561 if (VT != Value->getOperand(0).getValueType()) { 7562 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 7563 VT.getVectorNumElements(); 7564 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7565 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 7566 Value, DAG.getConstant(index, dl, MVT::i32)), 7567 DAG.getConstant(index, dl, MVT::i32)); 7568 } else 7569 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7570 Value->getOperand(0), Value->getOperand(1)); 7571 } else 7572 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 7573 7574 if (!usesOnlyOneValue) { 7575 // The dominant value was splatted as 'N', but we now have to insert 7576 // all differing elements. 7577 for (unsigned I = 0; I < NumElts; ++I) { 7578 if (Op.getOperand(I) == Value) 7579 continue; 7580 SmallVector<SDValue, 3> Ops; 7581 Ops.push_back(N); 7582 Ops.push_back(Op.getOperand(I)); 7583 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 7584 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 7585 } 7586 } 7587 return N; 7588 } 7589 if (VT.getVectorElementType().isFloatingPoint()) { 7590 SmallVector<SDValue, 8> Ops; 7591 MVT FVT = VT.getVectorElementType().getSimpleVT(); 7592 assert(FVT == MVT::f32 || FVT == MVT::f16); 7593 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 7594 for (unsigned i = 0; i < NumElts; ++i) 7595 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 7596 Op.getOperand(i))); 7597 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 7598 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7599 Val = LowerBUILD_VECTOR(Val, DAG, ST); 7600 if (Val.getNode()) 7601 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7602 } 7603 if (usesOnlyOneValue) { 7604 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 7605 if (isConstant && Val.getNode()) 7606 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 7607 } 7608 } 7609 7610 // If all elements are constants and the case above didn't get hit, fall back 7611 // to the default expansion, which will generate a load from the constant 7612 // pool. 7613 if (isConstant) 7614 return SDValue(); 7615 7616 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and 7617 // vmovn). Empirical tests suggest this is rarely worth it for vectors of 7618 // length <= 2. 7619 if (NumElts >= 4) 7620 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 7621 return shuffle; 7622 7623 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into 7624 // VCVT's 7625 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget)) 7626 return VCVT; 7627 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget)) 7628 return VCVT; 7629 7630 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7631 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7632 // into two 64-bit vectors; we might discover a better way to lower it. 7633 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7634 EVT ExtVT = VT.getVectorElementType(); 7635 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7636 SDValue Lower = 7637 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7638 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7639 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7640 SDValue Upper = DAG.getBuildVector( 7641 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7642 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7643 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7644 if (Lower && Upper) 7645 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7646 } 7647 7648 // Vectors with 32- or 64-bit elements can be built by directly assigning 7649 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7650 // will be legalized. 7651 if (EltSize >= 32) { 7652 // Do the expansion with floating-point types, since that is what the VFP 7653 // registers are defined to use, and since i64 is not legal. 7654 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7655 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7656 SmallVector<SDValue, 8> Ops; 7657 for (unsigned i = 0; i < NumElts; ++i) 7658 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7659 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7660 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7661 } 7662 7663 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7664 // know the default expansion would otherwise fall back on something even 7665 // worse. For a vector with one or two non-undef values, that's 7666 // scalar_to_vector for the elements followed by a shuffle (provided the 7667 // shuffle is valid for the target) and materialization element by element 7668 // on the stack followed by a load for everything else. 7669 if (!isConstant && !usesOnlyOneValue) { 7670 SDValue Vec = DAG.getUNDEF(VT); 7671 for (unsigned i = 0 ; i < NumElts; ++i) { 7672 SDValue V = Op.getOperand(i); 7673 if (V.isUndef()) 7674 continue; 7675 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7676 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7677 } 7678 return Vec; 7679 } 7680 7681 return SDValue(); 7682 } 7683 7684 // Gather data to see if the operation can be modelled as a 7685 // shuffle in combination with VEXTs. 7686 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7687 SelectionDAG &DAG) const { 7688 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7689 SDLoc dl(Op); 7690 EVT VT = Op.getValueType(); 7691 unsigned NumElts = VT.getVectorNumElements(); 7692 7693 struct ShuffleSourceInfo { 7694 SDValue Vec; 7695 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7696 unsigned MaxElt = 0; 7697 7698 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7699 // be compatible with the shuffle we intend to construct. As a result 7700 // ShuffleVec will be some sliding window into the original Vec. 7701 SDValue ShuffleVec; 7702 7703 // Code should guarantee that element i in Vec starts at element "WindowBase 7704 // + i * WindowScale in ShuffleVec". 7705 int WindowBase = 0; 7706 int WindowScale = 1; 7707 7708 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7709 7710 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7711 }; 7712 7713 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7714 // node. 7715 SmallVector<ShuffleSourceInfo, 2> Sources; 7716 for (unsigned i = 0; i < NumElts; ++i) { 7717 SDValue V = Op.getOperand(i); 7718 if (V.isUndef()) 7719 continue; 7720 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7721 // A shuffle can only come from building a vector from various 7722 // elements of other vectors. 7723 return SDValue(); 7724 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7725 // Furthermore, shuffles require a constant mask, whereas extractelts 7726 // accept variable indices. 7727 return SDValue(); 7728 } 7729 7730 // Add this element source to the list if it's not already there. 7731 SDValue SourceVec = V.getOperand(0); 7732 auto Source = llvm::find(Sources, SourceVec); 7733 if (Source == Sources.end()) 7734 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7735 7736 // Update the minimum and maximum lane number seen. 7737 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7738 Source->MinElt = std::min(Source->MinElt, EltNo); 7739 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7740 } 7741 7742 // Currently only do something sane when at most two source vectors 7743 // are involved. 7744 if (Sources.size() > 2) 7745 return SDValue(); 7746 7747 // Find out the smallest element size among result and two sources, and use 7748 // it as element size to build the shuffle_vector. 7749 EVT SmallestEltTy = VT.getVectorElementType(); 7750 for (auto &Source : Sources) { 7751 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7752 if (SrcEltTy.bitsLT(SmallestEltTy)) 7753 SmallestEltTy = SrcEltTy; 7754 } 7755 unsigned ResMultiplier = 7756 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7757 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7758 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7759 7760 // If the source vector is too wide or too narrow, we may nevertheless be able 7761 // to construct a compatible shuffle either by concatenating it with UNDEF or 7762 // extracting a suitable range of elements. 7763 for (auto &Src : Sources) { 7764 EVT SrcVT = Src.ShuffleVec.getValueType(); 7765 7766 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 7767 continue; 7768 7769 // This stage of the search produces a source with the same element type as 7770 // the original, but with a total width matching the BUILD_VECTOR output. 7771 EVT EltVT = SrcVT.getVectorElementType(); 7772 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 7773 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7774 7775 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 7776 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 7777 return SDValue(); 7778 // We can pad out the smaller vector for free, so if it's part of a 7779 // shuffle... 7780 Src.ShuffleVec = 7781 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7782 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7783 continue; 7784 } 7785 7786 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 7787 return SDValue(); 7788 7789 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7790 // Span too large for a VEXT to cope 7791 return SDValue(); 7792 } 7793 7794 if (Src.MinElt >= NumSrcElts) { 7795 // The extraction can just take the second half 7796 Src.ShuffleVec = 7797 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7798 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7799 Src.WindowBase = -NumSrcElts; 7800 } else if (Src.MaxElt < NumSrcElts) { 7801 // The extraction can just take the first half 7802 Src.ShuffleVec = 7803 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7804 DAG.getConstant(0, dl, MVT::i32)); 7805 } else { 7806 // An actual VEXT is needed 7807 SDValue VEXTSrc1 = 7808 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7809 DAG.getConstant(0, dl, MVT::i32)); 7810 SDValue VEXTSrc2 = 7811 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7812 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7813 7814 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7815 VEXTSrc2, 7816 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7817 Src.WindowBase = -Src.MinElt; 7818 } 7819 } 7820 7821 // Another possible incompatibility occurs from the vector element types. We 7822 // can fix this by bitcasting the source vectors to the same type we intend 7823 // for the shuffle. 7824 for (auto &Src : Sources) { 7825 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7826 if (SrcEltTy == SmallestEltTy) 7827 continue; 7828 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7829 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec); 7830 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7831 Src.WindowBase *= Src.WindowScale; 7832 } 7833 7834 // Final sanity check before we try to actually produce a shuffle. 7835 LLVM_DEBUG(for (auto Src 7836 : Sources) 7837 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7838 7839 // The stars all align, our next step is to produce the mask for the shuffle. 7840 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7841 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7842 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7843 SDValue Entry = Op.getOperand(i); 7844 if (Entry.isUndef()) 7845 continue; 7846 7847 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7848 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7849 7850 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7851 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7852 // segment. 7853 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7854 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(), 7855 VT.getScalarSizeInBits()); 7856 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7857 7858 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7859 // starting at the appropriate offset. 7860 int *LaneMask = &Mask[i * ResMultiplier]; 7861 7862 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7863 ExtractBase += NumElts * (Src - Sources.begin()); 7864 for (int j = 0; j < LanesDefined; ++j) 7865 LaneMask[j] = ExtractBase + j; 7866 } 7867 7868 7869 // We can't handle more than two sources. This should have already 7870 // been checked before this point. 7871 assert(Sources.size() <= 2 && "Too many sources!"); 7872 7873 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7874 for (unsigned i = 0; i < Sources.size(); ++i) 7875 ShuffleOps[i] = Sources[i].ShuffleVec; 7876 7877 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7878 ShuffleOps[1], Mask, DAG); 7879 if (!Shuffle) 7880 return SDValue(); 7881 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle); 7882 } 7883 7884 enum ShuffleOpCodes { 7885 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7886 OP_VREV, 7887 OP_VDUP0, 7888 OP_VDUP1, 7889 OP_VDUP2, 7890 OP_VDUP3, 7891 OP_VEXT1, 7892 OP_VEXT2, 7893 OP_VEXT3, 7894 OP_VUZPL, // VUZP, left result 7895 OP_VUZPR, // VUZP, right result 7896 OP_VZIPL, // VZIP, left result 7897 OP_VZIPR, // VZIP, right result 7898 OP_VTRNL, // VTRN, left result 7899 OP_VTRNR // VTRN, right result 7900 }; 7901 7902 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7903 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7904 switch (OpNum) { 7905 case OP_COPY: 7906 case OP_VREV: 7907 case OP_VDUP0: 7908 case OP_VDUP1: 7909 case OP_VDUP2: 7910 case OP_VDUP3: 7911 return true; 7912 } 7913 return false; 7914 } 7915 7916 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7917 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7918 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7919 /// are assumed to be legal. 7920 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7921 if (VT.getVectorNumElements() == 4 && 7922 (VT.is128BitVector() || VT.is64BitVector())) { 7923 unsigned PFIndexes[4]; 7924 for (unsigned i = 0; i != 4; ++i) { 7925 if (M[i] < 0) 7926 PFIndexes[i] = 8; 7927 else 7928 PFIndexes[i] = M[i]; 7929 } 7930 7931 // Compute the index in the perfect shuffle table. 7932 unsigned PFTableIndex = 7933 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7934 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7935 unsigned Cost = (PFEntry >> 30); 7936 7937 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7938 return true; 7939 } 7940 7941 bool ReverseVEXT, isV_UNDEF; 7942 unsigned Imm, WhichResult; 7943 7944 unsigned EltSize = VT.getScalarSizeInBits(); 7945 if (EltSize >= 32 || 7946 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7947 ShuffleVectorInst::isIdentityMask(M) || 7948 isVREVMask(M, VT, 64) || 7949 isVREVMask(M, VT, 32) || 7950 isVREVMask(M, VT, 16)) 7951 return true; 7952 else if (Subtarget->hasNEON() && 7953 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7954 isVTBLMask(M, VT) || 7955 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7956 return true; 7957 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7958 isReverseMask(M, VT)) 7959 return true; 7960 else if (Subtarget->hasMVEIntegerOps() && 7961 (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1))) 7962 return true; 7963 else 7964 return false; 7965 } 7966 7967 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7968 /// the specified operations to build the shuffle. 7969 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7970 SDValue RHS, SelectionDAG &DAG, 7971 const SDLoc &dl) { 7972 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7973 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7974 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7975 7976 if (OpNum == OP_COPY) { 7977 if (LHSID == (1*9+2)*9+3) return LHS; 7978 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7979 return RHS; 7980 } 7981 7982 SDValue OpLHS, OpRHS; 7983 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7984 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7985 EVT VT = OpLHS.getValueType(); 7986 7987 switch (OpNum) { 7988 default: llvm_unreachable("Unknown shuffle opcode!"); 7989 case OP_VREV: 7990 // VREV divides the vector in half and swaps within the half. 7991 if (VT.getVectorElementType() == MVT::i32 || 7992 VT.getVectorElementType() == MVT::f32) 7993 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7994 // vrev <4 x i16> -> VREV32 7995 if (VT.getVectorElementType() == MVT::i16) 7996 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7997 // vrev <4 x i8> -> VREV16 7998 assert(VT.getVectorElementType() == MVT::i8); 7999 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 8000 case OP_VDUP0: 8001 case OP_VDUP1: 8002 case OP_VDUP2: 8003 case OP_VDUP3: 8004 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 8005 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 8006 case OP_VEXT1: 8007 case OP_VEXT2: 8008 case OP_VEXT3: 8009 return DAG.getNode(ARMISD::VEXT, dl, VT, 8010 OpLHS, OpRHS, 8011 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 8012 case OP_VUZPL: 8013 case OP_VUZPR: 8014 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 8015 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 8016 case OP_VZIPL: 8017 case OP_VZIPR: 8018 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 8019 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 8020 case OP_VTRNL: 8021 case OP_VTRNR: 8022 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 8023 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 8024 } 8025 } 8026 8027 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 8028 ArrayRef<int> ShuffleMask, 8029 SelectionDAG &DAG) { 8030 // Check to see if we can use the VTBL instruction. 8031 SDValue V1 = Op.getOperand(0); 8032 SDValue V2 = Op.getOperand(1); 8033 SDLoc DL(Op); 8034 8035 SmallVector<SDValue, 8> VTBLMask; 8036 for (ArrayRef<int>::iterator 8037 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 8038 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 8039 8040 if (V2.getNode()->isUndef()) 8041 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 8042 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 8043 8044 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 8045 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 8046 } 8047 8048 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 8049 SelectionDAG &DAG) { 8050 SDLoc DL(Op); 8051 SDValue OpLHS = Op.getOperand(0); 8052 EVT VT = OpLHS.getValueType(); 8053 8054 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 8055 "Expect an v8i16/v16i8 type"); 8056 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 8057 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 8058 // extract the first 8 bytes into the top double word and the last 8 bytes 8059 // into the bottom double word. The v8i16 case is similar. 8060 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 8061 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 8062 DAG.getConstant(ExtractNum, DL, MVT::i32)); 8063 } 8064 8065 static EVT getVectorTyFromPredicateVector(EVT VT) { 8066 switch (VT.getSimpleVT().SimpleTy) { 8067 case MVT::v4i1: 8068 return MVT::v4i32; 8069 case MVT::v8i1: 8070 return MVT::v8i16; 8071 case MVT::v16i1: 8072 return MVT::v16i8; 8073 default: 8074 llvm_unreachable("Unexpected vector predicate type"); 8075 } 8076 } 8077 8078 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 8079 SelectionDAG &DAG) { 8080 // Converting from boolean predicates to integers involves creating a vector 8081 // of all ones or all zeroes and selecting the lanes based upon the real 8082 // predicate. 8083 SDValue AllOnes = 8084 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 8085 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 8086 8087 SDValue AllZeroes = 8088 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 8089 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 8090 8091 // Get full vector type from predicate type 8092 EVT NewVT = getVectorTyFromPredicateVector(VT); 8093 8094 SDValue RecastV1; 8095 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 8096 // this to a v16i1. This cannot be done with an ordinary bitcast because the 8097 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 8098 // since we know in hardware the sizes are really the same. 8099 if (VT != MVT::v16i1) 8100 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 8101 else 8102 RecastV1 = Pred; 8103 8104 // Select either all ones or zeroes depending upon the real predicate bits. 8105 SDValue PredAsVector = 8106 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 8107 8108 // Recast our new predicate-as-integer v16i8 vector into something 8109 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 8110 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 8111 } 8112 8113 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 8114 const ARMSubtarget *ST) { 8115 EVT VT = Op.getValueType(); 8116 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8117 ArrayRef<int> ShuffleMask = SVN->getMask(); 8118 8119 assert(ST->hasMVEIntegerOps() && 8120 "No support for vector shuffle of boolean predicates"); 8121 8122 SDValue V1 = Op.getOperand(0); 8123 SDLoc dl(Op); 8124 if (isReverseMask(ShuffleMask, VT)) { 8125 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 8126 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 8127 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 8128 DAG.getConstant(16, dl, MVT::i32)); 8129 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 8130 } 8131 8132 // Until we can come up with optimised cases for every single vector 8133 // shuffle in existence we have chosen the least painful strategy. This is 8134 // to essentially promote the boolean predicate to a 8-bit integer, where 8135 // each predicate represents a byte. Then we fall back on a normal integer 8136 // vector shuffle and convert the result back into a predicate vector. In 8137 // many cases the generated code might be even better than scalar code 8138 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 8139 // fields in a register into 8 other arbitrary 2-bit fields! 8140 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 8141 EVT NewVT = PredAsVector.getValueType(); 8142 8143 // Do the shuffle! 8144 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 8145 DAG.getUNDEF(NewVT), ShuffleMask); 8146 8147 // Now return the result of comparing the shuffled vector with zero, 8148 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8149 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 8150 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8151 } 8152 8153 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op, 8154 ArrayRef<int> ShuffleMask, 8155 SelectionDAG &DAG) { 8156 // Attempt to lower the vector shuffle using as many whole register movs as 8157 // possible. This is useful for types smaller than 32bits, which would 8158 // often otherwise become a series for grp movs. 8159 SDLoc dl(Op); 8160 EVT VT = Op.getValueType(); 8161 if (VT.getScalarSizeInBits() >= 32) 8162 return SDValue(); 8163 8164 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && 8165 "Unexpected vector type"); 8166 int NumElts = VT.getVectorNumElements(); 8167 int QuarterSize = NumElts / 4; 8168 // The four final parts of the vector, as i32's 8169 SDValue Parts[4]; 8170 8171 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not 8172 // <u,u,u,u>), returning the vmov lane index 8173 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) { 8174 // Detect which mov lane this would be from the first non-undef element. 8175 int MovIdx = -1; 8176 for (int i = 0; i < Length; i++) { 8177 if (ShuffleMask[Start + i] >= 0) { 8178 if (ShuffleMask[Start + i] % Length != i) 8179 return -1; 8180 MovIdx = ShuffleMask[Start + i] / Length; 8181 break; 8182 } 8183 } 8184 // If all items are undef, leave this for other combines 8185 if (MovIdx == -1) 8186 return -1; 8187 // Check the remaining values are the correct part of the same mov 8188 for (int i = 1; i < Length; i++) { 8189 if (ShuffleMask[Start + i] >= 0 && 8190 (ShuffleMask[Start + i] / Length != MovIdx || 8191 ShuffleMask[Start + i] % Length != i)) 8192 return -1; 8193 } 8194 return MovIdx; 8195 }; 8196 8197 for (int Part = 0; Part < 4; ++Part) { 8198 // Does this part look like a mov 8199 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize); 8200 if (Elt != -1) { 8201 SDValue Input = Op->getOperand(0); 8202 if (Elt >= 4) { 8203 Input = Op->getOperand(1); 8204 Elt -= 4; 8205 } 8206 SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input); 8207 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast, 8208 DAG.getConstant(Elt, dl, MVT::i32)); 8209 } 8210 } 8211 8212 // Nothing interesting found, just return 8213 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3]) 8214 return SDValue(); 8215 8216 // The other parts need to be built with the old shuffle vector, cast to a 8217 // v4i32 and extract_vector_elts 8218 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) { 8219 SmallVector<int, 16> NewShuffleMask; 8220 for (int Part = 0; Part < 4; ++Part) 8221 for (int i = 0; i < QuarterSize; i++) 8222 NewShuffleMask.push_back( 8223 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]); 8224 SDValue NewShuffle = DAG.getVectorShuffle( 8225 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask); 8226 SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle); 8227 8228 for (int Part = 0; Part < 4; ++Part) 8229 if (!Parts[Part]) 8230 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 8231 BitCast, DAG.getConstant(Part, dl, MVT::i32)); 8232 } 8233 // Build a vector out of the various parts and bitcast it back to the original 8234 // type. 8235 SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts); 8236 return DAG.getBitcast(VT, NewVec); 8237 } 8238 8239 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 8240 const ARMSubtarget *ST) { 8241 SDValue V1 = Op.getOperand(0); 8242 SDValue V2 = Op.getOperand(1); 8243 SDLoc dl(Op); 8244 EVT VT = Op.getValueType(); 8245 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8246 unsigned EltSize = VT.getScalarSizeInBits(); 8247 8248 if (ST->hasMVEIntegerOps() && EltSize == 1) 8249 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 8250 8251 // Convert shuffles that are directly supported on NEON to target-specific 8252 // DAG nodes, instead of keeping them as shuffles and matching them again 8253 // during code selection. This is more efficient and avoids the possibility 8254 // of inconsistencies between legalization and selection. 8255 // FIXME: floating-point vectors should be canonicalized to integer vectors 8256 // of the same time so that they get CSEd properly. 8257 ArrayRef<int> ShuffleMask = SVN->getMask(); 8258 8259 if (EltSize <= 32) { 8260 if (SVN->isSplat()) { 8261 int Lane = SVN->getSplatIndex(); 8262 // If this is undef splat, generate it via "just" vdup, if possible. 8263 if (Lane == -1) Lane = 0; 8264 8265 // Test if V1 is a SCALAR_TO_VECTOR. 8266 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 8267 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8268 } 8269 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 8270 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 8271 // reaches it). 8272 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 8273 !isa<ConstantSDNode>(V1.getOperand(0))) { 8274 bool IsScalarToVector = true; 8275 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 8276 if (!V1.getOperand(i).isUndef()) { 8277 IsScalarToVector = false; 8278 break; 8279 } 8280 if (IsScalarToVector) 8281 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8282 } 8283 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 8284 DAG.getConstant(Lane, dl, MVT::i32)); 8285 } 8286 8287 bool ReverseVEXT = false; 8288 unsigned Imm = 0; 8289 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 8290 if (ReverseVEXT) 8291 std::swap(V1, V2); 8292 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 8293 DAG.getConstant(Imm, dl, MVT::i32)); 8294 } 8295 8296 if (isVREVMask(ShuffleMask, VT, 64)) 8297 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 8298 if (isVREVMask(ShuffleMask, VT, 32)) 8299 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 8300 if (isVREVMask(ShuffleMask, VT, 16)) 8301 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 8302 8303 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 8304 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 8305 DAG.getConstant(Imm, dl, MVT::i32)); 8306 } 8307 8308 // Check for Neon shuffles that modify both input vectors in place. 8309 // If both results are used, i.e., if there are two shuffles with the same 8310 // source operands and with masks corresponding to both results of one of 8311 // these operations, DAG memoization will ensure that a single node is 8312 // used for both shuffles. 8313 unsigned WhichResult = 0; 8314 bool isV_UNDEF = false; 8315 if (ST->hasNEON()) { 8316 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8317 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 8318 if (isV_UNDEF) 8319 V2 = V1; 8320 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 8321 .getValue(WhichResult); 8322 } 8323 } 8324 if (ST->hasMVEIntegerOps()) { 8325 if (isVMOVNMask(ShuffleMask, VT, 0)) 8326 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1, 8327 DAG.getConstant(0, dl, MVT::i32)); 8328 if (isVMOVNMask(ShuffleMask, VT, 1)) 8329 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2, 8330 DAG.getConstant(1, dl, MVT::i32)); 8331 } 8332 8333 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 8334 // shuffles that produce a result larger than their operands with: 8335 // shuffle(concat(v1, undef), concat(v2, undef)) 8336 // -> 8337 // shuffle(concat(v1, v2), undef) 8338 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 8339 // 8340 // This is useful in the general case, but there are special cases where 8341 // native shuffles produce larger results: the two-result ops. 8342 // 8343 // Look through the concat when lowering them: 8344 // shuffle(concat(v1, v2), undef) 8345 // -> 8346 // concat(VZIP(v1, v2):0, :1) 8347 // 8348 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 8349 SDValue SubV1 = V1->getOperand(0); 8350 SDValue SubV2 = V1->getOperand(1); 8351 EVT SubVT = SubV1.getValueType(); 8352 8353 // We expect these to have been canonicalized to -1. 8354 assert(llvm::all_of(ShuffleMask, [&](int i) { 8355 return i < (int)VT.getVectorNumElements(); 8356 }) && "Unexpected shuffle index into UNDEF operand!"); 8357 8358 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8359 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 8360 if (isV_UNDEF) 8361 SubV2 = SubV1; 8362 assert((WhichResult == 0) && 8363 "In-place shuffle of concat can only have one result!"); 8364 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 8365 SubV1, SubV2); 8366 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 8367 Res.getValue(1)); 8368 } 8369 } 8370 } 8371 8372 // If the shuffle is not directly supported and it has 4 elements, use 8373 // the PerfectShuffle-generated table to synthesize it from other shuffles. 8374 unsigned NumElts = VT.getVectorNumElements(); 8375 if (NumElts == 4) { 8376 unsigned PFIndexes[4]; 8377 for (unsigned i = 0; i != 4; ++i) { 8378 if (ShuffleMask[i] < 0) 8379 PFIndexes[i] = 8; 8380 else 8381 PFIndexes[i] = ShuffleMask[i]; 8382 } 8383 8384 // Compute the index in the perfect shuffle table. 8385 unsigned PFTableIndex = 8386 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8387 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8388 unsigned Cost = (PFEntry >> 30); 8389 8390 if (Cost <= 4) { 8391 if (ST->hasNEON()) 8392 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8393 else if (isLegalMVEShuffleOp(PFEntry)) { 8394 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8395 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8396 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 8397 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 8398 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 8399 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8400 } 8401 } 8402 } 8403 8404 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 8405 if (EltSize >= 32) { 8406 // Do the expansion with floating-point types, since that is what the VFP 8407 // registers are defined to use, and since i64 is not legal. 8408 EVT EltVT = EVT::getFloatingPointVT(EltSize); 8409 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 8410 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 8411 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 8412 SmallVector<SDValue, 8> Ops; 8413 for (unsigned i = 0; i < NumElts; ++i) { 8414 if (ShuffleMask[i] < 0) 8415 Ops.push_back(DAG.getUNDEF(EltVT)); 8416 else 8417 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 8418 ShuffleMask[i] < (int)NumElts ? V1 : V2, 8419 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 8420 dl, MVT::i32))); 8421 } 8422 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 8423 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8424 } 8425 8426 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 8427 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 8428 8429 if (ST->hasNEON() && VT == MVT::v8i8) 8430 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 8431 return NewOp; 8432 8433 if (ST->hasMVEIntegerOps()) 8434 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG)) 8435 return NewOp; 8436 8437 return SDValue(); 8438 } 8439 8440 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8441 const ARMSubtarget *ST) { 8442 EVT VecVT = Op.getOperand(0).getValueType(); 8443 SDLoc dl(Op); 8444 8445 assert(ST->hasMVEIntegerOps() && 8446 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8447 8448 SDValue Conv = 8449 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8450 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8451 unsigned LaneWidth = 8452 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8453 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 8454 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 8455 Op.getOperand(1), DAG.getValueType(MVT::i1)); 8456 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 8457 DAG.getConstant(~Mask, dl, MVT::i32)); 8458 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 8459 } 8460 8461 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8462 SelectionDAG &DAG) const { 8463 // INSERT_VECTOR_ELT is legal only for immediate indexes. 8464 SDValue Lane = Op.getOperand(2); 8465 if (!isa<ConstantSDNode>(Lane)) 8466 return SDValue(); 8467 8468 SDValue Elt = Op.getOperand(1); 8469 EVT EltVT = Elt.getValueType(); 8470 8471 if (Subtarget->hasMVEIntegerOps() && 8472 Op.getValueType().getScalarSizeInBits() == 1) 8473 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 8474 8475 if (getTypeAction(*DAG.getContext(), EltVT) == 8476 TargetLowering::TypePromoteFloat) { 8477 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 8478 // but the type system will try to do that if we don't intervene. 8479 // Reinterpret any such vector-element insertion as one with the 8480 // corresponding integer types. 8481 8482 SDLoc dl(Op); 8483 8484 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 8485 assert(getTypeAction(*DAG.getContext(), IEltVT) != 8486 TargetLowering::TypePromoteFloat); 8487 8488 SDValue VecIn = Op.getOperand(0); 8489 EVT VecVT = VecIn.getValueType(); 8490 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 8491 VecVT.getVectorNumElements()); 8492 8493 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 8494 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 8495 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 8496 IVecIn, IElt, Lane); 8497 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 8498 } 8499 8500 return Op; 8501 } 8502 8503 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8504 const ARMSubtarget *ST) { 8505 EVT VecVT = Op.getOperand(0).getValueType(); 8506 SDLoc dl(Op); 8507 8508 assert(ST->hasMVEIntegerOps() && 8509 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8510 8511 SDValue Conv = 8512 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8513 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8514 unsigned LaneWidth = 8515 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8516 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 8517 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 8518 return Shift; 8519 } 8520 8521 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 8522 const ARMSubtarget *ST) { 8523 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 8524 SDValue Lane = Op.getOperand(1); 8525 if (!isa<ConstantSDNode>(Lane)) 8526 return SDValue(); 8527 8528 SDValue Vec = Op.getOperand(0); 8529 EVT VT = Vec.getValueType(); 8530 8531 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8532 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 8533 8534 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 8535 SDLoc dl(Op); 8536 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 8537 } 8538 8539 return Op; 8540 } 8541 8542 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 8543 const ARMSubtarget *ST) { 8544 SDValue V1 = Op.getOperand(0); 8545 SDValue V2 = Op.getOperand(1); 8546 SDLoc dl(Op); 8547 EVT VT = Op.getValueType(); 8548 EVT Op1VT = V1.getValueType(); 8549 EVT Op2VT = V2.getValueType(); 8550 unsigned NumElts = VT.getVectorNumElements(); 8551 8552 assert(Op1VT == Op2VT && "Operand types don't match!"); 8553 assert(VT.getScalarSizeInBits() == 1 && 8554 "Unexpected custom CONCAT_VECTORS lowering"); 8555 assert(ST->hasMVEIntegerOps() && 8556 "CONCAT_VECTORS lowering only supported for MVE"); 8557 8558 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8559 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 8560 8561 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 8562 // promoted to v8i16, etc. 8563 8564 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8565 8566 // Extract the vector elements from Op1 and Op2 one by one and truncate them 8567 // to be the right size for the destination. For example, if Op1 is v4i1 then 8568 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 8569 // which when promoted is v8i16. That means each i32 element from Op1 needs 8570 // truncating to i16 and inserting in the result. 8571 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 8572 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 8573 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 8574 EVT NewVT = NewV.getValueType(); 8575 EVT ConcatVT = ConVec.getValueType(); 8576 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 8577 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 8578 DAG.getIntPtrConstant(i, dl)); 8579 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 8580 DAG.getConstant(j, dl, MVT::i32)); 8581 } 8582 return ConVec; 8583 }; 8584 unsigned j = 0; 8585 ConVec = ExractInto(NewV1, ConVec, j); 8586 ConVec = ExractInto(NewV2, ConVec, j); 8587 8588 // Now return the result of comparing the subvector with zero, 8589 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8590 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 8591 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8592 } 8593 8594 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 8595 const ARMSubtarget *ST) { 8596 EVT VT = Op->getValueType(0); 8597 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8598 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 8599 8600 // The only time a CONCAT_VECTORS operation can have legal types is when 8601 // two 64-bit vectors are concatenated to a 128-bit vector. 8602 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 8603 "unexpected CONCAT_VECTORS"); 8604 SDLoc dl(Op); 8605 SDValue Val = DAG.getUNDEF(MVT::v2f64); 8606 SDValue Op0 = Op.getOperand(0); 8607 SDValue Op1 = Op.getOperand(1); 8608 if (!Op0.isUndef()) 8609 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8610 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 8611 DAG.getIntPtrConstant(0, dl)); 8612 if (!Op1.isUndef()) 8613 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8614 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 8615 DAG.getIntPtrConstant(1, dl)); 8616 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 8617 } 8618 8619 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 8620 const ARMSubtarget *ST) { 8621 SDValue V1 = Op.getOperand(0); 8622 SDValue V2 = Op.getOperand(1); 8623 SDLoc dl(Op); 8624 EVT VT = Op.getValueType(); 8625 EVT Op1VT = V1.getValueType(); 8626 unsigned NumElts = VT.getVectorNumElements(); 8627 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 8628 8629 assert(VT.getScalarSizeInBits() == 1 && 8630 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 8631 assert(ST->hasMVEIntegerOps() && 8632 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 8633 8634 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8635 8636 // We now have Op1 promoted to a vector of integers, where v8i1 gets 8637 // promoted to v8i16, etc. 8638 8639 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8640 8641 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 8642 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 8643 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 8644 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 8645 DAG.getIntPtrConstant(i, dl)); 8646 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 8647 DAG.getConstant(j, dl, MVT::i32)); 8648 } 8649 8650 // Now return the result of comparing the subvector with zero, 8651 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8652 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 8653 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8654 } 8655 8656 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 8657 /// element has been zero/sign-extended, depending on the isSigned parameter, 8658 /// from an integer type half its size. 8659 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 8660 bool isSigned) { 8661 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 8662 EVT VT = N->getValueType(0); 8663 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 8664 SDNode *BVN = N->getOperand(0).getNode(); 8665 if (BVN->getValueType(0) != MVT::v4i32 || 8666 BVN->getOpcode() != ISD::BUILD_VECTOR) 8667 return false; 8668 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8669 unsigned HiElt = 1 - LoElt; 8670 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 8671 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 8672 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 8673 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 8674 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 8675 return false; 8676 if (isSigned) { 8677 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 8678 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 8679 return true; 8680 } else { 8681 if (Hi0->isNullValue() && Hi1->isNullValue()) 8682 return true; 8683 } 8684 return false; 8685 } 8686 8687 if (N->getOpcode() != ISD::BUILD_VECTOR) 8688 return false; 8689 8690 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 8691 SDNode *Elt = N->getOperand(i).getNode(); 8692 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 8693 unsigned EltSize = VT.getScalarSizeInBits(); 8694 unsigned HalfSize = EltSize / 2; 8695 if (isSigned) { 8696 if (!isIntN(HalfSize, C->getSExtValue())) 8697 return false; 8698 } else { 8699 if (!isUIntN(HalfSize, C->getZExtValue())) 8700 return false; 8701 } 8702 continue; 8703 } 8704 return false; 8705 } 8706 8707 return true; 8708 } 8709 8710 /// isSignExtended - Check if a node is a vector value that is sign-extended 8711 /// or a constant BUILD_VECTOR with sign-extended elements. 8712 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 8713 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 8714 return true; 8715 if (isExtendedBUILD_VECTOR(N, DAG, true)) 8716 return true; 8717 return false; 8718 } 8719 8720 /// isZeroExtended - Check if a node is a vector value that is zero-extended 8721 /// or a constant BUILD_VECTOR with zero-extended elements. 8722 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8723 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 8724 return true; 8725 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8726 return true; 8727 return false; 8728 } 8729 8730 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8731 if (OrigVT.getSizeInBits() >= 64) 8732 return OrigVT; 8733 8734 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8735 8736 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8737 switch (OrigSimpleTy) { 8738 default: llvm_unreachable("Unexpected Vector Type"); 8739 case MVT::v2i8: 8740 case MVT::v2i16: 8741 return MVT::v2i32; 8742 case MVT::v4i8: 8743 return MVT::v4i16; 8744 } 8745 } 8746 8747 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8748 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8749 /// We insert the required extension here to get the vector to fill a D register. 8750 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8751 const EVT &OrigTy, 8752 const EVT &ExtTy, 8753 unsigned ExtOpcode) { 8754 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8755 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8756 // 64-bits we need to insert a new extension so that it will be 64-bits. 8757 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8758 if (OrigTy.getSizeInBits() >= 64) 8759 return N; 8760 8761 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8762 EVT NewVT = getExtensionTo64Bits(OrigTy); 8763 8764 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8765 } 8766 8767 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8768 /// does not do any sign/zero extension. If the original vector is less 8769 /// than 64 bits, an appropriate extension will be added after the load to 8770 /// reach a total size of 64 bits. We have to add the extension separately 8771 /// because ARM does not have a sign/zero extending load for vectors. 8772 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8773 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8774 8775 // The load already has the right type. 8776 if (ExtendedTy == LD->getMemoryVT()) 8777 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8778 LD->getBasePtr(), LD->getPointerInfo(), 8779 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8780 8781 // We need to create a zextload/sextload. We cannot just create a load 8782 // followed by a zext/zext node because LowerMUL is also run during normal 8783 // operation legalization where we can't create illegal types. 8784 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8785 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8786 LD->getMemoryVT(), LD->getAlignment(), 8787 LD->getMemOperand()->getFlags()); 8788 } 8789 8790 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8791 /// extending load, or BUILD_VECTOR with extended elements, return the 8792 /// unextended value. The unextended vector should be 64 bits so that it can 8793 /// be used as an operand to a VMULL instruction. If the original vector size 8794 /// before extension is less than 64 bits we add a an extension to resize 8795 /// the vector to 64 bits. 8796 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8797 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 8798 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8799 N->getOperand(0)->getValueType(0), 8800 N->getValueType(0), 8801 N->getOpcode()); 8802 8803 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8804 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8805 "Expected extending load"); 8806 8807 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8808 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8809 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8810 SDValue extLoad = 8811 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8812 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8813 8814 return newLoad; 8815 } 8816 8817 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8818 // have been legalized as a BITCAST from v4i32. 8819 if (N->getOpcode() == ISD::BITCAST) { 8820 SDNode *BVN = N->getOperand(0).getNode(); 8821 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8822 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8823 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8824 return DAG.getBuildVector( 8825 MVT::v2i32, SDLoc(N), 8826 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8827 } 8828 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8829 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8830 EVT VT = N->getValueType(0); 8831 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8832 unsigned NumElts = VT.getVectorNumElements(); 8833 MVT TruncVT = MVT::getIntegerVT(EltSize); 8834 SmallVector<SDValue, 8> Ops; 8835 SDLoc dl(N); 8836 for (unsigned i = 0; i != NumElts; ++i) { 8837 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8838 const APInt &CInt = C->getAPIntValue(); 8839 // Element types smaller than 32 bits are not legal, so use i32 elements. 8840 // The values are implicitly truncated so sext vs. zext doesn't matter. 8841 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8842 } 8843 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8844 } 8845 8846 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8847 unsigned Opcode = N->getOpcode(); 8848 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8849 SDNode *N0 = N->getOperand(0).getNode(); 8850 SDNode *N1 = N->getOperand(1).getNode(); 8851 return N0->hasOneUse() && N1->hasOneUse() && 8852 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8853 } 8854 return false; 8855 } 8856 8857 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8858 unsigned Opcode = N->getOpcode(); 8859 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8860 SDNode *N0 = N->getOperand(0).getNode(); 8861 SDNode *N1 = N->getOperand(1).getNode(); 8862 return N0->hasOneUse() && N1->hasOneUse() && 8863 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8864 } 8865 return false; 8866 } 8867 8868 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8869 // Multiplications are only custom-lowered for 128-bit vectors so that 8870 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8871 EVT VT = Op.getValueType(); 8872 assert(VT.is128BitVector() && VT.isInteger() && 8873 "unexpected type for custom-lowering ISD::MUL"); 8874 SDNode *N0 = Op.getOperand(0).getNode(); 8875 SDNode *N1 = Op.getOperand(1).getNode(); 8876 unsigned NewOpc = 0; 8877 bool isMLA = false; 8878 bool isN0SExt = isSignExtended(N0, DAG); 8879 bool isN1SExt = isSignExtended(N1, DAG); 8880 if (isN0SExt && isN1SExt) 8881 NewOpc = ARMISD::VMULLs; 8882 else { 8883 bool isN0ZExt = isZeroExtended(N0, DAG); 8884 bool isN1ZExt = isZeroExtended(N1, DAG); 8885 if (isN0ZExt && isN1ZExt) 8886 NewOpc = ARMISD::VMULLu; 8887 else if (isN1SExt || isN1ZExt) { 8888 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8889 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8890 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8891 NewOpc = ARMISD::VMULLs; 8892 isMLA = true; 8893 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8894 NewOpc = ARMISD::VMULLu; 8895 isMLA = true; 8896 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8897 std::swap(N0, N1); 8898 NewOpc = ARMISD::VMULLu; 8899 isMLA = true; 8900 } 8901 } 8902 8903 if (!NewOpc) { 8904 if (VT == MVT::v2i64) 8905 // Fall through to expand this. It is not legal. 8906 return SDValue(); 8907 else 8908 // Other vector multiplications are legal. 8909 return Op; 8910 } 8911 } 8912 8913 // Legalize to a VMULL instruction. 8914 SDLoc DL(Op); 8915 SDValue Op0; 8916 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8917 if (!isMLA) { 8918 Op0 = SkipExtensionForVMULL(N0, DAG); 8919 assert(Op0.getValueType().is64BitVector() && 8920 Op1.getValueType().is64BitVector() && 8921 "unexpected types for extended operands to VMULL"); 8922 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8923 } 8924 8925 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8926 // isel lowering to take advantage of no-stall back to back vmul + vmla. 8927 // vmull q0, d4, d6 8928 // vmlal q0, d5, d6 8929 // is faster than 8930 // vaddl q0, d4, d5 8931 // vmovl q1, d6 8932 // vmul q0, q0, q1 8933 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 8934 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 8935 EVT Op1VT = Op1.getValueType(); 8936 return DAG.getNode(N0->getOpcode(), DL, VT, 8937 DAG.getNode(NewOpc, DL, VT, 8938 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 8939 DAG.getNode(NewOpc, DL, VT, 8940 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 8941 } 8942 8943 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 8944 SelectionDAG &DAG) { 8945 // TODO: Should this propagate fast-math-flags? 8946 8947 // Convert to float 8948 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 8949 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 8950 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 8951 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 8952 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 8953 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 8954 // Get reciprocal estimate. 8955 // float4 recip = vrecpeq_f32(yf); 8956 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8957 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8958 Y); 8959 // Because char has a smaller range than uchar, we can actually get away 8960 // without any newton steps. This requires that we use a weird bias 8961 // of 0xb000, however (again, this has been exhaustively tested). 8962 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 8963 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 8964 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 8965 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 8966 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 8967 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 8968 // Convert back to short. 8969 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 8970 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 8971 return X; 8972 } 8973 8974 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 8975 SelectionDAG &DAG) { 8976 // TODO: Should this propagate fast-math-flags? 8977 8978 SDValue N2; 8979 // Convert to float. 8980 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 8981 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 8982 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 8983 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 8984 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8985 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8986 8987 // Use reciprocal estimate and one refinement step. 8988 // float4 recip = vrecpeq_f32(yf); 8989 // recip *= vrecpsq_f32(yf, recip); 8990 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8991 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8992 N1); 8993 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8994 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8995 N1, N2); 8996 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8997 // Because short has a smaller range than ushort, we can actually get away 8998 // with only a single newton step. This requires that we use a weird bias 8999 // of 89, however (again, this has been exhaustively tested). 9000 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 9001 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 9002 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 9003 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 9004 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 9005 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 9006 // Convert back to integer and return. 9007 // return vmovn_s32(vcvt_s32_f32(result)); 9008 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 9009 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 9010 return N0; 9011 } 9012 9013 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 9014 const ARMSubtarget *ST) { 9015 EVT VT = Op.getValueType(); 9016 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 9017 "unexpected type for custom-lowering ISD::SDIV"); 9018 9019 SDLoc dl(Op); 9020 SDValue N0 = Op.getOperand(0); 9021 SDValue N1 = Op.getOperand(1); 9022 SDValue N2, N3; 9023 9024 if (VT == MVT::v8i8) { 9025 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 9026 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 9027 9028 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9029 DAG.getIntPtrConstant(4, dl)); 9030 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9031 DAG.getIntPtrConstant(4, dl)); 9032 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9033 DAG.getIntPtrConstant(0, dl)); 9034 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9035 DAG.getIntPtrConstant(0, dl)); 9036 9037 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 9038 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 9039 9040 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 9041 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 9042 9043 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 9044 return N0; 9045 } 9046 return LowerSDIV_v4i16(N0, N1, dl, DAG); 9047 } 9048 9049 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 9050 const ARMSubtarget *ST) { 9051 // TODO: Should this propagate fast-math-flags? 9052 EVT VT = Op.getValueType(); 9053 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 9054 "unexpected type for custom-lowering ISD::UDIV"); 9055 9056 SDLoc dl(Op); 9057 SDValue N0 = Op.getOperand(0); 9058 SDValue N1 = Op.getOperand(1); 9059 SDValue N2, N3; 9060 9061 if (VT == MVT::v8i8) { 9062 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 9063 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 9064 9065 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9066 DAG.getIntPtrConstant(4, dl)); 9067 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9068 DAG.getIntPtrConstant(4, dl)); 9069 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9070 DAG.getIntPtrConstant(0, dl)); 9071 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9072 DAG.getIntPtrConstant(0, dl)); 9073 9074 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 9075 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 9076 9077 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 9078 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 9079 9080 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 9081 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 9082 MVT::i32), 9083 N0); 9084 return N0; 9085 } 9086 9087 // v4i16 sdiv ... Convert to float. 9088 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 9089 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 9090 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 9091 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 9092 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 9093 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 9094 9095 // Use reciprocal estimate and two refinement steps. 9096 // float4 recip = vrecpeq_f32(yf); 9097 // recip *= vrecpsq_f32(yf, recip); 9098 // recip *= vrecpsq_f32(yf, recip); 9099 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9100 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 9101 BN1); 9102 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9103 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9104 BN1, N2); 9105 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9106 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9107 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9108 BN1, N2); 9109 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9110 // Simply multiplying by the reciprocal estimate can leave us a few ulps 9111 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 9112 // and that it will never cause us to return an answer too large). 9113 // float4 result = as_float4(as_int4(xf*recip) + 2); 9114 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 9115 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 9116 N1 = DAG.getConstant(2, dl, MVT::v4i32); 9117 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 9118 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 9119 // Convert back to integer and return. 9120 // return vmovn_u32(vcvt_s32_f32(result)); 9121 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 9122 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 9123 return N0; 9124 } 9125 9126 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 9127 SDNode *N = Op.getNode(); 9128 EVT VT = N->getValueType(0); 9129 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 9130 9131 SDValue Carry = Op.getOperand(2); 9132 9133 SDLoc DL(Op); 9134 9135 SDValue Result; 9136 if (Op.getOpcode() == ISD::ADDCARRY) { 9137 // This converts the boolean value carry into the carry flag. 9138 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 9139 9140 // Do the addition proper using the carry flag we wanted. 9141 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 9142 Op.getOperand(1), Carry); 9143 9144 // Now convert the carry flag into a boolean value. 9145 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 9146 } else { 9147 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 9148 // have to invert the carry first. 9149 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 9150 DAG.getConstant(1, DL, MVT::i32), Carry); 9151 // This converts the boolean value carry into the carry flag. 9152 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 9153 9154 // Do the subtraction proper using the carry flag we wanted. 9155 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 9156 Op.getOperand(1), Carry); 9157 9158 // Now convert the carry flag into a boolean value. 9159 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 9160 // But the carry returned by ARMISD::SUBE is not a borrow as expected 9161 // by ISD::SUBCARRY, so compute 1 - C. 9162 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 9163 DAG.getConstant(1, DL, MVT::i32), Carry); 9164 } 9165 9166 // Return both values. 9167 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 9168 } 9169 9170 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 9171 assert(Subtarget->isTargetDarwin()); 9172 9173 // For iOS, we want to call an alternative entry point: __sincos_stret, 9174 // return values are passed via sret. 9175 SDLoc dl(Op); 9176 SDValue Arg = Op.getOperand(0); 9177 EVT ArgVT = Arg.getValueType(); 9178 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 9179 auto PtrVT = getPointerTy(DAG.getDataLayout()); 9180 9181 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9182 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9183 9184 // Pair of floats / doubles used to pass the result. 9185 Type *RetTy = StructType::get(ArgTy, ArgTy); 9186 auto &DL = DAG.getDataLayout(); 9187 9188 ArgListTy Args; 9189 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 9190 SDValue SRet; 9191 if (ShouldUseSRet) { 9192 // Create stack object for sret. 9193 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 9194 const Align StackAlign = DL.getPrefTypeAlign(RetTy); 9195 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 9196 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 9197 9198 ArgListEntry Entry; 9199 Entry.Node = SRet; 9200 Entry.Ty = RetTy->getPointerTo(); 9201 Entry.IsSExt = false; 9202 Entry.IsZExt = false; 9203 Entry.IsSRet = true; 9204 Args.push_back(Entry); 9205 RetTy = Type::getVoidTy(*DAG.getContext()); 9206 } 9207 9208 ArgListEntry Entry; 9209 Entry.Node = Arg; 9210 Entry.Ty = ArgTy; 9211 Entry.IsSExt = false; 9212 Entry.IsZExt = false; 9213 Args.push_back(Entry); 9214 9215 RTLIB::Libcall LC = 9216 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 9217 const char *LibcallName = getLibcallName(LC); 9218 CallingConv::ID CC = getLibcallCallingConv(LC); 9219 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 9220 9221 TargetLowering::CallLoweringInfo CLI(DAG); 9222 CLI.setDebugLoc(dl) 9223 .setChain(DAG.getEntryNode()) 9224 .setCallee(CC, RetTy, Callee, std::move(Args)) 9225 .setDiscardResult(ShouldUseSRet); 9226 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 9227 9228 if (!ShouldUseSRet) 9229 return CallResult.first; 9230 9231 SDValue LoadSin = 9232 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 9233 9234 // Address of cos field. 9235 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 9236 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 9237 SDValue LoadCos = 9238 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 9239 9240 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 9241 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 9242 LoadSin.getValue(0), LoadCos.getValue(0)); 9243 } 9244 9245 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 9246 bool Signed, 9247 SDValue &Chain) const { 9248 EVT VT = Op.getValueType(); 9249 assert((VT == MVT::i32 || VT == MVT::i64) && 9250 "unexpected type for custom lowering DIV"); 9251 SDLoc dl(Op); 9252 9253 const auto &DL = DAG.getDataLayout(); 9254 const auto &TLI = DAG.getTargetLoweringInfo(); 9255 9256 const char *Name = nullptr; 9257 if (Signed) 9258 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 9259 else 9260 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 9261 9262 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 9263 9264 ARMTargetLowering::ArgListTy Args; 9265 9266 for (auto AI : {1, 0}) { 9267 ArgListEntry Arg; 9268 Arg.Node = Op.getOperand(AI); 9269 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 9270 Args.push_back(Arg); 9271 } 9272 9273 CallLoweringInfo CLI(DAG); 9274 CLI.setDebugLoc(dl) 9275 .setChain(Chain) 9276 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 9277 ES, std::move(Args)); 9278 9279 return LowerCallTo(CLI).first; 9280 } 9281 9282 // This is a code size optimisation: return the original SDIV node to 9283 // DAGCombiner when we don't want to expand SDIV into a sequence of 9284 // instructions, and an empty node otherwise which will cause the 9285 // SDIV to be expanded in DAGCombine. 9286 SDValue 9287 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 9288 SelectionDAG &DAG, 9289 SmallVectorImpl<SDNode *> &Created) const { 9290 // TODO: Support SREM 9291 if (N->getOpcode() != ISD::SDIV) 9292 return SDValue(); 9293 9294 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 9295 const bool MinSize = ST.hasMinSize(); 9296 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 9297 : ST.hasDivideInARMMode(); 9298 9299 // Don't touch vector types; rewriting this may lead to scalarizing 9300 // the int divs. 9301 if (N->getOperand(0).getValueType().isVector()) 9302 return SDValue(); 9303 9304 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 9305 // hwdiv support for this to be really profitable. 9306 if (!(MinSize && HasDivide)) 9307 return SDValue(); 9308 9309 // ARM mode is a bit simpler than Thumb: we can handle large power 9310 // of 2 immediates with 1 mov instruction; no further checks required, 9311 // just return the sdiv node. 9312 if (!ST.isThumb()) 9313 return SDValue(N, 0); 9314 9315 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 9316 // and thus lose the code size benefits of a MOVS that requires only 2. 9317 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 9318 // but as it's doing exactly this, it's not worth the trouble to get TTI. 9319 if (Divisor.sgt(128)) 9320 return SDValue(); 9321 9322 return SDValue(N, 0); 9323 } 9324 9325 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 9326 bool Signed) const { 9327 assert(Op.getValueType() == MVT::i32 && 9328 "unexpected type for custom lowering DIV"); 9329 SDLoc dl(Op); 9330 9331 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 9332 DAG.getEntryNode(), Op.getOperand(1)); 9333 9334 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9335 } 9336 9337 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 9338 SDLoc DL(N); 9339 SDValue Op = N->getOperand(1); 9340 if (N->getValueType(0) == MVT::i32) 9341 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 9342 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9343 DAG.getConstant(0, DL, MVT::i32)); 9344 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9345 DAG.getConstant(1, DL, MVT::i32)); 9346 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 9347 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 9348 } 9349 9350 void ARMTargetLowering::ExpandDIV_Windows( 9351 SDValue Op, SelectionDAG &DAG, bool Signed, 9352 SmallVectorImpl<SDValue> &Results) const { 9353 const auto &DL = DAG.getDataLayout(); 9354 const auto &TLI = DAG.getTargetLoweringInfo(); 9355 9356 assert(Op.getValueType() == MVT::i64 && 9357 "unexpected type for custom lowering DIV"); 9358 SDLoc dl(Op); 9359 9360 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 9361 9362 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9363 9364 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 9365 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 9366 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 9367 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 9368 9369 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper)); 9370 } 9371 9372 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) { 9373 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode()); 9374 EVT MemVT = LD->getMemoryVT(); 9375 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9376 "Expected a predicate type!"); 9377 assert(MemVT == Op.getValueType()); 9378 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && 9379 "Expected a non-extending load"); 9380 assert(LD->isUnindexed() && "Expected a unindexed load"); 9381 9382 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit 9383 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We 9384 // need to make sure that 8/4 bits are actually loaded into the correct 9385 // place, which means loading the value and then shuffling the values into 9386 // the bottom bits of the predicate. 9387 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect 9388 // for BE). 9389 9390 SDLoc dl(Op); 9391 SDValue Load = DAG.getExtLoad( 9392 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(), 9393 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9394 LD->getMemOperand()); 9395 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load); 9396 if (MemVT != MVT::v16i1) 9397 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred, 9398 DAG.getConstant(0, dl, MVT::i32)); 9399 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl); 9400 } 9401 9402 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results, 9403 SelectionDAG &DAG) const { 9404 LoadSDNode *LD = cast<LoadSDNode>(N); 9405 EVT MemVT = LD->getMemoryVT(); 9406 assert(LD->isUnindexed() && "Loads should be unindexed at this point."); 9407 9408 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9409 !Subtarget->isThumb1Only() && LD->isVolatile()) { 9410 SDLoc dl(N); 9411 SDValue Result = DAG.getMemIntrinsicNode( 9412 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}), 9413 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand()); 9414 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1); 9415 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0); 9416 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 9417 Results.append({Pair, Result.getValue(2)}); 9418 } 9419 } 9420 9421 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) { 9422 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9423 EVT MemVT = ST->getMemoryVT(); 9424 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9425 "Expected a predicate type!"); 9426 assert(MemVT == ST->getValue().getValueType()); 9427 assert(!ST->isTruncatingStore() && "Expected a non-extending store"); 9428 assert(ST->isUnindexed() && "Expected a unindexed store"); 9429 9430 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits 9431 // unset and a scalar store. 9432 SDLoc dl(Op); 9433 SDValue Build = ST->getValue(); 9434 if (MemVT != MVT::v16i1) { 9435 SmallVector<SDValue, 16> Ops; 9436 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) 9437 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build, 9438 DAG.getConstant(I, dl, MVT::i32))); 9439 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++) 9440 Ops.push_back(DAG.getUNDEF(MVT::i32)); 9441 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops); 9442 } 9443 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build); 9444 return DAG.getTruncStore( 9445 ST->getChain(), dl, GRP, ST->getBasePtr(), 9446 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9447 ST->getMemOperand()); 9448 } 9449 9450 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG, 9451 const ARMSubtarget *Subtarget) { 9452 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9453 EVT MemVT = ST->getMemoryVT(); 9454 assert(ST->isUnindexed() && "Stores should be unindexed at this point."); 9455 9456 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9457 !Subtarget->isThumb1Only() && ST->isVolatile()) { 9458 SDNode *N = Op.getNode(); 9459 SDLoc dl(N); 9460 9461 SDValue Lo = DAG.getNode( 9462 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9463 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl, 9464 MVT::i32)); 9465 SDValue Hi = DAG.getNode( 9466 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9467 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl, 9468 MVT::i32)); 9469 9470 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other), 9471 {ST->getChain(), Lo, Hi, ST->getBasePtr()}, 9472 MemVT, ST->getMemOperand()); 9473 } else if (Subtarget->hasMVEIntegerOps() && 9474 ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || 9475 MemVT == MVT::v16i1))) { 9476 return LowerPredicateStore(Op, DAG); 9477 } 9478 9479 return SDValue(); 9480 } 9481 9482 static bool isZeroVector(SDValue N) { 9483 return (ISD::isBuildVectorAllZeros(N.getNode()) || 9484 (N->getOpcode() == ARMISD::VMOVIMM && 9485 isNullConstant(N->getOperand(0)))); 9486 } 9487 9488 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) { 9489 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode()); 9490 MVT VT = Op.getSimpleValueType(); 9491 SDValue Mask = N->getMask(); 9492 SDValue PassThru = N->getPassThru(); 9493 SDLoc dl(Op); 9494 9495 if (isZeroVector(PassThru)) 9496 return Op; 9497 9498 // MVE Masked loads use zero as the passthru value. Here we convert undef to 9499 // zero too, and other values are lowered to a select. 9500 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 9501 DAG.getTargetConstant(0, dl, MVT::i32)); 9502 SDValue NewLoad = DAG.getMaskedLoad( 9503 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec, 9504 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(), 9505 N->getExtensionType(), N->isExpandingLoad()); 9506 SDValue Combo = NewLoad; 9507 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST || 9508 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) && 9509 isZeroVector(PassThru->getOperand(0)); 9510 if (!PassThru.isUndef() && !PassThruIsCastZero) 9511 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru); 9512 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl); 9513 } 9514 9515 static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG, 9516 const ARMSubtarget *ST) { 9517 if (!ST->hasMVEIntegerOps()) 9518 return SDValue(); 9519 9520 SDLoc dl(Op); 9521 unsigned BaseOpcode = 0; 9522 switch (Op->getOpcode()) { 9523 default: llvm_unreachable("Expected VECREDUCE opcode"); 9524 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break; 9525 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break; 9526 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break; 9527 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break; 9528 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break; 9529 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break; 9530 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break; 9531 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break; 9532 } 9533 9534 SDValue Op0 = Op->getOperand(0); 9535 EVT VT = Op0.getValueType(); 9536 EVT EltVT = VT.getVectorElementType(); 9537 unsigned NumElts = VT.getVectorNumElements(); 9538 unsigned NumActiveLanes = NumElts; 9539 9540 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || 9541 NumActiveLanes == 2) && 9542 "Only expected a power 2 vector size"); 9543 9544 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements 9545 // allows us to easily extract vector elements from the lanes. 9546 while (NumActiveLanes > 4) { 9547 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32; 9548 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0); 9549 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev); 9550 NumActiveLanes /= 2; 9551 } 9552 9553 SDValue Res; 9554 if (NumActiveLanes == 4) { 9555 // The remaining 4 elements are summed sequentially 9556 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9557 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32)); 9558 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9559 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32)); 9560 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9561 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32)); 9562 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9563 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32)); 9564 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags()); 9565 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags()); 9566 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags()); 9567 } else { 9568 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9569 DAG.getConstant(0, dl, MVT::i32)); 9570 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9571 DAG.getConstant(1, dl, MVT::i32)); 9572 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags()); 9573 } 9574 9575 // Result type may be wider than element type. 9576 if (EltVT != Op->getValueType(0)) 9577 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res); 9578 return Res; 9579 } 9580 9581 static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG, 9582 const ARMSubtarget *ST) { 9583 if (!ST->hasMVEFloatOps()) 9584 return SDValue(); 9585 return LowerVecReduce(Op, DAG, ST); 9586 } 9587 9588 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 9589 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 9590 // Acquire/Release load/store is not legal for targets without a dmb or 9591 // equivalent available. 9592 return SDValue(); 9593 9594 // Monotonic load/store is legal for all targets. 9595 return Op; 9596 } 9597 9598 static void ReplaceREADCYCLECOUNTER(SDNode *N, 9599 SmallVectorImpl<SDValue> &Results, 9600 SelectionDAG &DAG, 9601 const ARMSubtarget *Subtarget) { 9602 SDLoc DL(N); 9603 // Under Power Management extensions, the cycle-count is: 9604 // mrc p15, #0, <Rt>, c9, c13, #0 9605 SDValue Ops[] = { N->getOperand(0), // Chain 9606 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 9607 DAG.getTargetConstant(15, DL, MVT::i32), 9608 DAG.getTargetConstant(0, DL, MVT::i32), 9609 DAG.getTargetConstant(9, DL, MVT::i32), 9610 DAG.getTargetConstant(13, DL, MVT::i32), 9611 DAG.getTargetConstant(0, DL, MVT::i32) 9612 }; 9613 9614 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 9615 DAG.getVTList(MVT::i32, MVT::Other), Ops); 9616 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 9617 DAG.getConstant(0, DL, MVT::i32))); 9618 Results.push_back(Cycles32.getValue(1)); 9619 } 9620 9621 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 9622 SDLoc dl(V.getNode()); 9623 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 9624 SDValue VHi = DAG.getAnyExtOrTrunc( 9625 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 9626 dl, MVT::i32); 9627 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9628 if (isBigEndian) 9629 std::swap (VLo, VHi); 9630 SDValue RegClass = 9631 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 9632 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 9633 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 9634 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 9635 return SDValue( 9636 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 9637 } 9638 9639 static void ReplaceCMP_SWAP_64Results(SDNode *N, 9640 SmallVectorImpl<SDValue> & Results, 9641 SelectionDAG &DAG) { 9642 assert(N->getValueType(0) == MVT::i64 && 9643 "AtomicCmpSwap on types less than 64 should be legal"); 9644 SDValue Ops[] = {N->getOperand(1), 9645 createGPRPairNode(DAG, N->getOperand(2)), 9646 createGPRPairNode(DAG, N->getOperand(3)), 9647 N->getOperand(0)}; 9648 SDNode *CmpSwap = DAG.getMachineNode( 9649 ARM::CMP_SWAP_64, SDLoc(N), 9650 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 9651 9652 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 9653 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 9654 9655 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9656 9657 SDValue Lo = 9658 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 9659 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9660 SDValue Hi = 9661 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 9662 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9663 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi)); 9664 Results.push_back(SDValue(CmpSwap, 2)); 9665 } 9666 9667 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const { 9668 SDLoc dl(Op); 9669 EVT VT = Op.getValueType(); 9670 SDValue Chain = Op.getOperand(0); 9671 SDValue LHS = Op.getOperand(1); 9672 SDValue RHS = Op.getOperand(2); 9673 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get(); 9674 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 9675 9676 // If we don't have instructions of this float type then soften to a libcall 9677 // and use SETCC instead. 9678 if (isUnsupportedFloatingType(LHS.getValueType())) { 9679 DAG.getTargetLoweringInfo().softenSetCCOperands( 9680 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling); 9681 if (!RHS.getNode()) { 9682 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 9683 CC = ISD::SETNE; 9684 } 9685 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS, 9686 DAG.getCondCode(CC)); 9687 return DAG.getMergeValues({Result, Chain}, dl); 9688 } 9689 9690 ARMCC::CondCodes CondCode, CondCode2; 9691 FPCCToARMCC(CC, CondCode, CondCode2); 9692 9693 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit 9694 // in CMPFP and CMPFPE, but instead it should be made explicit by these 9695 // instructions using a chain instead of glue. This would also fix the problem 9696 // here (and also in LowerSELECT_CC) where we generate two comparisons when 9697 // CondCode2 != AL. 9698 SDValue True = DAG.getConstant(1, dl, VT); 9699 SDValue False = DAG.getConstant(0, dl, VT); 9700 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 9701 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 9702 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9703 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG); 9704 if (CondCode2 != ARMCC::AL) { 9705 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 9706 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9707 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG); 9708 } 9709 return DAG.getMergeValues({Result, Chain}, dl); 9710 } 9711 9712 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9713 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 9714 switch (Op.getOpcode()) { 9715 default: llvm_unreachable("Don't know how to custom lower this!"); 9716 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 9717 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9718 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9719 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9720 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9721 case ISD::SELECT: return LowerSELECT(Op, DAG); 9722 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9723 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9724 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 9725 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 9726 case ISD::VASTART: return LowerVASTART(Op, DAG); 9727 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 9728 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 9729 case ISD::SINT_TO_FP: 9730 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9731 case ISD::STRICT_FP_TO_SINT: 9732 case ISD::STRICT_FP_TO_UINT: 9733 case ISD::FP_TO_SINT: 9734 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 9735 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9736 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9737 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9738 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 9739 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 9740 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 9741 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget); 9742 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 9743 Subtarget); 9744 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 9745 case ISD::SHL: 9746 case ISD::SRL: 9747 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 9748 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 9749 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 9750 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 9751 case ISD::SRL_PARTS: 9752 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 9753 case ISD::CTTZ: 9754 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 9755 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 9756 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 9757 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 9758 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 9759 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 9760 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 9761 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 9762 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9763 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 9764 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 9765 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9766 case ISD::MUL: return LowerMUL(Op, DAG); 9767 case ISD::SDIV: 9768 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9769 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 9770 return LowerSDIV(Op, DAG, Subtarget); 9771 case ISD::UDIV: 9772 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9773 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 9774 return LowerUDIV(Op, DAG, Subtarget); 9775 case ISD::ADDCARRY: 9776 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 9777 case ISD::SADDO: 9778 case ISD::SSUBO: 9779 return LowerSignedALUO(Op, DAG); 9780 case ISD::UADDO: 9781 case ISD::USUBO: 9782 return LowerUnsignedALUO(Op, DAG); 9783 case ISD::SADDSAT: 9784 case ISD::SSUBSAT: 9785 return LowerSADDSUBSAT(Op, DAG, Subtarget); 9786 case ISD::LOAD: 9787 return LowerPredicateLoad(Op, DAG); 9788 case ISD::STORE: 9789 return LowerSTORE(Op, DAG, Subtarget); 9790 case ISD::MLOAD: 9791 return LowerMLOAD(Op, DAG); 9792 case ISD::VECREDUCE_MUL: 9793 case ISD::VECREDUCE_AND: 9794 case ISD::VECREDUCE_OR: 9795 case ISD::VECREDUCE_XOR: 9796 return LowerVecReduce(Op, DAG, Subtarget); 9797 case ISD::VECREDUCE_FADD: 9798 case ISD::VECREDUCE_FMUL: 9799 case ISD::VECREDUCE_FMIN: 9800 case ISD::VECREDUCE_FMAX: 9801 return LowerVecReduceF(Op, DAG, Subtarget); 9802 case ISD::ATOMIC_LOAD: 9803 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 9804 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 9805 case ISD::SDIVREM: 9806 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 9807 case ISD::DYNAMIC_STACKALLOC: 9808 if (Subtarget->isTargetWindows()) 9809 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9810 llvm_unreachable("Don't know how to custom lower this!"); 9811 case ISD::STRICT_FP_ROUND: 9812 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 9813 case ISD::STRICT_FP_EXTEND: 9814 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9815 case ISD::STRICT_FSETCC: 9816 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG); 9817 case ARMISD::WIN__DBZCHK: return SDValue(); 9818 } 9819 } 9820 9821 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 9822 SelectionDAG &DAG) { 9823 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9824 unsigned Opc = 0; 9825 if (IntNo == Intrinsic::arm_smlald) 9826 Opc = ARMISD::SMLALD; 9827 else if (IntNo == Intrinsic::arm_smlaldx) 9828 Opc = ARMISD::SMLALDX; 9829 else if (IntNo == Intrinsic::arm_smlsld) 9830 Opc = ARMISD::SMLSLD; 9831 else if (IntNo == Intrinsic::arm_smlsldx) 9832 Opc = ARMISD::SMLSLDX; 9833 else 9834 return; 9835 9836 SDLoc dl(N); 9837 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9838 N->getOperand(3), 9839 DAG.getConstant(0, dl, MVT::i32)); 9840 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9841 N->getOperand(3), 9842 DAG.getConstant(1, dl, MVT::i32)); 9843 9844 SDValue LongMul = DAG.getNode(Opc, dl, 9845 DAG.getVTList(MVT::i32, MVT::i32), 9846 N->getOperand(1), N->getOperand(2), 9847 Lo, Hi); 9848 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, 9849 LongMul.getValue(0), LongMul.getValue(1))); 9850 } 9851 9852 /// ReplaceNodeResults - Replace the results of node with an illegal result 9853 /// type with new values built out of custom code. 9854 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 9855 SmallVectorImpl<SDValue> &Results, 9856 SelectionDAG &DAG) const { 9857 SDValue Res; 9858 switch (N->getOpcode()) { 9859 default: 9860 llvm_unreachable("Don't know how to custom expand this!"); 9861 case ISD::READ_REGISTER: 9862 ExpandREAD_REGISTER(N, Results, DAG); 9863 break; 9864 case ISD::BITCAST: 9865 Res = ExpandBITCAST(N, DAG, Subtarget); 9866 break; 9867 case ISD::SRL: 9868 case ISD::SRA: 9869 case ISD::SHL: 9870 Res = Expand64BitShift(N, DAG, Subtarget); 9871 break; 9872 case ISD::SREM: 9873 case ISD::UREM: 9874 Res = LowerREM(N, DAG); 9875 break; 9876 case ISD::SDIVREM: 9877 case ISD::UDIVREM: 9878 Res = LowerDivRem(SDValue(N, 0), DAG); 9879 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 9880 Results.push_back(Res.getValue(0)); 9881 Results.push_back(Res.getValue(1)); 9882 return; 9883 case ISD::SADDSAT: 9884 case ISD::SSUBSAT: 9885 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget); 9886 break; 9887 case ISD::READCYCLECOUNTER: 9888 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 9889 return; 9890 case ISD::UDIV: 9891 case ISD::SDIV: 9892 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 9893 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 9894 Results); 9895 case ISD::ATOMIC_CMP_SWAP: 9896 ReplaceCMP_SWAP_64Results(N, Results, DAG); 9897 return; 9898 case ISD::INTRINSIC_WO_CHAIN: 9899 return ReplaceLongIntrinsic(N, Results, DAG); 9900 case ISD::ABS: 9901 lowerABS(N, Results, DAG); 9902 return ; 9903 case ISD::LOAD: 9904 LowerLOAD(N, Results, DAG); 9905 break; 9906 } 9907 if (Res.getNode()) 9908 Results.push_back(Res); 9909 } 9910 9911 //===----------------------------------------------------------------------===// 9912 // ARM Scheduler Hooks 9913 //===----------------------------------------------------------------------===// 9914 9915 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 9916 /// registers the function context. 9917 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 9918 MachineBasicBlock *MBB, 9919 MachineBasicBlock *DispatchBB, 9920 int FI) const { 9921 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 9922 "ROPI/RWPI not currently supported with SjLj"); 9923 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9924 DebugLoc dl = MI.getDebugLoc(); 9925 MachineFunction *MF = MBB->getParent(); 9926 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9927 MachineConstantPool *MCP = MF->getConstantPool(); 9928 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 9929 const Function &F = MF->getFunction(); 9930 9931 bool isThumb = Subtarget->isThumb(); 9932 bool isThumb2 = Subtarget->isThumb2(); 9933 9934 unsigned PCLabelId = AFI->createPICLabelUId(); 9935 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 9936 ARMConstantPoolValue *CPV = 9937 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 9938 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4)); 9939 9940 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 9941 : &ARM::GPRRegClass; 9942 9943 // Grab constant pool and fixed stack memory operands. 9944 MachineMemOperand *CPMMO = 9945 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9946 MachineMemOperand::MOLoad, 4, Align(4)); 9947 9948 MachineMemOperand *FIMMOSt = 9949 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 9950 MachineMemOperand::MOStore, 4, Align(4)); 9951 9952 // Load the address of the dispatch MBB into the jump buffer. 9953 if (isThumb2) { 9954 // Incoming value: jbuf 9955 // ldr.n r5, LCPI1_1 9956 // orr r5, r5, #1 9957 // add r5, pc 9958 // str r5, [$jbuf, #+4] ; &jbuf[1] 9959 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9960 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 9961 .addConstantPoolIndex(CPI) 9962 .addMemOperand(CPMMO) 9963 .add(predOps(ARMCC::AL)); 9964 // Set the low bit because of thumb mode. 9965 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9966 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 9967 .addReg(NewVReg1, RegState::Kill) 9968 .addImm(0x01) 9969 .add(predOps(ARMCC::AL)) 9970 .add(condCodeOp()); 9971 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9972 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 9973 .addReg(NewVReg2, RegState::Kill) 9974 .addImm(PCLabelId); 9975 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 9976 .addReg(NewVReg3, RegState::Kill) 9977 .addFrameIndex(FI) 9978 .addImm(36) // &jbuf[1] :: pc 9979 .addMemOperand(FIMMOSt) 9980 .add(predOps(ARMCC::AL)); 9981 } else if (isThumb) { 9982 // Incoming value: jbuf 9983 // ldr.n r1, LCPI1_4 9984 // add r1, pc 9985 // mov r2, #1 9986 // orrs r1, r2 9987 // add r2, $jbuf, #+4 ; &jbuf[1] 9988 // str r1, [r2] 9989 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9990 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 9991 .addConstantPoolIndex(CPI) 9992 .addMemOperand(CPMMO) 9993 .add(predOps(ARMCC::AL)); 9994 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9995 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 9996 .addReg(NewVReg1, RegState::Kill) 9997 .addImm(PCLabelId); 9998 // Set the low bit because of thumb mode. 9999 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10000 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 10001 .addReg(ARM::CPSR, RegState::Define) 10002 .addImm(1) 10003 .add(predOps(ARMCC::AL)); 10004 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10005 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 10006 .addReg(ARM::CPSR, RegState::Define) 10007 .addReg(NewVReg2, RegState::Kill) 10008 .addReg(NewVReg3, RegState::Kill) 10009 .add(predOps(ARMCC::AL)); 10010 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10011 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 10012 .addFrameIndex(FI) 10013 .addImm(36); // &jbuf[1] :: pc 10014 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 10015 .addReg(NewVReg4, RegState::Kill) 10016 .addReg(NewVReg5, RegState::Kill) 10017 .addImm(0) 10018 .addMemOperand(FIMMOSt) 10019 .add(predOps(ARMCC::AL)); 10020 } else { 10021 // Incoming value: jbuf 10022 // ldr r1, LCPI1_1 10023 // add r1, pc, r1 10024 // str r1, [$jbuf, #+4] ; &jbuf[1] 10025 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10026 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 10027 .addConstantPoolIndex(CPI) 10028 .addImm(0) 10029 .addMemOperand(CPMMO) 10030 .add(predOps(ARMCC::AL)); 10031 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10032 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 10033 .addReg(NewVReg1, RegState::Kill) 10034 .addImm(PCLabelId) 10035 .add(predOps(ARMCC::AL)); 10036 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 10037 .addReg(NewVReg2, RegState::Kill) 10038 .addFrameIndex(FI) 10039 .addImm(36) // &jbuf[1] :: pc 10040 .addMemOperand(FIMMOSt) 10041 .add(predOps(ARMCC::AL)); 10042 } 10043 } 10044 10045 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 10046 MachineBasicBlock *MBB) const { 10047 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10048 DebugLoc dl = MI.getDebugLoc(); 10049 MachineFunction *MF = MBB->getParent(); 10050 MachineRegisterInfo *MRI = &MF->getRegInfo(); 10051 MachineFrameInfo &MFI = MF->getFrameInfo(); 10052 int FI = MFI.getFunctionContextIndex(); 10053 10054 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 10055 : &ARM::GPRnopcRegClass; 10056 10057 // Get a mapping of the call site numbers to all of the landing pads they're 10058 // associated with. 10059 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 10060 unsigned MaxCSNum = 0; 10061 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 10062 ++BB) { 10063 if (!BB->isEHPad()) continue; 10064 10065 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 10066 // pad. 10067 for (MachineBasicBlock::iterator 10068 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 10069 if (!II->isEHLabel()) continue; 10070 10071 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 10072 if (!MF->hasCallSiteLandingPad(Sym)) continue; 10073 10074 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 10075 for (SmallVectorImpl<unsigned>::iterator 10076 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 10077 CSI != CSE; ++CSI) { 10078 CallSiteNumToLPad[*CSI].push_back(&*BB); 10079 MaxCSNum = std::max(MaxCSNum, *CSI); 10080 } 10081 break; 10082 } 10083 } 10084 10085 // Get an ordered list of the machine basic blocks for the jump table. 10086 std::vector<MachineBasicBlock*> LPadList; 10087 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 10088 LPadList.reserve(CallSiteNumToLPad.size()); 10089 for (unsigned I = 1; I <= MaxCSNum; ++I) { 10090 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 10091 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10092 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 10093 LPadList.push_back(*II); 10094 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 10095 } 10096 } 10097 10098 assert(!LPadList.empty() && 10099 "No landing pad destinations for the dispatch jump table!"); 10100 10101 // Create the jump table and associated information. 10102 MachineJumpTableInfo *JTI = 10103 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 10104 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 10105 10106 // Create the MBBs for the dispatch code. 10107 10108 // Shove the dispatch's address into the return slot in the function context. 10109 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 10110 DispatchBB->setIsEHPad(); 10111 10112 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10113 unsigned trap_opcode; 10114 if (Subtarget->isThumb()) 10115 trap_opcode = ARM::tTRAP; 10116 else 10117 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 10118 10119 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 10120 DispatchBB->addSuccessor(TrapBB); 10121 10122 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 10123 DispatchBB->addSuccessor(DispContBB); 10124 10125 // Insert and MBBs. 10126 MF->insert(MF->end(), DispatchBB); 10127 MF->insert(MF->end(), DispContBB); 10128 MF->insert(MF->end(), TrapBB); 10129 10130 // Insert code into the entry block that creates and registers the function 10131 // context. 10132 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 10133 10134 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 10135 MachinePointerInfo::getFixedStack(*MF, FI), 10136 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4)); 10137 10138 MachineInstrBuilder MIB; 10139 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 10140 10141 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 10142 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 10143 10144 // Add a register mask with no preserved registers. This results in all 10145 // registers being marked as clobbered. This can't work if the dispatch block 10146 // is in a Thumb1 function and is linked with ARM code which uses the FP 10147 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 10148 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 10149 10150 bool IsPositionIndependent = isPositionIndependent(); 10151 unsigned NumLPads = LPadList.size(); 10152 if (Subtarget->isThumb2()) { 10153 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10154 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 10155 .addFrameIndex(FI) 10156 .addImm(4) 10157 .addMemOperand(FIMMOLd) 10158 .add(predOps(ARMCC::AL)); 10159 10160 if (NumLPads < 256) { 10161 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 10162 .addReg(NewVReg1) 10163 .addImm(LPadList.size()) 10164 .add(predOps(ARMCC::AL)); 10165 } else { 10166 Register VReg1 = MRI->createVirtualRegister(TRC); 10167 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 10168 .addImm(NumLPads & 0xFFFF) 10169 .add(predOps(ARMCC::AL)); 10170 10171 unsigned VReg2 = VReg1; 10172 if ((NumLPads & 0xFFFF0000) != 0) { 10173 VReg2 = MRI->createVirtualRegister(TRC); 10174 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 10175 .addReg(VReg1) 10176 .addImm(NumLPads >> 16) 10177 .add(predOps(ARMCC::AL)); 10178 } 10179 10180 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 10181 .addReg(NewVReg1) 10182 .addReg(VReg2) 10183 .add(predOps(ARMCC::AL)); 10184 } 10185 10186 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 10187 .addMBB(TrapBB) 10188 .addImm(ARMCC::HI) 10189 .addReg(ARM::CPSR); 10190 10191 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10192 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 10193 .addJumpTableIndex(MJTI) 10194 .add(predOps(ARMCC::AL)); 10195 10196 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10197 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 10198 .addReg(NewVReg3, RegState::Kill) 10199 .addReg(NewVReg1) 10200 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10201 .add(predOps(ARMCC::AL)) 10202 .add(condCodeOp()); 10203 10204 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 10205 .addReg(NewVReg4, RegState::Kill) 10206 .addReg(NewVReg1) 10207 .addJumpTableIndex(MJTI); 10208 } else if (Subtarget->isThumb()) { 10209 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10210 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 10211 .addFrameIndex(FI) 10212 .addImm(1) 10213 .addMemOperand(FIMMOLd) 10214 .add(predOps(ARMCC::AL)); 10215 10216 if (NumLPads < 256) { 10217 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 10218 .addReg(NewVReg1) 10219 .addImm(NumLPads) 10220 .add(predOps(ARMCC::AL)); 10221 } else { 10222 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10223 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10224 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 10225 10226 // MachineConstantPool wants an explicit alignment. 10227 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10228 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10229 10230 Register VReg1 = MRI->createVirtualRegister(TRC); 10231 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 10232 .addReg(VReg1, RegState::Define) 10233 .addConstantPoolIndex(Idx) 10234 .add(predOps(ARMCC::AL)); 10235 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 10236 .addReg(NewVReg1) 10237 .addReg(VReg1) 10238 .add(predOps(ARMCC::AL)); 10239 } 10240 10241 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 10242 .addMBB(TrapBB) 10243 .addImm(ARMCC::HI) 10244 .addReg(ARM::CPSR); 10245 10246 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10247 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 10248 .addReg(ARM::CPSR, RegState::Define) 10249 .addReg(NewVReg1) 10250 .addImm(2) 10251 .add(predOps(ARMCC::AL)); 10252 10253 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10254 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 10255 .addJumpTableIndex(MJTI) 10256 .add(predOps(ARMCC::AL)); 10257 10258 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10259 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 10260 .addReg(ARM::CPSR, RegState::Define) 10261 .addReg(NewVReg2, RegState::Kill) 10262 .addReg(NewVReg3) 10263 .add(predOps(ARMCC::AL)); 10264 10265 MachineMemOperand *JTMMOLd = 10266 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10267 MachineMemOperand::MOLoad, 4, Align(4)); 10268 10269 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10270 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 10271 .addReg(NewVReg4, RegState::Kill) 10272 .addImm(0) 10273 .addMemOperand(JTMMOLd) 10274 .add(predOps(ARMCC::AL)); 10275 10276 unsigned NewVReg6 = NewVReg5; 10277 if (IsPositionIndependent) { 10278 NewVReg6 = MRI->createVirtualRegister(TRC); 10279 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 10280 .addReg(ARM::CPSR, RegState::Define) 10281 .addReg(NewVReg5, RegState::Kill) 10282 .addReg(NewVReg3) 10283 .add(predOps(ARMCC::AL)); 10284 } 10285 10286 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 10287 .addReg(NewVReg6, RegState::Kill) 10288 .addJumpTableIndex(MJTI); 10289 } else { 10290 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10291 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 10292 .addFrameIndex(FI) 10293 .addImm(4) 10294 .addMemOperand(FIMMOLd) 10295 .add(predOps(ARMCC::AL)); 10296 10297 if (NumLPads < 256) { 10298 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 10299 .addReg(NewVReg1) 10300 .addImm(NumLPads) 10301 .add(predOps(ARMCC::AL)); 10302 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 10303 Register VReg1 = MRI->createVirtualRegister(TRC); 10304 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 10305 .addImm(NumLPads & 0xFFFF) 10306 .add(predOps(ARMCC::AL)); 10307 10308 unsigned VReg2 = VReg1; 10309 if ((NumLPads & 0xFFFF0000) != 0) { 10310 VReg2 = MRI->createVirtualRegister(TRC); 10311 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 10312 .addReg(VReg1) 10313 .addImm(NumLPads >> 16) 10314 .add(predOps(ARMCC::AL)); 10315 } 10316 10317 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 10318 .addReg(NewVReg1) 10319 .addReg(VReg2) 10320 .add(predOps(ARMCC::AL)); 10321 } else { 10322 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10323 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10324 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 10325 10326 // MachineConstantPool wants an explicit alignment. 10327 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10328 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10329 10330 Register VReg1 = MRI->createVirtualRegister(TRC); 10331 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 10332 .addReg(VReg1, RegState::Define) 10333 .addConstantPoolIndex(Idx) 10334 .addImm(0) 10335 .add(predOps(ARMCC::AL)); 10336 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 10337 .addReg(NewVReg1) 10338 .addReg(VReg1, RegState::Kill) 10339 .add(predOps(ARMCC::AL)); 10340 } 10341 10342 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 10343 .addMBB(TrapBB) 10344 .addImm(ARMCC::HI) 10345 .addReg(ARM::CPSR); 10346 10347 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10348 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 10349 .addReg(NewVReg1) 10350 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10351 .add(predOps(ARMCC::AL)) 10352 .add(condCodeOp()); 10353 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10354 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 10355 .addJumpTableIndex(MJTI) 10356 .add(predOps(ARMCC::AL)); 10357 10358 MachineMemOperand *JTMMOLd = 10359 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10360 MachineMemOperand::MOLoad, 4, Align(4)); 10361 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10362 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 10363 .addReg(NewVReg3, RegState::Kill) 10364 .addReg(NewVReg4) 10365 .addImm(0) 10366 .addMemOperand(JTMMOLd) 10367 .add(predOps(ARMCC::AL)); 10368 10369 if (IsPositionIndependent) { 10370 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 10371 .addReg(NewVReg5, RegState::Kill) 10372 .addReg(NewVReg4) 10373 .addJumpTableIndex(MJTI); 10374 } else { 10375 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 10376 .addReg(NewVReg5, RegState::Kill) 10377 .addJumpTableIndex(MJTI); 10378 } 10379 } 10380 10381 // Add the jump table entries as successors to the MBB. 10382 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 10383 for (std::vector<MachineBasicBlock*>::iterator 10384 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 10385 MachineBasicBlock *CurMBB = *I; 10386 if (SeenMBBs.insert(CurMBB).second) 10387 DispContBB->addSuccessor(CurMBB); 10388 } 10389 10390 // N.B. the order the invoke BBs are processed in doesn't matter here. 10391 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 10392 SmallVector<MachineBasicBlock*, 64> MBBLPads; 10393 for (MachineBasicBlock *BB : InvokeBBs) { 10394 10395 // Remove the landing pad successor from the invoke block and replace it 10396 // with the new dispatch block. 10397 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 10398 BB->succ_end()); 10399 while (!Successors.empty()) { 10400 MachineBasicBlock *SMBB = Successors.pop_back_val(); 10401 if (SMBB->isEHPad()) { 10402 BB->removeSuccessor(SMBB); 10403 MBBLPads.push_back(SMBB); 10404 } 10405 } 10406 10407 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 10408 BB->normalizeSuccProbs(); 10409 10410 // Find the invoke call and mark all of the callee-saved registers as 10411 // 'implicit defined' so that they're spilled. This prevents code from 10412 // moving instructions to before the EH block, where they will never be 10413 // executed. 10414 for (MachineBasicBlock::reverse_iterator 10415 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 10416 if (!II->isCall()) continue; 10417 10418 DenseMap<unsigned, bool> DefRegs; 10419 for (MachineInstr::mop_iterator 10420 OI = II->operands_begin(), OE = II->operands_end(); 10421 OI != OE; ++OI) { 10422 if (!OI->isReg()) continue; 10423 DefRegs[OI->getReg()] = true; 10424 } 10425 10426 MachineInstrBuilder MIB(*MF, &*II); 10427 10428 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 10429 unsigned Reg = SavedRegs[i]; 10430 if (Subtarget->isThumb2() && 10431 !ARM::tGPRRegClass.contains(Reg) && 10432 !ARM::hGPRRegClass.contains(Reg)) 10433 continue; 10434 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 10435 continue; 10436 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 10437 continue; 10438 if (!DefRegs[Reg]) 10439 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 10440 } 10441 10442 break; 10443 } 10444 } 10445 10446 // Mark all former landing pads as non-landing pads. The dispatch is the only 10447 // landing pad now. 10448 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10449 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 10450 (*I)->setIsEHPad(false); 10451 10452 // The instruction is gone now. 10453 MI.eraseFromParent(); 10454 } 10455 10456 static 10457 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 10458 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 10459 E = MBB->succ_end(); I != E; ++I) 10460 if (*I != Succ) 10461 return *I; 10462 llvm_unreachable("Expecting a BB with two successors!"); 10463 } 10464 10465 /// Return the load opcode for a given load size. If load size >= 8, 10466 /// neon opcode will be returned. 10467 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 10468 if (LdSize >= 8) 10469 return LdSize == 16 ? ARM::VLD1q32wb_fixed 10470 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 10471 if (IsThumb1) 10472 return LdSize == 4 ? ARM::tLDRi 10473 : LdSize == 2 ? ARM::tLDRHi 10474 : LdSize == 1 ? ARM::tLDRBi : 0; 10475 if (IsThumb2) 10476 return LdSize == 4 ? ARM::t2LDR_POST 10477 : LdSize == 2 ? ARM::t2LDRH_POST 10478 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 10479 return LdSize == 4 ? ARM::LDR_POST_IMM 10480 : LdSize == 2 ? ARM::LDRH_POST 10481 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 10482 } 10483 10484 /// Return the store opcode for a given store size. If store size >= 8, 10485 /// neon opcode will be returned. 10486 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 10487 if (StSize >= 8) 10488 return StSize == 16 ? ARM::VST1q32wb_fixed 10489 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 10490 if (IsThumb1) 10491 return StSize == 4 ? ARM::tSTRi 10492 : StSize == 2 ? ARM::tSTRHi 10493 : StSize == 1 ? ARM::tSTRBi : 0; 10494 if (IsThumb2) 10495 return StSize == 4 ? ARM::t2STR_POST 10496 : StSize == 2 ? ARM::t2STRH_POST 10497 : StSize == 1 ? ARM::t2STRB_POST : 0; 10498 return StSize == 4 ? ARM::STR_POST_IMM 10499 : StSize == 2 ? ARM::STRH_POST 10500 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 10501 } 10502 10503 /// Emit a post-increment load operation with given size. The instructions 10504 /// will be added to BB at Pos. 10505 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10506 const TargetInstrInfo *TII, const DebugLoc &dl, 10507 unsigned LdSize, unsigned Data, unsigned AddrIn, 10508 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10509 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 10510 assert(LdOpc != 0 && "Should have a load opcode"); 10511 if (LdSize >= 8) { 10512 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10513 .addReg(AddrOut, RegState::Define) 10514 .addReg(AddrIn) 10515 .addImm(0) 10516 .add(predOps(ARMCC::AL)); 10517 } else if (IsThumb1) { 10518 // load + update AddrIn 10519 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10520 .addReg(AddrIn) 10521 .addImm(0) 10522 .add(predOps(ARMCC::AL)); 10523 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10524 .add(t1CondCodeOp()) 10525 .addReg(AddrIn) 10526 .addImm(LdSize) 10527 .add(predOps(ARMCC::AL)); 10528 } else if (IsThumb2) { 10529 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10530 .addReg(AddrOut, RegState::Define) 10531 .addReg(AddrIn) 10532 .addImm(LdSize) 10533 .add(predOps(ARMCC::AL)); 10534 } else { // arm 10535 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10536 .addReg(AddrOut, RegState::Define) 10537 .addReg(AddrIn) 10538 .addReg(0) 10539 .addImm(LdSize) 10540 .add(predOps(ARMCC::AL)); 10541 } 10542 } 10543 10544 /// Emit a post-increment store operation with given size. The instructions 10545 /// will be added to BB at Pos. 10546 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10547 const TargetInstrInfo *TII, const DebugLoc &dl, 10548 unsigned StSize, unsigned Data, unsigned AddrIn, 10549 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10550 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 10551 assert(StOpc != 0 && "Should have a store opcode"); 10552 if (StSize >= 8) { 10553 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10554 .addReg(AddrIn) 10555 .addImm(0) 10556 .addReg(Data) 10557 .add(predOps(ARMCC::AL)); 10558 } else if (IsThumb1) { 10559 // store + update AddrIn 10560 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 10561 .addReg(Data) 10562 .addReg(AddrIn) 10563 .addImm(0) 10564 .add(predOps(ARMCC::AL)); 10565 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10566 .add(t1CondCodeOp()) 10567 .addReg(AddrIn) 10568 .addImm(StSize) 10569 .add(predOps(ARMCC::AL)); 10570 } else if (IsThumb2) { 10571 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10572 .addReg(Data) 10573 .addReg(AddrIn) 10574 .addImm(StSize) 10575 .add(predOps(ARMCC::AL)); 10576 } else { // arm 10577 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10578 .addReg(Data) 10579 .addReg(AddrIn) 10580 .addReg(0) 10581 .addImm(StSize) 10582 .add(predOps(ARMCC::AL)); 10583 } 10584 } 10585 10586 MachineBasicBlock * 10587 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 10588 MachineBasicBlock *BB) const { 10589 // This pseudo instruction has 3 operands: dst, src, size 10590 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 10591 // Otherwise, we will generate unrolled scalar copies. 10592 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10593 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10594 MachineFunction::iterator It = ++BB->getIterator(); 10595 10596 Register dest = MI.getOperand(0).getReg(); 10597 Register src = MI.getOperand(1).getReg(); 10598 unsigned SizeVal = MI.getOperand(2).getImm(); 10599 unsigned Alignment = MI.getOperand(3).getImm(); 10600 DebugLoc dl = MI.getDebugLoc(); 10601 10602 MachineFunction *MF = BB->getParent(); 10603 MachineRegisterInfo &MRI = MF->getRegInfo(); 10604 unsigned UnitSize = 0; 10605 const TargetRegisterClass *TRC = nullptr; 10606 const TargetRegisterClass *VecTRC = nullptr; 10607 10608 bool IsThumb1 = Subtarget->isThumb1Only(); 10609 bool IsThumb2 = Subtarget->isThumb2(); 10610 bool IsThumb = Subtarget->isThumb(); 10611 10612 if (Alignment & 1) { 10613 UnitSize = 1; 10614 } else if (Alignment & 2) { 10615 UnitSize = 2; 10616 } else { 10617 // Check whether we can use NEON instructions. 10618 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 10619 Subtarget->hasNEON()) { 10620 if ((Alignment % 16 == 0) && SizeVal >= 16) 10621 UnitSize = 16; 10622 else if ((Alignment % 8 == 0) && SizeVal >= 8) 10623 UnitSize = 8; 10624 } 10625 // Can't use NEON instructions. 10626 if (UnitSize == 0) 10627 UnitSize = 4; 10628 } 10629 10630 // Select the correct opcode and register class for unit size load/store 10631 bool IsNeon = UnitSize >= 8; 10632 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 10633 if (IsNeon) 10634 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 10635 : UnitSize == 8 ? &ARM::DPRRegClass 10636 : nullptr; 10637 10638 unsigned BytesLeft = SizeVal % UnitSize; 10639 unsigned LoopSize = SizeVal - BytesLeft; 10640 10641 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 10642 // Use LDR and STR to copy. 10643 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 10644 // [destOut] = STR_POST(scratch, destIn, UnitSize) 10645 unsigned srcIn = src; 10646 unsigned destIn = dest; 10647 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 10648 Register srcOut = MRI.createVirtualRegister(TRC); 10649 Register destOut = MRI.createVirtualRegister(TRC); 10650 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10651 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 10652 IsThumb1, IsThumb2); 10653 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 10654 IsThumb1, IsThumb2); 10655 srcIn = srcOut; 10656 destIn = destOut; 10657 } 10658 10659 // Handle the leftover bytes with LDRB and STRB. 10660 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 10661 // [destOut] = STRB_POST(scratch, destIn, 1) 10662 for (unsigned i = 0; i < BytesLeft; i++) { 10663 Register srcOut = MRI.createVirtualRegister(TRC); 10664 Register destOut = MRI.createVirtualRegister(TRC); 10665 Register scratch = MRI.createVirtualRegister(TRC); 10666 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 10667 IsThumb1, IsThumb2); 10668 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 10669 IsThumb1, IsThumb2); 10670 srcIn = srcOut; 10671 destIn = destOut; 10672 } 10673 MI.eraseFromParent(); // The instruction is gone now. 10674 return BB; 10675 } 10676 10677 // Expand the pseudo op to a loop. 10678 // thisMBB: 10679 // ... 10680 // movw varEnd, # --> with thumb2 10681 // movt varEnd, # 10682 // ldrcp varEnd, idx --> without thumb2 10683 // fallthrough --> loopMBB 10684 // loopMBB: 10685 // PHI varPhi, varEnd, varLoop 10686 // PHI srcPhi, src, srcLoop 10687 // PHI destPhi, dst, destLoop 10688 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10689 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 10690 // subs varLoop, varPhi, #UnitSize 10691 // bne loopMBB 10692 // fallthrough --> exitMBB 10693 // exitMBB: 10694 // epilogue to handle left-over bytes 10695 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10696 // [destOut] = STRB_POST(scratch, destLoop, 1) 10697 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10698 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10699 MF->insert(It, loopMBB); 10700 MF->insert(It, exitMBB); 10701 10702 // Transfer the remainder of BB and its successor edges to exitMBB. 10703 exitMBB->splice(exitMBB->begin(), BB, 10704 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10705 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10706 10707 // Load an immediate to varEnd. 10708 Register varEnd = MRI.createVirtualRegister(TRC); 10709 if (Subtarget->useMovt()) { 10710 unsigned Vtmp = varEnd; 10711 if ((LoopSize & 0xFFFF0000) != 0) 10712 Vtmp = MRI.createVirtualRegister(TRC); 10713 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 10714 .addImm(LoopSize & 0xFFFF) 10715 .add(predOps(ARMCC::AL)); 10716 10717 if ((LoopSize & 0xFFFF0000) != 0) 10718 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 10719 .addReg(Vtmp) 10720 .addImm(LoopSize >> 16) 10721 .add(predOps(ARMCC::AL)); 10722 } else { 10723 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10724 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10725 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 10726 10727 // MachineConstantPool wants an explicit alignment. 10728 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10729 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10730 MachineMemOperand *CPMMO = 10731 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 10732 MachineMemOperand::MOLoad, 4, Align(4)); 10733 10734 if (IsThumb) 10735 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 10736 .addReg(varEnd, RegState::Define) 10737 .addConstantPoolIndex(Idx) 10738 .add(predOps(ARMCC::AL)) 10739 .addMemOperand(CPMMO); 10740 else 10741 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 10742 .addReg(varEnd, RegState::Define) 10743 .addConstantPoolIndex(Idx) 10744 .addImm(0) 10745 .add(predOps(ARMCC::AL)) 10746 .addMemOperand(CPMMO); 10747 } 10748 BB->addSuccessor(loopMBB); 10749 10750 // Generate the loop body: 10751 // varPhi = PHI(varLoop, varEnd) 10752 // srcPhi = PHI(srcLoop, src) 10753 // destPhi = PHI(destLoop, dst) 10754 MachineBasicBlock *entryBB = BB; 10755 BB = loopMBB; 10756 Register varLoop = MRI.createVirtualRegister(TRC); 10757 Register varPhi = MRI.createVirtualRegister(TRC); 10758 Register srcLoop = MRI.createVirtualRegister(TRC); 10759 Register srcPhi = MRI.createVirtualRegister(TRC); 10760 Register destLoop = MRI.createVirtualRegister(TRC); 10761 Register destPhi = MRI.createVirtualRegister(TRC); 10762 10763 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 10764 .addReg(varLoop).addMBB(loopMBB) 10765 .addReg(varEnd).addMBB(entryBB); 10766 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 10767 .addReg(srcLoop).addMBB(loopMBB) 10768 .addReg(src).addMBB(entryBB); 10769 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 10770 .addReg(destLoop).addMBB(loopMBB) 10771 .addReg(dest).addMBB(entryBB); 10772 10773 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10774 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 10775 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10776 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 10777 IsThumb1, IsThumb2); 10778 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 10779 IsThumb1, IsThumb2); 10780 10781 // Decrement loop variable by UnitSize. 10782 if (IsThumb1) { 10783 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 10784 .add(t1CondCodeOp()) 10785 .addReg(varPhi) 10786 .addImm(UnitSize) 10787 .add(predOps(ARMCC::AL)); 10788 } else { 10789 MachineInstrBuilder MIB = 10790 BuildMI(*BB, BB->end(), dl, 10791 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 10792 MIB.addReg(varPhi) 10793 .addImm(UnitSize) 10794 .add(predOps(ARMCC::AL)) 10795 .add(condCodeOp()); 10796 MIB->getOperand(5).setReg(ARM::CPSR); 10797 MIB->getOperand(5).setIsDef(true); 10798 } 10799 BuildMI(*BB, BB->end(), dl, 10800 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10801 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 10802 10803 // loopMBB can loop back to loopMBB or fall through to exitMBB. 10804 BB->addSuccessor(loopMBB); 10805 BB->addSuccessor(exitMBB); 10806 10807 // Add epilogue to handle BytesLeft. 10808 BB = exitMBB; 10809 auto StartOfExit = exitMBB->begin(); 10810 10811 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10812 // [destOut] = STRB_POST(scratch, destLoop, 1) 10813 unsigned srcIn = srcLoop; 10814 unsigned destIn = destLoop; 10815 for (unsigned i = 0; i < BytesLeft; i++) { 10816 Register srcOut = MRI.createVirtualRegister(TRC); 10817 Register destOut = MRI.createVirtualRegister(TRC); 10818 Register scratch = MRI.createVirtualRegister(TRC); 10819 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 10820 IsThumb1, IsThumb2); 10821 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 10822 IsThumb1, IsThumb2); 10823 srcIn = srcOut; 10824 destIn = destOut; 10825 } 10826 10827 MI.eraseFromParent(); // The instruction is gone now. 10828 return BB; 10829 } 10830 10831 MachineBasicBlock * 10832 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 10833 MachineBasicBlock *MBB) const { 10834 const TargetMachine &TM = getTargetMachine(); 10835 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 10836 DebugLoc DL = MI.getDebugLoc(); 10837 10838 assert(Subtarget->isTargetWindows() && 10839 "__chkstk is only supported on Windows"); 10840 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 10841 10842 // __chkstk takes the number of words to allocate on the stack in R4, and 10843 // returns the stack adjustment in number of bytes in R4. This will not 10844 // clober any other registers (other than the obvious lr). 10845 // 10846 // Although, technically, IP should be considered a register which may be 10847 // clobbered, the call itself will not touch it. Windows on ARM is a pure 10848 // thumb-2 environment, so there is no interworking required. As a result, we 10849 // do not expect a veneer to be emitted by the linker, clobbering IP. 10850 // 10851 // Each module receives its own copy of __chkstk, so no import thunk is 10852 // required, again, ensuring that IP is not clobbered. 10853 // 10854 // Finally, although some linkers may theoretically provide a trampoline for 10855 // out of range calls (which is quite common due to a 32M range limitation of 10856 // branches for Thumb), we can generate the long-call version via 10857 // -mcmodel=large, alleviating the need for the trampoline which may clobber 10858 // IP. 10859 10860 switch (TM.getCodeModel()) { 10861 case CodeModel::Tiny: 10862 llvm_unreachable("Tiny code model not available on ARM."); 10863 case CodeModel::Small: 10864 case CodeModel::Medium: 10865 case CodeModel::Kernel: 10866 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 10867 .add(predOps(ARMCC::AL)) 10868 .addExternalSymbol("__chkstk") 10869 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10870 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10871 .addReg(ARM::R12, 10872 RegState::Implicit | RegState::Define | RegState::Dead) 10873 .addReg(ARM::CPSR, 10874 RegState::Implicit | RegState::Define | RegState::Dead); 10875 break; 10876 case CodeModel::Large: { 10877 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 10878 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 10879 10880 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 10881 .addExternalSymbol("__chkstk"); 10882 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 10883 .add(predOps(ARMCC::AL)) 10884 .addReg(Reg, RegState::Kill) 10885 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10886 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10887 .addReg(ARM::R12, 10888 RegState::Implicit | RegState::Define | RegState::Dead) 10889 .addReg(ARM::CPSR, 10890 RegState::Implicit | RegState::Define | RegState::Dead); 10891 break; 10892 } 10893 } 10894 10895 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 10896 .addReg(ARM::SP, RegState::Kill) 10897 .addReg(ARM::R4, RegState::Kill) 10898 .setMIFlags(MachineInstr::FrameSetup) 10899 .add(predOps(ARMCC::AL)) 10900 .add(condCodeOp()); 10901 10902 MI.eraseFromParent(); 10903 return MBB; 10904 } 10905 10906 MachineBasicBlock * 10907 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 10908 MachineBasicBlock *MBB) const { 10909 DebugLoc DL = MI.getDebugLoc(); 10910 MachineFunction *MF = MBB->getParent(); 10911 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10912 10913 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 10914 MF->insert(++MBB->getIterator(), ContBB); 10915 ContBB->splice(ContBB->begin(), MBB, 10916 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10917 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 10918 MBB->addSuccessor(ContBB); 10919 10920 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10921 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 10922 MF->push_back(TrapBB); 10923 MBB->addSuccessor(TrapBB); 10924 10925 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 10926 .addReg(MI.getOperand(0).getReg()) 10927 .addImm(0) 10928 .add(predOps(ARMCC::AL)); 10929 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 10930 .addMBB(TrapBB) 10931 .addImm(ARMCC::EQ) 10932 .addReg(ARM::CPSR); 10933 10934 MI.eraseFromParent(); 10935 return ContBB; 10936 } 10937 10938 // The CPSR operand of SelectItr might be missing a kill marker 10939 // because there were multiple uses of CPSR, and ISel didn't know 10940 // which to mark. Figure out whether SelectItr should have had a 10941 // kill marker, and set it if it should. Returns the correct kill 10942 // marker value. 10943 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 10944 MachineBasicBlock* BB, 10945 const TargetRegisterInfo* TRI) { 10946 // Scan forward through BB for a use/def of CPSR. 10947 MachineBasicBlock::iterator miI(std::next(SelectItr)); 10948 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 10949 const MachineInstr& mi = *miI; 10950 if (mi.readsRegister(ARM::CPSR)) 10951 return false; 10952 if (mi.definesRegister(ARM::CPSR)) 10953 break; // Should have kill-flag - update below. 10954 } 10955 10956 // If we hit the end of the block, check whether CPSR is live into a 10957 // successor. 10958 if (miI == BB->end()) { 10959 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 10960 sEnd = BB->succ_end(); 10961 sItr != sEnd; ++sItr) { 10962 MachineBasicBlock* succ = *sItr; 10963 if (succ->isLiveIn(ARM::CPSR)) 10964 return false; 10965 } 10966 } 10967 10968 // We found a def, or hit the end of the basic block and CPSR wasn't live 10969 // out. SelectMI should have a kill flag on CPSR. 10970 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 10971 return true; 10972 } 10973 10974 MachineBasicBlock * 10975 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10976 MachineBasicBlock *BB) const { 10977 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10978 DebugLoc dl = MI.getDebugLoc(); 10979 bool isThumb2 = Subtarget->isThumb2(); 10980 switch (MI.getOpcode()) { 10981 default: { 10982 MI.print(errs()); 10983 llvm_unreachable("Unexpected instr type to insert"); 10984 } 10985 10986 // Thumb1 post-indexed loads are really just single-register LDMs. 10987 case ARM::tLDR_postidx: { 10988 MachineOperand Def(MI.getOperand(1)); 10989 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 10990 .add(Def) // Rn_wb 10991 .add(MI.getOperand(2)) // Rn 10992 .add(MI.getOperand(3)) // PredImm 10993 .add(MI.getOperand(4)) // PredReg 10994 .add(MI.getOperand(0)) // Rt 10995 .cloneMemRefs(MI); 10996 MI.eraseFromParent(); 10997 return BB; 10998 } 10999 11000 // The Thumb2 pre-indexed stores have the same MI operands, they just 11001 // define them differently in the .td files from the isel patterns, so 11002 // they need pseudos. 11003 case ARM::t2STR_preidx: 11004 MI.setDesc(TII->get(ARM::t2STR_PRE)); 11005 return BB; 11006 case ARM::t2STRB_preidx: 11007 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 11008 return BB; 11009 case ARM::t2STRH_preidx: 11010 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 11011 return BB; 11012 11013 case ARM::STRi_preidx: 11014 case ARM::STRBi_preidx: { 11015 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 11016 : ARM::STRB_PRE_IMM; 11017 // Decode the offset. 11018 unsigned Offset = MI.getOperand(4).getImm(); 11019 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 11020 Offset = ARM_AM::getAM2Offset(Offset); 11021 if (isSub) 11022 Offset = -Offset; 11023 11024 MachineMemOperand *MMO = *MI.memoperands_begin(); 11025 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 11026 .add(MI.getOperand(0)) // Rn_wb 11027 .add(MI.getOperand(1)) // Rt 11028 .add(MI.getOperand(2)) // Rn 11029 .addImm(Offset) // offset (skip GPR==zero_reg) 11030 .add(MI.getOperand(5)) // pred 11031 .add(MI.getOperand(6)) 11032 .addMemOperand(MMO); 11033 MI.eraseFromParent(); 11034 return BB; 11035 } 11036 case ARM::STRr_preidx: 11037 case ARM::STRBr_preidx: 11038 case ARM::STRH_preidx: { 11039 unsigned NewOpc; 11040 switch (MI.getOpcode()) { 11041 default: llvm_unreachable("unexpected opcode!"); 11042 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 11043 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 11044 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 11045 } 11046 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 11047 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 11048 MIB.add(MI.getOperand(i)); 11049 MI.eraseFromParent(); 11050 return BB; 11051 } 11052 11053 case ARM::tMOVCCr_pseudo: { 11054 // To "insert" a SELECT_CC instruction, we actually have to insert the 11055 // diamond control-flow pattern. The incoming instruction knows the 11056 // destination vreg to set, the condition code register to branch on, the 11057 // true/false values to select between, and a branch opcode to use. 11058 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11059 MachineFunction::iterator It = ++BB->getIterator(); 11060 11061 // thisMBB: 11062 // ... 11063 // TrueVal = ... 11064 // cmpTY ccX, r1, r2 11065 // bCC copy1MBB 11066 // fallthrough --> copy0MBB 11067 MachineBasicBlock *thisMBB = BB; 11068 MachineFunction *F = BB->getParent(); 11069 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11070 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11071 F->insert(It, copy0MBB); 11072 F->insert(It, sinkMBB); 11073 11074 // Check whether CPSR is live past the tMOVCCr_pseudo. 11075 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11076 if (!MI.killsRegister(ARM::CPSR) && 11077 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 11078 copy0MBB->addLiveIn(ARM::CPSR); 11079 sinkMBB->addLiveIn(ARM::CPSR); 11080 } 11081 11082 // Transfer the remainder of BB and its successor edges to sinkMBB. 11083 sinkMBB->splice(sinkMBB->begin(), BB, 11084 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11085 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11086 11087 BB->addSuccessor(copy0MBB); 11088 BB->addSuccessor(sinkMBB); 11089 11090 BuildMI(BB, dl, TII->get(ARM::tBcc)) 11091 .addMBB(sinkMBB) 11092 .addImm(MI.getOperand(3).getImm()) 11093 .addReg(MI.getOperand(4).getReg()); 11094 11095 // copy0MBB: 11096 // %FalseValue = ... 11097 // # fallthrough to sinkMBB 11098 BB = copy0MBB; 11099 11100 // Update machine-CFG edges 11101 BB->addSuccessor(sinkMBB); 11102 11103 // sinkMBB: 11104 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11105 // ... 11106 BB = sinkMBB; 11107 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 11108 .addReg(MI.getOperand(1).getReg()) 11109 .addMBB(copy0MBB) 11110 .addReg(MI.getOperand(2).getReg()) 11111 .addMBB(thisMBB); 11112 11113 MI.eraseFromParent(); // The pseudo instruction is gone now. 11114 return BB; 11115 } 11116 11117 case ARM::BCCi64: 11118 case ARM::BCCZi64: { 11119 // If there is an unconditional branch to the other successor, remove it. 11120 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11121 11122 // Compare both parts that make up the double comparison separately for 11123 // equality. 11124 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 11125 11126 Register LHS1 = MI.getOperand(1).getReg(); 11127 Register LHS2 = MI.getOperand(2).getReg(); 11128 if (RHSisZero) { 11129 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11130 .addReg(LHS1) 11131 .addImm(0) 11132 .add(predOps(ARMCC::AL)); 11133 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11134 .addReg(LHS2).addImm(0) 11135 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 11136 } else { 11137 Register RHS1 = MI.getOperand(3).getReg(); 11138 Register RHS2 = MI.getOperand(4).getReg(); 11139 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 11140 .addReg(LHS1) 11141 .addReg(RHS1) 11142 .add(predOps(ARMCC::AL)); 11143 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 11144 .addReg(LHS2).addReg(RHS2) 11145 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 11146 } 11147 11148 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 11149 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 11150 if (MI.getOperand(0).getImm() == ARMCC::NE) 11151 std::swap(destMBB, exitMBB); 11152 11153 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 11154 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 11155 if (isThumb2) 11156 BuildMI(BB, dl, TII->get(ARM::t2B)) 11157 .addMBB(exitMBB) 11158 .add(predOps(ARMCC::AL)); 11159 else 11160 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 11161 11162 MI.eraseFromParent(); // The pseudo instruction is gone now. 11163 return BB; 11164 } 11165 11166 case ARM::Int_eh_sjlj_setjmp: 11167 case ARM::Int_eh_sjlj_setjmp_nofp: 11168 case ARM::tInt_eh_sjlj_setjmp: 11169 case ARM::t2Int_eh_sjlj_setjmp: 11170 case ARM::t2Int_eh_sjlj_setjmp_nofp: 11171 return BB; 11172 11173 case ARM::Int_eh_sjlj_setup_dispatch: 11174 EmitSjLjDispatchBlock(MI, BB); 11175 return BB; 11176 11177 case ARM::ABS: 11178 case ARM::t2ABS: { 11179 // To insert an ABS instruction, we have to insert the 11180 // diamond control-flow pattern. The incoming instruction knows the 11181 // source vreg to test against 0, the destination vreg to set, 11182 // the condition code register to branch on, the 11183 // true/false values to select between, and a branch opcode to use. 11184 // It transforms 11185 // V1 = ABS V0 11186 // into 11187 // V2 = MOVS V0 11188 // BCC (branch to SinkBB if V0 >= 0) 11189 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 11190 // SinkBB: V1 = PHI(V2, V3) 11191 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11192 MachineFunction::iterator BBI = ++BB->getIterator(); 11193 MachineFunction *Fn = BB->getParent(); 11194 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 11195 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 11196 Fn->insert(BBI, RSBBB); 11197 Fn->insert(BBI, SinkBB); 11198 11199 Register ABSSrcReg = MI.getOperand(1).getReg(); 11200 Register ABSDstReg = MI.getOperand(0).getReg(); 11201 bool ABSSrcKIll = MI.getOperand(1).isKill(); 11202 bool isThumb2 = Subtarget->isThumb2(); 11203 MachineRegisterInfo &MRI = Fn->getRegInfo(); 11204 // In Thumb mode S must not be specified if source register is the SP or 11205 // PC and if destination register is the SP, so restrict register class 11206 Register NewRsbDstReg = MRI.createVirtualRegister( 11207 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 11208 11209 // Transfer the remainder of BB and its successor edges to sinkMBB. 11210 SinkBB->splice(SinkBB->begin(), BB, 11211 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11212 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 11213 11214 BB->addSuccessor(RSBBB); 11215 BB->addSuccessor(SinkBB); 11216 11217 // fall through to SinkMBB 11218 RSBBB->addSuccessor(SinkBB); 11219 11220 // insert a cmp at the end of BB 11221 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11222 .addReg(ABSSrcReg) 11223 .addImm(0) 11224 .add(predOps(ARMCC::AL)); 11225 11226 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 11227 BuildMI(BB, dl, 11228 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 11229 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 11230 11231 // insert rsbri in RSBBB 11232 // Note: BCC and rsbri will be converted into predicated rsbmi 11233 // by if-conversion pass 11234 BuildMI(*RSBBB, RSBBB->begin(), dl, 11235 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 11236 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 11237 .addImm(0) 11238 .add(predOps(ARMCC::AL)) 11239 .add(condCodeOp()); 11240 11241 // insert PHI in SinkBB, 11242 // reuse ABSDstReg to not change uses of ABS instruction 11243 BuildMI(*SinkBB, SinkBB->begin(), dl, 11244 TII->get(ARM::PHI), ABSDstReg) 11245 .addReg(NewRsbDstReg).addMBB(RSBBB) 11246 .addReg(ABSSrcReg).addMBB(BB); 11247 11248 // remove ABS instruction 11249 MI.eraseFromParent(); 11250 11251 // return last added BB 11252 return SinkBB; 11253 } 11254 case ARM::COPY_STRUCT_BYVAL_I32: 11255 ++NumLoopByVals; 11256 return EmitStructByval(MI, BB); 11257 case ARM::WIN__CHKSTK: 11258 return EmitLowered__chkstk(MI, BB); 11259 case ARM::WIN__DBZCHK: 11260 return EmitLowered__dbzchk(MI, BB); 11261 } 11262 } 11263 11264 /// Attaches vregs to MEMCPY that it will use as scratch registers 11265 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 11266 /// instead of as a custom inserter because we need the use list from the SDNode. 11267 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 11268 MachineInstr &MI, const SDNode *Node) { 11269 bool isThumb1 = Subtarget->isThumb1Only(); 11270 11271 DebugLoc DL = MI.getDebugLoc(); 11272 MachineFunction *MF = MI.getParent()->getParent(); 11273 MachineRegisterInfo &MRI = MF->getRegInfo(); 11274 MachineInstrBuilder MIB(*MF, MI); 11275 11276 // If the new dst/src is unused mark it as dead. 11277 if (!Node->hasAnyUseOfValue(0)) { 11278 MI.getOperand(0).setIsDead(true); 11279 } 11280 if (!Node->hasAnyUseOfValue(1)) { 11281 MI.getOperand(1).setIsDead(true); 11282 } 11283 11284 // The MEMCPY both defines and kills the scratch registers. 11285 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 11286 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 11287 : &ARM::GPRRegClass); 11288 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 11289 } 11290 } 11291 11292 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11293 SDNode *Node) const { 11294 if (MI.getOpcode() == ARM::MEMCPY) { 11295 attachMEMCPYScratchRegs(Subtarget, MI, Node); 11296 return; 11297 } 11298 11299 const MCInstrDesc *MCID = &MI.getDesc(); 11300 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 11301 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 11302 // operand is still set to noreg. If needed, set the optional operand's 11303 // register to CPSR, and remove the redundant implicit def. 11304 // 11305 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 11306 11307 // Rename pseudo opcodes. 11308 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 11309 unsigned ccOutIdx; 11310 if (NewOpc) { 11311 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 11312 MCID = &TII->get(NewOpc); 11313 11314 assert(MCID->getNumOperands() == 11315 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 11316 && "converted opcode should be the same except for cc_out" 11317 " (and, on Thumb1, pred)"); 11318 11319 MI.setDesc(*MCID); 11320 11321 // Add the optional cc_out operand 11322 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 11323 11324 // On Thumb1, move all input operands to the end, then add the predicate 11325 if (Subtarget->isThumb1Only()) { 11326 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 11327 MI.addOperand(MI.getOperand(1)); 11328 MI.RemoveOperand(1); 11329 } 11330 11331 // Restore the ties 11332 for (unsigned i = MI.getNumOperands(); i--;) { 11333 const MachineOperand& op = MI.getOperand(i); 11334 if (op.isReg() && op.isUse()) { 11335 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 11336 if (DefIdx != -1) 11337 MI.tieOperands(DefIdx, i); 11338 } 11339 } 11340 11341 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 11342 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 11343 ccOutIdx = 1; 11344 } else 11345 ccOutIdx = MCID->getNumOperands() - 1; 11346 } else 11347 ccOutIdx = MCID->getNumOperands() - 1; 11348 11349 // Any ARM instruction that sets the 's' bit should specify an optional 11350 // "cc_out" operand in the last operand position. 11351 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 11352 assert(!NewOpc && "Optional cc_out operand required"); 11353 return; 11354 } 11355 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 11356 // since we already have an optional CPSR def. 11357 bool definesCPSR = false; 11358 bool deadCPSR = false; 11359 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 11360 ++i) { 11361 const MachineOperand &MO = MI.getOperand(i); 11362 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 11363 definesCPSR = true; 11364 if (MO.isDead()) 11365 deadCPSR = true; 11366 MI.RemoveOperand(i); 11367 break; 11368 } 11369 } 11370 if (!definesCPSR) { 11371 assert(!NewOpc && "Optional cc_out operand required"); 11372 return; 11373 } 11374 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 11375 if (deadCPSR) { 11376 assert(!MI.getOperand(ccOutIdx).getReg() && 11377 "expect uninitialized optional cc_out operand"); 11378 // Thumb1 instructions must have the S bit even if the CPSR is dead. 11379 if (!Subtarget->isThumb1Only()) 11380 return; 11381 } 11382 11383 // If this instruction was defined with an optional CPSR def and its dag node 11384 // had a live implicit CPSR def, then activate the optional CPSR def. 11385 MachineOperand &MO = MI.getOperand(ccOutIdx); 11386 MO.setReg(ARM::CPSR); 11387 MO.setIsDef(true); 11388 } 11389 11390 //===----------------------------------------------------------------------===// 11391 // ARM Optimization Hooks 11392 //===----------------------------------------------------------------------===// 11393 11394 // Helper function that checks if N is a null or all ones constant. 11395 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 11396 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 11397 } 11398 11399 // Return true if N is conditionally 0 or all ones. 11400 // Detects these expressions where cc is an i1 value: 11401 // 11402 // (select cc 0, y) [AllOnes=0] 11403 // (select cc y, 0) [AllOnes=0] 11404 // (zext cc) [AllOnes=0] 11405 // (sext cc) [AllOnes=0/1] 11406 // (select cc -1, y) [AllOnes=1] 11407 // (select cc y, -1) [AllOnes=1] 11408 // 11409 // Invert is set when N is the null/all ones constant when CC is false. 11410 // OtherOp is set to the alternative value of N. 11411 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 11412 SDValue &CC, bool &Invert, 11413 SDValue &OtherOp, 11414 SelectionDAG &DAG) { 11415 switch (N->getOpcode()) { 11416 default: return false; 11417 case ISD::SELECT: { 11418 CC = N->getOperand(0); 11419 SDValue N1 = N->getOperand(1); 11420 SDValue N2 = N->getOperand(2); 11421 if (isZeroOrAllOnes(N1, AllOnes)) { 11422 Invert = false; 11423 OtherOp = N2; 11424 return true; 11425 } 11426 if (isZeroOrAllOnes(N2, AllOnes)) { 11427 Invert = true; 11428 OtherOp = N1; 11429 return true; 11430 } 11431 return false; 11432 } 11433 case ISD::ZERO_EXTEND: 11434 // (zext cc) can never be the all ones value. 11435 if (AllOnes) 11436 return false; 11437 LLVM_FALLTHROUGH; 11438 case ISD::SIGN_EXTEND: { 11439 SDLoc dl(N); 11440 EVT VT = N->getValueType(0); 11441 CC = N->getOperand(0); 11442 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 11443 return false; 11444 Invert = !AllOnes; 11445 if (AllOnes) 11446 // When looking for an AllOnes constant, N is an sext, and the 'other' 11447 // value is 0. 11448 OtherOp = DAG.getConstant(0, dl, VT); 11449 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11450 // When looking for a 0 constant, N can be zext or sext. 11451 OtherOp = DAG.getConstant(1, dl, VT); 11452 else 11453 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 11454 VT); 11455 return true; 11456 } 11457 } 11458 } 11459 11460 // Combine a constant select operand into its use: 11461 // 11462 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11463 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11464 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 11465 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11466 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11467 // 11468 // The transform is rejected if the select doesn't have a constant operand that 11469 // is null, or all ones when AllOnes is set. 11470 // 11471 // Also recognize sext/zext from i1: 11472 // 11473 // (add (zext cc), x) -> (select cc (add x, 1), x) 11474 // (add (sext cc), x) -> (select cc (add x, -1), x) 11475 // 11476 // These transformations eventually create predicated instructions. 11477 // 11478 // @param N The node to transform. 11479 // @param Slct The N operand that is a select. 11480 // @param OtherOp The other N operand (x above). 11481 // @param DCI Context. 11482 // @param AllOnes Require the select constant to be all ones instead of null. 11483 // @returns The new node, or SDValue() on failure. 11484 static 11485 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 11486 TargetLowering::DAGCombinerInfo &DCI, 11487 bool AllOnes = false) { 11488 SelectionDAG &DAG = DCI.DAG; 11489 EVT VT = N->getValueType(0); 11490 SDValue NonConstantVal; 11491 SDValue CCOp; 11492 bool SwapSelectOps; 11493 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 11494 NonConstantVal, DAG)) 11495 return SDValue(); 11496 11497 // Slct is now know to be the desired identity constant when CC is true. 11498 SDValue TrueVal = OtherOp; 11499 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 11500 OtherOp, NonConstantVal); 11501 // Unless SwapSelectOps says CC should be false. 11502 if (SwapSelectOps) 11503 std::swap(TrueVal, FalseVal); 11504 11505 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 11506 CCOp, TrueVal, FalseVal); 11507 } 11508 11509 // Attempt combineSelectAndUse on each operand of a commutative operator N. 11510 static 11511 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 11512 TargetLowering::DAGCombinerInfo &DCI) { 11513 SDValue N0 = N->getOperand(0); 11514 SDValue N1 = N->getOperand(1); 11515 if (N0.getNode()->hasOneUse()) 11516 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 11517 return Result; 11518 if (N1.getNode()->hasOneUse()) 11519 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 11520 return Result; 11521 return SDValue(); 11522 } 11523 11524 static bool IsVUZPShuffleNode(SDNode *N) { 11525 // VUZP shuffle node. 11526 if (N->getOpcode() == ARMISD::VUZP) 11527 return true; 11528 11529 // "VUZP" on i32 is an alias for VTRN. 11530 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 11531 return true; 11532 11533 return false; 11534 } 11535 11536 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 11537 TargetLowering::DAGCombinerInfo &DCI, 11538 const ARMSubtarget *Subtarget) { 11539 // Look for ADD(VUZP.0, VUZP.1). 11540 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 11541 N0 == N1) 11542 return SDValue(); 11543 11544 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 11545 if (!N->getValueType(0).is64BitVector()) 11546 return SDValue(); 11547 11548 // Generate vpadd. 11549 SelectionDAG &DAG = DCI.DAG; 11550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11551 SDLoc dl(N); 11552 SDNode *Unzip = N0.getNode(); 11553 EVT VT = N->getValueType(0); 11554 11555 SmallVector<SDValue, 8> Ops; 11556 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 11557 TLI.getPointerTy(DAG.getDataLayout()))); 11558 Ops.push_back(Unzip->getOperand(0)); 11559 Ops.push_back(Unzip->getOperand(1)); 11560 11561 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11562 } 11563 11564 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11565 TargetLowering::DAGCombinerInfo &DCI, 11566 const ARMSubtarget *Subtarget) { 11567 // Check for two extended operands. 11568 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 11569 N1.getOpcode() == ISD::SIGN_EXTEND) && 11570 !(N0.getOpcode() == ISD::ZERO_EXTEND && 11571 N1.getOpcode() == ISD::ZERO_EXTEND)) 11572 return SDValue(); 11573 11574 SDValue N00 = N0.getOperand(0); 11575 SDValue N10 = N1.getOperand(0); 11576 11577 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 11578 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 11579 N00 == N10) 11580 return SDValue(); 11581 11582 // We only recognize Q register paddl here; this can't be reached until 11583 // after type legalization. 11584 if (!N00.getValueType().is64BitVector() || 11585 !N0.getValueType().is128BitVector()) 11586 return SDValue(); 11587 11588 // Generate vpaddl. 11589 SelectionDAG &DAG = DCI.DAG; 11590 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11591 SDLoc dl(N); 11592 EVT VT = N->getValueType(0); 11593 11594 SmallVector<SDValue, 8> Ops; 11595 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 11596 unsigned Opcode; 11597 if (N0.getOpcode() == ISD::SIGN_EXTEND) 11598 Opcode = Intrinsic::arm_neon_vpaddls; 11599 else 11600 Opcode = Intrinsic::arm_neon_vpaddlu; 11601 Ops.push_back(DAG.getConstant(Opcode, dl, 11602 TLI.getPointerTy(DAG.getDataLayout()))); 11603 EVT ElemTy = N00.getValueType().getVectorElementType(); 11604 unsigned NumElts = VT.getVectorNumElements(); 11605 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 11606 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 11607 N00.getOperand(0), N00.getOperand(1)); 11608 Ops.push_back(Concat); 11609 11610 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11611 } 11612 11613 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 11614 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 11615 // much easier to match. 11616 static SDValue 11617 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11618 TargetLowering::DAGCombinerInfo &DCI, 11619 const ARMSubtarget *Subtarget) { 11620 // Only perform optimization if after legalize, and if NEON is available. We 11621 // also expected both operands to be BUILD_VECTORs. 11622 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 11623 || N0.getOpcode() != ISD::BUILD_VECTOR 11624 || N1.getOpcode() != ISD::BUILD_VECTOR) 11625 return SDValue(); 11626 11627 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 11628 EVT VT = N->getValueType(0); 11629 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 11630 return SDValue(); 11631 11632 // Check that the vector operands are of the right form. 11633 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 11634 // operands, where N is the size of the formed vector. 11635 // Each EXTRACT_VECTOR should have the same input vector and odd or even 11636 // index such that we have a pair wise add pattern. 11637 11638 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 11639 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11640 return SDValue(); 11641 SDValue Vec = N0->getOperand(0)->getOperand(0); 11642 SDNode *V = Vec.getNode(); 11643 unsigned nextIndex = 0; 11644 11645 // For each operands to the ADD which are BUILD_VECTORs, 11646 // check to see if each of their operands are an EXTRACT_VECTOR with 11647 // the same vector and appropriate index. 11648 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 11649 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 11650 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11651 11652 SDValue ExtVec0 = N0->getOperand(i); 11653 SDValue ExtVec1 = N1->getOperand(i); 11654 11655 // First operand is the vector, verify its the same. 11656 if (V != ExtVec0->getOperand(0).getNode() || 11657 V != ExtVec1->getOperand(0).getNode()) 11658 return SDValue(); 11659 11660 // Second is the constant, verify its correct. 11661 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 11662 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 11663 11664 // For the constant, we want to see all the even or all the odd. 11665 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 11666 || C1->getZExtValue() != nextIndex+1) 11667 return SDValue(); 11668 11669 // Increment index. 11670 nextIndex+=2; 11671 } else 11672 return SDValue(); 11673 } 11674 11675 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 11676 // we're using the entire input vector, otherwise there's a size/legality 11677 // mismatch somewhere. 11678 if (nextIndex != Vec.getValueType().getVectorNumElements() || 11679 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 11680 return SDValue(); 11681 11682 // Create VPADDL node. 11683 SelectionDAG &DAG = DCI.DAG; 11684 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11685 11686 SDLoc dl(N); 11687 11688 // Build operand list. 11689 SmallVector<SDValue, 8> Ops; 11690 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 11691 TLI.getPointerTy(DAG.getDataLayout()))); 11692 11693 // Input is the vector. 11694 Ops.push_back(Vec); 11695 11696 // Get widened type and narrowed type. 11697 MVT widenType; 11698 unsigned numElem = VT.getVectorNumElements(); 11699 11700 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 11701 switch (inputLaneType.getSimpleVT().SimpleTy) { 11702 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 11703 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 11704 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 11705 default: 11706 llvm_unreachable("Invalid vector element type for padd optimization."); 11707 } 11708 11709 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 11710 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 11711 return DAG.getNode(ExtOp, dl, VT, tmp); 11712 } 11713 11714 static SDValue findMUL_LOHI(SDValue V) { 11715 if (V->getOpcode() == ISD::UMUL_LOHI || 11716 V->getOpcode() == ISD::SMUL_LOHI) 11717 return V; 11718 return SDValue(); 11719 } 11720 11721 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 11722 TargetLowering::DAGCombinerInfo &DCI, 11723 const ARMSubtarget *Subtarget) { 11724 if (!Subtarget->hasBaseDSP()) 11725 return SDValue(); 11726 11727 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 11728 // accumulates the product into a 64-bit value. The 16-bit values will 11729 // be sign extended somehow or SRA'd into 32-bit values 11730 // (addc (adde (mul 16bit, 16bit), lo), hi) 11731 SDValue Mul = AddcNode->getOperand(0); 11732 SDValue Lo = AddcNode->getOperand(1); 11733 if (Mul.getOpcode() != ISD::MUL) { 11734 Lo = AddcNode->getOperand(0); 11735 Mul = AddcNode->getOperand(1); 11736 if (Mul.getOpcode() != ISD::MUL) 11737 return SDValue(); 11738 } 11739 11740 SDValue SRA = AddeNode->getOperand(0); 11741 SDValue Hi = AddeNode->getOperand(1); 11742 if (SRA.getOpcode() != ISD::SRA) { 11743 SRA = AddeNode->getOperand(1); 11744 Hi = AddeNode->getOperand(0); 11745 if (SRA.getOpcode() != ISD::SRA) 11746 return SDValue(); 11747 } 11748 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 11749 if (Const->getZExtValue() != 31) 11750 return SDValue(); 11751 } else 11752 return SDValue(); 11753 11754 if (SRA.getOperand(0) != Mul) 11755 return SDValue(); 11756 11757 SelectionDAG &DAG = DCI.DAG; 11758 SDLoc dl(AddcNode); 11759 unsigned Opcode = 0; 11760 SDValue Op0; 11761 SDValue Op1; 11762 11763 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 11764 Opcode = ARMISD::SMLALBB; 11765 Op0 = Mul.getOperand(0); 11766 Op1 = Mul.getOperand(1); 11767 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 11768 Opcode = ARMISD::SMLALBT; 11769 Op0 = Mul.getOperand(0); 11770 Op1 = Mul.getOperand(1).getOperand(0); 11771 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 11772 Opcode = ARMISD::SMLALTB; 11773 Op0 = Mul.getOperand(0).getOperand(0); 11774 Op1 = Mul.getOperand(1); 11775 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 11776 Opcode = ARMISD::SMLALTT; 11777 Op0 = Mul->getOperand(0).getOperand(0); 11778 Op1 = Mul->getOperand(1).getOperand(0); 11779 } 11780 11781 if (!Op0 || !Op1) 11782 return SDValue(); 11783 11784 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 11785 Op0, Op1, Lo, Hi); 11786 // Replace the ADDs' nodes uses by the MLA node's values. 11787 SDValue HiMLALResult(SMLAL.getNode(), 1); 11788 SDValue LoMLALResult(SMLAL.getNode(), 0); 11789 11790 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 11791 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 11792 11793 // Return original node to notify the driver to stop replacing. 11794 SDValue resNode(AddcNode, 0); 11795 return resNode; 11796 } 11797 11798 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 11799 TargetLowering::DAGCombinerInfo &DCI, 11800 const ARMSubtarget *Subtarget) { 11801 // Look for multiply add opportunities. 11802 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 11803 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 11804 // a glue link from the first add to the second add. 11805 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 11806 // a S/UMLAL instruction. 11807 // UMUL_LOHI 11808 // / :lo \ :hi 11809 // V \ [no multiline comment] 11810 // loAdd -> ADDC | 11811 // \ :carry / 11812 // V V 11813 // ADDE <- hiAdd 11814 // 11815 // In the special case where only the higher part of a signed result is used 11816 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 11817 // a constant with the exact value of 0x80000000, we recognize we are dealing 11818 // with a "rounded multiply and add" (or subtract) and transform it into 11819 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 11820 11821 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 11822 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 11823 "Expect an ADDE or SUBE"); 11824 11825 assert(AddeSubeNode->getNumOperands() == 3 && 11826 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 11827 "ADDE node has the wrong inputs"); 11828 11829 // Check that we are chained to the right ADDC or SUBC node. 11830 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 11831 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 11832 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 11833 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 11834 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 11835 return SDValue(); 11836 11837 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 11838 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 11839 11840 // Check if the two operands are from the same mul_lohi node. 11841 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 11842 return SDValue(); 11843 11844 assert(AddcSubcNode->getNumValues() == 2 && 11845 AddcSubcNode->getValueType(0) == MVT::i32 && 11846 "Expect ADDC with two result values. First: i32"); 11847 11848 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 11849 // maybe a SMLAL which multiplies two 16-bit values. 11850 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 11851 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 11852 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 11853 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 11854 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 11855 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 11856 11857 // Check for the triangle shape. 11858 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 11859 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 11860 11861 // Make sure that the ADDE/SUBE operands are not coming from the same node. 11862 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 11863 return SDValue(); 11864 11865 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 11866 bool IsLeftOperandMUL = false; 11867 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 11868 if (MULOp == SDValue()) 11869 MULOp = findMUL_LOHI(AddeSubeOp1); 11870 else 11871 IsLeftOperandMUL = true; 11872 if (MULOp == SDValue()) 11873 return SDValue(); 11874 11875 // Figure out the right opcode. 11876 unsigned Opc = MULOp->getOpcode(); 11877 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 11878 11879 // Figure out the high and low input values to the MLAL node. 11880 SDValue *HiAddSub = nullptr; 11881 SDValue *LoMul = nullptr; 11882 SDValue *LowAddSub = nullptr; 11883 11884 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 11885 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 11886 return SDValue(); 11887 11888 if (IsLeftOperandMUL) 11889 HiAddSub = &AddeSubeOp1; 11890 else 11891 HiAddSub = &AddeSubeOp0; 11892 11893 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 11894 // whose low result is fed to the ADDC/SUBC we are checking. 11895 11896 if (AddcSubcOp0 == MULOp.getValue(0)) { 11897 LoMul = &AddcSubcOp0; 11898 LowAddSub = &AddcSubcOp1; 11899 } 11900 if (AddcSubcOp1 == MULOp.getValue(0)) { 11901 LoMul = &AddcSubcOp1; 11902 LowAddSub = &AddcSubcOp0; 11903 } 11904 11905 if (!LoMul) 11906 return SDValue(); 11907 11908 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 11909 // the replacement below will create a cycle. 11910 if (AddcSubcNode == HiAddSub->getNode() || 11911 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 11912 return SDValue(); 11913 11914 // Create the merged node. 11915 SelectionDAG &DAG = DCI.DAG; 11916 11917 // Start building operand list. 11918 SmallVector<SDValue, 8> Ops; 11919 Ops.push_back(LoMul->getOperand(0)); 11920 Ops.push_back(LoMul->getOperand(1)); 11921 11922 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 11923 // the case, we must be doing signed multiplication and only use the higher 11924 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 11925 // addition or subtraction with the value of 0x800000. 11926 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 11927 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 11928 LowAddSub->getNode()->getOpcode() == ISD::Constant && 11929 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 11930 0x80000000) { 11931 Ops.push_back(*HiAddSub); 11932 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 11933 FinalOpc = ARMISD::SMMLSR; 11934 } else { 11935 FinalOpc = ARMISD::SMMLAR; 11936 } 11937 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 11938 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 11939 11940 return SDValue(AddeSubeNode, 0); 11941 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 11942 // SMMLS is generated during instruction selection and the rest of this 11943 // function can not handle the case where AddcSubcNode is a SUBC. 11944 return SDValue(); 11945 11946 // Finish building the operand list for {U/S}MLAL 11947 Ops.push_back(*LowAddSub); 11948 Ops.push_back(*HiAddSub); 11949 11950 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 11951 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11952 11953 // Replace the ADDs' nodes uses by the MLA node's values. 11954 SDValue HiMLALResult(MLALNode.getNode(), 1); 11955 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 11956 11957 SDValue LoMLALResult(MLALNode.getNode(), 0); 11958 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 11959 11960 // Return original node to notify the driver to stop replacing. 11961 return SDValue(AddeSubeNode, 0); 11962 } 11963 11964 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 11965 TargetLowering::DAGCombinerInfo &DCI, 11966 const ARMSubtarget *Subtarget) { 11967 // UMAAL is similar to UMLAL except that it adds two unsigned values. 11968 // While trying to combine for the other MLAL nodes, first search for the 11969 // chance to use UMAAL. Check if Addc uses a node which has already 11970 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 11971 // as the addend, and it's handled in PerformUMLALCombine. 11972 11973 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11974 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11975 11976 // Check that we have a glued ADDC node. 11977 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 11978 if (AddcNode->getOpcode() != ARMISD::ADDC) 11979 return SDValue(); 11980 11981 // Find the converted UMAAL or quit if it doesn't exist. 11982 SDNode *UmlalNode = nullptr; 11983 SDValue AddHi; 11984 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 11985 UmlalNode = AddcNode->getOperand(0).getNode(); 11986 AddHi = AddcNode->getOperand(1); 11987 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 11988 UmlalNode = AddcNode->getOperand(1).getNode(); 11989 AddHi = AddcNode->getOperand(0); 11990 } else { 11991 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11992 } 11993 11994 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 11995 // the ADDC as well as Zero. 11996 if (!isNullConstant(UmlalNode->getOperand(3))) 11997 return SDValue(); 11998 11999 if ((isNullConstant(AddeNode->getOperand(0)) && 12000 AddeNode->getOperand(1).getNode() == UmlalNode) || 12001 (AddeNode->getOperand(0).getNode() == UmlalNode && 12002 isNullConstant(AddeNode->getOperand(1)))) { 12003 SelectionDAG &DAG = DCI.DAG; 12004 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 12005 UmlalNode->getOperand(2), AddHi }; 12006 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 12007 DAG.getVTList(MVT::i32, MVT::i32), Ops); 12008 12009 // Replace the ADDs' nodes uses by the UMAAL node's values. 12010 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 12011 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 12012 12013 // Return original node to notify the driver to stop replacing. 12014 return SDValue(AddeNode, 0); 12015 } 12016 return SDValue(); 12017 } 12018 12019 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 12020 const ARMSubtarget *Subtarget) { 12021 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 12022 return SDValue(); 12023 12024 // Check that we have a pair of ADDC and ADDE as operands. 12025 // Both addends of the ADDE must be zero. 12026 SDNode* AddcNode = N->getOperand(2).getNode(); 12027 SDNode* AddeNode = N->getOperand(3).getNode(); 12028 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 12029 (AddeNode->getOpcode() == ARMISD::ADDE) && 12030 isNullConstant(AddeNode->getOperand(0)) && 12031 isNullConstant(AddeNode->getOperand(1)) && 12032 (AddeNode->getOperand(2).getNode() == AddcNode)) 12033 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 12034 DAG.getVTList(MVT::i32, MVT::i32), 12035 {N->getOperand(0), N->getOperand(1), 12036 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 12037 else 12038 return SDValue(); 12039 } 12040 12041 static SDValue PerformAddcSubcCombine(SDNode *N, 12042 TargetLowering::DAGCombinerInfo &DCI, 12043 const ARMSubtarget *Subtarget) { 12044 SelectionDAG &DAG(DCI.DAG); 12045 12046 if (N->getOpcode() == ARMISD::SUBC) { 12047 // (SUBC (ADDE 0, 0, C), 1) -> C 12048 SDValue LHS = N->getOperand(0); 12049 SDValue RHS = N->getOperand(1); 12050 if (LHS->getOpcode() == ARMISD::ADDE && 12051 isNullConstant(LHS->getOperand(0)) && 12052 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 12053 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 12054 } 12055 } 12056 12057 if (Subtarget->isThumb1Only()) { 12058 SDValue RHS = N->getOperand(1); 12059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 12060 int32_t imm = C->getSExtValue(); 12061 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 12062 SDLoc DL(N); 12063 RHS = DAG.getConstant(-imm, DL, MVT::i32); 12064 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 12065 : ARMISD::ADDC; 12066 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 12067 } 12068 } 12069 } 12070 12071 return SDValue(); 12072 } 12073 12074 static SDValue PerformAddeSubeCombine(SDNode *N, 12075 TargetLowering::DAGCombinerInfo &DCI, 12076 const ARMSubtarget *Subtarget) { 12077 if (Subtarget->isThumb1Only()) { 12078 SelectionDAG &DAG = DCI.DAG; 12079 SDValue RHS = N->getOperand(1); 12080 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 12081 int64_t imm = C->getSExtValue(); 12082 if (imm < 0) { 12083 SDLoc DL(N); 12084 12085 // The with-carry-in form matches bitwise not instead of the negation. 12086 // Effectively, the inverse interpretation of the carry flag already 12087 // accounts for part of the negation. 12088 RHS = DAG.getConstant(~imm, DL, MVT::i32); 12089 12090 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 12091 : ARMISD::ADDE; 12092 return DAG.getNode(Opcode, DL, N->getVTList(), 12093 N->getOperand(0), RHS, N->getOperand(2)); 12094 } 12095 } 12096 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 12097 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 12098 } 12099 return SDValue(); 12100 } 12101 12102 static SDValue PerformSELECTCombine(SDNode *N, 12103 TargetLowering::DAGCombinerInfo &DCI, 12104 const ARMSubtarget *Subtarget) { 12105 if (!Subtarget->hasMVEIntegerOps()) 12106 return SDValue(); 12107 12108 SDLoc dl(N); 12109 SDValue SetCC; 12110 SDValue LHS; 12111 SDValue RHS; 12112 ISD::CondCode CC; 12113 SDValue TrueVal; 12114 SDValue FalseVal; 12115 12116 if (N->getOpcode() == ISD::SELECT && 12117 N->getOperand(0)->getOpcode() == ISD::SETCC) { 12118 SetCC = N->getOperand(0); 12119 LHS = SetCC->getOperand(0); 12120 RHS = SetCC->getOperand(1); 12121 CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 12122 TrueVal = N->getOperand(1); 12123 FalseVal = N->getOperand(2); 12124 } else if (N->getOpcode() == ISD::SELECT_CC) { 12125 LHS = N->getOperand(0); 12126 RHS = N->getOperand(1); 12127 CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 12128 TrueVal = N->getOperand(2); 12129 FalseVal = N->getOperand(3); 12130 } else { 12131 return SDValue(); 12132 } 12133 12134 unsigned int Opcode = 0; 12135 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN || 12136 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) && 12137 (CC == ISD::SETULT || CC == ISD::SETUGT)) { 12138 Opcode = ARMISD::VMINVu; 12139 if (CC == ISD::SETUGT) 12140 std::swap(TrueVal, FalseVal); 12141 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN || 12142 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) && 12143 (CC == ISD::SETLT || CC == ISD::SETGT)) { 12144 Opcode = ARMISD::VMINVs; 12145 if (CC == ISD::SETGT) 12146 std::swap(TrueVal, FalseVal); 12147 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX || 12148 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) && 12149 (CC == ISD::SETUGT || CC == ISD::SETULT)) { 12150 Opcode = ARMISD::VMAXVu; 12151 if (CC == ISD::SETULT) 12152 std::swap(TrueVal, FalseVal); 12153 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX || 12154 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) && 12155 (CC == ISD::SETGT || CC == ISD::SETLT)) { 12156 Opcode = ARMISD::VMAXVs; 12157 if (CC == ISD::SETLT) 12158 std::swap(TrueVal, FalseVal); 12159 } else 12160 return SDValue(); 12161 12162 // Normalise to the right hand side being the vector reduction 12163 switch (TrueVal->getOpcode()) { 12164 case ISD::VECREDUCE_UMIN: 12165 case ISD::VECREDUCE_SMIN: 12166 case ISD::VECREDUCE_UMAX: 12167 case ISD::VECREDUCE_SMAX: 12168 std::swap(LHS, RHS); 12169 std::swap(TrueVal, FalseVal); 12170 break; 12171 } 12172 12173 EVT VectorType = FalseVal->getOperand(0).getValueType(); 12174 12175 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 && 12176 VectorType != MVT::v4i32) 12177 return SDValue(); 12178 12179 EVT VectorScalarType = VectorType.getVectorElementType(); 12180 12181 // The values being selected must also be the ones being compared 12182 if (TrueVal != LHS || FalseVal != RHS) 12183 return SDValue(); 12184 12185 EVT LeftType = LHS->getValueType(0); 12186 EVT RightType = RHS->getValueType(0); 12187 12188 // The types must match the reduced type too 12189 if (LeftType != VectorScalarType || RightType != VectorScalarType) 12190 return SDValue(); 12191 12192 // Legalise the scalar to an i32 12193 if (VectorScalarType != MVT::i32) 12194 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 12195 12196 // Generate the reduction as an i32 for legalisation purposes 12197 auto Reduction = 12198 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0)); 12199 12200 // The result isn't actually an i32 so truncate it back to its original type 12201 if (VectorScalarType != MVT::i32) 12202 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction); 12203 12204 return Reduction; 12205 } 12206 12207 static SDValue PerformVSELECTCombine(SDNode *N, 12208 TargetLowering::DAGCombinerInfo &DCI, 12209 const ARMSubtarget *Subtarget) { 12210 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs). 12211 // 12212 // We need to re-implement this optimization here as the implementation in the 12213 // Target-Independent DAGCombiner does not handle the kind of constant we make 12214 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for 12215 // good reason, allowing truncation there would break other targets). 12216 // 12217 // Currently, this is only done for MVE, as it's the only target that benefits 12218 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL). 12219 if (!Subtarget->hasMVEIntegerOps()) 12220 return SDValue(); 12221 12222 if (N->getOperand(0).getOpcode() != ISD::XOR) 12223 return SDValue(); 12224 SDValue XOR = N->getOperand(0); 12225 12226 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s. 12227 // It is important to check with truncation allowed as the BUILD_VECTORs we 12228 // generate in those situations will truncate their operands. 12229 ConstantSDNode *Const = 12230 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false, 12231 /*AllowTruncation*/ true); 12232 if (!Const || !Const->isOne()) 12233 return SDValue(); 12234 12235 // Rewrite into vselect(cond, rhs, lhs). 12236 SDValue Cond = XOR->getOperand(0); 12237 SDValue LHS = N->getOperand(1); 12238 SDValue RHS = N->getOperand(2); 12239 EVT Type = N->getValueType(0); 12240 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS); 12241 } 12242 12243 static SDValue PerformABSCombine(SDNode *N, 12244 TargetLowering::DAGCombinerInfo &DCI, 12245 const ARMSubtarget *Subtarget) { 12246 SDValue res; 12247 SelectionDAG &DAG = DCI.DAG; 12248 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12249 12250 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 12251 return SDValue(); 12252 12253 if (!TLI.expandABS(N, res, DAG)) 12254 return SDValue(); 12255 12256 return res; 12257 } 12258 12259 /// PerformADDECombine - Target-specific dag combine transform from 12260 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 12261 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 12262 static SDValue PerformADDECombine(SDNode *N, 12263 TargetLowering::DAGCombinerInfo &DCI, 12264 const ARMSubtarget *Subtarget) { 12265 // Only ARM and Thumb2 support UMLAL/SMLAL. 12266 if (Subtarget->isThumb1Only()) 12267 return PerformAddeSubeCombine(N, DCI, Subtarget); 12268 12269 // Only perform the checks after legalize when the pattern is available. 12270 if (DCI.isBeforeLegalize()) return SDValue(); 12271 12272 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 12273 } 12274 12275 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 12276 /// operands N0 and N1. This is a helper for PerformADDCombine that is 12277 /// called with the default operands, and if that fails, with commuted 12278 /// operands. 12279 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 12280 TargetLowering::DAGCombinerInfo &DCI, 12281 const ARMSubtarget *Subtarget){ 12282 // Attempt to create vpadd for this add. 12283 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 12284 return Result; 12285 12286 // Attempt to create vpaddl for this add. 12287 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 12288 return Result; 12289 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 12290 Subtarget)) 12291 return Result; 12292 12293 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 12294 if (N0.getNode()->hasOneUse()) 12295 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 12296 return Result; 12297 return SDValue(); 12298 } 12299 12300 static SDValue PerformADDVecReduce(SDNode *N, 12301 TargetLowering::DAGCombinerInfo &DCI, 12302 const ARMSubtarget *Subtarget) { 12303 if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64) 12304 return SDValue(); 12305 12306 SDValue N0 = N->getOperand(0); 12307 SDValue N1 = N->getOperand(1); 12308 12309 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this 12310 // will look like: 12311 // t1: i32,i32 = ARMISD::VADDLVs x 12312 // t2: i64 = build_pair t1, t1:1 12313 // t3: i64 = add t2, y 12314 // We also need to check for sext / zext and commutitive adds. 12315 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA, 12316 SDValue NB) { 12317 if (NB->getOpcode() != ISD::BUILD_PAIR) 12318 return SDValue(); 12319 SDValue VecRed = NB->getOperand(0); 12320 if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 || 12321 NB->getOperand(1) != SDValue(VecRed.getNode(), 1)) 12322 return SDValue(); 12323 12324 SDLoc dl(N); 12325 SmallVector<SDValue, 4> Ops; 12326 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 12327 DCI.DAG.getConstant(0, dl, MVT::i32))); 12328 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 12329 DCI.DAG.getConstant(1, dl, MVT::i32))); 12330 for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++) 12331 Ops.push_back(VecRed->getOperand(i)); 12332 SDValue Red = DCI.DAG.getNode(OpcodeA, dl, 12333 DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops); 12334 return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red, 12335 SDValue(Red.getNode(), 1)); 12336 }; 12337 12338 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1)) 12339 return M; 12340 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1)) 12341 return M; 12342 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0)) 12343 return M; 12344 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0)) 12345 return M; 12346 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1)) 12347 return M; 12348 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1)) 12349 return M; 12350 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0)) 12351 return M; 12352 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0)) 12353 return M; 12354 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1)) 12355 return M; 12356 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1)) 12357 return M; 12358 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0)) 12359 return M; 12360 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0)) 12361 return M; 12362 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1)) 12363 return M; 12364 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1)) 12365 return M; 12366 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0)) 12367 return M; 12368 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0)) 12369 return M; 12370 return SDValue(); 12371 } 12372 12373 bool 12374 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 12375 CombineLevel Level) const { 12376 if (Level == BeforeLegalizeTypes) 12377 return true; 12378 12379 if (N->getOpcode() != ISD::SHL) 12380 return true; 12381 12382 if (Subtarget->isThumb1Only()) { 12383 // Avoid making expensive immediates by commuting shifts. (This logic 12384 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 12385 // for free.) 12386 if (N->getOpcode() != ISD::SHL) 12387 return true; 12388 SDValue N1 = N->getOperand(0); 12389 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 12390 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 12391 return true; 12392 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 12393 if (Const->getAPIntValue().ult(256)) 12394 return false; 12395 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 12396 Const->getAPIntValue().sgt(-256)) 12397 return false; 12398 } 12399 return true; 12400 } 12401 12402 // Turn off commute-with-shift transform after legalization, so it doesn't 12403 // conflict with PerformSHLSimplify. (We could try to detect when 12404 // PerformSHLSimplify would trigger more precisely, but it isn't 12405 // really necessary.) 12406 return false; 12407 } 12408 12409 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 12410 const SDNode *N, CombineLevel Level) const { 12411 if (!Subtarget->isThumb1Only()) 12412 return true; 12413 12414 if (Level == BeforeLegalizeTypes) 12415 return true; 12416 12417 return false; 12418 } 12419 12420 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 12421 if (!Subtarget->hasNEON()) { 12422 if (Subtarget->isThumb1Only()) 12423 return VT.getScalarSizeInBits() <= 32; 12424 return true; 12425 } 12426 return VT.isScalarInteger(); 12427 } 12428 12429 static SDValue PerformSHLSimplify(SDNode *N, 12430 TargetLowering::DAGCombinerInfo &DCI, 12431 const ARMSubtarget *ST) { 12432 // Allow the generic combiner to identify potential bswaps. 12433 if (DCI.isBeforeLegalize()) 12434 return SDValue(); 12435 12436 // DAG combiner will fold: 12437 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 12438 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 12439 // Other code patterns that can be also be modified have the following form: 12440 // b + ((a << 1) | 510) 12441 // b + ((a << 1) & 510) 12442 // b + ((a << 1) ^ 510) 12443 // b + ((a << 1) + 510) 12444 12445 // Many instructions can perform the shift for free, but it requires both 12446 // the operands to be registers. If c1 << c2 is too large, a mov immediate 12447 // instruction will needed. So, unfold back to the original pattern if: 12448 // - if c1 and c2 are small enough that they don't require mov imms. 12449 // - the user(s) of the node can perform an shl 12450 12451 // No shifted operands for 16-bit instructions. 12452 if (ST->isThumb() && ST->isThumb1Only()) 12453 return SDValue(); 12454 12455 // Check that all the users could perform the shl themselves. 12456 for (auto U : N->uses()) { 12457 switch(U->getOpcode()) { 12458 default: 12459 return SDValue(); 12460 case ISD::SUB: 12461 case ISD::ADD: 12462 case ISD::AND: 12463 case ISD::OR: 12464 case ISD::XOR: 12465 case ISD::SETCC: 12466 case ARMISD::CMP: 12467 // Check that the user isn't already using a constant because there 12468 // aren't any instructions that support an immediate operand and a 12469 // shifted operand. 12470 if (isa<ConstantSDNode>(U->getOperand(0)) || 12471 isa<ConstantSDNode>(U->getOperand(1))) 12472 return SDValue(); 12473 12474 // Check that it's not already using a shift. 12475 if (U->getOperand(0).getOpcode() == ISD::SHL || 12476 U->getOperand(1).getOpcode() == ISD::SHL) 12477 return SDValue(); 12478 break; 12479 } 12480 } 12481 12482 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 12483 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 12484 return SDValue(); 12485 12486 if (N->getOperand(0).getOpcode() != ISD::SHL) 12487 return SDValue(); 12488 12489 SDValue SHL = N->getOperand(0); 12490 12491 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12492 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 12493 if (!C1ShlC2 || !C2) 12494 return SDValue(); 12495 12496 APInt C2Int = C2->getAPIntValue(); 12497 APInt C1Int = C1ShlC2->getAPIntValue(); 12498 12499 // Check that performing a lshr will not lose any information. 12500 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 12501 C2Int.getBitWidth() - C2->getZExtValue()); 12502 if ((C1Int & Mask) != C1Int) 12503 return SDValue(); 12504 12505 // Shift the first constant. 12506 C1Int.lshrInPlace(C2Int); 12507 12508 // The immediates are encoded as an 8-bit value that can be rotated. 12509 auto LargeImm = [](const APInt &Imm) { 12510 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 12511 return Imm.getBitWidth() - Zeros > 8; 12512 }; 12513 12514 if (LargeImm(C1Int) || LargeImm(C2Int)) 12515 return SDValue(); 12516 12517 SelectionDAG &DAG = DCI.DAG; 12518 SDLoc dl(N); 12519 SDValue X = SHL.getOperand(0); 12520 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 12521 DAG.getConstant(C1Int, dl, MVT::i32)); 12522 // Shift left to compensate for the lshr of C1Int. 12523 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 12524 12525 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 12526 SHL.dump(); N->dump()); 12527 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 12528 return Res; 12529 } 12530 12531 12532 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 12533 /// 12534 static SDValue PerformADDCombine(SDNode *N, 12535 TargetLowering::DAGCombinerInfo &DCI, 12536 const ARMSubtarget *Subtarget) { 12537 SDValue N0 = N->getOperand(0); 12538 SDValue N1 = N->getOperand(1); 12539 12540 // Only works one way, because it needs an immediate operand. 12541 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12542 return Result; 12543 12544 if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget)) 12545 return Result; 12546 12547 // First try with the default operand order. 12548 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 12549 return Result; 12550 12551 // If that didn't work, try again with the operands commuted. 12552 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 12553 } 12554 12555 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 12556 /// 12557 static SDValue PerformSUBCombine(SDNode *N, 12558 TargetLowering::DAGCombinerInfo &DCI, 12559 const ARMSubtarget *Subtarget) { 12560 SDValue N0 = N->getOperand(0); 12561 SDValue N1 = N->getOperand(1); 12562 12563 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 12564 if (N1.getNode()->hasOneUse()) 12565 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 12566 return Result; 12567 12568 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector()) 12569 return SDValue(); 12570 12571 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x)) 12572 // so that we can readily pattern match more mve instructions which can use 12573 // a scalar operand. 12574 SDValue VDup = N->getOperand(1); 12575 if (VDup->getOpcode() != ARMISD::VDUP) 12576 return SDValue(); 12577 12578 SDValue VMov = N->getOperand(0); 12579 if (VMov->getOpcode() == ISD::BITCAST) 12580 VMov = VMov->getOperand(0); 12581 12582 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov)) 12583 return SDValue(); 12584 12585 SDLoc dl(N); 12586 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32, 12587 DCI.DAG.getConstant(0, dl, MVT::i32), 12588 VDup->getOperand(0)); 12589 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate); 12590 } 12591 12592 /// PerformVMULCombine 12593 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 12594 /// special multiplier accumulator forwarding. 12595 /// vmul d3, d0, d2 12596 /// vmla d3, d1, d2 12597 /// is faster than 12598 /// vadd d3, d0, d1 12599 /// vmul d3, d3, d2 12600 // However, for (A + B) * (A + B), 12601 // vadd d2, d0, d1 12602 // vmul d3, d0, d2 12603 // vmla d3, d1, d2 12604 // is slower than 12605 // vadd d2, d0, d1 12606 // vmul d3, d2, d2 12607 static SDValue PerformVMULCombine(SDNode *N, 12608 TargetLowering::DAGCombinerInfo &DCI, 12609 const ARMSubtarget *Subtarget) { 12610 if (!Subtarget->hasVMLxForwarding()) 12611 return SDValue(); 12612 12613 SelectionDAG &DAG = DCI.DAG; 12614 SDValue N0 = N->getOperand(0); 12615 SDValue N1 = N->getOperand(1); 12616 unsigned Opcode = N0.getOpcode(); 12617 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12618 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 12619 Opcode = N1.getOpcode(); 12620 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12621 Opcode != ISD::FADD && Opcode != ISD::FSUB) 12622 return SDValue(); 12623 std::swap(N0, N1); 12624 } 12625 12626 if (N0 == N1) 12627 return SDValue(); 12628 12629 EVT VT = N->getValueType(0); 12630 SDLoc DL(N); 12631 SDValue N00 = N0->getOperand(0); 12632 SDValue N01 = N0->getOperand(1); 12633 return DAG.getNode(Opcode, DL, VT, 12634 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 12635 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 12636 } 12637 12638 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG, 12639 const ARMSubtarget *Subtarget) { 12640 EVT VT = N->getValueType(0); 12641 if (VT != MVT::v2i64) 12642 return SDValue(); 12643 12644 SDValue N0 = N->getOperand(0); 12645 SDValue N1 = N->getOperand(1); 12646 12647 auto IsSignExt = [&](SDValue Op) { 12648 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG) 12649 return SDValue(); 12650 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT(); 12651 if (VT.getScalarSizeInBits() == 32) 12652 return Op->getOperand(0); 12653 return SDValue(); 12654 }; 12655 auto IsZeroExt = [&](SDValue Op) { 12656 // Zero extends are a little more awkward. At the point we are matching 12657 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask. 12658 // That might be before of after a bitcast depending on how the and is 12659 // placed. Because this has to look through bitcasts, it is currently only 12660 // supported on LE. 12661 if (!Subtarget->isLittle()) 12662 return SDValue(); 12663 12664 SDValue And = Op; 12665 if (And->getOpcode() == ISD::BITCAST) 12666 And = And->getOperand(0); 12667 if (And->getOpcode() != ISD::AND) 12668 return SDValue(); 12669 SDValue Mask = And->getOperand(1); 12670 if (Mask->getOpcode() == ISD::BITCAST) 12671 Mask = Mask->getOperand(0); 12672 12673 if (Mask->getOpcode() != ISD::BUILD_VECTOR || 12674 Mask.getValueType() != MVT::v4i32) 12675 return SDValue(); 12676 if (isAllOnesConstant(Mask->getOperand(0)) && 12677 isNullConstant(Mask->getOperand(1)) && 12678 isAllOnesConstant(Mask->getOperand(2)) && 12679 isNullConstant(Mask->getOperand(3))) 12680 return And->getOperand(0); 12681 return SDValue(); 12682 }; 12683 12684 SDLoc dl(N); 12685 if (SDValue Op0 = IsSignExt(N0)) { 12686 if (SDValue Op1 = IsSignExt(N1)) { 12687 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12688 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12689 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a); 12690 } 12691 } 12692 if (SDValue Op0 = IsZeroExt(N0)) { 12693 if (SDValue Op1 = IsZeroExt(N1)) { 12694 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12695 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12696 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a); 12697 } 12698 } 12699 12700 return SDValue(); 12701 } 12702 12703 static SDValue PerformMULCombine(SDNode *N, 12704 TargetLowering::DAGCombinerInfo &DCI, 12705 const ARMSubtarget *Subtarget) { 12706 SelectionDAG &DAG = DCI.DAG; 12707 12708 EVT VT = N->getValueType(0); 12709 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64) 12710 return PerformMVEVMULLCombine(N, DAG, Subtarget); 12711 12712 if (Subtarget->isThumb1Only()) 12713 return SDValue(); 12714 12715 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12716 return SDValue(); 12717 12718 if (VT.is64BitVector() || VT.is128BitVector()) 12719 return PerformVMULCombine(N, DCI, Subtarget); 12720 if (VT != MVT::i32) 12721 return SDValue(); 12722 12723 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12724 if (!C) 12725 return SDValue(); 12726 12727 int64_t MulAmt = C->getSExtValue(); 12728 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 12729 12730 ShiftAmt = ShiftAmt & (32 - 1); 12731 SDValue V = N->getOperand(0); 12732 SDLoc DL(N); 12733 12734 SDValue Res; 12735 MulAmt >>= ShiftAmt; 12736 12737 if (MulAmt >= 0) { 12738 if (isPowerOf2_32(MulAmt - 1)) { 12739 // (mul x, 2^N + 1) => (add (shl x, N), x) 12740 Res = DAG.getNode(ISD::ADD, DL, VT, 12741 V, 12742 DAG.getNode(ISD::SHL, DL, VT, 12743 V, 12744 DAG.getConstant(Log2_32(MulAmt - 1), DL, 12745 MVT::i32))); 12746 } else if (isPowerOf2_32(MulAmt + 1)) { 12747 // (mul x, 2^N - 1) => (sub (shl x, N), x) 12748 Res = DAG.getNode(ISD::SUB, DL, VT, 12749 DAG.getNode(ISD::SHL, DL, VT, 12750 V, 12751 DAG.getConstant(Log2_32(MulAmt + 1), DL, 12752 MVT::i32)), 12753 V); 12754 } else 12755 return SDValue(); 12756 } else { 12757 uint64_t MulAmtAbs = -MulAmt; 12758 if (isPowerOf2_32(MulAmtAbs + 1)) { 12759 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 12760 Res = DAG.getNode(ISD::SUB, DL, VT, 12761 V, 12762 DAG.getNode(ISD::SHL, DL, VT, 12763 V, 12764 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 12765 MVT::i32))); 12766 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 12767 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 12768 Res = DAG.getNode(ISD::ADD, DL, VT, 12769 V, 12770 DAG.getNode(ISD::SHL, DL, VT, 12771 V, 12772 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 12773 MVT::i32))); 12774 Res = DAG.getNode(ISD::SUB, DL, VT, 12775 DAG.getConstant(0, DL, MVT::i32), Res); 12776 } else 12777 return SDValue(); 12778 } 12779 12780 if (ShiftAmt != 0) 12781 Res = DAG.getNode(ISD::SHL, DL, VT, 12782 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 12783 12784 // Do not add new nodes to DAG combiner worklist. 12785 DCI.CombineTo(N, Res, false); 12786 return SDValue(); 12787 } 12788 12789 static SDValue CombineANDShift(SDNode *N, 12790 TargetLowering::DAGCombinerInfo &DCI, 12791 const ARMSubtarget *Subtarget) { 12792 // Allow DAGCombine to pattern-match before we touch the canonical form. 12793 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12794 return SDValue(); 12795 12796 if (N->getValueType(0) != MVT::i32) 12797 return SDValue(); 12798 12799 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12800 if (!N1C) 12801 return SDValue(); 12802 12803 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 12804 // Don't transform uxtb/uxth. 12805 if (C1 == 255 || C1 == 65535) 12806 return SDValue(); 12807 12808 SDNode *N0 = N->getOperand(0).getNode(); 12809 if (!N0->hasOneUse()) 12810 return SDValue(); 12811 12812 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 12813 return SDValue(); 12814 12815 bool LeftShift = N0->getOpcode() == ISD::SHL; 12816 12817 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12818 if (!N01C) 12819 return SDValue(); 12820 12821 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 12822 if (!C2 || C2 >= 32) 12823 return SDValue(); 12824 12825 // Clear irrelevant bits in the mask. 12826 if (LeftShift) 12827 C1 &= (-1U << C2); 12828 else 12829 C1 &= (-1U >> C2); 12830 12831 SelectionDAG &DAG = DCI.DAG; 12832 SDLoc DL(N); 12833 12834 // We have a pattern of the form "(and (shl x, c2) c1)" or 12835 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 12836 // transform to a pair of shifts, to save materializing c1. 12837 12838 // First pattern: right shift, then mask off leading bits. 12839 // FIXME: Use demanded bits? 12840 if (!LeftShift && isMask_32(C1)) { 12841 uint32_t C3 = countLeadingZeros(C1); 12842 if (C2 < C3) { 12843 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12844 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12845 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12846 DAG.getConstant(C3, DL, MVT::i32)); 12847 } 12848 } 12849 12850 // First pattern, reversed: left shift, then mask off trailing bits. 12851 if (LeftShift && isMask_32(~C1)) { 12852 uint32_t C3 = countTrailingZeros(C1); 12853 if (C2 < C3) { 12854 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12855 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12856 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12857 DAG.getConstant(C3, DL, MVT::i32)); 12858 } 12859 } 12860 12861 // Second pattern: left shift, then mask off leading bits. 12862 // FIXME: Use demanded bits? 12863 if (LeftShift && isShiftedMask_32(C1)) { 12864 uint32_t Trailing = countTrailingZeros(C1); 12865 uint32_t C3 = countLeadingZeros(C1); 12866 if (Trailing == C2 && C2 + C3 < 32) { 12867 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12868 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12869 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12870 DAG.getConstant(C3, DL, MVT::i32)); 12871 } 12872 } 12873 12874 // Second pattern, reversed: right shift, then mask off trailing bits. 12875 // FIXME: Handle other patterns of known/demanded bits. 12876 if (!LeftShift && isShiftedMask_32(C1)) { 12877 uint32_t Leading = countLeadingZeros(C1); 12878 uint32_t C3 = countTrailingZeros(C1); 12879 if (Leading == C2 && C2 + C3 < 32) { 12880 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12881 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12882 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12883 DAG.getConstant(C3, DL, MVT::i32)); 12884 } 12885 } 12886 12887 // FIXME: Transform "(and (shl x, c2) c1)" -> 12888 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 12889 // c1. 12890 return SDValue(); 12891 } 12892 12893 static SDValue PerformANDCombine(SDNode *N, 12894 TargetLowering::DAGCombinerInfo &DCI, 12895 const ARMSubtarget *Subtarget) { 12896 // Attempt to use immediate-form VBIC 12897 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12898 SDLoc dl(N); 12899 EVT VT = N->getValueType(0); 12900 SelectionDAG &DAG = DCI.DAG; 12901 12902 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 || 12903 VT == MVT::v8i1 || VT == MVT::v16i1) 12904 return SDValue(); 12905 12906 APInt SplatBits, SplatUndef; 12907 unsigned SplatBitSize; 12908 bool HasAnyUndefs; 12909 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 12910 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 12911 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 || 12912 SplatBitSize == 64) { 12913 EVT VbicVT; 12914 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 12915 SplatUndef.getZExtValue(), SplatBitSize, 12916 DAG, dl, VbicVT, VT, OtherModImm); 12917 if (Val.getNode()) { 12918 SDValue Input = 12919 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 12920 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 12921 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 12922 } 12923 } 12924 } 12925 12926 if (!Subtarget->isThumb1Only()) { 12927 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 12928 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 12929 return Result; 12930 12931 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12932 return Result; 12933 } 12934 12935 if (Subtarget->isThumb1Only()) 12936 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 12937 return Result; 12938 12939 return SDValue(); 12940 } 12941 12942 // Try combining OR nodes to SMULWB, SMULWT. 12943 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 12944 TargetLowering::DAGCombinerInfo &DCI, 12945 const ARMSubtarget *Subtarget) { 12946 if (!Subtarget->hasV6Ops() || 12947 (Subtarget->isThumb() && 12948 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 12949 return SDValue(); 12950 12951 SDValue SRL = OR->getOperand(0); 12952 SDValue SHL = OR->getOperand(1); 12953 12954 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 12955 SRL = OR->getOperand(1); 12956 SHL = OR->getOperand(0); 12957 } 12958 if (!isSRL16(SRL) || !isSHL16(SHL)) 12959 return SDValue(); 12960 12961 // The first operands to the shifts need to be the two results from the 12962 // same smul_lohi node. 12963 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 12964 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 12965 return SDValue(); 12966 12967 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 12968 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 12969 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 12970 return SDValue(); 12971 12972 // Now we have: 12973 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 12974 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 12975 // For SMUWB the 16-bit value will signed extended somehow. 12976 // For SMULWT only the SRA is required. 12977 // Check both sides of SMUL_LOHI 12978 SDValue OpS16 = SMULLOHI->getOperand(0); 12979 SDValue OpS32 = SMULLOHI->getOperand(1); 12980 12981 SelectionDAG &DAG = DCI.DAG; 12982 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 12983 OpS16 = OpS32; 12984 OpS32 = SMULLOHI->getOperand(0); 12985 } 12986 12987 SDLoc dl(OR); 12988 unsigned Opcode = 0; 12989 if (isS16(OpS16, DAG)) 12990 Opcode = ARMISD::SMULWB; 12991 else if (isSRA16(OpS16)) { 12992 Opcode = ARMISD::SMULWT; 12993 OpS16 = OpS16->getOperand(0); 12994 } 12995 else 12996 return SDValue(); 12997 12998 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 12999 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 13000 return SDValue(OR, 0); 13001 } 13002 13003 static SDValue PerformORCombineToBFI(SDNode *N, 13004 TargetLowering::DAGCombinerInfo &DCI, 13005 const ARMSubtarget *Subtarget) { 13006 // BFI is only available on V6T2+ 13007 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 13008 return SDValue(); 13009 13010 EVT VT = N->getValueType(0); 13011 SDValue N0 = N->getOperand(0); 13012 SDValue N1 = N->getOperand(1); 13013 SelectionDAG &DAG = DCI.DAG; 13014 SDLoc DL(N); 13015 // 1) or (and A, mask), val => ARMbfi A, val, mask 13016 // iff (val & mask) == val 13017 // 13018 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 13019 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 13020 // && mask == ~mask2 13021 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 13022 // && ~mask == mask2 13023 // (i.e., copy a bitfield value into another bitfield of the same width) 13024 13025 if (VT != MVT::i32) 13026 return SDValue(); 13027 13028 SDValue N00 = N0.getOperand(0); 13029 13030 // The value and the mask need to be constants so we can verify this is 13031 // actually a bitfield set. If the mask is 0xffff, we can do better 13032 // via a movt instruction, so don't use BFI in that case. 13033 SDValue MaskOp = N0.getOperand(1); 13034 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 13035 if (!MaskC) 13036 return SDValue(); 13037 unsigned Mask = MaskC->getZExtValue(); 13038 if (Mask == 0xffff) 13039 return SDValue(); 13040 SDValue Res; 13041 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 13042 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 13043 if (N1C) { 13044 unsigned Val = N1C->getZExtValue(); 13045 if ((Val & ~Mask) != Val) 13046 return SDValue(); 13047 13048 if (ARM::isBitFieldInvertedMask(Mask)) { 13049 Val >>= countTrailingZeros(~Mask); 13050 13051 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 13052 DAG.getConstant(Val, DL, MVT::i32), 13053 DAG.getConstant(Mask, DL, MVT::i32)); 13054 13055 DCI.CombineTo(N, Res, false); 13056 // Return value from the original node to inform the combiner than N is 13057 // now dead. 13058 return SDValue(N, 0); 13059 } 13060 } else if (N1.getOpcode() == ISD::AND) { 13061 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 13062 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 13063 if (!N11C) 13064 return SDValue(); 13065 unsigned Mask2 = N11C->getZExtValue(); 13066 13067 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 13068 // as is to match. 13069 if (ARM::isBitFieldInvertedMask(Mask) && 13070 (Mask == ~Mask2)) { 13071 // The pack halfword instruction works better for masks that fit it, 13072 // so use that when it's available. 13073 if (Subtarget->hasDSP() && 13074 (Mask == 0xffff || Mask == 0xffff0000)) 13075 return SDValue(); 13076 // 2a 13077 unsigned amt = countTrailingZeros(Mask2); 13078 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 13079 DAG.getConstant(amt, DL, MVT::i32)); 13080 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 13081 DAG.getConstant(Mask, DL, MVT::i32)); 13082 DCI.CombineTo(N, Res, false); 13083 // Return value from the original node to inform the combiner than N is 13084 // now dead. 13085 return SDValue(N, 0); 13086 } else if (ARM::isBitFieldInvertedMask(~Mask) && 13087 (~Mask == Mask2)) { 13088 // The pack halfword instruction works better for masks that fit it, 13089 // so use that when it's available. 13090 if (Subtarget->hasDSP() && 13091 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 13092 return SDValue(); 13093 // 2b 13094 unsigned lsb = countTrailingZeros(Mask); 13095 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 13096 DAG.getConstant(lsb, DL, MVT::i32)); 13097 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 13098 DAG.getConstant(Mask2, DL, MVT::i32)); 13099 DCI.CombineTo(N, Res, false); 13100 // Return value from the original node to inform the combiner than N is 13101 // now dead. 13102 return SDValue(N, 0); 13103 } 13104 } 13105 13106 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 13107 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 13108 ARM::isBitFieldInvertedMask(~Mask)) { 13109 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 13110 // where lsb(mask) == #shamt and masked bits of B are known zero. 13111 SDValue ShAmt = N00.getOperand(1); 13112 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 13113 unsigned LSB = countTrailingZeros(Mask); 13114 if (ShAmtC != LSB) 13115 return SDValue(); 13116 13117 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 13118 DAG.getConstant(~Mask, DL, MVT::i32)); 13119 13120 DCI.CombineTo(N, Res, false); 13121 // Return value from the original node to inform the combiner than N is 13122 // now dead. 13123 return SDValue(N, 0); 13124 } 13125 13126 return SDValue(); 13127 } 13128 13129 static bool isValidMVECond(unsigned CC, bool IsFloat) { 13130 switch (CC) { 13131 case ARMCC::EQ: 13132 case ARMCC::NE: 13133 case ARMCC::LE: 13134 case ARMCC::GT: 13135 case ARMCC::GE: 13136 case ARMCC::LT: 13137 return true; 13138 case ARMCC::HS: 13139 case ARMCC::HI: 13140 return !IsFloat; 13141 default: 13142 return false; 13143 }; 13144 } 13145 13146 static ARMCC::CondCodes getVCMPCondCode(SDValue N) { 13147 if (N->getOpcode() == ARMISD::VCMP) 13148 return (ARMCC::CondCodes)N->getConstantOperandVal(2); 13149 else if (N->getOpcode() == ARMISD::VCMPZ) 13150 return (ARMCC::CondCodes)N->getConstantOperandVal(1); 13151 else 13152 llvm_unreachable("Not a VCMP/VCMPZ!"); 13153 } 13154 13155 static bool CanInvertMVEVCMP(SDValue N) { 13156 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N)); 13157 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint()); 13158 } 13159 13160 static SDValue PerformORCombine_i1(SDNode *N, 13161 TargetLowering::DAGCombinerInfo &DCI, 13162 const ARMSubtarget *Subtarget) { 13163 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 13164 // together with predicates 13165 EVT VT = N->getValueType(0); 13166 SDLoc DL(N); 13167 SDValue N0 = N->getOperand(0); 13168 SDValue N1 = N->getOperand(1); 13169 13170 auto IsFreelyInvertable = [&](SDValue V) { 13171 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ) 13172 return CanInvertMVEVCMP(V); 13173 return false; 13174 }; 13175 13176 // At least one operand must be freely invertable. 13177 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1))) 13178 return SDValue(); 13179 13180 SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT); 13181 SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT); 13182 SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1); 13183 return DCI.DAG.getLogicalNOT(DL, And, VT); 13184 } 13185 13186 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 13187 static SDValue PerformORCombine(SDNode *N, 13188 TargetLowering::DAGCombinerInfo &DCI, 13189 const ARMSubtarget *Subtarget) { 13190 // Attempt to use immediate-form VORR 13191 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 13192 SDLoc dl(N); 13193 EVT VT = N->getValueType(0); 13194 SelectionDAG &DAG = DCI.DAG; 13195 13196 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13197 return SDValue(); 13198 13199 if (Subtarget->hasMVEIntegerOps() && 13200 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 13201 return PerformORCombine_i1(N, DCI, Subtarget); 13202 13203 APInt SplatBits, SplatUndef; 13204 unsigned SplatBitSize; 13205 bool HasAnyUndefs; 13206 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 13207 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 13208 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 || 13209 SplatBitSize == 64) { 13210 EVT VorrVT; 13211 SDValue Val = 13212 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 13213 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm); 13214 if (Val.getNode()) { 13215 SDValue Input = 13216 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 13217 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 13218 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 13219 } 13220 } 13221 } 13222 13223 if (!Subtarget->isThumb1Only()) { 13224 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 13225 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 13226 return Result; 13227 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 13228 return Result; 13229 } 13230 13231 SDValue N0 = N->getOperand(0); 13232 SDValue N1 = N->getOperand(1); 13233 13234 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 13235 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 13236 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 13237 13238 // The code below optimizes (or (and X, Y), Z). 13239 // The AND operand needs to have a single user to make these optimizations 13240 // profitable. 13241 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 13242 return SDValue(); 13243 13244 APInt SplatUndef; 13245 unsigned SplatBitSize; 13246 bool HasAnyUndefs; 13247 13248 APInt SplatBits0, SplatBits1; 13249 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 13250 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 13251 // Ensure that the second operand of both ands are constants 13252 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 13253 HasAnyUndefs) && !HasAnyUndefs) { 13254 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 13255 HasAnyUndefs) && !HasAnyUndefs) { 13256 // Ensure that the bit width of the constants are the same and that 13257 // the splat arguments are logical inverses as per the pattern we 13258 // are trying to simplify. 13259 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 13260 SplatBits0 == ~SplatBits1) { 13261 // Canonicalize the vector type to make instruction selection 13262 // simpler. 13263 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 13264 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT, 13265 N0->getOperand(1), 13266 N0->getOperand(0), 13267 N1->getOperand(0)); 13268 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 13269 } 13270 } 13271 } 13272 } 13273 13274 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 13275 // reasonable. 13276 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 13277 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 13278 return Res; 13279 } 13280 13281 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13282 return Result; 13283 13284 return SDValue(); 13285 } 13286 13287 static SDValue PerformXORCombine(SDNode *N, 13288 TargetLowering::DAGCombinerInfo &DCI, 13289 const ARMSubtarget *Subtarget) { 13290 EVT VT = N->getValueType(0); 13291 SelectionDAG &DAG = DCI.DAG; 13292 13293 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13294 return SDValue(); 13295 13296 if (!Subtarget->isThumb1Only()) { 13297 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 13298 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 13299 return Result; 13300 13301 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13302 return Result; 13303 } 13304 13305 if (Subtarget->hasMVEIntegerOps()) { 13306 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition. 13307 SDValue N0 = N->getOperand(0); 13308 SDValue N1 = N->getOperand(1); 13309 const TargetLowering *TLI = Subtarget->getTargetLowering(); 13310 if (TLI->isConstTrueVal(N1.getNode()) && 13311 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) { 13312 if (CanInvertMVEVCMP(N0)) { 13313 SDLoc DL(N0); 13314 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0)); 13315 13316 SmallVector<SDValue, 4> Ops; 13317 Ops.push_back(N0->getOperand(0)); 13318 if (N0->getOpcode() == ARMISD::VCMP) 13319 Ops.push_back(N0->getOperand(1)); 13320 Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32)); 13321 return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops); 13322 } 13323 } 13324 } 13325 13326 return SDValue(); 13327 } 13328 13329 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 13330 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 13331 // their position in "to" (Rd). 13332 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 13333 assert(N->getOpcode() == ARMISD::BFI); 13334 13335 SDValue From = N->getOperand(1); 13336 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 13337 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 13338 13339 // If the Base came from a SHR #C, we can deduce that it is really testing bit 13340 // #C in the base of the SHR. 13341 if (From->getOpcode() == ISD::SRL && 13342 isa<ConstantSDNode>(From->getOperand(1))) { 13343 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 13344 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 13345 FromMask <<= Shift.getLimitedValue(31); 13346 From = From->getOperand(0); 13347 } 13348 13349 return From; 13350 } 13351 13352 // If A and B contain one contiguous set of bits, does A | B == A . B? 13353 // 13354 // Neither A nor B must be zero. 13355 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 13356 unsigned LastActiveBitInA = A.countTrailingZeros(); 13357 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 13358 return LastActiveBitInA - 1 == FirstActiveBitInB; 13359 } 13360 13361 static SDValue FindBFIToCombineWith(SDNode *N) { 13362 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 13363 // if one exists. 13364 APInt ToMask, FromMask; 13365 SDValue From = ParseBFI(N, ToMask, FromMask); 13366 SDValue To = N->getOperand(0); 13367 13368 // Now check for a compatible BFI to merge with. We can pass through BFIs that 13369 // aren't compatible, but not if they set the same bit in their destination as 13370 // we do (or that of any BFI we're going to combine with). 13371 SDValue V = To; 13372 APInt CombinedToMask = ToMask; 13373 while (V.getOpcode() == ARMISD::BFI) { 13374 APInt NewToMask, NewFromMask; 13375 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 13376 if (NewFrom != From) { 13377 // This BFI has a different base. Keep going. 13378 CombinedToMask |= NewToMask; 13379 V = V.getOperand(0); 13380 continue; 13381 } 13382 13383 // Do the written bits conflict with any we've seen so far? 13384 if ((NewToMask & CombinedToMask).getBoolValue()) 13385 // Conflicting bits - bail out because going further is unsafe. 13386 return SDValue(); 13387 13388 // Are the new bits contiguous when combined with the old bits? 13389 if (BitsProperlyConcatenate(ToMask, NewToMask) && 13390 BitsProperlyConcatenate(FromMask, NewFromMask)) 13391 return V; 13392 if (BitsProperlyConcatenate(NewToMask, ToMask) && 13393 BitsProperlyConcatenate(NewFromMask, FromMask)) 13394 return V; 13395 13396 // We've seen a write to some bits, so track it. 13397 CombinedToMask |= NewToMask; 13398 // Keep going... 13399 V = V.getOperand(0); 13400 } 13401 13402 return SDValue(); 13403 } 13404 13405 static SDValue PerformBFICombine(SDNode *N, 13406 TargetLowering::DAGCombinerInfo &DCI) { 13407 SDValue N1 = N->getOperand(1); 13408 if (N1.getOpcode() == ISD::AND) { 13409 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 13410 // the bits being cleared by the AND are not demanded by the BFI. 13411 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 13412 if (!N11C) 13413 return SDValue(); 13414 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 13415 unsigned LSB = countTrailingZeros(~InvMask); 13416 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 13417 assert(Width < 13418 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 13419 "undefined behavior"); 13420 unsigned Mask = (1u << Width) - 1; 13421 unsigned Mask2 = N11C->getZExtValue(); 13422 if ((Mask & (~Mask2)) == 0) 13423 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 13424 N->getOperand(0), N1.getOperand(0), 13425 N->getOperand(2)); 13426 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 13427 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 13428 // Keep track of any consecutive bits set that all come from the same base 13429 // value. We can combine these together into a single BFI. 13430 SDValue CombineBFI = FindBFIToCombineWith(N); 13431 if (CombineBFI == SDValue()) 13432 return SDValue(); 13433 13434 // We've found a BFI. 13435 APInt ToMask1, FromMask1; 13436 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 13437 13438 APInt ToMask2, FromMask2; 13439 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 13440 assert(From1 == From2); 13441 (void)From2; 13442 13443 // First, unlink CombineBFI. 13444 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 13445 // Then create a new BFI, combining the two together. 13446 APInt NewFromMask = FromMask1 | FromMask2; 13447 APInt NewToMask = ToMask1 | ToMask2; 13448 13449 EVT VT = N->getValueType(0); 13450 SDLoc dl(N); 13451 13452 if (NewFromMask[0] == 0) 13453 From1 = DCI.DAG.getNode( 13454 ISD::SRL, dl, VT, From1, 13455 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 13456 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 13457 DCI.DAG.getConstant(~NewToMask, dl, VT)); 13458 } 13459 return SDValue(); 13460 } 13461 13462 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 13463 /// ARMISD::VMOVRRD. 13464 static SDValue PerformVMOVRRDCombine(SDNode *N, 13465 TargetLowering::DAGCombinerInfo &DCI, 13466 const ARMSubtarget *Subtarget) { 13467 // vmovrrd(vmovdrr x, y) -> x,y 13468 SDValue InDouble = N->getOperand(0); 13469 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 13470 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 13471 13472 // vmovrrd(load f64) -> (load i32), (load i32) 13473 SDNode *InNode = InDouble.getNode(); 13474 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 13475 InNode->getValueType(0) == MVT::f64 && 13476 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 13477 !cast<LoadSDNode>(InNode)->isVolatile()) { 13478 // TODO: Should this be done for non-FrameIndex operands? 13479 LoadSDNode *LD = cast<LoadSDNode>(InNode); 13480 13481 SelectionDAG &DAG = DCI.DAG; 13482 SDLoc DL(LD); 13483 SDValue BasePtr = LD->getBasePtr(); 13484 SDValue NewLD1 = 13485 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 13486 LD->getAlignment(), LD->getMemOperand()->getFlags()); 13487 13488 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 13489 DAG.getConstant(4, DL, MVT::i32)); 13490 13491 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 13492 LD->getPointerInfo().getWithOffset(4), 13493 std::min(4U, LD->getAlignment()), 13494 LD->getMemOperand()->getFlags()); 13495 13496 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 13497 if (DCI.DAG.getDataLayout().isBigEndian()) 13498 std::swap (NewLD1, NewLD2); 13499 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 13500 return Result; 13501 } 13502 13503 return SDValue(); 13504 } 13505 13506 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 13507 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 13508 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 13509 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 13510 SDValue Op0 = N->getOperand(0); 13511 SDValue Op1 = N->getOperand(1); 13512 if (Op0.getOpcode() == ISD::BITCAST) 13513 Op0 = Op0.getOperand(0); 13514 if (Op1.getOpcode() == ISD::BITCAST) 13515 Op1 = Op1.getOperand(0); 13516 if (Op0.getOpcode() == ARMISD::VMOVRRD && 13517 Op0.getNode() == Op1.getNode() && 13518 Op0.getResNo() == 0 && Op1.getResNo() == 1) 13519 return DAG.getNode(ISD::BITCAST, SDLoc(N), 13520 N->getValueType(0), Op0.getOperand(0)); 13521 return SDValue(); 13522 } 13523 13524 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13525 SDValue Op0 = N->getOperand(0); 13526 13527 // VMOVhr (VMOVrh (X)) -> X 13528 if (Op0->getOpcode() == ARMISD::VMOVrh) 13529 return Op0->getOperand(0); 13530 13531 // FullFP16: half values are passed in S-registers, and we don't 13532 // need any of the bitcast and moves: 13533 // 13534 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 13535 // t5: i32 = bitcast t2 13536 // t18: f16 = ARMISD::VMOVhr t5 13537 if (Op0->getOpcode() == ISD::BITCAST) { 13538 SDValue Copy = Op0->getOperand(0); 13539 if (Copy.getValueType() == MVT::f32 && 13540 Copy->getOpcode() == ISD::CopyFromReg) { 13541 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)}; 13542 SDValue NewCopy = 13543 DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops); 13544 return NewCopy; 13545 } 13546 } 13547 13548 // fold (VMOVhr (load x)) -> (load (f16*)x) 13549 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) { 13550 if (LN0->hasOneUse() && LN0->isUnindexed() && 13551 LN0->getMemoryVT() == MVT::i16) { 13552 SDValue Load = 13553 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(), 13554 LN0->getBasePtr(), LN0->getMemOperand()); 13555 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13556 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1)); 13557 return Load; 13558 } 13559 } 13560 13561 // Only the bottom 16 bits of the source register are used. 13562 APInt DemandedMask = APInt::getLowBitsSet(32, 16); 13563 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 13564 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI)) 13565 return SDValue(N, 0); 13566 13567 return SDValue(); 13568 } 13569 13570 static SDValue PerformVMOVrhCombine(SDNode *N, 13571 TargetLowering::DAGCombinerInfo &DCI) { 13572 SDValue N0 = N->getOperand(0); 13573 EVT VT = N->getValueType(0); 13574 13575 // fold (VMOVrh (fpconst x)) -> const x 13576 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) { 13577 APFloat V = C->getValueAPF(); 13578 return DCI.DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT); 13579 } 13580 13581 // fold (VMOVrh (load x)) -> (zextload (i16*)x) 13582 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) { 13583 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 13584 13585 SDValue Load = 13586 DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(), 13587 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand()); 13588 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13589 DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 13590 return Load; 13591 } 13592 13593 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n) 13594 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 13595 isa<ConstantSDNode>(N0->getOperand(1))) 13596 return DCI.DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0), 13597 N0->getOperand(1)); 13598 13599 return SDValue(); 13600 } 13601 13602 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 13603 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 13604 /// i64 vector to have f64 elements, since the value can then be loaded 13605 /// directly into a VFP register. 13606 static bool hasNormalLoadOperand(SDNode *N) { 13607 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 13608 for (unsigned i = 0; i < NumElts; ++i) { 13609 SDNode *Elt = N->getOperand(i).getNode(); 13610 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 13611 return true; 13612 } 13613 return false; 13614 } 13615 13616 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 13617 /// ISD::BUILD_VECTOR. 13618 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 13619 TargetLowering::DAGCombinerInfo &DCI, 13620 const ARMSubtarget *Subtarget) { 13621 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 13622 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 13623 // into a pair of GPRs, which is fine when the value is used as a scalar, 13624 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 13625 SelectionDAG &DAG = DCI.DAG; 13626 if (N->getNumOperands() == 2) 13627 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 13628 return RV; 13629 13630 // Load i64 elements as f64 values so that type legalization does not split 13631 // them up into i32 values. 13632 EVT VT = N->getValueType(0); 13633 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 13634 return SDValue(); 13635 SDLoc dl(N); 13636 SmallVector<SDValue, 8> Ops; 13637 unsigned NumElts = VT.getVectorNumElements(); 13638 for (unsigned i = 0; i < NumElts; ++i) { 13639 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 13640 Ops.push_back(V); 13641 // Make the DAGCombiner fold the bitcast. 13642 DCI.AddToWorklist(V.getNode()); 13643 } 13644 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 13645 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 13646 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 13647 } 13648 13649 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 13650 static SDValue 13651 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13652 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 13653 // At that time, we may have inserted bitcasts from integer to float. 13654 // If these bitcasts have survived DAGCombine, change the lowering of this 13655 // BUILD_VECTOR in something more vector friendly, i.e., that does not 13656 // force to use floating point types. 13657 13658 // Make sure we can change the type of the vector. 13659 // This is possible iff: 13660 // 1. The vector is only used in a bitcast to a integer type. I.e., 13661 // 1.1. Vector is used only once. 13662 // 1.2. Use is a bit convert to an integer type. 13663 // 2. The size of its operands are 32-bits (64-bits are not legal). 13664 EVT VT = N->getValueType(0); 13665 EVT EltVT = VT.getVectorElementType(); 13666 13667 // Check 1.1. and 2. 13668 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 13669 return SDValue(); 13670 13671 // By construction, the input type must be float. 13672 assert(EltVT == MVT::f32 && "Unexpected type!"); 13673 13674 // Check 1.2. 13675 SDNode *Use = *N->use_begin(); 13676 if (Use->getOpcode() != ISD::BITCAST || 13677 Use->getValueType(0).isFloatingPoint()) 13678 return SDValue(); 13679 13680 // Check profitability. 13681 // Model is, if more than half of the relevant operands are bitcast from 13682 // i32, turn the build_vector into a sequence of insert_vector_elt. 13683 // Relevant operands are everything that is not statically 13684 // (i.e., at compile time) bitcasted. 13685 unsigned NumOfBitCastedElts = 0; 13686 unsigned NumElts = VT.getVectorNumElements(); 13687 unsigned NumOfRelevantElts = NumElts; 13688 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 13689 SDValue Elt = N->getOperand(Idx); 13690 if (Elt->getOpcode() == ISD::BITCAST) { 13691 // Assume only bit cast to i32 will go away. 13692 if (Elt->getOperand(0).getValueType() == MVT::i32) 13693 ++NumOfBitCastedElts; 13694 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 13695 // Constants are statically casted, thus do not count them as 13696 // relevant operands. 13697 --NumOfRelevantElts; 13698 } 13699 13700 // Check if more than half of the elements require a non-free bitcast. 13701 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 13702 return SDValue(); 13703 13704 SelectionDAG &DAG = DCI.DAG; 13705 // Create the new vector type. 13706 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 13707 // Check if the type is legal. 13708 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13709 if (!TLI.isTypeLegal(VecVT)) 13710 return SDValue(); 13711 13712 // Combine: 13713 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 13714 // => BITCAST INSERT_VECTOR_ELT 13715 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 13716 // (BITCAST EN), N. 13717 SDValue Vec = DAG.getUNDEF(VecVT); 13718 SDLoc dl(N); 13719 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 13720 SDValue V = N->getOperand(Idx); 13721 if (V.isUndef()) 13722 continue; 13723 if (V.getOpcode() == ISD::BITCAST && 13724 V->getOperand(0).getValueType() == MVT::i32) 13725 // Fold obvious case. 13726 V = V.getOperand(0); 13727 else { 13728 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 13729 // Make the DAGCombiner fold the bitcasts. 13730 DCI.AddToWorklist(V.getNode()); 13731 } 13732 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 13733 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 13734 } 13735 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 13736 // Make the DAGCombiner fold the bitcasts. 13737 DCI.AddToWorklist(Vec.getNode()); 13738 return Vec; 13739 } 13740 13741 static SDValue 13742 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13743 EVT VT = N->getValueType(0); 13744 SDValue Op = N->getOperand(0); 13745 SDLoc dl(N); 13746 13747 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x) 13748 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) { 13749 // If the valuetypes are the same, we can remove the cast entirely. 13750 if (Op->getOperand(0).getValueType() == VT) 13751 return Op->getOperand(0); 13752 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0)); 13753 } 13754 13755 return SDValue(); 13756 } 13757 13758 static SDValue 13759 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 13760 const ARMSubtarget *ST) { 13761 EVT VT = N->getValueType(0); 13762 SDValue Op = N->getOperand(0); 13763 SDLoc dl(N); 13764 13765 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST 13766 if (ST->isLittle()) 13767 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op); 13768 13769 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x) 13770 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) { 13771 // If the valuetypes are the same, we can remove the cast entirely. 13772 if (Op->getOperand(0).getValueType() == VT) 13773 return Op->getOperand(0); 13774 return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0)); 13775 } 13776 13777 return SDValue(); 13778 } 13779 13780 static SDValue PerformVCMPCombine(SDNode *N, 13781 TargetLowering::DAGCombinerInfo &DCI, 13782 const ARMSubtarget *Subtarget) { 13783 if (!Subtarget->hasMVEIntegerOps()) 13784 return SDValue(); 13785 13786 EVT VT = N->getValueType(0); 13787 SDValue Op0 = N->getOperand(0); 13788 SDValue Op1 = N->getOperand(1); 13789 ARMCC::CondCodes Cond = 13790 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 13791 SDLoc dl(N); 13792 13793 // vcmp X, 0, cc -> vcmpz X, cc 13794 if (isZeroVector(Op1)) 13795 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, 13796 N->getOperand(2)); 13797 13798 unsigned SwappedCond = getSwappedCondition(Cond); 13799 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) { 13800 // vcmp 0, X, cc -> vcmpz X, reversed(cc) 13801 if (isZeroVector(Op0)) 13802 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1, 13803 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13804 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc) 13805 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP) 13806 return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0, 13807 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13808 } 13809 13810 return SDValue(); 13811 } 13812 13813 /// PerformInsertEltCombine - Target-specific dag combine xforms for 13814 /// ISD::INSERT_VECTOR_ELT. 13815 static SDValue PerformInsertEltCombine(SDNode *N, 13816 TargetLowering::DAGCombinerInfo &DCI) { 13817 // Bitcast an i64 load inserted into a vector to f64. 13818 // Otherwise, the i64 value will be legalized to a pair of i32 values. 13819 EVT VT = N->getValueType(0); 13820 SDNode *Elt = N->getOperand(1).getNode(); 13821 if (VT.getVectorElementType() != MVT::i64 || 13822 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 13823 return SDValue(); 13824 13825 SelectionDAG &DAG = DCI.DAG; 13826 SDLoc dl(N); 13827 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 13828 VT.getVectorNumElements()); 13829 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 13830 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 13831 // Make the DAGCombiner fold the bitcasts. 13832 DCI.AddToWorklist(Vec.getNode()); 13833 DCI.AddToWorklist(V.getNode()); 13834 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 13835 Vec, V, N->getOperand(2)); 13836 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 13837 } 13838 13839 static SDValue PerformExtractEltCombine(SDNode *N, 13840 TargetLowering::DAGCombinerInfo &DCI) { 13841 SDValue Op0 = N->getOperand(0); 13842 EVT VT = N->getValueType(0); 13843 SDLoc dl(N); 13844 13845 // extract (vdup x) -> x 13846 if (Op0->getOpcode() == ARMISD::VDUP) { 13847 SDValue X = Op0->getOperand(0); 13848 if (VT == MVT::f16 && X.getValueType() == MVT::i32) 13849 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X); 13850 if (VT == MVT::i32 && X.getValueType() == MVT::f16) 13851 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X); 13852 13853 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST) 13854 X = X->getOperand(0); 13855 if (X.getValueType() == VT) 13856 return X; 13857 } 13858 13859 return SDValue(); 13860 } 13861 13862 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 13863 /// ISD::VECTOR_SHUFFLE. 13864 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 13865 // The LLVM shufflevector instruction does not require the shuffle mask 13866 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 13867 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 13868 // operands do not match the mask length, they are extended by concatenating 13869 // them with undef vectors. That is probably the right thing for other 13870 // targets, but for NEON it is better to concatenate two double-register 13871 // size vector operands into a single quad-register size vector. Do that 13872 // transformation here: 13873 // shuffle(concat(v1, undef), concat(v2, undef)) -> 13874 // shuffle(concat(v1, v2), undef) 13875 SDValue Op0 = N->getOperand(0); 13876 SDValue Op1 = N->getOperand(1); 13877 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 13878 Op1.getOpcode() != ISD::CONCAT_VECTORS || 13879 Op0.getNumOperands() != 2 || 13880 Op1.getNumOperands() != 2) 13881 return SDValue(); 13882 SDValue Concat0Op1 = Op0.getOperand(1); 13883 SDValue Concat1Op1 = Op1.getOperand(1); 13884 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 13885 return SDValue(); 13886 // Skip the transformation if any of the types are illegal. 13887 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13888 EVT VT = N->getValueType(0); 13889 if (!TLI.isTypeLegal(VT) || 13890 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 13891 !TLI.isTypeLegal(Concat1Op1.getValueType())) 13892 return SDValue(); 13893 13894 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13895 Op0.getOperand(0), Op1.getOperand(0)); 13896 // Translate the shuffle mask. 13897 SmallVector<int, 16> NewMask; 13898 unsigned NumElts = VT.getVectorNumElements(); 13899 unsigned HalfElts = NumElts/2; 13900 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13901 for (unsigned n = 0; n < NumElts; ++n) { 13902 int MaskElt = SVN->getMaskElt(n); 13903 int NewElt = -1; 13904 if (MaskElt < (int)HalfElts) 13905 NewElt = MaskElt; 13906 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 13907 NewElt = HalfElts + MaskElt - NumElts; 13908 NewMask.push_back(NewElt); 13909 } 13910 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 13911 DAG.getUNDEF(VT), NewMask); 13912 } 13913 13914 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 13915 /// NEON load/store intrinsics, and generic vector load/stores, to merge 13916 /// base address updates. 13917 /// For generic load/stores, the memory type is assumed to be a vector. 13918 /// The caller is assumed to have checked legality. 13919 static SDValue CombineBaseUpdate(SDNode *N, 13920 TargetLowering::DAGCombinerInfo &DCI) { 13921 SelectionDAG &DAG = DCI.DAG; 13922 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 13923 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 13924 const bool isStore = N->getOpcode() == ISD::STORE; 13925 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 13926 SDValue Addr = N->getOperand(AddrOpIdx); 13927 MemSDNode *MemN = cast<MemSDNode>(N); 13928 SDLoc dl(N); 13929 13930 // Search for a use of the address operand that is an increment. 13931 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 13932 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 13933 SDNode *User = *UI; 13934 if (User->getOpcode() != ISD::ADD || 13935 UI.getUse().getResNo() != Addr.getResNo()) 13936 continue; 13937 13938 // Check that the add is independent of the load/store. Otherwise, folding 13939 // it would create a cycle. We can avoid searching through Addr as it's a 13940 // predecessor to both. 13941 SmallPtrSet<const SDNode *, 32> Visited; 13942 SmallVector<const SDNode *, 16> Worklist; 13943 Visited.insert(Addr.getNode()); 13944 Worklist.push_back(N); 13945 Worklist.push_back(User); 13946 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 13947 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 13948 continue; 13949 13950 // Find the new opcode for the updating load/store. 13951 bool isLoadOp = true; 13952 bool isLaneOp = false; 13953 unsigned NewOpc = 0; 13954 unsigned NumVecs = 0; 13955 if (isIntrinsic) { 13956 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 13957 switch (IntNo) { 13958 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 13959 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 13960 NumVecs = 1; break; 13961 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 13962 NumVecs = 2; break; 13963 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 13964 NumVecs = 3; break; 13965 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 13966 NumVecs = 4; break; 13967 case Intrinsic::arm_neon_vld1x2: 13968 case Intrinsic::arm_neon_vld1x3: 13969 case Intrinsic::arm_neon_vld1x4: 13970 case Intrinsic::arm_neon_vld2dup: 13971 case Intrinsic::arm_neon_vld3dup: 13972 case Intrinsic::arm_neon_vld4dup: 13973 // TODO: Support updating VLD1x and VLDxDUP nodes. For now, we just skip 13974 // combining base updates for such intrinsics. 13975 continue; 13976 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 13977 NumVecs = 2; isLaneOp = true; break; 13978 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 13979 NumVecs = 3; isLaneOp = true; break; 13980 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 13981 NumVecs = 4; isLaneOp = true; break; 13982 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 13983 NumVecs = 1; isLoadOp = false; break; 13984 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 13985 NumVecs = 2; isLoadOp = false; break; 13986 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 13987 NumVecs = 3; isLoadOp = false; break; 13988 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 13989 NumVecs = 4; isLoadOp = false; break; 13990 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 13991 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 13992 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 13993 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 13994 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 13995 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 13996 } 13997 } else { 13998 isLaneOp = true; 13999 switch (N->getOpcode()) { 14000 default: llvm_unreachable("unexpected opcode for Neon base update"); 14001 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 14002 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 14003 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 14004 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 14005 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 14006 NumVecs = 1; isLaneOp = false; break; 14007 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 14008 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 14009 } 14010 } 14011 14012 // Find the size of memory referenced by the load/store. 14013 EVT VecTy; 14014 if (isLoadOp) { 14015 VecTy = N->getValueType(0); 14016 } else if (isIntrinsic) { 14017 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 14018 } else { 14019 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 14020 VecTy = N->getOperand(1).getValueType(); 14021 } 14022 14023 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14024 if (isLaneOp) 14025 NumBytes /= VecTy.getVectorNumElements(); 14026 14027 // If the increment is a constant, it must match the memory ref size. 14028 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14029 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 14030 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 14031 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 14032 // separate instructions that make it harder to use a non-constant update. 14033 continue; 14034 } 14035 14036 // OK, we found an ADD we can fold into the base update. 14037 // Now, create a _UPD node, taking care of not breaking alignment. 14038 14039 EVT AlignedVecTy = VecTy; 14040 unsigned Alignment = MemN->getAlignment(); 14041 14042 // If this is a less-than-standard-aligned load/store, change the type to 14043 // match the standard alignment. 14044 // The alignment is overlooked when selecting _UPD variants; and it's 14045 // easier to introduce bitcasts here than fix that. 14046 // There are 3 ways to get to this base-update combine: 14047 // - intrinsics: they are assumed to be properly aligned (to the standard 14048 // alignment of the memory type), so we don't need to do anything. 14049 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 14050 // intrinsics, so, likewise, there's nothing to do. 14051 // - generic load/store instructions: the alignment is specified as an 14052 // explicit operand, rather than implicitly as the standard alignment 14053 // of the memory type (like the intrisics). We need to change the 14054 // memory type to match the explicit alignment. That way, we don't 14055 // generate non-standard-aligned ARMISD::VLDx nodes. 14056 if (isa<LSBaseSDNode>(N)) { 14057 if (Alignment == 0) 14058 Alignment = 1; 14059 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 14060 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 14061 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 14062 assert(!isLaneOp && "Unexpected generic load/store lane."); 14063 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 14064 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 14065 } 14066 // Don't set an explicit alignment on regular load/stores that we want 14067 // to transform to VLD/VST 1_UPD nodes. 14068 // This matches the behavior of regular load/stores, which only get an 14069 // explicit alignment if the MMO alignment is larger than the standard 14070 // alignment of the memory type. 14071 // Intrinsics, however, always get an explicit alignment, set to the 14072 // alignment of the MMO. 14073 Alignment = 1; 14074 } 14075 14076 // Create the new updating load/store node. 14077 // First, create an SDVTList for the new updating node's results. 14078 EVT Tys[6]; 14079 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 14080 unsigned n; 14081 for (n = 0; n < NumResultVecs; ++n) 14082 Tys[n] = AlignedVecTy; 14083 Tys[n++] = MVT::i32; 14084 Tys[n] = MVT::Other; 14085 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 14086 14087 // Then, gather the new node's operands. 14088 SmallVector<SDValue, 8> Ops; 14089 Ops.push_back(N->getOperand(0)); // incoming chain 14090 Ops.push_back(N->getOperand(AddrOpIdx)); 14091 Ops.push_back(Inc); 14092 14093 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 14094 // Try to match the intrinsic's signature 14095 Ops.push_back(StN->getValue()); 14096 } else { 14097 // Loads (and of course intrinsics) match the intrinsics' signature, 14098 // so just add all but the alignment operand. 14099 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 14100 Ops.push_back(N->getOperand(i)); 14101 } 14102 14103 // For all node types, the alignment operand is always the last one. 14104 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 14105 14106 // If this is a non-standard-aligned STORE, the penultimate operand is the 14107 // stored value. Bitcast it to the aligned type. 14108 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 14109 SDValue &StVal = Ops[Ops.size()-2]; 14110 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 14111 } 14112 14113 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 14114 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 14115 MemN->getMemOperand()); 14116 14117 // Update the uses. 14118 SmallVector<SDValue, 5> NewResults; 14119 for (unsigned i = 0; i < NumResultVecs; ++i) 14120 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14121 14122 // If this is an non-standard-aligned LOAD, the first result is the loaded 14123 // value. Bitcast it to the expected result type. 14124 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 14125 SDValue &LdVal = NewResults[0]; 14126 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 14127 } 14128 14129 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 14130 DCI.CombineTo(N, NewResults); 14131 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14132 14133 break; 14134 } 14135 return SDValue(); 14136 } 14137 14138 static SDValue PerformVLDCombine(SDNode *N, 14139 TargetLowering::DAGCombinerInfo &DCI) { 14140 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14141 return SDValue(); 14142 14143 return CombineBaseUpdate(N, DCI); 14144 } 14145 14146 static SDValue PerformMVEVLDCombine(SDNode *N, 14147 TargetLowering::DAGCombinerInfo &DCI) { 14148 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14149 return SDValue(); 14150 14151 SelectionDAG &DAG = DCI.DAG; 14152 SDValue Addr = N->getOperand(2); 14153 MemSDNode *MemN = cast<MemSDNode>(N); 14154 SDLoc dl(N); 14155 14156 // For the stores, where there are multiple intrinsics we only actually want 14157 // to post-inc the last of the them. 14158 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 14159 if (IntNo == Intrinsic::arm_mve_vst2q && 14160 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1) 14161 return SDValue(); 14162 if (IntNo == Intrinsic::arm_mve_vst4q && 14163 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3) 14164 return SDValue(); 14165 14166 // Search for a use of the address operand that is an increment. 14167 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 14168 UE = Addr.getNode()->use_end(); 14169 UI != UE; ++UI) { 14170 SDNode *User = *UI; 14171 if (User->getOpcode() != ISD::ADD || 14172 UI.getUse().getResNo() != Addr.getResNo()) 14173 continue; 14174 14175 // Check that the add is independent of the load/store. Otherwise, folding 14176 // it would create a cycle. We can avoid searching through Addr as it's a 14177 // predecessor to both. 14178 SmallPtrSet<const SDNode *, 32> Visited; 14179 SmallVector<const SDNode *, 16> Worklist; 14180 Visited.insert(Addr.getNode()); 14181 Worklist.push_back(N); 14182 Worklist.push_back(User); 14183 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 14184 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14185 continue; 14186 14187 // Find the new opcode for the updating load/store. 14188 bool isLoadOp = true; 14189 unsigned NewOpc = 0; 14190 unsigned NumVecs = 0; 14191 switch (IntNo) { 14192 default: 14193 llvm_unreachable("unexpected intrinsic for MVE VLDn combine"); 14194 case Intrinsic::arm_mve_vld2q: 14195 NewOpc = ARMISD::VLD2_UPD; 14196 NumVecs = 2; 14197 break; 14198 case Intrinsic::arm_mve_vld4q: 14199 NewOpc = ARMISD::VLD4_UPD; 14200 NumVecs = 4; 14201 break; 14202 case Intrinsic::arm_mve_vst2q: 14203 NewOpc = ARMISD::VST2_UPD; 14204 NumVecs = 2; 14205 isLoadOp = false; 14206 break; 14207 case Intrinsic::arm_mve_vst4q: 14208 NewOpc = ARMISD::VST4_UPD; 14209 NumVecs = 4; 14210 isLoadOp = false; 14211 break; 14212 } 14213 14214 // Find the size of memory referenced by the load/store. 14215 EVT VecTy; 14216 if (isLoadOp) { 14217 VecTy = N->getValueType(0); 14218 } else { 14219 VecTy = N->getOperand(3).getValueType(); 14220 } 14221 14222 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14223 14224 // If the increment is a constant, it must match the memory ref size. 14225 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14226 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 14227 if (!CInc || CInc->getZExtValue() != NumBytes) 14228 continue; 14229 14230 // Create the new updating load/store node. 14231 // First, create an SDVTList for the new updating node's results. 14232 EVT Tys[6]; 14233 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 14234 unsigned n; 14235 for (n = 0; n < NumResultVecs; ++n) 14236 Tys[n] = VecTy; 14237 Tys[n++] = MVT::i32; 14238 Tys[n] = MVT::Other; 14239 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 14240 14241 // Then, gather the new node's operands. 14242 SmallVector<SDValue, 8> Ops; 14243 Ops.push_back(N->getOperand(0)); // incoming chain 14244 Ops.push_back(N->getOperand(2)); // ptr 14245 Ops.push_back(Inc); 14246 14247 for (unsigned i = 3; i < N->getNumOperands(); ++i) 14248 Ops.push_back(N->getOperand(i)); 14249 14250 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy, 14251 MemN->getMemOperand()); 14252 14253 // Update the uses. 14254 SmallVector<SDValue, 5> NewResults; 14255 for (unsigned i = 0; i < NumResultVecs; ++i) 14256 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14257 14258 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain 14259 DCI.CombineTo(N, NewResults); 14260 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14261 14262 break; 14263 } 14264 14265 return SDValue(); 14266 } 14267 14268 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 14269 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 14270 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 14271 /// return true. 14272 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 14273 SelectionDAG &DAG = DCI.DAG; 14274 EVT VT = N->getValueType(0); 14275 // vldN-dup instructions only support 64-bit vectors for N > 1. 14276 if (!VT.is64BitVector()) 14277 return false; 14278 14279 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 14280 SDNode *VLD = N->getOperand(0).getNode(); 14281 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 14282 return false; 14283 unsigned NumVecs = 0; 14284 unsigned NewOpc = 0; 14285 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 14286 if (IntNo == Intrinsic::arm_neon_vld2lane) { 14287 NumVecs = 2; 14288 NewOpc = ARMISD::VLD2DUP; 14289 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 14290 NumVecs = 3; 14291 NewOpc = ARMISD::VLD3DUP; 14292 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 14293 NumVecs = 4; 14294 NewOpc = ARMISD::VLD4DUP; 14295 } else { 14296 return false; 14297 } 14298 14299 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 14300 // numbers match the load. 14301 unsigned VLDLaneNo = 14302 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 14303 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 14304 UI != UE; ++UI) { 14305 // Ignore uses of the chain result. 14306 if (UI.getUse().getResNo() == NumVecs) 14307 continue; 14308 SDNode *User = *UI; 14309 if (User->getOpcode() != ARMISD::VDUPLANE || 14310 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 14311 return false; 14312 } 14313 14314 // Create the vldN-dup node. 14315 EVT Tys[5]; 14316 unsigned n; 14317 for (n = 0; n < NumVecs; ++n) 14318 Tys[n] = VT; 14319 Tys[n] = MVT::Other; 14320 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 14321 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 14322 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 14323 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 14324 Ops, VLDMemInt->getMemoryVT(), 14325 VLDMemInt->getMemOperand()); 14326 14327 // Update the uses. 14328 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 14329 UI != UE; ++UI) { 14330 unsigned ResNo = UI.getUse().getResNo(); 14331 // Ignore uses of the chain result. 14332 if (ResNo == NumVecs) 14333 continue; 14334 SDNode *User = *UI; 14335 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 14336 } 14337 14338 // Now the vldN-lane intrinsic is dead except for its chain result. 14339 // Update uses of the chain. 14340 std::vector<SDValue> VLDDupResults; 14341 for (unsigned n = 0; n < NumVecs; ++n) 14342 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 14343 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 14344 DCI.CombineTo(VLD, VLDDupResults); 14345 14346 return true; 14347 } 14348 14349 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 14350 /// ARMISD::VDUPLANE. 14351 static SDValue PerformVDUPLANECombine(SDNode *N, 14352 TargetLowering::DAGCombinerInfo &DCI, 14353 const ARMSubtarget *Subtarget) { 14354 SDValue Op = N->getOperand(0); 14355 EVT VT = N->getValueType(0); 14356 14357 // On MVE, we just convert the VDUPLANE to a VDUP with an extract. 14358 if (Subtarget->hasMVEIntegerOps()) { 14359 EVT ExtractVT = VT.getVectorElementType(); 14360 // We need to ensure we are creating a legal type. 14361 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT)) 14362 ExtractVT = MVT::i32; 14363 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT, 14364 N->getOperand(0), N->getOperand(1)); 14365 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract); 14366 } 14367 14368 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 14369 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 14370 if (CombineVLDDUP(N, DCI)) 14371 return SDValue(N, 0); 14372 14373 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 14374 // redundant. Ignore bit_converts for now; element sizes are checked below. 14375 while (Op.getOpcode() == ISD::BITCAST) 14376 Op = Op.getOperand(0); 14377 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 14378 return SDValue(); 14379 14380 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 14381 unsigned EltSize = Op.getScalarValueSizeInBits(); 14382 // The canonical VMOV for a zero vector uses a 32-bit element size. 14383 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14384 unsigned EltBits; 14385 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 14386 EltSize = 8; 14387 if (EltSize > VT.getScalarSizeInBits()) 14388 return SDValue(); 14389 14390 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 14391 } 14392 14393 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 14394 static SDValue PerformVDUPCombine(SDNode *N, 14395 TargetLowering::DAGCombinerInfo &DCI, 14396 const ARMSubtarget *Subtarget) { 14397 SelectionDAG &DAG = DCI.DAG; 14398 SDValue Op = N->getOperand(0); 14399 SDLoc dl(N); 14400 14401 if (Subtarget->hasMVEIntegerOps()) { 14402 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will 14403 // need to come from a GPR. 14404 if (Op.getValueType() == MVT::f32) 14405 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 14406 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op)); 14407 else if (Op.getValueType() == MVT::f16) 14408 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 14409 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op)); 14410 } 14411 14412 if (!Subtarget->hasNEON()) 14413 return SDValue(); 14414 14415 // Match VDUP(LOAD) -> VLD1DUP. 14416 // We match this pattern here rather than waiting for isel because the 14417 // transform is only legal for unindexed loads. 14418 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 14419 if (LD && Op.hasOneUse() && LD->isUnindexed() && 14420 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 14421 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 14422 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 14423 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 14424 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 14425 Ops, LD->getMemoryVT(), 14426 LD->getMemOperand()); 14427 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 14428 return VLDDup; 14429 } 14430 14431 return SDValue(); 14432 } 14433 14434 static SDValue PerformLOADCombine(SDNode *N, 14435 TargetLowering::DAGCombinerInfo &DCI) { 14436 EVT VT = N->getValueType(0); 14437 14438 // If this is a legal vector load, try to combine it into a VLD1_UPD. 14439 if (ISD::isNormalLoad(N) && VT.isVector() && 14440 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 14441 return CombineBaseUpdate(N, DCI); 14442 14443 return SDValue(); 14444 } 14445 14446 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 14447 // pack all of the elements in one place. Next, store to memory in fewer 14448 // chunks. 14449 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St, 14450 SelectionDAG &DAG) { 14451 SDValue StVal = St->getValue(); 14452 EVT VT = StVal.getValueType(); 14453 if (!St->isTruncatingStore() || !VT.isVector()) 14454 return SDValue(); 14455 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14456 EVT StVT = St->getMemoryVT(); 14457 unsigned NumElems = VT.getVectorNumElements(); 14458 assert(StVT != VT && "Cannot truncate to the same type"); 14459 unsigned FromEltSz = VT.getScalarSizeInBits(); 14460 unsigned ToEltSz = StVT.getScalarSizeInBits(); 14461 14462 // From, To sizes and ElemCount must be pow of two 14463 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) 14464 return SDValue(); 14465 14466 // We are going to use the original vector elt for storing. 14467 // Accumulated smaller vector elements must be a multiple of the store size. 14468 if (0 != (NumElems * FromEltSz) % ToEltSz) 14469 return SDValue(); 14470 14471 unsigned SizeRatio = FromEltSz / ToEltSz; 14472 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 14473 14474 // Create a type on which we perform the shuffle. 14475 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 14476 NumElems * SizeRatio); 14477 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 14478 14479 SDLoc DL(St); 14480 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 14481 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14482 for (unsigned i = 0; i < NumElems; ++i) 14483 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1 14484 : i * SizeRatio; 14485 14486 // Can't shuffle using an illegal type. 14487 if (!TLI.isTypeLegal(WideVecVT)) 14488 return SDValue(); 14489 14490 SDValue Shuff = DAG.getVectorShuffle( 14491 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec); 14492 // At this point all of the data is stored at the bottom of the 14493 // register. We now need to save it to mem. 14494 14495 // Find the largest store unit 14496 MVT StoreType = MVT::i8; 14497 for (MVT Tp : MVT::integer_valuetypes()) { 14498 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 14499 StoreType = Tp; 14500 } 14501 // Didn't find a legal store type. 14502 if (!TLI.isTypeLegal(StoreType)) 14503 return SDValue(); 14504 14505 // Bitcast the original vector into a vector of store-size units 14506 EVT StoreVecVT = 14507 EVT::getVectorVT(*DAG.getContext(), StoreType, 14508 VT.getSizeInBits() / EVT(StoreType).getSizeInBits()); 14509 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 14510 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 14511 SmallVector<SDValue, 8> Chains; 14512 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 14513 TLI.getPointerTy(DAG.getDataLayout())); 14514 SDValue BasePtr = St->getBasePtr(); 14515 14516 // Perform one or more big stores into memory. 14517 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits(); 14518 for (unsigned I = 0; I < E; I++) { 14519 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType, 14520 ShuffWide, DAG.getIntPtrConstant(I, DL)); 14521 SDValue Ch = 14522 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(), 14523 St->getAlignment(), St->getMemOperand()->getFlags()); 14524 BasePtr = 14525 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment); 14526 Chains.push_back(Ch); 14527 } 14528 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 14529 } 14530 14531 // Try taking a single vector store from an truncate (which would otherwise turn 14532 // into an expensive buildvector) and splitting it into a series of narrowing 14533 // stores. 14534 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St, 14535 SelectionDAG &DAG) { 14536 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed()) 14537 return SDValue(); 14538 SDValue Trunc = St->getValue(); 14539 if (Trunc->getOpcode() != ISD::TRUNCATE && Trunc->getOpcode() != ISD::FP_ROUND) 14540 return SDValue(); 14541 EVT FromVT = Trunc->getOperand(0).getValueType(); 14542 EVT ToVT = Trunc.getValueType(); 14543 if (!ToVT.isVector()) 14544 return SDValue(); 14545 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 14546 EVT ToEltVT = ToVT.getVectorElementType(); 14547 EVT FromEltVT = FromVT.getVectorElementType(); 14548 14549 unsigned NumElements = 0; 14550 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8)) 14551 NumElements = 4; 14552 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8) 14553 NumElements = 8; 14554 if (FromEltVT == MVT::f32 && ToEltVT == MVT::f16) 14555 NumElements = 4; 14556 if (NumElements == 0 || 14557 (FromEltVT != MVT::f32 && FromVT.getVectorNumElements() == NumElements) || 14558 FromVT.getVectorNumElements() % NumElements != 0) 14559 return SDValue(); 14560 14561 // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so 14562 // use the VMOVN over splitting the store. We are looking for patterns of: 14563 // !rev: 0 N 1 N+1 2 N+2 ... 14564 // rev: N 0 N+1 1 N+2 2 ... 14565 auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) { 14566 unsigned NumElts = ToVT.getVectorNumElements(); 14567 if (NumElts != M.size()) 14568 return false; 14569 14570 unsigned Off0 = rev ? NumElts : 0; 14571 unsigned Off1 = rev ? 0 : NumElts; 14572 14573 for (unsigned i = 0; i < NumElts; i += 2) { 14574 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2)) 14575 return false; 14576 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2)) 14577 return false; 14578 } 14579 14580 return true; 14581 }; 14582 14583 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0))) 14584 if (isVMOVNOriginalMask(Shuffle->getMask(), false) || 14585 isVMOVNOriginalMask(Shuffle->getMask(), true)) 14586 return SDValue(); 14587 14588 LLVMContext &C = *DAG.getContext(); 14589 SDLoc DL(St); 14590 // Details about the old store 14591 SDValue Ch = St->getChain(); 14592 SDValue BasePtr = St->getBasePtr(); 14593 Align Alignment = St->getOriginalAlign(); 14594 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags(); 14595 AAMDNodes AAInfo = St->getAAInfo(); 14596 14597 // We split the store into slices of NumElements. fp16 trunc stores are vcvt 14598 // and then stored as truncating integer stores. 14599 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements); 14600 EVT NewToVT = EVT::getVectorVT( 14601 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements); 14602 14603 SmallVector<SDValue, 4> Stores; 14604 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 14605 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8; 14606 SDValue NewPtr = 14607 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset)); 14608 14609 SDValue Extract = 14610 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0), 14611 DAG.getConstant(i * NumElements, DL, MVT::i32)); 14612 14613 if (ToEltVT == MVT::f16) { 14614 SDValue FPTrunc = 14615 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16), 14616 Extract, DAG.getConstant(0, DL, MVT::i32)); 14617 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc); 14618 } 14619 14620 SDValue Store = DAG.getTruncStore( 14621 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset), 14622 NewToVT, Alignment.value(), MMOFlags, AAInfo); 14623 Stores.push_back(Store); 14624 } 14625 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores); 14626 } 14627 14628 /// PerformSTORECombine - Target-specific dag combine xforms for 14629 /// ISD::STORE. 14630 static SDValue PerformSTORECombine(SDNode *N, 14631 TargetLowering::DAGCombinerInfo &DCI, 14632 const ARMSubtarget *Subtarget) { 14633 StoreSDNode *St = cast<StoreSDNode>(N); 14634 if (St->isVolatile()) 14635 return SDValue(); 14636 SDValue StVal = St->getValue(); 14637 EVT VT = StVal.getValueType(); 14638 14639 if (Subtarget->hasNEON()) 14640 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG)) 14641 return Store; 14642 14643 if (Subtarget->hasMVEIntegerOps()) 14644 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG)) 14645 return NewToken; 14646 14647 if (!ISD::isNormalStore(St)) 14648 return SDValue(); 14649 14650 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 14651 // ARM stores of arguments in the same cache line. 14652 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 14653 StVal.getNode()->hasOneUse()) { 14654 SelectionDAG &DAG = DCI.DAG; 14655 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 14656 SDLoc DL(St); 14657 SDValue BasePtr = St->getBasePtr(); 14658 SDValue NewST1 = DAG.getStore( 14659 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 14660 BasePtr, St->getPointerInfo(), St->getOriginalAlign(), 14661 St->getMemOperand()->getFlags()); 14662 14663 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 14664 DAG.getConstant(4, DL, MVT::i32)); 14665 return DAG.getStore(NewST1.getValue(0), DL, 14666 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 14667 OffsetPtr, St->getPointerInfo().getWithOffset(4), 14668 St->getOriginalAlign(), 14669 St->getMemOperand()->getFlags()); 14670 } 14671 14672 if (StVal.getValueType() == MVT::i64 && 14673 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14674 14675 // Bitcast an i64 store extracted from a vector to f64. 14676 // Otherwise, the i64 value will be legalized to a pair of i32 values. 14677 SelectionDAG &DAG = DCI.DAG; 14678 SDLoc dl(StVal); 14679 SDValue IntVec = StVal.getOperand(0); 14680 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 14681 IntVec.getValueType().getVectorNumElements()); 14682 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 14683 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 14684 Vec, StVal.getOperand(1)); 14685 dl = SDLoc(N); 14686 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 14687 // Make the DAGCombiner fold the bitcasts. 14688 DCI.AddToWorklist(Vec.getNode()); 14689 DCI.AddToWorklist(ExtElt.getNode()); 14690 DCI.AddToWorklist(V.getNode()); 14691 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 14692 St->getPointerInfo(), St->getAlignment(), 14693 St->getMemOperand()->getFlags(), St->getAAInfo()); 14694 } 14695 14696 // If this is a legal vector store, try to combine it into a VST1_UPD. 14697 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() && 14698 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 14699 return CombineBaseUpdate(N, DCI); 14700 14701 return SDValue(); 14702 } 14703 14704 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 14705 /// can replace combinations of VMUL and VCVT (floating-point to integer) 14706 /// when the VMUL has a constant operand that is a power of 2. 14707 /// 14708 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 14709 /// vmul.f32 d16, d17, d16 14710 /// vcvt.s32.f32 d16, d16 14711 /// becomes: 14712 /// vcvt.s32.f32 d16, d16, #3 14713 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 14714 const ARMSubtarget *Subtarget) { 14715 if (!Subtarget->hasNEON()) 14716 return SDValue(); 14717 14718 SDValue Op = N->getOperand(0); 14719 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 14720 Op.getOpcode() != ISD::FMUL) 14721 return SDValue(); 14722 14723 SDValue ConstVec = Op->getOperand(1); 14724 if (!isa<BuildVectorSDNode>(ConstVec)) 14725 return SDValue(); 14726 14727 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 14728 uint32_t FloatBits = FloatTy.getSizeInBits(); 14729 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 14730 uint32_t IntBits = IntTy.getSizeInBits(); 14731 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 14732 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 14733 // These instructions only exist converting from f32 to i32. We can handle 14734 // smaller integers by generating an extra truncate, but larger ones would 14735 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 14736 // these intructions only support v2i32/v4i32 types. 14737 return SDValue(); 14738 } 14739 14740 BitVector UndefElements; 14741 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 14742 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 14743 if (C == -1 || C == 0 || C > 32) 14744 return SDValue(); 14745 14746 SDLoc dl(N); 14747 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 14748 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 14749 Intrinsic::arm_neon_vcvtfp2fxu; 14750 SDValue FixConv = DAG.getNode( 14751 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 14752 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 14753 DAG.getConstant(C, dl, MVT::i32)); 14754 14755 if (IntBits < FloatBits) 14756 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 14757 14758 return FixConv; 14759 } 14760 14761 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 14762 /// can replace combinations of VCVT (integer to floating-point) and VDIV 14763 /// when the VDIV has a constant operand that is a power of 2. 14764 /// 14765 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 14766 /// vcvt.f32.s32 d16, d16 14767 /// vdiv.f32 d16, d17, d16 14768 /// becomes: 14769 /// vcvt.f32.s32 d16, d16, #3 14770 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 14771 const ARMSubtarget *Subtarget) { 14772 if (!Subtarget->hasNEON()) 14773 return SDValue(); 14774 14775 SDValue Op = N->getOperand(0); 14776 unsigned OpOpcode = Op.getNode()->getOpcode(); 14777 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 14778 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 14779 return SDValue(); 14780 14781 SDValue ConstVec = N->getOperand(1); 14782 if (!isa<BuildVectorSDNode>(ConstVec)) 14783 return SDValue(); 14784 14785 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 14786 uint32_t FloatBits = FloatTy.getSizeInBits(); 14787 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 14788 uint32_t IntBits = IntTy.getSizeInBits(); 14789 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 14790 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 14791 // These instructions only exist converting from i32 to f32. We can handle 14792 // smaller integers by generating an extra extend, but larger ones would 14793 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 14794 // these intructions only support v2i32/v4i32 types. 14795 return SDValue(); 14796 } 14797 14798 BitVector UndefElements; 14799 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 14800 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 14801 if (C == -1 || C == 0 || C > 32) 14802 return SDValue(); 14803 14804 SDLoc dl(N); 14805 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 14806 SDValue ConvInput = Op.getOperand(0); 14807 if (IntBits < FloatBits) 14808 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 14809 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 14810 ConvInput); 14811 14812 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 14813 Intrinsic::arm_neon_vcvtfxu2fp; 14814 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 14815 Op.getValueType(), 14816 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 14817 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 14818 } 14819 14820 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG, 14821 const ARMSubtarget *ST) { 14822 if (!ST->hasMVEIntegerOps()) 14823 return SDValue(); 14824 14825 assert(N->getOpcode() == ISD::VECREDUCE_ADD); 14826 EVT ResVT = N->getValueType(0); 14827 SDValue N0 = N->getOperand(0); 14828 SDLoc dl(N); 14829 14830 // We are looking for something that will have illegal types if left alone, 14831 // but that we can convert to a single instruction undef MVE. For example 14832 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A 14833 // or 14834 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B 14835 14836 // Cases: 14837 // VADDV u/s 8/16/32 14838 // VMLAV u/s 8/16/32 14839 // VADDLV u/s 32 14840 // VMLALV u/s 16/32 14841 14842 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) { 14843 if (ResVT != RetTy || N0->getOpcode() != ExtendCode) 14844 return SDValue(); 14845 SDValue A = N0->getOperand(0); 14846 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14847 return A; 14848 return SDValue(); 14849 }; 14850 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode, 14851 ArrayRef<MVT> ExtTypes, SDValue &Mask) { 14852 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT || 14853 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode())) 14854 return SDValue(); 14855 Mask = N0->getOperand(0); 14856 SDValue Ext = N0->getOperand(1); 14857 if (Ext->getOpcode() != ExtendCode) 14858 return SDValue(); 14859 SDValue A = Ext->getOperand(0); 14860 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14861 return A; 14862 return SDValue(); 14863 }; 14864 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 14865 SDValue &A, SDValue &B) { 14866 // For a vmla we are trying to match a larger pattern: 14867 // ExtA = sext/zext A 14868 // ExtB = sext/zext B 14869 // Mul = mul ExtA, ExtB 14870 // vecreduce.add Mul 14871 // There might also be en extra extend between the mul and the addreduce, so 14872 // long as the bitwidth is high enough to make them equivalent (for example 14873 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64). 14874 if (ResVT != RetTy) 14875 return false; 14876 SDValue Mul = N0; 14877 if (Mul->getOpcode() == ExtendCode && 14878 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >= 14879 ResVT.getScalarSizeInBits()) 14880 Mul = Mul->getOperand(0); 14881 if (Mul->getOpcode() != ISD::MUL) 14882 return false; 14883 SDValue ExtA = Mul->getOperand(0); 14884 SDValue ExtB = Mul->getOperand(1); 14885 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 14886 return false; 14887 A = ExtA->getOperand(0); 14888 B = ExtB->getOperand(0); 14889 if (A.getValueType() == B.getValueType() && 14890 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14891 return true; 14892 return false; 14893 }; 14894 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 14895 SDValue &A, SDValue &B, SDValue &Mask) { 14896 // Same as the pattern above with a select for the zero predicated lanes 14897 // ExtA = sext/zext A 14898 // ExtB = sext/zext B 14899 // Mul = mul ExtA, ExtB 14900 // N0 = select Mask, Mul, 0 14901 // vecreduce.add N0 14902 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT || 14903 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode())) 14904 return false; 14905 Mask = N0->getOperand(0); 14906 SDValue Mul = N0->getOperand(1); 14907 if (Mul->getOpcode() == ExtendCode && 14908 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >= 14909 ResVT.getScalarSizeInBits()) 14910 Mul = Mul->getOperand(0); 14911 if (Mul->getOpcode() != ISD::MUL) 14912 return false; 14913 SDValue ExtA = Mul->getOperand(0); 14914 SDValue ExtB = Mul->getOperand(1); 14915 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 14916 return false; 14917 A = ExtA->getOperand(0); 14918 B = ExtB->getOperand(0); 14919 if (A.getValueType() == B.getValueType() && 14920 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14921 return true; 14922 return false; 14923 }; 14924 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) { 14925 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops); 14926 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node, 14927 SDValue(Node.getNode(), 1)); 14928 }; 14929 14930 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8})) 14931 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A); 14932 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8})) 14933 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A); 14934 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32})) 14935 return Create64bitNode(ARMISD::VADDLVs, {A}); 14936 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32})) 14937 return Create64bitNode(ARMISD::VADDLVu, {A}); 14938 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8})) 14939 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14940 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A)); 14941 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8})) 14942 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14943 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A)); 14944 14945 SDValue Mask; 14946 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask)) 14947 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask); 14948 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask)) 14949 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask); 14950 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask)) 14951 return Create64bitNode(ARMISD::VADDLVps, {A, Mask}); 14952 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask)) 14953 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask}); 14954 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask)) 14955 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14956 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask)); 14957 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask)) 14958 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14959 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask)); 14960 14961 SDValue A, B; 14962 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 14963 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B); 14964 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 14965 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B); 14966 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B)) 14967 return Create64bitNode(ARMISD::VMLALVs, {A, B}); 14968 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B)) 14969 return Create64bitNode(ARMISD::VMLALVu, {A, B}); 14970 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B)) 14971 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14972 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B)); 14973 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B)) 14974 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14975 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B)); 14976 14977 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask)) 14978 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask); 14979 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask)) 14980 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask); 14981 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask)) 14982 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask}); 14983 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask)) 14984 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask}); 14985 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask)) 14986 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14987 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask)); 14988 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask)) 14989 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14990 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask)); 14991 14992 // Some complications. We can get a case where the two inputs of the mul are 14993 // the same, then the output sext will have been helpfully converted to a 14994 // zext. Turn it back. 14995 SDValue Op = N0; 14996 if (Op->getOpcode() == ISD::VSELECT) 14997 Op = Op->getOperand(1); 14998 if (Op->getOpcode() == ISD::ZERO_EXTEND && 14999 Op->getOperand(0)->getOpcode() == ISD::MUL) { 15000 SDValue Mul = Op->getOperand(0); 15001 if (Mul->getOperand(0) == Mul->getOperand(1) && 15002 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) { 15003 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul); 15004 if (Op != N0) 15005 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0), 15006 N0->getOperand(0), Ext, N0->getOperand(2)); 15007 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext); 15008 } 15009 } 15010 15011 return SDValue(); 15012 } 15013 15014 static SDValue PerformVMOVNCombine(SDNode *N, 15015 TargetLowering::DAGCombinerInfo &DCI) { 15016 SDValue Op0 = N->getOperand(0); 15017 SDValue Op1 = N->getOperand(1); 15018 unsigned IsTop = N->getConstantOperandVal(2); 15019 15020 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b) 15021 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b) 15022 if ((Op1->getOpcode() == ARMISD::VQMOVNs || 15023 Op1->getOpcode() == ARMISD::VQMOVNu) && 15024 Op1->getConstantOperandVal(2) == 0) 15025 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0), 15026 Op0, Op1->getOperand(1), N->getOperand(2)); 15027 15028 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from 15029 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting 15030 // into the top or bottom lanes. 15031 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 15032 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1)); 15033 APInt Op0DemandedElts = 15034 IsTop ? Op1DemandedElts 15035 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1)); 15036 15037 APInt KnownUndef, KnownZero; 15038 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 15039 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef, 15040 KnownZero, DCI)) 15041 return SDValue(N, 0); 15042 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef, 15043 KnownZero, DCI)) 15044 return SDValue(N, 0); 15045 15046 return SDValue(); 15047 } 15048 15049 static SDValue PerformVQMOVNCombine(SDNode *N, 15050 TargetLowering::DAGCombinerInfo &DCI) { 15051 SDValue Op0 = N->getOperand(0); 15052 unsigned IsTop = N->getConstantOperandVal(2); 15053 15054 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 15055 APInt Op0DemandedElts = 15056 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1) 15057 : APInt::getHighBitsSet(2, 1)); 15058 15059 APInt KnownUndef, KnownZero; 15060 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 15061 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef, 15062 KnownZero, DCI)) 15063 return SDValue(N, 0); 15064 return SDValue(); 15065 } 15066 15067 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) { 15068 SDLoc DL(N); 15069 SDValue Op0 = N->getOperand(0); 15070 SDValue Op1 = N->getOperand(1); 15071 15072 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from 15073 // uses of the intrinsics. 15074 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 15075 int ShiftAmt = C->getSExtValue(); 15076 if (ShiftAmt == 0) { 15077 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL); 15078 DAG.ReplaceAllUsesWith(N, Merge.getNode()); 15079 return SDValue(); 15080 } 15081 15082 if (ShiftAmt >= -32 && ShiftAmt < 0) { 15083 unsigned NewOpcode = 15084 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL; 15085 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1, 15086 DAG.getConstant(-ShiftAmt, DL, MVT::i32)); 15087 DAG.ReplaceAllUsesWith(N, NewShift.getNode()); 15088 return NewShift; 15089 } 15090 } 15091 15092 return SDValue(); 15093 } 15094 15095 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 15096 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N, 15097 DAGCombinerInfo &DCI) const { 15098 SelectionDAG &DAG = DCI.DAG; 15099 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15100 switch (IntNo) { 15101 default: 15102 // Don't do anything for most intrinsics. 15103 break; 15104 15105 // Vector shifts: check for immediate versions and lower them. 15106 // Note: This is done during DAG combining instead of DAG legalizing because 15107 // the build_vectors for 64-bit vector element shift counts are generally 15108 // not legal, and it is hard to see their values after they get legalized to 15109 // loads from a constant pool. 15110 case Intrinsic::arm_neon_vshifts: 15111 case Intrinsic::arm_neon_vshiftu: 15112 case Intrinsic::arm_neon_vrshifts: 15113 case Intrinsic::arm_neon_vrshiftu: 15114 case Intrinsic::arm_neon_vrshiftn: 15115 case Intrinsic::arm_neon_vqshifts: 15116 case Intrinsic::arm_neon_vqshiftu: 15117 case Intrinsic::arm_neon_vqshiftsu: 15118 case Intrinsic::arm_neon_vqshiftns: 15119 case Intrinsic::arm_neon_vqshiftnu: 15120 case Intrinsic::arm_neon_vqshiftnsu: 15121 case Intrinsic::arm_neon_vqrshiftns: 15122 case Intrinsic::arm_neon_vqrshiftnu: 15123 case Intrinsic::arm_neon_vqrshiftnsu: { 15124 EVT VT = N->getOperand(1).getValueType(); 15125 int64_t Cnt; 15126 unsigned VShiftOpc = 0; 15127 15128 switch (IntNo) { 15129 case Intrinsic::arm_neon_vshifts: 15130 case Intrinsic::arm_neon_vshiftu: 15131 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 15132 VShiftOpc = ARMISD::VSHLIMM; 15133 break; 15134 } 15135 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 15136 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 15137 : ARMISD::VSHRuIMM); 15138 break; 15139 } 15140 return SDValue(); 15141 15142 case Intrinsic::arm_neon_vrshifts: 15143 case Intrinsic::arm_neon_vrshiftu: 15144 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 15145 break; 15146 return SDValue(); 15147 15148 case Intrinsic::arm_neon_vqshifts: 15149 case Intrinsic::arm_neon_vqshiftu: 15150 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 15151 break; 15152 return SDValue(); 15153 15154 case Intrinsic::arm_neon_vqshiftsu: 15155 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 15156 break; 15157 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 15158 15159 case Intrinsic::arm_neon_vrshiftn: 15160 case Intrinsic::arm_neon_vqshiftns: 15161 case Intrinsic::arm_neon_vqshiftnu: 15162 case Intrinsic::arm_neon_vqshiftnsu: 15163 case Intrinsic::arm_neon_vqrshiftns: 15164 case Intrinsic::arm_neon_vqrshiftnu: 15165 case Intrinsic::arm_neon_vqrshiftnsu: 15166 // Narrowing shifts require an immediate right shift. 15167 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 15168 break; 15169 llvm_unreachable("invalid shift count for narrowing vector shift " 15170 "intrinsic"); 15171 15172 default: 15173 llvm_unreachable("unhandled vector shift"); 15174 } 15175 15176 switch (IntNo) { 15177 case Intrinsic::arm_neon_vshifts: 15178 case Intrinsic::arm_neon_vshiftu: 15179 // Opcode already set above. 15180 break; 15181 case Intrinsic::arm_neon_vrshifts: 15182 VShiftOpc = ARMISD::VRSHRsIMM; 15183 break; 15184 case Intrinsic::arm_neon_vrshiftu: 15185 VShiftOpc = ARMISD::VRSHRuIMM; 15186 break; 15187 case Intrinsic::arm_neon_vrshiftn: 15188 VShiftOpc = ARMISD::VRSHRNIMM; 15189 break; 15190 case Intrinsic::arm_neon_vqshifts: 15191 VShiftOpc = ARMISD::VQSHLsIMM; 15192 break; 15193 case Intrinsic::arm_neon_vqshiftu: 15194 VShiftOpc = ARMISD::VQSHLuIMM; 15195 break; 15196 case Intrinsic::arm_neon_vqshiftsu: 15197 VShiftOpc = ARMISD::VQSHLsuIMM; 15198 break; 15199 case Intrinsic::arm_neon_vqshiftns: 15200 VShiftOpc = ARMISD::VQSHRNsIMM; 15201 break; 15202 case Intrinsic::arm_neon_vqshiftnu: 15203 VShiftOpc = ARMISD::VQSHRNuIMM; 15204 break; 15205 case Intrinsic::arm_neon_vqshiftnsu: 15206 VShiftOpc = ARMISD::VQSHRNsuIMM; 15207 break; 15208 case Intrinsic::arm_neon_vqrshiftns: 15209 VShiftOpc = ARMISD::VQRSHRNsIMM; 15210 break; 15211 case Intrinsic::arm_neon_vqrshiftnu: 15212 VShiftOpc = ARMISD::VQRSHRNuIMM; 15213 break; 15214 case Intrinsic::arm_neon_vqrshiftnsu: 15215 VShiftOpc = ARMISD::VQRSHRNsuIMM; 15216 break; 15217 } 15218 15219 SDLoc dl(N); 15220 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 15221 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 15222 } 15223 15224 case Intrinsic::arm_neon_vshiftins: { 15225 EVT VT = N->getOperand(1).getValueType(); 15226 int64_t Cnt; 15227 unsigned VShiftOpc = 0; 15228 15229 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 15230 VShiftOpc = ARMISD::VSLIIMM; 15231 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 15232 VShiftOpc = ARMISD::VSRIIMM; 15233 else { 15234 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 15235 } 15236 15237 SDLoc dl(N); 15238 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 15239 N->getOperand(1), N->getOperand(2), 15240 DAG.getConstant(Cnt, dl, MVT::i32)); 15241 } 15242 15243 case Intrinsic::arm_neon_vqrshifts: 15244 case Intrinsic::arm_neon_vqrshiftu: 15245 // No immediate versions of these to check for. 15246 break; 15247 15248 case Intrinsic::arm_mve_vqdmlah: 15249 case Intrinsic::arm_mve_vqdmlash: 15250 case Intrinsic::arm_mve_vqrdmlah: 15251 case Intrinsic::arm_mve_vqrdmlash: 15252 case Intrinsic::arm_mve_vmla_n_predicated: 15253 case Intrinsic::arm_mve_vmlas_n_predicated: 15254 case Intrinsic::arm_mve_vqdmlah_predicated: 15255 case Intrinsic::arm_mve_vqdmlash_predicated: 15256 case Intrinsic::arm_mve_vqrdmlah_predicated: 15257 case Intrinsic::arm_mve_vqrdmlash_predicated: { 15258 // These intrinsics all take an i32 scalar operand which is narrowed to the 15259 // size of a single lane of the vector type they return. So we don't need 15260 // any bits of that operand above that point, which allows us to eliminate 15261 // uxth/sxth. 15262 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits(); 15263 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 15264 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI)) 15265 return SDValue(); 15266 break; 15267 } 15268 15269 case Intrinsic::arm_mve_minv: 15270 case Intrinsic::arm_mve_maxv: 15271 case Intrinsic::arm_mve_minav: 15272 case Intrinsic::arm_mve_maxav: 15273 case Intrinsic::arm_mve_minv_predicated: 15274 case Intrinsic::arm_mve_maxv_predicated: 15275 case Intrinsic::arm_mve_minav_predicated: 15276 case Intrinsic::arm_mve_maxav_predicated: { 15277 // These intrinsics all take an i32 scalar operand which is narrowed to the 15278 // size of a single lane of the vector type they take as the other input. 15279 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits(); 15280 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 15281 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 15282 return SDValue(); 15283 break; 15284 } 15285 15286 case Intrinsic::arm_mve_addv: { 15287 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node, 15288 // which allow PerformADDVecReduce to turn it into VADDLV when possible. 15289 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15290 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs; 15291 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1)); 15292 } 15293 15294 case Intrinsic::arm_mve_addlv: 15295 case Intrinsic::arm_mve_addlv_predicated: { 15296 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR 15297 // which recombines the two outputs into an i64 15298 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15299 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ? 15300 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) : 15301 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps); 15302 15303 SmallVector<SDValue, 4> Ops; 15304 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++) 15305 if (i != 2) // skip the unsigned flag 15306 Ops.push_back(N->getOperand(i)); 15307 15308 SDLoc dl(N); 15309 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops); 15310 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0), 15311 val.getValue(1)); 15312 } 15313 } 15314 15315 return SDValue(); 15316 } 15317 15318 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 15319 /// lowers them. As with the vector shift intrinsics, this is done during DAG 15320 /// combining instead of DAG legalizing because the build_vectors for 64-bit 15321 /// vector element shift counts are generally not legal, and it is hard to see 15322 /// their values after they get legalized to loads from a constant pool. 15323 static SDValue PerformShiftCombine(SDNode *N, 15324 TargetLowering::DAGCombinerInfo &DCI, 15325 const ARMSubtarget *ST) { 15326 SelectionDAG &DAG = DCI.DAG; 15327 EVT VT = N->getValueType(0); 15328 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 15329 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 15330 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 15331 SDValue N1 = N->getOperand(1); 15332 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 15333 SDValue N0 = N->getOperand(0); 15334 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 15335 DAG.MaskedValueIsZero(N0.getOperand(0), 15336 APInt::getHighBitsSet(32, 16))) 15337 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 15338 } 15339 } 15340 15341 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 15342 N->getOperand(0)->getOpcode() == ISD::AND && 15343 N->getOperand(0)->hasOneUse()) { 15344 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 15345 return SDValue(); 15346 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 15347 // usually show up because instcombine prefers to canonicalize it to 15348 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 15349 // out of GEP lowering in some cases. 15350 SDValue N0 = N->getOperand(0); 15351 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15352 if (!ShiftAmtNode) 15353 return SDValue(); 15354 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 15355 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 15356 if (!AndMaskNode) 15357 return SDValue(); 15358 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 15359 // Don't transform uxtb/uxth. 15360 if (AndMask == 255 || AndMask == 65535) 15361 return SDValue(); 15362 if (isMask_32(AndMask)) { 15363 uint32_t MaskedBits = countLeadingZeros(AndMask); 15364 if (MaskedBits > ShiftAmt) { 15365 SDLoc DL(N); 15366 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 15367 DAG.getConstant(MaskedBits, DL, MVT::i32)); 15368 return DAG.getNode( 15369 ISD::SRL, DL, MVT::i32, SHL, 15370 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 15371 } 15372 } 15373 } 15374 15375 // Nothing to be done for scalar shifts. 15376 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15377 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 15378 return SDValue(); 15379 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 15380 return SDValue(); 15381 15382 int64_t Cnt; 15383 15384 switch (N->getOpcode()) { 15385 default: llvm_unreachable("unexpected shift opcode"); 15386 15387 case ISD::SHL: 15388 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 15389 SDLoc dl(N); 15390 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 15391 DAG.getConstant(Cnt, dl, MVT::i32)); 15392 } 15393 break; 15394 15395 case ISD::SRA: 15396 case ISD::SRL: 15397 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 15398 unsigned VShiftOpc = 15399 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 15400 SDLoc dl(N); 15401 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 15402 DAG.getConstant(Cnt, dl, MVT::i32)); 15403 } 15404 } 15405 return SDValue(); 15406 } 15407 15408 // Look for a sign/zero/fpextend extend of a larger than legal load. This can be 15409 // split into multiple extending loads, which are simpler to deal with than an 15410 // arbitrary extend. For fp extends we use an integer extending load and a VCVTL 15411 // to convert the type to an f32. 15412 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) { 15413 SDValue N0 = N->getOperand(0); 15414 if (N0.getOpcode() != ISD::LOAD) 15415 return SDValue(); 15416 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode()); 15417 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() || 15418 LD->getExtensionType() != ISD::NON_EXTLOAD) 15419 return SDValue(); 15420 EVT FromVT = LD->getValueType(0); 15421 EVT ToVT = N->getValueType(0); 15422 if (!ToVT.isVector()) 15423 return SDValue(); 15424 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 15425 EVT ToEltVT = ToVT.getVectorElementType(); 15426 EVT FromEltVT = FromVT.getVectorElementType(); 15427 15428 unsigned NumElements = 0; 15429 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8)) 15430 NumElements = 4; 15431 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8) 15432 NumElements = 8; 15433 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16) 15434 NumElements = 4; 15435 if (NumElements == 0 || 15436 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) || 15437 FromVT.getVectorNumElements() % NumElements != 0 || 15438 !isPowerOf2_32(NumElements)) 15439 return SDValue(); 15440 15441 LLVMContext &C = *DAG.getContext(); 15442 SDLoc DL(LD); 15443 // Details about the old load 15444 SDValue Ch = LD->getChain(); 15445 SDValue BasePtr = LD->getBasePtr(); 15446 Align Alignment = LD->getOriginalAlign(); 15447 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 15448 AAMDNodes AAInfo = LD->getAAInfo(); 15449 15450 ISD::LoadExtType NewExtType = 15451 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 15452 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType()); 15453 EVT NewFromVT = EVT::getVectorVT( 15454 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements); 15455 EVT NewToVT = EVT::getVectorVT( 15456 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements); 15457 15458 SmallVector<SDValue, 4> Loads; 15459 SmallVector<SDValue, 4> Chains; 15460 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 15461 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8; 15462 SDValue NewPtr = 15463 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset)); 15464 15465 SDValue NewLoad = 15466 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset, 15467 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT, 15468 Alignment, MMOFlags, AAInfo); 15469 Loads.push_back(NewLoad); 15470 Chains.push_back(SDValue(NewLoad.getNode(), 1)); 15471 } 15472 15473 // Float truncs need to extended with VCVTB's into their floating point types. 15474 if (FromEltVT == MVT::f16) { 15475 SmallVector<SDValue, 4> Extends; 15476 15477 for (unsigned i = 0; i < Loads.size(); i++) { 15478 SDValue LoadBC = 15479 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]); 15480 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC, 15481 DAG.getConstant(0, DL, MVT::i32)); 15482 Extends.push_back(FPExt); 15483 } 15484 15485 Loads = Extends; 15486 } 15487 15488 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 15489 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain); 15490 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads); 15491 } 15492 15493 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 15494 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 15495 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 15496 const ARMSubtarget *ST) { 15497 SDValue N0 = N->getOperand(0); 15498 15499 // Check for sign- and zero-extensions of vector extract operations of 8- and 15500 // 16-bit vector elements. NEON and MVE support these directly. They are 15501 // handled during DAG combining because type legalization will promote them 15502 // to 32-bit types and it is messy to recognize the operations after that. 15503 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) && 15504 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 15505 SDValue Vec = N0.getOperand(0); 15506 SDValue Lane = N0.getOperand(1); 15507 EVT VT = N->getValueType(0); 15508 EVT EltVT = N0.getValueType(); 15509 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15510 15511 if (VT == MVT::i32 && 15512 (EltVT == MVT::i8 || EltVT == MVT::i16) && 15513 TLI.isTypeLegal(Vec.getValueType()) && 15514 isa<ConstantSDNode>(Lane)) { 15515 15516 unsigned Opc = 0; 15517 switch (N->getOpcode()) { 15518 default: llvm_unreachable("unexpected opcode"); 15519 case ISD::SIGN_EXTEND: 15520 Opc = ARMISD::VGETLANEs; 15521 break; 15522 case ISD::ZERO_EXTEND: 15523 case ISD::ANY_EXTEND: 15524 Opc = ARMISD::VGETLANEu; 15525 break; 15526 } 15527 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 15528 } 15529 } 15530 15531 if (ST->hasMVEIntegerOps()) 15532 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 15533 return NewLoad; 15534 15535 return SDValue(); 15536 } 15537 15538 static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG, 15539 const ARMSubtarget *ST) { 15540 if (ST->hasMVEFloatOps()) 15541 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 15542 return NewLoad; 15543 15544 return SDValue(); 15545 } 15546 15547 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating 15548 /// saturates. 15549 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG, 15550 const ARMSubtarget *ST) { 15551 EVT VT = N->getValueType(0); 15552 SDValue N0 = N->getOperand(0); 15553 if (!ST->hasMVEIntegerOps()) 15554 return SDValue(); 15555 15556 if (VT != MVT::v4i32 && VT != MVT::v8i16) 15557 return SDValue(); 15558 15559 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) { 15560 // Check one is a smin and the other is a smax 15561 if (Min->getOpcode() != ISD::SMIN) 15562 std::swap(Min, Max); 15563 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX) 15564 return false; 15565 15566 APInt SaturateC; 15567 if (VT == MVT::v4i32) 15568 SaturateC = APInt(32, (1 << 15) - 1, true); 15569 else //if (VT == MVT::v8i16) 15570 SaturateC = APInt(16, (1 << 7) - 1, true); 15571 15572 APInt MinC, MaxC; 15573 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) || 15574 MinC != SaturateC) 15575 return false; 15576 if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) || 15577 MaxC != ~SaturateC) 15578 return false; 15579 return true; 15580 }; 15581 15582 if (IsSignedSaturate(N, N0.getNode())) { 15583 SDLoc DL(N); 15584 MVT ExtVT, HalfVT; 15585 if (VT == MVT::v4i32) { 15586 HalfVT = MVT::v8i16; 15587 ExtVT = MVT::v4i16; 15588 } else { // if (VT == MVT::v8i16) 15589 HalfVT = MVT::v16i8; 15590 ExtVT = MVT::v8i8; 15591 } 15592 15593 // Create a VQMOVNB with undef top lanes, then signed extended into the top 15594 // half. That extend will hopefully be removed if only the bottom bits are 15595 // demanded (though a truncating store, for example). 15596 SDValue VQMOVN = 15597 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT), 15598 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32)); 15599 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN); 15600 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast, 15601 DAG.getValueType(ExtVT)); 15602 } 15603 15604 auto IsUnsignedSaturate = [&](SDNode *Min) { 15605 // For unsigned, we just need to check for <= 0xffff 15606 if (Min->getOpcode() != ISD::UMIN) 15607 return false; 15608 15609 APInt SaturateC; 15610 if (VT == MVT::v4i32) 15611 SaturateC = APInt(32, (1 << 16) - 1, true); 15612 else //if (VT == MVT::v8i16) 15613 SaturateC = APInt(16, (1 << 8) - 1, true); 15614 15615 APInt MinC; 15616 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) || 15617 MinC != SaturateC) 15618 return false; 15619 return true; 15620 }; 15621 15622 if (IsUnsignedSaturate(N)) { 15623 SDLoc DL(N); 15624 MVT HalfVT; 15625 unsigned ExtConst; 15626 if (VT == MVT::v4i32) { 15627 HalfVT = MVT::v8i16; 15628 ExtConst = 0x0000FFFF; 15629 } else { //if (VT == MVT::v8i16) 15630 HalfVT = MVT::v16i8; 15631 ExtConst = 0x00FF; 15632 } 15633 15634 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with 15635 // an AND. That extend will hopefully be removed if only the bottom bits are 15636 // demanded (though a truncating store, for example). 15637 SDValue VQMOVN = 15638 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0, 15639 DAG.getConstant(0, DL, MVT::i32)); 15640 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN); 15641 return DAG.getNode(ISD::AND, DL, VT, Bitcast, 15642 DAG.getConstant(ExtConst, DL, VT)); 15643 } 15644 15645 return SDValue(); 15646 } 15647 15648 static const APInt *isPowerOf2Constant(SDValue V) { 15649 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 15650 if (!C) 15651 return nullptr; 15652 const APInt *CV = &C->getAPIntValue(); 15653 return CV->isPowerOf2() ? CV : nullptr; 15654 } 15655 15656 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 15657 // If we have a CMOV, OR and AND combination such as: 15658 // if (x & CN) 15659 // y |= CM; 15660 // 15661 // And: 15662 // * CN is a single bit; 15663 // * All bits covered by CM are known zero in y 15664 // 15665 // Then we can convert this into a sequence of BFI instructions. This will 15666 // always be a win if CM is a single bit, will always be no worse than the 15667 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 15668 // three bits (due to the extra IT instruction). 15669 15670 SDValue Op0 = CMOV->getOperand(0); 15671 SDValue Op1 = CMOV->getOperand(1); 15672 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 15673 auto CC = CCNode->getAPIntValue().getLimitedValue(); 15674 SDValue CmpZ = CMOV->getOperand(4); 15675 15676 // The compare must be against zero. 15677 if (!isNullConstant(CmpZ->getOperand(1))) 15678 return SDValue(); 15679 15680 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 15681 SDValue And = CmpZ->getOperand(0); 15682 if (And->getOpcode() != ISD::AND) 15683 return SDValue(); 15684 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 15685 if (!AndC) 15686 return SDValue(); 15687 SDValue X = And->getOperand(0); 15688 15689 if (CC == ARMCC::EQ) { 15690 // We're performing an "equal to zero" compare. Swap the operands so we 15691 // canonicalize on a "not equal to zero" compare. 15692 std::swap(Op0, Op1); 15693 } else { 15694 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 15695 } 15696 15697 if (Op1->getOpcode() != ISD::OR) 15698 return SDValue(); 15699 15700 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 15701 if (!OrC) 15702 return SDValue(); 15703 SDValue Y = Op1->getOperand(0); 15704 15705 if (Op0 != Y) 15706 return SDValue(); 15707 15708 // Now, is it profitable to continue? 15709 APInt OrCI = OrC->getAPIntValue(); 15710 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 15711 if (OrCI.countPopulation() > Heuristic) 15712 return SDValue(); 15713 15714 // Lastly, can we determine that the bits defined by OrCI 15715 // are zero in Y? 15716 KnownBits Known = DAG.computeKnownBits(Y); 15717 if ((OrCI & Known.Zero) != OrCI) 15718 return SDValue(); 15719 15720 // OK, we can do the combine. 15721 SDValue V = Y; 15722 SDLoc dl(X); 15723 EVT VT = X.getValueType(); 15724 unsigned BitInX = AndC->logBase2(); 15725 15726 if (BitInX != 0) { 15727 // We must shift X first. 15728 X = DAG.getNode(ISD::SRL, dl, VT, X, 15729 DAG.getConstant(BitInX, dl, VT)); 15730 } 15731 15732 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 15733 BitInY < NumActiveBits; ++BitInY) { 15734 if (OrCI[BitInY] == 0) 15735 continue; 15736 APInt Mask(VT.getSizeInBits(), 0); 15737 Mask.setBit(BitInY); 15738 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 15739 // Confusingly, the operand is an *inverted* mask. 15740 DAG.getConstant(~Mask, dl, VT)); 15741 } 15742 15743 return V; 15744 } 15745 15746 // Given N, the value controlling the conditional branch, search for the loop 15747 // intrinsic, returning it, along with how the value is used. We need to handle 15748 // patterns such as the following: 15749 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 15750 // (brcond (setcc (loop.decrement), 0, eq), exit) 15751 // (brcond (setcc (loop.decrement), 0, ne), header) 15752 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 15753 bool &Negate) { 15754 switch (N->getOpcode()) { 15755 default: 15756 break; 15757 case ISD::XOR: { 15758 if (!isa<ConstantSDNode>(N.getOperand(1))) 15759 return SDValue(); 15760 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 15761 return SDValue(); 15762 Negate = !Negate; 15763 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 15764 } 15765 case ISD::SETCC: { 15766 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 15767 if (!Const) 15768 return SDValue(); 15769 if (Const->isNullValue()) 15770 Imm = 0; 15771 else if (Const->isOne()) 15772 Imm = 1; 15773 else 15774 return SDValue(); 15775 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 15776 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 15777 } 15778 case ISD::INTRINSIC_W_CHAIN: { 15779 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 15780 if (IntOp != Intrinsic::test_set_loop_iterations && 15781 IntOp != Intrinsic::loop_decrement_reg) 15782 return SDValue(); 15783 return N; 15784 } 15785 } 15786 return SDValue(); 15787 } 15788 15789 static SDValue PerformHWLoopCombine(SDNode *N, 15790 TargetLowering::DAGCombinerInfo &DCI, 15791 const ARMSubtarget *ST) { 15792 15793 // The hwloop intrinsics that we're interested are used for control-flow, 15794 // either for entering or exiting the loop: 15795 // - test.set.loop.iterations will test whether its operand is zero. If it 15796 // is zero, the proceeding branch should not enter the loop. 15797 // - loop.decrement.reg also tests whether its operand is zero. If it is 15798 // zero, the proceeding branch should not branch back to the beginning of 15799 // the loop. 15800 // So here, we need to check that how the brcond is using the result of each 15801 // of the intrinsics to ensure that we're branching to the right place at the 15802 // right time. 15803 15804 ISD::CondCode CC; 15805 SDValue Cond; 15806 int Imm = 1; 15807 bool Negate = false; 15808 SDValue Chain = N->getOperand(0); 15809 SDValue Dest; 15810 15811 if (N->getOpcode() == ISD::BRCOND) { 15812 CC = ISD::SETEQ; 15813 Cond = N->getOperand(1); 15814 Dest = N->getOperand(2); 15815 } else { 15816 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 15817 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15818 Cond = N->getOperand(2); 15819 Dest = N->getOperand(4); 15820 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 15821 if (!Const->isOne() && !Const->isNullValue()) 15822 return SDValue(); 15823 Imm = Const->getZExtValue(); 15824 } else 15825 return SDValue(); 15826 } 15827 15828 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 15829 if (!Int) 15830 return SDValue(); 15831 15832 if (Negate) 15833 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32); 15834 15835 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 15836 return (CC == ISD::SETEQ && Imm == 0) || 15837 (CC == ISD::SETNE && Imm == 1) || 15838 (CC == ISD::SETLT && Imm == 1) || 15839 (CC == ISD::SETULT && Imm == 1); 15840 }; 15841 15842 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 15843 return (CC == ISD::SETEQ && Imm == 1) || 15844 (CC == ISD::SETNE && Imm == 0) || 15845 (CC == ISD::SETGT && Imm == 0) || 15846 (CC == ISD::SETUGT && Imm == 0) || 15847 (CC == ISD::SETGE && Imm == 1) || 15848 (CC == ISD::SETUGE && Imm == 1); 15849 }; 15850 15851 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 15852 "unsupported condition"); 15853 15854 SDLoc dl(Int); 15855 SelectionDAG &DAG = DCI.DAG; 15856 SDValue Elements = Int.getOperand(2); 15857 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 15858 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 15859 && "expected single br user"); 15860 SDNode *Br = *N->use_begin(); 15861 SDValue OtherTarget = Br->getOperand(1); 15862 15863 // Update the unconditional branch to branch to the given Dest. 15864 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 15865 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 15866 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 15867 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 15868 }; 15869 15870 if (IntOp == Intrinsic::test_set_loop_iterations) { 15871 SDValue Res; 15872 // We expect this 'instruction' to branch when the counter is zero. 15873 if (IsTrueIfZero(CC, Imm)) { 15874 SDValue Ops[] = { Chain, Elements, Dest }; 15875 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 15876 } else { 15877 // The logic is the reverse of what we need for WLS, so find the other 15878 // basic block target: the target of the proceeding br. 15879 UpdateUncondBr(Br, Dest, DAG); 15880 15881 SDValue Ops[] = { Chain, Elements, OtherTarget }; 15882 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 15883 } 15884 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 15885 return Res; 15886 } else { 15887 SDValue Size = DAG.getTargetConstant( 15888 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 15889 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 15890 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 15891 DAG.getVTList(MVT::i32, MVT::Other), Args); 15892 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 15893 15894 // We expect this instruction to branch when the count is not zero. 15895 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 15896 15897 // Update the unconditional branch to target the loop preheader if we've 15898 // found the condition has been reversed. 15899 if (Target == OtherTarget) 15900 UpdateUncondBr(Br, Dest, DAG); 15901 15902 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15903 SDValue(LoopDec.getNode(), 1), Chain); 15904 15905 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 15906 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 15907 } 15908 return SDValue(); 15909 } 15910 15911 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 15912 SDValue 15913 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 15914 SDValue Cmp = N->getOperand(4); 15915 if (Cmp.getOpcode() != ARMISD::CMPZ) 15916 // Only looking at NE cases. 15917 return SDValue(); 15918 15919 EVT VT = N->getValueType(0); 15920 SDLoc dl(N); 15921 SDValue LHS = Cmp.getOperand(0); 15922 SDValue RHS = Cmp.getOperand(1); 15923 SDValue Chain = N->getOperand(0); 15924 SDValue BB = N->getOperand(1); 15925 SDValue ARMcc = N->getOperand(2); 15926 ARMCC::CondCodes CC = 15927 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 15928 15929 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 15930 // -> (brcond Chain BB CC CPSR Cmp) 15931 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 15932 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 15933 LHS->getOperand(0)->hasOneUse()) { 15934 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 15935 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 15936 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 15937 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 15938 if ((LHS00C && LHS00C->getZExtValue() == 0) && 15939 (LHS01C && LHS01C->getZExtValue() == 1) && 15940 (LHS1C && LHS1C->getZExtValue() == 1) && 15941 (RHSC && RHSC->getZExtValue() == 0)) { 15942 return DAG.getNode( 15943 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 15944 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 15945 } 15946 } 15947 15948 return SDValue(); 15949 } 15950 15951 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 15952 SDValue 15953 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 15954 SDValue Cmp = N->getOperand(4); 15955 if (Cmp.getOpcode() != ARMISD::CMPZ) 15956 // Only looking at EQ and NE cases. 15957 return SDValue(); 15958 15959 EVT VT = N->getValueType(0); 15960 SDLoc dl(N); 15961 SDValue LHS = Cmp.getOperand(0); 15962 SDValue RHS = Cmp.getOperand(1); 15963 SDValue FalseVal = N->getOperand(0); 15964 SDValue TrueVal = N->getOperand(1); 15965 SDValue ARMcc = N->getOperand(2); 15966 ARMCC::CondCodes CC = 15967 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 15968 15969 // BFI is only available on V6T2+. 15970 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 15971 SDValue R = PerformCMOVToBFICombine(N, DAG); 15972 if (R) 15973 return R; 15974 } 15975 15976 // Simplify 15977 // mov r1, r0 15978 // cmp r1, x 15979 // mov r0, y 15980 // moveq r0, x 15981 // to 15982 // cmp r0, x 15983 // movne r0, y 15984 // 15985 // mov r1, r0 15986 // cmp r1, x 15987 // mov r0, x 15988 // movne r0, y 15989 // to 15990 // cmp r0, x 15991 // movne r0, y 15992 /// FIXME: Turn this into a target neutral optimization? 15993 SDValue Res; 15994 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 15995 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 15996 N->getOperand(3), Cmp); 15997 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 15998 SDValue ARMcc; 15999 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 16000 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 16001 N->getOperand(3), NewCmp); 16002 } 16003 16004 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 16005 // -> (cmov F T CC CPSR Cmp) 16006 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 16007 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 16008 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 16009 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 16010 if ((LHS0C && LHS0C->getZExtValue() == 0) && 16011 (LHS1C && LHS1C->getZExtValue() == 1) && 16012 (RHSC && RHSC->getZExtValue() == 0)) { 16013 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 16014 LHS->getOperand(2), LHS->getOperand(3), 16015 LHS->getOperand(4)); 16016 } 16017 } 16018 16019 if (!VT.isInteger()) 16020 return SDValue(); 16021 16022 // Materialize a boolean comparison for integers so we can avoid branching. 16023 if (isNullConstant(FalseVal)) { 16024 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 16025 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 16026 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 16027 // right 5 bits will make that 32 be 1, otherwise it will be 0. 16028 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 16029 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 16030 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 16031 DAG.getConstant(5, dl, MVT::i32)); 16032 } else { 16033 // CMOV 0, 1, ==, (CMPZ x, y) -> 16034 // (ADDCARRY (SUB x, y), t:0, t:1) 16035 // where t = (SUBCARRY 0, (SUB x, y), 0) 16036 // 16037 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 16038 // x != y. In other words, a carry C == 1 when x == y, C == 0 16039 // otherwise. 16040 // The final ADDCARRY computes 16041 // x - y + (0 - (x - y)) + C == C 16042 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 16043 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 16044 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 16045 // ISD::SUBCARRY returns a borrow but we want the carry here 16046 // actually. 16047 SDValue Carry = 16048 DAG.getNode(ISD::SUB, dl, MVT::i32, 16049 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 16050 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 16051 } 16052 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 16053 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 16054 // This seems pointless but will allow us to combine it further below. 16055 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 16056 SDValue Sub = 16057 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 16058 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 16059 Sub.getValue(1), SDValue()); 16060 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 16061 N->getOperand(3), CPSRGlue.getValue(1)); 16062 FalseVal = Sub; 16063 } 16064 } else if (isNullConstant(TrueVal)) { 16065 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 16066 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 16067 // This seems pointless but will allow us to combine it further below 16068 // Note that we change == for != as this is the dual for the case above. 16069 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 16070 SDValue Sub = 16071 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 16072 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 16073 Sub.getValue(1), SDValue()); 16074 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 16075 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 16076 N->getOperand(3), CPSRGlue.getValue(1)); 16077 FalseVal = Sub; 16078 } 16079 } 16080 16081 // On Thumb1, the DAG above may be further combined if z is a power of 2 16082 // (z == 2 ^ K). 16083 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 16084 // t1 = (USUBO (SUB x, y), 1) 16085 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 16086 // Result = if K != 0 then (SHL t2:0, K) else t2:0 16087 // 16088 // This also handles the special case of comparing against zero; it's 16089 // essentially, the same pattern, except there's no SUBS: 16090 // CMOV x, z, !=, (CMPZ x, 0) -> 16091 // t1 = (USUBO x, 1) 16092 // t2 = (SUBCARRY x, t1:0, t1:1) 16093 // Result = if K != 0 then (SHL t2:0, K) else t2:0 16094 const APInt *TrueConst; 16095 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 16096 ((FalseVal.getOpcode() == ARMISD::SUBS && 16097 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 16098 (FalseVal == LHS && isNullConstant(RHS))) && 16099 (TrueConst = isPowerOf2Constant(TrueVal))) { 16100 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 16101 unsigned ShiftAmount = TrueConst->logBase2(); 16102 if (ShiftAmount) 16103 TrueVal = DAG.getConstant(1, dl, VT); 16104 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 16105 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 16106 16107 if (ShiftAmount) 16108 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 16109 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 16110 } 16111 16112 if (Res.getNode()) { 16113 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 16114 // Capture demanded bits information that would be otherwise lost. 16115 if (Known.Zero == 0xfffffffe) 16116 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16117 DAG.getValueType(MVT::i1)); 16118 else if (Known.Zero == 0xffffff00) 16119 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16120 DAG.getValueType(MVT::i8)); 16121 else if (Known.Zero == 0xffff0000) 16122 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16123 DAG.getValueType(MVT::i16)); 16124 } 16125 16126 return Res; 16127 } 16128 16129 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG, 16130 const ARMSubtarget *ST) { 16131 SDValue Src = N->getOperand(0); 16132 EVT DstVT = N->getValueType(0); 16133 16134 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE. 16135 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) { 16136 EVT SrcVT = Src.getValueType(); 16137 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits()) 16138 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0)); 16139 } 16140 16141 // We may have a bitcast of something that has already had this bitcast 16142 // combine performed on it, so skip past any VECTOR_REG_CASTs. 16143 while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST) 16144 Src = Src.getOperand(0); 16145 16146 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that 16147 // would be generated is at least the width of the element type. 16148 EVT SrcVT = Src.getValueType(); 16149 if ((Src.getOpcode() == ARMISD::VMOVIMM || 16150 Src.getOpcode() == ARMISD::VMVNIMM || 16151 Src.getOpcode() == ARMISD::VMOVFPIMM) && 16152 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() && 16153 DAG.getDataLayout().isBigEndian()) 16154 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src); 16155 16156 return SDValue(); 16157 } 16158 16159 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 16160 DAGCombinerInfo &DCI) const { 16161 switch (N->getOpcode()) { 16162 default: break; 16163 case ISD::SELECT_CC: 16164 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget); 16165 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget); 16166 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 16167 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 16168 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 16169 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 16170 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget); 16171 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 16172 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 16173 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 16174 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 16175 case ISD::BRCOND: 16176 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 16177 case ARMISD::ADDC: 16178 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 16179 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 16180 case ARMISD::BFI: return PerformBFICombine(N, DCI); 16181 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 16182 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 16183 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI); 16184 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI); 16185 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget); 16186 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 16187 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 16188 case ISD::EXTRACT_VECTOR_ELT: return PerformExtractEltCombine(N, DCI); 16189 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 16190 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget); 16191 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 16192 case ISD::FP_TO_SINT: 16193 case ISD::FP_TO_UINT: 16194 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 16195 case ISD::FDIV: 16196 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 16197 case ISD::INTRINSIC_WO_CHAIN: 16198 return PerformIntrinsicCombine(N, DCI); 16199 case ISD::SHL: 16200 case ISD::SRA: 16201 case ISD::SRL: 16202 return PerformShiftCombine(N, DCI, Subtarget); 16203 case ISD::SIGN_EXTEND: 16204 case ISD::ZERO_EXTEND: 16205 case ISD::ANY_EXTEND: 16206 return PerformExtendCombine(N, DCI.DAG, Subtarget); 16207 case ISD::FP_EXTEND: 16208 return PerformFPExtendCombine(N, DCI.DAG, Subtarget); 16209 case ISD::SMIN: 16210 case ISD::UMIN: 16211 case ISD::SMAX: 16212 case ISD::UMAX: 16213 return PerformMinMaxCombine(N, DCI.DAG, Subtarget); 16214 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 16215 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 16216 case ISD::LOAD: return PerformLOADCombine(N, DCI); 16217 case ARMISD::VLD1DUP: 16218 case ARMISD::VLD2DUP: 16219 case ARMISD::VLD3DUP: 16220 case ARMISD::VLD4DUP: 16221 return PerformVLDCombine(N, DCI); 16222 case ARMISD::BUILD_VECTOR: 16223 return PerformARMBUILD_VECTORCombine(N, DCI); 16224 case ISD::BITCAST: 16225 return PerformBITCASTCombine(N, DCI.DAG, Subtarget); 16226 case ARMISD::PREDICATE_CAST: 16227 return PerformPREDICATE_CASTCombine(N, DCI); 16228 case ARMISD::VECTOR_REG_CAST: 16229 return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget); 16230 case ARMISD::VCMP: 16231 return PerformVCMPCombine(N, DCI, Subtarget); 16232 case ISD::VECREDUCE_ADD: 16233 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget); 16234 case ARMISD::VMOVN: 16235 return PerformVMOVNCombine(N, DCI); 16236 case ARMISD::VQMOVNs: 16237 case ARMISD::VQMOVNu: 16238 return PerformVQMOVNCombine(N, DCI); 16239 case ARMISD::ASRL: 16240 case ARMISD::LSRL: 16241 case ARMISD::LSLL: 16242 return PerformLongShiftCombine(N, DCI.DAG); 16243 case ARMISD::SMULWB: { 16244 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16245 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 16246 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 16247 return SDValue(); 16248 break; 16249 } 16250 case ARMISD::SMULWT: { 16251 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16252 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 16253 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 16254 return SDValue(); 16255 break; 16256 } 16257 case ARMISD::SMLALBB: 16258 case ARMISD::QADD16b: 16259 case ARMISD::QSUB16b: { 16260 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16261 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 16262 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16263 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16264 return SDValue(); 16265 break; 16266 } 16267 case ARMISD::SMLALBT: { 16268 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 16269 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 16270 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 16271 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 16272 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 16273 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 16274 return SDValue(); 16275 break; 16276 } 16277 case ARMISD::SMLALTB: { 16278 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 16279 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 16280 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 16281 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 16282 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 16283 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 16284 return SDValue(); 16285 break; 16286 } 16287 case ARMISD::SMLALTT: { 16288 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16289 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 16290 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16291 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16292 return SDValue(); 16293 break; 16294 } 16295 case ARMISD::QADD8b: 16296 case ARMISD::QSUB8b: { 16297 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16298 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8); 16299 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16300 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16301 return SDValue(); 16302 break; 16303 } 16304 case ISD::INTRINSIC_VOID: 16305 case ISD::INTRINSIC_W_CHAIN: 16306 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 16307 case Intrinsic::arm_neon_vld1: 16308 case Intrinsic::arm_neon_vld1x2: 16309 case Intrinsic::arm_neon_vld1x3: 16310 case Intrinsic::arm_neon_vld1x4: 16311 case Intrinsic::arm_neon_vld2: 16312 case Intrinsic::arm_neon_vld3: 16313 case Intrinsic::arm_neon_vld4: 16314 case Intrinsic::arm_neon_vld2lane: 16315 case Intrinsic::arm_neon_vld3lane: 16316 case Intrinsic::arm_neon_vld4lane: 16317 case Intrinsic::arm_neon_vld2dup: 16318 case Intrinsic::arm_neon_vld3dup: 16319 case Intrinsic::arm_neon_vld4dup: 16320 case Intrinsic::arm_neon_vst1: 16321 case Intrinsic::arm_neon_vst1x2: 16322 case Intrinsic::arm_neon_vst1x3: 16323 case Intrinsic::arm_neon_vst1x4: 16324 case Intrinsic::arm_neon_vst2: 16325 case Intrinsic::arm_neon_vst3: 16326 case Intrinsic::arm_neon_vst4: 16327 case Intrinsic::arm_neon_vst2lane: 16328 case Intrinsic::arm_neon_vst3lane: 16329 case Intrinsic::arm_neon_vst4lane: 16330 return PerformVLDCombine(N, DCI); 16331 case Intrinsic::arm_mve_vld2q: 16332 case Intrinsic::arm_mve_vld4q: 16333 case Intrinsic::arm_mve_vst2q: 16334 case Intrinsic::arm_mve_vst4q: 16335 return PerformMVEVLDCombine(N, DCI); 16336 default: break; 16337 } 16338 break; 16339 } 16340 return SDValue(); 16341 } 16342 16343 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 16344 EVT VT) const { 16345 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 16346 } 16347 16348 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 16349 unsigned Alignment, 16350 MachineMemOperand::Flags, 16351 bool *Fast) const { 16352 // Depends what it gets converted into if the type is weird. 16353 if (!VT.isSimple()) 16354 return false; 16355 16356 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus 16357 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 16358 auto Ty = VT.getSimpleVT().SimpleTy; 16359 16360 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 16361 // Unaligned access can use (for example) LRDB, LRDH, LDR 16362 if (AllowsUnaligned) { 16363 if (Fast) 16364 *Fast = Subtarget->hasV7Ops(); 16365 return true; 16366 } 16367 } 16368 16369 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 16370 // For any little-endian targets with neon, we can support unaligned ld/st 16371 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 16372 // A big-endian target may also explicitly support unaligned accesses 16373 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 16374 if (Fast) 16375 *Fast = true; 16376 return true; 16377 } 16378 } 16379 16380 if (!Subtarget->hasMVEIntegerOps()) 16381 return false; 16382 16383 // These are for predicates 16384 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 16385 if (Fast) 16386 *Fast = true; 16387 return true; 16388 } 16389 16390 // These are for truncated stores/narrowing loads. They are fine so long as 16391 // the alignment is at least the size of the item being loaded 16392 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) && 16393 Alignment >= VT.getScalarSizeInBits() / 8) { 16394 if (Fast) 16395 *Fast = true; 16396 return true; 16397 } 16398 16399 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and 16400 // VSTRW.U32 all store the vector register in exactly the same format, and 16401 // differ only in the range of their immediate offset field and the required 16402 // alignment. So there is always a store that can be used, regardless of 16403 // actual type. 16404 // 16405 // For big endian, that is not the case. But can still emit a (VSTRB.U8; 16406 // VREV64.8) pair and get the same effect. This will likely be better than 16407 // aligning the vector through the stack. 16408 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 || 16409 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 || 16410 Ty == MVT::v2f64) { 16411 if (Fast) 16412 *Fast = true; 16413 return true; 16414 } 16415 16416 return false; 16417 } 16418 16419 16420 EVT ARMTargetLowering::getOptimalMemOpType( 16421 const MemOp &Op, const AttributeList &FuncAttributes) const { 16422 // See if we can use NEON instructions for this... 16423 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() && 16424 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 16425 bool Fast; 16426 if (Op.size() >= 16 && 16427 (Op.isAligned(Align(16)) || 16428 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 16429 MachineMemOperand::MONone, &Fast) && 16430 Fast))) { 16431 return MVT::v2f64; 16432 } else if (Op.size() >= 8 && 16433 (Op.isAligned(Align(8)) || 16434 (allowsMisalignedMemoryAccesses( 16435 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 16436 Fast))) { 16437 return MVT::f64; 16438 } 16439 } 16440 16441 // Let the target-independent logic figure it out. 16442 return MVT::Other; 16443 } 16444 16445 // 64-bit integers are split into their high and low parts and held in two 16446 // different registers, so the trunc is free since the low register can just 16447 // be used. 16448 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 16449 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 16450 return false; 16451 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 16452 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 16453 return (SrcBits == 64 && DestBits == 32); 16454 } 16455 16456 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 16457 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 16458 !DstVT.isInteger()) 16459 return false; 16460 unsigned SrcBits = SrcVT.getSizeInBits(); 16461 unsigned DestBits = DstVT.getSizeInBits(); 16462 return (SrcBits == 64 && DestBits == 32); 16463 } 16464 16465 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16466 if (Val.getOpcode() != ISD::LOAD) 16467 return false; 16468 16469 EVT VT1 = Val.getValueType(); 16470 if (!VT1.isSimple() || !VT1.isInteger() || 16471 !VT2.isSimple() || !VT2.isInteger()) 16472 return false; 16473 16474 switch (VT1.getSimpleVT().SimpleTy) { 16475 default: break; 16476 case MVT::i1: 16477 case MVT::i8: 16478 case MVT::i16: 16479 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 16480 return true; 16481 } 16482 16483 return false; 16484 } 16485 16486 bool ARMTargetLowering::isFNegFree(EVT VT) const { 16487 if (!VT.isSimple()) 16488 return false; 16489 16490 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 16491 // negate values directly (fneg is free). So, we don't want to let the DAG 16492 // combiner rewrite fneg into xors and some other instructions. For f16 and 16493 // FullFP16 argument passing, some bitcast nodes may be introduced, 16494 // triggering this DAG combine rewrite, so we are avoiding that with this. 16495 switch (VT.getSimpleVT().SimpleTy) { 16496 default: break; 16497 case MVT::f16: 16498 return Subtarget->hasFullFP16(); 16499 } 16500 16501 return false; 16502 } 16503 16504 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 16505 /// of the vector elements. 16506 static bool areExtractExts(Value *Ext1, Value *Ext2) { 16507 auto areExtDoubled = [](Instruction *Ext) { 16508 return Ext->getType()->getScalarSizeInBits() == 16509 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 16510 }; 16511 16512 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 16513 !match(Ext2, m_ZExtOrSExt(m_Value())) || 16514 !areExtDoubled(cast<Instruction>(Ext1)) || 16515 !areExtDoubled(cast<Instruction>(Ext2))) 16516 return false; 16517 16518 return true; 16519 } 16520 16521 /// Check if sinking \p I's operands to I's basic block is profitable, because 16522 /// the operands can be folded into a target instruction, e.g. 16523 /// sext/zext can be folded into vsubl. 16524 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 16525 SmallVectorImpl<Use *> &Ops) const { 16526 if (!I->getType()->isVectorTy()) 16527 return false; 16528 16529 if (Subtarget->hasNEON()) { 16530 switch (I->getOpcode()) { 16531 case Instruction::Sub: 16532 case Instruction::Add: { 16533 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 16534 return false; 16535 Ops.push_back(&I->getOperandUse(0)); 16536 Ops.push_back(&I->getOperandUse(1)); 16537 return true; 16538 } 16539 default: 16540 return false; 16541 } 16542 } 16543 16544 if (!Subtarget->hasMVEIntegerOps()) 16545 return false; 16546 16547 auto IsFMSMul = [&](Instruction *I) { 16548 if (!I->hasOneUse()) 16549 return false; 16550 auto *Sub = cast<Instruction>(*I->users().begin()); 16551 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I; 16552 }; 16553 auto IsFMS = [&](Instruction *I) { 16554 if (match(I->getOperand(0), m_FNeg(m_Value())) || 16555 match(I->getOperand(1), m_FNeg(m_Value()))) 16556 return true; 16557 return false; 16558 }; 16559 16560 auto IsSinker = [&](Instruction *I, int Operand) { 16561 switch (I->getOpcode()) { 16562 case Instruction::Add: 16563 case Instruction::Mul: 16564 case Instruction::FAdd: 16565 case Instruction::ICmp: 16566 case Instruction::FCmp: 16567 return true; 16568 case Instruction::FMul: 16569 return !IsFMSMul(I); 16570 case Instruction::Sub: 16571 case Instruction::FSub: 16572 case Instruction::Shl: 16573 case Instruction::LShr: 16574 case Instruction::AShr: 16575 return Operand == 1; 16576 case Instruction::Call: 16577 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 16578 switch (II->getIntrinsicID()) { 16579 case Intrinsic::fma: 16580 return !IsFMS(I); 16581 case Intrinsic::arm_mve_add_predicated: 16582 case Intrinsic::arm_mve_mul_predicated: 16583 case Intrinsic::arm_mve_qadd_predicated: 16584 case Intrinsic::arm_mve_hadd_predicated: 16585 case Intrinsic::arm_mve_vqdmull_predicated: 16586 case Intrinsic::arm_mve_qdmulh_predicated: 16587 case Intrinsic::arm_mve_qrdmulh_predicated: 16588 case Intrinsic::arm_mve_fma_predicated: 16589 return true; 16590 case Intrinsic::arm_mve_sub_predicated: 16591 case Intrinsic::arm_mve_qsub_predicated: 16592 case Intrinsic::arm_mve_hsub_predicated: 16593 return Operand == 1; 16594 default: 16595 return false; 16596 } 16597 } 16598 return false; 16599 default: 16600 return false; 16601 } 16602 }; 16603 16604 for (auto OpIdx : enumerate(I->operands())) { 16605 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 16606 // Make sure we are not already sinking this operand 16607 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 16608 continue; 16609 16610 Instruction *Shuffle = Op; 16611 if (Shuffle->getOpcode() == Instruction::BitCast) 16612 Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0)); 16613 // We are looking for a splat that can be sunk. 16614 if (!Shuffle || 16615 !match(Shuffle, m_Shuffle( 16616 m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 16617 m_Undef(), m_ZeroMask()))) 16618 continue; 16619 if (!IsSinker(I, OpIdx.index())) 16620 continue; 16621 16622 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 16623 // and vector registers 16624 for (Use &U : Op->uses()) { 16625 Instruction *Insn = cast<Instruction>(U.getUser()); 16626 if (!IsSinker(Insn, U.getOperandNo())) 16627 return false; 16628 } 16629 16630 Ops.push_back(&Shuffle->getOperandUse(0)); 16631 if (Shuffle != Op) 16632 Ops.push_back(&Op->getOperandUse(0)); 16633 Ops.push_back(&OpIdx.value()); 16634 } 16635 return true; 16636 } 16637 16638 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const { 16639 if (!Subtarget->hasMVEIntegerOps()) 16640 return nullptr; 16641 Type *SVIType = SVI->getType(); 16642 Type *ScalarType = SVIType->getScalarType(); 16643 16644 if (ScalarType->isFloatTy()) 16645 return Type::getInt32Ty(SVIType->getContext()); 16646 if (ScalarType->isHalfTy()) 16647 return Type::getInt16Ty(SVIType->getContext()); 16648 return nullptr; 16649 } 16650 16651 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 16652 EVT VT = ExtVal.getValueType(); 16653 16654 if (!isTypeLegal(VT)) 16655 return false; 16656 16657 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) { 16658 if (Ld->isExpandingLoad()) 16659 return false; 16660 } 16661 16662 if (Subtarget->hasMVEIntegerOps()) 16663 return true; 16664 16665 // Don't create a loadext if we can fold the extension into a wide/long 16666 // instruction. 16667 // If there's more than one user instruction, the loadext is desirable no 16668 // matter what. There can be two uses by the same instruction. 16669 if (ExtVal->use_empty() || 16670 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 16671 return true; 16672 16673 SDNode *U = *ExtVal->use_begin(); 16674 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 16675 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 16676 return false; 16677 16678 return true; 16679 } 16680 16681 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 16682 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16683 return false; 16684 16685 if (!isTypeLegal(EVT::getEVT(Ty1))) 16686 return false; 16687 16688 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 16689 16690 // Assuming the caller doesn't have a zeroext or signext return parameter, 16691 // truncation all the way down to i1 is valid. 16692 return true; 16693 } 16694 16695 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 16696 const AddrMode &AM, Type *Ty, 16697 unsigned AS) const { 16698 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 16699 if (Subtarget->hasFPAO()) 16700 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 16701 return 0; 16702 } 16703 return -1; 16704 } 16705 16706 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster 16707 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be 16708 /// expanded to FMAs when this method returns true, otherwise fmuladd is 16709 /// expanded to fmul + fadd. 16710 /// 16711 /// ARM supports both fused and unfused multiply-add operations; we already 16712 /// lower a pair of fmul and fadd to the latter so it's not clear that there 16713 /// would be a gain or that the gain would be worthwhile enough to risk 16714 /// correctness bugs. 16715 /// 16716 /// For MVE, we set this to true as it helps simplify the need for some 16717 /// patterns (and we don't have the non-fused floating point instruction). 16718 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16719 EVT VT) const { 16720 if (!VT.isSimple()) 16721 return false; 16722 16723 switch (VT.getSimpleVT().SimpleTy) { 16724 case MVT::v4f32: 16725 case MVT::v8f16: 16726 return Subtarget->hasMVEFloatOps(); 16727 case MVT::f16: 16728 return Subtarget->useFPVFMx16(); 16729 case MVT::f32: 16730 return Subtarget->useFPVFMx(); 16731 case MVT::f64: 16732 return Subtarget->useFPVFMx64(); 16733 default: 16734 break; 16735 } 16736 16737 return false; 16738 } 16739 16740 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 16741 if (V < 0) 16742 return false; 16743 16744 unsigned Scale = 1; 16745 switch (VT.getSimpleVT().SimpleTy) { 16746 case MVT::i1: 16747 case MVT::i8: 16748 // Scale == 1; 16749 break; 16750 case MVT::i16: 16751 // Scale == 2; 16752 Scale = 2; 16753 break; 16754 default: 16755 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 16756 // Scale == 4; 16757 Scale = 4; 16758 break; 16759 } 16760 16761 if ((V & (Scale - 1)) != 0) 16762 return false; 16763 return isUInt<5>(V / Scale); 16764 } 16765 16766 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 16767 const ARMSubtarget *Subtarget) { 16768 if (!VT.isInteger() && !VT.isFloatingPoint()) 16769 return false; 16770 if (VT.isVector() && Subtarget->hasNEON()) 16771 return false; 16772 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 16773 !Subtarget->hasMVEFloatOps()) 16774 return false; 16775 16776 bool IsNeg = false; 16777 if (V < 0) { 16778 IsNeg = true; 16779 V = -V; 16780 } 16781 16782 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U); 16783 16784 // MVE: size * imm7 16785 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 16786 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 16787 case MVT::i32: 16788 case MVT::f32: 16789 return isShiftedUInt<7,2>(V); 16790 case MVT::i16: 16791 case MVT::f16: 16792 return isShiftedUInt<7,1>(V); 16793 case MVT::i8: 16794 return isUInt<7>(V); 16795 default: 16796 return false; 16797 } 16798 } 16799 16800 // half VLDR: 2 * imm8 16801 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 16802 return isShiftedUInt<8, 1>(V); 16803 // VLDR and LDRD: 4 * imm8 16804 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 16805 return isShiftedUInt<8, 2>(V); 16806 16807 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 16808 // + imm12 or - imm8 16809 if (IsNeg) 16810 return isUInt<8>(V); 16811 return isUInt<12>(V); 16812 } 16813 16814 return false; 16815 } 16816 16817 /// isLegalAddressImmediate - Return true if the integer value can be used 16818 /// as the offset of the target addressing mode for load / store of the 16819 /// given type. 16820 static bool isLegalAddressImmediate(int64_t V, EVT VT, 16821 const ARMSubtarget *Subtarget) { 16822 if (V == 0) 16823 return true; 16824 16825 if (!VT.isSimple()) 16826 return false; 16827 16828 if (Subtarget->isThumb1Only()) 16829 return isLegalT1AddressImmediate(V, VT); 16830 else if (Subtarget->isThumb2()) 16831 return isLegalT2AddressImmediate(V, VT, Subtarget); 16832 16833 // ARM mode. 16834 if (V < 0) 16835 V = - V; 16836 switch (VT.getSimpleVT().SimpleTy) { 16837 default: return false; 16838 case MVT::i1: 16839 case MVT::i8: 16840 case MVT::i32: 16841 // +- imm12 16842 return isUInt<12>(V); 16843 case MVT::i16: 16844 // +- imm8 16845 return isUInt<8>(V); 16846 case MVT::f32: 16847 case MVT::f64: 16848 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 16849 return false; 16850 return isShiftedUInt<8, 2>(V); 16851 } 16852 } 16853 16854 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 16855 EVT VT) const { 16856 int Scale = AM.Scale; 16857 if (Scale < 0) 16858 return false; 16859 16860 switch (VT.getSimpleVT().SimpleTy) { 16861 default: return false; 16862 case MVT::i1: 16863 case MVT::i8: 16864 case MVT::i16: 16865 case MVT::i32: 16866 if (Scale == 1) 16867 return true; 16868 // r + r << imm 16869 Scale = Scale & ~1; 16870 return Scale == 2 || Scale == 4 || Scale == 8; 16871 case MVT::i64: 16872 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 16873 // version in Thumb mode. 16874 // r + r 16875 if (Scale == 1) 16876 return true; 16877 // r * 2 (this can be lowered to r + r). 16878 if (!AM.HasBaseReg && Scale == 2) 16879 return true; 16880 return false; 16881 case MVT::isVoid: 16882 // Note, we allow "void" uses (basically, uses that aren't loads or 16883 // stores), because arm allows folding a scale into many arithmetic 16884 // operations. This should be made more precise and revisited later. 16885 16886 // Allow r << imm, but the imm has to be a multiple of two. 16887 if (Scale & 1) return false; 16888 return isPowerOf2_32(Scale); 16889 } 16890 } 16891 16892 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 16893 EVT VT) const { 16894 const int Scale = AM.Scale; 16895 16896 // Negative scales are not supported in Thumb1. 16897 if (Scale < 0) 16898 return false; 16899 16900 // Thumb1 addressing modes do not support register scaling excepting the 16901 // following cases: 16902 // 1. Scale == 1 means no scaling. 16903 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 16904 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 16905 } 16906 16907 /// isLegalAddressingMode - Return true if the addressing mode represented 16908 /// by AM is legal for this target, for a load/store of the specified type. 16909 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 16910 const AddrMode &AM, Type *Ty, 16911 unsigned AS, Instruction *I) const { 16912 EVT VT = getValueType(DL, Ty, true); 16913 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 16914 return false; 16915 16916 // Can never fold addr of global into load/store. 16917 if (AM.BaseGV) 16918 return false; 16919 16920 switch (AM.Scale) { 16921 case 0: // no scale reg, must be "r+i" or "r", or "i". 16922 break; 16923 default: 16924 // ARM doesn't support any R+R*scale+imm addr modes. 16925 if (AM.BaseOffs) 16926 return false; 16927 16928 if (!VT.isSimple()) 16929 return false; 16930 16931 if (Subtarget->isThumb1Only()) 16932 return isLegalT1ScaledAddressingMode(AM, VT); 16933 16934 if (Subtarget->isThumb2()) 16935 return isLegalT2ScaledAddressingMode(AM, VT); 16936 16937 int Scale = AM.Scale; 16938 switch (VT.getSimpleVT().SimpleTy) { 16939 default: return false; 16940 case MVT::i1: 16941 case MVT::i8: 16942 case MVT::i32: 16943 if (Scale < 0) Scale = -Scale; 16944 if (Scale == 1) 16945 return true; 16946 // r + r << imm 16947 return isPowerOf2_32(Scale & ~1); 16948 case MVT::i16: 16949 case MVT::i64: 16950 // r +/- r 16951 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 16952 return true; 16953 // r * 2 (this can be lowered to r + r). 16954 if (!AM.HasBaseReg && Scale == 2) 16955 return true; 16956 return false; 16957 16958 case MVT::isVoid: 16959 // Note, we allow "void" uses (basically, uses that aren't loads or 16960 // stores), because arm allows folding a scale into many arithmetic 16961 // operations. This should be made more precise and revisited later. 16962 16963 // Allow r << imm, but the imm has to be a multiple of two. 16964 if (Scale & 1) return false; 16965 return isPowerOf2_32(Scale); 16966 } 16967 } 16968 return true; 16969 } 16970 16971 /// isLegalICmpImmediate - Return true if the specified immediate is legal 16972 /// icmp immediate, that is the target has icmp instructions which can compare 16973 /// a register against the immediate without having to materialize the 16974 /// immediate into a register. 16975 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16976 // Thumb2 and ARM modes can use cmn for negative immediates. 16977 if (!Subtarget->isThumb()) 16978 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 16979 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 16980 if (Subtarget->isThumb2()) 16981 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 16982 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 16983 // Thumb1 doesn't have cmn, and only 8-bit immediates. 16984 return Imm >= 0 && Imm <= 255; 16985 } 16986 16987 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 16988 /// *or sub* immediate, that is the target has add or sub instructions which can 16989 /// add a register with the immediate without having to materialize the 16990 /// immediate into a register. 16991 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16992 // Same encoding for add/sub, just flip the sign. 16993 int64_t AbsImm = std::abs(Imm); 16994 if (!Subtarget->isThumb()) 16995 return ARM_AM::getSOImmVal(AbsImm) != -1; 16996 if (Subtarget->isThumb2()) 16997 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 16998 // Thumb1 only has 8-bit unsigned immediate. 16999 return AbsImm >= 0 && AbsImm <= 255; 17000 } 17001 17002 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 17003 bool isSEXTLoad, SDValue &Base, 17004 SDValue &Offset, bool &isInc, 17005 SelectionDAG &DAG) { 17006 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17007 return false; 17008 17009 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 17010 // AddressingMode 3 17011 Base = Ptr->getOperand(0); 17012 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17013 int RHSC = (int)RHS->getZExtValue(); 17014 if (RHSC < 0 && RHSC > -256) { 17015 assert(Ptr->getOpcode() == ISD::ADD); 17016 isInc = false; 17017 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17018 return true; 17019 } 17020 } 17021 isInc = (Ptr->getOpcode() == ISD::ADD); 17022 Offset = Ptr->getOperand(1); 17023 return true; 17024 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 17025 // AddressingMode 2 17026 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17027 int RHSC = (int)RHS->getZExtValue(); 17028 if (RHSC < 0 && RHSC > -0x1000) { 17029 assert(Ptr->getOpcode() == ISD::ADD); 17030 isInc = false; 17031 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17032 Base = Ptr->getOperand(0); 17033 return true; 17034 } 17035 } 17036 17037 if (Ptr->getOpcode() == ISD::ADD) { 17038 isInc = true; 17039 ARM_AM::ShiftOpc ShOpcVal= 17040 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 17041 if (ShOpcVal != ARM_AM::no_shift) { 17042 Base = Ptr->getOperand(1); 17043 Offset = Ptr->getOperand(0); 17044 } else { 17045 Base = Ptr->getOperand(0); 17046 Offset = Ptr->getOperand(1); 17047 } 17048 return true; 17049 } 17050 17051 isInc = (Ptr->getOpcode() == ISD::ADD); 17052 Base = Ptr->getOperand(0); 17053 Offset = Ptr->getOperand(1); 17054 return true; 17055 } 17056 17057 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 17058 return false; 17059 } 17060 17061 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 17062 bool isSEXTLoad, SDValue &Base, 17063 SDValue &Offset, bool &isInc, 17064 SelectionDAG &DAG) { 17065 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17066 return false; 17067 17068 Base = Ptr->getOperand(0); 17069 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17070 int RHSC = (int)RHS->getZExtValue(); 17071 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 17072 assert(Ptr->getOpcode() == ISD::ADD); 17073 isInc = false; 17074 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17075 return true; 17076 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 17077 isInc = Ptr->getOpcode() == ISD::ADD; 17078 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17079 return true; 17080 } 17081 } 17082 17083 return false; 17084 } 17085 17086 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment, 17087 bool isSEXTLoad, bool IsMasked, bool isLE, 17088 SDValue &Base, SDValue &Offset, 17089 bool &isInc, SelectionDAG &DAG) { 17090 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17091 return false; 17092 if (!isa<ConstantSDNode>(Ptr->getOperand(1))) 17093 return false; 17094 17095 // We allow LE non-masked loads to change the type (for example use a vldrb.8 17096 // as opposed to a vldrw.32). This can allow extra addressing modes or 17097 // alignments for what is otherwise an equivalent instruction. 17098 bool CanChangeType = isLE && !IsMasked; 17099 17100 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1)); 17101 int RHSC = (int)RHS->getZExtValue(); 17102 17103 auto IsInRange = [&](int RHSC, int Limit, int Scale) { 17104 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) { 17105 assert(Ptr->getOpcode() == ISD::ADD); 17106 isInc = false; 17107 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17108 return true; 17109 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) { 17110 isInc = Ptr->getOpcode() == ISD::ADD; 17111 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17112 return true; 17113 } 17114 return false; 17115 }; 17116 17117 // Try to find a matching instruction based on s/zext, Alignment, Offset and 17118 // (in BE/masked) type. 17119 Base = Ptr->getOperand(0); 17120 if (VT == MVT::v4i16) { 17121 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2)) 17122 return true; 17123 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) { 17124 if (IsInRange(RHSC, 0x80, 1)) 17125 return true; 17126 } else if (Alignment >= 4 && 17127 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) && 17128 IsInRange(RHSC, 0x80, 4)) 17129 return true; 17130 else if (Alignment >= 2 && 17131 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) && 17132 IsInRange(RHSC, 0x80, 2)) 17133 return true; 17134 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1)) 17135 return true; 17136 return false; 17137 } 17138 17139 /// getPreIndexedAddressParts - returns true by value, base pointer and 17140 /// offset pointer and addressing mode by reference if the node's address 17141 /// can be legally represented as pre-indexed load / store address. 17142 bool 17143 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 17144 SDValue &Offset, 17145 ISD::MemIndexedMode &AM, 17146 SelectionDAG &DAG) const { 17147 if (Subtarget->isThumb1Only()) 17148 return false; 17149 17150 EVT VT; 17151 SDValue Ptr; 17152 Align Alignment; 17153 bool isSEXTLoad = false; 17154 bool IsMasked = false; 17155 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 17156 Ptr = LD->getBasePtr(); 17157 VT = LD->getMemoryVT(); 17158 Alignment = LD->getAlign(); 17159 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17160 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 17161 Ptr = ST->getBasePtr(); 17162 VT = ST->getMemoryVT(); 17163 Alignment = ST->getAlign(); 17164 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 17165 Ptr = LD->getBasePtr(); 17166 VT = LD->getMemoryVT(); 17167 Alignment = LD->getAlign(); 17168 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17169 IsMasked = true; 17170 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 17171 Ptr = ST->getBasePtr(); 17172 VT = ST->getMemoryVT(); 17173 Alignment = ST->getAlign(); 17174 IsMasked = true; 17175 } else 17176 return false; 17177 17178 bool isInc; 17179 bool isLegal = false; 17180 if (VT.isVector()) 17181 isLegal = Subtarget->hasMVEIntegerOps() && 17182 getMVEIndexedAddressParts( 17183 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked, 17184 Subtarget->isLittle(), Base, Offset, isInc, DAG); 17185 else { 17186 if (Subtarget->isThumb2()) 17187 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 17188 Offset, isInc, DAG); 17189 else 17190 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 17191 Offset, isInc, DAG); 17192 } 17193 if (!isLegal) 17194 return false; 17195 17196 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 17197 return true; 17198 } 17199 17200 /// getPostIndexedAddressParts - returns true by value, base pointer and 17201 /// offset pointer and addressing mode by reference if this node can be 17202 /// combined with a load / store to form a post-indexed load / store. 17203 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 17204 SDValue &Base, 17205 SDValue &Offset, 17206 ISD::MemIndexedMode &AM, 17207 SelectionDAG &DAG) const { 17208 EVT VT; 17209 SDValue Ptr; 17210 Align Alignment; 17211 bool isSEXTLoad = false, isNonExt; 17212 bool IsMasked = false; 17213 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 17214 VT = LD->getMemoryVT(); 17215 Ptr = LD->getBasePtr(); 17216 Alignment = LD->getAlign(); 17217 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17218 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 17219 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 17220 VT = ST->getMemoryVT(); 17221 Ptr = ST->getBasePtr(); 17222 Alignment = ST->getAlign(); 17223 isNonExt = !ST->isTruncatingStore(); 17224 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 17225 VT = LD->getMemoryVT(); 17226 Ptr = LD->getBasePtr(); 17227 Alignment = LD->getAlign(); 17228 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17229 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 17230 IsMasked = true; 17231 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 17232 VT = ST->getMemoryVT(); 17233 Ptr = ST->getBasePtr(); 17234 Alignment = ST->getAlign(); 17235 isNonExt = !ST->isTruncatingStore(); 17236 IsMasked = true; 17237 } else 17238 return false; 17239 17240 if (Subtarget->isThumb1Only()) { 17241 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 17242 // must be non-extending/truncating, i32, with an offset of 4. 17243 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 17244 if (Op->getOpcode() != ISD::ADD || !isNonExt) 17245 return false; 17246 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 17247 if (!RHS || RHS->getZExtValue() != 4) 17248 return false; 17249 17250 Offset = Op->getOperand(1); 17251 Base = Op->getOperand(0); 17252 AM = ISD::POST_INC; 17253 return true; 17254 } 17255 17256 bool isInc; 17257 bool isLegal = false; 17258 if (VT.isVector()) 17259 isLegal = Subtarget->hasMVEIntegerOps() && 17260 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked, 17261 Subtarget->isLittle(), Base, Offset, 17262 isInc, DAG); 17263 else { 17264 if (Subtarget->isThumb2()) 17265 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 17266 isInc, DAG); 17267 else 17268 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 17269 isInc, DAG); 17270 } 17271 if (!isLegal) 17272 return false; 17273 17274 if (Ptr != Base) { 17275 // Swap base ptr and offset to catch more post-index load / store when 17276 // it's legal. In Thumb2 mode, offset must be an immediate. 17277 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 17278 !Subtarget->isThumb2()) 17279 std::swap(Base, Offset); 17280 17281 // Post-indexed load / store update the base pointer. 17282 if (Ptr != Base) 17283 return false; 17284 } 17285 17286 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 17287 return true; 17288 } 17289 17290 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 17291 KnownBits &Known, 17292 const APInt &DemandedElts, 17293 const SelectionDAG &DAG, 17294 unsigned Depth) const { 17295 unsigned BitWidth = Known.getBitWidth(); 17296 Known.resetAll(); 17297 switch (Op.getOpcode()) { 17298 default: break; 17299 case ARMISD::ADDC: 17300 case ARMISD::ADDE: 17301 case ARMISD::SUBC: 17302 case ARMISD::SUBE: 17303 // Special cases when we convert a carry to a boolean. 17304 if (Op.getResNo() == 0) { 17305 SDValue LHS = Op.getOperand(0); 17306 SDValue RHS = Op.getOperand(1); 17307 // (ADDE 0, 0, C) will give us a single bit. 17308 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 17309 isNullConstant(RHS)) { 17310 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 17311 return; 17312 } 17313 } 17314 break; 17315 case ARMISD::CMOV: { 17316 // Bits are known zero/one if known on the LHS and RHS. 17317 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 17318 if (Known.isUnknown()) 17319 return; 17320 17321 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 17322 Known.Zero &= KnownRHS.Zero; 17323 Known.One &= KnownRHS.One; 17324 return; 17325 } 17326 case ISD::INTRINSIC_W_CHAIN: { 17327 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 17328 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 17329 switch (IntID) { 17330 default: return; 17331 case Intrinsic::arm_ldaex: 17332 case Intrinsic::arm_ldrex: { 17333 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 17334 unsigned MemBits = VT.getScalarSizeInBits(); 17335 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 17336 return; 17337 } 17338 } 17339 } 17340 case ARMISD::BFI: { 17341 // Conservatively, we can recurse down the first operand 17342 // and just mask out all affected bits. 17343 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 17344 17345 // The operand to BFI is already a mask suitable for removing the bits it 17346 // sets. 17347 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 17348 const APInt &Mask = CI->getAPIntValue(); 17349 Known.Zero &= Mask; 17350 Known.One &= Mask; 17351 return; 17352 } 17353 case ARMISD::VGETLANEs: 17354 case ARMISD::VGETLANEu: { 17355 const SDValue &SrcSV = Op.getOperand(0); 17356 EVT VecVT = SrcSV.getValueType(); 17357 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 17358 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 17359 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 17360 assert(Pos->getAPIntValue().ult(NumSrcElts) && 17361 "VGETLANE index out of bounds"); 17362 unsigned Idx = Pos->getZExtValue(); 17363 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 17364 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 17365 17366 EVT VT = Op.getValueType(); 17367 const unsigned DstSz = VT.getScalarSizeInBits(); 17368 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 17369 (void)SrcSz; 17370 assert(SrcSz == Known.getBitWidth()); 17371 assert(DstSz > SrcSz); 17372 if (Op.getOpcode() == ARMISD::VGETLANEs) 17373 Known = Known.sext(DstSz); 17374 else { 17375 Known = Known.zext(DstSz); 17376 } 17377 assert(DstSz == Known.getBitWidth()); 17378 break; 17379 } 17380 case ARMISD::VMOVrh: { 17381 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 17382 assert(KnownOp.getBitWidth() == 16); 17383 Known = KnownOp.zext(32); 17384 break; 17385 } 17386 } 17387 } 17388 17389 bool ARMTargetLowering::targetShrinkDemandedConstant( 17390 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 17391 TargetLoweringOpt &TLO) const { 17392 // Delay optimization, so we don't have to deal with illegal types, or block 17393 // optimizations. 17394 if (!TLO.LegalOps) 17395 return false; 17396 17397 // Only optimize AND for now. 17398 if (Op.getOpcode() != ISD::AND) 17399 return false; 17400 17401 EVT VT = Op.getValueType(); 17402 17403 // Ignore vectors. 17404 if (VT.isVector()) 17405 return false; 17406 17407 assert(VT == MVT::i32 && "Unexpected integer type"); 17408 17409 // Make sure the RHS really is a constant. 17410 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 17411 if (!C) 17412 return false; 17413 17414 unsigned Mask = C->getZExtValue(); 17415 17416 unsigned Demanded = DemandedBits.getZExtValue(); 17417 unsigned ShrunkMask = Mask & Demanded; 17418 unsigned ExpandedMask = Mask | ~Demanded; 17419 17420 // If the mask is all zeros, let the target-independent code replace the 17421 // result with zero. 17422 if (ShrunkMask == 0) 17423 return false; 17424 17425 // If the mask is all ones, erase the AND. (Currently, the target-independent 17426 // code won't do this, so we have to do it explicitly to avoid an infinite 17427 // loop in obscure cases.) 17428 if (ExpandedMask == ~0U) 17429 return TLO.CombineTo(Op, Op.getOperand(0)); 17430 17431 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 17432 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 17433 }; 17434 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 17435 if (NewMask == Mask) 17436 return true; 17437 SDLoc DL(Op); 17438 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 17439 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 17440 return TLO.CombineTo(Op, NewOp); 17441 }; 17442 17443 // Prefer uxtb mask. 17444 if (IsLegalMask(0xFF)) 17445 return UseMask(0xFF); 17446 17447 // Prefer uxth mask. 17448 if (IsLegalMask(0xFFFF)) 17449 return UseMask(0xFFFF); 17450 17451 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 17452 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 17453 if (ShrunkMask < 256) 17454 return UseMask(ShrunkMask); 17455 17456 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 17457 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 17458 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 17459 return UseMask(ExpandedMask); 17460 17461 // Potential improvements: 17462 // 17463 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 17464 // We could try to prefer Thumb1 immediates which can be lowered to a 17465 // two-instruction sequence. 17466 // We could try to recognize more legal ARM/Thumb2 immediates here. 17467 17468 return false; 17469 } 17470 17471 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode( 17472 SDValue Op, const APInt &OriginalDemandedBits, 17473 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 17474 unsigned Depth) const { 17475 unsigned Opc = Op.getOpcode(); 17476 17477 switch (Opc) { 17478 case ARMISD::ASRL: 17479 case ARMISD::LSRL: { 17480 // If this is result 0 and the other result is unused, see if the demand 17481 // bits allow us to shrink this long shift into a standard small shift in 17482 // the opposite direction. 17483 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) && 17484 isa<ConstantSDNode>(Op->getOperand(2))) { 17485 unsigned ShAmt = Op->getConstantOperandVal(2); 17486 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf( 17487 APInt::getAllOnesValue(32) << (32 - ShAmt))) 17488 return TLO.CombineTo( 17489 Op, TLO.DAG.getNode( 17490 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1), 17491 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32))); 17492 } 17493 break; 17494 } 17495 } 17496 17497 return TargetLowering::SimplifyDemandedBitsForTargetNode( 17498 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth); 17499 } 17500 17501 //===----------------------------------------------------------------------===// 17502 // ARM Inline Assembly Support 17503 //===----------------------------------------------------------------------===// 17504 17505 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 17506 // Looking for "rev" which is V6+. 17507 if (!Subtarget->hasV6Ops()) 17508 return false; 17509 17510 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand()); 17511 std::string AsmStr = IA->getAsmString(); 17512 SmallVector<StringRef, 4> AsmPieces; 17513 SplitString(AsmStr, AsmPieces, ";\n"); 17514 17515 switch (AsmPieces.size()) { 17516 default: return false; 17517 case 1: 17518 AsmStr = std::string(AsmPieces[0]); 17519 AsmPieces.clear(); 17520 SplitString(AsmStr, AsmPieces, " \t,"); 17521 17522 // rev $0, $1 17523 if (AsmPieces.size() == 3 && 17524 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 17525 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 17526 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 17527 if (Ty && Ty->getBitWidth() == 32) 17528 return IntrinsicLowering::LowerToByteSwap(CI); 17529 } 17530 break; 17531 } 17532 17533 return false; 17534 } 17535 17536 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 17537 // At this point, we have to lower this constraint to something else, so we 17538 // lower it to an "r" or "w". However, by doing this we will force the result 17539 // to be in register, while the X constraint is much more permissive. 17540 // 17541 // Although we are correct (we are free to emit anything, without 17542 // constraints), we might break use cases that would expect us to be more 17543 // efficient and emit something else. 17544 if (!Subtarget->hasVFP2Base()) 17545 return "r"; 17546 if (ConstraintVT.isFloatingPoint()) 17547 return "w"; 17548 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 17549 (ConstraintVT.getSizeInBits() == 64 || 17550 ConstraintVT.getSizeInBits() == 128)) 17551 return "w"; 17552 17553 return "r"; 17554 } 17555 17556 /// getConstraintType - Given a constraint letter, return the type of 17557 /// constraint it is for this target. 17558 ARMTargetLowering::ConstraintType 17559 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 17560 unsigned S = Constraint.size(); 17561 if (S == 1) { 17562 switch (Constraint[0]) { 17563 default: break; 17564 case 'l': return C_RegisterClass; 17565 case 'w': return C_RegisterClass; 17566 case 'h': return C_RegisterClass; 17567 case 'x': return C_RegisterClass; 17568 case 't': return C_RegisterClass; 17569 case 'j': return C_Immediate; // Constant for movw. 17570 // An address with a single base register. Due to the way we 17571 // currently handle addresses it is the same as an 'r' memory constraint. 17572 case 'Q': return C_Memory; 17573 } 17574 } else if (S == 2) { 17575 switch (Constraint[0]) { 17576 default: break; 17577 case 'T': return C_RegisterClass; 17578 // All 'U+' constraints are addresses. 17579 case 'U': return C_Memory; 17580 } 17581 } 17582 return TargetLowering::getConstraintType(Constraint); 17583 } 17584 17585 /// Examine constraint type and operand type and determine a weight value. 17586 /// This object must already have been set up with the operand type 17587 /// and the current alternative constraint selected. 17588 TargetLowering::ConstraintWeight 17589 ARMTargetLowering::getSingleConstraintMatchWeight( 17590 AsmOperandInfo &info, const char *constraint) const { 17591 ConstraintWeight weight = CW_Invalid; 17592 Value *CallOperandVal = info.CallOperandVal; 17593 // If we don't have a value, we can't do a match, 17594 // but allow it at the lowest weight. 17595 if (!CallOperandVal) 17596 return CW_Default; 17597 Type *type = CallOperandVal->getType(); 17598 // Look at the constraint type. 17599 switch (*constraint) { 17600 default: 17601 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 17602 break; 17603 case 'l': 17604 if (type->isIntegerTy()) { 17605 if (Subtarget->isThumb()) 17606 weight = CW_SpecificReg; 17607 else 17608 weight = CW_Register; 17609 } 17610 break; 17611 case 'w': 17612 if (type->isFloatingPointTy()) 17613 weight = CW_Register; 17614 break; 17615 } 17616 return weight; 17617 } 17618 17619 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 17620 17621 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 17622 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 17623 switch (Constraint.size()) { 17624 case 1: 17625 // GCC ARM Constraint Letters 17626 switch (Constraint[0]) { 17627 case 'l': // Low regs or general regs. 17628 if (Subtarget->isThumb()) 17629 return RCPair(0U, &ARM::tGPRRegClass); 17630 return RCPair(0U, &ARM::GPRRegClass); 17631 case 'h': // High regs or no regs. 17632 if (Subtarget->isThumb()) 17633 return RCPair(0U, &ARM::hGPRRegClass); 17634 break; 17635 case 'r': 17636 if (Subtarget->isThumb1Only()) 17637 return RCPair(0U, &ARM::tGPRRegClass); 17638 return RCPair(0U, &ARM::GPRRegClass); 17639 case 'w': 17640 if (VT == MVT::Other) 17641 break; 17642 if (VT == MVT::f32) 17643 return RCPair(0U, &ARM::SPRRegClass); 17644 if (VT.getSizeInBits() == 64) 17645 return RCPair(0U, &ARM::DPRRegClass); 17646 if (VT.getSizeInBits() == 128) 17647 return RCPair(0U, &ARM::QPRRegClass); 17648 break; 17649 case 'x': 17650 if (VT == MVT::Other) 17651 break; 17652 if (VT == MVT::f32) 17653 return RCPair(0U, &ARM::SPR_8RegClass); 17654 if (VT.getSizeInBits() == 64) 17655 return RCPair(0U, &ARM::DPR_8RegClass); 17656 if (VT.getSizeInBits() == 128) 17657 return RCPair(0U, &ARM::QPR_8RegClass); 17658 break; 17659 case 't': 17660 if (VT == MVT::Other) 17661 break; 17662 if (VT == MVT::f32 || VT == MVT::i32) 17663 return RCPair(0U, &ARM::SPRRegClass); 17664 if (VT.getSizeInBits() == 64) 17665 return RCPair(0U, &ARM::DPR_VFP2RegClass); 17666 if (VT.getSizeInBits() == 128) 17667 return RCPair(0U, &ARM::QPR_VFP2RegClass); 17668 break; 17669 } 17670 break; 17671 17672 case 2: 17673 if (Constraint[0] == 'T') { 17674 switch (Constraint[1]) { 17675 default: 17676 break; 17677 case 'e': 17678 return RCPair(0U, &ARM::tGPREvenRegClass); 17679 case 'o': 17680 return RCPair(0U, &ARM::tGPROddRegClass); 17681 } 17682 } 17683 break; 17684 17685 default: 17686 break; 17687 } 17688 17689 if (StringRef("{cc}").equals_lower(Constraint)) 17690 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 17691 17692 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 17693 } 17694 17695 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 17696 /// vector. If it is invalid, don't add anything to Ops. 17697 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 17698 std::string &Constraint, 17699 std::vector<SDValue>&Ops, 17700 SelectionDAG &DAG) const { 17701 SDValue Result; 17702 17703 // Currently only support length 1 constraints. 17704 if (Constraint.length() != 1) return; 17705 17706 char ConstraintLetter = Constraint[0]; 17707 switch (ConstraintLetter) { 17708 default: break; 17709 case 'j': 17710 case 'I': case 'J': case 'K': case 'L': 17711 case 'M': case 'N': case 'O': 17712 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 17713 if (!C) 17714 return; 17715 17716 int64_t CVal64 = C->getSExtValue(); 17717 int CVal = (int) CVal64; 17718 // None of these constraints allow values larger than 32 bits. Check 17719 // that the value fits in an int. 17720 if (CVal != CVal64) 17721 return; 17722 17723 switch (ConstraintLetter) { 17724 case 'j': 17725 // Constant suitable for movw, must be between 0 and 17726 // 65535. 17727 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps())) 17728 if (CVal >= 0 && CVal <= 65535) 17729 break; 17730 return; 17731 case 'I': 17732 if (Subtarget->isThumb1Only()) { 17733 // This must be a constant between 0 and 255, for ADD 17734 // immediates. 17735 if (CVal >= 0 && CVal <= 255) 17736 break; 17737 } else if (Subtarget->isThumb2()) { 17738 // A constant that can be used as an immediate value in a 17739 // data-processing instruction. 17740 if (ARM_AM::getT2SOImmVal(CVal) != -1) 17741 break; 17742 } else { 17743 // A constant that can be used as an immediate value in a 17744 // data-processing instruction. 17745 if (ARM_AM::getSOImmVal(CVal) != -1) 17746 break; 17747 } 17748 return; 17749 17750 case 'J': 17751 if (Subtarget->isThumb1Only()) { 17752 // This must be a constant between -255 and -1, for negated ADD 17753 // immediates. This can be used in GCC with an "n" modifier that 17754 // prints the negated value, for use with SUB instructions. It is 17755 // not useful otherwise but is implemented for compatibility. 17756 if (CVal >= -255 && CVal <= -1) 17757 break; 17758 } else { 17759 // This must be a constant between -4095 and 4095. It is not clear 17760 // what this constraint is intended for. Implemented for 17761 // compatibility with GCC. 17762 if (CVal >= -4095 && CVal <= 4095) 17763 break; 17764 } 17765 return; 17766 17767 case 'K': 17768 if (Subtarget->isThumb1Only()) { 17769 // A 32-bit value where only one byte has a nonzero value. Exclude 17770 // zero to match GCC. This constraint is used by GCC internally for 17771 // constants that can be loaded with a move/shift combination. 17772 // It is not useful otherwise but is implemented for compatibility. 17773 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 17774 break; 17775 } else if (Subtarget->isThumb2()) { 17776 // A constant whose bitwise inverse can be used as an immediate 17777 // value in a data-processing instruction. This can be used in GCC 17778 // with a "B" modifier that prints the inverted value, for use with 17779 // BIC and MVN instructions. It is not useful otherwise but is 17780 // implemented for compatibility. 17781 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 17782 break; 17783 } else { 17784 // A constant whose bitwise inverse can be used as an immediate 17785 // value in a data-processing instruction. This can be used in GCC 17786 // with a "B" modifier that prints the inverted value, for use with 17787 // BIC and MVN instructions. It is not useful otherwise but is 17788 // implemented for compatibility. 17789 if (ARM_AM::getSOImmVal(~CVal) != -1) 17790 break; 17791 } 17792 return; 17793 17794 case 'L': 17795 if (Subtarget->isThumb1Only()) { 17796 // This must be a constant between -7 and 7, 17797 // for 3-operand ADD/SUB immediate instructions. 17798 if (CVal >= -7 && CVal < 7) 17799 break; 17800 } else if (Subtarget->isThumb2()) { 17801 // A constant whose negation can be used as an immediate value in a 17802 // data-processing instruction. This can be used in GCC with an "n" 17803 // modifier that prints the negated value, for use with SUB 17804 // instructions. It is not useful otherwise but is implemented for 17805 // compatibility. 17806 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 17807 break; 17808 } else { 17809 // A constant whose negation can be used as an immediate value in a 17810 // data-processing instruction. This can be used in GCC with an "n" 17811 // modifier that prints the negated value, for use with SUB 17812 // instructions. It is not useful otherwise but is implemented for 17813 // compatibility. 17814 if (ARM_AM::getSOImmVal(-CVal) != -1) 17815 break; 17816 } 17817 return; 17818 17819 case 'M': 17820 if (Subtarget->isThumb1Only()) { 17821 // This must be a multiple of 4 between 0 and 1020, for 17822 // ADD sp + immediate. 17823 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 17824 break; 17825 } else { 17826 // A power of two or a constant between 0 and 32. This is used in 17827 // GCC for the shift amount on shifted register operands, but it is 17828 // useful in general for any shift amounts. 17829 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 17830 break; 17831 } 17832 return; 17833 17834 case 'N': 17835 if (Subtarget->isThumb1Only()) { 17836 // This must be a constant between 0 and 31, for shift amounts. 17837 if (CVal >= 0 && CVal <= 31) 17838 break; 17839 } 17840 return; 17841 17842 case 'O': 17843 if (Subtarget->isThumb1Only()) { 17844 // This must be a multiple of 4 between -508 and 508, for 17845 // ADD/SUB sp = sp + immediate. 17846 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 17847 break; 17848 } 17849 return; 17850 } 17851 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 17852 break; 17853 } 17854 17855 if (Result.getNode()) { 17856 Ops.push_back(Result); 17857 return; 17858 } 17859 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 17860 } 17861 17862 static RTLIB::Libcall getDivRemLibcall( 17863 const SDNode *N, MVT::SimpleValueType SVT) { 17864 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 17865 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 17866 "Unhandled Opcode in getDivRemLibcall"); 17867 bool isSigned = N->getOpcode() == ISD::SDIVREM || 17868 N->getOpcode() == ISD::SREM; 17869 RTLIB::Libcall LC; 17870 switch (SVT) { 17871 default: llvm_unreachable("Unexpected request for libcall!"); 17872 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 17873 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 17874 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 17875 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 17876 } 17877 return LC; 17878 } 17879 17880 static TargetLowering::ArgListTy getDivRemArgList( 17881 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 17882 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 17883 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 17884 "Unhandled Opcode in getDivRemArgList"); 17885 bool isSigned = N->getOpcode() == ISD::SDIVREM || 17886 N->getOpcode() == ISD::SREM; 17887 TargetLowering::ArgListTy Args; 17888 TargetLowering::ArgListEntry Entry; 17889 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 17890 EVT ArgVT = N->getOperand(i).getValueType(); 17891 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 17892 Entry.Node = N->getOperand(i); 17893 Entry.Ty = ArgTy; 17894 Entry.IsSExt = isSigned; 17895 Entry.IsZExt = !isSigned; 17896 Args.push_back(Entry); 17897 } 17898 if (Subtarget->isTargetWindows() && Args.size() >= 2) 17899 std::swap(Args[0], Args[1]); 17900 return Args; 17901 } 17902 17903 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 17904 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 17905 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 17906 Subtarget->isTargetWindows()) && 17907 "Register-based DivRem lowering only"); 17908 unsigned Opcode = Op->getOpcode(); 17909 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 17910 "Invalid opcode for Div/Rem lowering"); 17911 bool isSigned = (Opcode == ISD::SDIVREM); 17912 EVT VT = Op->getValueType(0); 17913 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 17914 SDLoc dl(Op); 17915 17916 // If the target has hardware divide, use divide + multiply + subtract: 17917 // div = a / b 17918 // rem = a - b * div 17919 // return {div, rem} 17920 // This should be lowered into UDIV/SDIV + MLS later on. 17921 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 17922 : Subtarget->hasDivideInARMMode(); 17923 if (hasDivide && Op->getValueType(0).isSimple() && 17924 Op->getSimpleValueType(0) == MVT::i32) { 17925 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 17926 const SDValue Dividend = Op->getOperand(0); 17927 const SDValue Divisor = Op->getOperand(1); 17928 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 17929 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 17930 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 17931 17932 SDValue Values[2] = {Div, Rem}; 17933 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 17934 } 17935 17936 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 17937 VT.getSimpleVT().SimpleTy); 17938 SDValue InChain = DAG.getEntryNode(); 17939 17940 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 17941 DAG.getContext(), 17942 Subtarget); 17943 17944 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 17945 getPointerTy(DAG.getDataLayout())); 17946 17947 Type *RetTy = StructType::get(Ty, Ty); 17948 17949 if (Subtarget->isTargetWindows()) 17950 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 17951 17952 TargetLowering::CallLoweringInfo CLI(DAG); 17953 CLI.setDebugLoc(dl).setChain(InChain) 17954 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 17955 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 17956 17957 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 17958 return CallInfo.first; 17959 } 17960 17961 // Lowers REM using divmod helpers 17962 // see RTABI section 4.2/4.3 17963 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 17964 // Build return types (div and rem) 17965 std::vector<Type*> RetTyParams; 17966 Type *RetTyElement; 17967 17968 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 17969 default: llvm_unreachable("Unexpected request for libcall!"); 17970 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 17971 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 17972 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 17973 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 17974 } 17975 17976 RetTyParams.push_back(RetTyElement); 17977 RetTyParams.push_back(RetTyElement); 17978 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 17979 Type *RetTy = StructType::get(*DAG.getContext(), ret); 17980 17981 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 17982 SimpleTy); 17983 SDValue InChain = DAG.getEntryNode(); 17984 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 17985 Subtarget); 17986 bool isSigned = N->getOpcode() == ISD::SREM; 17987 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 17988 getPointerTy(DAG.getDataLayout())); 17989 17990 if (Subtarget->isTargetWindows()) 17991 InChain = WinDBZCheckDenominator(DAG, N, InChain); 17992 17993 // Lower call 17994 CallLoweringInfo CLI(DAG); 17995 CLI.setChain(InChain) 17996 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 17997 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 17998 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 17999 18000 // Return second (rem) result operand (first contains div) 18001 SDNode *ResNode = CallResult.first.getNode(); 18002 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 18003 return ResNode->getOperand(1); 18004 } 18005 18006 SDValue 18007 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 18008 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 18009 SDLoc DL(Op); 18010 18011 // Get the inputs. 18012 SDValue Chain = Op.getOperand(0); 18013 SDValue Size = Op.getOperand(1); 18014 18015 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 18016 "no-stack-arg-probe")) { 18017 MaybeAlign Align = 18018 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue(); 18019 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 18020 Chain = SP.getValue(1); 18021 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 18022 if (Align) 18023 SP = 18024 DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 18025 DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32)); 18026 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 18027 SDValue Ops[2] = { SP, Chain }; 18028 return DAG.getMergeValues(Ops, DL); 18029 } 18030 18031 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 18032 DAG.getConstant(2, DL, MVT::i32)); 18033 18034 SDValue Flag; 18035 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 18036 Flag = Chain.getValue(1); 18037 18038 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 18039 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 18040 18041 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 18042 Chain = NewSP.getValue(1); 18043 18044 SDValue Ops[2] = { NewSP, Chain }; 18045 return DAG.getMergeValues(Ops, DL); 18046 } 18047 18048 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 18049 bool IsStrict = Op->isStrictFPOpcode(); 18050 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 18051 const unsigned DstSz = Op.getValueType().getSizeInBits(); 18052 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 18053 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 18054 "Unexpected type for custom-lowering FP_EXTEND"); 18055 18056 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 18057 "With both FP DP and 16, any FP conversion is legal!"); 18058 18059 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 18060 "With FP16, 16 to 32 conversion is legal!"); 18061 18062 // Converting from 32 -> 64 is valid if we have FP64. 18063 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) { 18064 // FIXME: Remove this when we have strict fp instruction selection patterns 18065 if (IsStrict) { 18066 SDLoc Loc(Op); 18067 SDValue Result = DAG.getNode(ISD::FP_EXTEND, 18068 Loc, Op.getValueType(), SrcVal); 18069 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 18070 } 18071 return Op; 18072 } 18073 18074 // Either we are converting from 16 -> 64, without FP16 and/or 18075 // FP.double-precision or without Armv8-fp. So we must do it in two 18076 // steps. 18077 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 18078 // without FP16. So we must do a function call. 18079 SDLoc Loc(Op); 18080 RTLIB::Libcall LC; 18081 MakeLibCallOptions CallOptions; 18082 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 18083 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) { 18084 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64()); 18085 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32); 18086 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64); 18087 if (Supported) { 18088 if (IsStrict) { 18089 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc, 18090 {DstVT, MVT::Other}, {Chain, SrcVal}); 18091 Chain = SrcVal.getValue(1); 18092 } else { 18093 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal); 18094 } 18095 } else { 18096 LC = RTLIB::getFPEXT(SrcVT, DstVT); 18097 assert(LC != RTLIB::UNKNOWN_LIBCALL && 18098 "Unexpected type for custom-lowering FP_EXTEND"); 18099 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 18100 Loc, Chain); 18101 } 18102 } 18103 18104 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal; 18105 } 18106 18107 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 18108 bool IsStrict = Op->isStrictFPOpcode(); 18109 18110 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 18111 EVT SrcVT = SrcVal.getValueType(); 18112 EVT DstVT = Op.getValueType(); 18113 const unsigned DstSz = Op.getValueType().getSizeInBits(); 18114 const unsigned SrcSz = SrcVT.getSizeInBits(); 18115 (void)DstSz; 18116 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 18117 "Unexpected type for custom-lowering FP_ROUND"); 18118 18119 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 18120 "With both FP DP and 16, any FP conversion is legal!"); 18121 18122 SDLoc Loc(Op); 18123 18124 // Instruction from 32 -> 16 if hasFP16 is valid 18125 if (SrcSz == 32 && Subtarget->hasFP16()) 18126 return Op; 18127 18128 // Lib call from 32 -> 16 / 64 -> [32, 16] 18129 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 18130 assert(LC != RTLIB::UNKNOWN_LIBCALL && 18131 "Unexpected type for custom-lowering FP_ROUND"); 18132 MakeLibCallOptions CallOptions; 18133 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 18134 SDValue Result; 18135 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 18136 Loc, Chain); 18137 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 18138 } 18139 18140 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 18141 SelectionDAG &DAG) const { 18142 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 18143 MVT HalfT = MVT::i32; 18144 SDLoc dl(N); 18145 SDValue Hi, Lo, Tmp; 18146 18147 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 18148 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 18149 return ; 18150 18151 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 18152 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 18153 18154 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 18155 DAG.getConstant(0, dl, HalfT)); 18156 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 18157 DAG.getConstant(1, dl, HalfT)); 18158 18159 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 18160 DAG.getConstant(OpTypeBits - 1, dl, 18161 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 18162 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 18163 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 18164 SDValue(Lo.getNode(), 1)); 18165 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 18166 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 18167 18168 Results.push_back(Lo); 18169 Results.push_back(Hi); 18170 } 18171 18172 bool 18173 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 18174 // The ARM target isn't yet aware of offsets. 18175 return false; 18176 } 18177 18178 bool ARM::isBitFieldInvertedMask(unsigned v) { 18179 if (v == 0xffffffff) 18180 return false; 18181 18182 // there can be 1's on either or both "outsides", all the "inside" 18183 // bits must be 0's 18184 return isShiftedMask_32(~v); 18185 } 18186 18187 /// isFPImmLegal - Returns true if the target can instruction select the 18188 /// specified FP immediate natively. If false, the legalizer will 18189 /// materialize the FP immediate as a load from a constant pool. 18190 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 18191 bool ForCodeSize) const { 18192 if (!Subtarget->hasVFP3Base()) 18193 return false; 18194 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 18195 return ARM_AM::getFP16Imm(Imm) != -1; 18196 if (VT == MVT::f32 && Subtarget->hasFullFP16() && 18197 ARM_AM::getFP32FP16Imm(Imm) != -1) 18198 return true; 18199 if (VT == MVT::f32) 18200 return ARM_AM::getFP32Imm(Imm) != -1; 18201 if (VT == MVT::f64 && Subtarget->hasFP64()) 18202 return ARM_AM::getFP64Imm(Imm) != -1; 18203 return false; 18204 } 18205 18206 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 18207 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 18208 /// specified in the intrinsic calls. 18209 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 18210 const CallInst &I, 18211 MachineFunction &MF, 18212 unsigned Intrinsic) const { 18213 switch (Intrinsic) { 18214 case Intrinsic::arm_neon_vld1: 18215 case Intrinsic::arm_neon_vld2: 18216 case Intrinsic::arm_neon_vld3: 18217 case Intrinsic::arm_neon_vld4: 18218 case Intrinsic::arm_neon_vld2lane: 18219 case Intrinsic::arm_neon_vld3lane: 18220 case Intrinsic::arm_neon_vld4lane: 18221 case Intrinsic::arm_neon_vld2dup: 18222 case Intrinsic::arm_neon_vld3dup: 18223 case Intrinsic::arm_neon_vld4dup: { 18224 Info.opc = ISD::INTRINSIC_W_CHAIN; 18225 // Conservatively set memVT to the entire set of vectors loaded. 18226 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18227 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 18228 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18229 Info.ptrVal = I.getArgOperand(0); 18230 Info.offset = 0; 18231 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 18232 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue(); 18233 // volatile loads with NEON intrinsics not supported 18234 Info.flags = MachineMemOperand::MOLoad; 18235 return true; 18236 } 18237 case Intrinsic::arm_neon_vld1x2: 18238 case Intrinsic::arm_neon_vld1x3: 18239 case Intrinsic::arm_neon_vld1x4: { 18240 Info.opc = ISD::INTRINSIC_W_CHAIN; 18241 // Conservatively set memVT to the entire set of vectors loaded. 18242 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18243 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 18244 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18245 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 18246 Info.offset = 0; 18247 Info.align.reset(); 18248 // volatile loads with NEON intrinsics not supported 18249 Info.flags = MachineMemOperand::MOLoad; 18250 return true; 18251 } 18252 case Intrinsic::arm_neon_vst1: 18253 case Intrinsic::arm_neon_vst2: 18254 case Intrinsic::arm_neon_vst3: 18255 case Intrinsic::arm_neon_vst4: 18256 case Intrinsic::arm_neon_vst2lane: 18257 case Intrinsic::arm_neon_vst3lane: 18258 case Intrinsic::arm_neon_vst4lane: { 18259 Info.opc = ISD::INTRINSIC_VOID; 18260 // Conservatively set memVT to the entire set of vectors stored. 18261 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18262 unsigned NumElts = 0; 18263 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 18264 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 18265 if (!ArgTy->isVectorTy()) 18266 break; 18267 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 18268 } 18269 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18270 Info.ptrVal = I.getArgOperand(0); 18271 Info.offset = 0; 18272 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 18273 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue(); 18274 // volatile stores with NEON intrinsics not supported 18275 Info.flags = MachineMemOperand::MOStore; 18276 return true; 18277 } 18278 case Intrinsic::arm_neon_vst1x2: 18279 case Intrinsic::arm_neon_vst1x3: 18280 case Intrinsic::arm_neon_vst1x4: { 18281 Info.opc = ISD::INTRINSIC_VOID; 18282 // Conservatively set memVT to the entire set of vectors stored. 18283 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18284 unsigned NumElts = 0; 18285 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 18286 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 18287 if (!ArgTy->isVectorTy()) 18288 break; 18289 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 18290 } 18291 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18292 Info.ptrVal = I.getArgOperand(0); 18293 Info.offset = 0; 18294 Info.align.reset(); 18295 // volatile stores with NEON intrinsics not supported 18296 Info.flags = MachineMemOperand::MOStore; 18297 return true; 18298 } 18299 case Intrinsic::arm_mve_vld2q: 18300 case Intrinsic::arm_mve_vld4q: { 18301 Info.opc = ISD::INTRINSIC_W_CHAIN; 18302 // Conservatively set memVT to the entire set of vectors loaded. 18303 Type *VecTy = cast<StructType>(I.getType())->getElementType(1); 18304 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4; 18305 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 18306 Info.ptrVal = I.getArgOperand(0); 18307 Info.offset = 0; 18308 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 18309 // volatile loads with MVE intrinsics not supported 18310 Info.flags = MachineMemOperand::MOLoad; 18311 return true; 18312 } 18313 case Intrinsic::arm_mve_vst2q: 18314 case Intrinsic::arm_mve_vst4q: { 18315 Info.opc = ISD::INTRINSIC_VOID; 18316 // Conservatively set memVT to the entire set of vectors stored. 18317 Type *VecTy = I.getArgOperand(1)->getType(); 18318 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4; 18319 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 18320 Info.ptrVal = I.getArgOperand(0); 18321 Info.offset = 0; 18322 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 18323 // volatile stores with MVE intrinsics not supported 18324 Info.flags = MachineMemOperand::MOStore; 18325 return true; 18326 } 18327 case Intrinsic::arm_ldaex: 18328 case Intrinsic::arm_ldrex: { 18329 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18330 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 18331 Info.opc = ISD::INTRINSIC_W_CHAIN; 18332 Info.memVT = MVT::getVT(PtrTy->getElementType()); 18333 Info.ptrVal = I.getArgOperand(0); 18334 Info.offset = 0; 18335 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 18336 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 18337 return true; 18338 } 18339 case Intrinsic::arm_stlex: 18340 case Intrinsic::arm_strex: { 18341 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18342 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 18343 Info.opc = ISD::INTRINSIC_W_CHAIN; 18344 Info.memVT = MVT::getVT(PtrTy->getElementType()); 18345 Info.ptrVal = I.getArgOperand(1); 18346 Info.offset = 0; 18347 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 18348 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 18349 return true; 18350 } 18351 case Intrinsic::arm_stlexd: 18352 case Intrinsic::arm_strexd: 18353 Info.opc = ISD::INTRINSIC_W_CHAIN; 18354 Info.memVT = MVT::i64; 18355 Info.ptrVal = I.getArgOperand(2); 18356 Info.offset = 0; 18357 Info.align = Align(8); 18358 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 18359 return true; 18360 18361 case Intrinsic::arm_ldaexd: 18362 case Intrinsic::arm_ldrexd: 18363 Info.opc = ISD::INTRINSIC_W_CHAIN; 18364 Info.memVT = MVT::i64; 18365 Info.ptrVal = I.getArgOperand(0); 18366 Info.offset = 0; 18367 Info.align = Align(8); 18368 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 18369 return true; 18370 18371 default: 18372 break; 18373 } 18374 18375 return false; 18376 } 18377 18378 /// Returns true if it is beneficial to convert a load of a constant 18379 /// to just the constant itself. 18380 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 18381 Type *Ty) const { 18382 assert(Ty->isIntegerTy()); 18383 18384 unsigned Bits = Ty->getPrimitiveSizeInBits(); 18385 if (Bits == 0 || Bits > 32) 18386 return false; 18387 return true; 18388 } 18389 18390 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 18391 unsigned Index) const { 18392 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 18393 return false; 18394 18395 return (Index == 0 || Index == ResVT.getVectorNumElements()); 18396 } 18397 18398 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 18399 ARM_MB::MemBOpt Domain) const { 18400 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18401 18402 // First, if the target has no DMB, see what fallback we can use. 18403 if (!Subtarget->hasDataBarrier()) { 18404 // Some ARMv6 cpus can support data barriers with an mcr instruction. 18405 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 18406 // here. 18407 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 18408 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 18409 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 18410 Builder.getInt32(0), Builder.getInt32(7), 18411 Builder.getInt32(10), Builder.getInt32(5)}; 18412 return Builder.CreateCall(MCR, args); 18413 } else { 18414 // Instead of using barriers, atomic accesses on these subtargets use 18415 // libcalls. 18416 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 18417 } 18418 } else { 18419 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 18420 // Only a full system barrier exists in the M-class architectures. 18421 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 18422 Constant *CDomain = Builder.getInt32(Domain); 18423 return Builder.CreateCall(DMB, CDomain); 18424 } 18425 } 18426 18427 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 18428 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 18429 Instruction *Inst, 18430 AtomicOrdering Ord) const { 18431 switch (Ord) { 18432 case AtomicOrdering::NotAtomic: 18433 case AtomicOrdering::Unordered: 18434 llvm_unreachable("Invalid fence: unordered/non-atomic"); 18435 case AtomicOrdering::Monotonic: 18436 case AtomicOrdering::Acquire: 18437 return nullptr; // Nothing to do 18438 case AtomicOrdering::SequentiallyConsistent: 18439 if (!Inst->hasAtomicStore()) 18440 return nullptr; // Nothing to do 18441 LLVM_FALLTHROUGH; 18442 case AtomicOrdering::Release: 18443 case AtomicOrdering::AcquireRelease: 18444 if (Subtarget->preferISHSTBarriers()) 18445 return makeDMB(Builder, ARM_MB::ISHST); 18446 // FIXME: add a comment with a link to documentation justifying this. 18447 else 18448 return makeDMB(Builder, ARM_MB::ISH); 18449 } 18450 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 18451 } 18452 18453 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 18454 Instruction *Inst, 18455 AtomicOrdering Ord) const { 18456 switch (Ord) { 18457 case AtomicOrdering::NotAtomic: 18458 case AtomicOrdering::Unordered: 18459 llvm_unreachable("Invalid fence: unordered/not-atomic"); 18460 case AtomicOrdering::Monotonic: 18461 case AtomicOrdering::Release: 18462 return nullptr; // Nothing to do 18463 case AtomicOrdering::Acquire: 18464 case AtomicOrdering::AcquireRelease: 18465 case AtomicOrdering::SequentiallyConsistent: 18466 return makeDMB(Builder, ARM_MB::ISH); 18467 } 18468 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 18469 } 18470 18471 // Loads and stores less than 64-bits are already atomic; ones above that 18472 // are doomed anyway, so defer to the default libcall and blame the OS when 18473 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 18474 // anything for those. 18475 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 18476 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 18477 return (Size == 64) && !Subtarget->isMClass(); 18478 } 18479 18480 // Loads and stores less than 64-bits are already atomic; ones above that 18481 // are doomed anyway, so defer to the default libcall and blame the OS when 18482 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 18483 // anything for those. 18484 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 18485 // guarantee, see DDI0406C ARM architecture reference manual, 18486 // sections A8.8.72-74 LDRD) 18487 TargetLowering::AtomicExpansionKind 18488 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 18489 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 18490 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 18491 : AtomicExpansionKind::None; 18492 } 18493 18494 // For the real atomic operations, we have ldrex/strex up to 32 bits, 18495 // and up to 64 bits on the non-M profiles 18496 TargetLowering::AtomicExpansionKind 18497 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 18498 if (AI->isFloatingPointOperation()) 18499 return AtomicExpansionKind::CmpXChg; 18500 18501 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 18502 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 18503 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 18504 ? AtomicExpansionKind::LLSC 18505 : AtomicExpansionKind::None; 18506 } 18507 18508 TargetLowering::AtomicExpansionKind 18509 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 18510 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 18511 // implement cmpxchg without spilling. If the address being exchanged is also 18512 // on the stack and close enough to the spill slot, this can lead to a 18513 // situation where the monitor always gets cleared and the atomic operation 18514 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 18515 bool HasAtomicCmpXchg = 18516 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 18517 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 18518 return AtomicExpansionKind::LLSC; 18519 return AtomicExpansionKind::None; 18520 } 18521 18522 bool ARMTargetLowering::shouldInsertFencesForAtomic( 18523 const Instruction *I) const { 18524 return InsertFencesForAtomic; 18525 } 18526 18527 // This has so far only been implemented for MachO. 18528 bool ARMTargetLowering::useLoadStackGuardNode() const { 18529 return Subtarget->isTargetMachO(); 18530 } 18531 18532 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 18533 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18534 return TargetLowering::insertSSPDeclarations(M); 18535 18536 // MSVC CRT has a global variable holding security cookie. 18537 M.getOrInsertGlobal("__security_cookie", 18538 Type::getInt8PtrTy(M.getContext())); 18539 18540 // MSVC CRT has a function to validate security cookie. 18541 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 18542 "__security_check_cookie", Type::getVoidTy(M.getContext()), 18543 Type::getInt8PtrTy(M.getContext())); 18544 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 18545 F->addAttribute(1, Attribute::AttrKind::InReg); 18546 } 18547 18548 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 18549 // MSVC CRT has a global variable holding security cookie. 18550 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18551 return M.getGlobalVariable("__security_cookie"); 18552 return TargetLowering::getSDagStackGuard(M); 18553 } 18554 18555 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 18556 // MSVC CRT has a function to validate security cookie. 18557 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18558 return M.getFunction("__security_check_cookie"); 18559 return TargetLowering::getSSPStackGuardCheck(M); 18560 } 18561 18562 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 18563 unsigned &Cost) const { 18564 // If we do not have NEON, vector types are not natively supported. 18565 if (!Subtarget->hasNEON()) 18566 return false; 18567 18568 // Floating point values and vector values map to the same register file. 18569 // Therefore, although we could do a store extract of a vector type, this is 18570 // better to leave at float as we have more freedom in the addressing mode for 18571 // those. 18572 if (VectorTy->isFPOrFPVectorTy()) 18573 return false; 18574 18575 // If the index is unknown at compile time, this is very expensive to lower 18576 // and it is not possible to combine the store with the extract. 18577 if (!isa<ConstantInt>(Idx)) 18578 return false; 18579 18580 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 18581 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize(); 18582 // We can do a store + vector extract on any vector that fits perfectly in a D 18583 // or Q register. 18584 if (BitWidth == 64 || BitWidth == 128) { 18585 Cost = 0; 18586 return true; 18587 } 18588 return false; 18589 } 18590 18591 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 18592 return Subtarget->hasV6T2Ops(); 18593 } 18594 18595 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 18596 return Subtarget->hasV6T2Ops(); 18597 } 18598 18599 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 18600 return !Subtarget->hasMinSize() || Subtarget->isTargetWindows(); 18601 } 18602 18603 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 18604 AtomicOrdering Ord) const { 18605 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18606 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 18607 bool IsAcquire = isAcquireOrStronger(Ord); 18608 18609 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 18610 // intrinsic must return {i32, i32} and we have to recombine them into a 18611 // single i64 here. 18612 if (ValTy->getPrimitiveSizeInBits() == 64) { 18613 Intrinsic::ID Int = 18614 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 18615 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 18616 18617 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 18618 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 18619 18620 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18621 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18622 if (!Subtarget->isLittle()) 18623 std::swap (Lo, Hi); 18624 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18625 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18626 return Builder.CreateOr( 18627 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 18628 } 18629 18630 Type *Tys[] = { Addr->getType() }; 18631 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 18632 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 18633 18634 return Builder.CreateTruncOrBitCast( 18635 Builder.CreateCall(Ldrex, Addr), 18636 cast<PointerType>(Addr->getType())->getElementType()); 18637 } 18638 18639 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 18640 IRBuilder<> &Builder) const { 18641 if (!Subtarget->hasV7Ops()) 18642 return; 18643 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18644 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 18645 } 18646 18647 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 18648 Value *Addr, 18649 AtomicOrdering Ord) const { 18650 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18651 bool IsRelease = isReleaseOrStronger(Ord); 18652 18653 // Since the intrinsics must have legal type, the i64 intrinsics take two 18654 // parameters: "i32, i32". We must marshal Val into the appropriate form 18655 // before the call. 18656 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 18657 Intrinsic::ID Int = 18658 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 18659 Function *Strex = Intrinsic::getDeclaration(M, Int); 18660 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 18661 18662 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 18663 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 18664 if (!Subtarget->isLittle()) 18665 std::swap(Lo, Hi); 18666 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 18667 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 18668 } 18669 18670 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 18671 Type *Tys[] = { Addr->getType() }; 18672 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 18673 18674 return Builder.CreateCall( 18675 Strex, {Builder.CreateZExtOrBitCast( 18676 Val, Strex->getFunctionType()->getParamType(0)), 18677 Addr}); 18678 } 18679 18680 18681 bool ARMTargetLowering::alignLoopsWithOptSize() const { 18682 return Subtarget->isMClass(); 18683 } 18684 18685 /// A helper function for determining the number of interleaved accesses we 18686 /// will generate when lowering accesses of the given type. 18687 unsigned 18688 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 18689 const DataLayout &DL) const { 18690 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 18691 } 18692 18693 bool ARMTargetLowering::isLegalInterleavedAccessType( 18694 unsigned Factor, FixedVectorType *VecTy, const DataLayout &DL) const { 18695 18696 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 18697 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 18698 18699 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) 18700 return false; 18701 18702 // Ensure the vector doesn't have f16 elements. Even though we could do an 18703 // i16 vldN, we can't hold the f16 vectors and will end up converting via 18704 // f32. 18705 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy()) 18706 return false; 18707 if (Subtarget->hasMVEIntegerOps() && Factor == 3) 18708 return false; 18709 18710 // Ensure the number of vector elements is greater than 1. 18711 if (VecTy->getNumElements() < 2) 18712 return false; 18713 18714 // Ensure the element type is legal. 18715 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 18716 return false; 18717 18718 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 18719 // 128 will be split into multiple interleaved accesses. 18720 if (Subtarget->hasNEON() && VecSize == 64) 18721 return true; 18722 return VecSize % 128 == 0; 18723 } 18724 18725 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const { 18726 if (Subtarget->hasNEON()) 18727 return 4; 18728 if (Subtarget->hasMVEIntegerOps()) 18729 return MVEMaxSupportedInterleaveFactor; 18730 return TargetLoweringBase::getMaxSupportedInterleaveFactor(); 18731 } 18732 18733 /// Lower an interleaved load into a vldN intrinsic. 18734 /// 18735 /// E.g. Lower an interleaved load (Factor = 2): 18736 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 18737 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 18738 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 18739 /// 18740 /// Into: 18741 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 18742 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 18743 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 18744 bool ARMTargetLowering::lowerInterleavedLoad( 18745 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 18746 ArrayRef<unsigned> Indices, unsigned Factor) const { 18747 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 18748 "Invalid interleave factor"); 18749 assert(!Shuffles.empty() && "Empty shufflevector input"); 18750 assert(Shuffles.size() == Indices.size() && 18751 "Unmatched number of shufflevectors and indices"); 18752 18753 auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType()); 18754 Type *EltTy = VecTy->getElementType(); 18755 18756 const DataLayout &DL = LI->getModule()->getDataLayout(); 18757 18758 // Skip if we do not have NEON and skip illegal vector types. We can 18759 // "legalize" wide vector types into multiple interleaved accesses as long as 18760 // the vector types are divisible by 128. 18761 if (!isLegalInterleavedAccessType(Factor, VecTy, DL)) 18762 return false; 18763 18764 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 18765 18766 // A pointer vector can not be the return type of the ldN intrinsics. Need to 18767 // load integer vectors first and then convert to pointer vectors. 18768 if (EltTy->isPointerTy()) 18769 VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy); 18770 18771 IRBuilder<> Builder(LI); 18772 18773 // The base address of the load. 18774 Value *BaseAddr = LI->getPointerOperand(); 18775 18776 if (NumLoads > 1) { 18777 // If we're going to generate more than one load, reset the sub-vector type 18778 // to something legal. 18779 VecTy = FixedVectorType::get(VecTy->getElementType(), 18780 VecTy->getNumElements() / NumLoads); 18781 18782 // We will compute the pointer operand of each load from the original base 18783 // address using GEPs. Cast the base address to a pointer to the scalar 18784 // element type. 18785 BaseAddr = Builder.CreateBitCast( 18786 BaseAddr, 18787 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())); 18788 } 18789 18790 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 18791 18792 auto createLoadIntrinsic = [&](Value *BaseAddr) { 18793 if (Subtarget->hasNEON()) { 18794 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 18795 Type *Tys[] = {VecTy, Int8Ptr}; 18796 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 18797 Intrinsic::arm_neon_vld3, 18798 Intrinsic::arm_neon_vld4}; 18799 Function *VldnFunc = 18800 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 18801 18802 SmallVector<Value *, 2> Ops; 18803 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 18804 Ops.push_back(Builder.getInt32(LI->getAlignment())); 18805 18806 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 18807 } else { 18808 assert((Factor == 2 || Factor == 4) && 18809 "expected interleave factor of 2 or 4 for MVE"); 18810 Intrinsic::ID LoadInts = 18811 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q; 18812 Type *VecEltTy = 18813 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()); 18814 Type *Tys[] = {VecTy, VecEltTy}; 18815 Function *VldnFunc = 18816 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys); 18817 18818 SmallVector<Value *, 2> Ops; 18819 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy)); 18820 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 18821 } 18822 }; 18823 18824 // Holds sub-vectors extracted from the load intrinsic return values. The 18825 // sub-vectors are associated with the shufflevector instructions they will 18826 // replace. 18827 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 18828 18829 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 18830 // If we're generating more than one load, compute the base address of 18831 // subsequent loads as an offset from the previous. 18832 if (LoadCount > 0) 18833 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr, 18834 VecTy->getNumElements() * Factor); 18835 18836 CallInst *VldN = createLoadIntrinsic(BaseAddr); 18837 18838 // Replace uses of each shufflevector with the corresponding vector loaded 18839 // by ldN. 18840 for (unsigned i = 0; i < Shuffles.size(); i++) { 18841 ShuffleVectorInst *SV = Shuffles[i]; 18842 unsigned Index = Indices[i]; 18843 18844 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 18845 18846 // Convert the integer vector to pointer vector if the element is pointer. 18847 if (EltTy->isPointerTy()) 18848 SubVec = Builder.CreateIntToPtr( 18849 SubVec, 18850 FixedVectorType::get(SV->getType()->getElementType(), VecTy)); 18851 18852 SubVecs[SV].push_back(SubVec); 18853 } 18854 } 18855 18856 // Replace uses of the shufflevector instructions with the sub-vectors 18857 // returned by the load intrinsic. If a shufflevector instruction is 18858 // associated with more than one sub-vector, those sub-vectors will be 18859 // concatenated into a single wide vector. 18860 for (ShuffleVectorInst *SVI : Shuffles) { 18861 auto &SubVec = SubVecs[SVI]; 18862 auto *WideVec = 18863 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 18864 SVI->replaceAllUsesWith(WideVec); 18865 } 18866 18867 return true; 18868 } 18869 18870 /// Lower an interleaved store into a vstN intrinsic. 18871 /// 18872 /// E.g. Lower an interleaved store (Factor = 3): 18873 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 18874 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 18875 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 18876 /// 18877 /// Into: 18878 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 18879 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 18880 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 18881 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 18882 /// 18883 /// Note that the new shufflevectors will be removed and we'll only generate one 18884 /// vst3 instruction in CodeGen. 18885 /// 18886 /// Example for a more general valid mask (Factor 3). Lower: 18887 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 18888 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 18889 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 18890 /// 18891 /// Into: 18892 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 18893 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 18894 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 18895 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 18896 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 18897 ShuffleVectorInst *SVI, 18898 unsigned Factor) const { 18899 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 18900 "Invalid interleave factor"); 18901 18902 auto *VecTy = cast<FixedVectorType>(SVI->getType()); 18903 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store"); 18904 18905 unsigned LaneLen = VecTy->getNumElements() / Factor; 18906 Type *EltTy = VecTy->getElementType(); 18907 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen); 18908 18909 const DataLayout &DL = SI->getModule()->getDataLayout(); 18910 18911 // Skip if we do not have NEON and skip illegal vector types. We can 18912 // "legalize" wide vector types into multiple interleaved accesses as long as 18913 // the vector types are divisible by 128. 18914 if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL)) 18915 return false; 18916 18917 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 18918 18919 Value *Op0 = SVI->getOperand(0); 18920 Value *Op1 = SVI->getOperand(1); 18921 IRBuilder<> Builder(SI); 18922 18923 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 18924 // vectors to integer vectors. 18925 if (EltTy->isPointerTy()) { 18926 Type *IntTy = DL.getIntPtrType(EltTy); 18927 18928 // Convert to the corresponding integer vector. 18929 auto *IntVecTy = 18930 FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType())); 18931 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 18932 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 18933 18934 SubVecTy = FixedVectorType::get(IntTy, LaneLen); 18935 } 18936 18937 // The base address of the store. 18938 Value *BaseAddr = SI->getPointerOperand(); 18939 18940 if (NumStores > 1) { 18941 // If we're going to generate more than one store, reset the lane length 18942 // and sub-vector type to something legal. 18943 LaneLen /= NumStores; 18944 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen); 18945 18946 // We will compute the pointer operand of each store from the original base 18947 // address using GEPs. Cast the base address to a pointer to the scalar 18948 // element type. 18949 BaseAddr = Builder.CreateBitCast( 18950 BaseAddr, 18951 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())); 18952 } 18953 18954 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 18955 18956 auto Mask = SVI->getShuffleMask(); 18957 18958 auto createStoreIntrinsic = [&](Value *BaseAddr, 18959 SmallVectorImpl<Value *> &Shuffles) { 18960 if (Subtarget->hasNEON()) { 18961 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 18962 Intrinsic::arm_neon_vst3, 18963 Intrinsic::arm_neon_vst4}; 18964 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 18965 Type *Tys[] = {Int8Ptr, SubVecTy}; 18966 18967 Function *VstNFunc = Intrinsic::getDeclaration( 18968 SI->getModule(), StoreInts[Factor - 2], Tys); 18969 18970 SmallVector<Value *, 6> Ops; 18971 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 18972 for (auto S : Shuffles) 18973 Ops.push_back(S); 18974 Ops.push_back(Builder.getInt32(SI->getAlignment())); 18975 Builder.CreateCall(VstNFunc, Ops); 18976 } else { 18977 assert((Factor == 2 || Factor == 4) && 18978 "expected interleave factor of 2 or 4 for MVE"); 18979 Intrinsic::ID StoreInts = 18980 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q; 18981 Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo( 18982 SI->getPointerAddressSpace()); 18983 Type *Tys[] = {EltPtrTy, SubVecTy}; 18984 Function *VstNFunc = 18985 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys); 18986 18987 SmallVector<Value *, 6> Ops; 18988 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy)); 18989 for (auto S : Shuffles) 18990 Ops.push_back(S); 18991 for (unsigned F = 0; F < Factor; F++) { 18992 Ops.push_back(Builder.getInt32(F)); 18993 Builder.CreateCall(VstNFunc, Ops); 18994 Ops.pop_back(); 18995 } 18996 } 18997 }; 18998 18999 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 19000 // If we generating more than one store, we compute the base address of 19001 // subsequent stores as an offset from the previous. 19002 if (StoreCount > 0) 19003 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(), 19004 BaseAddr, LaneLen * Factor); 19005 19006 SmallVector<Value *, 4> Shuffles; 19007 19008 // Split the shufflevector operands into sub vectors for the new vstN call. 19009 for (unsigned i = 0; i < Factor; i++) { 19010 unsigned IdxI = StoreCount * LaneLen * Factor + i; 19011 if (Mask[IdxI] >= 0) { 19012 Shuffles.push_back(Builder.CreateShuffleVector( 19013 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0))); 19014 } else { 19015 unsigned StartMask = 0; 19016 for (unsigned j = 1; j < LaneLen; j++) { 19017 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 19018 if (Mask[IdxJ * Factor + IdxI] >= 0) { 19019 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 19020 break; 19021 } 19022 } 19023 // Note: If all elements in a chunk are undefs, StartMask=0! 19024 // Note: Filling undef gaps with random elements is ok, since 19025 // those elements were being written anyway (with undefs). 19026 // In the case of all undefs we're defaulting to using elems from 0 19027 // Note: StartMask cannot be negative, it's checked in 19028 // isReInterleaveMask 19029 Shuffles.push_back(Builder.CreateShuffleVector( 19030 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0))); 19031 } 19032 } 19033 19034 createStoreIntrinsic(BaseAddr, Shuffles); 19035 } 19036 return true; 19037 } 19038 19039 enum HABaseType { 19040 HA_UNKNOWN = 0, 19041 HA_FLOAT, 19042 HA_DOUBLE, 19043 HA_VECT64, 19044 HA_VECT128 19045 }; 19046 19047 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 19048 uint64_t &Members) { 19049 if (auto *ST = dyn_cast<StructType>(Ty)) { 19050 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 19051 uint64_t SubMembers = 0; 19052 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 19053 return false; 19054 Members += SubMembers; 19055 } 19056 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 19057 uint64_t SubMembers = 0; 19058 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 19059 return false; 19060 Members += SubMembers * AT->getNumElements(); 19061 } else if (Ty->isFloatTy()) { 19062 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 19063 return false; 19064 Members = 1; 19065 Base = HA_FLOAT; 19066 } else if (Ty->isDoubleTy()) { 19067 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 19068 return false; 19069 Members = 1; 19070 Base = HA_DOUBLE; 19071 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 19072 Members = 1; 19073 switch (Base) { 19074 case HA_FLOAT: 19075 case HA_DOUBLE: 19076 return false; 19077 case HA_VECT64: 19078 return VT->getPrimitiveSizeInBits().getFixedSize() == 64; 19079 case HA_VECT128: 19080 return VT->getPrimitiveSizeInBits().getFixedSize() == 128; 19081 case HA_UNKNOWN: 19082 switch (VT->getPrimitiveSizeInBits().getFixedSize()) { 19083 case 64: 19084 Base = HA_VECT64; 19085 return true; 19086 case 128: 19087 Base = HA_VECT128; 19088 return true; 19089 default: 19090 return false; 19091 } 19092 } 19093 } 19094 19095 return (Members > 0 && Members <= 4); 19096 } 19097 19098 /// Return the correct alignment for the current calling convention. 19099 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 19100 DataLayout DL) const { 19101 const Align ABITypeAlign = DL.getABITypeAlign(ArgTy); 19102 if (!ArgTy->isVectorTy()) 19103 return ABITypeAlign; 19104 19105 // Avoid over-aligning vector parameters. It would require realigning the 19106 // stack and waste space for no real benefit. 19107 return std::min(ABITypeAlign, DL.getStackAlignment()); 19108 } 19109 19110 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 19111 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 19112 /// passing according to AAPCS rules. 19113 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 19114 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 19115 if (getEffectiveCallingConv(CallConv, isVarArg) != 19116 CallingConv::ARM_AAPCS_VFP) 19117 return false; 19118 19119 HABaseType Base = HA_UNKNOWN; 19120 uint64_t Members = 0; 19121 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 19122 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 19123 19124 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 19125 return IsHA || IsIntArray; 19126 } 19127 19128 Register ARMTargetLowering::getExceptionPointerRegister( 19129 const Constant *PersonalityFn) const { 19130 // Platforms which do not use SjLj EH may return values in these registers 19131 // via the personality function. 19132 return Subtarget->useSjLjEH() ? Register() : ARM::R0; 19133 } 19134 19135 Register ARMTargetLowering::getExceptionSelectorRegister( 19136 const Constant *PersonalityFn) const { 19137 // Platforms which do not use SjLj EH may return values in these registers 19138 // via the personality function. 19139 return Subtarget->useSjLjEH() ? Register() : ARM::R1; 19140 } 19141 19142 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 19143 // Update IsSplitCSR in ARMFunctionInfo. 19144 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 19145 AFI->setIsSplitCSR(true); 19146 } 19147 19148 void ARMTargetLowering::insertCopiesSplitCSR( 19149 MachineBasicBlock *Entry, 19150 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 19151 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 19152 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 19153 if (!IStart) 19154 return; 19155 19156 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 19157 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 19158 MachineBasicBlock::iterator MBBI = Entry->begin(); 19159 for (const MCPhysReg *I = IStart; *I; ++I) { 19160 const TargetRegisterClass *RC = nullptr; 19161 if (ARM::GPRRegClass.contains(*I)) 19162 RC = &ARM::GPRRegClass; 19163 else if (ARM::DPRRegClass.contains(*I)) 19164 RC = &ARM::DPRRegClass; 19165 else 19166 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 19167 19168 Register NewVR = MRI->createVirtualRegister(RC); 19169 // Create copy from CSR to a virtual register. 19170 // FIXME: this currently does not emit CFI pseudo-instructions, it works 19171 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 19172 // nounwind. If we want to generalize this later, we may need to emit 19173 // CFI pseudo-instructions. 19174 assert(Entry->getParent()->getFunction().hasFnAttribute( 19175 Attribute::NoUnwind) && 19176 "Function should be nounwind in insertCopiesSplitCSR!"); 19177 Entry->addLiveIn(*I); 19178 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 19179 .addReg(*I); 19180 19181 // Insert the copy-back instructions right before the terminator. 19182 for (auto *Exit : Exits) 19183 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 19184 TII->get(TargetOpcode::COPY), *I) 19185 .addReg(NewVR); 19186 } 19187 } 19188 19189 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 19190 MF.getFrameInfo().computeMaxCallFrameSize(MF); 19191 TargetLoweringBase::finalizeLowering(MF); 19192 } 19193