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 static 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 } 991 992 if (!Subtarget->hasFP64()) { 993 // When targeting a floating-point unit with only single-precision 994 // operations, f64 is legal for the few double-precision instructions which 995 // are present However, no double-precision operations other than moves, 996 // loads and stores are provided by the hardware. 997 setOperationAction(ISD::FADD, MVT::f64, Expand); 998 setOperationAction(ISD::FSUB, MVT::f64, Expand); 999 setOperationAction(ISD::FMUL, MVT::f64, Expand); 1000 setOperationAction(ISD::FMA, MVT::f64, Expand); 1001 setOperationAction(ISD::FDIV, MVT::f64, Expand); 1002 setOperationAction(ISD::FREM, MVT::f64, Expand); 1003 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 1004 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 1005 setOperationAction(ISD::FNEG, MVT::f64, Expand); 1006 setOperationAction(ISD::FABS, MVT::f64, Expand); 1007 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 1008 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1009 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1010 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1011 setOperationAction(ISD::FLOG, MVT::f64, Expand); 1012 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 1013 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 1014 setOperationAction(ISD::FEXP, MVT::f64, Expand); 1015 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 1016 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 1017 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 1018 setOperationAction(ISD::FRINT, MVT::f64, Expand); 1019 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 1020 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 1021 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 1022 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 1023 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 1024 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 1025 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 1026 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 1027 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 1028 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 1029 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 1030 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom); 1031 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom); 1032 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 1033 } 1034 1035 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) { 1036 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 1037 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom); 1038 if (Subtarget->hasFullFP16()) { 1039 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 1040 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom); 1041 } 1042 } 1043 1044 if (!Subtarget->hasFP16()) { 1045 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 1046 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom); 1047 } 1048 1049 computeRegisterProperties(Subtarget->getRegisterInfo()); 1050 1051 // ARM does not have floating-point extending loads. 1052 for (MVT VT : MVT::fp_valuetypes()) { 1053 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 1054 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 1055 } 1056 1057 // ... or truncating stores 1058 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 1059 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 1060 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 1061 1062 // ARM does not have i1 sign extending load. 1063 for (MVT VT : MVT::integer_valuetypes()) 1064 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 1065 1066 // ARM supports all 4 flavors of integer indexed load / store. 1067 if (!Subtarget->isThumb1Only()) { 1068 for (unsigned im = (unsigned)ISD::PRE_INC; 1069 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 1070 setIndexedLoadAction(im, MVT::i1, Legal); 1071 setIndexedLoadAction(im, MVT::i8, Legal); 1072 setIndexedLoadAction(im, MVT::i16, Legal); 1073 setIndexedLoadAction(im, MVT::i32, Legal); 1074 setIndexedStoreAction(im, MVT::i1, Legal); 1075 setIndexedStoreAction(im, MVT::i8, Legal); 1076 setIndexedStoreAction(im, MVT::i16, Legal); 1077 setIndexedStoreAction(im, MVT::i32, Legal); 1078 } 1079 } else { 1080 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 1081 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 1082 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 1083 } 1084 1085 setOperationAction(ISD::SADDO, MVT::i32, Custom); 1086 setOperationAction(ISD::UADDO, MVT::i32, Custom); 1087 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 1088 setOperationAction(ISD::USUBO, MVT::i32, Custom); 1089 1090 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 1091 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 1092 if (Subtarget->hasDSP()) { 1093 setOperationAction(ISD::SADDSAT, MVT::i8, Custom); 1094 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom); 1095 setOperationAction(ISD::SADDSAT, MVT::i16, Custom); 1096 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom); 1097 } 1098 if (Subtarget->hasBaseDSP()) { 1099 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 1100 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 1101 } 1102 1103 // i64 operation support. 1104 setOperationAction(ISD::MUL, MVT::i64, Expand); 1105 setOperationAction(ISD::MULHU, MVT::i32, Expand); 1106 if (Subtarget->isThumb1Only()) { 1107 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 1108 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 1109 } 1110 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 1111 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 1112 setOperationAction(ISD::MULHS, MVT::i32, Expand); 1113 1114 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 1115 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 1116 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 1117 setOperationAction(ISD::SRL, MVT::i64, Custom); 1118 setOperationAction(ISD::SRA, MVT::i64, Custom); 1119 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 1120 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 1121 setOperationAction(ISD::LOAD, MVT::i64, Custom); 1122 setOperationAction(ISD::STORE, MVT::i64, Custom); 1123 1124 // MVE lowers 64 bit shifts to lsll and lsrl 1125 // assuming that ISD::SRL and SRA of i64 are already marked custom 1126 if (Subtarget->hasMVEIntegerOps()) 1127 setOperationAction(ISD::SHL, MVT::i64, Custom); 1128 1129 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 1130 if (Subtarget->isThumb1Only()) { 1131 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 1132 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 1133 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 1134 } 1135 1136 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 1137 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 1138 1139 // ARM does not have ROTL. 1140 setOperationAction(ISD::ROTL, MVT::i32, Expand); 1141 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 1142 setOperationAction(ISD::ROTL, VT, Expand); 1143 setOperationAction(ISD::ROTR, VT, Expand); 1144 } 1145 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1146 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1147 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1148 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1149 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1150 } 1151 1152 // @llvm.readcyclecounter requires the Performance Monitors extension. 1153 // Default to the 0 expansion on unsupported platforms. 1154 // FIXME: Technically there are older ARM CPUs that have 1155 // implementation-specific ways of obtaining this information. 1156 if (Subtarget->hasPerfMon()) 1157 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1158 1159 // Only ARMv6 has BSWAP. 1160 if (!Subtarget->hasV6Ops()) 1161 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1162 1163 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1164 : Subtarget->hasDivideInARMMode(); 1165 if (!hasDivide) { 1166 // These are expanded into libcalls if the cpu doesn't have HW divider. 1167 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1168 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1169 } 1170 1171 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1172 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1173 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1174 1175 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1176 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1177 } 1178 1179 setOperationAction(ISD::SREM, MVT::i32, Expand); 1180 setOperationAction(ISD::UREM, MVT::i32, Expand); 1181 1182 // Register based DivRem for AEABI (RTABI 4.2) 1183 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1184 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1185 Subtarget->isTargetWindows()) { 1186 setOperationAction(ISD::SREM, MVT::i64, Custom); 1187 setOperationAction(ISD::UREM, MVT::i64, Custom); 1188 HasStandaloneRem = false; 1189 1190 if (Subtarget->isTargetWindows()) { 1191 const struct { 1192 const RTLIB::Libcall Op; 1193 const char * const Name; 1194 const CallingConv::ID CC; 1195 } LibraryCalls[] = { 1196 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1197 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1198 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1199 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1200 1201 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1202 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1203 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1204 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1205 }; 1206 1207 for (const auto &LC : LibraryCalls) { 1208 setLibcallName(LC.Op, LC.Name); 1209 setLibcallCallingConv(LC.Op, LC.CC); 1210 } 1211 } else { 1212 const struct { 1213 const RTLIB::Libcall Op; 1214 const char * const Name; 1215 const CallingConv::ID CC; 1216 } LibraryCalls[] = { 1217 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1218 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1219 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1220 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1221 1222 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1223 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1224 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1225 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1226 }; 1227 1228 for (const auto &LC : LibraryCalls) { 1229 setLibcallName(LC.Op, LC.Name); 1230 setLibcallCallingConv(LC.Op, LC.CC); 1231 } 1232 } 1233 1234 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1235 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1236 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1237 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1238 } else { 1239 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1240 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1241 } 1242 1243 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 1244 // MSVCRT doesn't have powi; fall back to pow 1245 setLibcallName(RTLIB::POWI_F32, nullptr); 1246 setLibcallName(RTLIB::POWI_F64, nullptr); 1247 } 1248 1249 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1250 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1251 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1252 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1253 1254 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1255 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1256 1257 // Use the default implementation. 1258 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1259 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1260 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1261 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1262 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1263 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1264 1265 if (Subtarget->isTargetWindows()) 1266 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1267 else 1268 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1269 1270 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1271 // the default expansion. 1272 InsertFencesForAtomic = false; 1273 if (Subtarget->hasAnyDataBarrier() && 1274 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1275 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1276 // to ldrex/strex loops already. 1277 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1278 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1279 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1280 1281 // On v8, we have particularly efficient implementations of atomic fences 1282 // if they can be combined with nearby atomic loads and stores. 1283 if (!Subtarget->hasAcquireRelease() || 1284 getTargetMachine().getOptLevel() == 0) { 1285 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1286 InsertFencesForAtomic = true; 1287 } 1288 } else { 1289 // If there's anything we can use as a barrier, go through custom lowering 1290 // for ATOMIC_FENCE. 1291 // If target has DMB in thumb, Fences can be inserted. 1292 if (Subtarget->hasDataBarrier()) 1293 InsertFencesForAtomic = true; 1294 1295 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1296 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1297 1298 // Set them all for expansion, which will force libcalls. 1299 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1300 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1301 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1302 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1303 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1304 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1305 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1306 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1307 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1308 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1309 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1310 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1311 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1312 // Unordered/Monotonic case. 1313 if (!InsertFencesForAtomic) { 1314 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1315 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1316 } 1317 } 1318 1319 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1320 1321 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1322 if (!Subtarget->hasV6Ops()) { 1323 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1324 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1325 } 1326 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1327 1328 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1329 !Subtarget->isThumb1Only()) { 1330 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1331 // iff target supports vfp2. 1332 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1333 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1334 } 1335 1336 // We want to custom lower some of our intrinsics. 1337 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1338 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1339 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1340 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1341 if (Subtarget->useSjLjEH()) 1342 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1343 1344 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1345 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1346 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1347 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1348 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1349 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1350 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1351 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1352 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1353 if (Subtarget->hasFullFP16()) { 1354 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1355 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1356 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1357 } 1358 1359 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1360 1361 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1362 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1363 if (Subtarget->hasFullFP16()) 1364 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1365 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1366 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1367 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1368 1369 // We don't support sin/cos/fmod/copysign/pow 1370 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1371 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1372 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1373 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1374 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1375 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1376 setOperationAction(ISD::FREM, MVT::f64, Expand); 1377 setOperationAction(ISD::FREM, MVT::f32, Expand); 1378 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1379 !Subtarget->isThumb1Only()) { 1380 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1381 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1382 } 1383 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1384 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1385 1386 if (!Subtarget->hasVFP4Base()) { 1387 setOperationAction(ISD::FMA, MVT::f64, Expand); 1388 setOperationAction(ISD::FMA, MVT::f32, Expand); 1389 } 1390 1391 // Various VFP goodness 1392 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1393 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1394 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1395 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1396 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1397 } 1398 1399 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1400 if (!Subtarget->hasFP16()) { 1401 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1402 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1403 } 1404 1405 // Strict floating-point comparisons need custom lowering. 1406 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 1407 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 1408 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 1409 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 1410 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 1411 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 1412 } 1413 1414 // Use __sincos_stret if available. 1415 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1416 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1417 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1418 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1419 } 1420 1421 // FP-ARMv8 implements a lot of rounding-like FP operations. 1422 if (Subtarget->hasFPARMv8Base()) { 1423 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1424 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1425 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1426 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1427 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1428 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1429 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1430 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1431 if (Subtarget->hasNEON()) { 1432 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1433 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1434 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1435 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1436 } 1437 1438 if (Subtarget->hasFP64()) { 1439 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1440 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1441 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1442 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1443 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1444 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1445 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1446 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1447 } 1448 } 1449 1450 // FP16 often need to be promoted to call lib functions 1451 if (Subtarget->hasFullFP16()) { 1452 setOperationAction(ISD::FREM, MVT::f16, Promote); 1453 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1454 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1455 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1456 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1457 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1458 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1459 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1460 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1461 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1462 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1463 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1464 1465 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1466 } 1467 1468 if (Subtarget->hasNEON()) { 1469 // vmin and vmax aren't available in a scalar form, so we can use 1470 // a NEON instruction with an undef lane instead. This has a performance 1471 // penalty on some cores, so we don't do this unless we have been 1472 // asked to by the core tuning model. 1473 if (Subtarget->useNEONForSinglePrecisionFP()) { 1474 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1475 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1476 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1477 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1478 } 1479 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1480 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1481 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1482 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1483 1484 if (Subtarget->hasFullFP16()) { 1485 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1486 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1487 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1488 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1489 1490 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1491 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1492 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1493 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1494 } 1495 } 1496 1497 // We have target-specific dag combine patterns for the following nodes: 1498 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1499 setTargetDAGCombine(ISD::ADD); 1500 setTargetDAGCombine(ISD::SUB); 1501 setTargetDAGCombine(ISD::MUL); 1502 setTargetDAGCombine(ISD::AND); 1503 setTargetDAGCombine(ISD::OR); 1504 setTargetDAGCombine(ISD::XOR); 1505 1506 if (Subtarget->hasMVEIntegerOps()) 1507 setTargetDAGCombine(ISD::VSELECT); 1508 1509 if (Subtarget->hasV6Ops()) 1510 setTargetDAGCombine(ISD::SRL); 1511 if (Subtarget->isThumb1Only()) 1512 setTargetDAGCombine(ISD::SHL); 1513 1514 setStackPointerRegisterToSaveRestore(ARM::SP); 1515 1516 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1517 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1518 setSchedulingPreference(Sched::RegPressure); 1519 else 1520 setSchedulingPreference(Sched::Hybrid); 1521 1522 //// temporary - rewrite interface to use type 1523 MaxStoresPerMemset = 8; 1524 MaxStoresPerMemsetOptSize = 4; 1525 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1526 MaxStoresPerMemcpyOptSize = 2; 1527 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1528 MaxStoresPerMemmoveOptSize = 2; 1529 1530 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1531 // are at least 4 bytes aligned. 1532 setMinStackArgumentAlignment(Align(4)); 1533 1534 // Prefer likely predicted branches to selects on out-of-order cores. 1535 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1536 1537 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment())); 1538 1539 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4)); 1540 1541 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1542 setTargetDAGCombine(ISD::ABS); 1543 } 1544 1545 bool ARMTargetLowering::useSoftFloat() const { 1546 return Subtarget->useSoftFloat(); 1547 } 1548 1549 // FIXME: It might make sense to define the representative register class as the 1550 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1551 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1552 // SPR's representative would be DPR_VFP2. This should work well if register 1553 // pressure tracking were modified such that a register use would increment the 1554 // pressure of the register class's representative and all of it's super 1555 // classes' representatives transitively. We have not implemented this because 1556 // of the difficulty prior to coalescing of modeling operand register classes 1557 // due to the common occurrence of cross class copies and subregister insertions 1558 // and extractions. 1559 std::pair<const TargetRegisterClass *, uint8_t> 1560 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1561 MVT VT) const { 1562 const TargetRegisterClass *RRC = nullptr; 1563 uint8_t Cost = 1; 1564 switch (VT.SimpleTy) { 1565 default: 1566 return TargetLowering::findRepresentativeClass(TRI, VT); 1567 // Use DPR as representative register class for all floating point 1568 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1569 // the cost is 1 for both f32 and f64. 1570 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1571 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1572 RRC = &ARM::DPRRegClass; 1573 // When NEON is used for SP, only half of the register file is available 1574 // because operations that define both SP and DP results will be constrained 1575 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1576 // coalescing by double-counting the SP regs. See the FIXME above. 1577 if (Subtarget->useNEONForSinglePrecisionFP()) 1578 Cost = 2; 1579 break; 1580 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1581 case MVT::v4f32: case MVT::v2f64: 1582 RRC = &ARM::DPRRegClass; 1583 Cost = 2; 1584 break; 1585 case MVT::v4i64: 1586 RRC = &ARM::DPRRegClass; 1587 Cost = 4; 1588 break; 1589 case MVT::v8i64: 1590 RRC = &ARM::DPRRegClass; 1591 Cost = 8; 1592 break; 1593 } 1594 return std::make_pair(RRC, Cost); 1595 } 1596 1597 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1598 switch ((ARMISD::NodeType)Opcode) { 1599 case ARMISD::FIRST_NUMBER: break; 1600 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1601 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1602 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1603 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1604 case ARMISD::CALL: return "ARMISD::CALL"; 1605 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1606 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1607 case ARMISD::tSECALL: return "ARMISD::tSECALL"; 1608 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1609 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1610 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1611 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1612 case ARMISD::SERET_FLAG: return "ARMISD::SERET_FLAG"; 1613 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1614 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1615 case ARMISD::CMP: return "ARMISD::CMP"; 1616 case ARMISD::CMN: return "ARMISD::CMN"; 1617 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1618 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1619 case ARMISD::CMPFPE: return "ARMISD::CMPFPE"; 1620 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1621 case ARMISD::CMPFPEw0: return "ARMISD::CMPFPEw0"; 1622 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1623 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1624 1625 case ARMISD::CMOV: return "ARMISD::CMOV"; 1626 case ARMISD::SUBS: return "ARMISD::SUBS"; 1627 1628 case ARMISD::SSAT: return "ARMISD::SSAT"; 1629 case ARMISD::USAT: return "ARMISD::USAT"; 1630 1631 case ARMISD::ASRL: return "ARMISD::ASRL"; 1632 case ARMISD::LSRL: return "ARMISD::LSRL"; 1633 case ARMISD::LSLL: return "ARMISD::LSLL"; 1634 1635 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1636 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1637 case ARMISD::RRX: return "ARMISD::RRX"; 1638 1639 case ARMISD::ADDC: return "ARMISD::ADDC"; 1640 case ARMISD::ADDE: return "ARMISD::ADDE"; 1641 case ARMISD::SUBC: return "ARMISD::SUBC"; 1642 case ARMISD::SUBE: return "ARMISD::SUBE"; 1643 case ARMISD::LSLS: return "ARMISD::LSLS"; 1644 1645 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1646 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1647 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1648 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1649 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1650 1651 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1652 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1653 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1654 1655 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1656 1657 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1658 1659 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1660 1661 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1662 1663 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1664 1665 case ARMISD::LDRD: return "ARMISD::LDRD"; 1666 case ARMISD::STRD: return "ARMISD::STRD"; 1667 1668 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1669 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1670 1671 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST"; 1672 case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST"; 1673 case ARMISD::VCMP: return "ARMISD::VCMP"; 1674 case ARMISD::VCMPZ: return "ARMISD::VCMPZ"; 1675 case ARMISD::VTST: return "ARMISD::VTST"; 1676 1677 case ARMISD::VSHLs: return "ARMISD::VSHLs"; 1678 case ARMISD::VSHLu: return "ARMISD::VSHLu"; 1679 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM"; 1680 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM"; 1681 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM"; 1682 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM"; 1683 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM"; 1684 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM"; 1685 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM"; 1686 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM"; 1687 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM"; 1688 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM"; 1689 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM"; 1690 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM"; 1691 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM"; 1692 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM"; 1693 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM"; 1694 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM"; 1695 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM"; 1696 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1697 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1698 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1699 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1700 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1701 case ARMISD::VDUP: return "ARMISD::VDUP"; 1702 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1703 case ARMISD::VEXT: return "ARMISD::VEXT"; 1704 case ARMISD::VREV64: return "ARMISD::VREV64"; 1705 case ARMISD::VREV32: return "ARMISD::VREV32"; 1706 case ARMISD::VREV16: return "ARMISD::VREV16"; 1707 case ARMISD::VZIP: return "ARMISD::VZIP"; 1708 case ARMISD::VUZP: return "ARMISD::VUZP"; 1709 case ARMISD::VTRN: return "ARMISD::VTRN"; 1710 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1711 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1712 case ARMISD::VMOVN: return "ARMISD::VMOVN"; 1713 case ARMISD::VQMOVNs: return "ARMISD::VQMOVNs"; 1714 case ARMISD::VQMOVNu: return "ARMISD::VQMOVNu"; 1715 case ARMISD::VCVTN: return "ARMISD::VCVTN"; 1716 case ARMISD::VCVTL: return "ARMISD::VCVTL"; 1717 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1718 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1719 case ARMISD::VADDVs: return "ARMISD::VADDVs"; 1720 case ARMISD::VADDVu: return "ARMISD::VADDVu"; 1721 case ARMISD::VADDVps: return "ARMISD::VADDVps"; 1722 case ARMISD::VADDVpu: return "ARMISD::VADDVpu"; 1723 case ARMISD::VADDLVs: return "ARMISD::VADDLVs"; 1724 case ARMISD::VADDLVu: return "ARMISD::VADDLVu"; 1725 case ARMISD::VADDLVAs: return "ARMISD::VADDLVAs"; 1726 case ARMISD::VADDLVAu: return "ARMISD::VADDLVAu"; 1727 case ARMISD::VADDLVps: return "ARMISD::VADDLVps"; 1728 case ARMISD::VADDLVpu: return "ARMISD::VADDLVpu"; 1729 case ARMISD::VADDLVAps: return "ARMISD::VADDLVAps"; 1730 case ARMISD::VADDLVApu: return "ARMISD::VADDLVApu"; 1731 case ARMISD::VMLAVs: return "ARMISD::VMLAVs"; 1732 case ARMISD::VMLAVu: return "ARMISD::VMLAVu"; 1733 case ARMISD::VMLAVps: return "ARMISD::VMLAVps"; 1734 case ARMISD::VMLAVpu: return "ARMISD::VMLAVpu"; 1735 case ARMISD::VMLALVs: return "ARMISD::VMLALVs"; 1736 case ARMISD::VMLALVu: return "ARMISD::VMLALVu"; 1737 case ARMISD::VMLALVps: return "ARMISD::VMLALVps"; 1738 case ARMISD::VMLALVpu: return "ARMISD::VMLALVpu"; 1739 case ARMISD::VMLALVAs: return "ARMISD::VMLALVAs"; 1740 case ARMISD::VMLALVAu: return "ARMISD::VMLALVAu"; 1741 case ARMISD::VMLALVAps: return "ARMISD::VMLALVAps"; 1742 case ARMISD::VMLALVApu: return "ARMISD::VMLALVApu"; 1743 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1744 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1745 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1746 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1747 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1748 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1749 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1750 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1751 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1752 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1753 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1754 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1755 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1756 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1757 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1758 case ARMISD::QADD16b: return "ARMISD::QADD16b"; 1759 case ARMISD::QSUB16b: return "ARMISD::QSUB16b"; 1760 case ARMISD::QADD8b: return "ARMISD::QADD8b"; 1761 case ARMISD::QSUB8b: return "ARMISD::QSUB8b"; 1762 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1763 case ARMISD::BFI: return "ARMISD::BFI"; 1764 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1765 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1766 case ARMISD::VBSP: return "ARMISD::VBSP"; 1767 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1768 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1769 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1770 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1771 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1772 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1773 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1774 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1775 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1776 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1777 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1778 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1779 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1780 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1781 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1782 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1783 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1784 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1785 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1786 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1787 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1788 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1789 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1790 case ARMISD::WLS: return "ARMISD::WLS"; 1791 case ARMISD::LE: return "ARMISD::LE"; 1792 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1793 case ARMISD::CSINV: return "ARMISD::CSINV"; 1794 case ARMISD::CSNEG: return "ARMISD::CSNEG"; 1795 case ARMISD::CSINC: return "ARMISD::CSINC"; 1796 } 1797 return nullptr; 1798 } 1799 1800 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1801 EVT VT) const { 1802 if (!VT.isVector()) 1803 return getPointerTy(DL); 1804 1805 // MVE has a predicate register. 1806 if (Subtarget->hasMVEIntegerOps() && 1807 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1808 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1809 return VT.changeVectorElementTypeToInteger(); 1810 } 1811 1812 /// getRegClassFor - Return the register class that should be used for the 1813 /// specified value type. 1814 const TargetRegisterClass * 1815 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1816 (void)isDivergent; 1817 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1818 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1819 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1820 // MVE Q registers. 1821 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1822 if (VT == MVT::v4i64) 1823 return &ARM::QQPRRegClass; 1824 if (VT == MVT::v8i64) 1825 return &ARM::QQQQPRRegClass; 1826 } 1827 return TargetLowering::getRegClassFor(VT); 1828 } 1829 1830 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1831 // source/dest is aligned and the copy size is large enough. We therefore want 1832 // to align such objects passed to memory intrinsics. 1833 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1834 unsigned &PrefAlign) const { 1835 if (!isa<MemIntrinsic>(CI)) 1836 return false; 1837 MinSize = 8; 1838 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1839 // cycle faster than 4-byte aligned LDM. 1840 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1841 return true; 1842 } 1843 1844 // Create a fast isel object. 1845 FastISel * 1846 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1847 const TargetLibraryInfo *libInfo) const { 1848 return ARM::createFastISel(funcInfo, libInfo); 1849 } 1850 1851 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1852 unsigned NumVals = N->getNumValues(); 1853 if (!NumVals) 1854 return Sched::RegPressure; 1855 1856 for (unsigned i = 0; i != NumVals; ++i) { 1857 EVT VT = N->getValueType(i); 1858 if (VT == MVT::Glue || VT == MVT::Other) 1859 continue; 1860 if (VT.isFloatingPoint() || VT.isVector()) 1861 return Sched::ILP; 1862 } 1863 1864 if (!N->isMachineOpcode()) 1865 return Sched::RegPressure; 1866 1867 // Load are scheduled for latency even if there instruction itinerary 1868 // is not available. 1869 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1870 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1871 1872 if (MCID.getNumDefs() == 0) 1873 return Sched::RegPressure; 1874 if (!Itins->isEmpty() && 1875 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1876 return Sched::ILP; 1877 1878 return Sched::RegPressure; 1879 } 1880 1881 //===----------------------------------------------------------------------===// 1882 // Lowering Code 1883 //===----------------------------------------------------------------------===// 1884 1885 static bool isSRL16(const SDValue &Op) { 1886 if (Op.getOpcode() != ISD::SRL) 1887 return false; 1888 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1889 return Const->getZExtValue() == 16; 1890 return false; 1891 } 1892 1893 static bool isSRA16(const SDValue &Op) { 1894 if (Op.getOpcode() != ISD::SRA) 1895 return false; 1896 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1897 return Const->getZExtValue() == 16; 1898 return false; 1899 } 1900 1901 static bool isSHL16(const SDValue &Op) { 1902 if (Op.getOpcode() != ISD::SHL) 1903 return false; 1904 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1905 return Const->getZExtValue() == 16; 1906 return false; 1907 } 1908 1909 // Check for a signed 16-bit value. We special case SRA because it makes it 1910 // more simple when also looking for SRAs that aren't sign extending a 1911 // smaller value. Without the check, we'd need to take extra care with 1912 // checking order for some operations. 1913 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1914 if (isSRA16(Op)) 1915 return isSHL16(Op.getOperand(0)); 1916 return DAG.ComputeNumSignBits(Op) == 17; 1917 } 1918 1919 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1920 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1921 switch (CC) { 1922 default: llvm_unreachable("Unknown condition code!"); 1923 case ISD::SETNE: return ARMCC::NE; 1924 case ISD::SETEQ: return ARMCC::EQ; 1925 case ISD::SETGT: return ARMCC::GT; 1926 case ISD::SETGE: return ARMCC::GE; 1927 case ISD::SETLT: return ARMCC::LT; 1928 case ISD::SETLE: return ARMCC::LE; 1929 case ISD::SETUGT: return ARMCC::HI; 1930 case ISD::SETUGE: return ARMCC::HS; 1931 case ISD::SETULT: return ARMCC::LO; 1932 case ISD::SETULE: return ARMCC::LS; 1933 } 1934 } 1935 1936 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1937 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1938 ARMCC::CondCodes &CondCode2) { 1939 CondCode2 = ARMCC::AL; 1940 switch (CC) { 1941 default: llvm_unreachable("Unknown FP condition!"); 1942 case ISD::SETEQ: 1943 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1944 case ISD::SETGT: 1945 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1946 case ISD::SETGE: 1947 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1948 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1949 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1950 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1951 case ISD::SETO: CondCode = ARMCC::VC; break; 1952 case ISD::SETUO: CondCode = ARMCC::VS; break; 1953 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1954 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1955 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1956 case ISD::SETLT: 1957 case ISD::SETULT: CondCode = ARMCC::LT; break; 1958 case ISD::SETLE: 1959 case ISD::SETULE: CondCode = ARMCC::LE; break; 1960 case ISD::SETNE: 1961 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1962 } 1963 } 1964 1965 //===----------------------------------------------------------------------===// 1966 // Calling Convention Implementation 1967 //===----------------------------------------------------------------------===// 1968 1969 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1970 /// account presence of floating point hardware and calling convention 1971 /// limitations, such as support for variadic functions. 1972 CallingConv::ID 1973 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1974 bool isVarArg) const { 1975 switch (CC) { 1976 default: 1977 report_fatal_error("Unsupported calling convention"); 1978 case CallingConv::ARM_AAPCS: 1979 case CallingConv::ARM_APCS: 1980 case CallingConv::GHC: 1981 case CallingConv::CFGuard_Check: 1982 return CC; 1983 case CallingConv::PreserveMost: 1984 return CallingConv::PreserveMost; 1985 case CallingConv::ARM_AAPCS_VFP: 1986 case CallingConv::Swift: 1987 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1988 case CallingConv::C: 1989 if (!Subtarget->isAAPCS_ABI()) 1990 return CallingConv::ARM_APCS; 1991 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1992 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1993 !isVarArg) 1994 return CallingConv::ARM_AAPCS_VFP; 1995 else 1996 return CallingConv::ARM_AAPCS; 1997 case CallingConv::Fast: 1998 case CallingConv::CXX_FAST_TLS: 1999 if (!Subtarget->isAAPCS_ABI()) { 2000 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 2001 return CallingConv::Fast; 2002 return CallingConv::ARM_APCS; 2003 } else if (Subtarget->hasVFP2Base() && 2004 !Subtarget->isThumb1Only() && !isVarArg) 2005 return CallingConv::ARM_AAPCS_VFP; 2006 else 2007 return CallingConv::ARM_AAPCS; 2008 } 2009 } 2010 2011 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2012 bool isVarArg) const { 2013 return CCAssignFnForNode(CC, false, isVarArg); 2014 } 2015 2016 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 2017 bool isVarArg) const { 2018 return CCAssignFnForNode(CC, true, isVarArg); 2019 } 2020 2021 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 2022 /// CallingConvention. 2023 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 2024 bool Return, 2025 bool isVarArg) const { 2026 switch (getEffectiveCallingConv(CC, isVarArg)) { 2027 default: 2028 report_fatal_error("Unsupported calling convention"); 2029 case CallingConv::ARM_APCS: 2030 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 2031 case CallingConv::ARM_AAPCS: 2032 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 2033 case CallingConv::ARM_AAPCS_VFP: 2034 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 2035 case CallingConv::Fast: 2036 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 2037 case CallingConv::GHC: 2038 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 2039 case CallingConv::PreserveMost: 2040 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 2041 case CallingConv::CFGuard_Check: 2042 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check); 2043 } 2044 } 2045 2046 SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG, 2047 MVT LocVT, MVT ValVT, SDValue Val) const { 2048 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()), 2049 Val); 2050 if (Subtarget->hasFullFP16()) { 2051 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val); 2052 } else { 2053 Val = DAG.getNode(ISD::TRUNCATE, dl, 2054 MVT::getIntegerVT(ValVT.getSizeInBits()), Val); 2055 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val); 2056 } 2057 return Val; 2058 } 2059 2060 SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG, 2061 MVT LocVT, MVT ValVT, 2062 SDValue Val) const { 2063 if (Subtarget->hasFullFP16()) { 2064 Val = DAG.getNode(ARMISD::VMOVrh, dl, 2065 MVT::getIntegerVT(LocVT.getSizeInBits()), Val); 2066 } else { 2067 Val = DAG.getNode(ISD::BITCAST, dl, 2068 MVT::getIntegerVT(ValVT.getSizeInBits()), Val); 2069 Val = DAG.getNode(ISD::ZERO_EXTEND, dl, 2070 MVT::getIntegerVT(LocVT.getSizeInBits()), Val); 2071 } 2072 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val); 2073 } 2074 2075 /// LowerCallResult - Lower the result values of a call into the 2076 /// appropriate copies out of appropriate physical registers. 2077 SDValue ARMTargetLowering::LowerCallResult( 2078 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2079 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 2080 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2081 SDValue ThisVal) const { 2082 // Assign locations to each value returned by this call. 2083 SmallVector<CCValAssign, 16> RVLocs; 2084 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2085 *DAG.getContext()); 2086 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 2087 2088 // Copy all of the result registers out of their specified physreg. 2089 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2090 CCValAssign VA = RVLocs[i]; 2091 2092 // Pass 'this' value directly from the argument to return value, to avoid 2093 // reg unit interference 2094 if (i == 0 && isThisReturn) { 2095 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 2096 "unexpected return calling convention register assignment"); 2097 InVals.push_back(ThisVal); 2098 continue; 2099 } 2100 2101 SDValue Val; 2102 if (VA.needsCustom() && 2103 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) { 2104 // Handle f64 or half of a v2f64. 2105 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2106 InFlag); 2107 Chain = Lo.getValue(1); 2108 InFlag = Lo.getValue(2); 2109 VA = RVLocs[++i]; // skip ahead to next loc 2110 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2111 InFlag); 2112 Chain = Hi.getValue(1); 2113 InFlag = Hi.getValue(2); 2114 if (!Subtarget->isLittle()) 2115 std::swap (Lo, Hi); 2116 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2117 2118 if (VA.getLocVT() == MVT::v2f64) { 2119 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 2120 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2121 DAG.getConstant(0, dl, MVT::i32)); 2122 2123 VA = RVLocs[++i]; // skip ahead to next loc 2124 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2125 Chain = Lo.getValue(1); 2126 InFlag = Lo.getValue(2); 2127 VA = RVLocs[++i]; // skip ahead to next loc 2128 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2129 Chain = Hi.getValue(1); 2130 InFlag = Hi.getValue(2); 2131 if (!Subtarget->isLittle()) 2132 std::swap (Lo, Hi); 2133 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2134 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2135 DAG.getConstant(1, dl, MVT::i32)); 2136 } 2137 } else { 2138 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 2139 InFlag); 2140 Chain = Val.getValue(1); 2141 InFlag = Val.getValue(2); 2142 } 2143 2144 switch (VA.getLocInfo()) { 2145 default: llvm_unreachable("Unknown loc info!"); 2146 case CCValAssign::Full: break; 2147 case CCValAssign::BCvt: 2148 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 2149 break; 2150 } 2151 2152 // f16 arguments have their size extended to 4 bytes and passed as if they 2153 // had been copied to the LSBs of a 32-bit register. 2154 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 2155 if (VA.needsCustom() && 2156 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) 2157 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val); 2158 2159 InVals.push_back(Val); 2160 } 2161 2162 return Chain; 2163 } 2164 2165 /// LowerMemOpCallTo - Store the argument to the stack. 2166 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 2167 SDValue Arg, const SDLoc &dl, 2168 SelectionDAG &DAG, 2169 const CCValAssign &VA, 2170 ISD::ArgFlagsTy Flags) const { 2171 unsigned LocMemOffset = VA.getLocMemOffset(); 2172 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2173 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 2174 StackPtr, PtrOff); 2175 return DAG.getStore( 2176 Chain, dl, Arg, PtrOff, 2177 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 2178 } 2179 2180 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 2181 SDValue Chain, SDValue &Arg, 2182 RegsToPassVector &RegsToPass, 2183 CCValAssign &VA, CCValAssign &NextVA, 2184 SDValue &StackPtr, 2185 SmallVectorImpl<SDValue> &MemOpChains, 2186 ISD::ArgFlagsTy Flags) const { 2187 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2188 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2189 unsigned id = Subtarget->isLittle() ? 0 : 1; 2190 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 2191 2192 if (NextVA.isRegLoc()) 2193 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 2194 else { 2195 assert(NextVA.isMemLoc()); 2196 if (!StackPtr.getNode()) 2197 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 2198 getPointerTy(DAG.getDataLayout())); 2199 2200 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 2201 dl, DAG, NextVA, 2202 Flags)); 2203 } 2204 } 2205 2206 /// LowerCall - Lowering a call into a callseq_start <- 2207 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 2208 /// nodes. 2209 SDValue 2210 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2211 SmallVectorImpl<SDValue> &InVals) const { 2212 SelectionDAG &DAG = CLI.DAG; 2213 SDLoc &dl = CLI.DL; 2214 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2215 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2216 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2217 SDValue Chain = CLI.Chain; 2218 SDValue Callee = CLI.Callee; 2219 bool &isTailCall = CLI.IsTailCall; 2220 CallingConv::ID CallConv = CLI.CallConv; 2221 bool doesNotRet = CLI.DoesNotReturn; 2222 bool isVarArg = CLI.IsVarArg; 2223 2224 MachineFunction &MF = DAG.getMachineFunction(); 2225 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2226 MachineFunction::CallSiteInfo CSInfo; 2227 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2228 bool isThisReturn = false; 2229 bool isCmseNSCall = false; 2230 bool PreferIndirect = false; 2231 2232 // Determine whether this is a non-secure function call. 2233 if (CLI.CB && CLI.CB->getAttributes().hasFnAttribute("cmse_nonsecure_call")) 2234 isCmseNSCall = true; 2235 2236 // Disable tail calls if they're not supported. 2237 if (!Subtarget->supportsTailCall()) 2238 isTailCall = false; 2239 2240 // For both the non-secure calls and the returns from a CMSE entry function, 2241 // the function needs to do some extra work afte r the call, or before the 2242 // return, respectively, thus it cannot end with atail call 2243 if (isCmseNSCall || AFI->isCmseNSEntryFunction()) 2244 isTailCall = false; 2245 2246 if (isa<GlobalAddressSDNode>(Callee)) { 2247 // If we're optimizing for minimum size and the function is called three or 2248 // more times in this block, we can improve codesize by calling indirectly 2249 // as BLXr has a 16-bit encoding. 2250 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2251 if (CLI.CB) { 2252 auto *BB = CLI.CB->getParent(); 2253 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2254 count_if(GV->users(), [&BB](const User *U) { 2255 return isa<Instruction>(U) && 2256 cast<Instruction>(U)->getParent() == BB; 2257 }) > 2; 2258 } 2259 } 2260 if (isTailCall) { 2261 // Check if it's really possible to do a tail call. 2262 isTailCall = IsEligibleForTailCallOptimization( 2263 Callee, CallConv, isVarArg, isStructRet, 2264 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2265 PreferIndirect); 2266 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall()) 2267 report_fatal_error("failed to perform tail call elimination on a call " 2268 "site marked musttail"); 2269 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2270 // detected sibcalls. 2271 if (isTailCall) 2272 ++NumTailCalls; 2273 } 2274 2275 // Analyze operands of the call, assigning locations to each operand. 2276 SmallVector<CCValAssign, 16> ArgLocs; 2277 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2278 *DAG.getContext()); 2279 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2280 2281 // Get a count of how many bytes are to be pushed on the stack. 2282 unsigned NumBytes = CCInfo.getNextStackOffset(); 2283 2284 if (isTailCall) { 2285 // For tail calls, memory operands are available in our caller's stack. 2286 NumBytes = 0; 2287 } else { 2288 // Adjust the stack pointer for the new arguments... 2289 // These operations are automatically eliminated by the prolog/epilog pass 2290 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2291 } 2292 2293 SDValue StackPtr = 2294 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2295 2296 RegsToPassVector RegsToPass; 2297 SmallVector<SDValue, 8> MemOpChains; 2298 2299 // Walk the register/memloc assignments, inserting copies/loads. In the case 2300 // of tail call optimization, arguments are handled later. 2301 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2302 i != e; 2303 ++i, ++realArgIdx) { 2304 CCValAssign &VA = ArgLocs[i]; 2305 SDValue Arg = OutVals[realArgIdx]; 2306 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2307 bool isByVal = Flags.isByVal(); 2308 2309 // Promote the value if needed. 2310 switch (VA.getLocInfo()) { 2311 default: llvm_unreachable("Unknown loc info!"); 2312 case CCValAssign::Full: break; 2313 case CCValAssign::SExt: 2314 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2315 break; 2316 case CCValAssign::ZExt: 2317 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2318 break; 2319 case CCValAssign::AExt: 2320 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2321 break; 2322 case CCValAssign::BCvt: 2323 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2324 break; 2325 } 2326 2327 // f16 arguments have their size extended to 4 bytes and passed as if they 2328 // had been copied to the LSBs of a 32-bit register. 2329 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 2330 if (VA.needsCustom() && 2331 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) { 2332 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg); 2333 } else { 2334 // f16 arguments could have been extended prior to argument lowering. 2335 // Mask them arguments if this is a CMSE nonsecure call. 2336 auto ArgVT = Outs[realArgIdx].ArgVT; 2337 if (isCmseNSCall && (ArgVT == MVT::f16)) { 2338 auto LocBits = VA.getLocVT().getSizeInBits(); 2339 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits()); 2340 SDValue Mask = 2341 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits)); 2342 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg); 2343 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask); 2344 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2345 } 2346 } 2347 2348 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2349 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) { 2350 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2351 DAG.getConstant(0, dl, MVT::i32)); 2352 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2353 DAG.getConstant(1, dl, MVT::i32)); 2354 2355 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i], 2356 StackPtr, MemOpChains, Flags); 2357 2358 VA = ArgLocs[++i]; // skip ahead to next loc 2359 if (VA.isRegLoc()) { 2360 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i], 2361 StackPtr, MemOpChains, Flags); 2362 } else { 2363 assert(VA.isMemLoc()); 2364 2365 MemOpChains.push_back( 2366 LowerMemOpCallTo(Chain, StackPtr, Op1, dl, DAG, VA, Flags)); 2367 } 2368 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) { 2369 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2370 StackPtr, MemOpChains, Flags); 2371 } else if (VA.isRegLoc()) { 2372 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2373 Outs[0].VT == MVT::i32) { 2374 assert(VA.getLocVT() == MVT::i32 && 2375 "unexpected calling convention register assignment"); 2376 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2377 "unexpected use of 'returned'"); 2378 isThisReturn = true; 2379 } 2380 const TargetOptions &Options = DAG.getTarget().Options; 2381 if (Options.EmitCallSiteInfo) 2382 CSInfo.emplace_back(VA.getLocReg(), i); 2383 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2384 } else if (isByVal) { 2385 assert(VA.isMemLoc()); 2386 unsigned offset = 0; 2387 2388 // True if this byval aggregate will be split between registers 2389 // and memory. 2390 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2391 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2392 2393 if (CurByValIdx < ByValArgsCount) { 2394 2395 unsigned RegBegin, RegEnd; 2396 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2397 2398 EVT PtrVT = 2399 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2400 unsigned int i, j; 2401 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2402 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2403 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2404 SDValue Load = 2405 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(), 2406 DAG.InferPtrAlign(AddArg)); 2407 MemOpChains.push_back(Load.getValue(1)); 2408 RegsToPass.push_back(std::make_pair(j, Load)); 2409 } 2410 2411 // If parameter size outsides register area, "offset" value 2412 // helps us to calculate stack slot for remained part properly. 2413 offset = RegEnd - RegBegin; 2414 2415 CCInfo.nextInRegsParam(); 2416 } 2417 2418 if (Flags.getByValSize() > 4*offset) { 2419 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2420 unsigned LocMemOffset = VA.getLocMemOffset(); 2421 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2422 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2423 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2424 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2425 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2426 MVT::i32); 2427 SDValue AlignNode = 2428 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32); 2429 2430 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2431 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2432 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2433 Ops)); 2434 } 2435 } else if (!isTailCall) { 2436 assert(VA.isMemLoc()); 2437 2438 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2439 dl, DAG, VA, Flags)); 2440 } 2441 } 2442 2443 if (!MemOpChains.empty()) 2444 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2445 2446 // Build a sequence of copy-to-reg nodes chained together with token chain 2447 // and flag operands which copy the outgoing args into the appropriate regs. 2448 SDValue InFlag; 2449 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2450 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2451 RegsToPass[i].second, InFlag); 2452 InFlag = Chain.getValue(1); 2453 } 2454 2455 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2456 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2457 // node so that legalize doesn't hack it. 2458 bool isDirect = false; 2459 2460 const TargetMachine &TM = getTargetMachine(); 2461 const Module *Mod = MF.getFunction().getParent(); 2462 const GlobalValue *GV = nullptr; 2463 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2464 GV = G->getGlobal(); 2465 bool isStub = 2466 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2467 2468 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2469 bool isLocalARMFunc = false; 2470 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2471 2472 if (Subtarget->genLongCalls()) { 2473 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2474 "long-calls codegen is not position independent!"); 2475 // Handle a global address or an external symbol. If it's not one of 2476 // those, the target's already in a register, so we don't need to do 2477 // anything extra. 2478 if (isa<GlobalAddressSDNode>(Callee)) { 2479 // Create a constant pool entry for the callee address 2480 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2481 ARMConstantPoolValue *CPV = 2482 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2483 2484 // Get the address of the callee into a register 2485 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2486 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2487 Callee = DAG.getLoad( 2488 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2489 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2490 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2491 const char *Sym = S->getSymbol(); 2492 2493 // Create a constant pool entry for the callee address 2494 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2495 ARMConstantPoolValue *CPV = 2496 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2497 ARMPCLabelIndex, 0); 2498 // Get the address of the callee into a register 2499 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2500 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2501 Callee = DAG.getLoad( 2502 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2503 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2504 } 2505 } else if (isa<GlobalAddressSDNode>(Callee)) { 2506 if (!PreferIndirect) { 2507 isDirect = true; 2508 bool isDef = GV->isStrongDefinitionForLinker(); 2509 2510 // ARM call to a local ARM function is predicable. 2511 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2512 // tBX takes a register source operand. 2513 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2514 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2515 Callee = DAG.getNode( 2516 ARMISD::WrapperPIC, dl, PtrVt, 2517 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2518 Callee = DAG.getLoad( 2519 PtrVt, dl, DAG.getEntryNode(), Callee, 2520 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2521 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2522 MachineMemOperand::MOInvariant); 2523 } else if (Subtarget->isTargetCOFF()) { 2524 assert(Subtarget->isTargetWindows() && 2525 "Windows is the only supported COFF target"); 2526 unsigned TargetFlags = ARMII::MO_NO_FLAG; 2527 if (GV->hasDLLImportStorageClass()) 2528 TargetFlags = ARMII::MO_DLLIMPORT; 2529 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 2530 TargetFlags = ARMII::MO_COFFSTUB; 2531 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2532 TargetFlags); 2533 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 2534 Callee = 2535 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2536 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2537 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2538 } else { 2539 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2540 } 2541 } 2542 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2543 isDirect = true; 2544 // tBX takes a register source operand. 2545 const char *Sym = S->getSymbol(); 2546 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2547 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2548 ARMConstantPoolValue *CPV = 2549 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2550 ARMPCLabelIndex, 4); 2551 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2552 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2553 Callee = DAG.getLoad( 2554 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2555 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2556 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2557 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2558 } else { 2559 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2560 } 2561 } 2562 2563 if (isCmseNSCall) { 2564 assert(!isARMFunc && !isDirect && 2565 "Cannot handle call to ARM function or direct call"); 2566 if (NumBytes > 0) { 2567 DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(), 2568 "call to non-secure function would " 2569 "require passing arguments on stack", 2570 dl.getDebugLoc()); 2571 DAG.getContext()->diagnose(Diag); 2572 } 2573 if (isStructRet) { 2574 DiagnosticInfoUnsupported Diag( 2575 DAG.getMachineFunction().getFunction(), 2576 "call to non-secure function would return value through pointer", 2577 dl.getDebugLoc()); 2578 DAG.getContext()->diagnose(Diag); 2579 } 2580 } 2581 2582 // FIXME: handle tail calls differently. 2583 unsigned CallOpc; 2584 if (Subtarget->isThumb()) { 2585 if (isCmseNSCall) 2586 CallOpc = ARMISD::tSECALL; 2587 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2588 CallOpc = ARMISD::CALL_NOLINK; 2589 else 2590 CallOpc = ARMISD::CALL; 2591 } else { 2592 if (!isDirect && !Subtarget->hasV5TOps()) 2593 CallOpc = ARMISD::CALL_NOLINK; 2594 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2595 // Emit regular call when code size is the priority 2596 !Subtarget->hasMinSize()) 2597 // "mov lr, pc; b _foo" to avoid confusing the RSP 2598 CallOpc = ARMISD::CALL_NOLINK; 2599 else 2600 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2601 } 2602 2603 std::vector<SDValue> Ops; 2604 Ops.push_back(Chain); 2605 Ops.push_back(Callee); 2606 2607 // Add argument registers to the end of the list so that they are known live 2608 // into the call. 2609 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2610 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2611 RegsToPass[i].second.getValueType())); 2612 2613 // Add a register mask operand representing the call-preserved registers. 2614 if (!isTailCall) { 2615 const uint32_t *Mask; 2616 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2617 if (isThisReturn) { 2618 // For 'this' returns, use the R0-preserving mask if applicable 2619 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2620 if (!Mask) { 2621 // Set isThisReturn to false if the calling convention is not one that 2622 // allows 'returned' to be modeled in this way, so LowerCallResult does 2623 // not try to pass 'this' straight through 2624 isThisReturn = false; 2625 Mask = ARI->getCallPreservedMask(MF, CallConv); 2626 } 2627 } else 2628 Mask = ARI->getCallPreservedMask(MF, CallConv); 2629 2630 assert(Mask && "Missing call preserved mask for calling convention"); 2631 Ops.push_back(DAG.getRegisterMask(Mask)); 2632 } 2633 2634 if (InFlag.getNode()) 2635 Ops.push_back(InFlag); 2636 2637 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2638 if (isTailCall) { 2639 MF.getFrameInfo().setHasTailCall(); 2640 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2641 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 2642 return Ret; 2643 } 2644 2645 // Returns a chain and a flag for retval copy to use. 2646 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2647 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 2648 InFlag = Chain.getValue(1); 2649 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 2650 2651 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2652 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2653 if (!Ins.empty()) 2654 InFlag = Chain.getValue(1); 2655 2656 // Handle result values, copying them out of physregs into vregs that we 2657 // return. 2658 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2659 InVals, isThisReturn, 2660 isThisReturn ? OutVals[0] : SDValue()); 2661 } 2662 2663 /// HandleByVal - Every parameter *after* a byval parameter is passed 2664 /// on the stack. Remember the next parameter register to allocate, 2665 /// and then confiscate the rest of the parameter registers to insure 2666 /// this. 2667 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2668 Align Alignment) const { 2669 // Byval (as with any stack) slots are always at least 4 byte aligned. 2670 Alignment = std::max(Alignment, Align(4)); 2671 2672 unsigned Reg = State->AllocateReg(GPRArgRegs); 2673 if (!Reg) 2674 return; 2675 2676 unsigned AlignInRegs = Alignment.value() / 4; 2677 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2678 for (unsigned i = 0; i < Waste; ++i) 2679 Reg = State->AllocateReg(GPRArgRegs); 2680 2681 if (!Reg) 2682 return; 2683 2684 unsigned Excess = 4 * (ARM::R4 - Reg); 2685 2686 // Special case when NSAA != SP and parameter size greater than size of 2687 // all remained GPR regs. In that case we can't split parameter, we must 2688 // send it to stack. We also must set NCRN to R4, so waste all 2689 // remained registers. 2690 const unsigned NSAAOffset = State->getNextStackOffset(); 2691 if (NSAAOffset != 0 && Size > Excess) { 2692 while (State->AllocateReg(GPRArgRegs)) 2693 ; 2694 return; 2695 } 2696 2697 // First register for byval parameter is the first register that wasn't 2698 // allocated before this method call, so it would be "reg". 2699 // If parameter is small enough to be saved in range [reg, r4), then 2700 // the end (first after last) register would be reg + param-size-in-regs, 2701 // else parameter would be splitted between registers and stack, 2702 // end register would be r4 in this case. 2703 unsigned ByValRegBegin = Reg; 2704 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2705 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2706 // Note, first register is allocated in the beginning of function already, 2707 // allocate remained amount of registers we need. 2708 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2709 State->AllocateReg(GPRArgRegs); 2710 // A byval parameter that is split between registers and memory needs its 2711 // size truncated here. 2712 // In the case where the entire structure fits in registers, we set the 2713 // size in memory to zero. 2714 Size = std::max<int>(Size - Excess, 0); 2715 } 2716 2717 /// MatchingStackOffset - Return true if the given stack call argument is 2718 /// already available in the same position (relatively) of the caller's 2719 /// incoming argument stack. 2720 static 2721 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2722 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2723 const TargetInstrInfo *TII) { 2724 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2725 int FI = std::numeric_limits<int>::max(); 2726 if (Arg.getOpcode() == ISD::CopyFromReg) { 2727 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2728 if (!Register::isVirtualRegister(VR)) 2729 return false; 2730 MachineInstr *Def = MRI->getVRegDef(VR); 2731 if (!Def) 2732 return false; 2733 if (!Flags.isByVal()) { 2734 if (!TII->isLoadFromStackSlot(*Def, FI)) 2735 return false; 2736 } else { 2737 return false; 2738 } 2739 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2740 if (Flags.isByVal()) 2741 // ByVal argument is passed in as a pointer but it's now being 2742 // dereferenced. e.g. 2743 // define @foo(%struct.X* %A) { 2744 // tail call @bar(%struct.X* byval %A) 2745 // } 2746 return false; 2747 SDValue Ptr = Ld->getBasePtr(); 2748 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2749 if (!FINode) 2750 return false; 2751 FI = FINode->getIndex(); 2752 } else 2753 return false; 2754 2755 assert(FI != std::numeric_limits<int>::max()); 2756 if (!MFI.isFixedObjectIndex(FI)) 2757 return false; 2758 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2759 } 2760 2761 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2762 /// for tail call optimization. Targets which want to do tail call 2763 /// optimization should implement this function. 2764 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2765 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2766 bool isCalleeStructRet, bool isCallerStructRet, 2767 const SmallVectorImpl<ISD::OutputArg> &Outs, 2768 const SmallVectorImpl<SDValue> &OutVals, 2769 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2770 const bool isIndirect) const { 2771 MachineFunction &MF = DAG.getMachineFunction(); 2772 const Function &CallerF = MF.getFunction(); 2773 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2774 2775 assert(Subtarget->supportsTailCall()); 2776 2777 // Indirect tail calls cannot be optimized for Thumb1 if the args 2778 // to the call take up r0-r3. The reason is that there are no legal registers 2779 // left to hold the pointer to the function to be called. 2780 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2781 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2782 return false; 2783 2784 // Look for obvious safe cases to perform tail call optimization that do not 2785 // require ABI changes. This is what gcc calls sibcall. 2786 2787 // Exception-handling functions need a special set of instructions to indicate 2788 // a return to the hardware. Tail-calling another function would probably 2789 // break this. 2790 if (CallerF.hasFnAttribute("interrupt")) 2791 return false; 2792 2793 // Also avoid sibcall optimization if either caller or callee uses struct 2794 // return semantics. 2795 if (isCalleeStructRet || isCallerStructRet) 2796 return false; 2797 2798 // Externally-defined functions with weak linkage should not be 2799 // tail-called on ARM when the OS does not support dynamic 2800 // pre-emption of symbols, as the AAELF spec requires normal calls 2801 // to undefined weak functions to be replaced with a NOP or jump to the 2802 // next instruction. The behaviour of branch instructions in this 2803 // situation (as used for tail calls) is implementation-defined, so we 2804 // cannot rely on the linker replacing the tail call with a return. 2805 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2806 const GlobalValue *GV = G->getGlobal(); 2807 const Triple &TT = getTargetMachine().getTargetTriple(); 2808 if (GV->hasExternalWeakLinkage() && 2809 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2810 return false; 2811 } 2812 2813 // Check that the call results are passed in the same way. 2814 LLVMContext &C = *DAG.getContext(); 2815 if (!CCState::resultsCompatible( 2816 getEffectiveCallingConv(CalleeCC, isVarArg), 2817 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins, 2818 CCAssignFnForReturn(CalleeCC, isVarArg), 2819 CCAssignFnForReturn(CallerCC, CallerF.isVarArg()))) 2820 return false; 2821 // The callee has to preserve all registers the caller needs to preserve. 2822 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2823 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2824 if (CalleeCC != CallerCC) { 2825 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2826 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2827 return false; 2828 } 2829 2830 // If Caller's vararg or byval argument has been split between registers and 2831 // stack, do not perform tail call, since part of the argument is in caller's 2832 // local frame. 2833 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2834 if (AFI_Caller->getArgRegsSaveSize()) 2835 return false; 2836 2837 // If the callee takes no arguments then go on to check the results of the 2838 // call. 2839 if (!Outs.empty()) { 2840 // Check if stack adjustment is needed. For now, do not do this if any 2841 // argument is passed on the stack. 2842 SmallVector<CCValAssign, 16> ArgLocs; 2843 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2844 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2845 if (CCInfo.getNextStackOffset()) { 2846 // Check if the arguments are already laid out in the right way as 2847 // the caller's fixed stack objects. 2848 MachineFrameInfo &MFI = MF.getFrameInfo(); 2849 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2850 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2851 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2852 i != e; 2853 ++i, ++realArgIdx) { 2854 CCValAssign &VA = ArgLocs[i]; 2855 EVT RegVT = VA.getLocVT(); 2856 SDValue Arg = OutVals[realArgIdx]; 2857 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2858 if (VA.getLocInfo() == CCValAssign::Indirect) 2859 return false; 2860 if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) { 2861 // f64 and vector types are split into multiple registers or 2862 // register/stack-slot combinations. The types will not match 2863 // the registers; give up on memory f64 refs until we figure 2864 // out what to do about this. 2865 if (!VA.isRegLoc()) 2866 return false; 2867 if (!ArgLocs[++i].isRegLoc()) 2868 return false; 2869 if (RegVT == MVT::v2f64) { 2870 if (!ArgLocs[++i].isRegLoc()) 2871 return false; 2872 if (!ArgLocs[++i].isRegLoc()) 2873 return false; 2874 } 2875 } else if (!VA.isRegLoc()) { 2876 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2877 MFI, MRI, TII)) 2878 return false; 2879 } 2880 } 2881 } 2882 2883 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2884 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2885 return false; 2886 } 2887 2888 return true; 2889 } 2890 2891 bool 2892 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2893 MachineFunction &MF, bool isVarArg, 2894 const SmallVectorImpl<ISD::OutputArg> &Outs, 2895 LLVMContext &Context) const { 2896 SmallVector<CCValAssign, 16> RVLocs; 2897 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2898 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2899 } 2900 2901 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2902 const SDLoc &DL, SelectionDAG &DAG) { 2903 const MachineFunction &MF = DAG.getMachineFunction(); 2904 const Function &F = MF.getFunction(); 2905 2906 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2907 2908 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2909 // version of the "preferred return address". These offsets affect the return 2910 // instruction if this is a return from PL1 without hypervisor extensions. 2911 // IRQ/FIQ: +4 "subs pc, lr, #4" 2912 // SWI: 0 "subs pc, lr, #0" 2913 // ABORT: +4 "subs pc, lr, #4" 2914 // UNDEF: +4/+2 "subs pc, lr, #0" 2915 // UNDEF varies depending on where the exception came from ARM or Thumb 2916 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2917 2918 int64_t LROffset; 2919 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2920 IntKind == "ABORT") 2921 LROffset = 4; 2922 else if (IntKind == "SWI" || IntKind == "UNDEF") 2923 LROffset = 0; 2924 else 2925 report_fatal_error("Unsupported interrupt attribute. If present, value " 2926 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2927 2928 RetOps.insert(RetOps.begin() + 1, 2929 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2930 2931 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2932 } 2933 2934 SDValue 2935 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2936 bool isVarArg, 2937 const SmallVectorImpl<ISD::OutputArg> &Outs, 2938 const SmallVectorImpl<SDValue> &OutVals, 2939 const SDLoc &dl, SelectionDAG &DAG) const { 2940 // CCValAssign - represent the assignment of the return value to a location. 2941 SmallVector<CCValAssign, 16> RVLocs; 2942 2943 // CCState - Info about the registers and stack slots. 2944 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2945 *DAG.getContext()); 2946 2947 // Analyze outgoing return values. 2948 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2949 2950 SDValue Flag; 2951 SmallVector<SDValue, 4> RetOps; 2952 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2953 bool isLittleEndian = Subtarget->isLittle(); 2954 2955 MachineFunction &MF = DAG.getMachineFunction(); 2956 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2957 AFI->setReturnRegsCount(RVLocs.size()); 2958 2959 // Report error if cmse entry function returns structure through first ptr arg. 2960 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) { 2961 // Note: using an empty SDLoc(), as the first line of the function is a 2962 // better place to report than the last line. 2963 DiagnosticInfoUnsupported Diag( 2964 DAG.getMachineFunction().getFunction(), 2965 "secure entry function would return value through pointer", 2966 SDLoc().getDebugLoc()); 2967 DAG.getContext()->diagnose(Diag); 2968 } 2969 2970 // Copy the result values into the output registers. 2971 for (unsigned i = 0, realRVLocIdx = 0; 2972 i != RVLocs.size(); 2973 ++i, ++realRVLocIdx) { 2974 CCValAssign &VA = RVLocs[i]; 2975 assert(VA.isRegLoc() && "Can only return in registers!"); 2976 2977 SDValue Arg = OutVals[realRVLocIdx]; 2978 bool ReturnF16 = false; 2979 2980 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2981 // Half-precision return values can be returned like this: 2982 // 2983 // t11 f16 = fadd ... 2984 // t12: i16 = bitcast t11 2985 // t13: i32 = zero_extend t12 2986 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2987 // 2988 // to avoid code generation for bitcasts, we simply set Arg to the node 2989 // that produces the f16 value, t11 in this case. 2990 // 2991 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2992 SDValue ZE = Arg.getOperand(0); 2993 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2994 SDValue BC = ZE.getOperand(0); 2995 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2996 Arg = BC.getOperand(0); 2997 ReturnF16 = true; 2998 } 2999 } 3000 } 3001 } 3002 3003 switch (VA.getLocInfo()) { 3004 default: llvm_unreachable("Unknown loc info!"); 3005 case CCValAssign::Full: break; 3006 case CCValAssign::BCvt: 3007 if (!ReturnF16) 3008 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 3009 break; 3010 } 3011 3012 // Mask f16 arguments if this is a CMSE nonsecure entry. 3013 auto RetVT = Outs[realRVLocIdx].ArgVT; 3014 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) { 3015 if (VA.needsCustom() && VA.getValVT() == MVT::f16) { 3016 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg); 3017 } else { 3018 auto LocBits = VA.getLocVT().getSizeInBits(); 3019 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits()); 3020 SDValue Mask = 3021 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits)); 3022 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg); 3023 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask); 3024 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 3025 } 3026 } 3027 3028 if (VA.needsCustom() && 3029 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) { 3030 if (VA.getLocVT() == MVT::v2f64) { 3031 // Extract the first half and return it in two registers. 3032 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 3033 DAG.getConstant(0, dl, MVT::i32)); 3034 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 3035 DAG.getVTList(MVT::i32, MVT::i32), Half); 3036 3037 Chain = 3038 DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3039 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag); 3040 Flag = Chain.getValue(1); 3041 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3042 VA = RVLocs[++i]; // skip ahead to next loc 3043 Chain = 3044 DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3045 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 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 3050 // Extract the 2nd half and fall through to handle it as an f64 value. 3051 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 3052 DAG.getConstant(1, dl, MVT::i32)); 3053 } 3054 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 3055 // available. 3056 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 3057 DAG.getVTList(MVT::i32, MVT::i32), Arg); 3058 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3059 fmrrd.getValue(isLittleEndian ? 0 : 1), Flag); 3060 Flag = Chain.getValue(1); 3061 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3062 VA = RVLocs[++i]; // skip ahead to next loc 3063 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3064 fmrrd.getValue(isLittleEndian ? 1 : 0), Flag); 3065 } else 3066 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 3067 3068 // Guarantee that all emitted copies are 3069 // stuck together, avoiding something bad. 3070 Flag = Chain.getValue(1); 3071 RetOps.push_back(DAG.getRegister( 3072 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT())); 3073 } 3074 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 3075 const MCPhysReg *I = 3076 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3077 if (I) { 3078 for (; *I; ++I) { 3079 if (ARM::GPRRegClass.contains(*I)) 3080 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 3081 else if (ARM::DPRRegClass.contains(*I)) 3082 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3083 else 3084 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3085 } 3086 } 3087 3088 // Update chain and glue. 3089 RetOps[0] = Chain; 3090 if (Flag.getNode()) 3091 RetOps.push_back(Flag); 3092 3093 // CPUs which aren't M-class use a special sequence to return from 3094 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 3095 // though we use "subs pc, lr, #N"). 3096 // 3097 // M-class CPUs actually use a normal return sequence with a special 3098 // (hardware-provided) value in LR, so the normal code path works. 3099 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 3100 !Subtarget->isMClass()) { 3101 if (Subtarget->isThumb1Only()) 3102 report_fatal_error("interrupt attribute is not supported in Thumb1"); 3103 return LowerInterruptReturn(RetOps, dl, DAG); 3104 } 3105 3106 ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG : 3107 ARMISD::RET_FLAG; 3108 return DAG.getNode(RetNode, dl, MVT::Other, RetOps); 3109 } 3110 3111 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 3112 if (N->getNumValues() != 1) 3113 return false; 3114 if (!N->hasNUsesOfValue(1, 0)) 3115 return false; 3116 3117 SDValue TCChain = Chain; 3118 SDNode *Copy = *N->use_begin(); 3119 if (Copy->getOpcode() == ISD::CopyToReg) { 3120 // If the copy has a glue operand, we conservatively assume it isn't safe to 3121 // perform a tail call. 3122 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 3123 return false; 3124 TCChain = Copy->getOperand(0); 3125 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 3126 SDNode *VMov = Copy; 3127 // f64 returned in a pair of GPRs. 3128 SmallPtrSet<SDNode*, 2> Copies; 3129 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 3130 UI != UE; ++UI) { 3131 if (UI->getOpcode() != ISD::CopyToReg) 3132 return false; 3133 Copies.insert(*UI); 3134 } 3135 if (Copies.size() > 2) 3136 return false; 3137 3138 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 3139 UI != UE; ++UI) { 3140 SDValue UseChain = UI->getOperand(0); 3141 if (Copies.count(UseChain.getNode())) 3142 // Second CopyToReg 3143 Copy = *UI; 3144 else { 3145 // We are at the top of this chain. 3146 // If the copy has a glue operand, we conservatively assume it 3147 // isn't safe to perform a tail call. 3148 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 3149 return false; 3150 // First CopyToReg 3151 TCChain = UseChain; 3152 } 3153 } 3154 } else if (Copy->getOpcode() == ISD::BITCAST) { 3155 // f32 returned in a single GPR. 3156 if (!Copy->hasOneUse()) 3157 return false; 3158 Copy = *Copy->use_begin(); 3159 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 3160 return false; 3161 // If the copy has a glue operand, we conservatively assume it isn't safe to 3162 // perform a tail call. 3163 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 3164 return false; 3165 TCChain = Copy->getOperand(0); 3166 } else { 3167 return false; 3168 } 3169 3170 bool HasRet = false; 3171 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 3172 UI != UE; ++UI) { 3173 if (UI->getOpcode() != ARMISD::RET_FLAG && 3174 UI->getOpcode() != ARMISD::INTRET_FLAG) 3175 return false; 3176 HasRet = true; 3177 } 3178 3179 if (!HasRet) 3180 return false; 3181 3182 Chain = TCChain; 3183 return true; 3184 } 3185 3186 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3187 if (!Subtarget->supportsTailCall()) 3188 return false; 3189 3190 if (!CI->isTailCall()) 3191 return false; 3192 3193 return true; 3194 } 3195 3196 // Trying to write a 64 bit value so need to split into two 32 bit values first, 3197 // and pass the lower and high parts through. 3198 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 3199 SDLoc DL(Op); 3200 SDValue WriteValue = Op->getOperand(2); 3201 3202 // This function is only supposed to be called for i64 type argument. 3203 assert(WriteValue.getValueType() == MVT::i64 3204 && "LowerWRITE_REGISTER called for non-i64 type argument."); 3205 3206 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3207 DAG.getConstant(0, DL, MVT::i32)); 3208 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3209 DAG.getConstant(1, DL, MVT::i32)); 3210 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 3211 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 3212 } 3213 3214 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 3215 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 3216 // one of the above mentioned nodes. It has to be wrapped because otherwise 3217 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 3218 // be used to form addressing mode. These wrapped nodes will be selected 3219 // into MOVi. 3220 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 3221 SelectionDAG &DAG) const { 3222 EVT PtrVT = Op.getValueType(); 3223 // FIXME there is no actual debug info here 3224 SDLoc dl(Op); 3225 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3226 SDValue Res; 3227 3228 // When generating execute-only code Constant Pools must be promoted to the 3229 // global data section. It's a bit ugly that we can't share them across basic 3230 // blocks, but this way we guarantee that execute-only behaves correct with 3231 // position-independent addressing modes. 3232 if (Subtarget->genExecuteOnly()) { 3233 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 3234 auto T = const_cast<Type*>(CP->getType()); 3235 auto C = const_cast<Constant*>(CP->getConstVal()); 3236 auto M = const_cast<Module*>(DAG.getMachineFunction(). 3237 getFunction().getParent()); 3238 auto GV = new GlobalVariable( 3239 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 3240 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 3241 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 3242 Twine(AFI->createPICLabelUId()) 3243 ); 3244 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 3245 dl, PtrVT); 3246 return LowerGlobalAddress(GA, DAG); 3247 } 3248 3249 if (CP->isMachineConstantPoolEntry()) 3250 Res = 3251 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign()); 3252 else 3253 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign()); 3254 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 3255 } 3256 3257 unsigned ARMTargetLowering::getJumpTableEncoding() const { 3258 return MachineJumpTableInfo::EK_Inline; 3259 } 3260 3261 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 3262 SelectionDAG &DAG) const { 3263 MachineFunction &MF = DAG.getMachineFunction(); 3264 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3265 unsigned ARMPCLabelIndex = 0; 3266 SDLoc DL(Op); 3267 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3268 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 3269 SDValue CPAddr; 3270 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 3271 if (!IsPositionIndependent) { 3272 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4)); 3273 } else { 3274 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3275 ARMPCLabelIndex = AFI->createPICLabelUId(); 3276 ARMConstantPoolValue *CPV = 3277 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 3278 ARMCP::CPBlockAddress, PCAdj); 3279 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3280 } 3281 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 3282 SDValue Result = DAG.getLoad( 3283 PtrVT, DL, DAG.getEntryNode(), CPAddr, 3284 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3285 if (!IsPositionIndependent) 3286 return Result; 3287 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 3288 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 3289 } 3290 3291 /// Convert a TLS address reference into the correct sequence of loads 3292 /// and calls to compute the variable's address for Darwin, and return an 3293 /// SDValue containing the final node. 3294 3295 /// Darwin only has one TLS scheme which must be capable of dealing with the 3296 /// fully general situation, in the worst case. This means: 3297 /// + "extern __thread" declaration. 3298 /// + Defined in a possibly unknown dynamic library. 3299 /// 3300 /// The general system is that each __thread variable has a [3 x i32] descriptor 3301 /// which contains information used by the runtime to calculate the address. The 3302 /// only part of this the compiler needs to know about is the first word, which 3303 /// contains a function pointer that must be called with the address of the 3304 /// entire descriptor in "r0". 3305 /// 3306 /// Since this descriptor may be in a different unit, in general access must 3307 /// proceed along the usual ARM rules. A common sequence to produce is: 3308 /// 3309 /// movw rT1, :lower16:_var$non_lazy_ptr 3310 /// movt rT1, :upper16:_var$non_lazy_ptr 3311 /// ldr r0, [rT1] 3312 /// ldr rT2, [r0] 3313 /// blx rT2 3314 /// [...address now in r0...] 3315 SDValue 3316 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3317 SelectionDAG &DAG) const { 3318 assert(Subtarget->isTargetDarwin() && 3319 "This function expects a Darwin target"); 3320 SDLoc DL(Op); 3321 3322 // First step is to get the address of the actua global symbol. This is where 3323 // the TLS descriptor lives. 3324 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3325 3326 // The first entry in the descriptor is a function pointer that we must call 3327 // to obtain the address of the variable. 3328 SDValue Chain = DAG.getEntryNode(); 3329 SDValue FuncTLVGet = DAG.getLoad( 3330 MVT::i32, DL, Chain, DescAddr, 3331 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3332 /* Alignment = */ 4, 3333 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3334 MachineMemOperand::MOInvariant); 3335 Chain = FuncTLVGet.getValue(1); 3336 3337 MachineFunction &F = DAG.getMachineFunction(); 3338 MachineFrameInfo &MFI = F.getFrameInfo(); 3339 MFI.setAdjustsStack(true); 3340 3341 // TLS calls preserve all registers except those that absolutely must be 3342 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3343 // silly). 3344 auto TRI = 3345 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3346 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3347 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3348 3349 // Finally, we can make the call. This is just a degenerate version of a 3350 // normal AArch64 call node: r0 takes the address of the descriptor, and 3351 // returns the address of the variable in this thread. 3352 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3353 Chain = 3354 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3355 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3356 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3357 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3358 } 3359 3360 SDValue 3361 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3362 SelectionDAG &DAG) const { 3363 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3364 3365 SDValue Chain = DAG.getEntryNode(); 3366 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3367 SDLoc DL(Op); 3368 3369 // Load the current TEB (thread environment block) 3370 SDValue Ops[] = {Chain, 3371 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3372 DAG.getTargetConstant(15, DL, MVT::i32), 3373 DAG.getTargetConstant(0, DL, MVT::i32), 3374 DAG.getTargetConstant(13, DL, MVT::i32), 3375 DAG.getTargetConstant(0, DL, MVT::i32), 3376 DAG.getTargetConstant(2, DL, MVT::i32)}; 3377 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3378 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3379 3380 SDValue TEB = CurrentTEB.getValue(0); 3381 Chain = CurrentTEB.getValue(1); 3382 3383 // Load the ThreadLocalStoragePointer from the TEB 3384 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3385 SDValue TLSArray = 3386 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3387 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3388 3389 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3390 // offset into the TLSArray. 3391 3392 // Load the TLS index from the C runtime 3393 SDValue TLSIndex = 3394 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3395 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3396 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3397 3398 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3399 DAG.getConstant(2, DL, MVT::i32)); 3400 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3401 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3402 MachinePointerInfo()); 3403 3404 // Get the offset of the start of the .tls section (section base) 3405 const auto *GA = cast<GlobalAddressSDNode>(Op); 3406 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3407 SDValue Offset = DAG.getLoad( 3408 PtrVT, DL, Chain, 3409 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3410 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))), 3411 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3412 3413 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3414 } 3415 3416 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3417 SDValue 3418 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3419 SelectionDAG &DAG) const { 3420 SDLoc dl(GA); 3421 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3422 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3423 MachineFunction &MF = DAG.getMachineFunction(); 3424 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3425 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3426 ARMConstantPoolValue *CPV = 3427 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3428 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3429 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3430 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3431 Argument = DAG.getLoad( 3432 PtrVT, dl, DAG.getEntryNode(), Argument, 3433 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3434 SDValue Chain = Argument.getValue(1); 3435 3436 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3437 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3438 3439 // call __tls_get_addr. 3440 ArgListTy Args; 3441 ArgListEntry Entry; 3442 Entry.Node = Argument; 3443 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3444 Args.push_back(Entry); 3445 3446 // FIXME: is there useful debug info available here? 3447 TargetLowering::CallLoweringInfo CLI(DAG); 3448 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3449 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3450 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3451 3452 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3453 return CallResult.first; 3454 } 3455 3456 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3457 // "local exec" model. 3458 SDValue 3459 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3460 SelectionDAG &DAG, 3461 TLSModel::Model model) const { 3462 const GlobalValue *GV = GA->getGlobal(); 3463 SDLoc dl(GA); 3464 SDValue Offset; 3465 SDValue Chain = DAG.getEntryNode(); 3466 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3467 // Get the Thread Pointer 3468 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3469 3470 if (model == TLSModel::InitialExec) { 3471 MachineFunction &MF = DAG.getMachineFunction(); 3472 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3473 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3474 // Initial exec model. 3475 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3476 ARMConstantPoolValue *CPV = 3477 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3478 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3479 true); 3480 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3481 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3482 Offset = DAG.getLoad( 3483 PtrVT, dl, Chain, Offset, 3484 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3485 Chain = Offset.getValue(1); 3486 3487 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3488 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3489 3490 Offset = DAG.getLoad( 3491 PtrVT, dl, Chain, Offset, 3492 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3493 } else { 3494 // local exec model 3495 assert(model == TLSModel::LocalExec); 3496 ARMConstantPoolValue *CPV = 3497 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3498 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3499 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3500 Offset = DAG.getLoad( 3501 PtrVT, dl, Chain, Offset, 3502 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3503 } 3504 3505 // The address of the thread local variable is the add of the thread 3506 // pointer with the offset of the variable. 3507 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3508 } 3509 3510 SDValue 3511 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3512 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3513 if (DAG.getTarget().useEmulatedTLS()) 3514 return LowerToTLSEmulatedModel(GA, DAG); 3515 3516 if (Subtarget->isTargetDarwin()) 3517 return LowerGlobalTLSAddressDarwin(Op, DAG); 3518 3519 if (Subtarget->isTargetWindows()) 3520 return LowerGlobalTLSAddressWindows(Op, DAG); 3521 3522 // TODO: implement the "local dynamic" model 3523 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3524 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3525 3526 switch (model) { 3527 case TLSModel::GeneralDynamic: 3528 case TLSModel::LocalDynamic: 3529 return LowerToTLSGeneralDynamicModel(GA, DAG); 3530 case TLSModel::InitialExec: 3531 case TLSModel::LocalExec: 3532 return LowerToTLSExecModels(GA, DAG, model); 3533 } 3534 llvm_unreachable("bogus TLS model"); 3535 } 3536 3537 /// Return true if all users of V are within function F, looking through 3538 /// ConstantExprs. 3539 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3540 SmallVector<const User*,4> Worklist; 3541 for (auto *U : V->users()) 3542 Worklist.push_back(U); 3543 while (!Worklist.empty()) { 3544 auto *U = Worklist.pop_back_val(); 3545 if (isa<ConstantExpr>(U)) { 3546 for (auto *UU : U->users()) 3547 Worklist.push_back(UU); 3548 continue; 3549 } 3550 3551 auto *I = dyn_cast<Instruction>(U); 3552 if (!I || I->getParent()->getParent() != F) 3553 return false; 3554 } 3555 return true; 3556 } 3557 3558 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3559 const GlobalValue *GV, SelectionDAG &DAG, 3560 EVT PtrVT, const SDLoc &dl) { 3561 // If we're creating a pool entry for a constant global with unnamed address, 3562 // and the global is small enough, we can emit it inline into the constant pool 3563 // to save ourselves an indirection. 3564 // 3565 // This is a win if the constant is only used in one function (so it doesn't 3566 // need to be duplicated) or duplicating the constant wouldn't increase code 3567 // size (implying the constant is no larger than 4 bytes). 3568 const Function &F = DAG.getMachineFunction().getFunction(); 3569 3570 // We rely on this decision to inline being idemopotent and unrelated to the 3571 // use-site. We know that if we inline a variable at one use site, we'll 3572 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3573 // doesn't know about this optimization, so bail out if it's enabled else 3574 // we could decide to inline here (and thus never emit the GV) but require 3575 // the GV from fast-isel generated code. 3576 if (!EnableConstpoolPromotion || 3577 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3578 return SDValue(); 3579 3580 auto *GVar = dyn_cast<GlobalVariable>(GV); 3581 if (!GVar || !GVar->hasInitializer() || 3582 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3583 !GVar->hasLocalLinkage()) 3584 return SDValue(); 3585 3586 // If we inline a value that contains relocations, we move the relocations 3587 // from .data to .text. This is not allowed in position-independent code. 3588 auto *Init = GVar->getInitializer(); 3589 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3590 Init->needsRelocation()) 3591 return SDValue(); 3592 3593 // The constant islands pass can only really deal with alignment requests 3594 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3595 // any type wanting greater alignment requirements than 4 bytes. We also 3596 // can only promote constants that are multiples of 4 bytes in size or 3597 // are paddable to a multiple of 4. Currently we only try and pad constants 3598 // that are strings for simplicity. 3599 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3600 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3601 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar); 3602 unsigned RequiredPadding = 4 - (Size % 4); 3603 bool PaddingPossible = 3604 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3605 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize || 3606 Size == 0) 3607 return SDValue(); 3608 3609 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3610 MachineFunction &MF = DAG.getMachineFunction(); 3611 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3612 3613 // We can't bloat the constant pool too much, else the ConstantIslands pass 3614 // may fail to converge. If we haven't promoted this global yet (it may have 3615 // multiple uses), and promoting it would increase the constant pool size (Sz 3616 // > 4), ensure we have space to do so up to MaxTotal. 3617 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3618 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3619 ConstpoolPromotionMaxTotal) 3620 return SDValue(); 3621 3622 // This is only valid if all users are in a single function; we can't clone 3623 // the constant in general. The LLVM IR unnamed_addr allows merging 3624 // constants, but not cloning them. 3625 // 3626 // We could potentially allow cloning if we could prove all uses of the 3627 // constant in the current function don't care about the address, like 3628 // printf format strings. But that isn't implemented for now. 3629 if (!allUsersAreInFunction(GVar, &F)) 3630 return SDValue(); 3631 3632 // We're going to inline this global. Pad it out if needed. 3633 if (RequiredPadding != 4) { 3634 StringRef S = CDAInit->getAsString(); 3635 3636 SmallVector<uint8_t,16> V(S.size()); 3637 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3638 while (RequiredPadding--) 3639 V.push_back(0); 3640 Init = ConstantDataArray::get(*DAG.getContext(), V); 3641 } 3642 3643 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3644 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4)); 3645 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3646 AFI->markGlobalAsPromotedToConstantPool(GVar); 3647 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3648 PaddedSize - 4); 3649 } 3650 ++NumConstpoolPromoted; 3651 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3652 } 3653 3654 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3655 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3656 if (!(GV = GA->getBaseObject())) 3657 return false; 3658 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3659 return V->isConstant(); 3660 return isa<Function>(GV); 3661 } 3662 3663 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3664 SelectionDAG &DAG) const { 3665 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3666 default: llvm_unreachable("unknown object format"); 3667 case Triple::COFF: 3668 return LowerGlobalAddressWindows(Op, DAG); 3669 case Triple::ELF: 3670 return LowerGlobalAddressELF(Op, DAG); 3671 case Triple::MachO: 3672 return LowerGlobalAddressDarwin(Op, DAG); 3673 } 3674 } 3675 3676 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3677 SelectionDAG &DAG) const { 3678 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3679 SDLoc dl(Op); 3680 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3681 const TargetMachine &TM = getTargetMachine(); 3682 bool IsRO = isReadOnly(GV); 3683 3684 // promoteToConstantPool only if not generating XO text section 3685 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3686 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3687 return V; 3688 3689 if (isPositionIndependent()) { 3690 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3691 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3692 UseGOT_PREL ? ARMII::MO_GOT : 0); 3693 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3694 if (UseGOT_PREL) 3695 Result = 3696 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3697 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3698 return Result; 3699 } else if (Subtarget->isROPI() && IsRO) { 3700 // PC-relative. 3701 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3702 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3703 return Result; 3704 } else if (Subtarget->isRWPI() && !IsRO) { 3705 // SB-relative. 3706 SDValue RelAddr; 3707 if (Subtarget->useMovt()) { 3708 ++NumMovwMovt; 3709 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3710 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3711 } else { // use literal pool for address constant 3712 ARMConstantPoolValue *CPV = 3713 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3714 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3715 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3716 RelAddr = DAG.getLoad( 3717 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3718 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3719 } 3720 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3721 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3722 return Result; 3723 } 3724 3725 // If we have T2 ops, we can materialize the address directly via movt/movw 3726 // pair. This is always cheaper. 3727 if (Subtarget->useMovt()) { 3728 ++NumMovwMovt; 3729 // FIXME: Once remat is capable of dealing with instructions with register 3730 // operands, expand this into two nodes. 3731 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3732 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3733 } else { 3734 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4)); 3735 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3736 return DAG.getLoad( 3737 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3738 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3739 } 3740 } 3741 3742 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3743 SelectionDAG &DAG) const { 3744 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3745 "ROPI/RWPI not currently supported for Darwin"); 3746 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3747 SDLoc dl(Op); 3748 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3749 3750 if (Subtarget->useMovt()) 3751 ++NumMovwMovt; 3752 3753 // FIXME: Once remat is capable of dealing with instructions with register 3754 // operands, expand this into multiple nodes 3755 unsigned Wrapper = 3756 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3757 3758 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3759 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3760 3761 if (Subtarget->isGVIndirectSymbol(GV)) 3762 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3763 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3764 return Result; 3765 } 3766 3767 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3768 SelectionDAG &DAG) const { 3769 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3770 assert(Subtarget->useMovt() && 3771 "Windows on ARM expects to use movw/movt"); 3772 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3773 "ROPI/RWPI not currently supported for Windows"); 3774 3775 const TargetMachine &TM = getTargetMachine(); 3776 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3777 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3778 if (GV->hasDLLImportStorageClass()) 3779 TargetFlags = ARMII::MO_DLLIMPORT; 3780 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3781 TargetFlags = ARMII::MO_COFFSTUB; 3782 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3783 SDValue Result; 3784 SDLoc DL(Op); 3785 3786 ++NumMovwMovt; 3787 3788 // FIXME: Once remat is capable of dealing with instructions with register 3789 // operands, expand this into two nodes. 3790 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3791 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3792 TargetFlags)); 3793 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3794 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3795 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3796 return Result; 3797 } 3798 3799 SDValue 3800 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3801 SDLoc dl(Op); 3802 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3803 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3804 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3805 Op.getOperand(1), Val); 3806 } 3807 3808 SDValue 3809 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3810 SDLoc dl(Op); 3811 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3812 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3813 } 3814 3815 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3816 SelectionDAG &DAG) const { 3817 SDLoc dl(Op); 3818 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3819 Op.getOperand(0)); 3820 } 3821 3822 SDValue ARMTargetLowering::LowerINTRINSIC_VOID( 3823 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const { 3824 unsigned IntNo = 3825 cast<ConstantSDNode>( 3826 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other)) 3827 ->getZExtValue(); 3828 switch (IntNo) { 3829 default: 3830 return SDValue(); // Don't custom lower most intrinsics. 3831 case Intrinsic::arm_gnu_eabi_mcount: { 3832 MachineFunction &MF = DAG.getMachineFunction(); 3833 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3834 SDLoc dl(Op); 3835 SDValue Chain = Op.getOperand(0); 3836 // call "\01__gnu_mcount_nc" 3837 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 3838 const uint32_t *Mask = 3839 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 3840 assert(Mask && "Missing call preserved mask for calling convention"); 3841 // Mark LR an implicit live-in. 3842 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 3843 SDValue ReturnAddress = 3844 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT); 3845 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue}; 3846 SDValue Callee = 3847 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0); 3848 SDValue RegisterMask = DAG.getRegisterMask(Mask); 3849 if (Subtarget->isThumb()) 3850 return SDValue( 3851 DAG.getMachineNode( 3852 ARM::tBL_PUSHLR, dl, ResultTys, 3853 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT), 3854 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}), 3855 0); 3856 return SDValue( 3857 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys, 3858 {ReturnAddress, Callee, RegisterMask, Chain}), 3859 0); 3860 } 3861 } 3862 } 3863 3864 SDValue 3865 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3866 const ARMSubtarget *Subtarget) const { 3867 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3868 SDLoc dl(Op); 3869 switch (IntNo) { 3870 default: return SDValue(); // Don't custom lower most intrinsics. 3871 case Intrinsic::thread_pointer: { 3872 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3873 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3874 } 3875 case Intrinsic::arm_cls: { 3876 const SDValue &Operand = Op.getOperand(1); 3877 const EVT VTy = Op.getValueType(); 3878 SDValue SRA = 3879 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy)); 3880 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand); 3881 SDValue SHL = 3882 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy)); 3883 SDValue OR = 3884 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy)); 3885 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR); 3886 return Result; 3887 } 3888 case Intrinsic::arm_cls64: { 3889 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x)) 3890 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x))) 3891 const SDValue &Operand = Op.getOperand(1); 3892 const EVT VTy = Op.getValueType(); 3893 3894 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3895 DAG.getConstant(1, dl, VTy)); 3896 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3897 DAG.getConstant(0, dl, VTy)); 3898 SDValue Constant0 = DAG.getConstant(0, dl, VTy); 3899 SDValue Constant1 = DAG.getConstant(1, dl, VTy); 3900 SDValue Constant31 = DAG.getConstant(31, dl, VTy); 3901 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31); 3902 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi); 3903 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1); 3904 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1); 3905 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi); 3906 SDValue CheckLo = 3907 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ); 3908 SDValue HiIsZero = 3909 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ); 3910 SDValue AdjustedLo = 3911 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy)); 3912 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo); 3913 SDValue Result = 3914 DAG.getSelect(dl, VTy, CheckLo, 3915 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi); 3916 return Result; 3917 } 3918 case Intrinsic::eh_sjlj_lsda: { 3919 MachineFunction &MF = DAG.getMachineFunction(); 3920 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3921 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3922 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3923 SDValue CPAddr; 3924 bool IsPositionIndependent = isPositionIndependent(); 3925 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3926 ARMConstantPoolValue *CPV = 3927 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3928 ARMCP::CPLSDA, PCAdj); 3929 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3930 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3931 SDValue Result = DAG.getLoad( 3932 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3933 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3934 3935 if (IsPositionIndependent) { 3936 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3937 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3938 } 3939 return Result; 3940 } 3941 case Intrinsic::arm_neon_vabs: 3942 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3943 Op.getOperand(1)); 3944 case Intrinsic::arm_neon_vmulls: 3945 case Intrinsic::arm_neon_vmullu: { 3946 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3947 ? ARMISD::VMULLs : ARMISD::VMULLu; 3948 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3949 Op.getOperand(1), Op.getOperand(2)); 3950 } 3951 case Intrinsic::arm_neon_vminnm: 3952 case Intrinsic::arm_neon_vmaxnm: { 3953 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3954 ? ISD::FMINNUM : ISD::FMAXNUM; 3955 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3956 Op.getOperand(1), Op.getOperand(2)); 3957 } 3958 case Intrinsic::arm_neon_vminu: 3959 case Intrinsic::arm_neon_vmaxu: { 3960 if (Op.getValueType().isFloatingPoint()) 3961 return SDValue(); 3962 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3963 ? ISD::UMIN : ISD::UMAX; 3964 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3965 Op.getOperand(1), Op.getOperand(2)); 3966 } 3967 case Intrinsic::arm_neon_vmins: 3968 case Intrinsic::arm_neon_vmaxs: { 3969 // v{min,max}s is overloaded between signed integers and floats. 3970 if (!Op.getValueType().isFloatingPoint()) { 3971 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3972 ? ISD::SMIN : ISD::SMAX; 3973 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3974 Op.getOperand(1), Op.getOperand(2)); 3975 } 3976 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3977 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3978 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3979 Op.getOperand(1), Op.getOperand(2)); 3980 } 3981 case Intrinsic::arm_neon_vtbl1: 3982 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3983 Op.getOperand(1), Op.getOperand(2)); 3984 case Intrinsic::arm_neon_vtbl2: 3985 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3986 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3987 case Intrinsic::arm_mve_pred_i2v: 3988 case Intrinsic::arm_mve_pred_v2i: 3989 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(), 3990 Op.getOperand(1)); 3991 case Intrinsic::arm_mve_vreinterpretq: 3992 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(), 3993 Op.getOperand(1)); 3994 case Intrinsic::arm_mve_lsll: 3995 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(), 3996 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3997 case Intrinsic::arm_mve_asrl: 3998 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(), 3999 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4000 } 4001 } 4002 4003 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 4004 const ARMSubtarget *Subtarget) { 4005 SDLoc dl(Op); 4006 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 4007 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 4008 if (SSID == SyncScope::SingleThread) 4009 return Op; 4010 4011 if (!Subtarget->hasDataBarrier()) { 4012 // Some ARMv6 cpus can support data barriers with an mcr instruction. 4013 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 4014 // here. 4015 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 4016 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 4017 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 4018 DAG.getConstant(0, dl, MVT::i32)); 4019 } 4020 4021 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 4022 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 4023 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 4024 if (Subtarget->isMClass()) { 4025 // Only a full system barrier exists in the M-class architectures. 4026 Domain = ARM_MB::SY; 4027 } else if (Subtarget->preferISHSTBarriers() && 4028 Ord == AtomicOrdering::Release) { 4029 // Swift happens to implement ISHST barriers in a way that's compatible with 4030 // Release semantics but weaker than ISH so we'd be fools not to use 4031 // it. Beware: other processors probably don't! 4032 Domain = ARM_MB::ISHST; 4033 } 4034 4035 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 4036 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 4037 DAG.getConstant(Domain, dl, MVT::i32)); 4038 } 4039 4040 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 4041 const ARMSubtarget *Subtarget) { 4042 // ARM pre v5TE and Thumb1 does not have preload instructions. 4043 if (!(Subtarget->isThumb2() || 4044 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 4045 // Just preserve the chain. 4046 return Op.getOperand(0); 4047 4048 SDLoc dl(Op); 4049 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 4050 if (!isRead && 4051 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 4052 // ARMv7 with MP extension has PLDW. 4053 return Op.getOperand(0); 4054 4055 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 4056 if (Subtarget->isThumb()) { 4057 // Invert the bits. 4058 isRead = ~isRead & 1; 4059 isData = ~isData & 1; 4060 } 4061 4062 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 4063 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 4064 DAG.getConstant(isData, dl, MVT::i32)); 4065 } 4066 4067 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 4068 MachineFunction &MF = DAG.getMachineFunction(); 4069 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 4070 4071 // vastart just stores the address of the VarArgsFrameIndex slot into the 4072 // memory location argument. 4073 SDLoc dl(Op); 4074 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4075 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4076 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4077 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 4078 MachinePointerInfo(SV)); 4079 } 4080 4081 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 4082 CCValAssign &NextVA, 4083 SDValue &Root, 4084 SelectionDAG &DAG, 4085 const SDLoc &dl) const { 4086 MachineFunction &MF = DAG.getMachineFunction(); 4087 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4088 4089 const TargetRegisterClass *RC; 4090 if (AFI->isThumb1OnlyFunction()) 4091 RC = &ARM::tGPRRegClass; 4092 else 4093 RC = &ARM::GPRRegClass; 4094 4095 // Transform the arguments stored in physical registers into virtual ones. 4096 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4097 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 4098 4099 SDValue ArgValue2; 4100 if (NextVA.isMemLoc()) { 4101 MachineFrameInfo &MFI = MF.getFrameInfo(); 4102 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 4103 4104 // Create load node to retrieve arguments from the stack. 4105 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4106 ArgValue2 = DAG.getLoad( 4107 MVT::i32, dl, Root, FIN, 4108 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4109 } else { 4110 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 4111 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 4112 } 4113 if (!Subtarget->isLittle()) 4114 std::swap (ArgValue, ArgValue2); 4115 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 4116 } 4117 4118 // The remaining GPRs hold either the beginning of variable-argument 4119 // data, or the beginning of an aggregate passed by value (usually 4120 // byval). Either way, we allocate stack slots adjacent to the data 4121 // provided by our caller, and store the unallocated registers there. 4122 // If this is a variadic function, the va_list pointer will begin with 4123 // these values; otherwise, this reassembles a (byval) structure that 4124 // was split between registers and memory. 4125 // Return: The frame index registers were stored into. 4126 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 4127 const SDLoc &dl, SDValue &Chain, 4128 const Value *OrigArg, 4129 unsigned InRegsParamRecordIdx, 4130 int ArgOffset, unsigned ArgSize) const { 4131 // Currently, two use-cases possible: 4132 // Case #1. Non-var-args function, and we meet first byval parameter. 4133 // Setup first unallocated register as first byval register; 4134 // eat all remained registers 4135 // (these two actions are performed by HandleByVal method). 4136 // Then, here, we initialize stack frame with 4137 // "store-reg" instructions. 4138 // Case #2. Var-args function, that doesn't contain byval parameters. 4139 // The same: eat all remained unallocated registers, 4140 // initialize stack frame. 4141 4142 MachineFunction &MF = DAG.getMachineFunction(); 4143 MachineFrameInfo &MFI = MF.getFrameInfo(); 4144 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4145 unsigned RBegin, REnd; 4146 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 4147 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 4148 } else { 4149 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4150 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 4151 REnd = ARM::R4; 4152 } 4153 4154 if (REnd != RBegin) 4155 ArgOffset = -4 * (ARM::R4 - RBegin); 4156 4157 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4158 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 4159 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 4160 4161 SmallVector<SDValue, 4> MemOps; 4162 const TargetRegisterClass *RC = 4163 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 4164 4165 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 4166 unsigned VReg = MF.addLiveIn(Reg, RC); 4167 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4168 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4169 MachinePointerInfo(OrigArg, 4 * i)); 4170 MemOps.push_back(Store); 4171 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 4172 } 4173 4174 if (!MemOps.empty()) 4175 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4176 return FrameIndex; 4177 } 4178 4179 // Setup stack frame, the va_list pointer will start from. 4180 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 4181 const SDLoc &dl, SDValue &Chain, 4182 unsigned ArgOffset, 4183 unsigned TotalArgRegsSaveSize, 4184 bool ForceMutable) const { 4185 MachineFunction &MF = DAG.getMachineFunction(); 4186 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4187 4188 // Try to store any remaining integer argument regs 4189 // to their spots on the stack so that they may be loaded by dereferencing 4190 // the result of va_next. 4191 // If there is no regs to be stored, just point address after last 4192 // argument passed via stack. 4193 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 4194 CCInfo.getInRegsParamsCount(), 4195 CCInfo.getNextStackOffset(), 4196 std::max(4U, TotalArgRegsSaveSize)); 4197 AFI->setVarArgsFrameIndex(FrameIndex); 4198 } 4199 4200 bool ARMTargetLowering::splitValueIntoRegisterParts( 4201 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 4202 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 4203 bool IsABIRegCopy = CC.hasValue(); 4204 EVT ValueVT = Val.getValueType(); 4205 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) && 4206 PartVT == MVT::f32) { 4207 unsigned ValueBits = ValueVT.getSizeInBits(); 4208 unsigned PartBits = PartVT.getSizeInBits(); 4209 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val); 4210 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val); 4211 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 4212 Parts[0] = Val; 4213 return true; 4214 } 4215 return false; 4216 } 4217 4218 SDValue ARMTargetLowering::joinRegisterPartsIntoValue( 4219 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 4220 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 4221 bool IsABIRegCopy = CC.hasValue(); 4222 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) && 4223 PartVT == MVT::f32) { 4224 unsigned ValueBits = ValueVT.getSizeInBits(); 4225 unsigned PartBits = PartVT.getSizeInBits(); 4226 SDValue Val = Parts[0]; 4227 4228 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val); 4229 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val); 4230 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 4231 return Val; 4232 } 4233 return SDValue(); 4234 } 4235 4236 SDValue ARMTargetLowering::LowerFormalArguments( 4237 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4238 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4239 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4240 MachineFunction &MF = DAG.getMachineFunction(); 4241 MachineFrameInfo &MFI = MF.getFrameInfo(); 4242 4243 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4244 4245 // Assign locations to all of the incoming arguments. 4246 SmallVector<CCValAssign, 16> ArgLocs; 4247 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4248 *DAG.getContext()); 4249 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 4250 4251 SmallVector<SDValue, 16> ArgValues; 4252 SDValue ArgValue; 4253 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 4254 unsigned CurArgIdx = 0; 4255 4256 // Initially ArgRegsSaveSize is zero. 4257 // Then we increase this value each time we meet byval parameter. 4258 // We also increase this value in case of varargs function. 4259 AFI->setArgRegsSaveSize(0); 4260 4261 // Calculate the amount of stack space that we need to allocate to store 4262 // byval and variadic arguments that are passed in registers. 4263 // We need to know this before we allocate the first byval or variadic 4264 // argument, as they will be allocated a stack slot below the CFA (Canonical 4265 // Frame Address, the stack pointer at entry to the function). 4266 unsigned ArgRegBegin = ARM::R4; 4267 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4268 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 4269 break; 4270 4271 CCValAssign &VA = ArgLocs[i]; 4272 unsigned Index = VA.getValNo(); 4273 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 4274 if (!Flags.isByVal()) 4275 continue; 4276 4277 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 4278 unsigned RBegin, REnd; 4279 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 4280 ArgRegBegin = std::min(ArgRegBegin, RBegin); 4281 4282 CCInfo.nextInRegsParam(); 4283 } 4284 CCInfo.rewindByValRegsInfo(); 4285 4286 int lastInsIndex = -1; 4287 if (isVarArg && MFI.hasVAStart()) { 4288 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4289 if (RegIdx != array_lengthof(GPRArgRegs)) 4290 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 4291 } 4292 4293 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 4294 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 4295 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4296 4297 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4298 CCValAssign &VA = ArgLocs[i]; 4299 if (Ins[VA.getValNo()].isOrigArg()) { 4300 std::advance(CurOrigArg, 4301 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 4302 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 4303 } 4304 // Arguments stored in registers. 4305 if (VA.isRegLoc()) { 4306 EVT RegVT = VA.getLocVT(); 4307 4308 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) { 4309 // f64 and vector types are split up into multiple registers or 4310 // combinations of registers and stack slots. 4311 SDValue ArgValue1 = 4312 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4313 VA = ArgLocs[++i]; // skip ahead to next loc 4314 SDValue ArgValue2; 4315 if (VA.isMemLoc()) { 4316 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 4317 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4318 ArgValue2 = DAG.getLoad( 4319 MVT::f64, dl, Chain, FIN, 4320 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4321 } else { 4322 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4323 } 4324 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 4325 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue, 4326 ArgValue1, DAG.getIntPtrConstant(0, dl)); 4327 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue, 4328 ArgValue2, DAG.getIntPtrConstant(1, dl)); 4329 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) { 4330 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4331 } else { 4332 const TargetRegisterClass *RC; 4333 4334 if (RegVT == MVT::f16 || RegVT == MVT::bf16) 4335 RC = &ARM::HPRRegClass; 4336 else if (RegVT == MVT::f32) 4337 RC = &ARM::SPRRegClass; 4338 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 || 4339 RegVT == MVT::v4bf16) 4340 RC = &ARM::DPRRegClass; 4341 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 || 4342 RegVT == MVT::v8bf16) 4343 RC = &ARM::QPRRegClass; 4344 else if (RegVT == MVT::i32) 4345 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 4346 : &ARM::GPRRegClass; 4347 else 4348 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4349 4350 // Transform the arguments in physical registers into virtual ones. 4351 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4352 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 4353 4354 // If this value is passed in r0 and has the returned attribute (e.g. 4355 // C++ 'structors), record this fact for later use. 4356 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 4357 AFI->setPreservesR0(); 4358 } 4359 } 4360 4361 // If this is an 8 or 16-bit value, it is really passed promoted 4362 // to 32 bits. Insert an assert[sz]ext to capture this, then 4363 // truncate to the right size. 4364 switch (VA.getLocInfo()) { 4365 default: llvm_unreachable("Unknown loc info!"); 4366 case CCValAssign::Full: break; 4367 case CCValAssign::BCvt: 4368 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 4369 break; 4370 case CCValAssign::SExt: 4371 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 4372 DAG.getValueType(VA.getValVT())); 4373 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4374 break; 4375 case CCValAssign::ZExt: 4376 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 4377 DAG.getValueType(VA.getValVT())); 4378 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4379 break; 4380 } 4381 4382 // f16 arguments have their size extended to 4 bytes and passed as if they 4383 // had been copied to the LSBs of a 32-bit register. 4384 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 4385 if (VA.needsCustom() && 4386 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) 4387 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue); 4388 4389 InVals.push_back(ArgValue); 4390 } else { // VA.isRegLoc() 4391 // sanity check 4392 assert(VA.isMemLoc()); 4393 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 4394 4395 int index = VA.getValNo(); 4396 4397 // Some Ins[] entries become multiple ArgLoc[] entries. 4398 // Process them only once. 4399 if (index != lastInsIndex) 4400 { 4401 ISD::ArgFlagsTy Flags = Ins[index].Flags; 4402 // FIXME: For now, all byval parameter objects are marked mutable. 4403 // This can be changed with more analysis. 4404 // In case of tail call optimization mark all arguments mutable. 4405 // Since they could be overwritten by lowering of arguments in case of 4406 // a tail call. 4407 if (Flags.isByVal()) { 4408 assert(Ins[index].isOrigArg() && 4409 "Byval arguments cannot be implicit"); 4410 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 4411 4412 int FrameIndex = StoreByValRegs( 4413 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 4414 VA.getLocMemOffset(), Flags.getByValSize()); 4415 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 4416 CCInfo.nextInRegsParam(); 4417 } else { 4418 unsigned FIOffset = VA.getLocMemOffset(); 4419 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 4420 FIOffset, true); 4421 4422 // Create load nodes to retrieve arguments from the stack. 4423 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4424 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 4425 MachinePointerInfo::getFixedStack( 4426 DAG.getMachineFunction(), FI))); 4427 } 4428 lastInsIndex = index; 4429 } 4430 } 4431 } 4432 4433 // varargs 4434 if (isVarArg && MFI.hasVAStart()) 4435 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 4436 CCInfo.getNextStackOffset(), 4437 TotalArgRegsSaveSize); 4438 4439 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4440 4441 return Chain; 4442 } 4443 4444 /// isFloatingPointZero - Return true if this is +0.0. 4445 static bool isFloatingPointZero(SDValue Op) { 4446 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4447 return CFP->getValueAPF().isPosZero(); 4448 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4449 // Maybe this has already been legalized into the constant pool? 4450 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4451 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4452 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4453 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4454 return CFP->getValueAPF().isPosZero(); 4455 } 4456 } else if (Op->getOpcode() == ISD::BITCAST && 4457 Op->getValueType(0) == MVT::f64) { 4458 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4459 // created by LowerConstantFP(). 4460 SDValue BitcastOp = Op->getOperand(0); 4461 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4462 isNullConstant(BitcastOp->getOperand(0))) 4463 return true; 4464 } 4465 return false; 4466 } 4467 4468 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4469 /// the given operands. 4470 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4471 SDValue &ARMcc, SelectionDAG &DAG, 4472 const SDLoc &dl) const { 4473 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4474 unsigned C = RHSC->getZExtValue(); 4475 if (!isLegalICmpImmediate((int32_t)C)) { 4476 // Constant does not fit, try adjusting it by one. 4477 switch (CC) { 4478 default: break; 4479 case ISD::SETLT: 4480 case ISD::SETGE: 4481 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4482 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4483 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4484 } 4485 break; 4486 case ISD::SETULT: 4487 case ISD::SETUGE: 4488 if (C != 0 && isLegalICmpImmediate(C-1)) { 4489 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4490 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4491 } 4492 break; 4493 case ISD::SETLE: 4494 case ISD::SETGT: 4495 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4496 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4497 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4498 } 4499 break; 4500 case ISD::SETULE: 4501 case ISD::SETUGT: 4502 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4503 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4504 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4505 } 4506 break; 4507 } 4508 } 4509 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4510 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4511 // In ARM and Thumb-2, the compare instructions can shift their second 4512 // operand. 4513 CC = ISD::getSetCCSwappedOperands(CC); 4514 std::swap(LHS, RHS); 4515 } 4516 4517 // Thumb1 has very limited immediate modes, so turning an "and" into a 4518 // shift can save multiple instructions. 4519 // 4520 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4521 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4522 // own. If it's the operand to an unsigned comparison with an immediate, 4523 // we can eliminate one of the shifts: we transform 4524 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4525 // 4526 // We avoid transforming cases which aren't profitable due to encoding 4527 // details: 4528 // 4529 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4530 // would not; in that case, we're essentially trading one immediate load for 4531 // another. 4532 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4533 // 3. C2 is zero; we have other code for this special case. 4534 // 4535 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4536 // instruction, since the AND is always one instruction anyway, but we could 4537 // use narrow instructions in some cases. 4538 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4539 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4540 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4541 !isSignedIntSetCC(CC)) { 4542 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4543 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4544 uint64_t RHSV = RHSC->getZExtValue(); 4545 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4546 unsigned ShiftBits = countLeadingZeros(Mask); 4547 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4548 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4549 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4550 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4551 } 4552 } 4553 } 4554 4555 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4556 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4557 // way a cmp would. 4558 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4559 // some tweaks to the heuristics for the previous and->shift transform. 4560 // FIXME: Optimize cases where the LHS isn't a shift. 4561 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4562 isa<ConstantSDNode>(RHS) && 4563 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4564 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4565 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4566 unsigned ShiftAmt = 4567 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4568 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4569 DAG.getVTList(MVT::i32, MVT::i32), 4570 LHS.getOperand(0), 4571 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4572 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4573 Shift.getValue(1), SDValue()); 4574 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4575 return Chain.getValue(1); 4576 } 4577 4578 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4579 4580 // If the RHS is a constant zero then the V (overflow) flag will never be 4581 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4582 // simpler for other passes (like the peephole optimiser) to deal with. 4583 if (isNullConstant(RHS)) { 4584 switch (CondCode) { 4585 default: break; 4586 case ARMCC::GE: 4587 CondCode = ARMCC::PL; 4588 break; 4589 case ARMCC::LT: 4590 CondCode = ARMCC::MI; 4591 break; 4592 } 4593 } 4594 4595 ARMISD::NodeType CompareType; 4596 switch (CondCode) { 4597 default: 4598 CompareType = ARMISD::CMP; 4599 break; 4600 case ARMCC::EQ: 4601 case ARMCC::NE: 4602 // Uses only Z Flag 4603 CompareType = ARMISD::CMPZ; 4604 break; 4605 } 4606 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4607 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4608 } 4609 4610 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4611 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4612 SelectionDAG &DAG, const SDLoc &dl, 4613 bool Signaling) const { 4614 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4615 SDValue Cmp; 4616 if (!isFloatingPointZero(RHS)) 4617 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, 4618 dl, MVT::Glue, LHS, RHS); 4619 else 4620 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, 4621 dl, MVT::Glue, LHS); 4622 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4623 } 4624 4625 /// duplicateCmp - Glue values can have only one use, so this function 4626 /// duplicates a comparison node. 4627 SDValue 4628 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4629 unsigned Opc = Cmp.getOpcode(); 4630 SDLoc DL(Cmp); 4631 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4632 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4633 4634 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4635 Cmp = Cmp.getOperand(0); 4636 Opc = Cmp.getOpcode(); 4637 if (Opc == ARMISD::CMPFP) 4638 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4639 else { 4640 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4641 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 4642 } 4643 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4644 } 4645 4646 // This function returns three things: the arithmetic computation itself 4647 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4648 // comparison and the condition code define the case in which the arithmetic 4649 // computation *does not* overflow. 4650 std::pair<SDValue, SDValue> 4651 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4652 SDValue &ARMcc) const { 4653 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4654 4655 SDValue Value, OverflowCmp; 4656 SDValue LHS = Op.getOperand(0); 4657 SDValue RHS = Op.getOperand(1); 4658 SDLoc dl(Op); 4659 4660 // FIXME: We are currently always generating CMPs because we don't support 4661 // generating CMN through the backend. This is not as good as the natural 4662 // CMP case because it causes a register dependency and cannot be folded 4663 // later. 4664 4665 switch (Op.getOpcode()) { 4666 default: 4667 llvm_unreachable("Unknown overflow instruction!"); 4668 case ISD::SADDO: 4669 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4670 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4671 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4672 break; 4673 case ISD::UADDO: 4674 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4675 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4676 // We do not use it in the USUBO case as Value may not be used. 4677 Value = DAG.getNode(ARMISD::ADDC, dl, 4678 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4679 .getValue(0); 4680 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4681 break; 4682 case ISD::SSUBO: 4683 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4684 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4685 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4686 break; 4687 case ISD::USUBO: 4688 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4689 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4690 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4691 break; 4692 case ISD::UMULO: 4693 // We generate a UMUL_LOHI and then check if the high word is 0. 4694 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4695 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4696 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4697 LHS, RHS); 4698 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4699 DAG.getConstant(0, dl, MVT::i32)); 4700 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4701 break; 4702 case ISD::SMULO: 4703 // We generate a SMUL_LOHI and then check if all the bits of the high word 4704 // are the same as the sign bit of the low word. 4705 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4706 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4707 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4708 LHS, RHS); 4709 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4710 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4711 Value.getValue(0), 4712 DAG.getConstant(31, dl, MVT::i32))); 4713 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4714 break; 4715 } // switch (...) 4716 4717 return std::make_pair(Value, OverflowCmp); 4718 } 4719 4720 SDValue 4721 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4722 // Let legalize expand this if it isn't a legal type yet. 4723 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4724 return SDValue(); 4725 4726 SDValue Value, OverflowCmp; 4727 SDValue ARMcc; 4728 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4729 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4730 SDLoc dl(Op); 4731 // We use 0 and 1 as false and true values. 4732 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4733 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4734 EVT VT = Op.getValueType(); 4735 4736 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4737 ARMcc, CCR, OverflowCmp); 4738 4739 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4740 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4741 } 4742 4743 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4744 SelectionDAG &DAG) { 4745 SDLoc DL(BoolCarry); 4746 EVT CarryVT = BoolCarry.getValueType(); 4747 4748 // This converts the boolean value carry into the carry flag by doing 4749 // ARMISD::SUBC Carry, 1 4750 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4751 DAG.getVTList(CarryVT, MVT::i32), 4752 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4753 return Carry.getValue(1); 4754 } 4755 4756 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4757 SelectionDAG &DAG) { 4758 SDLoc DL(Flags); 4759 4760 // Now convert the carry flag into a boolean carry. We do this 4761 // using ARMISD:ADDE 0, 0, Carry 4762 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4763 DAG.getConstant(0, DL, MVT::i32), 4764 DAG.getConstant(0, DL, MVT::i32), Flags); 4765 } 4766 4767 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4768 SelectionDAG &DAG) const { 4769 // Let legalize expand this if it isn't a legal type yet. 4770 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4771 return SDValue(); 4772 4773 SDValue LHS = Op.getOperand(0); 4774 SDValue RHS = Op.getOperand(1); 4775 SDLoc dl(Op); 4776 4777 EVT VT = Op.getValueType(); 4778 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4779 SDValue Value; 4780 SDValue Overflow; 4781 switch (Op.getOpcode()) { 4782 default: 4783 llvm_unreachable("Unknown overflow instruction!"); 4784 case ISD::UADDO: 4785 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4786 // Convert the carry flag into a boolean value. 4787 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4788 break; 4789 case ISD::USUBO: { 4790 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4791 // Convert the carry flag into a boolean value. 4792 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4793 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4794 // value. So compute 1 - C. 4795 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4796 DAG.getConstant(1, dl, MVT::i32), Overflow); 4797 break; 4798 } 4799 } 4800 4801 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4802 } 4803 4804 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG, 4805 const ARMSubtarget *Subtarget) { 4806 EVT VT = Op.getValueType(); 4807 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 4808 return SDValue(); 4809 if (!VT.isSimple()) 4810 return SDValue(); 4811 4812 unsigned NewOpcode; 4813 bool IsAdd = Op->getOpcode() == ISD::SADDSAT; 4814 switch (VT.getSimpleVT().SimpleTy) { 4815 default: 4816 return SDValue(); 4817 case MVT::i8: 4818 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b; 4819 break; 4820 case MVT::i16: 4821 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b; 4822 break; 4823 } 4824 4825 SDLoc dl(Op); 4826 SDValue Add = 4827 DAG.getNode(NewOpcode, dl, MVT::i32, 4828 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32), 4829 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32)); 4830 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add); 4831 } 4832 4833 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4834 SDValue Cond = Op.getOperand(0); 4835 SDValue SelectTrue = Op.getOperand(1); 4836 SDValue SelectFalse = Op.getOperand(2); 4837 SDLoc dl(Op); 4838 unsigned Opc = Cond.getOpcode(); 4839 4840 if (Cond.getResNo() == 1 && 4841 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4842 Opc == ISD::USUBO)) { 4843 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4844 return SDValue(); 4845 4846 SDValue Value, OverflowCmp; 4847 SDValue ARMcc; 4848 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4849 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4850 EVT VT = Op.getValueType(); 4851 4852 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4853 OverflowCmp, DAG); 4854 } 4855 4856 // Convert: 4857 // 4858 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4859 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4860 // 4861 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4862 const ConstantSDNode *CMOVTrue = 4863 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4864 const ConstantSDNode *CMOVFalse = 4865 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4866 4867 if (CMOVTrue && CMOVFalse) { 4868 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4869 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4870 4871 SDValue True; 4872 SDValue False; 4873 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4874 True = SelectTrue; 4875 False = SelectFalse; 4876 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4877 True = SelectFalse; 4878 False = SelectTrue; 4879 } 4880 4881 if (True.getNode() && False.getNode()) { 4882 EVT VT = Op.getValueType(); 4883 SDValue ARMcc = Cond.getOperand(2); 4884 SDValue CCR = Cond.getOperand(3); 4885 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4886 assert(True.getValueType() == VT); 4887 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4888 } 4889 } 4890 } 4891 4892 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4893 // undefined bits before doing a full-word comparison with zero. 4894 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4895 DAG.getConstant(1, dl, Cond.getValueType())); 4896 4897 return DAG.getSelectCC(dl, Cond, 4898 DAG.getConstant(0, dl, Cond.getValueType()), 4899 SelectTrue, SelectFalse, ISD::SETNE); 4900 } 4901 4902 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4903 bool &swpCmpOps, bool &swpVselOps) { 4904 // Start by selecting the GE condition code for opcodes that return true for 4905 // 'equality' 4906 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4907 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4908 CondCode = ARMCC::GE; 4909 4910 // and GT for opcodes that return false for 'equality'. 4911 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4912 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4913 CondCode = ARMCC::GT; 4914 4915 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4916 // to swap the compare operands. 4917 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4918 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4919 swpCmpOps = true; 4920 4921 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4922 // If we have an unordered opcode, we need to swap the operands to the VSEL 4923 // instruction (effectively negating the condition). 4924 // 4925 // This also has the effect of swapping which one of 'less' or 'greater' 4926 // returns true, so we also swap the compare operands. It also switches 4927 // whether we return true for 'equality', so we compensate by picking the 4928 // opposite condition code to our original choice. 4929 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4930 CC == ISD::SETUGT) { 4931 swpCmpOps = !swpCmpOps; 4932 swpVselOps = !swpVselOps; 4933 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4934 } 4935 4936 // 'ordered' is 'anything but unordered', so use the VS condition code and 4937 // swap the VSEL operands. 4938 if (CC == ISD::SETO) { 4939 CondCode = ARMCC::VS; 4940 swpVselOps = true; 4941 } 4942 4943 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4944 // code and swap the VSEL operands. Also do this if we don't care about the 4945 // unordered case. 4946 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4947 CondCode = ARMCC::EQ; 4948 swpVselOps = true; 4949 } 4950 } 4951 4952 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4953 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4954 SDValue Cmp, SelectionDAG &DAG) const { 4955 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4956 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4957 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4958 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4959 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4960 4961 SDValue TrueLow = TrueVal.getValue(0); 4962 SDValue TrueHigh = TrueVal.getValue(1); 4963 SDValue FalseLow = FalseVal.getValue(0); 4964 SDValue FalseHigh = FalseVal.getValue(1); 4965 4966 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4967 ARMcc, CCR, Cmp); 4968 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4969 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4970 4971 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4972 } else { 4973 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4974 Cmp); 4975 } 4976 } 4977 4978 static bool isGTorGE(ISD::CondCode CC) { 4979 return CC == ISD::SETGT || CC == ISD::SETGE; 4980 } 4981 4982 static bool isLTorLE(ISD::CondCode CC) { 4983 return CC == ISD::SETLT || CC == ISD::SETLE; 4984 } 4985 4986 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4987 // All of these conditions (and their <= and >= counterparts) will do: 4988 // x < k ? k : x 4989 // x > k ? x : k 4990 // k < x ? x : k 4991 // k > x ? k : x 4992 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4993 const SDValue TrueVal, const SDValue FalseVal, 4994 const ISD::CondCode CC, const SDValue K) { 4995 return (isGTorGE(CC) && 4996 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4997 (isLTorLE(CC) && 4998 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4999 } 5000 5001 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 5002 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 5003 const SDValue TrueVal, const SDValue FalseVal, 5004 const ISD::CondCode CC, const SDValue K) { 5005 return (isGTorGE(CC) && 5006 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 5007 (isLTorLE(CC) && 5008 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 5009 } 5010 5011 // Check if two chained conditionals could be converted into SSAT or USAT. 5012 // 5013 // SSAT can replace a set of two conditional selectors that bound a number to an 5014 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 5015 // 5016 // x < -k ? -k : (x > k ? k : x) 5017 // x < -k ? -k : (x < k ? x : k) 5018 // x > -k ? (x > k ? k : x) : -k 5019 // x < k ? (x < -k ? -k : x) : k 5020 // etc. 5021 // 5022 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 5023 // a power of 2. 5024 // 5025 // It returns true if the conversion can be done, false otherwise. 5026 // Additionally, the variable is returned in parameter V, the constant in K and 5027 // usat is set to true if the conditional represents an unsigned saturation 5028 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 5029 uint64_t &K, bool &usat) { 5030 SDValue LHS1 = Op.getOperand(0); 5031 SDValue RHS1 = Op.getOperand(1); 5032 SDValue TrueVal1 = Op.getOperand(2); 5033 SDValue FalseVal1 = Op.getOperand(3); 5034 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5035 5036 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 5037 if (Op2.getOpcode() != ISD::SELECT_CC) 5038 return false; 5039 5040 SDValue LHS2 = Op2.getOperand(0); 5041 SDValue RHS2 = Op2.getOperand(1); 5042 SDValue TrueVal2 = Op2.getOperand(2); 5043 SDValue FalseVal2 = Op2.getOperand(3); 5044 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 5045 5046 // Find out which are the constants and which are the variables 5047 // in each conditional 5048 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 5049 ? &RHS1 5050 : nullptr; 5051 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 5052 ? &RHS2 5053 : nullptr; 5054 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 5055 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 5056 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 5057 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 5058 5059 // We must detect cases where the original operations worked with 16- or 5060 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 5061 // must work with sign-extended values but the select operations return 5062 // the original non-extended value. 5063 SDValue V2TmpReg = V2Tmp; 5064 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 5065 V2TmpReg = V2Tmp->getOperand(0); 5066 5067 // Check that the registers and the constants have the correct values 5068 // in both conditionals 5069 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 5070 V2TmpReg != V2) 5071 return false; 5072 5073 // Figure out which conditional is saturating the lower/upper bound. 5074 const SDValue *LowerCheckOp = 5075 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 5076 ? &Op 5077 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 5078 ? &Op2 5079 : nullptr; 5080 const SDValue *UpperCheckOp = 5081 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 5082 ? &Op 5083 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 5084 ? &Op2 5085 : nullptr; 5086 5087 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 5088 return false; 5089 5090 // Check that the constant in the lower-bound check is 5091 // the opposite of the constant in the upper-bound check 5092 // in 1's complement. 5093 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 5094 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 5095 int64_t PosVal = std::max(Val1, Val2); 5096 int64_t NegVal = std::min(Val1, Val2); 5097 5098 if (((Val1 > Val2 && UpperCheckOp == &Op) || 5099 (Val1 < Val2 && UpperCheckOp == &Op2)) && 5100 isPowerOf2_64(PosVal + 1)) { 5101 5102 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 5103 if (Val1 == ~Val2) 5104 usat = false; 5105 else if (NegVal == 0) 5106 usat = true; 5107 else 5108 return false; 5109 5110 V = V2; 5111 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 5112 5113 return true; 5114 } 5115 5116 return false; 5117 } 5118 5119 // Check if a condition of the type x < k ? k : x can be converted into a 5120 // bit operation instead of conditional moves. 5121 // Currently this is allowed given: 5122 // - The conditions and values match up 5123 // - k is 0 or -1 (all ones) 5124 // This function will not check the last condition, thats up to the caller 5125 // It returns true if the transformation can be made, and in such case 5126 // returns x in V, and k in SatK. 5127 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 5128 SDValue &SatK) 5129 { 5130 SDValue LHS = Op.getOperand(0); 5131 SDValue RHS = Op.getOperand(1); 5132 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5133 SDValue TrueVal = Op.getOperand(2); 5134 SDValue FalseVal = Op.getOperand(3); 5135 5136 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 5137 ? &RHS 5138 : nullptr; 5139 5140 // No constant operation in comparison, early out 5141 if (!K) 5142 return false; 5143 5144 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 5145 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 5146 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 5147 5148 // If the constant on left and right side, or variable on left and right, 5149 // does not match, early out 5150 if (*K != KTmp || V != VTmp) 5151 return false; 5152 5153 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 5154 SatK = *K; 5155 return true; 5156 } 5157 5158 return false; 5159 } 5160 5161 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 5162 if (VT == MVT::f32) 5163 return !Subtarget->hasVFP2Base(); 5164 if (VT == MVT::f64) 5165 return !Subtarget->hasFP64(); 5166 if (VT == MVT::f16) 5167 return !Subtarget->hasFullFP16(); 5168 return false; 5169 } 5170 5171 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 5172 EVT VT = Op.getValueType(); 5173 SDLoc dl(Op); 5174 5175 // Try to convert two saturating conditional selects into a single SSAT 5176 SDValue SatValue; 5177 uint64_t SatConstant; 5178 bool SatUSat; 5179 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 5180 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 5181 if (SatUSat) 5182 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 5183 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 5184 else 5185 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 5186 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 5187 } 5188 5189 // Try to convert expressions of the form x < k ? k : x (and similar forms) 5190 // into more efficient bit operations, which is possible when k is 0 or -1 5191 // On ARM and Thumb-2 which have flexible operand 2 this will result in 5192 // single instructions. On Thumb the shift and the bit operation will be two 5193 // instructions. 5194 // Only allow this transformation on full-width (32-bit) operations 5195 SDValue LowerSatConstant; 5196 if (VT == MVT::i32 && 5197 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 5198 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 5199 DAG.getConstant(31, dl, VT)); 5200 if (isNullConstant(LowerSatConstant)) { 5201 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 5202 DAG.getAllOnesConstant(dl, VT)); 5203 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 5204 } else if (isAllOnesConstant(LowerSatConstant)) 5205 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 5206 } 5207 5208 SDValue LHS = Op.getOperand(0); 5209 SDValue RHS = Op.getOperand(1); 5210 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5211 SDValue TrueVal = Op.getOperand(2); 5212 SDValue FalseVal = Op.getOperand(3); 5213 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal); 5214 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal); 5215 5216 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal && 5217 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) { 5218 unsigned TVal = CTVal->getZExtValue(); 5219 unsigned FVal = CFVal->getZExtValue(); 5220 unsigned Opcode = 0; 5221 5222 if (TVal == ~FVal) { 5223 Opcode = ARMISD::CSINV; 5224 } else if (TVal == ~FVal + 1) { 5225 Opcode = ARMISD::CSNEG; 5226 } else if (TVal + 1 == FVal) { 5227 Opcode = ARMISD::CSINC; 5228 } else if (TVal == FVal + 1) { 5229 Opcode = ARMISD::CSINC; 5230 std::swap(TrueVal, FalseVal); 5231 std::swap(TVal, FVal); 5232 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5233 } 5234 5235 if (Opcode) { 5236 // If one of the constants is cheaper than another, materialise the 5237 // cheaper one and let the csel generate the other. 5238 if (Opcode != ARMISD::CSINC && 5239 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) { 5240 std::swap(TrueVal, FalseVal); 5241 std::swap(TVal, FVal); 5242 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5243 } 5244 5245 // Attempt to use ZR checking TVal is 0, possibly inverting the condition 5246 // to get there. CSINC not is invertable like the other two (~(~a) == a, 5247 // -(-a) == a, but (a+1)+1 != a). 5248 if (FVal == 0 && Opcode != ARMISD::CSINC) { 5249 std::swap(TrueVal, FalseVal); 5250 std::swap(TVal, FVal); 5251 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5252 } 5253 if (TVal == 0) 5254 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32); 5255 5256 // Drops F's value because we can get it by inverting/negating TVal. 5257 FalseVal = TrueVal; 5258 5259 SDValue ARMcc; 5260 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5261 EVT VT = TrueVal.getValueType(); 5262 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp); 5263 } 5264 } 5265 5266 if (isUnsupportedFloatingType(LHS.getValueType())) { 5267 DAG.getTargetLoweringInfo().softenSetCCOperands( 5268 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5269 5270 // If softenSetCCOperands only returned one value, we should compare it to 5271 // zero. 5272 if (!RHS.getNode()) { 5273 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5274 CC = ISD::SETNE; 5275 } 5276 } 5277 5278 if (LHS.getValueType() == MVT::i32) { 5279 // Try to generate VSEL on ARMv8. 5280 // The VSEL instruction can't use all the usual ARM condition 5281 // codes: it only has two bits to select the condition code, so it's 5282 // constrained to use only GE, GT, VS and EQ. 5283 // 5284 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 5285 // swap the operands of the previous compare instruction (effectively 5286 // inverting the compare condition, swapping 'less' and 'greater') and 5287 // sometimes need to swap the operands to the VSEL (which inverts the 5288 // condition in the sense of firing whenever the previous condition didn't) 5289 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 5290 TrueVal.getValueType() == MVT::f32 || 5291 TrueVal.getValueType() == MVT::f64)) { 5292 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5293 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 5294 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 5295 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5296 std::swap(TrueVal, FalseVal); 5297 } 5298 } 5299 5300 SDValue ARMcc; 5301 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5302 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5303 // Choose GE over PL, which vsel does now support 5304 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 5305 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 5306 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5307 } 5308 5309 ARMCC::CondCodes CondCode, CondCode2; 5310 FPCCToARMCC(CC, CondCode, CondCode2); 5311 5312 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 5313 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 5314 // must use VSEL (limited condition codes), due to not having conditional f16 5315 // moves. 5316 if (Subtarget->hasFPARMv8Base() && 5317 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 5318 (TrueVal.getValueType() == MVT::f16 || 5319 TrueVal.getValueType() == MVT::f32 || 5320 TrueVal.getValueType() == MVT::f64)) { 5321 bool swpCmpOps = false; 5322 bool swpVselOps = false; 5323 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 5324 5325 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 5326 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 5327 if (swpCmpOps) 5328 std::swap(LHS, RHS); 5329 if (swpVselOps) 5330 std::swap(TrueVal, FalseVal); 5331 } 5332 } 5333 5334 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5335 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5336 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5337 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5338 if (CondCode2 != ARMCC::AL) { 5339 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 5340 // FIXME: Needs another CMP because flag can have but one use. 5341 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 5342 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 5343 } 5344 return Result; 5345 } 5346 5347 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 5348 /// to morph to an integer compare sequence. 5349 static bool canChangeToInt(SDValue Op, bool &SeenZero, 5350 const ARMSubtarget *Subtarget) { 5351 SDNode *N = Op.getNode(); 5352 if (!N->hasOneUse()) 5353 // Otherwise it requires moving the value from fp to integer registers. 5354 return false; 5355 if (!N->getNumValues()) 5356 return false; 5357 EVT VT = Op.getValueType(); 5358 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 5359 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 5360 // vmrs are very slow, e.g. cortex-a8. 5361 return false; 5362 5363 if (isFloatingPointZero(Op)) { 5364 SeenZero = true; 5365 return true; 5366 } 5367 return ISD::isNormalLoad(N); 5368 } 5369 5370 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 5371 if (isFloatingPointZero(Op)) 5372 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 5373 5374 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 5375 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 5376 Ld->getPointerInfo(), Ld->getAlignment(), 5377 Ld->getMemOperand()->getFlags()); 5378 5379 llvm_unreachable("Unknown VFP cmp argument!"); 5380 } 5381 5382 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 5383 SDValue &RetVal1, SDValue &RetVal2) { 5384 SDLoc dl(Op); 5385 5386 if (isFloatingPointZero(Op)) { 5387 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 5388 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 5389 return; 5390 } 5391 5392 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 5393 SDValue Ptr = Ld->getBasePtr(); 5394 RetVal1 = 5395 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 5396 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 5397 5398 EVT PtrType = Ptr.getValueType(); 5399 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 5400 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 5401 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 5402 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 5403 Ld->getPointerInfo().getWithOffset(4), NewAlign, 5404 Ld->getMemOperand()->getFlags()); 5405 return; 5406 } 5407 5408 llvm_unreachable("Unknown VFP cmp argument!"); 5409 } 5410 5411 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 5412 /// f32 and even f64 comparisons to integer ones. 5413 SDValue 5414 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 5415 SDValue Chain = Op.getOperand(0); 5416 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5417 SDValue LHS = Op.getOperand(2); 5418 SDValue RHS = Op.getOperand(3); 5419 SDValue Dest = Op.getOperand(4); 5420 SDLoc dl(Op); 5421 5422 bool LHSSeenZero = false; 5423 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 5424 bool RHSSeenZero = false; 5425 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 5426 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 5427 // If unsafe fp math optimization is enabled and there are no other uses of 5428 // the CMP operands, and the condition code is EQ or NE, we can optimize it 5429 // to an integer comparison. 5430 if (CC == ISD::SETOEQ) 5431 CC = ISD::SETEQ; 5432 else if (CC == ISD::SETUNE) 5433 CC = ISD::SETNE; 5434 5435 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5436 SDValue ARMcc; 5437 if (LHS.getValueType() == MVT::f32) { 5438 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5439 bitcastf32Toi32(LHS, DAG), Mask); 5440 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5441 bitcastf32Toi32(RHS, DAG), Mask); 5442 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5443 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5444 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5445 Chain, Dest, ARMcc, CCR, Cmp); 5446 } 5447 5448 SDValue LHS1, LHS2; 5449 SDValue RHS1, RHS2; 5450 expandf64Toi32(LHS, DAG, LHS1, LHS2); 5451 expandf64Toi32(RHS, DAG, RHS1, RHS2); 5452 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 5453 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 5454 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5455 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5456 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5457 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 5458 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 5459 } 5460 5461 return SDValue(); 5462 } 5463 5464 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 5465 SDValue Chain = Op.getOperand(0); 5466 SDValue Cond = Op.getOperand(1); 5467 SDValue Dest = Op.getOperand(2); 5468 SDLoc dl(Op); 5469 5470 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5471 // instruction. 5472 unsigned Opc = Cond.getOpcode(); 5473 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5474 !Subtarget->isThumb1Only(); 5475 if (Cond.getResNo() == 1 && 5476 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5477 Opc == ISD::USUBO || OptimizeMul)) { 5478 // Only lower legal XALUO ops. 5479 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 5480 return SDValue(); 5481 5482 // The actual operation with overflow check. 5483 SDValue Value, OverflowCmp; 5484 SDValue ARMcc; 5485 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 5486 5487 // Reverse the condition code. 5488 ARMCC::CondCodes CondCode = 5489 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5490 CondCode = ARMCC::getOppositeCondition(CondCode); 5491 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5492 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5493 5494 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5495 OverflowCmp); 5496 } 5497 5498 return SDValue(); 5499 } 5500 5501 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5502 SDValue Chain = Op.getOperand(0); 5503 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5504 SDValue LHS = Op.getOperand(2); 5505 SDValue RHS = Op.getOperand(3); 5506 SDValue Dest = Op.getOperand(4); 5507 SDLoc dl(Op); 5508 5509 if (isUnsupportedFloatingType(LHS.getValueType())) { 5510 DAG.getTargetLoweringInfo().softenSetCCOperands( 5511 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5512 5513 // If softenSetCCOperands only returned one value, we should compare it to 5514 // zero. 5515 if (!RHS.getNode()) { 5516 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5517 CC = ISD::SETNE; 5518 } 5519 } 5520 5521 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5522 // instruction. 5523 unsigned Opc = LHS.getOpcode(); 5524 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5525 !Subtarget->isThumb1Only(); 5526 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5527 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5528 Opc == ISD::USUBO || OptimizeMul) && 5529 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5530 // Only lower legal XALUO ops. 5531 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5532 return SDValue(); 5533 5534 // The actual operation with overflow check. 5535 SDValue Value, OverflowCmp; 5536 SDValue ARMcc; 5537 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5538 5539 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5540 // Reverse the condition code. 5541 ARMCC::CondCodes CondCode = 5542 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5543 CondCode = ARMCC::getOppositeCondition(CondCode); 5544 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5545 } 5546 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5547 5548 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5549 OverflowCmp); 5550 } 5551 5552 if (LHS.getValueType() == MVT::i32) { 5553 SDValue ARMcc; 5554 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5555 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5556 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5557 Chain, Dest, ARMcc, CCR, Cmp); 5558 } 5559 5560 if (getTargetMachine().Options.UnsafeFPMath && 5561 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5562 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5563 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5564 return Result; 5565 } 5566 5567 ARMCC::CondCodes CondCode, CondCode2; 5568 FPCCToARMCC(CC, CondCode, CondCode2); 5569 5570 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5571 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5572 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5573 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5574 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5575 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5576 if (CondCode2 != ARMCC::AL) { 5577 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5578 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5579 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5580 } 5581 return Res; 5582 } 5583 5584 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5585 SDValue Chain = Op.getOperand(0); 5586 SDValue Table = Op.getOperand(1); 5587 SDValue Index = Op.getOperand(2); 5588 SDLoc dl(Op); 5589 5590 EVT PTy = getPointerTy(DAG.getDataLayout()); 5591 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5592 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5593 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5594 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5595 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5596 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5597 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5598 // which does another jump to the destination. This also makes it easier 5599 // to translate it to TBB / TBH later (Thumb2 only). 5600 // FIXME: This might not work if the function is extremely large. 5601 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5602 Addr, Op.getOperand(2), JTI); 5603 } 5604 if (isPositionIndependent() || Subtarget->isROPI()) { 5605 Addr = 5606 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5607 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5608 Chain = Addr.getValue(1); 5609 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5610 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5611 } else { 5612 Addr = 5613 DAG.getLoad(PTy, dl, Chain, Addr, 5614 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5615 Chain = Addr.getValue(1); 5616 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5617 } 5618 } 5619 5620 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5621 EVT VT = Op.getValueType(); 5622 SDLoc dl(Op); 5623 5624 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5625 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5626 return Op; 5627 return DAG.UnrollVectorOp(Op.getNode()); 5628 } 5629 5630 const bool HasFullFP16 = 5631 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5632 5633 EVT NewTy; 5634 const EVT OpTy = Op.getOperand(0).getValueType(); 5635 if (OpTy == MVT::v4f32) 5636 NewTy = MVT::v4i32; 5637 else if (OpTy == MVT::v4f16 && HasFullFP16) 5638 NewTy = MVT::v4i16; 5639 else if (OpTy == MVT::v8f16 && HasFullFP16) 5640 NewTy = MVT::v8i16; 5641 else 5642 llvm_unreachable("Invalid type for custom lowering!"); 5643 5644 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5645 return DAG.UnrollVectorOp(Op.getNode()); 5646 5647 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5648 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5649 } 5650 5651 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5652 EVT VT = Op.getValueType(); 5653 if (VT.isVector()) 5654 return LowerVectorFP_TO_INT(Op, DAG); 5655 5656 bool IsStrict = Op->isStrictFPOpcode(); 5657 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 5658 5659 if (isUnsupportedFloatingType(SrcVal.getValueType())) { 5660 RTLIB::Libcall LC; 5661 if (Op.getOpcode() == ISD::FP_TO_SINT || 5662 Op.getOpcode() == ISD::STRICT_FP_TO_SINT) 5663 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), 5664 Op.getValueType()); 5665 else 5666 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), 5667 Op.getValueType()); 5668 SDLoc Loc(Op); 5669 MakeLibCallOptions CallOptions; 5670 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 5671 SDValue Result; 5672 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal, 5673 CallOptions, Loc, Chain); 5674 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 5675 } 5676 5677 // FIXME: Remove this when we have strict fp instruction selection patterns 5678 if (IsStrict) { 5679 SDLoc Loc(Op); 5680 SDValue Result = 5681 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT 5682 : ISD::FP_TO_UINT, 5683 Loc, Op.getValueType(), SrcVal); 5684 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 5685 } 5686 5687 return Op; 5688 } 5689 5690 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5691 EVT VT = Op.getValueType(); 5692 SDLoc dl(Op); 5693 5694 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5695 if (VT.getVectorElementType() == MVT::f32) 5696 return Op; 5697 return DAG.UnrollVectorOp(Op.getNode()); 5698 } 5699 5700 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5701 Op.getOperand(0).getValueType() == MVT::v8i16) && 5702 "Invalid type for custom lowering!"); 5703 5704 const bool HasFullFP16 = 5705 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5706 5707 EVT DestVecType; 5708 if (VT == MVT::v4f32) 5709 DestVecType = MVT::v4i32; 5710 else if (VT == MVT::v4f16 && HasFullFP16) 5711 DestVecType = MVT::v4i16; 5712 else if (VT == MVT::v8f16 && HasFullFP16) 5713 DestVecType = MVT::v8i16; 5714 else 5715 return DAG.UnrollVectorOp(Op.getNode()); 5716 5717 unsigned CastOpc; 5718 unsigned Opc; 5719 switch (Op.getOpcode()) { 5720 default: llvm_unreachable("Invalid opcode!"); 5721 case ISD::SINT_TO_FP: 5722 CastOpc = ISD::SIGN_EXTEND; 5723 Opc = ISD::SINT_TO_FP; 5724 break; 5725 case ISD::UINT_TO_FP: 5726 CastOpc = ISD::ZERO_EXTEND; 5727 Opc = ISD::UINT_TO_FP; 5728 break; 5729 } 5730 5731 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5732 return DAG.getNode(Opc, dl, VT, Op); 5733 } 5734 5735 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5736 EVT VT = Op.getValueType(); 5737 if (VT.isVector()) 5738 return LowerVectorINT_TO_FP(Op, DAG); 5739 if (isUnsupportedFloatingType(VT)) { 5740 RTLIB::Libcall LC; 5741 if (Op.getOpcode() == ISD::SINT_TO_FP) 5742 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5743 Op.getValueType()); 5744 else 5745 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5746 Op.getValueType()); 5747 MakeLibCallOptions CallOptions; 5748 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5749 CallOptions, SDLoc(Op)).first; 5750 } 5751 5752 return Op; 5753 } 5754 5755 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5756 // Implement fcopysign with a fabs and a conditional fneg. 5757 SDValue Tmp0 = Op.getOperand(0); 5758 SDValue Tmp1 = Op.getOperand(1); 5759 SDLoc dl(Op); 5760 EVT VT = Op.getValueType(); 5761 EVT SrcVT = Tmp1.getValueType(); 5762 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5763 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5764 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5765 5766 if (UseNEON) { 5767 // Use VBSL to copy the sign bit. 5768 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5769 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5770 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5771 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5772 if (VT == MVT::f64) 5773 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5774 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5775 DAG.getConstant(32, dl, MVT::i32)); 5776 else /*if (VT == MVT::f32)*/ 5777 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5778 if (SrcVT == MVT::f32) { 5779 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5780 if (VT == MVT::f64) 5781 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5782 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5783 DAG.getConstant(32, dl, MVT::i32)); 5784 } else if (VT == MVT::f32) 5785 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5786 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5787 DAG.getConstant(32, dl, MVT::i32)); 5788 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5789 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5790 5791 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5792 dl, MVT::i32); 5793 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5794 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5795 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5796 5797 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5798 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5799 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5800 if (VT == MVT::f32) { 5801 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5802 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5803 DAG.getConstant(0, dl, MVT::i32)); 5804 } else { 5805 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5806 } 5807 5808 return Res; 5809 } 5810 5811 // Bitcast operand 1 to i32. 5812 if (SrcVT == MVT::f64) 5813 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5814 Tmp1).getValue(1); 5815 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5816 5817 // Or in the signbit with integer operations. 5818 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5819 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5820 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5821 if (VT == MVT::f32) { 5822 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5823 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5824 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5825 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5826 } 5827 5828 // f64: Or the high part with signbit and then combine two parts. 5829 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5830 Tmp0); 5831 SDValue Lo = Tmp0.getValue(0); 5832 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5833 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5834 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5835 } 5836 5837 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5838 MachineFunction &MF = DAG.getMachineFunction(); 5839 MachineFrameInfo &MFI = MF.getFrameInfo(); 5840 MFI.setReturnAddressIsTaken(true); 5841 5842 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5843 return SDValue(); 5844 5845 EVT VT = Op.getValueType(); 5846 SDLoc dl(Op); 5847 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5848 if (Depth) { 5849 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5850 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5851 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5852 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5853 MachinePointerInfo()); 5854 } 5855 5856 // Return LR, which contains the return address. Mark it an implicit live-in. 5857 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5858 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5859 } 5860 5861 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5862 const ARMBaseRegisterInfo &ARI = 5863 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5864 MachineFunction &MF = DAG.getMachineFunction(); 5865 MachineFrameInfo &MFI = MF.getFrameInfo(); 5866 MFI.setFrameAddressIsTaken(true); 5867 5868 EVT VT = Op.getValueType(); 5869 SDLoc dl(Op); // FIXME probably not meaningful 5870 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5871 Register FrameReg = ARI.getFrameRegister(MF); 5872 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5873 while (Depth--) 5874 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5875 MachinePointerInfo()); 5876 return FrameAddr; 5877 } 5878 5879 // FIXME? Maybe this could be a TableGen attribute on some registers and 5880 // this table could be generated automatically from RegInfo. 5881 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT, 5882 const MachineFunction &MF) const { 5883 Register Reg = StringSwitch<unsigned>(RegName) 5884 .Case("sp", ARM::SP) 5885 .Default(0); 5886 if (Reg) 5887 return Reg; 5888 report_fatal_error(Twine("Invalid register name \"" 5889 + StringRef(RegName) + "\".")); 5890 } 5891 5892 // Result is 64 bit value so split into two 32 bit values and return as a 5893 // pair of values. 5894 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5895 SelectionDAG &DAG) { 5896 SDLoc DL(N); 5897 5898 // This function is only supposed to be called for i64 type destination. 5899 assert(N->getValueType(0) == MVT::i64 5900 && "ExpandREAD_REGISTER called for non-i64 type result."); 5901 5902 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5903 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5904 N->getOperand(0), 5905 N->getOperand(1)); 5906 5907 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5908 Read.getValue(1))); 5909 Results.push_back(Read.getOperand(0)); 5910 } 5911 5912 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5913 /// When \p DstVT, the destination type of \p BC, is on the vector 5914 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5915 /// it might be possible to combine them, such that everything stays on the 5916 /// vector register bank. 5917 /// \p return The node that would replace \p BT, if the combine 5918 /// is possible. 5919 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5920 SelectionDAG &DAG) { 5921 SDValue Op = BC->getOperand(0); 5922 EVT DstVT = BC->getValueType(0); 5923 5924 // The only vector instruction that can produce a scalar (remember, 5925 // since the bitcast was about to be turned into VMOVDRR, the source 5926 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5927 // Moreover, we can do this combine only if there is one use. 5928 // Finally, if the destination type is not a vector, there is not 5929 // much point on forcing everything on the vector bank. 5930 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5931 !Op.hasOneUse()) 5932 return SDValue(); 5933 5934 // If the index is not constant, we will introduce an additional 5935 // multiply that will stick. 5936 // Give up in that case. 5937 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5938 if (!Index) 5939 return SDValue(); 5940 unsigned DstNumElt = DstVT.getVectorNumElements(); 5941 5942 // Compute the new index. 5943 const APInt &APIntIndex = Index->getAPIntValue(); 5944 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5945 NewIndex *= APIntIndex; 5946 // Check if the new constant index fits into i32. 5947 if (NewIndex.getBitWidth() > 32) 5948 return SDValue(); 5949 5950 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5951 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5952 SDLoc dl(Op); 5953 SDValue ExtractSrc = Op.getOperand(0); 5954 EVT VecVT = EVT::getVectorVT( 5955 *DAG.getContext(), DstVT.getScalarType(), 5956 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5957 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5958 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5959 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5960 } 5961 5962 /// ExpandBITCAST - If the target supports VFP, this function is called to 5963 /// expand a bit convert where either the source or destination type is i64 to 5964 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5965 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5966 /// vectors), since the legalizer won't know what to do with that. 5967 SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5968 const ARMSubtarget *Subtarget) const { 5969 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5970 SDLoc dl(N); 5971 SDValue Op = N->getOperand(0); 5972 5973 // This function is only supposed to be called for i16 and i64 types, either 5974 // as the source or destination of the bit convert. 5975 EVT SrcVT = Op.getValueType(); 5976 EVT DstVT = N->getValueType(0); 5977 5978 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) && 5979 (DstVT == MVT::f16 || DstVT == MVT::bf16)) 5980 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(), 5981 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op)); 5982 5983 if ((DstVT == MVT::i16 || DstVT == MVT::i32) && 5984 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) 5985 return DAG.getNode( 5986 ISD::TRUNCATE, SDLoc(N), DstVT, 5987 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op)); 5988 5989 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5990 return SDValue(); 5991 5992 // Turn i64->f64 into VMOVDRR. 5993 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5994 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5995 // if we can combine the bitcast with its source. 5996 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5997 return Val; 5998 5999 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 6000 DAG.getConstant(0, dl, MVT::i32)); 6001 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 6002 DAG.getConstant(1, dl, MVT::i32)); 6003 return DAG.getNode(ISD::BITCAST, dl, DstVT, 6004 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 6005 } 6006 6007 // Turn f64->i64 into VMOVRRD. 6008 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 6009 SDValue Cvt; 6010 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 6011 SrcVT.getVectorNumElements() > 1) 6012 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 6013 DAG.getVTList(MVT::i32, MVT::i32), 6014 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 6015 else 6016 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 6017 DAG.getVTList(MVT::i32, MVT::i32), Op); 6018 // Merge the pieces into a single i64 value. 6019 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 6020 } 6021 6022 return SDValue(); 6023 } 6024 6025 /// getZeroVector - Returns a vector of specified type with all zero elements. 6026 /// Zero vectors are used to represent vector negation and in those cases 6027 /// will be implemented with the NEON VNEG instruction. However, VNEG does 6028 /// not support i64 elements, so sometimes the zero vectors will need to be 6029 /// explicitly constructed. Regardless, use a canonical VMOV to create the 6030 /// zero vector. 6031 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 6032 assert(VT.isVector() && "Expected a vector type"); 6033 // The canonical modified immediate encoding of a zero vector is....0! 6034 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 6035 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 6036 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 6037 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6038 } 6039 6040 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 6041 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 6042 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 6043 SelectionDAG &DAG) const { 6044 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6045 EVT VT = Op.getValueType(); 6046 unsigned VTBits = VT.getSizeInBits(); 6047 SDLoc dl(Op); 6048 SDValue ShOpLo = Op.getOperand(0); 6049 SDValue ShOpHi = Op.getOperand(1); 6050 SDValue ShAmt = Op.getOperand(2); 6051 SDValue ARMcc; 6052 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6053 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 6054 6055 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 6056 6057 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6058 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 6059 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 6060 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 6061 DAG.getConstant(VTBits, dl, MVT::i32)); 6062 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 6063 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 6064 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 6065 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6066 ISD::SETGE, ARMcc, DAG, dl); 6067 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 6068 ARMcc, CCR, CmpLo); 6069 6070 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 6071 SDValue HiBigShift = Opc == ISD::SRA 6072 ? DAG.getNode(Opc, dl, VT, ShOpHi, 6073 DAG.getConstant(VTBits - 1, dl, VT)) 6074 : DAG.getConstant(0, dl, VT); 6075 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6076 ISD::SETGE, ARMcc, DAG, dl); 6077 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 6078 ARMcc, CCR, CmpHi); 6079 6080 SDValue Ops[2] = { Lo, Hi }; 6081 return DAG.getMergeValues(Ops, dl); 6082 } 6083 6084 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 6085 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 6086 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 6087 SelectionDAG &DAG) const { 6088 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6089 EVT VT = Op.getValueType(); 6090 unsigned VTBits = VT.getSizeInBits(); 6091 SDLoc dl(Op); 6092 SDValue ShOpLo = Op.getOperand(0); 6093 SDValue ShOpHi = Op.getOperand(1); 6094 SDValue ShAmt = Op.getOperand(2); 6095 SDValue ARMcc; 6096 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6097 6098 assert(Op.getOpcode() == ISD::SHL_PARTS); 6099 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6100 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 6101 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 6102 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 6103 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 6104 6105 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 6106 DAG.getConstant(VTBits, dl, MVT::i32)); 6107 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 6108 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6109 ISD::SETGE, ARMcc, DAG, dl); 6110 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 6111 ARMcc, CCR, CmpHi); 6112 6113 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6114 ISD::SETGE, ARMcc, DAG, dl); 6115 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6116 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 6117 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 6118 6119 SDValue Ops[2] = { Lo, Hi }; 6120 return DAG.getMergeValues(Ops, dl); 6121 } 6122 6123 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 6124 SelectionDAG &DAG) const { 6125 // The rounding mode is in bits 23:22 of the FPSCR. 6126 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 6127 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 6128 // so that the shift + and get folded into a bitfield extract. 6129 SDLoc dl(Op); 6130 SDValue Chain = Op.getOperand(0); 6131 SDValue Ops[] = {Chain, 6132 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)}; 6133 6134 SDValue FPSCR = 6135 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops); 6136 Chain = FPSCR.getValue(1); 6137 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 6138 DAG.getConstant(1U << 22, dl, MVT::i32)); 6139 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 6140 DAG.getConstant(22, dl, MVT::i32)); 6141 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 6142 DAG.getConstant(3, dl, MVT::i32)); 6143 return DAG.getMergeValues({And, Chain}, dl); 6144 } 6145 6146 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 6147 const ARMSubtarget *ST) { 6148 SDLoc dl(N); 6149 EVT VT = N->getValueType(0); 6150 if (VT.isVector() && ST->hasNEON()) { 6151 6152 // Compute the least significant set bit: LSB = X & -X 6153 SDValue X = N->getOperand(0); 6154 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 6155 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 6156 6157 EVT ElemTy = VT.getVectorElementType(); 6158 6159 if (ElemTy == MVT::i8) { 6160 // Compute with: cttz(x) = ctpop(lsb - 1) 6161 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6162 DAG.getTargetConstant(1, dl, ElemTy)); 6163 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6164 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6165 } 6166 6167 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 6168 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 6169 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 6170 unsigned NumBits = ElemTy.getSizeInBits(); 6171 SDValue WidthMinus1 = 6172 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6173 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 6174 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 6175 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 6176 } 6177 6178 // Compute with: cttz(x) = ctpop(lsb - 1) 6179 6180 // Compute LSB - 1. 6181 SDValue Bits; 6182 if (ElemTy == MVT::i64) { 6183 // Load constant 0xffff'ffff'ffff'ffff to register. 6184 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6185 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 6186 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 6187 } else { 6188 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6189 DAG.getTargetConstant(1, dl, ElemTy)); 6190 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6191 } 6192 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6193 } 6194 6195 if (!ST->hasV6T2Ops()) 6196 return SDValue(); 6197 6198 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 6199 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 6200 } 6201 6202 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 6203 const ARMSubtarget *ST) { 6204 EVT VT = N->getValueType(0); 6205 SDLoc DL(N); 6206 6207 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 6208 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 6209 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 6210 "Unexpected type for custom ctpop lowering"); 6211 6212 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6213 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 6214 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 6215 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 6216 6217 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 6218 unsigned EltSize = 8; 6219 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 6220 while (EltSize != VT.getScalarSizeInBits()) { 6221 SmallVector<SDValue, 8> Ops; 6222 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 6223 TLI.getPointerTy(DAG.getDataLayout()))); 6224 Ops.push_back(Res); 6225 6226 EltSize *= 2; 6227 NumElts /= 2; 6228 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 6229 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 6230 } 6231 6232 return Res; 6233 } 6234 6235 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 6236 /// operand of a vector shift operation, where all the elements of the 6237 /// build_vector must have the same constant integer value. 6238 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6239 // Ignore bit_converts. 6240 while (Op.getOpcode() == ISD::BITCAST) 6241 Op = Op.getOperand(0); 6242 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6243 APInt SplatBits, SplatUndef; 6244 unsigned SplatBitSize; 6245 bool HasAnyUndefs; 6246 if (!BVN || 6247 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 6248 ElementBits) || 6249 SplatBitSize > ElementBits) 6250 return false; 6251 Cnt = SplatBits.getSExtValue(); 6252 return true; 6253 } 6254 6255 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6256 /// operand of a vector shift left operation. That value must be in the range: 6257 /// 0 <= Value < ElementBits for a left shift; or 6258 /// 0 <= Value <= ElementBits for a long left shift. 6259 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6260 assert(VT.isVector() && "vector shift count is not a vector type"); 6261 int64_t ElementBits = VT.getScalarSizeInBits(); 6262 if (!getVShiftImm(Op, ElementBits, Cnt)) 6263 return false; 6264 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6265 } 6266 6267 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6268 /// operand of a vector shift right operation. For a shift opcode, the value 6269 /// is positive, but for an intrinsic the value count must be negative. The 6270 /// absolute value must be in the range: 6271 /// 1 <= |Value| <= ElementBits for a right shift; or 6272 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 6273 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 6274 int64_t &Cnt) { 6275 assert(VT.isVector() && "vector shift count is not a vector type"); 6276 int64_t ElementBits = VT.getScalarSizeInBits(); 6277 if (!getVShiftImm(Op, ElementBits, Cnt)) 6278 return false; 6279 if (!isIntrinsic) 6280 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6281 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 6282 Cnt = -Cnt; 6283 return true; 6284 } 6285 return false; 6286 } 6287 6288 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 6289 const ARMSubtarget *ST) { 6290 EVT VT = N->getValueType(0); 6291 SDLoc dl(N); 6292 int64_t Cnt; 6293 6294 if (!VT.isVector()) 6295 return SDValue(); 6296 6297 // We essentially have two forms here. Shift by an immediate and shift by a 6298 // vector register (there are also shift by a gpr, but that is just handled 6299 // with a tablegen pattern). We cannot easily match shift by an immediate in 6300 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 6301 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 6302 // signed or unsigned, and a negative shift indicates a shift right). 6303 if (N->getOpcode() == ISD::SHL) { 6304 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 6305 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 6306 DAG.getConstant(Cnt, dl, MVT::i32)); 6307 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 6308 N->getOperand(1)); 6309 } 6310 6311 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 6312 "unexpected vector shift opcode"); 6313 6314 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 6315 unsigned VShiftOpc = 6316 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 6317 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 6318 DAG.getConstant(Cnt, dl, MVT::i32)); 6319 } 6320 6321 // Other right shifts we don't have operations for (we use a shift left by a 6322 // negative number). 6323 EVT ShiftVT = N->getOperand(1).getValueType(); 6324 SDValue NegatedCount = DAG.getNode( 6325 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 6326 unsigned VShiftOpc = 6327 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 6328 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 6329 } 6330 6331 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 6332 const ARMSubtarget *ST) { 6333 EVT VT = N->getValueType(0); 6334 SDLoc dl(N); 6335 6336 // We can get here for a node like i32 = ISD::SHL i32, i64 6337 if (VT != MVT::i64) 6338 return SDValue(); 6339 6340 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 6341 N->getOpcode() == ISD::SHL) && 6342 "Unknown shift to lower!"); 6343 6344 unsigned ShOpc = N->getOpcode(); 6345 if (ST->hasMVEIntegerOps()) { 6346 SDValue ShAmt = N->getOperand(1); 6347 unsigned ShPartsOpc = ARMISD::LSLL; 6348 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 6349 6350 // If the shift amount is greater than 32 or has a greater bitwidth than 64 6351 // then do the default optimisation 6352 if (ShAmt->getValueType(0).getSizeInBits() > 64 || 6353 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32))) 6354 return SDValue(); 6355 6356 // Extract the lower 32 bits of the shift amount if it's not an i32 6357 if (ShAmt->getValueType(0) != MVT::i32) 6358 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32); 6359 6360 if (ShOpc == ISD::SRL) { 6361 if (!Con) 6362 // There is no t2LSRLr instruction so negate and perform an lsll if the 6363 // shift amount is in a register, emulating a right shift. 6364 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6365 DAG.getConstant(0, dl, MVT::i32), ShAmt); 6366 else 6367 // Else generate an lsrl on the immediate shift amount 6368 ShPartsOpc = ARMISD::LSRL; 6369 } else if (ShOpc == ISD::SRA) 6370 ShPartsOpc = ARMISD::ASRL; 6371 6372 // Lower 32 bits of the destination/source 6373 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6374 DAG.getConstant(0, dl, MVT::i32)); 6375 // Upper 32 bits of the destination/source 6376 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6377 DAG.getConstant(1, dl, MVT::i32)); 6378 6379 // Generate the shift operation as computed above 6380 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 6381 ShAmt); 6382 // The upper 32 bits come from the second return value of lsll 6383 Hi = SDValue(Lo.getNode(), 1); 6384 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6385 } 6386 6387 // We only lower SRA, SRL of 1 here, all others use generic lowering. 6388 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 6389 return SDValue(); 6390 6391 // If we are in thumb mode, we don't have RRX. 6392 if (ST->isThumb1Only()) 6393 return SDValue(); 6394 6395 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 6396 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6397 DAG.getConstant(0, dl, MVT::i32)); 6398 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6399 DAG.getConstant(1, dl, MVT::i32)); 6400 6401 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 6402 // captures the result into a carry flag. 6403 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 6404 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 6405 6406 // The low part is an ARMISD::RRX operand, which shifts the carry in. 6407 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 6408 6409 // Merge the pieces into a single i64 value. 6410 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6411 } 6412 6413 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 6414 const ARMSubtarget *ST) { 6415 bool Invert = false; 6416 bool Swap = false; 6417 unsigned Opc = ARMCC::AL; 6418 6419 SDValue Op0 = Op.getOperand(0); 6420 SDValue Op1 = Op.getOperand(1); 6421 SDValue CC = Op.getOperand(2); 6422 EVT VT = Op.getValueType(); 6423 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 6424 SDLoc dl(Op); 6425 6426 EVT CmpVT; 6427 if (ST->hasNEON()) 6428 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 6429 else { 6430 assert(ST->hasMVEIntegerOps() && 6431 "No hardware support for integer vector comparison!"); 6432 6433 if (Op.getValueType().getVectorElementType() != MVT::i1) 6434 return SDValue(); 6435 6436 // Make sure we expand floating point setcc to scalar if we do not have 6437 // mve.fp, so that we can handle them from there. 6438 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 6439 return SDValue(); 6440 6441 CmpVT = VT; 6442 } 6443 6444 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 6445 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 6446 // Special-case integer 64-bit equality comparisons. They aren't legal, 6447 // but they can be lowered with a few vector instructions. 6448 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 6449 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 6450 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 6451 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 6452 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 6453 DAG.getCondCode(ISD::SETEQ)); 6454 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 6455 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 6456 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 6457 if (SetCCOpcode == ISD::SETNE) 6458 Merged = DAG.getNOT(dl, Merged, CmpVT); 6459 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 6460 return Merged; 6461 } 6462 6463 if (CmpVT.getVectorElementType() == MVT::i64) 6464 // 64-bit comparisons are not legal in general. 6465 return SDValue(); 6466 6467 if (Op1.getValueType().isFloatingPoint()) { 6468 switch (SetCCOpcode) { 6469 default: llvm_unreachable("Illegal FP comparison"); 6470 case ISD::SETUNE: 6471 case ISD::SETNE: 6472 if (ST->hasMVEFloatOps()) { 6473 Opc = ARMCC::NE; break; 6474 } else { 6475 Invert = true; LLVM_FALLTHROUGH; 6476 } 6477 case ISD::SETOEQ: 6478 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6479 case ISD::SETOLT: 6480 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6481 case ISD::SETOGT: 6482 case ISD::SETGT: Opc = ARMCC::GT; break; 6483 case ISD::SETOLE: 6484 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6485 case ISD::SETOGE: 6486 case ISD::SETGE: Opc = ARMCC::GE; break; 6487 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6488 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6489 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6490 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6491 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6492 case ISD::SETONE: { 6493 // Expand this to (OLT | OGT). 6494 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6495 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6496 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6497 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6498 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6499 if (Invert) 6500 Result = DAG.getNOT(dl, Result, VT); 6501 return Result; 6502 } 6503 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6504 case ISD::SETO: { 6505 // Expand this to (OLT | OGE). 6506 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6507 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6508 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6509 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6510 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6511 if (Invert) 6512 Result = DAG.getNOT(dl, Result, VT); 6513 return Result; 6514 } 6515 } 6516 } else { 6517 // Integer comparisons. 6518 switch (SetCCOpcode) { 6519 default: llvm_unreachable("Illegal integer comparison"); 6520 case ISD::SETNE: 6521 if (ST->hasMVEIntegerOps()) { 6522 Opc = ARMCC::NE; break; 6523 } else { 6524 Invert = true; LLVM_FALLTHROUGH; 6525 } 6526 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6527 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6528 case ISD::SETGT: Opc = ARMCC::GT; break; 6529 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6530 case ISD::SETGE: Opc = ARMCC::GE; break; 6531 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6532 case ISD::SETUGT: Opc = ARMCC::HI; break; 6533 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6534 case ISD::SETUGE: Opc = ARMCC::HS; break; 6535 } 6536 6537 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6538 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6539 SDValue AndOp; 6540 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6541 AndOp = Op0; 6542 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6543 AndOp = Op1; 6544 6545 // Ignore bitconvert. 6546 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6547 AndOp = AndOp.getOperand(0); 6548 6549 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6550 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6551 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6552 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6553 if (!Invert) 6554 Result = DAG.getNOT(dl, Result, VT); 6555 return Result; 6556 } 6557 } 6558 } 6559 6560 if (Swap) 6561 std::swap(Op0, Op1); 6562 6563 // If one of the operands is a constant vector zero, attempt to fold the 6564 // comparison to a specialized compare-against-zero form. 6565 SDValue SingleOp; 6566 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6567 SingleOp = Op0; 6568 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6569 if (Opc == ARMCC::GE) 6570 Opc = ARMCC::LE; 6571 else if (Opc == ARMCC::GT) 6572 Opc = ARMCC::LT; 6573 SingleOp = Op1; 6574 } 6575 6576 SDValue Result; 6577 if (SingleOp.getNode()) { 6578 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6579 DAG.getConstant(Opc, dl, MVT::i32)); 6580 } else { 6581 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6582 DAG.getConstant(Opc, dl, MVT::i32)); 6583 } 6584 6585 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6586 6587 if (Invert) 6588 Result = DAG.getNOT(dl, Result, VT); 6589 6590 return Result; 6591 } 6592 6593 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6594 SDValue LHS = Op.getOperand(0); 6595 SDValue RHS = Op.getOperand(1); 6596 SDValue Carry = Op.getOperand(2); 6597 SDValue Cond = Op.getOperand(3); 6598 SDLoc DL(Op); 6599 6600 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6601 6602 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6603 // have to invert the carry first. 6604 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6605 DAG.getConstant(1, DL, MVT::i32), Carry); 6606 // This converts the boolean value carry into the carry flag. 6607 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6608 6609 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6610 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6611 6612 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6613 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6614 SDValue ARMcc = DAG.getConstant( 6615 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6616 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6617 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6618 Cmp.getValue(1), SDValue()); 6619 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6620 CCR, Chain.getValue(1)); 6621 } 6622 6623 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6624 /// valid vector constant for a NEON or MVE instruction with a "modified 6625 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6626 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6627 unsigned SplatBitSize, SelectionDAG &DAG, 6628 const SDLoc &dl, EVT &VT, EVT VectorVT, 6629 VMOVModImmType type) { 6630 unsigned OpCmode, Imm; 6631 bool is128Bits = VectorVT.is128BitVector(); 6632 6633 // SplatBitSize is set to the smallest size that splats the vector, so a 6634 // zero vector will always have SplatBitSize == 8. However, NEON modified 6635 // immediate instructions others than VMOV do not support the 8-bit encoding 6636 // of a zero vector, and the default encoding of zero is supposed to be the 6637 // 32-bit version. 6638 if (SplatBits == 0) 6639 SplatBitSize = 32; 6640 6641 switch (SplatBitSize) { 6642 case 8: 6643 if (type != VMOVModImm) 6644 return SDValue(); 6645 // Any 1-byte value is OK. Op=0, Cmode=1110. 6646 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6647 OpCmode = 0xe; 6648 Imm = SplatBits; 6649 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6650 break; 6651 6652 case 16: 6653 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6654 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6655 if ((SplatBits & ~0xff) == 0) { 6656 // Value = 0x00nn: Op=x, Cmode=100x. 6657 OpCmode = 0x8; 6658 Imm = SplatBits; 6659 break; 6660 } 6661 if ((SplatBits & ~0xff00) == 0) { 6662 // Value = 0xnn00: Op=x, Cmode=101x. 6663 OpCmode = 0xa; 6664 Imm = SplatBits >> 8; 6665 break; 6666 } 6667 return SDValue(); 6668 6669 case 32: 6670 // NEON's 32-bit VMOV supports splat values where: 6671 // * only one byte is nonzero, or 6672 // * the least significant byte is 0xff and the second byte is nonzero, or 6673 // * the least significant 2 bytes are 0xff and the third is nonzero. 6674 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6675 if ((SplatBits & ~0xff) == 0) { 6676 // Value = 0x000000nn: Op=x, Cmode=000x. 6677 OpCmode = 0; 6678 Imm = SplatBits; 6679 break; 6680 } 6681 if ((SplatBits & ~0xff00) == 0) { 6682 // Value = 0x0000nn00: Op=x, Cmode=001x. 6683 OpCmode = 0x2; 6684 Imm = SplatBits >> 8; 6685 break; 6686 } 6687 if ((SplatBits & ~0xff0000) == 0) { 6688 // Value = 0x00nn0000: Op=x, Cmode=010x. 6689 OpCmode = 0x4; 6690 Imm = SplatBits >> 16; 6691 break; 6692 } 6693 if ((SplatBits & ~0xff000000) == 0) { 6694 // Value = 0xnn000000: Op=x, Cmode=011x. 6695 OpCmode = 0x6; 6696 Imm = SplatBits >> 24; 6697 break; 6698 } 6699 6700 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6701 if (type == OtherModImm) return SDValue(); 6702 6703 if ((SplatBits & ~0xffff) == 0 && 6704 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6705 // Value = 0x0000nnff: Op=x, Cmode=1100. 6706 OpCmode = 0xc; 6707 Imm = SplatBits >> 8; 6708 break; 6709 } 6710 6711 // cmode == 0b1101 is not supported for MVE VMVN 6712 if (type == MVEVMVNModImm) 6713 return SDValue(); 6714 6715 if ((SplatBits & ~0xffffff) == 0 && 6716 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6717 // Value = 0x00nnffff: Op=x, Cmode=1101. 6718 OpCmode = 0xd; 6719 Imm = SplatBits >> 16; 6720 break; 6721 } 6722 6723 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6724 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6725 // VMOV.I32. A (very) minor optimization would be to replicate the value 6726 // and fall through here to test for a valid 64-bit splat. But, then the 6727 // caller would also need to check and handle the change in size. 6728 return SDValue(); 6729 6730 case 64: { 6731 if (type != VMOVModImm) 6732 return SDValue(); 6733 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6734 uint64_t BitMask = 0xff; 6735 uint64_t Val = 0; 6736 unsigned ImmMask = 1; 6737 Imm = 0; 6738 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6739 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6740 Val |= BitMask; 6741 Imm |= ImmMask; 6742 } else if ((SplatBits & BitMask) != 0) { 6743 return SDValue(); 6744 } 6745 BitMask <<= 8; 6746 ImmMask <<= 1; 6747 } 6748 6749 if (DAG.getDataLayout().isBigEndian()) { 6750 // Reverse the order of elements within the vector. 6751 unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8; 6752 unsigned Mask = (1 << BytesPerElem) - 1; 6753 unsigned NumElems = 8 / BytesPerElem; 6754 unsigned NewImm = 0; 6755 for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) { 6756 unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask); 6757 NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem; 6758 } 6759 Imm = NewImm; 6760 } 6761 6762 // Op=1, Cmode=1110. 6763 OpCmode = 0x1e; 6764 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6765 break; 6766 } 6767 6768 default: 6769 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6770 } 6771 6772 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6773 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6774 } 6775 6776 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6777 const ARMSubtarget *ST) const { 6778 EVT VT = Op.getValueType(); 6779 bool IsDouble = (VT == MVT::f64); 6780 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6781 const APFloat &FPVal = CFP->getValueAPF(); 6782 6783 // Prevent floating-point constants from using literal loads 6784 // when execute-only is enabled. 6785 if (ST->genExecuteOnly()) { 6786 // If we can represent the constant as an immediate, don't lower it 6787 if (isFPImmLegal(FPVal, VT)) 6788 return Op; 6789 // Otherwise, construct as integer, and move to float register 6790 APInt INTVal = FPVal.bitcastToAPInt(); 6791 SDLoc DL(CFP); 6792 switch (VT.getSimpleVT().SimpleTy) { 6793 default: 6794 llvm_unreachable("Unknown floating point type!"); 6795 break; 6796 case MVT::f64: { 6797 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6798 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6799 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6800 } 6801 case MVT::f32: 6802 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6803 DAG.getConstant(INTVal, DL, MVT::i32)); 6804 } 6805 } 6806 6807 if (!ST->hasVFP3Base()) 6808 return SDValue(); 6809 6810 // Use the default (constant pool) lowering for double constants when we have 6811 // an SP-only FPU 6812 if (IsDouble && !Subtarget->hasFP64()) 6813 return SDValue(); 6814 6815 // Try splatting with a VMOV.f32... 6816 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6817 6818 if (ImmVal != -1) { 6819 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6820 // We have code in place to select a valid ConstantFP already, no need to 6821 // do any mangling. 6822 return Op; 6823 } 6824 6825 // It's a float and we are trying to use NEON operations where 6826 // possible. Lower it to a splat followed by an extract. 6827 SDLoc DL(Op); 6828 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6829 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6830 NewVal); 6831 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6832 DAG.getConstant(0, DL, MVT::i32)); 6833 } 6834 6835 // The rest of our options are NEON only, make sure that's allowed before 6836 // proceeding.. 6837 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6838 return SDValue(); 6839 6840 EVT VMovVT; 6841 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6842 6843 // It wouldn't really be worth bothering for doubles except for one very 6844 // important value, which does happen to match: 0.0. So make sure we don't do 6845 // anything stupid. 6846 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6847 return SDValue(); 6848 6849 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6850 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6851 VMovVT, VT, VMOVModImm); 6852 if (NewVal != SDValue()) { 6853 SDLoc DL(Op); 6854 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6855 NewVal); 6856 if (IsDouble) 6857 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6858 6859 // It's a float: cast and extract a vector element. 6860 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6861 VecConstant); 6862 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6863 DAG.getConstant(0, DL, MVT::i32)); 6864 } 6865 6866 // Finally, try a VMVN.i32 6867 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6868 VT, VMVNModImm); 6869 if (NewVal != SDValue()) { 6870 SDLoc DL(Op); 6871 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6872 6873 if (IsDouble) 6874 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6875 6876 // It's a float: cast and extract a vector element. 6877 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6878 VecConstant); 6879 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6880 DAG.getConstant(0, DL, MVT::i32)); 6881 } 6882 6883 return SDValue(); 6884 } 6885 6886 // check if an VEXT instruction can handle the shuffle mask when the 6887 // vector sources of the shuffle are the same. 6888 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6889 unsigned NumElts = VT.getVectorNumElements(); 6890 6891 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6892 if (M[0] < 0) 6893 return false; 6894 6895 Imm = M[0]; 6896 6897 // If this is a VEXT shuffle, the immediate value is the index of the first 6898 // element. The other shuffle indices must be the successive elements after 6899 // the first one. 6900 unsigned ExpectedElt = Imm; 6901 for (unsigned i = 1; i < NumElts; ++i) { 6902 // Increment the expected index. If it wraps around, just follow it 6903 // back to index zero and keep going. 6904 ++ExpectedElt; 6905 if (ExpectedElt == NumElts) 6906 ExpectedElt = 0; 6907 6908 if (M[i] < 0) continue; // ignore UNDEF indices 6909 if (ExpectedElt != static_cast<unsigned>(M[i])) 6910 return false; 6911 } 6912 6913 return true; 6914 } 6915 6916 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6917 bool &ReverseVEXT, unsigned &Imm) { 6918 unsigned NumElts = VT.getVectorNumElements(); 6919 ReverseVEXT = false; 6920 6921 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6922 if (M[0] < 0) 6923 return false; 6924 6925 Imm = M[0]; 6926 6927 // If this is a VEXT shuffle, the immediate value is the index of the first 6928 // element. The other shuffle indices must be the successive elements after 6929 // the first one. 6930 unsigned ExpectedElt = Imm; 6931 for (unsigned i = 1; i < NumElts; ++i) { 6932 // Increment the expected index. If it wraps around, it may still be 6933 // a VEXT but the source vectors must be swapped. 6934 ExpectedElt += 1; 6935 if (ExpectedElt == NumElts * 2) { 6936 ExpectedElt = 0; 6937 ReverseVEXT = true; 6938 } 6939 6940 if (M[i] < 0) continue; // ignore UNDEF indices 6941 if (ExpectedElt != static_cast<unsigned>(M[i])) 6942 return false; 6943 } 6944 6945 // Adjust the index value if the source operands will be swapped. 6946 if (ReverseVEXT) 6947 Imm -= NumElts; 6948 6949 return true; 6950 } 6951 6952 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6953 /// instruction with the specified blocksize. (The order of the elements 6954 /// within each block of the vector is reversed.) 6955 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6956 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6957 "Only possible block sizes for VREV are: 16, 32, 64"); 6958 6959 unsigned EltSz = VT.getScalarSizeInBits(); 6960 if (EltSz == 64) 6961 return false; 6962 6963 unsigned NumElts = VT.getVectorNumElements(); 6964 unsigned BlockElts = M[0] + 1; 6965 // If the first shuffle index is UNDEF, be optimistic. 6966 if (M[0] < 0) 6967 BlockElts = BlockSize / EltSz; 6968 6969 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6970 return false; 6971 6972 for (unsigned i = 0; i < NumElts; ++i) { 6973 if (M[i] < 0) continue; // ignore UNDEF indices 6974 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6975 return false; 6976 } 6977 6978 return true; 6979 } 6980 6981 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6982 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6983 // range, then 0 is placed into the resulting vector. So pretty much any mask 6984 // of 8 elements can work here. 6985 return VT == MVT::v8i8 && M.size() == 8; 6986 } 6987 6988 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6989 unsigned Index) { 6990 if (Mask.size() == Elements * 2) 6991 return Index / Elements; 6992 return Mask[Index] == 0 ? 0 : 1; 6993 } 6994 6995 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6996 // checking that pairs of elements in the shuffle mask represent the same index 6997 // in each vector, incrementing the expected index by 2 at each step. 6998 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6999 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 7000 // v2={e,f,g,h} 7001 // WhichResult gives the offset for each element in the mask based on which 7002 // of the two results it belongs to. 7003 // 7004 // The transpose can be represented either as: 7005 // result1 = shufflevector v1, v2, result1_shuffle_mask 7006 // result2 = shufflevector v1, v2, result2_shuffle_mask 7007 // where v1/v2 and the shuffle masks have the same number of elements 7008 // (here WhichResult (see below) indicates which result is being checked) 7009 // 7010 // or as: 7011 // results = shufflevector v1, v2, shuffle_mask 7012 // where both results are returned in one vector and the shuffle mask has twice 7013 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 7014 // want to check the low half and high half of the shuffle mask as if it were 7015 // the other case 7016 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7017 unsigned EltSz = VT.getScalarSizeInBits(); 7018 if (EltSz == 64) 7019 return false; 7020 7021 unsigned NumElts = VT.getVectorNumElements(); 7022 if (M.size() != NumElts && M.size() != NumElts*2) 7023 return false; 7024 7025 // If the mask is twice as long as the input vector then we need to check the 7026 // upper and lower parts of the mask with a matching value for WhichResult 7027 // FIXME: A mask with only even values will be rejected in case the first 7028 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 7029 // M[0] is used to determine WhichResult 7030 for (unsigned i = 0; i < M.size(); i += NumElts) { 7031 WhichResult = SelectPairHalf(NumElts, M, i); 7032 for (unsigned j = 0; j < NumElts; j += 2) { 7033 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 7034 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 7035 return false; 7036 } 7037 } 7038 7039 if (M.size() == NumElts*2) 7040 WhichResult = 0; 7041 7042 return true; 7043 } 7044 7045 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 7046 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7047 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 7048 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7049 unsigned EltSz = VT.getScalarSizeInBits(); 7050 if (EltSz == 64) 7051 return false; 7052 7053 unsigned NumElts = VT.getVectorNumElements(); 7054 if (M.size() != NumElts && M.size() != NumElts*2) 7055 return false; 7056 7057 for (unsigned i = 0; i < M.size(); i += NumElts) { 7058 WhichResult = SelectPairHalf(NumElts, M, i); 7059 for (unsigned j = 0; j < NumElts; j += 2) { 7060 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 7061 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 7062 return false; 7063 } 7064 } 7065 7066 if (M.size() == NumElts*2) 7067 WhichResult = 0; 7068 7069 return true; 7070 } 7071 7072 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 7073 // that the mask elements are either all even and in steps of size 2 or all odd 7074 // and in steps of size 2. 7075 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 7076 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 7077 // v2={e,f,g,h} 7078 // Requires similar checks to that of isVTRNMask with 7079 // respect the how results are returned. 7080 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7081 unsigned EltSz = VT.getScalarSizeInBits(); 7082 if (EltSz == 64) 7083 return false; 7084 7085 unsigned NumElts = VT.getVectorNumElements(); 7086 if (M.size() != NumElts && M.size() != NumElts*2) 7087 return false; 7088 7089 for (unsigned i = 0; i < M.size(); i += NumElts) { 7090 WhichResult = SelectPairHalf(NumElts, M, i); 7091 for (unsigned j = 0; j < NumElts; ++j) { 7092 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 7093 return false; 7094 } 7095 } 7096 7097 if (M.size() == NumElts*2) 7098 WhichResult = 0; 7099 7100 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7101 if (VT.is64BitVector() && EltSz == 32) 7102 return false; 7103 7104 return true; 7105 } 7106 7107 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 7108 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7109 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 7110 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7111 unsigned EltSz = VT.getScalarSizeInBits(); 7112 if (EltSz == 64) 7113 return false; 7114 7115 unsigned NumElts = VT.getVectorNumElements(); 7116 if (M.size() != NumElts && M.size() != NumElts*2) 7117 return false; 7118 7119 unsigned Half = NumElts / 2; 7120 for (unsigned i = 0; i < M.size(); i += NumElts) { 7121 WhichResult = SelectPairHalf(NumElts, M, i); 7122 for (unsigned j = 0; j < NumElts; j += Half) { 7123 unsigned Idx = WhichResult; 7124 for (unsigned k = 0; k < Half; ++k) { 7125 int MIdx = M[i + j + k]; 7126 if (MIdx >= 0 && (unsigned) MIdx != Idx) 7127 return false; 7128 Idx += 2; 7129 } 7130 } 7131 } 7132 7133 if (M.size() == NumElts*2) 7134 WhichResult = 0; 7135 7136 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7137 if (VT.is64BitVector() && EltSz == 32) 7138 return false; 7139 7140 return true; 7141 } 7142 7143 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 7144 // that pairs of elements of the shufflemask represent the same index in each 7145 // vector incrementing sequentially through the vectors. 7146 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 7147 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 7148 // v2={e,f,g,h} 7149 // Requires similar checks to that of isVTRNMask with respect the how results 7150 // are returned. 7151 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7152 unsigned EltSz = VT.getScalarSizeInBits(); 7153 if (EltSz == 64) 7154 return false; 7155 7156 unsigned NumElts = VT.getVectorNumElements(); 7157 if (M.size() != NumElts && M.size() != NumElts*2) 7158 return false; 7159 7160 for (unsigned i = 0; i < M.size(); i += NumElts) { 7161 WhichResult = SelectPairHalf(NumElts, M, i); 7162 unsigned Idx = WhichResult * NumElts / 2; 7163 for (unsigned j = 0; j < NumElts; j += 2) { 7164 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7165 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 7166 return false; 7167 Idx += 1; 7168 } 7169 } 7170 7171 if (M.size() == NumElts*2) 7172 WhichResult = 0; 7173 7174 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7175 if (VT.is64BitVector() && EltSz == 32) 7176 return false; 7177 7178 return true; 7179 } 7180 7181 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 7182 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7183 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 7184 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7185 unsigned EltSz = VT.getScalarSizeInBits(); 7186 if (EltSz == 64) 7187 return false; 7188 7189 unsigned NumElts = VT.getVectorNumElements(); 7190 if (M.size() != NumElts && M.size() != NumElts*2) 7191 return false; 7192 7193 for (unsigned i = 0; i < M.size(); i += NumElts) { 7194 WhichResult = SelectPairHalf(NumElts, M, i); 7195 unsigned Idx = WhichResult * NumElts / 2; 7196 for (unsigned j = 0; j < NumElts; j += 2) { 7197 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7198 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 7199 return false; 7200 Idx += 1; 7201 } 7202 } 7203 7204 if (M.size() == NumElts*2) 7205 WhichResult = 0; 7206 7207 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7208 if (VT.is64BitVector() && EltSz == 32) 7209 return false; 7210 7211 return true; 7212 } 7213 7214 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 7215 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 7216 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 7217 unsigned &WhichResult, 7218 bool &isV_UNDEF) { 7219 isV_UNDEF = false; 7220 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 7221 return ARMISD::VTRN; 7222 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 7223 return ARMISD::VUZP; 7224 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 7225 return ARMISD::VZIP; 7226 7227 isV_UNDEF = true; 7228 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7229 return ARMISD::VTRN; 7230 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7231 return ARMISD::VUZP; 7232 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7233 return ARMISD::VZIP; 7234 7235 return 0; 7236 } 7237 7238 /// \return true if this is a reverse operation on an vector. 7239 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 7240 unsigned NumElts = VT.getVectorNumElements(); 7241 // Make sure the mask has the right size. 7242 if (NumElts != M.size()) 7243 return false; 7244 7245 // Look for <15, ..., 3, -1, 1, 0>. 7246 for (unsigned i = 0; i != NumElts; ++i) 7247 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 7248 return false; 7249 7250 return true; 7251 } 7252 7253 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) { 7254 unsigned NumElts = VT.getVectorNumElements(); 7255 // Make sure the mask has the right size. 7256 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8)) 7257 return false; 7258 7259 // If Top 7260 // Look for <0, N, 2, N+2, 4, N+4, ..>. 7261 // This inserts Input2 into Input1 7262 // else if not Top 7263 // Look for <0, N+1, 2, N+3, 4, N+5, ..> 7264 // This inserts Input1 into Input2 7265 unsigned Offset = Top ? 0 : 1; 7266 for (unsigned i = 0; i < NumElts; i+=2) { 7267 if (M[i] >= 0 && M[i] != (int)i) 7268 return false; 7269 if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset)) 7270 return false; 7271 } 7272 7273 return true; 7274 } 7275 7276 // Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted 7277 // from a pair of inputs. For example: 7278 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0), 7279 // FP_ROUND(EXTRACT_ELT(Y, 0), 7280 // FP_ROUND(EXTRACT_ELT(X, 1), 7281 // FP_ROUND(EXTRACT_ELT(Y, 1), ...) 7282 static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG, 7283 const ARMSubtarget *ST) { 7284 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7285 if (!ST->hasMVEFloatOps()) 7286 return SDValue(); 7287 7288 SDLoc dl(BV); 7289 EVT VT = BV.getValueType(); 7290 if (VT != MVT::v8f16) 7291 return SDValue(); 7292 7293 // We are looking for a buildvector of fptrunc elements, where all the 7294 // elements are interleavingly extracted from two sources. Check the first two 7295 // items are valid enough and extract some info from them (they are checked 7296 // properly in the loop below). 7297 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND || 7298 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7299 BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0) 7300 return SDValue(); 7301 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND || 7302 BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7303 BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0) 7304 return SDValue(); 7305 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0); 7306 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0); 7307 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32) 7308 return SDValue(); 7309 7310 // Check all the values in the BuildVector line up with our expectations. 7311 for (unsigned i = 1; i < 4; i++) { 7312 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) { 7313 return Trunc.getOpcode() == ISD::FP_ROUND && 7314 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7315 Trunc.getOperand(0).getOperand(0) == Op && 7316 Trunc.getOperand(0).getConstantOperandVal(1) == Idx; 7317 }; 7318 if (!Check(BV.getOperand(i * 2 + 0), Op0, i)) 7319 return SDValue(); 7320 if (!Check(BV.getOperand(i * 2 + 1), Op1, i)) 7321 return SDValue(); 7322 } 7323 7324 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0, 7325 DAG.getConstant(0, dl, MVT::i32)); 7326 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1, 7327 DAG.getConstant(1, dl, MVT::i32)); 7328 } 7329 7330 // Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted 7331 // from a single input on alternating lanes. For example: 7332 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0), 7333 // FP_ROUND(EXTRACT_ELT(X, 2), 7334 // FP_ROUND(EXTRACT_ELT(X, 4), ...) 7335 static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG, 7336 const ARMSubtarget *ST) { 7337 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7338 if (!ST->hasMVEFloatOps()) 7339 return SDValue(); 7340 7341 SDLoc dl(BV); 7342 EVT VT = BV.getValueType(); 7343 if (VT != MVT::v4f32) 7344 return SDValue(); 7345 7346 // We are looking for a buildvector of fptext elements, where all the 7347 // elements are alternating lanes from a single source. For example <0,2,4,6> 7348 // or <1,3,5,7>. Check the first two items are valid enough and extract some 7349 // info from them (they are checked properly in the loop below). 7350 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND || 7351 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT) 7352 return SDValue(); 7353 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0); 7354 int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1); 7355 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1)) 7356 return SDValue(); 7357 7358 // Check all the values in the BuildVector line up with our expectations. 7359 for (unsigned i = 1; i < 4; i++) { 7360 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) { 7361 return Trunc.getOpcode() == ISD::FP_EXTEND && 7362 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7363 Trunc.getOperand(0).getOperand(0) == Op && 7364 Trunc.getOperand(0).getConstantOperandVal(1) == Idx; 7365 }; 7366 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset)) 7367 return SDValue(); 7368 } 7369 7370 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0, 7371 DAG.getConstant(Offset, dl, MVT::i32)); 7372 } 7373 7374 // If N is an integer constant that can be moved into a register in one 7375 // instruction, return an SDValue of such a constant (will become a MOV 7376 // instruction). Otherwise return null. 7377 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 7378 const ARMSubtarget *ST, const SDLoc &dl) { 7379 uint64_t Val; 7380 if (!isa<ConstantSDNode>(N)) 7381 return SDValue(); 7382 Val = cast<ConstantSDNode>(N)->getZExtValue(); 7383 7384 if (ST->isThumb1Only()) { 7385 if (Val <= 255 || ~Val <= 255) 7386 return DAG.getConstant(Val, dl, MVT::i32); 7387 } else { 7388 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 7389 return DAG.getConstant(Val, dl, MVT::i32); 7390 } 7391 return SDValue(); 7392 } 7393 7394 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 7395 const ARMSubtarget *ST) { 7396 SDLoc dl(Op); 7397 EVT VT = Op.getValueType(); 7398 7399 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 7400 7401 unsigned NumElts = VT.getVectorNumElements(); 7402 unsigned BoolMask; 7403 unsigned BitsPerBool; 7404 if (NumElts == 4) { 7405 BitsPerBool = 4; 7406 BoolMask = 0xf; 7407 } else if (NumElts == 8) { 7408 BitsPerBool = 2; 7409 BoolMask = 0x3; 7410 } else if (NumElts == 16) { 7411 BitsPerBool = 1; 7412 BoolMask = 0x1; 7413 } else 7414 return SDValue(); 7415 7416 // If this is a single value copied into all lanes (a splat), we can just sign 7417 // extend that single value 7418 SDValue FirstOp = Op.getOperand(0); 7419 if (!isa<ConstantSDNode>(FirstOp) && 7420 std::all_of(std::next(Op->op_begin()), Op->op_end(), 7421 [&FirstOp](SDUse &U) { 7422 return U.get().isUndef() || U.get() == FirstOp; 7423 })) { 7424 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp, 7425 DAG.getValueType(MVT::i1)); 7426 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext); 7427 } 7428 7429 // First create base with bits set where known 7430 unsigned Bits32 = 0; 7431 for (unsigned i = 0; i < NumElts; ++i) { 7432 SDValue V = Op.getOperand(i); 7433 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 7434 continue; 7435 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 7436 if (BitSet) 7437 Bits32 |= BoolMask << (i * BitsPerBool); 7438 } 7439 7440 // Add in unknown nodes 7441 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 7442 DAG.getConstant(Bits32, dl, MVT::i32)); 7443 for (unsigned i = 0; i < NumElts; ++i) { 7444 SDValue V = Op.getOperand(i); 7445 if (isa<ConstantSDNode>(V) || V.isUndef()) 7446 continue; 7447 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 7448 DAG.getConstant(i, dl, MVT::i32)); 7449 } 7450 7451 return Base; 7452 } 7453 7454 // If this is a case we can't handle, return null and let the default 7455 // expansion code take care of it. 7456 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 7457 const ARMSubtarget *ST) const { 7458 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7459 SDLoc dl(Op); 7460 EVT VT = Op.getValueType(); 7461 7462 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7463 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 7464 7465 APInt SplatBits, SplatUndef; 7466 unsigned SplatBitSize; 7467 bool HasAnyUndefs; 7468 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7469 if (SplatUndef.isAllOnesValue()) 7470 return DAG.getUNDEF(VT); 7471 7472 if ((ST->hasNEON() && SplatBitSize <= 64) || 7473 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) { 7474 // Check if an immediate VMOV works. 7475 EVT VmovVT; 7476 SDValue Val = 7477 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 7478 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm); 7479 7480 if (Val.getNode()) { 7481 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 7482 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7483 } 7484 7485 // Try an immediate VMVN. 7486 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 7487 Val = isVMOVModifiedImm( 7488 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT, 7489 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 7490 if (Val.getNode()) { 7491 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 7492 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7493 } 7494 7495 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 7496 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 7497 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 7498 if (ImmVal != -1) { 7499 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 7500 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 7501 } 7502 } 7503 } 7504 } 7505 7506 // Scan through the operands to see if only one value is used. 7507 // 7508 // As an optimisation, even if more than one value is used it may be more 7509 // profitable to splat with one value then change some lanes. 7510 // 7511 // Heuristically we decide to do this if the vector has a "dominant" value, 7512 // defined as splatted to more than half of the lanes. 7513 unsigned NumElts = VT.getVectorNumElements(); 7514 bool isOnlyLowElement = true; 7515 bool usesOnlyOneValue = true; 7516 bool hasDominantValue = false; 7517 bool isConstant = true; 7518 7519 // Map of the number of times a particular SDValue appears in the 7520 // element list. 7521 DenseMap<SDValue, unsigned> ValueCounts; 7522 SDValue Value; 7523 for (unsigned i = 0; i < NumElts; ++i) { 7524 SDValue V = Op.getOperand(i); 7525 if (V.isUndef()) 7526 continue; 7527 if (i > 0) 7528 isOnlyLowElement = false; 7529 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 7530 isConstant = false; 7531 7532 ValueCounts.insert(std::make_pair(V, 0)); 7533 unsigned &Count = ValueCounts[V]; 7534 7535 // Is this value dominant? (takes up more than half of the lanes) 7536 if (++Count > (NumElts / 2)) { 7537 hasDominantValue = true; 7538 Value = V; 7539 } 7540 } 7541 if (ValueCounts.size() != 1) 7542 usesOnlyOneValue = false; 7543 if (!Value.getNode() && !ValueCounts.empty()) 7544 Value = ValueCounts.begin()->first; 7545 7546 if (ValueCounts.empty()) 7547 return DAG.getUNDEF(VT); 7548 7549 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 7550 // Keep going if we are hitting this case. 7551 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 7552 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7553 7554 unsigned EltSize = VT.getScalarSizeInBits(); 7555 7556 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 7557 // i32 and try again. 7558 if (hasDominantValue && EltSize <= 32) { 7559 if (!isConstant) { 7560 SDValue N; 7561 7562 // If we are VDUPing a value that comes directly from a vector, that will 7563 // cause an unnecessary move to and from a GPR, where instead we could 7564 // just use VDUPLANE. We can only do this if the lane being extracted 7565 // is at a constant index, as the VDUP from lane instructions only have 7566 // constant-index forms. 7567 ConstantSDNode *constIndex; 7568 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7569 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 7570 // We need to create a new undef vector to use for the VDUPLANE if the 7571 // size of the vector from which we get the value is different than the 7572 // size of the vector that we need to create. We will insert the element 7573 // such that the register coalescer will remove unnecessary copies. 7574 if (VT != Value->getOperand(0).getValueType()) { 7575 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 7576 VT.getVectorNumElements(); 7577 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7578 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 7579 Value, DAG.getConstant(index, dl, MVT::i32)), 7580 DAG.getConstant(index, dl, MVT::i32)); 7581 } else 7582 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7583 Value->getOperand(0), Value->getOperand(1)); 7584 } else 7585 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 7586 7587 if (!usesOnlyOneValue) { 7588 // The dominant value was splatted as 'N', but we now have to insert 7589 // all differing elements. 7590 for (unsigned I = 0; I < NumElts; ++I) { 7591 if (Op.getOperand(I) == Value) 7592 continue; 7593 SmallVector<SDValue, 3> Ops; 7594 Ops.push_back(N); 7595 Ops.push_back(Op.getOperand(I)); 7596 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 7597 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 7598 } 7599 } 7600 return N; 7601 } 7602 if (VT.getVectorElementType().isFloatingPoint()) { 7603 SmallVector<SDValue, 8> Ops; 7604 MVT FVT = VT.getVectorElementType().getSimpleVT(); 7605 assert(FVT == MVT::f32 || FVT == MVT::f16); 7606 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 7607 for (unsigned i = 0; i < NumElts; ++i) 7608 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 7609 Op.getOperand(i))); 7610 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 7611 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7612 Val = LowerBUILD_VECTOR(Val, DAG, ST); 7613 if (Val.getNode()) 7614 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7615 } 7616 if (usesOnlyOneValue) { 7617 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 7618 if (isConstant && Val.getNode()) 7619 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 7620 } 7621 } 7622 7623 // If all elements are constants and the case above didn't get hit, fall back 7624 // to the default expansion, which will generate a load from the constant 7625 // pool. 7626 if (isConstant) 7627 return SDValue(); 7628 7629 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and 7630 // vmovn). Empirical tests suggest this is rarely worth it for vectors of 7631 // length <= 2. 7632 if (NumElts >= 4) 7633 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 7634 return shuffle; 7635 7636 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into 7637 // VCVT's 7638 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget)) 7639 return VCVT; 7640 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget)) 7641 return VCVT; 7642 7643 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7644 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7645 // into two 64-bit vectors; we might discover a better way to lower it. 7646 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7647 EVT ExtVT = VT.getVectorElementType(); 7648 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7649 SDValue Lower = 7650 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7651 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7652 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7653 SDValue Upper = DAG.getBuildVector( 7654 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7655 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7656 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7657 if (Lower && Upper) 7658 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7659 } 7660 7661 // Vectors with 32- or 64-bit elements can be built by directly assigning 7662 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7663 // will be legalized. 7664 if (EltSize >= 32) { 7665 // Do the expansion with floating-point types, since that is what the VFP 7666 // registers are defined to use, and since i64 is not legal. 7667 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7668 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7669 SmallVector<SDValue, 8> Ops; 7670 for (unsigned i = 0; i < NumElts; ++i) 7671 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7672 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7673 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7674 } 7675 7676 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7677 // know the default expansion would otherwise fall back on something even 7678 // worse. For a vector with one or two non-undef values, that's 7679 // scalar_to_vector for the elements followed by a shuffle (provided the 7680 // shuffle is valid for the target) and materialization element by element 7681 // on the stack followed by a load for everything else. 7682 if (!isConstant && !usesOnlyOneValue) { 7683 SDValue Vec = DAG.getUNDEF(VT); 7684 for (unsigned i = 0 ; i < NumElts; ++i) { 7685 SDValue V = Op.getOperand(i); 7686 if (V.isUndef()) 7687 continue; 7688 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7689 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7690 } 7691 return Vec; 7692 } 7693 7694 return SDValue(); 7695 } 7696 7697 // Gather data to see if the operation can be modelled as a 7698 // shuffle in combination with VEXTs. 7699 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7700 SelectionDAG &DAG) const { 7701 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7702 SDLoc dl(Op); 7703 EVT VT = Op.getValueType(); 7704 unsigned NumElts = VT.getVectorNumElements(); 7705 7706 struct ShuffleSourceInfo { 7707 SDValue Vec; 7708 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7709 unsigned MaxElt = 0; 7710 7711 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7712 // be compatible with the shuffle we intend to construct. As a result 7713 // ShuffleVec will be some sliding window into the original Vec. 7714 SDValue ShuffleVec; 7715 7716 // Code should guarantee that element i in Vec starts at element "WindowBase 7717 // + i * WindowScale in ShuffleVec". 7718 int WindowBase = 0; 7719 int WindowScale = 1; 7720 7721 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7722 7723 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7724 }; 7725 7726 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7727 // node. 7728 SmallVector<ShuffleSourceInfo, 2> Sources; 7729 for (unsigned i = 0; i < NumElts; ++i) { 7730 SDValue V = Op.getOperand(i); 7731 if (V.isUndef()) 7732 continue; 7733 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7734 // A shuffle can only come from building a vector from various 7735 // elements of other vectors. 7736 return SDValue(); 7737 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7738 // Furthermore, shuffles require a constant mask, whereas extractelts 7739 // accept variable indices. 7740 return SDValue(); 7741 } 7742 7743 // Add this element source to the list if it's not already there. 7744 SDValue SourceVec = V.getOperand(0); 7745 auto Source = llvm::find(Sources, SourceVec); 7746 if (Source == Sources.end()) 7747 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7748 7749 // Update the minimum and maximum lane number seen. 7750 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7751 Source->MinElt = std::min(Source->MinElt, EltNo); 7752 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7753 } 7754 7755 // Currently only do something sane when at most two source vectors 7756 // are involved. 7757 if (Sources.size() > 2) 7758 return SDValue(); 7759 7760 // Find out the smallest element size among result and two sources, and use 7761 // it as element size to build the shuffle_vector. 7762 EVT SmallestEltTy = VT.getVectorElementType(); 7763 for (auto &Source : Sources) { 7764 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7765 if (SrcEltTy.bitsLT(SmallestEltTy)) 7766 SmallestEltTy = SrcEltTy; 7767 } 7768 unsigned ResMultiplier = 7769 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7770 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7771 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7772 7773 // If the source vector is too wide or too narrow, we may nevertheless be able 7774 // to construct a compatible shuffle either by concatenating it with UNDEF or 7775 // extracting a suitable range of elements. 7776 for (auto &Src : Sources) { 7777 EVT SrcVT = Src.ShuffleVec.getValueType(); 7778 7779 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 7780 continue; 7781 7782 // This stage of the search produces a source with the same element type as 7783 // the original, but with a total width matching the BUILD_VECTOR output. 7784 EVT EltVT = SrcVT.getVectorElementType(); 7785 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 7786 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7787 7788 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 7789 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 7790 return SDValue(); 7791 // We can pad out the smaller vector for free, so if it's part of a 7792 // shuffle... 7793 Src.ShuffleVec = 7794 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7795 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7796 continue; 7797 } 7798 7799 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 7800 return SDValue(); 7801 7802 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7803 // Span too large for a VEXT to cope 7804 return SDValue(); 7805 } 7806 7807 if (Src.MinElt >= NumSrcElts) { 7808 // The extraction can just take the second half 7809 Src.ShuffleVec = 7810 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7811 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7812 Src.WindowBase = -NumSrcElts; 7813 } else if (Src.MaxElt < NumSrcElts) { 7814 // The extraction can just take the first half 7815 Src.ShuffleVec = 7816 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7817 DAG.getConstant(0, dl, MVT::i32)); 7818 } else { 7819 // An actual VEXT is needed 7820 SDValue VEXTSrc1 = 7821 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7822 DAG.getConstant(0, dl, MVT::i32)); 7823 SDValue VEXTSrc2 = 7824 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7825 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7826 7827 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7828 VEXTSrc2, 7829 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7830 Src.WindowBase = -Src.MinElt; 7831 } 7832 } 7833 7834 // Another possible incompatibility occurs from the vector element types. We 7835 // can fix this by bitcasting the source vectors to the same type we intend 7836 // for the shuffle. 7837 for (auto &Src : Sources) { 7838 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7839 if (SrcEltTy == SmallestEltTy) 7840 continue; 7841 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7842 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec); 7843 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7844 Src.WindowBase *= Src.WindowScale; 7845 } 7846 7847 // Final sanity check before we try to actually produce a shuffle. 7848 LLVM_DEBUG(for (auto Src 7849 : Sources) 7850 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7851 7852 // The stars all align, our next step is to produce the mask for the shuffle. 7853 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7854 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7855 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7856 SDValue Entry = Op.getOperand(i); 7857 if (Entry.isUndef()) 7858 continue; 7859 7860 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7861 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7862 7863 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7864 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7865 // segment. 7866 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7867 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 7868 VT.getScalarSizeInBits()); 7869 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7870 7871 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7872 // starting at the appropriate offset. 7873 int *LaneMask = &Mask[i * ResMultiplier]; 7874 7875 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7876 ExtractBase += NumElts * (Src - Sources.begin()); 7877 for (int j = 0; j < LanesDefined; ++j) 7878 LaneMask[j] = ExtractBase + j; 7879 } 7880 7881 7882 // We can't handle more than two sources. This should have already 7883 // been checked before this point. 7884 assert(Sources.size() <= 2 && "Too many sources!"); 7885 7886 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7887 for (unsigned i = 0; i < Sources.size(); ++i) 7888 ShuffleOps[i] = Sources[i].ShuffleVec; 7889 7890 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7891 ShuffleOps[1], Mask, DAG); 7892 if (!Shuffle) 7893 return SDValue(); 7894 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle); 7895 } 7896 7897 enum ShuffleOpCodes { 7898 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7899 OP_VREV, 7900 OP_VDUP0, 7901 OP_VDUP1, 7902 OP_VDUP2, 7903 OP_VDUP3, 7904 OP_VEXT1, 7905 OP_VEXT2, 7906 OP_VEXT3, 7907 OP_VUZPL, // VUZP, left result 7908 OP_VUZPR, // VUZP, right result 7909 OP_VZIPL, // VZIP, left result 7910 OP_VZIPR, // VZIP, right result 7911 OP_VTRNL, // VTRN, left result 7912 OP_VTRNR // VTRN, right result 7913 }; 7914 7915 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7916 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7917 switch (OpNum) { 7918 case OP_COPY: 7919 case OP_VREV: 7920 case OP_VDUP0: 7921 case OP_VDUP1: 7922 case OP_VDUP2: 7923 case OP_VDUP3: 7924 return true; 7925 } 7926 return false; 7927 } 7928 7929 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7930 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7931 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7932 /// are assumed to be legal. 7933 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7934 if (VT.getVectorNumElements() == 4 && 7935 (VT.is128BitVector() || VT.is64BitVector())) { 7936 unsigned PFIndexes[4]; 7937 for (unsigned i = 0; i != 4; ++i) { 7938 if (M[i] < 0) 7939 PFIndexes[i] = 8; 7940 else 7941 PFIndexes[i] = M[i]; 7942 } 7943 7944 // Compute the index in the perfect shuffle table. 7945 unsigned PFTableIndex = 7946 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7947 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7948 unsigned Cost = (PFEntry >> 30); 7949 7950 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7951 return true; 7952 } 7953 7954 bool ReverseVEXT, isV_UNDEF; 7955 unsigned Imm, WhichResult; 7956 7957 unsigned EltSize = VT.getScalarSizeInBits(); 7958 if (EltSize >= 32 || 7959 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7960 ShuffleVectorInst::isIdentityMask(M) || 7961 isVREVMask(M, VT, 64) || 7962 isVREVMask(M, VT, 32) || 7963 isVREVMask(M, VT, 16)) 7964 return true; 7965 else if (Subtarget->hasNEON() && 7966 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7967 isVTBLMask(M, VT) || 7968 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7969 return true; 7970 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7971 isReverseMask(M, VT)) 7972 return true; 7973 else if (Subtarget->hasMVEIntegerOps() && 7974 (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1))) 7975 return true; 7976 else 7977 return false; 7978 } 7979 7980 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7981 /// the specified operations to build the shuffle. 7982 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7983 SDValue RHS, SelectionDAG &DAG, 7984 const SDLoc &dl) { 7985 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7986 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7987 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7988 7989 if (OpNum == OP_COPY) { 7990 if (LHSID == (1*9+2)*9+3) return LHS; 7991 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7992 return RHS; 7993 } 7994 7995 SDValue OpLHS, OpRHS; 7996 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7997 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7998 EVT VT = OpLHS.getValueType(); 7999 8000 switch (OpNum) { 8001 default: llvm_unreachable("Unknown shuffle opcode!"); 8002 case OP_VREV: 8003 // VREV divides the vector in half and swaps within the half. 8004 if (VT.getVectorElementType() == MVT::i32 || 8005 VT.getVectorElementType() == MVT::f32) 8006 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 8007 // vrev <4 x i16> -> VREV32 8008 if (VT.getVectorElementType() == MVT::i16) 8009 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 8010 // vrev <4 x i8> -> VREV16 8011 assert(VT.getVectorElementType() == MVT::i8); 8012 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 8013 case OP_VDUP0: 8014 case OP_VDUP1: 8015 case OP_VDUP2: 8016 case OP_VDUP3: 8017 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 8018 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 8019 case OP_VEXT1: 8020 case OP_VEXT2: 8021 case OP_VEXT3: 8022 return DAG.getNode(ARMISD::VEXT, dl, VT, 8023 OpLHS, OpRHS, 8024 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 8025 case OP_VUZPL: 8026 case OP_VUZPR: 8027 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 8028 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 8029 case OP_VZIPL: 8030 case OP_VZIPR: 8031 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 8032 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 8033 case OP_VTRNL: 8034 case OP_VTRNR: 8035 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 8036 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 8037 } 8038 } 8039 8040 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 8041 ArrayRef<int> ShuffleMask, 8042 SelectionDAG &DAG) { 8043 // Check to see if we can use the VTBL instruction. 8044 SDValue V1 = Op.getOperand(0); 8045 SDValue V2 = Op.getOperand(1); 8046 SDLoc DL(Op); 8047 8048 SmallVector<SDValue, 8> VTBLMask; 8049 for (ArrayRef<int>::iterator 8050 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 8051 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 8052 8053 if (V2.getNode()->isUndef()) 8054 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 8055 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 8056 8057 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 8058 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 8059 } 8060 8061 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 8062 SelectionDAG &DAG) { 8063 SDLoc DL(Op); 8064 SDValue OpLHS = Op.getOperand(0); 8065 EVT VT = OpLHS.getValueType(); 8066 8067 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 8068 "Expect an v8i16/v16i8 type"); 8069 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 8070 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 8071 // extract the first 8 bytes into the top double word and the last 8 bytes 8072 // into the bottom double word. The v8i16 case is similar. 8073 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 8074 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 8075 DAG.getConstant(ExtractNum, DL, MVT::i32)); 8076 } 8077 8078 static EVT getVectorTyFromPredicateVector(EVT VT) { 8079 switch (VT.getSimpleVT().SimpleTy) { 8080 case MVT::v4i1: 8081 return MVT::v4i32; 8082 case MVT::v8i1: 8083 return MVT::v8i16; 8084 case MVT::v16i1: 8085 return MVT::v16i8; 8086 default: 8087 llvm_unreachable("Unexpected vector predicate type"); 8088 } 8089 } 8090 8091 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 8092 SelectionDAG &DAG) { 8093 // Converting from boolean predicates to integers involves creating a vector 8094 // of all ones or all zeroes and selecting the lanes based upon the real 8095 // predicate. 8096 SDValue AllOnes = 8097 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 8098 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 8099 8100 SDValue AllZeroes = 8101 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 8102 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 8103 8104 // Get full vector type from predicate type 8105 EVT NewVT = getVectorTyFromPredicateVector(VT); 8106 8107 SDValue RecastV1; 8108 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 8109 // this to a v16i1. This cannot be done with an ordinary bitcast because the 8110 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 8111 // since we know in hardware the sizes are really the same. 8112 if (VT != MVT::v16i1) 8113 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 8114 else 8115 RecastV1 = Pred; 8116 8117 // Select either all ones or zeroes depending upon the real predicate bits. 8118 SDValue PredAsVector = 8119 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 8120 8121 // Recast our new predicate-as-integer v16i8 vector into something 8122 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 8123 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 8124 } 8125 8126 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 8127 const ARMSubtarget *ST) { 8128 EVT VT = Op.getValueType(); 8129 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8130 ArrayRef<int> ShuffleMask = SVN->getMask(); 8131 8132 assert(ST->hasMVEIntegerOps() && 8133 "No support for vector shuffle of boolean predicates"); 8134 8135 SDValue V1 = Op.getOperand(0); 8136 SDLoc dl(Op); 8137 if (isReverseMask(ShuffleMask, VT)) { 8138 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 8139 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 8140 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 8141 DAG.getConstant(16, dl, MVT::i32)); 8142 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 8143 } 8144 8145 // Until we can come up with optimised cases for every single vector 8146 // shuffle in existence we have chosen the least painful strategy. This is 8147 // to essentially promote the boolean predicate to a 8-bit integer, where 8148 // each predicate represents a byte. Then we fall back on a normal integer 8149 // vector shuffle and convert the result back into a predicate vector. In 8150 // many cases the generated code might be even better than scalar code 8151 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 8152 // fields in a register into 8 other arbitrary 2-bit fields! 8153 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 8154 EVT NewVT = PredAsVector.getValueType(); 8155 8156 // Do the shuffle! 8157 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 8158 DAG.getUNDEF(NewVT), ShuffleMask); 8159 8160 // Now return the result of comparing the shuffled vector with zero, 8161 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8162 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 8163 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8164 } 8165 8166 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op, 8167 ArrayRef<int> ShuffleMask, 8168 SelectionDAG &DAG) { 8169 // Attempt to lower the vector shuffle using as many whole register movs as 8170 // possible. This is useful for types smaller than 32bits, which would 8171 // often otherwise become a series for grp movs. 8172 SDLoc dl(Op); 8173 EVT VT = Op.getValueType(); 8174 if (VT.getScalarSizeInBits() >= 32) 8175 return SDValue(); 8176 8177 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && 8178 "Unexpected vector type"); 8179 int NumElts = VT.getVectorNumElements(); 8180 int QuarterSize = NumElts / 4; 8181 // The four final parts of the vector, as i32's 8182 SDValue Parts[4]; 8183 8184 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not 8185 // <u,u,u,u>), returning the vmov lane index 8186 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) { 8187 // Detect which mov lane this would be from the first non-undef element. 8188 int MovIdx = -1; 8189 for (int i = 0; i < Length; i++) { 8190 if (ShuffleMask[Start + i] >= 0) { 8191 if (ShuffleMask[Start + i] % Length != i) 8192 return -1; 8193 MovIdx = ShuffleMask[Start + i] / Length; 8194 break; 8195 } 8196 } 8197 // If all items are undef, leave this for other combines 8198 if (MovIdx == -1) 8199 return -1; 8200 // Check the remaining values are the correct part of the same mov 8201 for (int i = 1; i < Length; i++) { 8202 if (ShuffleMask[Start + i] >= 0 && 8203 (ShuffleMask[Start + i] / Length != MovIdx || 8204 ShuffleMask[Start + i] % Length != i)) 8205 return -1; 8206 } 8207 return MovIdx; 8208 }; 8209 8210 for (int Part = 0; Part < 4; ++Part) { 8211 // Does this part look like a mov 8212 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize); 8213 if (Elt != -1) { 8214 SDValue Input = Op->getOperand(0); 8215 if (Elt >= 4) { 8216 Input = Op->getOperand(1); 8217 Elt -= 4; 8218 } 8219 SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input); 8220 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast, 8221 DAG.getConstant(Elt, dl, MVT::i32)); 8222 } 8223 } 8224 8225 // Nothing interesting found, just return 8226 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3]) 8227 return SDValue(); 8228 8229 // The other parts need to be built with the old shuffle vector, cast to a 8230 // v4i32 and extract_vector_elts 8231 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) { 8232 SmallVector<int, 16> NewShuffleMask; 8233 for (int Part = 0; Part < 4; ++Part) 8234 for (int i = 0; i < QuarterSize; i++) 8235 NewShuffleMask.push_back( 8236 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]); 8237 SDValue NewShuffle = DAG.getVectorShuffle( 8238 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask); 8239 SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle); 8240 8241 for (int Part = 0; Part < 4; ++Part) 8242 if (!Parts[Part]) 8243 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 8244 BitCast, DAG.getConstant(Part, dl, MVT::i32)); 8245 } 8246 // Build a vector out of the various parts and bitcast it back to the original 8247 // type. 8248 SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts); 8249 return DAG.getBitcast(VT, NewVec); 8250 } 8251 8252 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 8253 const ARMSubtarget *ST) { 8254 SDValue V1 = Op.getOperand(0); 8255 SDValue V2 = Op.getOperand(1); 8256 SDLoc dl(Op); 8257 EVT VT = Op.getValueType(); 8258 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8259 unsigned EltSize = VT.getScalarSizeInBits(); 8260 8261 if (ST->hasMVEIntegerOps() && EltSize == 1) 8262 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 8263 8264 // Convert shuffles that are directly supported on NEON to target-specific 8265 // DAG nodes, instead of keeping them as shuffles and matching them again 8266 // during code selection. This is more efficient and avoids the possibility 8267 // of inconsistencies between legalization and selection. 8268 // FIXME: floating-point vectors should be canonicalized to integer vectors 8269 // of the same time so that they get CSEd properly. 8270 ArrayRef<int> ShuffleMask = SVN->getMask(); 8271 8272 if (EltSize <= 32) { 8273 if (SVN->isSplat()) { 8274 int Lane = SVN->getSplatIndex(); 8275 // If this is undef splat, generate it via "just" vdup, if possible. 8276 if (Lane == -1) Lane = 0; 8277 8278 // Test if V1 is a SCALAR_TO_VECTOR. 8279 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 8280 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8281 } 8282 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 8283 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 8284 // reaches it). 8285 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 8286 !isa<ConstantSDNode>(V1.getOperand(0))) { 8287 bool IsScalarToVector = true; 8288 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 8289 if (!V1.getOperand(i).isUndef()) { 8290 IsScalarToVector = false; 8291 break; 8292 } 8293 if (IsScalarToVector) 8294 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8295 } 8296 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 8297 DAG.getConstant(Lane, dl, MVT::i32)); 8298 } 8299 8300 bool ReverseVEXT = false; 8301 unsigned Imm = 0; 8302 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 8303 if (ReverseVEXT) 8304 std::swap(V1, V2); 8305 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 8306 DAG.getConstant(Imm, dl, MVT::i32)); 8307 } 8308 8309 if (isVREVMask(ShuffleMask, VT, 64)) 8310 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 8311 if (isVREVMask(ShuffleMask, VT, 32)) 8312 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 8313 if (isVREVMask(ShuffleMask, VT, 16)) 8314 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 8315 8316 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 8317 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 8318 DAG.getConstant(Imm, dl, MVT::i32)); 8319 } 8320 8321 // Check for Neon shuffles that modify both input vectors in place. 8322 // If both results are used, i.e., if there are two shuffles with the same 8323 // source operands and with masks corresponding to both results of one of 8324 // these operations, DAG memoization will ensure that a single node is 8325 // used for both shuffles. 8326 unsigned WhichResult = 0; 8327 bool isV_UNDEF = false; 8328 if (ST->hasNEON()) { 8329 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8330 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 8331 if (isV_UNDEF) 8332 V2 = V1; 8333 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 8334 .getValue(WhichResult); 8335 } 8336 } 8337 if (ST->hasMVEIntegerOps()) { 8338 if (isVMOVNMask(ShuffleMask, VT, 0)) 8339 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1, 8340 DAG.getConstant(0, dl, MVT::i32)); 8341 if (isVMOVNMask(ShuffleMask, VT, 1)) 8342 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2, 8343 DAG.getConstant(1, dl, MVT::i32)); 8344 } 8345 8346 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 8347 // shuffles that produce a result larger than their operands with: 8348 // shuffle(concat(v1, undef), concat(v2, undef)) 8349 // -> 8350 // shuffle(concat(v1, v2), undef) 8351 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 8352 // 8353 // This is useful in the general case, but there are special cases where 8354 // native shuffles produce larger results: the two-result ops. 8355 // 8356 // Look through the concat when lowering them: 8357 // shuffle(concat(v1, v2), undef) 8358 // -> 8359 // concat(VZIP(v1, v2):0, :1) 8360 // 8361 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 8362 SDValue SubV1 = V1->getOperand(0); 8363 SDValue SubV2 = V1->getOperand(1); 8364 EVT SubVT = SubV1.getValueType(); 8365 8366 // We expect these to have been canonicalized to -1. 8367 assert(llvm::all_of(ShuffleMask, [&](int i) { 8368 return i < (int)VT.getVectorNumElements(); 8369 }) && "Unexpected shuffle index into UNDEF operand!"); 8370 8371 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8372 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 8373 if (isV_UNDEF) 8374 SubV2 = SubV1; 8375 assert((WhichResult == 0) && 8376 "In-place shuffle of concat can only have one result!"); 8377 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 8378 SubV1, SubV2); 8379 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 8380 Res.getValue(1)); 8381 } 8382 } 8383 } 8384 8385 // If the shuffle is not directly supported and it has 4 elements, use 8386 // the PerfectShuffle-generated table to synthesize it from other shuffles. 8387 unsigned NumElts = VT.getVectorNumElements(); 8388 if (NumElts == 4) { 8389 unsigned PFIndexes[4]; 8390 for (unsigned i = 0; i != 4; ++i) { 8391 if (ShuffleMask[i] < 0) 8392 PFIndexes[i] = 8; 8393 else 8394 PFIndexes[i] = ShuffleMask[i]; 8395 } 8396 8397 // Compute the index in the perfect shuffle table. 8398 unsigned PFTableIndex = 8399 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8400 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8401 unsigned Cost = (PFEntry >> 30); 8402 8403 if (Cost <= 4) { 8404 if (ST->hasNEON()) 8405 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8406 else if (isLegalMVEShuffleOp(PFEntry)) { 8407 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8408 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8409 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 8410 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 8411 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 8412 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8413 } 8414 } 8415 } 8416 8417 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 8418 if (EltSize >= 32) { 8419 // Do the expansion with floating-point types, since that is what the VFP 8420 // registers are defined to use, and since i64 is not legal. 8421 EVT EltVT = EVT::getFloatingPointVT(EltSize); 8422 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 8423 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 8424 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 8425 SmallVector<SDValue, 8> Ops; 8426 for (unsigned i = 0; i < NumElts; ++i) { 8427 if (ShuffleMask[i] < 0) 8428 Ops.push_back(DAG.getUNDEF(EltVT)); 8429 else 8430 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 8431 ShuffleMask[i] < (int)NumElts ? V1 : V2, 8432 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 8433 dl, MVT::i32))); 8434 } 8435 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 8436 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8437 } 8438 8439 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 8440 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 8441 8442 if (ST->hasNEON() && VT == MVT::v8i8) 8443 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 8444 return NewOp; 8445 8446 if (ST->hasMVEIntegerOps()) 8447 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG)) 8448 return NewOp; 8449 8450 return SDValue(); 8451 } 8452 8453 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8454 const ARMSubtarget *ST) { 8455 EVT VecVT = Op.getOperand(0).getValueType(); 8456 SDLoc dl(Op); 8457 8458 assert(ST->hasMVEIntegerOps() && 8459 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8460 8461 SDValue Conv = 8462 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8463 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8464 unsigned LaneWidth = 8465 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8466 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 8467 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 8468 Op.getOperand(1), DAG.getValueType(MVT::i1)); 8469 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 8470 DAG.getConstant(~Mask, dl, MVT::i32)); 8471 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 8472 } 8473 8474 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8475 SelectionDAG &DAG) const { 8476 // INSERT_VECTOR_ELT is legal only for immediate indexes. 8477 SDValue Lane = Op.getOperand(2); 8478 if (!isa<ConstantSDNode>(Lane)) 8479 return SDValue(); 8480 8481 SDValue Elt = Op.getOperand(1); 8482 EVT EltVT = Elt.getValueType(); 8483 8484 if (Subtarget->hasMVEIntegerOps() && 8485 Op.getValueType().getScalarSizeInBits() == 1) 8486 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 8487 8488 if (getTypeAction(*DAG.getContext(), EltVT) == 8489 TargetLowering::TypePromoteFloat) { 8490 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 8491 // but the type system will try to do that if we don't intervene. 8492 // Reinterpret any such vector-element insertion as one with the 8493 // corresponding integer types. 8494 8495 SDLoc dl(Op); 8496 8497 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 8498 assert(getTypeAction(*DAG.getContext(), IEltVT) != 8499 TargetLowering::TypePromoteFloat); 8500 8501 SDValue VecIn = Op.getOperand(0); 8502 EVT VecVT = VecIn.getValueType(); 8503 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 8504 VecVT.getVectorNumElements()); 8505 8506 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 8507 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 8508 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 8509 IVecIn, IElt, Lane); 8510 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 8511 } 8512 8513 return Op; 8514 } 8515 8516 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8517 const ARMSubtarget *ST) { 8518 EVT VecVT = Op.getOperand(0).getValueType(); 8519 SDLoc dl(Op); 8520 8521 assert(ST->hasMVEIntegerOps() && 8522 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8523 8524 SDValue Conv = 8525 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8526 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8527 unsigned LaneWidth = 8528 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8529 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 8530 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 8531 return Shift; 8532 } 8533 8534 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 8535 const ARMSubtarget *ST) { 8536 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 8537 SDValue Lane = Op.getOperand(1); 8538 if (!isa<ConstantSDNode>(Lane)) 8539 return SDValue(); 8540 8541 SDValue Vec = Op.getOperand(0); 8542 EVT VT = Vec.getValueType(); 8543 8544 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8545 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 8546 8547 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 8548 SDLoc dl(Op); 8549 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 8550 } 8551 8552 return Op; 8553 } 8554 8555 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 8556 const ARMSubtarget *ST) { 8557 SDValue V1 = Op.getOperand(0); 8558 SDValue V2 = Op.getOperand(1); 8559 SDLoc dl(Op); 8560 EVT VT = Op.getValueType(); 8561 EVT Op1VT = V1.getValueType(); 8562 EVT Op2VT = V2.getValueType(); 8563 unsigned NumElts = VT.getVectorNumElements(); 8564 8565 assert(Op1VT == Op2VT && "Operand types don't match!"); 8566 assert(VT.getScalarSizeInBits() == 1 && 8567 "Unexpected custom CONCAT_VECTORS lowering"); 8568 assert(ST->hasMVEIntegerOps() && 8569 "CONCAT_VECTORS lowering only supported for MVE"); 8570 8571 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8572 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 8573 8574 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 8575 // promoted to v8i16, etc. 8576 8577 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8578 8579 // Extract the vector elements from Op1 and Op2 one by one and truncate them 8580 // to be the right size for the destination. For example, if Op1 is v4i1 then 8581 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 8582 // which when promoted is v8i16. That means each i32 element from Op1 needs 8583 // truncating to i16 and inserting in the result. 8584 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 8585 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 8586 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 8587 EVT NewVT = NewV.getValueType(); 8588 EVT ConcatVT = ConVec.getValueType(); 8589 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 8590 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 8591 DAG.getIntPtrConstant(i, dl)); 8592 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 8593 DAG.getConstant(j, dl, MVT::i32)); 8594 } 8595 return ConVec; 8596 }; 8597 unsigned j = 0; 8598 ConVec = ExractInto(NewV1, ConVec, j); 8599 ConVec = ExractInto(NewV2, ConVec, j); 8600 8601 // Now return the result of comparing the subvector with zero, 8602 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8603 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 8604 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8605 } 8606 8607 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 8608 const ARMSubtarget *ST) { 8609 EVT VT = Op->getValueType(0); 8610 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8611 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 8612 8613 // The only time a CONCAT_VECTORS operation can have legal types is when 8614 // two 64-bit vectors are concatenated to a 128-bit vector. 8615 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 8616 "unexpected CONCAT_VECTORS"); 8617 SDLoc dl(Op); 8618 SDValue Val = DAG.getUNDEF(MVT::v2f64); 8619 SDValue Op0 = Op.getOperand(0); 8620 SDValue Op1 = Op.getOperand(1); 8621 if (!Op0.isUndef()) 8622 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8623 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 8624 DAG.getIntPtrConstant(0, dl)); 8625 if (!Op1.isUndef()) 8626 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8627 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 8628 DAG.getIntPtrConstant(1, dl)); 8629 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 8630 } 8631 8632 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 8633 const ARMSubtarget *ST) { 8634 SDValue V1 = Op.getOperand(0); 8635 SDValue V2 = Op.getOperand(1); 8636 SDLoc dl(Op); 8637 EVT VT = Op.getValueType(); 8638 EVT Op1VT = V1.getValueType(); 8639 unsigned NumElts = VT.getVectorNumElements(); 8640 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 8641 8642 assert(VT.getScalarSizeInBits() == 1 && 8643 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 8644 assert(ST->hasMVEIntegerOps() && 8645 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 8646 8647 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8648 8649 // We now have Op1 promoted to a vector of integers, where v8i1 gets 8650 // promoted to v8i16, etc. 8651 8652 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8653 8654 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 8655 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 8656 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 8657 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 8658 DAG.getIntPtrConstant(i, dl)); 8659 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 8660 DAG.getConstant(j, dl, MVT::i32)); 8661 } 8662 8663 // Now return the result of comparing the subvector with zero, 8664 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8665 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 8666 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8667 } 8668 8669 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 8670 /// element has been zero/sign-extended, depending on the isSigned parameter, 8671 /// from an integer type half its size. 8672 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 8673 bool isSigned) { 8674 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 8675 EVT VT = N->getValueType(0); 8676 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 8677 SDNode *BVN = N->getOperand(0).getNode(); 8678 if (BVN->getValueType(0) != MVT::v4i32 || 8679 BVN->getOpcode() != ISD::BUILD_VECTOR) 8680 return false; 8681 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8682 unsigned HiElt = 1 - LoElt; 8683 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 8684 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 8685 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 8686 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 8687 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 8688 return false; 8689 if (isSigned) { 8690 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 8691 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 8692 return true; 8693 } else { 8694 if (Hi0->isNullValue() && Hi1->isNullValue()) 8695 return true; 8696 } 8697 return false; 8698 } 8699 8700 if (N->getOpcode() != ISD::BUILD_VECTOR) 8701 return false; 8702 8703 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 8704 SDNode *Elt = N->getOperand(i).getNode(); 8705 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 8706 unsigned EltSize = VT.getScalarSizeInBits(); 8707 unsigned HalfSize = EltSize / 2; 8708 if (isSigned) { 8709 if (!isIntN(HalfSize, C->getSExtValue())) 8710 return false; 8711 } else { 8712 if (!isUIntN(HalfSize, C->getZExtValue())) 8713 return false; 8714 } 8715 continue; 8716 } 8717 return false; 8718 } 8719 8720 return true; 8721 } 8722 8723 /// isSignExtended - Check if a node is a vector value that is sign-extended 8724 /// or a constant BUILD_VECTOR with sign-extended elements. 8725 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 8726 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 8727 return true; 8728 if (isExtendedBUILD_VECTOR(N, DAG, true)) 8729 return true; 8730 return false; 8731 } 8732 8733 /// isZeroExtended - Check if a node is a vector value that is zero-extended 8734 /// or a constant BUILD_VECTOR with zero-extended elements. 8735 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8736 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 8737 return true; 8738 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8739 return true; 8740 return false; 8741 } 8742 8743 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8744 if (OrigVT.getSizeInBits() >= 64) 8745 return OrigVT; 8746 8747 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8748 8749 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8750 switch (OrigSimpleTy) { 8751 default: llvm_unreachable("Unexpected Vector Type"); 8752 case MVT::v2i8: 8753 case MVT::v2i16: 8754 return MVT::v2i32; 8755 case MVT::v4i8: 8756 return MVT::v4i16; 8757 } 8758 } 8759 8760 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8761 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8762 /// We insert the required extension here to get the vector to fill a D register. 8763 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8764 const EVT &OrigTy, 8765 const EVT &ExtTy, 8766 unsigned ExtOpcode) { 8767 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8768 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8769 // 64-bits we need to insert a new extension so that it will be 64-bits. 8770 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8771 if (OrigTy.getSizeInBits() >= 64) 8772 return N; 8773 8774 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8775 EVT NewVT = getExtensionTo64Bits(OrigTy); 8776 8777 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8778 } 8779 8780 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8781 /// does not do any sign/zero extension. If the original vector is less 8782 /// than 64 bits, an appropriate extension will be added after the load to 8783 /// reach a total size of 64 bits. We have to add the extension separately 8784 /// because ARM does not have a sign/zero extending load for vectors. 8785 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8786 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8787 8788 // The load already has the right type. 8789 if (ExtendedTy == LD->getMemoryVT()) 8790 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8791 LD->getBasePtr(), LD->getPointerInfo(), 8792 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8793 8794 // We need to create a zextload/sextload. We cannot just create a load 8795 // followed by a zext/zext node because LowerMUL is also run during normal 8796 // operation legalization where we can't create illegal types. 8797 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8798 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8799 LD->getMemoryVT(), LD->getAlignment(), 8800 LD->getMemOperand()->getFlags()); 8801 } 8802 8803 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8804 /// extending load, or BUILD_VECTOR with extended elements, return the 8805 /// unextended value. The unextended vector should be 64 bits so that it can 8806 /// be used as an operand to a VMULL instruction. If the original vector size 8807 /// before extension is less than 64 bits we add a an extension to resize 8808 /// the vector to 64 bits. 8809 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8810 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 8811 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8812 N->getOperand(0)->getValueType(0), 8813 N->getValueType(0), 8814 N->getOpcode()); 8815 8816 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8817 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8818 "Expected extending load"); 8819 8820 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8821 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8822 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8823 SDValue extLoad = 8824 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8825 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8826 8827 return newLoad; 8828 } 8829 8830 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8831 // have been legalized as a BITCAST from v4i32. 8832 if (N->getOpcode() == ISD::BITCAST) { 8833 SDNode *BVN = N->getOperand(0).getNode(); 8834 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8835 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8836 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8837 return DAG.getBuildVector( 8838 MVT::v2i32, SDLoc(N), 8839 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8840 } 8841 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8842 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8843 EVT VT = N->getValueType(0); 8844 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8845 unsigned NumElts = VT.getVectorNumElements(); 8846 MVT TruncVT = MVT::getIntegerVT(EltSize); 8847 SmallVector<SDValue, 8> Ops; 8848 SDLoc dl(N); 8849 for (unsigned i = 0; i != NumElts; ++i) { 8850 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8851 const APInt &CInt = C->getAPIntValue(); 8852 // Element types smaller than 32 bits are not legal, so use i32 elements. 8853 // The values are implicitly truncated so sext vs. zext doesn't matter. 8854 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8855 } 8856 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8857 } 8858 8859 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8860 unsigned Opcode = N->getOpcode(); 8861 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8862 SDNode *N0 = N->getOperand(0).getNode(); 8863 SDNode *N1 = N->getOperand(1).getNode(); 8864 return N0->hasOneUse() && N1->hasOneUse() && 8865 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8866 } 8867 return false; 8868 } 8869 8870 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8871 unsigned Opcode = N->getOpcode(); 8872 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8873 SDNode *N0 = N->getOperand(0).getNode(); 8874 SDNode *N1 = N->getOperand(1).getNode(); 8875 return N0->hasOneUse() && N1->hasOneUse() && 8876 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8877 } 8878 return false; 8879 } 8880 8881 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8882 // Multiplications are only custom-lowered for 128-bit vectors so that 8883 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8884 EVT VT = Op.getValueType(); 8885 assert(VT.is128BitVector() && VT.isInteger() && 8886 "unexpected type for custom-lowering ISD::MUL"); 8887 SDNode *N0 = Op.getOperand(0).getNode(); 8888 SDNode *N1 = Op.getOperand(1).getNode(); 8889 unsigned NewOpc = 0; 8890 bool isMLA = false; 8891 bool isN0SExt = isSignExtended(N0, DAG); 8892 bool isN1SExt = isSignExtended(N1, DAG); 8893 if (isN0SExt && isN1SExt) 8894 NewOpc = ARMISD::VMULLs; 8895 else { 8896 bool isN0ZExt = isZeroExtended(N0, DAG); 8897 bool isN1ZExt = isZeroExtended(N1, DAG); 8898 if (isN0ZExt && isN1ZExt) 8899 NewOpc = ARMISD::VMULLu; 8900 else if (isN1SExt || isN1ZExt) { 8901 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8902 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8903 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8904 NewOpc = ARMISD::VMULLs; 8905 isMLA = true; 8906 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8907 NewOpc = ARMISD::VMULLu; 8908 isMLA = true; 8909 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8910 std::swap(N0, N1); 8911 NewOpc = ARMISD::VMULLu; 8912 isMLA = true; 8913 } 8914 } 8915 8916 if (!NewOpc) { 8917 if (VT == MVT::v2i64) 8918 // Fall through to expand this. It is not legal. 8919 return SDValue(); 8920 else 8921 // Other vector multiplications are legal. 8922 return Op; 8923 } 8924 } 8925 8926 // Legalize to a VMULL instruction. 8927 SDLoc DL(Op); 8928 SDValue Op0; 8929 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8930 if (!isMLA) { 8931 Op0 = SkipExtensionForVMULL(N0, DAG); 8932 assert(Op0.getValueType().is64BitVector() && 8933 Op1.getValueType().is64BitVector() && 8934 "unexpected types for extended operands to VMULL"); 8935 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8936 } 8937 8938 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8939 // isel lowering to take advantage of no-stall back to back vmul + vmla. 8940 // vmull q0, d4, d6 8941 // vmlal q0, d5, d6 8942 // is faster than 8943 // vaddl q0, d4, d5 8944 // vmovl q1, d6 8945 // vmul q0, q0, q1 8946 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 8947 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 8948 EVT Op1VT = Op1.getValueType(); 8949 return DAG.getNode(N0->getOpcode(), DL, VT, 8950 DAG.getNode(NewOpc, DL, VT, 8951 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 8952 DAG.getNode(NewOpc, DL, VT, 8953 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 8954 } 8955 8956 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 8957 SelectionDAG &DAG) { 8958 // TODO: Should this propagate fast-math-flags? 8959 8960 // Convert to float 8961 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 8962 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 8963 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 8964 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 8965 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 8966 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 8967 // Get reciprocal estimate. 8968 // float4 recip = vrecpeq_f32(yf); 8969 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8970 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8971 Y); 8972 // Because char has a smaller range than uchar, we can actually get away 8973 // without any newton steps. This requires that we use a weird bias 8974 // of 0xb000, however (again, this has been exhaustively tested). 8975 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 8976 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 8977 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 8978 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 8979 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 8980 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 8981 // Convert back to short. 8982 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 8983 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 8984 return X; 8985 } 8986 8987 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 8988 SelectionDAG &DAG) { 8989 // TODO: Should this propagate fast-math-flags? 8990 8991 SDValue N2; 8992 // Convert to float. 8993 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 8994 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 8995 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 8996 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 8997 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8998 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8999 9000 // Use reciprocal estimate and one refinement step. 9001 // float4 recip = vrecpeq_f32(yf); 9002 // recip *= vrecpsq_f32(yf, recip); 9003 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9004 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 9005 N1); 9006 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9007 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9008 N1, N2); 9009 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9010 // Because short has a smaller range than ushort, we can actually get away 9011 // with only a single newton step. This requires that we use a weird bias 9012 // of 89, however (again, this has been exhaustively tested). 9013 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 9014 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 9015 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 9016 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 9017 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 9018 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 9019 // Convert back to integer and return. 9020 // return vmovn_s32(vcvt_s32_f32(result)); 9021 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 9022 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 9023 return N0; 9024 } 9025 9026 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 9027 const ARMSubtarget *ST) { 9028 EVT VT = Op.getValueType(); 9029 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 9030 "unexpected type for custom-lowering ISD::SDIV"); 9031 9032 SDLoc dl(Op); 9033 SDValue N0 = Op.getOperand(0); 9034 SDValue N1 = Op.getOperand(1); 9035 SDValue N2, N3; 9036 9037 if (VT == MVT::v8i8) { 9038 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 9039 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 9040 9041 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9042 DAG.getIntPtrConstant(4, dl)); 9043 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9044 DAG.getIntPtrConstant(4, dl)); 9045 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9046 DAG.getIntPtrConstant(0, dl)); 9047 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9048 DAG.getIntPtrConstant(0, dl)); 9049 9050 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 9051 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 9052 9053 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 9054 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 9055 9056 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 9057 return N0; 9058 } 9059 return LowerSDIV_v4i16(N0, N1, dl, DAG); 9060 } 9061 9062 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 9063 const ARMSubtarget *ST) { 9064 // TODO: Should this propagate fast-math-flags? 9065 EVT VT = Op.getValueType(); 9066 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 9067 "unexpected type for custom-lowering ISD::UDIV"); 9068 9069 SDLoc dl(Op); 9070 SDValue N0 = Op.getOperand(0); 9071 SDValue N1 = Op.getOperand(1); 9072 SDValue N2, N3; 9073 9074 if (VT == MVT::v8i8) { 9075 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 9076 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 9077 9078 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9079 DAG.getIntPtrConstant(4, dl)); 9080 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9081 DAG.getIntPtrConstant(4, dl)); 9082 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9083 DAG.getIntPtrConstant(0, dl)); 9084 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9085 DAG.getIntPtrConstant(0, dl)); 9086 9087 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 9088 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 9089 9090 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 9091 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 9092 9093 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 9094 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 9095 MVT::i32), 9096 N0); 9097 return N0; 9098 } 9099 9100 // v4i16 sdiv ... Convert to float. 9101 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 9102 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 9103 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 9104 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 9105 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 9106 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 9107 9108 // Use reciprocal estimate and two refinement steps. 9109 // float4 recip = vrecpeq_f32(yf); 9110 // recip *= vrecpsq_f32(yf, recip); 9111 // recip *= vrecpsq_f32(yf, recip); 9112 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9113 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 9114 BN1); 9115 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9116 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9117 BN1, N2); 9118 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9119 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9120 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9121 BN1, N2); 9122 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9123 // Simply multiplying by the reciprocal estimate can leave us a few ulps 9124 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 9125 // and that it will never cause us to return an answer too large). 9126 // float4 result = as_float4(as_int4(xf*recip) + 2); 9127 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 9128 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 9129 N1 = DAG.getConstant(2, dl, MVT::v4i32); 9130 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 9131 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 9132 // Convert back to integer and return. 9133 // return vmovn_u32(vcvt_s32_f32(result)); 9134 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 9135 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 9136 return N0; 9137 } 9138 9139 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 9140 SDNode *N = Op.getNode(); 9141 EVT VT = N->getValueType(0); 9142 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 9143 9144 SDValue Carry = Op.getOperand(2); 9145 9146 SDLoc DL(Op); 9147 9148 SDValue Result; 9149 if (Op.getOpcode() == ISD::ADDCARRY) { 9150 // This converts the boolean value carry into the carry flag. 9151 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 9152 9153 // Do the addition proper using the carry flag we wanted. 9154 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 9155 Op.getOperand(1), Carry); 9156 9157 // Now convert the carry flag into a boolean value. 9158 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 9159 } else { 9160 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 9161 // have to invert the carry first. 9162 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 9163 DAG.getConstant(1, DL, MVT::i32), Carry); 9164 // This converts the boolean value carry into the carry flag. 9165 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 9166 9167 // Do the subtraction proper using the carry flag we wanted. 9168 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 9169 Op.getOperand(1), Carry); 9170 9171 // Now convert the carry flag into a boolean value. 9172 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 9173 // But the carry returned by ARMISD::SUBE is not a borrow as expected 9174 // by ISD::SUBCARRY, so compute 1 - C. 9175 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 9176 DAG.getConstant(1, DL, MVT::i32), Carry); 9177 } 9178 9179 // Return both values. 9180 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 9181 } 9182 9183 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 9184 assert(Subtarget->isTargetDarwin()); 9185 9186 // For iOS, we want to call an alternative entry point: __sincos_stret, 9187 // return values are passed via sret. 9188 SDLoc dl(Op); 9189 SDValue Arg = Op.getOperand(0); 9190 EVT ArgVT = Arg.getValueType(); 9191 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 9192 auto PtrVT = getPointerTy(DAG.getDataLayout()); 9193 9194 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9195 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9196 9197 // Pair of floats / doubles used to pass the result. 9198 Type *RetTy = StructType::get(ArgTy, ArgTy); 9199 auto &DL = DAG.getDataLayout(); 9200 9201 ArgListTy Args; 9202 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 9203 SDValue SRet; 9204 if (ShouldUseSRet) { 9205 // Create stack object for sret. 9206 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 9207 const Align StackAlign = DL.getPrefTypeAlign(RetTy); 9208 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 9209 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 9210 9211 ArgListEntry Entry; 9212 Entry.Node = SRet; 9213 Entry.Ty = RetTy->getPointerTo(); 9214 Entry.IsSExt = false; 9215 Entry.IsZExt = false; 9216 Entry.IsSRet = true; 9217 Args.push_back(Entry); 9218 RetTy = Type::getVoidTy(*DAG.getContext()); 9219 } 9220 9221 ArgListEntry Entry; 9222 Entry.Node = Arg; 9223 Entry.Ty = ArgTy; 9224 Entry.IsSExt = false; 9225 Entry.IsZExt = false; 9226 Args.push_back(Entry); 9227 9228 RTLIB::Libcall LC = 9229 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 9230 const char *LibcallName = getLibcallName(LC); 9231 CallingConv::ID CC = getLibcallCallingConv(LC); 9232 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 9233 9234 TargetLowering::CallLoweringInfo CLI(DAG); 9235 CLI.setDebugLoc(dl) 9236 .setChain(DAG.getEntryNode()) 9237 .setCallee(CC, RetTy, Callee, std::move(Args)) 9238 .setDiscardResult(ShouldUseSRet); 9239 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 9240 9241 if (!ShouldUseSRet) 9242 return CallResult.first; 9243 9244 SDValue LoadSin = 9245 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 9246 9247 // Address of cos field. 9248 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 9249 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 9250 SDValue LoadCos = 9251 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 9252 9253 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 9254 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 9255 LoadSin.getValue(0), LoadCos.getValue(0)); 9256 } 9257 9258 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 9259 bool Signed, 9260 SDValue &Chain) const { 9261 EVT VT = Op.getValueType(); 9262 assert((VT == MVT::i32 || VT == MVT::i64) && 9263 "unexpected type for custom lowering DIV"); 9264 SDLoc dl(Op); 9265 9266 const auto &DL = DAG.getDataLayout(); 9267 const auto &TLI = DAG.getTargetLoweringInfo(); 9268 9269 const char *Name = nullptr; 9270 if (Signed) 9271 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 9272 else 9273 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 9274 9275 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 9276 9277 ARMTargetLowering::ArgListTy Args; 9278 9279 for (auto AI : {1, 0}) { 9280 ArgListEntry Arg; 9281 Arg.Node = Op.getOperand(AI); 9282 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 9283 Args.push_back(Arg); 9284 } 9285 9286 CallLoweringInfo CLI(DAG); 9287 CLI.setDebugLoc(dl) 9288 .setChain(Chain) 9289 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 9290 ES, std::move(Args)); 9291 9292 return LowerCallTo(CLI).first; 9293 } 9294 9295 // This is a code size optimisation: return the original SDIV node to 9296 // DAGCombiner when we don't want to expand SDIV into a sequence of 9297 // instructions, and an empty node otherwise which will cause the 9298 // SDIV to be expanded in DAGCombine. 9299 SDValue 9300 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 9301 SelectionDAG &DAG, 9302 SmallVectorImpl<SDNode *> &Created) const { 9303 // TODO: Support SREM 9304 if (N->getOpcode() != ISD::SDIV) 9305 return SDValue(); 9306 9307 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 9308 const bool MinSize = ST.hasMinSize(); 9309 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 9310 : ST.hasDivideInARMMode(); 9311 9312 // Don't touch vector types; rewriting this may lead to scalarizing 9313 // the int divs. 9314 if (N->getOperand(0).getValueType().isVector()) 9315 return SDValue(); 9316 9317 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 9318 // hwdiv support for this to be really profitable. 9319 if (!(MinSize && HasDivide)) 9320 return SDValue(); 9321 9322 // ARM mode is a bit simpler than Thumb: we can handle large power 9323 // of 2 immediates with 1 mov instruction; no further checks required, 9324 // just return the sdiv node. 9325 if (!ST.isThumb()) 9326 return SDValue(N, 0); 9327 9328 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 9329 // and thus lose the code size benefits of a MOVS that requires only 2. 9330 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 9331 // but as it's doing exactly this, it's not worth the trouble to get TTI. 9332 if (Divisor.sgt(128)) 9333 return SDValue(); 9334 9335 return SDValue(N, 0); 9336 } 9337 9338 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 9339 bool Signed) const { 9340 assert(Op.getValueType() == MVT::i32 && 9341 "unexpected type for custom lowering DIV"); 9342 SDLoc dl(Op); 9343 9344 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 9345 DAG.getEntryNode(), Op.getOperand(1)); 9346 9347 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9348 } 9349 9350 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 9351 SDLoc DL(N); 9352 SDValue Op = N->getOperand(1); 9353 if (N->getValueType(0) == MVT::i32) 9354 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 9355 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9356 DAG.getConstant(0, DL, MVT::i32)); 9357 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9358 DAG.getConstant(1, DL, MVT::i32)); 9359 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 9360 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 9361 } 9362 9363 void ARMTargetLowering::ExpandDIV_Windows( 9364 SDValue Op, SelectionDAG &DAG, bool Signed, 9365 SmallVectorImpl<SDValue> &Results) const { 9366 const auto &DL = DAG.getDataLayout(); 9367 const auto &TLI = DAG.getTargetLoweringInfo(); 9368 9369 assert(Op.getValueType() == MVT::i64 && 9370 "unexpected type for custom lowering DIV"); 9371 SDLoc dl(Op); 9372 9373 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 9374 9375 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9376 9377 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 9378 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 9379 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 9380 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 9381 9382 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper)); 9383 } 9384 9385 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) { 9386 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode()); 9387 EVT MemVT = LD->getMemoryVT(); 9388 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9389 "Expected a predicate type!"); 9390 assert(MemVT == Op.getValueType()); 9391 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && 9392 "Expected a non-extending load"); 9393 assert(LD->isUnindexed() && "Expected a unindexed load"); 9394 9395 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit 9396 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We 9397 // need to make sure that 8/4 bits are actually loaded into the correct 9398 // place, which means loading the value and then shuffling the values into 9399 // the bottom bits of the predicate. 9400 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect 9401 // for BE). 9402 9403 SDLoc dl(Op); 9404 SDValue Load = DAG.getExtLoad( 9405 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(), 9406 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9407 LD->getMemOperand()); 9408 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load); 9409 if (MemVT != MVT::v16i1) 9410 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred, 9411 DAG.getConstant(0, dl, MVT::i32)); 9412 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl); 9413 } 9414 9415 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results, 9416 SelectionDAG &DAG) const { 9417 LoadSDNode *LD = cast<LoadSDNode>(N); 9418 EVT MemVT = LD->getMemoryVT(); 9419 assert(LD->isUnindexed() && "Loads should be unindexed at this point."); 9420 9421 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9422 !Subtarget->isThumb1Only() && LD->isVolatile()) { 9423 SDLoc dl(N); 9424 SDValue Result = DAG.getMemIntrinsicNode( 9425 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}), 9426 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand()); 9427 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1); 9428 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0); 9429 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 9430 Results.append({Pair, Result.getValue(2)}); 9431 } 9432 } 9433 9434 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) { 9435 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9436 EVT MemVT = ST->getMemoryVT(); 9437 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9438 "Expected a predicate type!"); 9439 assert(MemVT == ST->getValue().getValueType()); 9440 assert(!ST->isTruncatingStore() && "Expected a non-extending store"); 9441 assert(ST->isUnindexed() && "Expected a unindexed store"); 9442 9443 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits 9444 // unset and a scalar store. 9445 SDLoc dl(Op); 9446 SDValue Build = ST->getValue(); 9447 if (MemVT != MVT::v16i1) { 9448 SmallVector<SDValue, 16> Ops; 9449 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) 9450 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build, 9451 DAG.getConstant(I, dl, MVT::i32))); 9452 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++) 9453 Ops.push_back(DAG.getUNDEF(MVT::i32)); 9454 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops); 9455 } 9456 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build); 9457 return DAG.getTruncStore( 9458 ST->getChain(), dl, GRP, ST->getBasePtr(), 9459 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9460 ST->getMemOperand()); 9461 } 9462 9463 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG, 9464 const ARMSubtarget *Subtarget) { 9465 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9466 EVT MemVT = ST->getMemoryVT(); 9467 assert(ST->isUnindexed() && "Stores should be unindexed at this point."); 9468 9469 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9470 !Subtarget->isThumb1Only() && ST->isVolatile()) { 9471 SDNode *N = Op.getNode(); 9472 SDLoc dl(N); 9473 9474 SDValue Lo = DAG.getNode( 9475 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9476 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl, 9477 MVT::i32)); 9478 SDValue Hi = DAG.getNode( 9479 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9480 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl, 9481 MVT::i32)); 9482 9483 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other), 9484 {ST->getChain(), Lo, Hi, ST->getBasePtr()}, 9485 MemVT, ST->getMemOperand()); 9486 } else if (Subtarget->hasMVEIntegerOps() && 9487 ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || 9488 MemVT == MVT::v16i1))) { 9489 return LowerPredicateStore(Op, DAG); 9490 } 9491 9492 return SDValue(); 9493 } 9494 9495 static bool isZeroVector(SDValue N) { 9496 return (ISD::isBuildVectorAllZeros(N.getNode()) || 9497 (N->getOpcode() == ARMISD::VMOVIMM && 9498 isNullConstant(N->getOperand(0)))); 9499 } 9500 9501 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) { 9502 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode()); 9503 MVT VT = Op.getSimpleValueType(); 9504 SDValue Mask = N->getMask(); 9505 SDValue PassThru = N->getPassThru(); 9506 SDLoc dl(Op); 9507 9508 if (isZeroVector(PassThru)) 9509 return Op; 9510 9511 // MVE Masked loads use zero as the passthru value. Here we convert undef to 9512 // zero too, and other values are lowered to a select. 9513 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 9514 DAG.getTargetConstant(0, dl, MVT::i32)); 9515 SDValue NewLoad = DAG.getMaskedLoad( 9516 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec, 9517 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(), 9518 N->getExtensionType(), N->isExpandingLoad()); 9519 SDValue Combo = NewLoad; 9520 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST || 9521 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) && 9522 isZeroVector(PassThru->getOperand(0)); 9523 if (!PassThru.isUndef() && !PassThruIsCastZero) 9524 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru); 9525 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl); 9526 } 9527 9528 static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG, 9529 const ARMSubtarget *ST) { 9530 if (!ST->hasMVEIntegerOps()) 9531 return SDValue(); 9532 9533 SDLoc dl(Op); 9534 unsigned BaseOpcode = 0; 9535 switch (Op->getOpcode()) { 9536 default: llvm_unreachable("Expected VECREDUCE opcode"); 9537 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break; 9538 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break; 9539 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break; 9540 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break; 9541 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break; 9542 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break; 9543 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break; 9544 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break; 9545 } 9546 9547 SDValue Op0 = Op->getOperand(0); 9548 EVT VT = Op0.getValueType(); 9549 EVT EltVT = VT.getVectorElementType(); 9550 unsigned NumElts = VT.getVectorNumElements(); 9551 unsigned NumActiveLanes = NumElts; 9552 9553 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || 9554 NumActiveLanes == 2) && 9555 "Only expected a power 2 vector size"); 9556 9557 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements 9558 // allows us to easily extract vector elements from the lanes. 9559 while (NumActiveLanes > 4) { 9560 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32; 9561 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0); 9562 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev); 9563 NumActiveLanes /= 2; 9564 } 9565 9566 SDValue Res; 9567 if (NumActiveLanes == 4) { 9568 // The remaining 4 elements are summed sequentially 9569 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9570 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32)); 9571 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9572 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32)); 9573 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9574 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32)); 9575 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9576 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32)); 9577 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags()); 9578 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags()); 9579 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags()); 9580 } else { 9581 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9582 DAG.getConstant(0, dl, MVT::i32)); 9583 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9584 DAG.getConstant(1, dl, MVT::i32)); 9585 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags()); 9586 } 9587 9588 // Result type may be wider than element type. 9589 if (EltVT != Op->getValueType(0)) 9590 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res); 9591 return Res; 9592 } 9593 9594 static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG, 9595 const ARMSubtarget *ST) { 9596 if (!ST->hasMVEFloatOps()) 9597 return SDValue(); 9598 return LowerVecReduce(Op, DAG, ST); 9599 } 9600 9601 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 9602 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 9603 // Acquire/Release load/store is not legal for targets without a dmb or 9604 // equivalent available. 9605 return SDValue(); 9606 9607 // Monotonic load/store is legal for all targets. 9608 return Op; 9609 } 9610 9611 static void ReplaceREADCYCLECOUNTER(SDNode *N, 9612 SmallVectorImpl<SDValue> &Results, 9613 SelectionDAG &DAG, 9614 const ARMSubtarget *Subtarget) { 9615 SDLoc DL(N); 9616 // Under Power Management extensions, the cycle-count is: 9617 // mrc p15, #0, <Rt>, c9, c13, #0 9618 SDValue Ops[] = { N->getOperand(0), // Chain 9619 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 9620 DAG.getTargetConstant(15, DL, MVT::i32), 9621 DAG.getTargetConstant(0, DL, MVT::i32), 9622 DAG.getTargetConstant(9, DL, MVT::i32), 9623 DAG.getTargetConstant(13, DL, MVT::i32), 9624 DAG.getTargetConstant(0, DL, MVT::i32) 9625 }; 9626 9627 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 9628 DAG.getVTList(MVT::i32, MVT::Other), Ops); 9629 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 9630 DAG.getConstant(0, DL, MVT::i32))); 9631 Results.push_back(Cycles32.getValue(1)); 9632 } 9633 9634 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 9635 SDLoc dl(V.getNode()); 9636 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 9637 SDValue VHi = DAG.getAnyExtOrTrunc( 9638 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 9639 dl, MVT::i32); 9640 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9641 if (isBigEndian) 9642 std::swap (VLo, VHi); 9643 SDValue RegClass = 9644 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 9645 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 9646 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 9647 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 9648 return SDValue( 9649 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 9650 } 9651 9652 static void ReplaceCMP_SWAP_64Results(SDNode *N, 9653 SmallVectorImpl<SDValue> & Results, 9654 SelectionDAG &DAG) { 9655 assert(N->getValueType(0) == MVT::i64 && 9656 "AtomicCmpSwap on types less than 64 should be legal"); 9657 SDValue Ops[] = {N->getOperand(1), 9658 createGPRPairNode(DAG, N->getOperand(2)), 9659 createGPRPairNode(DAG, N->getOperand(3)), 9660 N->getOperand(0)}; 9661 SDNode *CmpSwap = DAG.getMachineNode( 9662 ARM::CMP_SWAP_64, SDLoc(N), 9663 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 9664 9665 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 9666 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 9667 9668 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9669 9670 SDValue Lo = 9671 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 9672 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9673 SDValue Hi = 9674 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 9675 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9676 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi)); 9677 Results.push_back(SDValue(CmpSwap, 2)); 9678 } 9679 9680 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const { 9681 SDLoc dl(Op); 9682 EVT VT = Op.getValueType(); 9683 SDValue Chain = Op.getOperand(0); 9684 SDValue LHS = Op.getOperand(1); 9685 SDValue RHS = Op.getOperand(2); 9686 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get(); 9687 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 9688 9689 // If we don't have instructions of this float type then soften to a libcall 9690 // and use SETCC instead. 9691 if (isUnsupportedFloatingType(LHS.getValueType())) { 9692 DAG.getTargetLoweringInfo().softenSetCCOperands( 9693 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling); 9694 if (!RHS.getNode()) { 9695 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 9696 CC = ISD::SETNE; 9697 } 9698 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS, 9699 DAG.getCondCode(CC)); 9700 return DAG.getMergeValues({Result, Chain}, dl); 9701 } 9702 9703 ARMCC::CondCodes CondCode, CondCode2; 9704 FPCCToARMCC(CC, CondCode, CondCode2); 9705 9706 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit 9707 // in CMPFP and CMPFPE, but instead it should be made explicit by these 9708 // instructions using a chain instead of glue. This would also fix the problem 9709 // here (and also in LowerSELECT_CC) where we generate two comparisons when 9710 // CondCode2 != AL. 9711 SDValue True = DAG.getConstant(1, dl, VT); 9712 SDValue False = DAG.getConstant(0, dl, VT); 9713 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 9714 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 9715 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9716 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG); 9717 if (CondCode2 != ARMCC::AL) { 9718 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 9719 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9720 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG); 9721 } 9722 return DAG.getMergeValues({Result, Chain}, dl); 9723 } 9724 9725 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9726 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 9727 switch (Op.getOpcode()) { 9728 default: llvm_unreachable("Don't know how to custom lower this!"); 9729 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 9730 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9731 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9732 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9733 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9734 case ISD::SELECT: return LowerSELECT(Op, DAG); 9735 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9736 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9737 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 9738 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 9739 case ISD::VASTART: return LowerVASTART(Op, DAG); 9740 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 9741 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 9742 case ISD::SINT_TO_FP: 9743 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9744 case ISD::STRICT_FP_TO_SINT: 9745 case ISD::STRICT_FP_TO_UINT: 9746 case ISD::FP_TO_SINT: 9747 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 9748 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9749 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9750 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9751 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 9752 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 9753 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 9754 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget); 9755 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 9756 Subtarget); 9757 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 9758 case ISD::SHL: 9759 case ISD::SRL: 9760 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 9761 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 9762 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 9763 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 9764 case ISD::SRL_PARTS: 9765 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 9766 case ISD::CTTZ: 9767 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 9768 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 9769 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 9770 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 9771 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 9772 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 9773 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 9774 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 9775 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9776 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 9777 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 9778 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9779 case ISD::MUL: return LowerMUL(Op, DAG); 9780 case ISD::SDIV: 9781 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9782 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 9783 return LowerSDIV(Op, DAG, Subtarget); 9784 case ISD::UDIV: 9785 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9786 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 9787 return LowerUDIV(Op, DAG, Subtarget); 9788 case ISD::ADDCARRY: 9789 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 9790 case ISD::SADDO: 9791 case ISD::SSUBO: 9792 return LowerSignedALUO(Op, DAG); 9793 case ISD::UADDO: 9794 case ISD::USUBO: 9795 return LowerUnsignedALUO(Op, DAG); 9796 case ISD::SADDSAT: 9797 case ISD::SSUBSAT: 9798 return LowerSADDSUBSAT(Op, DAG, Subtarget); 9799 case ISD::LOAD: 9800 return LowerPredicateLoad(Op, DAG); 9801 case ISD::STORE: 9802 return LowerSTORE(Op, DAG, Subtarget); 9803 case ISD::MLOAD: 9804 return LowerMLOAD(Op, DAG); 9805 case ISD::VECREDUCE_MUL: 9806 case ISD::VECREDUCE_AND: 9807 case ISD::VECREDUCE_OR: 9808 case ISD::VECREDUCE_XOR: 9809 return LowerVecReduce(Op, DAG, Subtarget); 9810 case ISD::VECREDUCE_FADD: 9811 case ISD::VECREDUCE_FMUL: 9812 case ISD::VECREDUCE_FMIN: 9813 case ISD::VECREDUCE_FMAX: 9814 return LowerVecReduceF(Op, DAG, Subtarget); 9815 case ISD::ATOMIC_LOAD: 9816 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 9817 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 9818 case ISD::SDIVREM: 9819 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 9820 case ISD::DYNAMIC_STACKALLOC: 9821 if (Subtarget->isTargetWindows()) 9822 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9823 llvm_unreachable("Don't know how to custom lower this!"); 9824 case ISD::STRICT_FP_ROUND: 9825 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 9826 case ISD::STRICT_FP_EXTEND: 9827 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9828 case ISD::STRICT_FSETCC: 9829 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG); 9830 case ARMISD::WIN__DBZCHK: return SDValue(); 9831 } 9832 } 9833 9834 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 9835 SelectionDAG &DAG) { 9836 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9837 unsigned Opc = 0; 9838 if (IntNo == Intrinsic::arm_smlald) 9839 Opc = ARMISD::SMLALD; 9840 else if (IntNo == Intrinsic::arm_smlaldx) 9841 Opc = ARMISD::SMLALDX; 9842 else if (IntNo == Intrinsic::arm_smlsld) 9843 Opc = ARMISD::SMLSLD; 9844 else if (IntNo == Intrinsic::arm_smlsldx) 9845 Opc = ARMISD::SMLSLDX; 9846 else 9847 return; 9848 9849 SDLoc dl(N); 9850 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9851 N->getOperand(3), 9852 DAG.getConstant(0, dl, MVT::i32)); 9853 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9854 N->getOperand(3), 9855 DAG.getConstant(1, dl, MVT::i32)); 9856 9857 SDValue LongMul = DAG.getNode(Opc, dl, 9858 DAG.getVTList(MVT::i32, MVT::i32), 9859 N->getOperand(1), N->getOperand(2), 9860 Lo, Hi); 9861 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, 9862 LongMul.getValue(0), LongMul.getValue(1))); 9863 } 9864 9865 /// ReplaceNodeResults - Replace the results of node with an illegal result 9866 /// type with new values built out of custom code. 9867 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 9868 SmallVectorImpl<SDValue> &Results, 9869 SelectionDAG &DAG) const { 9870 SDValue Res; 9871 switch (N->getOpcode()) { 9872 default: 9873 llvm_unreachable("Don't know how to custom expand this!"); 9874 case ISD::READ_REGISTER: 9875 ExpandREAD_REGISTER(N, Results, DAG); 9876 break; 9877 case ISD::BITCAST: 9878 Res = ExpandBITCAST(N, DAG, Subtarget); 9879 break; 9880 case ISD::SRL: 9881 case ISD::SRA: 9882 case ISD::SHL: 9883 Res = Expand64BitShift(N, DAG, Subtarget); 9884 break; 9885 case ISD::SREM: 9886 case ISD::UREM: 9887 Res = LowerREM(N, DAG); 9888 break; 9889 case ISD::SDIVREM: 9890 case ISD::UDIVREM: 9891 Res = LowerDivRem(SDValue(N, 0), DAG); 9892 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 9893 Results.push_back(Res.getValue(0)); 9894 Results.push_back(Res.getValue(1)); 9895 return; 9896 case ISD::SADDSAT: 9897 case ISD::SSUBSAT: 9898 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget); 9899 break; 9900 case ISD::READCYCLECOUNTER: 9901 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 9902 return; 9903 case ISD::UDIV: 9904 case ISD::SDIV: 9905 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 9906 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 9907 Results); 9908 case ISD::ATOMIC_CMP_SWAP: 9909 ReplaceCMP_SWAP_64Results(N, Results, DAG); 9910 return; 9911 case ISD::INTRINSIC_WO_CHAIN: 9912 return ReplaceLongIntrinsic(N, Results, DAG); 9913 case ISD::ABS: 9914 lowerABS(N, Results, DAG); 9915 return ; 9916 case ISD::LOAD: 9917 LowerLOAD(N, Results, DAG); 9918 break; 9919 } 9920 if (Res.getNode()) 9921 Results.push_back(Res); 9922 } 9923 9924 //===----------------------------------------------------------------------===// 9925 // ARM Scheduler Hooks 9926 //===----------------------------------------------------------------------===// 9927 9928 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 9929 /// registers the function context. 9930 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 9931 MachineBasicBlock *MBB, 9932 MachineBasicBlock *DispatchBB, 9933 int FI) const { 9934 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 9935 "ROPI/RWPI not currently supported with SjLj"); 9936 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9937 DebugLoc dl = MI.getDebugLoc(); 9938 MachineFunction *MF = MBB->getParent(); 9939 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9940 MachineConstantPool *MCP = MF->getConstantPool(); 9941 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 9942 const Function &F = MF->getFunction(); 9943 9944 bool isThumb = Subtarget->isThumb(); 9945 bool isThumb2 = Subtarget->isThumb2(); 9946 9947 unsigned PCLabelId = AFI->createPICLabelUId(); 9948 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 9949 ARMConstantPoolValue *CPV = 9950 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 9951 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4)); 9952 9953 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 9954 : &ARM::GPRRegClass; 9955 9956 // Grab constant pool and fixed stack memory operands. 9957 MachineMemOperand *CPMMO = 9958 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9959 MachineMemOperand::MOLoad, 4, Align(4)); 9960 9961 MachineMemOperand *FIMMOSt = 9962 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 9963 MachineMemOperand::MOStore, 4, Align(4)); 9964 9965 // Load the address of the dispatch MBB into the jump buffer. 9966 if (isThumb2) { 9967 // Incoming value: jbuf 9968 // ldr.n r5, LCPI1_1 9969 // orr r5, r5, #1 9970 // add r5, pc 9971 // str r5, [$jbuf, #+4] ; &jbuf[1] 9972 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9973 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 9974 .addConstantPoolIndex(CPI) 9975 .addMemOperand(CPMMO) 9976 .add(predOps(ARMCC::AL)); 9977 // Set the low bit because of thumb mode. 9978 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9979 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 9980 .addReg(NewVReg1, RegState::Kill) 9981 .addImm(0x01) 9982 .add(predOps(ARMCC::AL)) 9983 .add(condCodeOp()); 9984 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9985 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 9986 .addReg(NewVReg2, RegState::Kill) 9987 .addImm(PCLabelId); 9988 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 9989 .addReg(NewVReg3, RegState::Kill) 9990 .addFrameIndex(FI) 9991 .addImm(36) // &jbuf[1] :: pc 9992 .addMemOperand(FIMMOSt) 9993 .add(predOps(ARMCC::AL)); 9994 } else if (isThumb) { 9995 // Incoming value: jbuf 9996 // ldr.n r1, LCPI1_4 9997 // add r1, pc 9998 // mov r2, #1 9999 // orrs r1, r2 10000 // add r2, $jbuf, #+4 ; &jbuf[1] 10001 // str r1, [r2] 10002 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10003 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 10004 .addConstantPoolIndex(CPI) 10005 .addMemOperand(CPMMO) 10006 .add(predOps(ARMCC::AL)); 10007 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10008 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 10009 .addReg(NewVReg1, RegState::Kill) 10010 .addImm(PCLabelId); 10011 // Set the low bit because of thumb mode. 10012 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10013 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 10014 .addReg(ARM::CPSR, RegState::Define) 10015 .addImm(1) 10016 .add(predOps(ARMCC::AL)); 10017 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10018 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 10019 .addReg(ARM::CPSR, RegState::Define) 10020 .addReg(NewVReg2, RegState::Kill) 10021 .addReg(NewVReg3, RegState::Kill) 10022 .add(predOps(ARMCC::AL)); 10023 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10024 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 10025 .addFrameIndex(FI) 10026 .addImm(36); // &jbuf[1] :: pc 10027 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 10028 .addReg(NewVReg4, RegState::Kill) 10029 .addReg(NewVReg5, RegState::Kill) 10030 .addImm(0) 10031 .addMemOperand(FIMMOSt) 10032 .add(predOps(ARMCC::AL)); 10033 } else { 10034 // Incoming value: jbuf 10035 // ldr r1, LCPI1_1 10036 // add r1, pc, r1 10037 // str r1, [$jbuf, #+4] ; &jbuf[1] 10038 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10039 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 10040 .addConstantPoolIndex(CPI) 10041 .addImm(0) 10042 .addMemOperand(CPMMO) 10043 .add(predOps(ARMCC::AL)); 10044 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10045 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 10046 .addReg(NewVReg1, RegState::Kill) 10047 .addImm(PCLabelId) 10048 .add(predOps(ARMCC::AL)); 10049 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 10050 .addReg(NewVReg2, RegState::Kill) 10051 .addFrameIndex(FI) 10052 .addImm(36) // &jbuf[1] :: pc 10053 .addMemOperand(FIMMOSt) 10054 .add(predOps(ARMCC::AL)); 10055 } 10056 } 10057 10058 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 10059 MachineBasicBlock *MBB) const { 10060 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10061 DebugLoc dl = MI.getDebugLoc(); 10062 MachineFunction *MF = MBB->getParent(); 10063 MachineRegisterInfo *MRI = &MF->getRegInfo(); 10064 MachineFrameInfo &MFI = MF->getFrameInfo(); 10065 int FI = MFI.getFunctionContextIndex(); 10066 10067 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 10068 : &ARM::GPRnopcRegClass; 10069 10070 // Get a mapping of the call site numbers to all of the landing pads they're 10071 // associated with. 10072 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 10073 unsigned MaxCSNum = 0; 10074 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 10075 ++BB) { 10076 if (!BB->isEHPad()) continue; 10077 10078 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 10079 // pad. 10080 for (MachineBasicBlock::iterator 10081 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 10082 if (!II->isEHLabel()) continue; 10083 10084 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 10085 if (!MF->hasCallSiteLandingPad(Sym)) continue; 10086 10087 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 10088 for (SmallVectorImpl<unsigned>::iterator 10089 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 10090 CSI != CSE; ++CSI) { 10091 CallSiteNumToLPad[*CSI].push_back(&*BB); 10092 MaxCSNum = std::max(MaxCSNum, *CSI); 10093 } 10094 break; 10095 } 10096 } 10097 10098 // Get an ordered list of the machine basic blocks for the jump table. 10099 std::vector<MachineBasicBlock*> LPadList; 10100 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 10101 LPadList.reserve(CallSiteNumToLPad.size()); 10102 for (unsigned I = 1; I <= MaxCSNum; ++I) { 10103 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 10104 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10105 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 10106 LPadList.push_back(*II); 10107 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 10108 } 10109 } 10110 10111 assert(!LPadList.empty() && 10112 "No landing pad destinations for the dispatch jump table!"); 10113 10114 // Create the jump table and associated information. 10115 MachineJumpTableInfo *JTI = 10116 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 10117 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 10118 10119 // Create the MBBs for the dispatch code. 10120 10121 // Shove the dispatch's address into the return slot in the function context. 10122 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 10123 DispatchBB->setIsEHPad(); 10124 10125 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10126 unsigned trap_opcode; 10127 if (Subtarget->isThumb()) 10128 trap_opcode = ARM::tTRAP; 10129 else 10130 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 10131 10132 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 10133 DispatchBB->addSuccessor(TrapBB); 10134 10135 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 10136 DispatchBB->addSuccessor(DispContBB); 10137 10138 // Insert and MBBs. 10139 MF->insert(MF->end(), DispatchBB); 10140 MF->insert(MF->end(), DispContBB); 10141 MF->insert(MF->end(), TrapBB); 10142 10143 // Insert code into the entry block that creates and registers the function 10144 // context. 10145 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 10146 10147 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 10148 MachinePointerInfo::getFixedStack(*MF, FI), 10149 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4)); 10150 10151 MachineInstrBuilder MIB; 10152 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 10153 10154 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 10155 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 10156 10157 // Add a register mask with no preserved registers. This results in all 10158 // registers being marked as clobbered. This can't work if the dispatch block 10159 // is in a Thumb1 function and is linked with ARM code which uses the FP 10160 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 10161 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 10162 10163 bool IsPositionIndependent = isPositionIndependent(); 10164 unsigned NumLPads = LPadList.size(); 10165 if (Subtarget->isThumb2()) { 10166 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10167 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 10168 .addFrameIndex(FI) 10169 .addImm(4) 10170 .addMemOperand(FIMMOLd) 10171 .add(predOps(ARMCC::AL)); 10172 10173 if (NumLPads < 256) { 10174 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 10175 .addReg(NewVReg1) 10176 .addImm(LPadList.size()) 10177 .add(predOps(ARMCC::AL)); 10178 } else { 10179 Register VReg1 = MRI->createVirtualRegister(TRC); 10180 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 10181 .addImm(NumLPads & 0xFFFF) 10182 .add(predOps(ARMCC::AL)); 10183 10184 unsigned VReg2 = VReg1; 10185 if ((NumLPads & 0xFFFF0000) != 0) { 10186 VReg2 = MRI->createVirtualRegister(TRC); 10187 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 10188 .addReg(VReg1) 10189 .addImm(NumLPads >> 16) 10190 .add(predOps(ARMCC::AL)); 10191 } 10192 10193 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 10194 .addReg(NewVReg1) 10195 .addReg(VReg2) 10196 .add(predOps(ARMCC::AL)); 10197 } 10198 10199 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 10200 .addMBB(TrapBB) 10201 .addImm(ARMCC::HI) 10202 .addReg(ARM::CPSR); 10203 10204 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10205 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 10206 .addJumpTableIndex(MJTI) 10207 .add(predOps(ARMCC::AL)); 10208 10209 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10210 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 10211 .addReg(NewVReg3, RegState::Kill) 10212 .addReg(NewVReg1) 10213 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10214 .add(predOps(ARMCC::AL)) 10215 .add(condCodeOp()); 10216 10217 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 10218 .addReg(NewVReg4, RegState::Kill) 10219 .addReg(NewVReg1) 10220 .addJumpTableIndex(MJTI); 10221 } else if (Subtarget->isThumb()) { 10222 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10223 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 10224 .addFrameIndex(FI) 10225 .addImm(1) 10226 .addMemOperand(FIMMOLd) 10227 .add(predOps(ARMCC::AL)); 10228 10229 if (NumLPads < 256) { 10230 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 10231 .addReg(NewVReg1) 10232 .addImm(NumLPads) 10233 .add(predOps(ARMCC::AL)); 10234 } else { 10235 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10236 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10237 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 10238 10239 // MachineConstantPool wants an explicit alignment. 10240 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10241 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10242 10243 Register VReg1 = MRI->createVirtualRegister(TRC); 10244 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 10245 .addReg(VReg1, RegState::Define) 10246 .addConstantPoolIndex(Idx) 10247 .add(predOps(ARMCC::AL)); 10248 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 10249 .addReg(NewVReg1) 10250 .addReg(VReg1) 10251 .add(predOps(ARMCC::AL)); 10252 } 10253 10254 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 10255 .addMBB(TrapBB) 10256 .addImm(ARMCC::HI) 10257 .addReg(ARM::CPSR); 10258 10259 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10260 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 10261 .addReg(ARM::CPSR, RegState::Define) 10262 .addReg(NewVReg1) 10263 .addImm(2) 10264 .add(predOps(ARMCC::AL)); 10265 10266 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10267 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 10268 .addJumpTableIndex(MJTI) 10269 .add(predOps(ARMCC::AL)); 10270 10271 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10272 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 10273 .addReg(ARM::CPSR, RegState::Define) 10274 .addReg(NewVReg2, RegState::Kill) 10275 .addReg(NewVReg3) 10276 .add(predOps(ARMCC::AL)); 10277 10278 MachineMemOperand *JTMMOLd = 10279 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10280 MachineMemOperand::MOLoad, 4, Align(4)); 10281 10282 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10283 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 10284 .addReg(NewVReg4, RegState::Kill) 10285 .addImm(0) 10286 .addMemOperand(JTMMOLd) 10287 .add(predOps(ARMCC::AL)); 10288 10289 unsigned NewVReg6 = NewVReg5; 10290 if (IsPositionIndependent) { 10291 NewVReg6 = MRI->createVirtualRegister(TRC); 10292 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 10293 .addReg(ARM::CPSR, RegState::Define) 10294 .addReg(NewVReg5, RegState::Kill) 10295 .addReg(NewVReg3) 10296 .add(predOps(ARMCC::AL)); 10297 } 10298 10299 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 10300 .addReg(NewVReg6, RegState::Kill) 10301 .addJumpTableIndex(MJTI); 10302 } else { 10303 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10304 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 10305 .addFrameIndex(FI) 10306 .addImm(4) 10307 .addMemOperand(FIMMOLd) 10308 .add(predOps(ARMCC::AL)); 10309 10310 if (NumLPads < 256) { 10311 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 10312 .addReg(NewVReg1) 10313 .addImm(NumLPads) 10314 .add(predOps(ARMCC::AL)); 10315 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 10316 Register VReg1 = MRI->createVirtualRegister(TRC); 10317 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 10318 .addImm(NumLPads & 0xFFFF) 10319 .add(predOps(ARMCC::AL)); 10320 10321 unsigned VReg2 = VReg1; 10322 if ((NumLPads & 0xFFFF0000) != 0) { 10323 VReg2 = MRI->createVirtualRegister(TRC); 10324 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 10325 .addReg(VReg1) 10326 .addImm(NumLPads >> 16) 10327 .add(predOps(ARMCC::AL)); 10328 } 10329 10330 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 10331 .addReg(NewVReg1) 10332 .addReg(VReg2) 10333 .add(predOps(ARMCC::AL)); 10334 } else { 10335 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10336 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10337 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 10338 10339 // MachineConstantPool wants an explicit alignment. 10340 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10341 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10342 10343 Register VReg1 = MRI->createVirtualRegister(TRC); 10344 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 10345 .addReg(VReg1, RegState::Define) 10346 .addConstantPoolIndex(Idx) 10347 .addImm(0) 10348 .add(predOps(ARMCC::AL)); 10349 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 10350 .addReg(NewVReg1) 10351 .addReg(VReg1, RegState::Kill) 10352 .add(predOps(ARMCC::AL)); 10353 } 10354 10355 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 10356 .addMBB(TrapBB) 10357 .addImm(ARMCC::HI) 10358 .addReg(ARM::CPSR); 10359 10360 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10361 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 10362 .addReg(NewVReg1) 10363 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10364 .add(predOps(ARMCC::AL)) 10365 .add(condCodeOp()); 10366 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10367 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 10368 .addJumpTableIndex(MJTI) 10369 .add(predOps(ARMCC::AL)); 10370 10371 MachineMemOperand *JTMMOLd = 10372 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10373 MachineMemOperand::MOLoad, 4, Align(4)); 10374 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10375 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 10376 .addReg(NewVReg3, RegState::Kill) 10377 .addReg(NewVReg4) 10378 .addImm(0) 10379 .addMemOperand(JTMMOLd) 10380 .add(predOps(ARMCC::AL)); 10381 10382 if (IsPositionIndependent) { 10383 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 10384 .addReg(NewVReg5, RegState::Kill) 10385 .addReg(NewVReg4) 10386 .addJumpTableIndex(MJTI); 10387 } else { 10388 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 10389 .addReg(NewVReg5, RegState::Kill) 10390 .addJumpTableIndex(MJTI); 10391 } 10392 } 10393 10394 // Add the jump table entries as successors to the MBB. 10395 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 10396 for (std::vector<MachineBasicBlock*>::iterator 10397 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 10398 MachineBasicBlock *CurMBB = *I; 10399 if (SeenMBBs.insert(CurMBB).second) 10400 DispContBB->addSuccessor(CurMBB); 10401 } 10402 10403 // N.B. the order the invoke BBs are processed in doesn't matter here. 10404 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 10405 SmallVector<MachineBasicBlock*, 64> MBBLPads; 10406 for (MachineBasicBlock *BB : InvokeBBs) { 10407 10408 // Remove the landing pad successor from the invoke block and replace it 10409 // with the new dispatch block. 10410 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 10411 BB->succ_end()); 10412 while (!Successors.empty()) { 10413 MachineBasicBlock *SMBB = Successors.pop_back_val(); 10414 if (SMBB->isEHPad()) { 10415 BB->removeSuccessor(SMBB); 10416 MBBLPads.push_back(SMBB); 10417 } 10418 } 10419 10420 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 10421 BB->normalizeSuccProbs(); 10422 10423 // Find the invoke call and mark all of the callee-saved registers as 10424 // 'implicit defined' so that they're spilled. This prevents code from 10425 // moving instructions to before the EH block, where they will never be 10426 // executed. 10427 for (MachineBasicBlock::reverse_iterator 10428 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 10429 if (!II->isCall()) continue; 10430 10431 DenseMap<unsigned, bool> DefRegs; 10432 for (MachineInstr::mop_iterator 10433 OI = II->operands_begin(), OE = II->operands_end(); 10434 OI != OE; ++OI) { 10435 if (!OI->isReg()) continue; 10436 DefRegs[OI->getReg()] = true; 10437 } 10438 10439 MachineInstrBuilder MIB(*MF, &*II); 10440 10441 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 10442 unsigned Reg = SavedRegs[i]; 10443 if (Subtarget->isThumb2() && 10444 !ARM::tGPRRegClass.contains(Reg) && 10445 !ARM::hGPRRegClass.contains(Reg)) 10446 continue; 10447 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 10448 continue; 10449 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 10450 continue; 10451 if (!DefRegs[Reg]) 10452 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 10453 } 10454 10455 break; 10456 } 10457 } 10458 10459 // Mark all former landing pads as non-landing pads. The dispatch is the only 10460 // landing pad now. 10461 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10462 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 10463 (*I)->setIsEHPad(false); 10464 10465 // The instruction is gone now. 10466 MI.eraseFromParent(); 10467 } 10468 10469 static 10470 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 10471 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 10472 E = MBB->succ_end(); I != E; ++I) 10473 if (*I != Succ) 10474 return *I; 10475 llvm_unreachable("Expecting a BB with two successors!"); 10476 } 10477 10478 /// Return the load opcode for a given load size. If load size >= 8, 10479 /// neon opcode will be returned. 10480 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 10481 if (LdSize >= 8) 10482 return LdSize == 16 ? ARM::VLD1q32wb_fixed 10483 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 10484 if (IsThumb1) 10485 return LdSize == 4 ? ARM::tLDRi 10486 : LdSize == 2 ? ARM::tLDRHi 10487 : LdSize == 1 ? ARM::tLDRBi : 0; 10488 if (IsThumb2) 10489 return LdSize == 4 ? ARM::t2LDR_POST 10490 : LdSize == 2 ? ARM::t2LDRH_POST 10491 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 10492 return LdSize == 4 ? ARM::LDR_POST_IMM 10493 : LdSize == 2 ? ARM::LDRH_POST 10494 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 10495 } 10496 10497 /// Return the store opcode for a given store size. If store size >= 8, 10498 /// neon opcode will be returned. 10499 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 10500 if (StSize >= 8) 10501 return StSize == 16 ? ARM::VST1q32wb_fixed 10502 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 10503 if (IsThumb1) 10504 return StSize == 4 ? ARM::tSTRi 10505 : StSize == 2 ? ARM::tSTRHi 10506 : StSize == 1 ? ARM::tSTRBi : 0; 10507 if (IsThumb2) 10508 return StSize == 4 ? ARM::t2STR_POST 10509 : StSize == 2 ? ARM::t2STRH_POST 10510 : StSize == 1 ? ARM::t2STRB_POST : 0; 10511 return StSize == 4 ? ARM::STR_POST_IMM 10512 : StSize == 2 ? ARM::STRH_POST 10513 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 10514 } 10515 10516 /// Emit a post-increment load operation with given size. The instructions 10517 /// will be added to BB at Pos. 10518 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10519 const TargetInstrInfo *TII, const DebugLoc &dl, 10520 unsigned LdSize, unsigned Data, unsigned AddrIn, 10521 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10522 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 10523 assert(LdOpc != 0 && "Should have a load opcode"); 10524 if (LdSize >= 8) { 10525 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10526 .addReg(AddrOut, RegState::Define) 10527 .addReg(AddrIn) 10528 .addImm(0) 10529 .add(predOps(ARMCC::AL)); 10530 } else if (IsThumb1) { 10531 // load + update AddrIn 10532 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10533 .addReg(AddrIn) 10534 .addImm(0) 10535 .add(predOps(ARMCC::AL)); 10536 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10537 .add(t1CondCodeOp()) 10538 .addReg(AddrIn) 10539 .addImm(LdSize) 10540 .add(predOps(ARMCC::AL)); 10541 } else if (IsThumb2) { 10542 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10543 .addReg(AddrOut, RegState::Define) 10544 .addReg(AddrIn) 10545 .addImm(LdSize) 10546 .add(predOps(ARMCC::AL)); 10547 } else { // arm 10548 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10549 .addReg(AddrOut, RegState::Define) 10550 .addReg(AddrIn) 10551 .addReg(0) 10552 .addImm(LdSize) 10553 .add(predOps(ARMCC::AL)); 10554 } 10555 } 10556 10557 /// Emit a post-increment store operation with given size. The instructions 10558 /// will be added to BB at Pos. 10559 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10560 const TargetInstrInfo *TII, const DebugLoc &dl, 10561 unsigned StSize, unsigned Data, unsigned AddrIn, 10562 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10563 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 10564 assert(StOpc != 0 && "Should have a store opcode"); 10565 if (StSize >= 8) { 10566 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10567 .addReg(AddrIn) 10568 .addImm(0) 10569 .addReg(Data) 10570 .add(predOps(ARMCC::AL)); 10571 } else if (IsThumb1) { 10572 // store + update AddrIn 10573 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 10574 .addReg(Data) 10575 .addReg(AddrIn) 10576 .addImm(0) 10577 .add(predOps(ARMCC::AL)); 10578 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10579 .add(t1CondCodeOp()) 10580 .addReg(AddrIn) 10581 .addImm(StSize) 10582 .add(predOps(ARMCC::AL)); 10583 } else if (IsThumb2) { 10584 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10585 .addReg(Data) 10586 .addReg(AddrIn) 10587 .addImm(StSize) 10588 .add(predOps(ARMCC::AL)); 10589 } else { // arm 10590 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10591 .addReg(Data) 10592 .addReg(AddrIn) 10593 .addReg(0) 10594 .addImm(StSize) 10595 .add(predOps(ARMCC::AL)); 10596 } 10597 } 10598 10599 MachineBasicBlock * 10600 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 10601 MachineBasicBlock *BB) const { 10602 // This pseudo instruction has 3 operands: dst, src, size 10603 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 10604 // Otherwise, we will generate unrolled scalar copies. 10605 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10606 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10607 MachineFunction::iterator It = ++BB->getIterator(); 10608 10609 Register dest = MI.getOperand(0).getReg(); 10610 Register src = MI.getOperand(1).getReg(); 10611 unsigned SizeVal = MI.getOperand(2).getImm(); 10612 unsigned Alignment = MI.getOperand(3).getImm(); 10613 DebugLoc dl = MI.getDebugLoc(); 10614 10615 MachineFunction *MF = BB->getParent(); 10616 MachineRegisterInfo &MRI = MF->getRegInfo(); 10617 unsigned UnitSize = 0; 10618 const TargetRegisterClass *TRC = nullptr; 10619 const TargetRegisterClass *VecTRC = nullptr; 10620 10621 bool IsThumb1 = Subtarget->isThumb1Only(); 10622 bool IsThumb2 = Subtarget->isThumb2(); 10623 bool IsThumb = Subtarget->isThumb(); 10624 10625 if (Alignment & 1) { 10626 UnitSize = 1; 10627 } else if (Alignment & 2) { 10628 UnitSize = 2; 10629 } else { 10630 // Check whether we can use NEON instructions. 10631 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 10632 Subtarget->hasNEON()) { 10633 if ((Alignment % 16 == 0) && SizeVal >= 16) 10634 UnitSize = 16; 10635 else if ((Alignment % 8 == 0) && SizeVal >= 8) 10636 UnitSize = 8; 10637 } 10638 // Can't use NEON instructions. 10639 if (UnitSize == 0) 10640 UnitSize = 4; 10641 } 10642 10643 // Select the correct opcode and register class for unit size load/store 10644 bool IsNeon = UnitSize >= 8; 10645 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 10646 if (IsNeon) 10647 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 10648 : UnitSize == 8 ? &ARM::DPRRegClass 10649 : nullptr; 10650 10651 unsigned BytesLeft = SizeVal % UnitSize; 10652 unsigned LoopSize = SizeVal - BytesLeft; 10653 10654 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 10655 // Use LDR and STR to copy. 10656 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 10657 // [destOut] = STR_POST(scratch, destIn, UnitSize) 10658 unsigned srcIn = src; 10659 unsigned destIn = dest; 10660 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 10661 Register srcOut = MRI.createVirtualRegister(TRC); 10662 Register destOut = MRI.createVirtualRegister(TRC); 10663 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10664 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 10665 IsThumb1, IsThumb2); 10666 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 10667 IsThumb1, IsThumb2); 10668 srcIn = srcOut; 10669 destIn = destOut; 10670 } 10671 10672 // Handle the leftover bytes with LDRB and STRB. 10673 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 10674 // [destOut] = STRB_POST(scratch, destIn, 1) 10675 for (unsigned i = 0; i < BytesLeft; i++) { 10676 Register srcOut = MRI.createVirtualRegister(TRC); 10677 Register destOut = MRI.createVirtualRegister(TRC); 10678 Register scratch = MRI.createVirtualRegister(TRC); 10679 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 10680 IsThumb1, IsThumb2); 10681 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 10682 IsThumb1, IsThumb2); 10683 srcIn = srcOut; 10684 destIn = destOut; 10685 } 10686 MI.eraseFromParent(); // The instruction is gone now. 10687 return BB; 10688 } 10689 10690 // Expand the pseudo op to a loop. 10691 // thisMBB: 10692 // ... 10693 // movw varEnd, # --> with thumb2 10694 // movt varEnd, # 10695 // ldrcp varEnd, idx --> without thumb2 10696 // fallthrough --> loopMBB 10697 // loopMBB: 10698 // PHI varPhi, varEnd, varLoop 10699 // PHI srcPhi, src, srcLoop 10700 // PHI destPhi, dst, destLoop 10701 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10702 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 10703 // subs varLoop, varPhi, #UnitSize 10704 // bne loopMBB 10705 // fallthrough --> exitMBB 10706 // exitMBB: 10707 // epilogue to handle left-over bytes 10708 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10709 // [destOut] = STRB_POST(scratch, destLoop, 1) 10710 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10711 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10712 MF->insert(It, loopMBB); 10713 MF->insert(It, exitMBB); 10714 10715 // Transfer the remainder of BB and its successor edges to exitMBB. 10716 exitMBB->splice(exitMBB->begin(), BB, 10717 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10718 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10719 10720 // Load an immediate to varEnd. 10721 Register varEnd = MRI.createVirtualRegister(TRC); 10722 if (Subtarget->useMovt()) { 10723 unsigned Vtmp = varEnd; 10724 if ((LoopSize & 0xFFFF0000) != 0) 10725 Vtmp = MRI.createVirtualRegister(TRC); 10726 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 10727 .addImm(LoopSize & 0xFFFF) 10728 .add(predOps(ARMCC::AL)); 10729 10730 if ((LoopSize & 0xFFFF0000) != 0) 10731 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 10732 .addReg(Vtmp) 10733 .addImm(LoopSize >> 16) 10734 .add(predOps(ARMCC::AL)); 10735 } else { 10736 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10737 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10738 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 10739 10740 // MachineConstantPool wants an explicit alignment. 10741 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10742 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10743 MachineMemOperand *CPMMO = 10744 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 10745 MachineMemOperand::MOLoad, 4, Align(4)); 10746 10747 if (IsThumb) 10748 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 10749 .addReg(varEnd, RegState::Define) 10750 .addConstantPoolIndex(Idx) 10751 .add(predOps(ARMCC::AL)) 10752 .addMemOperand(CPMMO); 10753 else 10754 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 10755 .addReg(varEnd, RegState::Define) 10756 .addConstantPoolIndex(Idx) 10757 .addImm(0) 10758 .add(predOps(ARMCC::AL)) 10759 .addMemOperand(CPMMO); 10760 } 10761 BB->addSuccessor(loopMBB); 10762 10763 // Generate the loop body: 10764 // varPhi = PHI(varLoop, varEnd) 10765 // srcPhi = PHI(srcLoop, src) 10766 // destPhi = PHI(destLoop, dst) 10767 MachineBasicBlock *entryBB = BB; 10768 BB = loopMBB; 10769 Register varLoop = MRI.createVirtualRegister(TRC); 10770 Register varPhi = MRI.createVirtualRegister(TRC); 10771 Register srcLoop = MRI.createVirtualRegister(TRC); 10772 Register srcPhi = MRI.createVirtualRegister(TRC); 10773 Register destLoop = MRI.createVirtualRegister(TRC); 10774 Register destPhi = MRI.createVirtualRegister(TRC); 10775 10776 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 10777 .addReg(varLoop).addMBB(loopMBB) 10778 .addReg(varEnd).addMBB(entryBB); 10779 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 10780 .addReg(srcLoop).addMBB(loopMBB) 10781 .addReg(src).addMBB(entryBB); 10782 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 10783 .addReg(destLoop).addMBB(loopMBB) 10784 .addReg(dest).addMBB(entryBB); 10785 10786 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10787 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 10788 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10789 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 10790 IsThumb1, IsThumb2); 10791 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 10792 IsThumb1, IsThumb2); 10793 10794 // Decrement loop variable by UnitSize. 10795 if (IsThumb1) { 10796 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 10797 .add(t1CondCodeOp()) 10798 .addReg(varPhi) 10799 .addImm(UnitSize) 10800 .add(predOps(ARMCC::AL)); 10801 } else { 10802 MachineInstrBuilder MIB = 10803 BuildMI(*BB, BB->end(), dl, 10804 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 10805 MIB.addReg(varPhi) 10806 .addImm(UnitSize) 10807 .add(predOps(ARMCC::AL)) 10808 .add(condCodeOp()); 10809 MIB->getOperand(5).setReg(ARM::CPSR); 10810 MIB->getOperand(5).setIsDef(true); 10811 } 10812 BuildMI(*BB, BB->end(), dl, 10813 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10814 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 10815 10816 // loopMBB can loop back to loopMBB or fall through to exitMBB. 10817 BB->addSuccessor(loopMBB); 10818 BB->addSuccessor(exitMBB); 10819 10820 // Add epilogue to handle BytesLeft. 10821 BB = exitMBB; 10822 auto StartOfExit = exitMBB->begin(); 10823 10824 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10825 // [destOut] = STRB_POST(scratch, destLoop, 1) 10826 unsigned srcIn = srcLoop; 10827 unsigned destIn = destLoop; 10828 for (unsigned i = 0; i < BytesLeft; i++) { 10829 Register srcOut = MRI.createVirtualRegister(TRC); 10830 Register destOut = MRI.createVirtualRegister(TRC); 10831 Register scratch = MRI.createVirtualRegister(TRC); 10832 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 10833 IsThumb1, IsThumb2); 10834 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 10835 IsThumb1, IsThumb2); 10836 srcIn = srcOut; 10837 destIn = destOut; 10838 } 10839 10840 MI.eraseFromParent(); // The instruction is gone now. 10841 return BB; 10842 } 10843 10844 MachineBasicBlock * 10845 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 10846 MachineBasicBlock *MBB) const { 10847 const TargetMachine &TM = getTargetMachine(); 10848 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 10849 DebugLoc DL = MI.getDebugLoc(); 10850 10851 assert(Subtarget->isTargetWindows() && 10852 "__chkstk is only supported on Windows"); 10853 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 10854 10855 // __chkstk takes the number of words to allocate on the stack in R4, and 10856 // returns the stack adjustment in number of bytes in R4. This will not 10857 // clober any other registers (other than the obvious lr). 10858 // 10859 // Although, technically, IP should be considered a register which may be 10860 // clobbered, the call itself will not touch it. Windows on ARM is a pure 10861 // thumb-2 environment, so there is no interworking required. As a result, we 10862 // do not expect a veneer to be emitted by the linker, clobbering IP. 10863 // 10864 // Each module receives its own copy of __chkstk, so no import thunk is 10865 // required, again, ensuring that IP is not clobbered. 10866 // 10867 // Finally, although some linkers may theoretically provide a trampoline for 10868 // out of range calls (which is quite common due to a 32M range limitation of 10869 // branches for Thumb), we can generate the long-call version via 10870 // -mcmodel=large, alleviating the need for the trampoline which may clobber 10871 // IP. 10872 10873 switch (TM.getCodeModel()) { 10874 case CodeModel::Tiny: 10875 llvm_unreachable("Tiny code model not available on ARM."); 10876 case CodeModel::Small: 10877 case CodeModel::Medium: 10878 case CodeModel::Kernel: 10879 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 10880 .add(predOps(ARMCC::AL)) 10881 .addExternalSymbol("__chkstk") 10882 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10883 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10884 .addReg(ARM::R12, 10885 RegState::Implicit | RegState::Define | RegState::Dead) 10886 .addReg(ARM::CPSR, 10887 RegState::Implicit | RegState::Define | RegState::Dead); 10888 break; 10889 case CodeModel::Large: { 10890 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 10891 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 10892 10893 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 10894 .addExternalSymbol("__chkstk"); 10895 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 10896 .add(predOps(ARMCC::AL)) 10897 .addReg(Reg, RegState::Kill) 10898 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10899 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10900 .addReg(ARM::R12, 10901 RegState::Implicit | RegState::Define | RegState::Dead) 10902 .addReg(ARM::CPSR, 10903 RegState::Implicit | RegState::Define | RegState::Dead); 10904 break; 10905 } 10906 } 10907 10908 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 10909 .addReg(ARM::SP, RegState::Kill) 10910 .addReg(ARM::R4, RegState::Kill) 10911 .setMIFlags(MachineInstr::FrameSetup) 10912 .add(predOps(ARMCC::AL)) 10913 .add(condCodeOp()); 10914 10915 MI.eraseFromParent(); 10916 return MBB; 10917 } 10918 10919 MachineBasicBlock * 10920 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 10921 MachineBasicBlock *MBB) const { 10922 DebugLoc DL = MI.getDebugLoc(); 10923 MachineFunction *MF = MBB->getParent(); 10924 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10925 10926 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 10927 MF->insert(++MBB->getIterator(), ContBB); 10928 ContBB->splice(ContBB->begin(), MBB, 10929 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10930 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 10931 MBB->addSuccessor(ContBB); 10932 10933 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10934 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 10935 MF->push_back(TrapBB); 10936 MBB->addSuccessor(TrapBB); 10937 10938 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 10939 .addReg(MI.getOperand(0).getReg()) 10940 .addImm(0) 10941 .add(predOps(ARMCC::AL)); 10942 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 10943 .addMBB(TrapBB) 10944 .addImm(ARMCC::EQ) 10945 .addReg(ARM::CPSR); 10946 10947 MI.eraseFromParent(); 10948 return ContBB; 10949 } 10950 10951 // The CPSR operand of SelectItr might be missing a kill marker 10952 // because there were multiple uses of CPSR, and ISel didn't know 10953 // which to mark. Figure out whether SelectItr should have had a 10954 // kill marker, and set it if it should. Returns the correct kill 10955 // marker value. 10956 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 10957 MachineBasicBlock* BB, 10958 const TargetRegisterInfo* TRI) { 10959 // Scan forward through BB for a use/def of CPSR. 10960 MachineBasicBlock::iterator miI(std::next(SelectItr)); 10961 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 10962 const MachineInstr& mi = *miI; 10963 if (mi.readsRegister(ARM::CPSR)) 10964 return false; 10965 if (mi.definesRegister(ARM::CPSR)) 10966 break; // Should have kill-flag - update below. 10967 } 10968 10969 // If we hit the end of the block, check whether CPSR is live into a 10970 // successor. 10971 if (miI == BB->end()) { 10972 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 10973 sEnd = BB->succ_end(); 10974 sItr != sEnd; ++sItr) { 10975 MachineBasicBlock* succ = *sItr; 10976 if (succ->isLiveIn(ARM::CPSR)) 10977 return false; 10978 } 10979 } 10980 10981 // We found a def, or hit the end of the basic block and CPSR wasn't live 10982 // out. SelectMI should have a kill flag on CPSR. 10983 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 10984 return true; 10985 } 10986 10987 MachineBasicBlock * 10988 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10989 MachineBasicBlock *BB) const { 10990 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10991 DebugLoc dl = MI.getDebugLoc(); 10992 bool isThumb2 = Subtarget->isThumb2(); 10993 switch (MI.getOpcode()) { 10994 default: { 10995 MI.print(errs()); 10996 llvm_unreachable("Unexpected instr type to insert"); 10997 } 10998 10999 // Thumb1 post-indexed loads are really just single-register LDMs. 11000 case ARM::tLDR_postidx: { 11001 MachineOperand Def(MI.getOperand(1)); 11002 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 11003 .add(Def) // Rn_wb 11004 .add(MI.getOperand(2)) // Rn 11005 .add(MI.getOperand(3)) // PredImm 11006 .add(MI.getOperand(4)) // PredReg 11007 .add(MI.getOperand(0)) // Rt 11008 .cloneMemRefs(MI); 11009 MI.eraseFromParent(); 11010 return BB; 11011 } 11012 11013 // The Thumb2 pre-indexed stores have the same MI operands, they just 11014 // define them differently in the .td files from the isel patterns, so 11015 // they need pseudos. 11016 case ARM::t2STR_preidx: 11017 MI.setDesc(TII->get(ARM::t2STR_PRE)); 11018 return BB; 11019 case ARM::t2STRB_preidx: 11020 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 11021 return BB; 11022 case ARM::t2STRH_preidx: 11023 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 11024 return BB; 11025 11026 case ARM::STRi_preidx: 11027 case ARM::STRBi_preidx: { 11028 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 11029 : ARM::STRB_PRE_IMM; 11030 // Decode the offset. 11031 unsigned Offset = MI.getOperand(4).getImm(); 11032 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 11033 Offset = ARM_AM::getAM2Offset(Offset); 11034 if (isSub) 11035 Offset = -Offset; 11036 11037 MachineMemOperand *MMO = *MI.memoperands_begin(); 11038 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 11039 .add(MI.getOperand(0)) // Rn_wb 11040 .add(MI.getOperand(1)) // Rt 11041 .add(MI.getOperand(2)) // Rn 11042 .addImm(Offset) // offset (skip GPR==zero_reg) 11043 .add(MI.getOperand(5)) // pred 11044 .add(MI.getOperand(6)) 11045 .addMemOperand(MMO); 11046 MI.eraseFromParent(); 11047 return BB; 11048 } 11049 case ARM::STRr_preidx: 11050 case ARM::STRBr_preidx: 11051 case ARM::STRH_preidx: { 11052 unsigned NewOpc; 11053 switch (MI.getOpcode()) { 11054 default: llvm_unreachable("unexpected opcode!"); 11055 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 11056 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 11057 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 11058 } 11059 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 11060 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 11061 MIB.add(MI.getOperand(i)); 11062 MI.eraseFromParent(); 11063 return BB; 11064 } 11065 11066 case ARM::tMOVCCr_pseudo: { 11067 // To "insert" a SELECT_CC instruction, we actually have to insert the 11068 // diamond control-flow pattern. The incoming instruction knows the 11069 // destination vreg to set, the condition code register to branch on, the 11070 // true/false values to select between, and a branch opcode to use. 11071 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11072 MachineFunction::iterator It = ++BB->getIterator(); 11073 11074 // thisMBB: 11075 // ... 11076 // TrueVal = ... 11077 // cmpTY ccX, r1, r2 11078 // bCC copy1MBB 11079 // fallthrough --> copy0MBB 11080 MachineBasicBlock *thisMBB = BB; 11081 MachineFunction *F = BB->getParent(); 11082 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11083 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11084 F->insert(It, copy0MBB); 11085 F->insert(It, sinkMBB); 11086 11087 // Check whether CPSR is live past the tMOVCCr_pseudo. 11088 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11089 if (!MI.killsRegister(ARM::CPSR) && 11090 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 11091 copy0MBB->addLiveIn(ARM::CPSR); 11092 sinkMBB->addLiveIn(ARM::CPSR); 11093 } 11094 11095 // Transfer the remainder of BB and its successor edges to sinkMBB. 11096 sinkMBB->splice(sinkMBB->begin(), BB, 11097 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11098 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11099 11100 BB->addSuccessor(copy0MBB); 11101 BB->addSuccessor(sinkMBB); 11102 11103 BuildMI(BB, dl, TII->get(ARM::tBcc)) 11104 .addMBB(sinkMBB) 11105 .addImm(MI.getOperand(3).getImm()) 11106 .addReg(MI.getOperand(4).getReg()); 11107 11108 // copy0MBB: 11109 // %FalseValue = ... 11110 // # fallthrough to sinkMBB 11111 BB = copy0MBB; 11112 11113 // Update machine-CFG edges 11114 BB->addSuccessor(sinkMBB); 11115 11116 // sinkMBB: 11117 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11118 // ... 11119 BB = sinkMBB; 11120 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 11121 .addReg(MI.getOperand(1).getReg()) 11122 .addMBB(copy0MBB) 11123 .addReg(MI.getOperand(2).getReg()) 11124 .addMBB(thisMBB); 11125 11126 MI.eraseFromParent(); // The pseudo instruction is gone now. 11127 return BB; 11128 } 11129 11130 case ARM::BCCi64: 11131 case ARM::BCCZi64: { 11132 // If there is an unconditional branch to the other successor, remove it. 11133 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11134 11135 // Compare both parts that make up the double comparison separately for 11136 // equality. 11137 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 11138 11139 Register LHS1 = MI.getOperand(1).getReg(); 11140 Register LHS2 = MI.getOperand(2).getReg(); 11141 if (RHSisZero) { 11142 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11143 .addReg(LHS1) 11144 .addImm(0) 11145 .add(predOps(ARMCC::AL)); 11146 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11147 .addReg(LHS2).addImm(0) 11148 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 11149 } else { 11150 Register RHS1 = MI.getOperand(3).getReg(); 11151 Register RHS2 = MI.getOperand(4).getReg(); 11152 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 11153 .addReg(LHS1) 11154 .addReg(RHS1) 11155 .add(predOps(ARMCC::AL)); 11156 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 11157 .addReg(LHS2).addReg(RHS2) 11158 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 11159 } 11160 11161 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 11162 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 11163 if (MI.getOperand(0).getImm() == ARMCC::NE) 11164 std::swap(destMBB, exitMBB); 11165 11166 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 11167 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 11168 if (isThumb2) 11169 BuildMI(BB, dl, TII->get(ARM::t2B)) 11170 .addMBB(exitMBB) 11171 .add(predOps(ARMCC::AL)); 11172 else 11173 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 11174 11175 MI.eraseFromParent(); // The pseudo instruction is gone now. 11176 return BB; 11177 } 11178 11179 case ARM::Int_eh_sjlj_setjmp: 11180 case ARM::Int_eh_sjlj_setjmp_nofp: 11181 case ARM::tInt_eh_sjlj_setjmp: 11182 case ARM::t2Int_eh_sjlj_setjmp: 11183 case ARM::t2Int_eh_sjlj_setjmp_nofp: 11184 return BB; 11185 11186 case ARM::Int_eh_sjlj_setup_dispatch: 11187 EmitSjLjDispatchBlock(MI, BB); 11188 return BB; 11189 11190 case ARM::ABS: 11191 case ARM::t2ABS: { 11192 // To insert an ABS instruction, we have to insert the 11193 // diamond control-flow pattern. The incoming instruction knows the 11194 // source vreg to test against 0, the destination vreg to set, 11195 // the condition code register to branch on, the 11196 // true/false values to select between, and a branch opcode to use. 11197 // It transforms 11198 // V1 = ABS V0 11199 // into 11200 // V2 = MOVS V0 11201 // BCC (branch to SinkBB if V0 >= 0) 11202 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 11203 // SinkBB: V1 = PHI(V2, V3) 11204 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11205 MachineFunction::iterator BBI = ++BB->getIterator(); 11206 MachineFunction *Fn = BB->getParent(); 11207 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 11208 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 11209 Fn->insert(BBI, RSBBB); 11210 Fn->insert(BBI, SinkBB); 11211 11212 Register ABSSrcReg = MI.getOperand(1).getReg(); 11213 Register ABSDstReg = MI.getOperand(0).getReg(); 11214 bool ABSSrcKIll = MI.getOperand(1).isKill(); 11215 bool isThumb2 = Subtarget->isThumb2(); 11216 MachineRegisterInfo &MRI = Fn->getRegInfo(); 11217 // In Thumb mode S must not be specified if source register is the SP or 11218 // PC and if destination register is the SP, so restrict register class 11219 Register NewRsbDstReg = MRI.createVirtualRegister( 11220 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 11221 11222 // Transfer the remainder of BB and its successor edges to sinkMBB. 11223 SinkBB->splice(SinkBB->begin(), BB, 11224 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11225 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 11226 11227 BB->addSuccessor(RSBBB); 11228 BB->addSuccessor(SinkBB); 11229 11230 // fall through to SinkMBB 11231 RSBBB->addSuccessor(SinkBB); 11232 11233 // insert a cmp at the end of BB 11234 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11235 .addReg(ABSSrcReg) 11236 .addImm(0) 11237 .add(predOps(ARMCC::AL)); 11238 11239 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 11240 BuildMI(BB, dl, 11241 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 11242 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 11243 11244 // insert rsbri in RSBBB 11245 // Note: BCC and rsbri will be converted into predicated rsbmi 11246 // by if-conversion pass 11247 BuildMI(*RSBBB, RSBBB->begin(), dl, 11248 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 11249 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 11250 .addImm(0) 11251 .add(predOps(ARMCC::AL)) 11252 .add(condCodeOp()); 11253 11254 // insert PHI in SinkBB, 11255 // reuse ABSDstReg to not change uses of ABS instruction 11256 BuildMI(*SinkBB, SinkBB->begin(), dl, 11257 TII->get(ARM::PHI), ABSDstReg) 11258 .addReg(NewRsbDstReg).addMBB(RSBBB) 11259 .addReg(ABSSrcReg).addMBB(BB); 11260 11261 // remove ABS instruction 11262 MI.eraseFromParent(); 11263 11264 // return last added BB 11265 return SinkBB; 11266 } 11267 case ARM::COPY_STRUCT_BYVAL_I32: 11268 ++NumLoopByVals; 11269 return EmitStructByval(MI, BB); 11270 case ARM::WIN__CHKSTK: 11271 return EmitLowered__chkstk(MI, BB); 11272 case ARM::WIN__DBZCHK: 11273 return EmitLowered__dbzchk(MI, BB); 11274 } 11275 } 11276 11277 /// Attaches vregs to MEMCPY that it will use as scratch registers 11278 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 11279 /// instead of as a custom inserter because we need the use list from the SDNode. 11280 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 11281 MachineInstr &MI, const SDNode *Node) { 11282 bool isThumb1 = Subtarget->isThumb1Only(); 11283 11284 DebugLoc DL = MI.getDebugLoc(); 11285 MachineFunction *MF = MI.getParent()->getParent(); 11286 MachineRegisterInfo &MRI = MF->getRegInfo(); 11287 MachineInstrBuilder MIB(*MF, MI); 11288 11289 // If the new dst/src is unused mark it as dead. 11290 if (!Node->hasAnyUseOfValue(0)) { 11291 MI.getOperand(0).setIsDead(true); 11292 } 11293 if (!Node->hasAnyUseOfValue(1)) { 11294 MI.getOperand(1).setIsDead(true); 11295 } 11296 11297 // The MEMCPY both defines and kills the scratch registers. 11298 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 11299 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 11300 : &ARM::GPRRegClass); 11301 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 11302 } 11303 } 11304 11305 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11306 SDNode *Node) const { 11307 if (MI.getOpcode() == ARM::MEMCPY) { 11308 attachMEMCPYScratchRegs(Subtarget, MI, Node); 11309 return; 11310 } 11311 11312 const MCInstrDesc *MCID = &MI.getDesc(); 11313 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 11314 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 11315 // operand is still set to noreg. If needed, set the optional operand's 11316 // register to CPSR, and remove the redundant implicit def. 11317 // 11318 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 11319 11320 // Rename pseudo opcodes. 11321 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 11322 unsigned ccOutIdx; 11323 if (NewOpc) { 11324 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 11325 MCID = &TII->get(NewOpc); 11326 11327 assert(MCID->getNumOperands() == 11328 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 11329 && "converted opcode should be the same except for cc_out" 11330 " (and, on Thumb1, pred)"); 11331 11332 MI.setDesc(*MCID); 11333 11334 // Add the optional cc_out operand 11335 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 11336 11337 // On Thumb1, move all input operands to the end, then add the predicate 11338 if (Subtarget->isThumb1Only()) { 11339 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 11340 MI.addOperand(MI.getOperand(1)); 11341 MI.RemoveOperand(1); 11342 } 11343 11344 // Restore the ties 11345 for (unsigned i = MI.getNumOperands(); i--;) { 11346 const MachineOperand& op = MI.getOperand(i); 11347 if (op.isReg() && op.isUse()) { 11348 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 11349 if (DefIdx != -1) 11350 MI.tieOperands(DefIdx, i); 11351 } 11352 } 11353 11354 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 11355 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 11356 ccOutIdx = 1; 11357 } else 11358 ccOutIdx = MCID->getNumOperands() - 1; 11359 } else 11360 ccOutIdx = MCID->getNumOperands() - 1; 11361 11362 // Any ARM instruction that sets the 's' bit should specify an optional 11363 // "cc_out" operand in the last operand position. 11364 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 11365 assert(!NewOpc && "Optional cc_out operand required"); 11366 return; 11367 } 11368 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 11369 // since we already have an optional CPSR def. 11370 bool definesCPSR = false; 11371 bool deadCPSR = false; 11372 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 11373 ++i) { 11374 const MachineOperand &MO = MI.getOperand(i); 11375 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 11376 definesCPSR = true; 11377 if (MO.isDead()) 11378 deadCPSR = true; 11379 MI.RemoveOperand(i); 11380 break; 11381 } 11382 } 11383 if (!definesCPSR) { 11384 assert(!NewOpc && "Optional cc_out operand required"); 11385 return; 11386 } 11387 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 11388 if (deadCPSR) { 11389 assert(!MI.getOperand(ccOutIdx).getReg() && 11390 "expect uninitialized optional cc_out operand"); 11391 // Thumb1 instructions must have the S bit even if the CPSR is dead. 11392 if (!Subtarget->isThumb1Only()) 11393 return; 11394 } 11395 11396 // If this instruction was defined with an optional CPSR def and its dag node 11397 // had a live implicit CPSR def, then activate the optional CPSR def. 11398 MachineOperand &MO = MI.getOperand(ccOutIdx); 11399 MO.setReg(ARM::CPSR); 11400 MO.setIsDef(true); 11401 } 11402 11403 //===----------------------------------------------------------------------===// 11404 // ARM Optimization Hooks 11405 //===----------------------------------------------------------------------===// 11406 11407 // Helper function that checks if N is a null or all ones constant. 11408 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 11409 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 11410 } 11411 11412 // Return true if N is conditionally 0 or all ones. 11413 // Detects these expressions where cc is an i1 value: 11414 // 11415 // (select cc 0, y) [AllOnes=0] 11416 // (select cc y, 0) [AllOnes=0] 11417 // (zext cc) [AllOnes=0] 11418 // (sext cc) [AllOnes=0/1] 11419 // (select cc -1, y) [AllOnes=1] 11420 // (select cc y, -1) [AllOnes=1] 11421 // 11422 // Invert is set when N is the null/all ones constant when CC is false. 11423 // OtherOp is set to the alternative value of N. 11424 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 11425 SDValue &CC, bool &Invert, 11426 SDValue &OtherOp, 11427 SelectionDAG &DAG) { 11428 switch (N->getOpcode()) { 11429 default: return false; 11430 case ISD::SELECT: { 11431 CC = N->getOperand(0); 11432 SDValue N1 = N->getOperand(1); 11433 SDValue N2 = N->getOperand(2); 11434 if (isZeroOrAllOnes(N1, AllOnes)) { 11435 Invert = false; 11436 OtherOp = N2; 11437 return true; 11438 } 11439 if (isZeroOrAllOnes(N2, AllOnes)) { 11440 Invert = true; 11441 OtherOp = N1; 11442 return true; 11443 } 11444 return false; 11445 } 11446 case ISD::ZERO_EXTEND: 11447 // (zext cc) can never be the all ones value. 11448 if (AllOnes) 11449 return false; 11450 LLVM_FALLTHROUGH; 11451 case ISD::SIGN_EXTEND: { 11452 SDLoc dl(N); 11453 EVT VT = N->getValueType(0); 11454 CC = N->getOperand(0); 11455 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 11456 return false; 11457 Invert = !AllOnes; 11458 if (AllOnes) 11459 // When looking for an AllOnes constant, N is an sext, and the 'other' 11460 // value is 0. 11461 OtherOp = DAG.getConstant(0, dl, VT); 11462 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11463 // When looking for a 0 constant, N can be zext or sext. 11464 OtherOp = DAG.getConstant(1, dl, VT); 11465 else 11466 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 11467 VT); 11468 return true; 11469 } 11470 } 11471 } 11472 11473 // Combine a constant select operand into its use: 11474 // 11475 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11476 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11477 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 11478 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11479 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11480 // 11481 // The transform is rejected if the select doesn't have a constant operand that 11482 // is null, or all ones when AllOnes is set. 11483 // 11484 // Also recognize sext/zext from i1: 11485 // 11486 // (add (zext cc), x) -> (select cc (add x, 1), x) 11487 // (add (sext cc), x) -> (select cc (add x, -1), x) 11488 // 11489 // These transformations eventually create predicated instructions. 11490 // 11491 // @param N The node to transform. 11492 // @param Slct The N operand that is a select. 11493 // @param OtherOp The other N operand (x above). 11494 // @param DCI Context. 11495 // @param AllOnes Require the select constant to be all ones instead of null. 11496 // @returns The new node, or SDValue() on failure. 11497 static 11498 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 11499 TargetLowering::DAGCombinerInfo &DCI, 11500 bool AllOnes = false) { 11501 SelectionDAG &DAG = DCI.DAG; 11502 EVT VT = N->getValueType(0); 11503 SDValue NonConstantVal; 11504 SDValue CCOp; 11505 bool SwapSelectOps; 11506 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 11507 NonConstantVal, DAG)) 11508 return SDValue(); 11509 11510 // Slct is now know to be the desired identity constant when CC is true. 11511 SDValue TrueVal = OtherOp; 11512 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 11513 OtherOp, NonConstantVal); 11514 // Unless SwapSelectOps says CC should be false. 11515 if (SwapSelectOps) 11516 std::swap(TrueVal, FalseVal); 11517 11518 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 11519 CCOp, TrueVal, FalseVal); 11520 } 11521 11522 // Attempt combineSelectAndUse on each operand of a commutative operator N. 11523 static 11524 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 11525 TargetLowering::DAGCombinerInfo &DCI) { 11526 SDValue N0 = N->getOperand(0); 11527 SDValue N1 = N->getOperand(1); 11528 if (N0.getNode()->hasOneUse()) 11529 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 11530 return Result; 11531 if (N1.getNode()->hasOneUse()) 11532 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 11533 return Result; 11534 return SDValue(); 11535 } 11536 11537 static bool IsVUZPShuffleNode(SDNode *N) { 11538 // VUZP shuffle node. 11539 if (N->getOpcode() == ARMISD::VUZP) 11540 return true; 11541 11542 // "VUZP" on i32 is an alias for VTRN. 11543 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 11544 return true; 11545 11546 return false; 11547 } 11548 11549 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 11550 TargetLowering::DAGCombinerInfo &DCI, 11551 const ARMSubtarget *Subtarget) { 11552 // Look for ADD(VUZP.0, VUZP.1). 11553 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 11554 N0 == N1) 11555 return SDValue(); 11556 11557 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 11558 if (!N->getValueType(0).is64BitVector()) 11559 return SDValue(); 11560 11561 // Generate vpadd. 11562 SelectionDAG &DAG = DCI.DAG; 11563 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11564 SDLoc dl(N); 11565 SDNode *Unzip = N0.getNode(); 11566 EVT VT = N->getValueType(0); 11567 11568 SmallVector<SDValue, 8> Ops; 11569 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 11570 TLI.getPointerTy(DAG.getDataLayout()))); 11571 Ops.push_back(Unzip->getOperand(0)); 11572 Ops.push_back(Unzip->getOperand(1)); 11573 11574 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11575 } 11576 11577 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11578 TargetLowering::DAGCombinerInfo &DCI, 11579 const ARMSubtarget *Subtarget) { 11580 // Check for two extended operands. 11581 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 11582 N1.getOpcode() == ISD::SIGN_EXTEND) && 11583 !(N0.getOpcode() == ISD::ZERO_EXTEND && 11584 N1.getOpcode() == ISD::ZERO_EXTEND)) 11585 return SDValue(); 11586 11587 SDValue N00 = N0.getOperand(0); 11588 SDValue N10 = N1.getOperand(0); 11589 11590 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 11591 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 11592 N00 == N10) 11593 return SDValue(); 11594 11595 // We only recognize Q register paddl here; this can't be reached until 11596 // after type legalization. 11597 if (!N00.getValueType().is64BitVector() || 11598 !N0.getValueType().is128BitVector()) 11599 return SDValue(); 11600 11601 // Generate vpaddl. 11602 SelectionDAG &DAG = DCI.DAG; 11603 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11604 SDLoc dl(N); 11605 EVT VT = N->getValueType(0); 11606 11607 SmallVector<SDValue, 8> Ops; 11608 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 11609 unsigned Opcode; 11610 if (N0.getOpcode() == ISD::SIGN_EXTEND) 11611 Opcode = Intrinsic::arm_neon_vpaddls; 11612 else 11613 Opcode = Intrinsic::arm_neon_vpaddlu; 11614 Ops.push_back(DAG.getConstant(Opcode, dl, 11615 TLI.getPointerTy(DAG.getDataLayout()))); 11616 EVT ElemTy = N00.getValueType().getVectorElementType(); 11617 unsigned NumElts = VT.getVectorNumElements(); 11618 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 11619 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 11620 N00.getOperand(0), N00.getOperand(1)); 11621 Ops.push_back(Concat); 11622 11623 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11624 } 11625 11626 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 11627 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 11628 // much easier to match. 11629 static SDValue 11630 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11631 TargetLowering::DAGCombinerInfo &DCI, 11632 const ARMSubtarget *Subtarget) { 11633 // Only perform optimization if after legalize, and if NEON is available. We 11634 // also expected both operands to be BUILD_VECTORs. 11635 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 11636 || N0.getOpcode() != ISD::BUILD_VECTOR 11637 || N1.getOpcode() != ISD::BUILD_VECTOR) 11638 return SDValue(); 11639 11640 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 11641 EVT VT = N->getValueType(0); 11642 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 11643 return SDValue(); 11644 11645 // Check that the vector operands are of the right form. 11646 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 11647 // operands, where N is the size of the formed vector. 11648 // Each EXTRACT_VECTOR should have the same input vector and odd or even 11649 // index such that we have a pair wise add pattern. 11650 11651 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 11652 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11653 return SDValue(); 11654 SDValue Vec = N0->getOperand(0)->getOperand(0); 11655 SDNode *V = Vec.getNode(); 11656 unsigned nextIndex = 0; 11657 11658 // For each operands to the ADD which are BUILD_VECTORs, 11659 // check to see if each of their operands are an EXTRACT_VECTOR with 11660 // the same vector and appropriate index. 11661 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 11662 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 11663 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11664 11665 SDValue ExtVec0 = N0->getOperand(i); 11666 SDValue ExtVec1 = N1->getOperand(i); 11667 11668 // First operand is the vector, verify its the same. 11669 if (V != ExtVec0->getOperand(0).getNode() || 11670 V != ExtVec1->getOperand(0).getNode()) 11671 return SDValue(); 11672 11673 // Second is the constant, verify its correct. 11674 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 11675 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 11676 11677 // For the constant, we want to see all the even or all the odd. 11678 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 11679 || C1->getZExtValue() != nextIndex+1) 11680 return SDValue(); 11681 11682 // Increment index. 11683 nextIndex+=2; 11684 } else 11685 return SDValue(); 11686 } 11687 11688 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 11689 // we're using the entire input vector, otherwise there's a size/legality 11690 // mismatch somewhere. 11691 if (nextIndex != Vec.getValueType().getVectorNumElements() || 11692 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 11693 return SDValue(); 11694 11695 // Create VPADDL node. 11696 SelectionDAG &DAG = DCI.DAG; 11697 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11698 11699 SDLoc dl(N); 11700 11701 // Build operand list. 11702 SmallVector<SDValue, 8> Ops; 11703 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 11704 TLI.getPointerTy(DAG.getDataLayout()))); 11705 11706 // Input is the vector. 11707 Ops.push_back(Vec); 11708 11709 // Get widened type and narrowed type. 11710 MVT widenType; 11711 unsigned numElem = VT.getVectorNumElements(); 11712 11713 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 11714 switch (inputLaneType.getSimpleVT().SimpleTy) { 11715 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 11716 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 11717 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 11718 default: 11719 llvm_unreachable("Invalid vector element type for padd optimization."); 11720 } 11721 11722 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 11723 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 11724 return DAG.getNode(ExtOp, dl, VT, tmp); 11725 } 11726 11727 static SDValue findMUL_LOHI(SDValue V) { 11728 if (V->getOpcode() == ISD::UMUL_LOHI || 11729 V->getOpcode() == ISD::SMUL_LOHI) 11730 return V; 11731 return SDValue(); 11732 } 11733 11734 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 11735 TargetLowering::DAGCombinerInfo &DCI, 11736 const ARMSubtarget *Subtarget) { 11737 if (!Subtarget->hasBaseDSP()) 11738 return SDValue(); 11739 11740 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 11741 // accumulates the product into a 64-bit value. The 16-bit values will 11742 // be sign extended somehow or SRA'd into 32-bit values 11743 // (addc (adde (mul 16bit, 16bit), lo), hi) 11744 SDValue Mul = AddcNode->getOperand(0); 11745 SDValue Lo = AddcNode->getOperand(1); 11746 if (Mul.getOpcode() != ISD::MUL) { 11747 Lo = AddcNode->getOperand(0); 11748 Mul = AddcNode->getOperand(1); 11749 if (Mul.getOpcode() != ISD::MUL) 11750 return SDValue(); 11751 } 11752 11753 SDValue SRA = AddeNode->getOperand(0); 11754 SDValue Hi = AddeNode->getOperand(1); 11755 if (SRA.getOpcode() != ISD::SRA) { 11756 SRA = AddeNode->getOperand(1); 11757 Hi = AddeNode->getOperand(0); 11758 if (SRA.getOpcode() != ISD::SRA) 11759 return SDValue(); 11760 } 11761 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 11762 if (Const->getZExtValue() != 31) 11763 return SDValue(); 11764 } else 11765 return SDValue(); 11766 11767 if (SRA.getOperand(0) != Mul) 11768 return SDValue(); 11769 11770 SelectionDAG &DAG = DCI.DAG; 11771 SDLoc dl(AddcNode); 11772 unsigned Opcode = 0; 11773 SDValue Op0; 11774 SDValue Op1; 11775 11776 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 11777 Opcode = ARMISD::SMLALBB; 11778 Op0 = Mul.getOperand(0); 11779 Op1 = Mul.getOperand(1); 11780 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 11781 Opcode = ARMISD::SMLALBT; 11782 Op0 = Mul.getOperand(0); 11783 Op1 = Mul.getOperand(1).getOperand(0); 11784 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 11785 Opcode = ARMISD::SMLALTB; 11786 Op0 = Mul.getOperand(0).getOperand(0); 11787 Op1 = Mul.getOperand(1); 11788 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 11789 Opcode = ARMISD::SMLALTT; 11790 Op0 = Mul->getOperand(0).getOperand(0); 11791 Op1 = Mul->getOperand(1).getOperand(0); 11792 } 11793 11794 if (!Op0 || !Op1) 11795 return SDValue(); 11796 11797 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 11798 Op0, Op1, Lo, Hi); 11799 // Replace the ADDs' nodes uses by the MLA node's values. 11800 SDValue HiMLALResult(SMLAL.getNode(), 1); 11801 SDValue LoMLALResult(SMLAL.getNode(), 0); 11802 11803 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 11804 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 11805 11806 // Return original node to notify the driver to stop replacing. 11807 SDValue resNode(AddcNode, 0); 11808 return resNode; 11809 } 11810 11811 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 11812 TargetLowering::DAGCombinerInfo &DCI, 11813 const ARMSubtarget *Subtarget) { 11814 // Look for multiply add opportunities. 11815 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 11816 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 11817 // a glue link from the first add to the second add. 11818 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 11819 // a S/UMLAL instruction. 11820 // UMUL_LOHI 11821 // / :lo \ :hi 11822 // V \ [no multiline comment] 11823 // loAdd -> ADDC | 11824 // \ :carry / 11825 // V V 11826 // ADDE <- hiAdd 11827 // 11828 // In the special case where only the higher part of a signed result is used 11829 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 11830 // a constant with the exact value of 0x80000000, we recognize we are dealing 11831 // with a "rounded multiply and add" (or subtract) and transform it into 11832 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 11833 11834 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 11835 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 11836 "Expect an ADDE or SUBE"); 11837 11838 assert(AddeSubeNode->getNumOperands() == 3 && 11839 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 11840 "ADDE node has the wrong inputs"); 11841 11842 // Check that we are chained to the right ADDC or SUBC node. 11843 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 11844 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 11845 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 11846 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 11847 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 11848 return SDValue(); 11849 11850 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 11851 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 11852 11853 // Check if the two operands are from the same mul_lohi node. 11854 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 11855 return SDValue(); 11856 11857 assert(AddcSubcNode->getNumValues() == 2 && 11858 AddcSubcNode->getValueType(0) == MVT::i32 && 11859 "Expect ADDC with two result values. First: i32"); 11860 11861 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 11862 // maybe a SMLAL which multiplies two 16-bit values. 11863 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 11864 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 11865 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 11866 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 11867 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 11868 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 11869 11870 // Check for the triangle shape. 11871 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 11872 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 11873 11874 // Make sure that the ADDE/SUBE operands are not coming from the same node. 11875 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 11876 return SDValue(); 11877 11878 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 11879 bool IsLeftOperandMUL = false; 11880 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 11881 if (MULOp == SDValue()) 11882 MULOp = findMUL_LOHI(AddeSubeOp1); 11883 else 11884 IsLeftOperandMUL = true; 11885 if (MULOp == SDValue()) 11886 return SDValue(); 11887 11888 // Figure out the right opcode. 11889 unsigned Opc = MULOp->getOpcode(); 11890 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 11891 11892 // Figure out the high and low input values to the MLAL node. 11893 SDValue *HiAddSub = nullptr; 11894 SDValue *LoMul = nullptr; 11895 SDValue *LowAddSub = nullptr; 11896 11897 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 11898 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 11899 return SDValue(); 11900 11901 if (IsLeftOperandMUL) 11902 HiAddSub = &AddeSubeOp1; 11903 else 11904 HiAddSub = &AddeSubeOp0; 11905 11906 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 11907 // whose low result is fed to the ADDC/SUBC we are checking. 11908 11909 if (AddcSubcOp0 == MULOp.getValue(0)) { 11910 LoMul = &AddcSubcOp0; 11911 LowAddSub = &AddcSubcOp1; 11912 } 11913 if (AddcSubcOp1 == MULOp.getValue(0)) { 11914 LoMul = &AddcSubcOp1; 11915 LowAddSub = &AddcSubcOp0; 11916 } 11917 11918 if (!LoMul) 11919 return SDValue(); 11920 11921 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 11922 // the replacement below will create a cycle. 11923 if (AddcSubcNode == HiAddSub->getNode() || 11924 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 11925 return SDValue(); 11926 11927 // Create the merged node. 11928 SelectionDAG &DAG = DCI.DAG; 11929 11930 // Start building operand list. 11931 SmallVector<SDValue, 8> Ops; 11932 Ops.push_back(LoMul->getOperand(0)); 11933 Ops.push_back(LoMul->getOperand(1)); 11934 11935 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 11936 // the case, we must be doing signed multiplication and only use the higher 11937 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 11938 // addition or subtraction with the value of 0x800000. 11939 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 11940 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 11941 LowAddSub->getNode()->getOpcode() == ISD::Constant && 11942 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 11943 0x80000000) { 11944 Ops.push_back(*HiAddSub); 11945 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 11946 FinalOpc = ARMISD::SMMLSR; 11947 } else { 11948 FinalOpc = ARMISD::SMMLAR; 11949 } 11950 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 11951 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 11952 11953 return SDValue(AddeSubeNode, 0); 11954 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 11955 // SMMLS is generated during instruction selection and the rest of this 11956 // function can not handle the case where AddcSubcNode is a SUBC. 11957 return SDValue(); 11958 11959 // Finish building the operand list for {U/S}MLAL 11960 Ops.push_back(*LowAddSub); 11961 Ops.push_back(*HiAddSub); 11962 11963 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 11964 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11965 11966 // Replace the ADDs' nodes uses by the MLA node's values. 11967 SDValue HiMLALResult(MLALNode.getNode(), 1); 11968 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 11969 11970 SDValue LoMLALResult(MLALNode.getNode(), 0); 11971 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 11972 11973 // Return original node to notify the driver to stop replacing. 11974 return SDValue(AddeSubeNode, 0); 11975 } 11976 11977 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 11978 TargetLowering::DAGCombinerInfo &DCI, 11979 const ARMSubtarget *Subtarget) { 11980 // UMAAL is similar to UMLAL except that it adds two unsigned values. 11981 // While trying to combine for the other MLAL nodes, first search for the 11982 // chance to use UMAAL. Check if Addc uses a node which has already 11983 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 11984 // as the addend, and it's handled in PerformUMLALCombine. 11985 11986 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11987 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11988 11989 // Check that we have a glued ADDC node. 11990 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 11991 if (AddcNode->getOpcode() != ARMISD::ADDC) 11992 return SDValue(); 11993 11994 // Find the converted UMAAL or quit if it doesn't exist. 11995 SDNode *UmlalNode = nullptr; 11996 SDValue AddHi; 11997 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 11998 UmlalNode = AddcNode->getOperand(0).getNode(); 11999 AddHi = AddcNode->getOperand(1); 12000 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 12001 UmlalNode = AddcNode->getOperand(1).getNode(); 12002 AddHi = AddcNode->getOperand(0); 12003 } else { 12004 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 12005 } 12006 12007 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 12008 // the ADDC as well as Zero. 12009 if (!isNullConstant(UmlalNode->getOperand(3))) 12010 return SDValue(); 12011 12012 if ((isNullConstant(AddeNode->getOperand(0)) && 12013 AddeNode->getOperand(1).getNode() == UmlalNode) || 12014 (AddeNode->getOperand(0).getNode() == UmlalNode && 12015 isNullConstant(AddeNode->getOperand(1)))) { 12016 SelectionDAG &DAG = DCI.DAG; 12017 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 12018 UmlalNode->getOperand(2), AddHi }; 12019 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 12020 DAG.getVTList(MVT::i32, MVT::i32), Ops); 12021 12022 // Replace the ADDs' nodes uses by the UMAAL node's values. 12023 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 12024 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 12025 12026 // Return original node to notify the driver to stop replacing. 12027 return SDValue(AddeNode, 0); 12028 } 12029 return SDValue(); 12030 } 12031 12032 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 12033 const ARMSubtarget *Subtarget) { 12034 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 12035 return SDValue(); 12036 12037 // Check that we have a pair of ADDC and ADDE as operands. 12038 // Both addends of the ADDE must be zero. 12039 SDNode* AddcNode = N->getOperand(2).getNode(); 12040 SDNode* AddeNode = N->getOperand(3).getNode(); 12041 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 12042 (AddeNode->getOpcode() == ARMISD::ADDE) && 12043 isNullConstant(AddeNode->getOperand(0)) && 12044 isNullConstant(AddeNode->getOperand(1)) && 12045 (AddeNode->getOperand(2).getNode() == AddcNode)) 12046 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 12047 DAG.getVTList(MVT::i32, MVT::i32), 12048 {N->getOperand(0), N->getOperand(1), 12049 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 12050 else 12051 return SDValue(); 12052 } 12053 12054 static SDValue PerformAddcSubcCombine(SDNode *N, 12055 TargetLowering::DAGCombinerInfo &DCI, 12056 const ARMSubtarget *Subtarget) { 12057 SelectionDAG &DAG(DCI.DAG); 12058 12059 if (N->getOpcode() == ARMISD::SUBC) { 12060 // (SUBC (ADDE 0, 0, C), 1) -> C 12061 SDValue LHS = N->getOperand(0); 12062 SDValue RHS = N->getOperand(1); 12063 if (LHS->getOpcode() == ARMISD::ADDE && 12064 isNullConstant(LHS->getOperand(0)) && 12065 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 12066 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 12067 } 12068 } 12069 12070 if (Subtarget->isThumb1Only()) { 12071 SDValue RHS = N->getOperand(1); 12072 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 12073 int32_t imm = C->getSExtValue(); 12074 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 12075 SDLoc DL(N); 12076 RHS = DAG.getConstant(-imm, DL, MVT::i32); 12077 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 12078 : ARMISD::ADDC; 12079 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 12080 } 12081 } 12082 } 12083 12084 return SDValue(); 12085 } 12086 12087 static SDValue PerformAddeSubeCombine(SDNode *N, 12088 TargetLowering::DAGCombinerInfo &DCI, 12089 const ARMSubtarget *Subtarget) { 12090 if (Subtarget->isThumb1Only()) { 12091 SelectionDAG &DAG = DCI.DAG; 12092 SDValue RHS = N->getOperand(1); 12093 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 12094 int64_t imm = C->getSExtValue(); 12095 if (imm < 0) { 12096 SDLoc DL(N); 12097 12098 // The with-carry-in form matches bitwise not instead of the negation. 12099 // Effectively, the inverse interpretation of the carry flag already 12100 // accounts for part of the negation. 12101 RHS = DAG.getConstant(~imm, DL, MVT::i32); 12102 12103 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 12104 : ARMISD::ADDE; 12105 return DAG.getNode(Opcode, DL, N->getVTList(), 12106 N->getOperand(0), RHS, N->getOperand(2)); 12107 } 12108 } 12109 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 12110 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 12111 } 12112 return SDValue(); 12113 } 12114 12115 static SDValue PerformVSELECTCombine(SDNode *N, 12116 TargetLowering::DAGCombinerInfo &DCI, 12117 const ARMSubtarget *Subtarget) { 12118 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs). 12119 // 12120 // We need to re-implement this optimization here as the implementation in the 12121 // Target-Independent DAGCombiner does not handle the kind of constant we make 12122 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for 12123 // good reason, allowing truncation there would break other targets). 12124 // 12125 // Currently, this is only done for MVE, as it's the only target that benefits 12126 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL). 12127 if (!Subtarget->hasMVEIntegerOps()) 12128 return SDValue(); 12129 12130 if (N->getOperand(0).getOpcode() != ISD::XOR) 12131 return SDValue(); 12132 SDValue XOR = N->getOperand(0); 12133 12134 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s. 12135 // It is important to check with truncation allowed as the BUILD_VECTORs we 12136 // generate in those situations will truncate their operands. 12137 ConstantSDNode *Const = 12138 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false, 12139 /*AllowTruncation*/ true); 12140 if (!Const || !Const->isOne()) 12141 return SDValue(); 12142 12143 // Rewrite into vselect(cond, rhs, lhs). 12144 SDValue Cond = XOR->getOperand(0); 12145 SDValue LHS = N->getOperand(1); 12146 SDValue RHS = N->getOperand(2); 12147 EVT Type = N->getValueType(0); 12148 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS); 12149 } 12150 12151 static SDValue PerformABSCombine(SDNode *N, 12152 TargetLowering::DAGCombinerInfo &DCI, 12153 const ARMSubtarget *Subtarget) { 12154 SDValue res; 12155 SelectionDAG &DAG = DCI.DAG; 12156 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12157 12158 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 12159 return SDValue(); 12160 12161 if (!TLI.expandABS(N, res, DAG)) 12162 return SDValue(); 12163 12164 return res; 12165 } 12166 12167 /// PerformADDECombine - Target-specific dag combine transform from 12168 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 12169 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 12170 static SDValue PerformADDECombine(SDNode *N, 12171 TargetLowering::DAGCombinerInfo &DCI, 12172 const ARMSubtarget *Subtarget) { 12173 // Only ARM and Thumb2 support UMLAL/SMLAL. 12174 if (Subtarget->isThumb1Only()) 12175 return PerformAddeSubeCombine(N, DCI, Subtarget); 12176 12177 // Only perform the checks after legalize when the pattern is available. 12178 if (DCI.isBeforeLegalize()) return SDValue(); 12179 12180 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 12181 } 12182 12183 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 12184 /// operands N0 and N1. This is a helper for PerformADDCombine that is 12185 /// called with the default operands, and if that fails, with commuted 12186 /// operands. 12187 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 12188 TargetLowering::DAGCombinerInfo &DCI, 12189 const ARMSubtarget *Subtarget){ 12190 // Attempt to create vpadd for this add. 12191 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 12192 return Result; 12193 12194 // Attempt to create vpaddl for this add. 12195 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 12196 return Result; 12197 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 12198 Subtarget)) 12199 return Result; 12200 12201 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 12202 if (N0.getNode()->hasOneUse()) 12203 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 12204 return Result; 12205 return SDValue(); 12206 } 12207 12208 static SDValue PerformADDVecReduce(SDNode *N, 12209 TargetLowering::DAGCombinerInfo &DCI, 12210 const ARMSubtarget *Subtarget) { 12211 if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64) 12212 return SDValue(); 12213 12214 SDValue N0 = N->getOperand(0); 12215 SDValue N1 = N->getOperand(1); 12216 12217 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this 12218 // will look like: 12219 // t1: i32,i32 = ARMISD::VADDLVs x 12220 // t2: i64 = build_pair t1, t1:1 12221 // t3: i64 = add t2, y 12222 // We also need to check for sext / zext and commutitive adds. 12223 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA, 12224 SDValue NB) { 12225 if (NB->getOpcode() != ISD::BUILD_PAIR) 12226 return SDValue(); 12227 SDValue VecRed = NB->getOperand(0); 12228 if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 || 12229 NB->getOperand(1) != SDValue(VecRed.getNode(), 1)) 12230 return SDValue(); 12231 12232 SDLoc dl(N); 12233 SmallVector<SDValue, 4> Ops; 12234 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 12235 DCI.DAG.getConstant(0, dl, MVT::i32))); 12236 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 12237 DCI.DAG.getConstant(1, dl, MVT::i32))); 12238 for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++) 12239 Ops.push_back(VecRed->getOperand(i)); 12240 SDValue Red = DCI.DAG.getNode(OpcodeA, dl, 12241 DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops); 12242 return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red, 12243 SDValue(Red.getNode(), 1)); 12244 }; 12245 12246 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1)) 12247 return M; 12248 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1)) 12249 return M; 12250 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0)) 12251 return M; 12252 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0)) 12253 return M; 12254 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1)) 12255 return M; 12256 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1)) 12257 return M; 12258 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0)) 12259 return M; 12260 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0)) 12261 return M; 12262 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1)) 12263 return M; 12264 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1)) 12265 return M; 12266 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0)) 12267 return M; 12268 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0)) 12269 return M; 12270 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1)) 12271 return M; 12272 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1)) 12273 return M; 12274 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0)) 12275 return M; 12276 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0)) 12277 return M; 12278 return SDValue(); 12279 } 12280 12281 bool 12282 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 12283 CombineLevel Level) const { 12284 if (Level == BeforeLegalizeTypes) 12285 return true; 12286 12287 if (N->getOpcode() != ISD::SHL) 12288 return true; 12289 12290 if (Subtarget->isThumb1Only()) { 12291 // Avoid making expensive immediates by commuting shifts. (This logic 12292 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 12293 // for free.) 12294 if (N->getOpcode() != ISD::SHL) 12295 return true; 12296 SDValue N1 = N->getOperand(0); 12297 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 12298 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 12299 return true; 12300 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 12301 if (Const->getAPIntValue().ult(256)) 12302 return false; 12303 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 12304 Const->getAPIntValue().sgt(-256)) 12305 return false; 12306 } 12307 return true; 12308 } 12309 12310 // Turn off commute-with-shift transform after legalization, so it doesn't 12311 // conflict with PerformSHLSimplify. (We could try to detect when 12312 // PerformSHLSimplify would trigger more precisely, but it isn't 12313 // really necessary.) 12314 return false; 12315 } 12316 12317 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 12318 const SDNode *N, CombineLevel Level) const { 12319 if (!Subtarget->isThumb1Only()) 12320 return true; 12321 12322 if (Level == BeforeLegalizeTypes) 12323 return true; 12324 12325 return false; 12326 } 12327 12328 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 12329 if (!Subtarget->hasNEON()) { 12330 if (Subtarget->isThumb1Only()) 12331 return VT.getScalarSizeInBits() <= 32; 12332 return true; 12333 } 12334 return VT.isScalarInteger(); 12335 } 12336 12337 static SDValue PerformSHLSimplify(SDNode *N, 12338 TargetLowering::DAGCombinerInfo &DCI, 12339 const ARMSubtarget *ST) { 12340 // Allow the generic combiner to identify potential bswaps. 12341 if (DCI.isBeforeLegalize()) 12342 return SDValue(); 12343 12344 // DAG combiner will fold: 12345 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 12346 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 12347 // Other code patterns that can be also be modified have the following form: 12348 // b + ((a << 1) | 510) 12349 // b + ((a << 1) & 510) 12350 // b + ((a << 1) ^ 510) 12351 // b + ((a << 1) + 510) 12352 12353 // Many instructions can perform the shift for free, but it requires both 12354 // the operands to be registers. If c1 << c2 is too large, a mov immediate 12355 // instruction will needed. So, unfold back to the original pattern if: 12356 // - if c1 and c2 are small enough that they don't require mov imms. 12357 // - the user(s) of the node can perform an shl 12358 12359 // No shifted operands for 16-bit instructions. 12360 if (ST->isThumb() && ST->isThumb1Only()) 12361 return SDValue(); 12362 12363 // Check that all the users could perform the shl themselves. 12364 for (auto U : N->uses()) { 12365 switch(U->getOpcode()) { 12366 default: 12367 return SDValue(); 12368 case ISD::SUB: 12369 case ISD::ADD: 12370 case ISD::AND: 12371 case ISD::OR: 12372 case ISD::XOR: 12373 case ISD::SETCC: 12374 case ARMISD::CMP: 12375 // Check that the user isn't already using a constant because there 12376 // aren't any instructions that support an immediate operand and a 12377 // shifted operand. 12378 if (isa<ConstantSDNode>(U->getOperand(0)) || 12379 isa<ConstantSDNode>(U->getOperand(1))) 12380 return SDValue(); 12381 12382 // Check that it's not already using a shift. 12383 if (U->getOperand(0).getOpcode() == ISD::SHL || 12384 U->getOperand(1).getOpcode() == ISD::SHL) 12385 return SDValue(); 12386 break; 12387 } 12388 } 12389 12390 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 12391 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 12392 return SDValue(); 12393 12394 if (N->getOperand(0).getOpcode() != ISD::SHL) 12395 return SDValue(); 12396 12397 SDValue SHL = N->getOperand(0); 12398 12399 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12400 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 12401 if (!C1ShlC2 || !C2) 12402 return SDValue(); 12403 12404 APInt C2Int = C2->getAPIntValue(); 12405 APInt C1Int = C1ShlC2->getAPIntValue(); 12406 12407 // Check that performing a lshr will not lose any information. 12408 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 12409 C2Int.getBitWidth() - C2->getZExtValue()); 12410 if ((C1Int & Mask) != C1Int) 12411 return SDValue(); 12412 12413 // Shift the first constant. 12414 C1Int.lshrInPlace(C2Int); 12415 12416 // The immediates are encoded as an 8-bit value that can be rotated. 12417 auto LargeImm = [](const APInt &Imm) { 12418 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 12419 return Imm.getBitWidth() - Zeros > 8; 12420 }; 12421 12422 if (LargeImm(C1Int) || LargeImm(C2Int)) 12423 return SDValue(); 12424 12425 SelectionDAG &DAG = DCI.DAG; 12426 SDLoc dl(N); 12427 SDValue X = SHL.getOperand(0); 12428 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 12429 DAG.getConstant(C1Int, dl, MVT::i32)); 12430 // Shift left to compensate for the lshr of C1Int. 12431 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 12432 12433 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 12434 SHL.dump(); N->dump()); 12435 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 12436 return Res; 12437 } 12438 12439 12440 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 12441 /// 12442 static SDValue PerformADDCombine(SDNode *N, 12443 TargetLowering::DAGCombinerInfo &DCI, 12444 const ARMSubtarget *Subtarget) { 12445 SDValue N0 = N->getOperand(0); 12446 SDValue N1 = N->getOperand(1); 12447 12448 // Only works one way, because it needs an immediate operand. 12449 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12450 return Result; 12451 12452 if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget)) 12453 return Result; 12454 12455 // First try with the default operand order. 12456 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 12457 return Result; 12458 12459 // If that didn't work, try again with the operands commuted. 12460 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 12461 } 12462 12463 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 12464 /// 12465 static SDValue PerformSUBCombine(SDNode *N, 12466 TargetLowering::DAGCombinerInfo &DCI, 12467 const ARMSubtarget *Subtarget) { 12468 SDValue N0 = N->getOperand(0); 12469 SDValue N1 = N->getOperand(1); 12470 12471 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 12472 if (N1.getNode()->hasOneUse()) 12473 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 12474 return Result; 12475 12476 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector()) 12477 return SDValue(); 12478 12479 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x)) 12480 // so that we can readily pattern match more mve instructions which can use 12481 // a scalar operand. 12482 SDValue VDup = N->getOperand(1); 12483 if (VDup->getOpcode() != ARMISD::VDUP) 12484 return SDValue(); 12485 12486 SDValue VMov = N->getOperand(0); 12487 if (VMov->getOpcode() == ISD::BITCAST) 12488 VMov = VMov->getOperand(0); 12489 12490 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov)) 12491 return SDValue(); 12492 12493 SDLoc dl(N); 12494 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32, 12495 DCI.DAG.getConstant(0, dl, MVT::i32), 12496 VDup->getOperand(0)); 12497 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate); 12498 } 12499 12500 /// PerformVMULCombine 12501 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 12502 /// special multiplier accumulator forwarding. 12503 /// vmul d3, d0, d2 12504 /// vmla d3, d1, d2 12505 /// is faster than 12506 /// vadd d3, d0, d1 12507 /// vmul d3, d3, d2 12508 // However, for (A + B) * (A + B), 12509 // vadd d2, d0, d1 12510 // vmul d3, d0, d2 12511 // vmla d3, d1, d2 12512 // is slower than 12513 // vadd d2, d0, d1 12514 // vmul d3, d2, d2 12515 static SDValue PerformVMULCombine(SDNode *N, 12516 TargetLowering::DAGCombinerInfo &DCI, 12517 const ARMSubtarget *Subtarget) { 12518 if (!Subtarget->hasVMLxForwarding()) 12519 return SDValue(); 12520 12521 SelectionDAG &DAG = DCI.DAG; 12522 SDValue N0 = N->getOperand(0); 12523 SDValue N1 = N->getOperand(1); 12524 unsigned Opcode = N0.getOpcode(); 12525 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12526 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 12527 Opcode = N1.getOpcode(); 12528 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12529 Opcode != ISD::FADD && Opcode != ISD::FSUB) 12530 return SDValue(); 12531 std::swap(N0, N1); 12532 } 12533 12534 if (N0 == N1) 12535 return SDValue(); 12536 12537 EVT VT = N->getValueType(0); 12538 SDLoc DL(N); 12539 SDValue N00 = N0->getOperand(0); 12540 SDValue N01 = N0->getOperand(1); 12541 return DAG.getNode(Opcode, DL, VT, 12542 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 12543 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 12544 } 12545 12546 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG, 12547 const ARMSubtarget *Subtarget) { 12548 EVT VT = N->getValueType(0); 12549 if (VT != MVT::v2i64) 12550 return SDValue(); 12551 12552 SDValue N0 = N->getOperand(0); 12553 SDValue N1 = N->getOperand(1); 12554 12555 auto IsSignExt = [&](SDValue Op) { 12556 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG) 12557 return SDValue(); 12558 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT(); 12559 if (VT.getScalarSizeInBits() == 32) 12560 return Op->getOperand(0); 12561 return SDValue(); 12562 }; 12563 auto IsZeroExt = [&](SDValue Op) { 12564 // Zero extends are a little more awkward. At the point we are matching 12565 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask. 12566 // That might be before of after a bitcast depending on how the and is 12567 // placed. Because this has to look through bitcasts, it is currently only 12568 // supported on LE. 12569 if (!Subtarget->isLittle()) 12570 return SDValue(); 12571 12572 SDValue And = Op; 12573 if (And->getOpcode() == ISD::BITCAST) 12574 And = And->getOperand(0); 12575 if (And->getOpcode() != ISD::AND) 12576 return SDValue(); 12577 SDValue Mask = And->getOperand(1); 12578 if (Mask->getOpcode() == ISD::BITCAST) 12579 Mask = Mask->getOperand(0); 12580 12581 if (Mask->getOpcode() != ISD::BUILD_VECTOR || 12582 Mask.getValueType() != MVT::v4i32) 12583 return SDValue(); 12584 if (isAllOnesConstant(Mask->getOperand(0)) && 12585 isNullConstant(Mask->getOperand(1)) && 12586 isAllOnesConstant(Mask->getOperand(2)) && 12587 isNullConstant(Mask->getOperand(3))) 12588 return And->getOperand(0); 12589 return SDValue(); 12590 }; 12591 12592 SDLoc dl(N); 12593 if (SDValue Op0 = IsSignExt(N0)) { 12594 if (SDValue Op1 = IsSignExt(N1)) { 12595 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12596 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12597 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a); 12598 } 12599 } 12600 if (SDValue Op0 = IsZeroExt(N0)) { 12601 if (SDValue Op1 = IsZeroExt(N1)) { 12602 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12603 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12604 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a); 12605 } 12606 } 12607 12608 return SDValue(); 12609 } 12610 12611 static SDValue PerformMULCombine(SDNode *N, 12612 TargetLowering::DAGCombinerInfo &DCI, 12613 const ARMSubtarget *Subtarget) { 12614 SelectionDAG &DAG = DCI.DAG; 12615 12616 EVT VT = N->getValueType(0); 12617 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64) 12618 return PerformMVEVMULLCombine(N, DAG, Subtarget); 12619 12620 if (Subtarget->isThumb1Only()) 12621 return SDValue(); 12622 12623 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12624 return SDValue(); 12625 12626 if (VT.is64BitVector() || VT.is128BitVector()) 12627 return PerformVMULCombine(N, DCI, Subtarget); 12628 if (VT != MVT::i32) 12629 return SDValue(); 12630 12631 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12632 if (!C) 12633 return SDValue(); 12634 12635 int64_t MulAmt = C->getSExtValue(); 12636 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 12637 12638 ShiftAmt = ShiftAmt & (32 - 1); 12639 SDValue V = N->getOperand(0); 12640 SDLoc DL(N); 12641 12642 SDValue Res; 12643 MulAmt >>= ShiftAmt; 12644 12645 if (MulAmt >= 0) { 12646 if (isPowerOf2_32(MulAmt - 1)) { 12647 // (mul x, 2^N + 1) => (add (shl x, N), x) 12648 Res = DAG.getNode(ISD::ADD, DL, VT, 12649 V, 12650 DAG.getNode(ISD::SHL, DL, VT, 12651 V, 12652 DAG.getConstant(Log2_32(MulAmt - 1), DL, 12653 MVT::i32))); 12654 } else if (isPowerOf2_32(MulAmt + 1)) { 12655 // (mul x, 2^N - 1) => (sub (shl x, N), x) 12656 Res = DAG.getNode(ISD::SUB, DL, VT, 12657 DAG.getNode(ISD::SHL, DL, VT, 12658 V, 12659 DAG.getConstant(Log2_32(MulAmt + 1), DL, 12660 MVT::i32)), 12661 V); 12662 } else 12663 return SDValue(); 12664 } else { 12665 uint64_t MulAmtAbs = -MulAmt; 12666 if (isPowerOf2_32(MulAmtAbs + 1)) { 12667 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 12668 Res = DAG.getNode(ISD::SUB, DL, VT, 12669 V, 12670 DAG.getNode(ISD::SHL, DL, VT, 12671 V, 12672 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 12673 MVT::i32))); 12674 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 12675 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 12676 Res = DAG.getNode(ISD::ADD, DL, VT, 12677 V, 12678 DAG.getNode(ISD::SHL, DL, VT, 12679 V, 12680 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 12681 MVT::i32))); 12682 Res = DAG.getNode(ISD::SUB, DL, VT, 12683 DAG.getConstant(0, DL, MVT::i32), Res); 12684 } else 12685 return SDValue(); 12686 } 12687 12688 if (ShiftAmt != 0) 12689 Res = DAG.getNode(ISD::SHL, DL, VT, 12690 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 12691 12692 // Do not add new nodes to DAG combiner worklist. 12693 DCI.CombineTo(N, Res, false); 12694 return SDValue(); 12695 } 12696 12697 static SDValue CombineANDShift(SDNode *N, 12698 TargetLowering::DAGCombinerInfo &DCI, 12699 const ARMSubtarget *Subtarget) { 12700 // Allow DAGCombine to pattern-match before we touch the canonical form. 12701 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12702 return SDValue(); 12703 12704 if (N->getValueType(0) != MVT::i32) 12705 return SDValue(); 12706 12707 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12708 if (!N1C) 12709 return SDValue(); 12710 12711 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 12712 // Don't transform uxtb/uxth. 12713 if (C1 == 255 || C1 == 65535) 12714 return SDValue(); 12715 12716 SDNode *N0 = N->getOperand(0).getNode(); 12717 if (!N0->hasOneUse()) 12718 return SDValue(); 12719 12720 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 12721 return SDValue(); 12722 12723 bool LeftShift = N0->getOpcode() == ISD::SHL; 12724 12725 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12726 if (!N01C) 12727 return SDValue(); 12728 12729 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 12730 if (!C2 || C2 >= 32) 12731 return SDValue(); 12732 12733 // Clear irrelevant bits in the mask. 12734 if (LeftShift) 12735 C1 &= (-1U << C2); 12736 else 12737 C1 &= (-1U >> C2); 12738 12739 SelectionDAG &DAG = DCI.DAG; 12740 SDLoc DL(N); 12741 12742 // We have a pattern of the form "(and (shl x, c2) c1)" or 12743 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 12744 // transform to a pair of shifts, to save materializing c1. 12745 12746 // First pattern: right shift, then mask off leading bits. 12747 // FIXME: Use demanded bits? 12748 if (!LeftShift && isMask_32(C1)) { 12749 uint32_t C3 = countLeadingZeros(C1); 12750 if (C2 < C3) { 12751 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12752 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12753 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12754 DAG.getConstant(C3, DL, MVT::i32)); 12755 } 12756 } 12757 12758 // First pattern, reversed: left shift, then mask off trailing bits. 12759 if (LeftShift && isMask_32(~C1)) { 12760 uint32_t C3 = countTrailingZeros(C1); 12761 if (C2 < C3) { 12762 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12763 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12764 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12765 DAG.getConstant(C3, DL, MVT::i32)); 12766 } 12767 } 12768 12769 // Second pattern: left shift, then mask off leading bits. 12770 // FIXME: Use demanded bits? 12771 if (LeftShift && isShiftedMask_32(C1)) { 12772 uint32_t Trailing = countTrailingZeros(C1); 12773 uint32_t C3 = countLeadingZeros(C1); 12774 if (Trailing == C2 && C2 + C3 < 32) { 12775 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12776 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12777 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12778 DAG.getConstant(C3, DL, MVT::i32)); 12779 } 12780 } 12781 12782 // Second pattern, reversed: right shift, then mask off trailing bits. 12783 // FIXME: Handle other patterns of known/demanded bits. 12784 if (!LeftShift && isShiftedMask_32(C1)) { 12785 uint32_t Leading = countLeadingZeros(C1); 12786 uint32_t C3 = countTrailingZeros(C1); 12787 if (Leading == C2 && C2 + C3 < 32) { 12788 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12789 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12790 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12791 DAG.getConstant(C3, DL, MVT::i32)); 12792 } 12793 } 12794 12795 // FIXME: Transform "(and (shl x, c2) c1)" -> 12796 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 12797 // c1. 12798 return SDValue(); 12799 } 12800 12801 static SDValue PerformANDCombine(SDNode *N, 12802 TargetLowering::DAGCombinerInfo &DCI, 12803 const ARMSubtarget *Subtarget) { 12804 // Attempt to use immediate-form VBIC 12805 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12806 SDLoc dl(N); 12807 EVT VT = N->getValueType(0); 12808 SelectionDAG &DAG = DCI.DAG; 12809 12810 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 || 12811 VT == MVT::v8i1 || VT == MVT::v16i1) 12812 return SDValue(); 12813 12814 APInt SplatBits, SplatUndef; 12815 unsigned SplatBitSize; 12816 bool HasAnyUndefs; 12817 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 12818 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 12819 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 || 12820 SplatBitSize == 64) { 12821 EVT VbicVT; 12822 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 12823 SplatUndef.getZExtValue(), SplatBitSize, 12824 DAG, dl, VbicVT, VT, OtherModImm); 12825 if (Val.getNode()) { 12826 SDValue Input = 12827 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 12828 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 12829 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 12830 } 12831 } 12832 } 12833 12834 if (!Subtarget->isThumb1Only()) { 12835 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 12836 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 12837 return Result; 12838 12839 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12840 return Result; 12841 } 12842 12843 if (Subtarget->isThumb1Only()) 12844 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 12845 return Result; 12846 12847 return SDValue(); 12848 } 12849 12850 // Try combining OR nodes to SMULWB, SMULWT. 12851 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 12852 TargetLowering::DAGCombinerInfo &DCI, 12853 const ARMSubtarget *Subtarget) { 12854 if (!Subtarget->hasV6Ops() || 12855 (Subtarget->isThumb() && 12856 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 12857 return SDValue(); 12858 12859 SDValue SRL = OR->getOperand(0); 12860 SDValue SHL = OR->getOperand(1); 12861 12862 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 12863 SRL = OR->getOperand(1); 12864 SHL = OR->getOperand(0); 12865 } 12866 if (!isSRL16(SRL) || !isSHL16(SHL)) 12867 return SDValue(); 12868 12869 // The first operands to the shifts need to be the two results from the 12870 // same smul_lohi node. 12871 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 12872 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 12873 return SDValue(); 12874 12875 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 12876 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 12877 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 12878 return SDValue(); 12879 12880 // Now we have: 12881 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 12882 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 12883 // For SMUWB the 16-bit value will signed extended somehow. 12884 // For SMULWT only the SRA is required. 12885 // Check both sides of SMUL_LOHI 12886 SDValue OpS16 = SMULLOHI->getOperand(0); 12887 SDValue OpS32 = SMULLOHI->getOperand(1); 12888 12889 SelectionDAG &DAG = DCI.DAG; 12890 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 12891 OpS16 = OpS32; 12892 OpS32 = SMULLOHI->getOperand(0); 12893 } 12894 12895 SDLoc dl(OR); 12896 unsigned Opcode = 0; 12897 if (isS16(OpS16, DAG)) 12898 Opcode = ARMISD::SMULWB; 12899 else if (isSRA16(OpS16)) { 12900 Opcode = ARMISD::SMULWT; 12901 OpS16 = OpS16->getOperand(0); 12902 } 12903 else 12904 return SDValue(); 12905 12906 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 12907 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 12908 return SDValue(OR, 0); 12909 } 12910 12911 static SDValue PerformORCombineToBFI(SDNode *N, 12912 TargetLowering::DAGCombinerInfo &DCI, 12913 const ARMSubtarget *Subtarget) { 12914 // BFI is only available on V6T2+ 12915 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 12916 return SDValue(); 12917 12918 EVT VT = N->getValueType(0); 12919 SDValue N0 = N->getOperand(0); 12920 SDValue N1 = N->getOperand(1); 12921 SelectionDAG &DAG = DCI.DAG; 12922 SDLoc DL(N); 12923 // 1) or (and A, mask), val => ARMbfi A, val, mask 12924 // iff (val & mask) == val 12925 // 12926 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 12927 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 12928 // && mask == ~mask2 12929 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 12930 // && ~mask == mask2 12931 // (i.e., copy a bitfield value into another bitfield of the same width) 12932 12933 if (VT != MVT::i32) 12934 return SDValue(); 12935 12936 SDValue N00 = N0.getOperand(0); 12937 12938 // The value and the mask need to be constants so we can verify this is 12939 // actually a bitfield set. If the mask is 0xffff, we can do better 12940 // via a movt instruction, so don't use BFI in that case. 12941 SDValue MaskOp = N0.getOperand(1); 12942 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 12943 if (!MaskC) 12944 return SDValue(); 12945 unsigned Mask = MaskC->getZExtValue(); 12946 if (Mask == 0xffff) 12947 return SDValue(); 12948 SDValue Res; 12949 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 12950 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 12951 if (N1C) { 12952 unsigned Val = N1C->getZExtValue(); 12953 if ((Val & ~Mask) != Val) 12954 return SDValue(); 12955 12956 if (ARM::isBitFieldInvertedMask(Mask)) { 12957 Val >>= countTrailingZeros(~Mask); 12958 12959 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 12960 DAG.getConstant(Val, DL, MVT::i32), 12961 DAG.getConstant(Mask, DL, MVT::i32)); 12962 12963 DCI.CombineTo(N, Res, false); 12964 // Return value from the original node to inform the combiner than N is 12965 // now dead. 12966 return SDValue(N, 0); 12967 } 12968 } else if (N1.getOpcode() == ISD::AND) { 12969 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 12970 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 12971 if (!N11C) 12972 return SDValue(); 12973 unsigned Mask2 = N11C->getZExtValue(); 12974 12975 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 12976 // as is to match. 12977 if (ARM::isBitFieldInvertedMask(Mask) && 12978 (Mask == ~Mask2)) { 12979 // The pack halfword instruction works better for masks that fit it, 12980 // so use that when it's available. 12981 if (Subtarget->hasDSP() && 12982 (Mask == 0xffff || Mask == 0xffff0000)) 12983 return SDValue(); 12984 // 2a 12985 unsigned amt = countTrailingZeros(Mask2); 12986 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 12987 DAG.getConstant(amt, DL, MVT::i32)); 12988 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 12989 DAG.getConstant(Mask, DL, MVT::i32)); 12990 DCI.CombineTo(N, Res, false); 12991 // Return value from the original node to inform the combiner than N is 12992 // now dead. 12993 return SDValue(N, 0); 12994 } else if (ARM::isBitFieldInvertedMask(~Mask) && 12995 (~Mask == Mask2)) { 12996 // The pack halfword instruction works better for masks that fit it, 12997 // so use that when it's available. 12998 if (Subtarget->hasDSP() && 12999 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 13000 return SDValue(); 13001 // 2b 13002 unsigned lsb = countTrailingZeros(Mask); 13003 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 13004 DAG.getConstant(lsb, DL, MVT::i32)); 13005 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 13006 DAG.getConstant(Mask2, DL, MVT::i32)); 13007 DCI.CombineTo(N, Res, false); 13008 // Return value from the original node to inform the combiner than N is 13009 // now dead. 13010 return SDValue(N, 0); 13011 } 13012 } 13013 13014 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 13015 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 13016 ARM::isBitFieldInvertedMask(~Mask)) { 13017 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 13018 // where lsb(mask) == #shamt and masked bits of B are known zero. 13019 SDValue ShAmt = N00.getOperand(1); 13020 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 13021 unsigned LSB = countTrailingZeros(Mask); 13022 if (ShAmtC != LSB) 13023 return SDValue(); 13024 13025 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 13026 DAG.getConstant(~Mask, DL, MVT::i32)); 13027 13028 DCI.CombineTo(N, Res, false); 13029 // Return value from the original node to inform the combiner than N is 13030 // now dead. 13031 return SDValue(N, 0); 13032 } 13033 13034 return SDValue(); 13035 } 13036 13037 static bool isValidMVECond(unsigned CC, bool IsFloat) { 13038 switch (CC) { 13039 case ARMCC::EQ: 13040 case ARMCC::NE: 13041 case ARMCC::LE: 13042 case ARMCC::GT: 13043 case ARMCC::GE: 13044 case ARMCC::LT: 13045 return true; 13046 case ARMCC::HS: 13047 case ARMCC::HI: 13048 return !IsFloat; 13049 default: 13050 return false; 13051 }; 13052 } 13053 13054 static ARMCC::CondCodes getVCMPCondCode(SDValue N) { 13055 if (N->getOpcode() == ARMISD::VCMP) 13056 return (ARMCC::CondCodes)N->getConstantOperandVal(2); 13057 else if (N->getOpcode() == ARMISD::VCMPZ) 13058 return (ARMCC::CondCodes)N->getConstantOperandVal(1); 13059 else 13060 llvm_unreachable("Not a VCMP/VCMPZ!"); 13061 } 13062 13063 static bool CanInvertMVEVCMP(SDValue N) { 13064 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N)); 13065 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint()); 13066 } 13067 13068 static SDValue PerformORCombine_i1(SDNode *N, 13069 TargetLowering::DAGCombinerInfo &DCI, 13070 const ARMSubtarget *Subtarget) { 13071 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 13072 // together with predicates 13073 EVT VT = N->getValueType(0); 13074 SDLoc DL(N); 13075 SDValue N0 = N->getOperand(0); 13076 SDValue N1 = N->getOperand(1); 13077 13078 auto IsFreelyInvertable = [&](SDValue V) { 13079 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ) 13080 return CanInvertMVEVCMP(V); 13081 return false; 13082 }; 13083 13084 // At least one operand must be freely invertable. 13085 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1))) 13086 return SDValue(); 13087 13088 SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT); 13089 SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT); 13090 SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1); 13091 return DCI.DAG.getLogicalNOT(DL, And, VT); 13092 } 13093 13094 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 13095 static SDValue PerformORCombine(SDNode *N, 13096 TargetLowering::DAGCombinerInfo &DCI, 13097 const ARMSubtarget *Subtarget) { 13098 // Attempt to use immediate-form VORR 13099 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 13100 SDLoc dl(N); 13101 EVT VT = N->getValueType(0); 13102 SelectionDAG &DAG = DCI.DAG; 13103 13104 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13105 return SDValue(); 13106 13107 if (Subtarget->hasMVEIntegerOps() && 13108 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 13109 return PerformORCombine_i1(N, DCI, Subtarget); 13110 13111 APInt SplatBits, SplatUndef; 13112 unsigned SplatBitSize; 13113 bool HasAnyUndefs; 13114 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 13115 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 13116 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 || 13117 SplatBitSize == 64) { 13118 EVT VorrVT; 13119 SDValue Val = 13120 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 13121 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm); 13122 if (Val.getNode()) { 13123 SDValue Input = 13124 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 13125 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 13126 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 13127 } 13128 } 13129 } 13130 13131 if (!Subtarget->isThumb1Only()) { 13132 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 13133 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 13134 return Result; 13135 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 13136 return Result; 13137 } 13138 13139 SDValue N0 = N->getOperand(0); 13140 SDValue N1 = N->getOperand(1); 13141 13142 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 13143 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 13144 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 13145 13146 // The code below optimizes (or (and X, Y), Z). 13147 // The AND operand needs to have a single user to make these optimizations 13148 // profitable. 13149 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 13150 return SDValue(); 13151 13152 APInt SplatUndef; 13153 unsigned SplatBitSize; 13154 bool HasAnyUndefs; 13155 13156 APInt SplatBits0, SplatBits1; 13157 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 13158 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 13159 // Ensure that the second operand of both ands are constants 13160 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 13161 HasAnyUndefs) && !HasAnyUndefs) { 13162 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 13163 HasAnyUndefs) && !HasAnyUndefs) { 13164 // Ensure that the bit width of the constants are the same and that 13165 // the splat arguments are logical inverses as per the pattern we 13166 // are trying to simplify. 13167 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 13168 SplatBits0 == ~SplatBits1) { 13169 // Canonicalize the vector type to make instruction selection 13170 // simpler. 13171 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 13172 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT, 13173 N0->getOperand(1), 13174 N0->getOperand(0), 13175 N1->getOperand(0)); 13176 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 13177 } 13178 } 13179 } 13180 } 13181 13182 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 13183 // reasonable. 13184 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 13185 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 13186 return Res; 13187 } 13188 13189 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13190 return Result; 13191 13192 return SDValue(); 13193 } 13194 13195 static SDValue PerformXORCombine(SDNode *N, 13196 TargetLowering::DAGCombinerInfo &DCI, 13197 const ARMSubtarget *Subtarget) { 13198 EVT VT = N->getValueType(0); 13199 SelectionDAG &DAG = DCI.DAG; 13200 13201 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13202 return SDValue(); 13203 13204 if (!Subtarget->isThumb1Only()) { 13205 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 13206 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 13207 return Result; 13208 13209 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13210 return Result; 13211 } 13212 13213 if (Subtarget->hasMVEIntegerOps()) { 13214 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition. 13215 SDValue N0 = N->getOperand(0); 13216 SDValue N1 = N->getOperand(1); 13217 const TargetLowering *TLI = Subtarget->getTargetLowering(); 13218 if (TLI->isConstTrueVal(N1.getNode()) && 13219 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) { 13220 if (CanInvertMVEVCMP(N0)) { 13221 SDLoc DL(N0); 13222 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0)); 13223 13224 SmallVector<SDValue, 4> Ops; 13225 Ops.push_back(N0->getOperand(0)); 13226 if (N0->getOpcode() == ARMISD::VCMP) 13227 Ops.push_back(N0->getOperand(1)); 13228 Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32)); 13229 return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops); 13230 } 13231 } 13232 } 13233 13234 return SDValue(); 13235 } 13236 13237 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 13238 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 13239 // their position in "to" (Rd). 13240 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 13241 assert(N->getOpcode() == ARMISD::BFI); 13242 13243 SDValue From = N->getOperand(1); 13244 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 13245 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 13246 13247 // If the Base came from a SHR #C, we can deduce that it is really testing bit 13248 // #C in the base of the SHR. 13249 if (From->getOpcode() == ISD::SRL && 13250 isa<ConstantSDNode>(From->getOperand(1))) { 13251 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 13252 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 13253 FromMask <<= Shift.getLimitedValue(31); 13254 From = From->getOperand(0); 13255 } 13256 13257 return From; 13258 } 13259 13260 // If A and B contain one contiguous set of bits, does A | B == A . B? 13261 // 13262 // Neither A nor B must be zero. 13263 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 13264 unsigned LastActiveBitInA = A.countTrailingZeros(); 13265 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 13266 return LastActiveBitInA - 1 == FirstActiveBitInB; 13267 } 13268 13269 static SDValue FindBFIToCombineWith(SDNode *N) { 13270 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 13271 // if one exists. 13272 APInt ToMask, FromMask; 13273 SDValue From = ParseBFI(N, ToMask, FromMask); 13274 SDValue To = N->getOperand(0); 13275 13276 // Now check for a compatible BFI to merge with. We can pass through BFIs that 13277 // aren't compatible, but not if they set the same bit in their destination as 13278 // we do (or that of any BFI we're going to combine with). 13279 SDValue V = To; 13280 APInt CombinedToMask = ToMask; 13281 while (V.getOpcode() == ARMISD::BFI) { 13282 APInt NewToMask, NewFromMask; 13283 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 13284 if (NewFrom != From) { 13285 // This BFI has a different base. Keep going. 13286 CombinedToMask |= NewToMask; 13287 V = V.getOperand(0); 13288 continue; 13289 } 13290 13291 // Do the written bits conflict with any we've seen so far? 13292 if ((NewToMask & CombinedToMask).getBoolValue()) 13293 // Conflicting bits - bail out because going further is unsafe. 13294 return SDValue(); 13295 13296 // Are the new bits contiguous when combined with the old bits? 13297 if (BitsProperlyConcatenate(ToMask, NewToMask) && 13298 BitsProperlyConcatenate(FromMask, NewFromMask)) 13299 return V; 13300 if (BitsProperlyConcatenate(NewToMask, ToMask) && 13301 BitsProperlyConcatenate(NewFromMask, FromMask)) 13302 return V; 13303 13304 // We've seen a write to some bits, so track it. 13305 CombinedToMask |= NewToMask; 13306 // Keep going... 13307 V = V.getOperand(0); 13308 } 13309 13310 return SDValue(); 13311 } 13312 13313 static SDValue PerformBFICombine(SDNode *N, 13314 TargetLowering::DAGCombinerInfo &DCI) { 13315 SDValue N1 = N->getOperand(1); 13316 if (N1.getOpcode() == ISD::AND) { 13317 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 13318 // the bits being cleared by the AND are not demanded by the BFI. 13319 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 13320 if (!N11C) 13321 return SDValue(); 13322 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 13323 unsigned LSB = countTrailingZeros(~InvMask); 13324 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 13325 assert(Width < 13326 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 13327 "undefined behavior"); 13328 unsigned Mask = (1u << Width) - 1; 13329 unsigned Mask2 = N11C->getZExtValue(); 13330 if ((Mask & (~Mask2)) == 0) 13331 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 13332 N->getOperand(0), N1.getOperand(0), 13333 N->getOperand(2)); 13334 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 13335 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 13336 // Keep track of any consecutive bits set that all come from the same base 13337 // value. We can combine these together into a single BFI. 13338 SDValue CombineBFI = FindBFIToCombineWith(N); 13339 if (CombineBFI == SDValue()) 13340 return SDValue(); 13341 13342 // We've found a BFI. 13343 APInt ToMask1, FromMask1; 13344 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 13345 13346 APInt ToMask2, FromMask2; 13347 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 13348 assert(From1 == From2); 13349 (void)From2; 13350 13351 // First, unlink CombineBFI. 13352 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 13353 // Then create a new BFI, combining the two together. 13354 APInt NewFromMask = FromMask1 | FromMask2; 13355 APInt NewToMask = ToMask1 | ToMask2; 13356 13357 EVT VT = N->getValueType(0); 13358 SDLoc dl(N); 13359 13360 if (NewFromMask[0] == 0) 13361 From1 = DCI.DAG.getNode( 13362 ISD::SRL, dl, VT, From1, 13363 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 13364 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 13365 DCI.DAG.getConstant(~NewToMask, dl, VT)); 13366 } 13367 return SDValue(); 13368 } 13369 13370 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 13371 /// ARMISD::VMOVRRD. 13372 static SDValue PerformVMOVRRDCombine(SDNode *N, 13373 TargetLowering::DAGCombinerInfo &DCI, 13374 const ARMSubtarget *Subtarget) { 13375 // vmovrrd(vmovdrr x, y) -> x,y 13376 SDValue InDouble = N->getOperand(0); 13377 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 13378 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 13379 13380 // vmovrrd(load f64) -> (load i32), (load i32) 13381 SDNode *InNode = InDouble.getNode(); 13382 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 13383 InNode->getValueType(0) == MVT::f64 && 13384 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 13385 !cast<LoadSDNode>(InNode)->isVolatile()) { 13386 // TODO: Should this be done for non-FrameIndex operands? 13387 LoadSDNode *LD = cast<LoadSDNode>(InNode); 13388 13389 SelectionDAG &DAG = DCI.DAG; 13390 SDLoc DL(LD); 13391 SDValue BasePtr = LD->getBasePtr(); 13392 SDValue NewLD1 = 13393 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 13394 LD->getAlignment(), LD->getMemOperand()->getFlags()); 13395 13396 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 13397 DAG.getConstant(4, DL, MVT::i32)); 13398 13399 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 13400 LD->getPointerInfo().getWithOffset(4), 13401 std::min(4U, LD->getAlignment()), 13402 LD->getMemOperand()->getFlags()); 13403 13404 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 13405 if (DCI.DAG.getDataLayout().isBigEndian()) 13406 std::swap (NewLD1, NewLD2); 13407 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 13408 return Result; 13409 } 13410 13411 return SDValue(); 13412 } 13413 13414 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 13415 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 13416 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 13417 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 13418 SDValue Op0 = N->getOperand(0); 13419 SDValue Op1 = N->getOperand(1); 13420 if (Op0.getOpcode() == ISD::BITCAST) 13421 Op0 = Op0.getOperand(0); 13422 if (Op1.getOpcode() == ISD::BITCAST) 13423 Op1 = Op1.getOperand(0); 13424 if (Op0.getOpcode() == ARMISD::VMOVRRD && 13425 Op0.getNode() == Op1.getNode() && 13426 Op0.getResNo() == 0 && Op1.getResNo() == 1) 13427 return DAG.getNode(ISD::BITCAST, SDLoc(N), 13428 N->getValueType(0), Op0.getOperand(0)); 13429 return SDValue(); 13430 } 13431 13432 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13433 SDValue Op0 = N->getOperand(0); 13434 13435 // VMOVhr (VMOVrh (X)) -> X 13436 if (Op0->getOpcode() == ARMISD::VMOVrh) 13437 return Op0->getOperand(0); 13438 13439 // FullFP16: half values are passed in S-registers, and we don't 13440 // need any of the bitcast and moves: 13441 // 13442 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 13443 // t5: i32 = bitcast t2 13444 // t18: f16 = ARMISD::VMOVhr t5 13445 if (Op0->getOpcode() == ISD::BITCAST) { 13446 SDValue Copy = Op0->getOperand(0); 13447 if (Copy.getValueType() == MVT::f32 && 13448 Copy->getOpcode() == ISD::CopyFromReg) { 13449 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)}; 13450 SDValue NewCopy = 13451 DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops); 13452 return NewCopy; 13453 } 13454 } 13455 13456 // fold (VMOVhr (load x)) -> (load (f16*)x) 13457 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) { 13458 if (LN0->hasOneUse() && LN0->isUnindexed() && 13459 LN0->getMemoryVT() == MVT::i16) { 13460 SDValue Load = 13461 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(), 13462 LN0->getBasePtr(), LN0->getMemOperand()); 13463 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13464 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1)); 13465 return Load; 13466 } 13467 } 13468 13469 // Only the bottom 16 bits of the source register are used. 13470 APInt DemandedMask = APInt::getLowBitsSet(32, 16); 13471 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 13472 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI)) 13473 return SDValue(N, 0); 13474 13475 return SDValue(); 13476 } 13477 13478 static SDValue PerformVMOVrhCombine(SDNode *N, 13479 TargetLowering::DAGCombinerInfo &DCI) { 13480 SDValue N0 = N->getOperand(0); 13481 EVT VT = N->getValueType(0); 13482 13483 // fold (VMOVrh (load x)) -> (zextload (i16*)x) 13484 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) { 13485 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 13486 13487 SDValue Load = 13488 DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(), 13489 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand()); 13490 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13491 DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 13492 return Load; 13493 } 13494 13495 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n) 13496 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 13497 isa<ConstantSDNode>(N0->getOperand(1))) 13498 return DCI.DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0), 13499 N0->getOperand(1)); 13500 13501 return SDValue(); 13502 } 13503 13504 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 13505 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 13506 /// i64 vector to have f64 elements, since the value can then be loaded 13507 /// directly into a VFP register. 13508 static bool hasNormalLoadOperand(SDNode *N) { 13509 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 13510 for (unsigned i = 0; i < NumElts; ++i) { 13511 SDNode *Elt = N->getOperand(i).getNode(); 13512 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 13513 return true; 13514 } 13515 return false; 13516 } 13517 13518 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 13519 /// ISD::BUILD_VECTOR. 13520 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 13521 TargetLowering::DAGCombinerInfo &DCI, 13522 const ARMSubtarget *Subtarget) { 13523 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 13524 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 13525 // into a pair of GPRs, which is fine when the value is used as a scalar, 13526 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 13527 SelectionDAG &DAG = DCI.DAG; 13528 if (N->getNumOperands() == 2) 13529 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 13530 return RV; 13531 13532 // Load i64 elements as f64 values so that type legalization does not split 13533 // them up into i32 values. 13534 EVT VT = N->getValueType(0); 13535 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 13536 return SDValue(); 13537 SDLoc dl(N); 13538 SmallVector<SDValue, 8> Ops; 13539 unsigned NumElts = VT.getVectorNumElements(); 13540 for (unsigned i = 0; i < NumElts; ++i) { 13541 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 13542 Ops.push_back(V); 13543 // Make the DAGCombiner fold the bitcast. 13544 DCI.AddToWorklist(V.getNode()); 13545 } 13546 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 13547 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 13548 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 13549 } 13550 13551 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 13552 static SDValue 13553 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13554 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 13555 // At that time, we may have inserted bitcasts from integer to float. 13556 // If these bitcasts have survived DAGCombine, change the lowering of this 13557 // BUILD_VECTOR in something more vector friendly, i.e., that does not 13558 // force to use floating point types. 13559 13560 // Make sure we can change the type of the vector. 13561 // This is possible iff: 13562 // 1. The vector is only used in a bitcast to a integer type. I.e., 13563 // 1.1. Vector is used only once. 13564 // 1.2. Use is a bit convert to an integer type. 13565 // 2. The size of its operands are 32-bits (64-bits are not legal). 13566 EVT VT = N->getValueType(0); 13567 EVT EltVT = VT.getVectorElementType(); 13568 13569 // Check 1.1. and 2. 13570 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 13571 return SDValue(); 13572 13573 // By construction, the input type must be float. 13574 assert(EltVT == MVT::f32 && "Unexpected type!"); 13575 13576 // Check 1.2. 13577 SDNode *Use = *N->use_begin(); 13578 if (Use->getOpcode() != ISD::BITCAST || 13579 Use->getValueType(0).isFloatingPoint()) 13580 return SDValue(); 13581 13582 // Check profitability. 13583 // Model is, if more than half of the relevant operands are bitcast from 13584 // i32, turn the build_vector into a sequence of insert_vector_elt. 13585 // Relevant operands are everything that is not statically 13586 // (i.e., at compile time) bitcasted. 13587 unsigned NumOfBitCastedElts = 0; 13588 unsigned NumElts = VT.getVectorNumElements(); 13589 unsigned NumOfRelevantElts = NumElts; 13590 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 13591 SDValue Elt = N->getOperand(Idx); 13592 if (Elt->getOpcode() == ISD::BITCAST) { 13593 // Assume only bit cast to i32 will go away. 13594 if (Elt->getOperand(0).getValueType() == MVT::i32) 13595 ++NumOfBitCastedElts; 13596 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 13597 // Constants are statically casted, thus do not count them as 13598 // relevant operands. 13599 --NumOfRelevantElts; 13600 } 13601 13602 // Check if more than half of the elements require a non-free bitcast. 13603 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 13604 return SDValue(); 13605 13606 SelectionDAG &DAG = DCI.DAG; 13607 // Create the new vector type. 13608 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 13609 // Check if the type is legal. 13610 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13611 if (!TLI.isTypeLegal(VecVT)) 13612 return SDValue(); 13613 13614 // Combine: 13615 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 13616 // => BITCAST INSERT_VECTOR_ELT 13617 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 13618 // (BITCAST EN), N. 13619 SDValue Vec = DAG.getUNDEF(VecVT); 13620 SDLoc dl(N); 13621 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 13622 SDValue V = N->getOperand(Idx); 13623 if (V.isUndef()) 13624 continue; 13625 if (V.getOpcode() == ISD::BITCAST && 13626 V->getOperand(0).getValueType() == MVT::i32) 13627 // Fold obvious case. 13628 V = V.getOperand(0); 13629 else { 13630 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 13631 // Make the DAGCombiner fold the bitcasts. 13632 DCI.AddToWorklist(V.getNode()); 13633 } 13634 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 13635 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 13636 } 13637 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 13638 // Make the DAGCombiner fold the bitcasts. 13639 DCI.AddToWorklist(Vec.getNode()); 13640 return Vec; 13641 } 13642 13643 static SDValue 13644 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13645 EVT VT = N->getValueType(0); 13646 SDValue Op = N->getOperand(0); 13647 SDLoc dl(N); 13648 13649 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x) 13650 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) { 13651 // If the valuetypes are the same, we can remove the cast entirely. 13652 if (Op->getOperand(0).getValueType() == VT) 13653 return Op->getOperand(0); 13654 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0)); 13655 } 13656 13657 return SDValue(); 13658 } 13659 13660 static SDValue 13661 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 13662 const ARMSubtarget *ST) { 13663 EVT VT = N->getValueType(0); 13664 SDValue Op = N->getOperand(0); 13665 SDLoc dl(N); 13666 13667 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST 13668 if (ST->isLittle()) 13669 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op); 13670 13671 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x) 13672 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) { 13673 // If the valuetypes are the same, we can remove the cast entirely. 13674 if (Op->getOperand(0).getValueType() == VT) 13675 return Op->getOperand(0); 13676 return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0)); 13677 } 13678 13679 return SDValue(); 13680 } 13681 13682 static SDValue PerformVCMPCombine(SDNode *N, 13683 TargetLowering::DAGCombinerInfo &DCI, 13684 const ARMSubtarget *Subtarget) { 13685 if (!Subtarget->hasMVEIntegerOps()) 13686 return SDValue(); 13687 13688 EVT VT = N->getValueType(0); 13689 SDValue Op0 = N->getOperand(0); 13690 SDValue Op1 = N->getOperand(1); 13691 ARMCC::CondCodes Cond = 13692 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 13693 SDLoc dl(N); 13694 13695 // vcmp X, 0, cc -> vcmpz X, cc 13696 if (isZeroVector(Op1)) 13697 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, 13698 N->getOperand(2)); 13699 13700 unsigned SwappedCond = getSwappedCondition(Cond); 13701 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) { 13702 // vcmp 0, X, cc -> vcmpz X, reversed(cc) 13703 if (isZeroVector(Op0)) 13704 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1, 13705 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13706 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc) 13707 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP) 13708 return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0, 13709 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13710 } 13711 13712 return SDValue(); 13713 } 13714 13715 /// PerformInsertEltCombine - Target-specific dag combine xforms for 13716 /// ISD::INSERT_VECTOR_ELT. 13717 static SDValue PerformInsertEltCombine(SDNode *N, 13718 TargetLowering::DAGCombinerInfo &DCI) { 13719 // Bitcast an i64 load inserted into a vector to f64. 13720 // Otherwise, the i64 value will be legalized to a pair of i32 values. 13721 EVT VT = N->getValueType(0); 13722 SDNode *Elt = N->getOperand(1).getNode(); 13723 if (VT.getVectorElementType() != MVT::i64 || 13724 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 13725 return SDValue(); 13726 13727 SelectionDAG &DAG = DCI.DAG; 13728 SDLoc dl(N); 13729 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 13730 VT.getVectorNumElements()); 13731 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 13732 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 13733 // Make the DAGCombiner fold the bitcasts. 13734 DCI.AddToWorklist(Vec.getNode()); 13735 DCI.AddToWorklist(V.getNode()); 13736 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 13737 Vec, V, N->getOperand(2)); 13738 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 13739 } 13740 13741 static SDValue PerformExtractEltCombine(SDNode *N, 13742 TargetLowering::DAGCombinerInfo &DCI) { 13743 SDValue Op0 = N->getOperand(0); 13744 EVT VT = N->getValueType(0); 13745 SDLoc dl(N); 13746 13747 // extract (vdup x) -> x 13748 if (Op0->getOpcode() == ARMISD::VDUP) { 13749 SDValue X = Op0->getOperand(0); 13750 if (VT == MVT::f16 && X.getValueType() == MVT::i32) 13751 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X); 13752 if (VT == MVT::i32 && X.getValueType() == MVT::f16) 13753 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X); 13754 13755 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST) 13756 X = X->getOperand(0); 13757 if (X.getValueType() == VT) 13758 return X; 13759 } 13760 13761 return SDValue(); 13762 } 13763 13764 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 13765 /// ISD::VECTOR_SHUFFLE. 13766 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 13767 // The LLVM shufflevector instruction does not require the shuffle mask 13768 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 13769 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 13770 // operands do not match the mask length, they are extended by concatenating 13771 // them with undef vectors. That is probably the right thing for other 13772 // targets, but for NEON it is better to concatenate two double-register 13773 // size vector operands into a single quad-register size vector. Do that 13774 // transformation here: 13775 // shuffle(concat(v1, undef), concat(v2, undef)) -> 13776 // shuffle(concat(v1, v2), undef) 13777 SDValue Op0 = N->getOperand(0); 13778 SDValue Op1 = N->getOperand(1); 13779 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 13780 Op1.getOpcode() != ISD::CONCAT_VECTORS || 13781 Op0.getNumOperands() != 2 || 13782 Op1.getNumOperands() != 2) 13783 return SDValue(); 13784 SDValue Concat0Op1 = Op0.getOperand(1); 13785 SDValue Concat1Op1 = Op1.getOperand(1); 13786 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 13787 return SDValue(); 13788 // Skip the transformation if any of the types are illegal. 13789 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13790 EVT VT = N->getValueType(0); 13791 if (!TLI.isTypeLegal(VT) || 13792 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 13793 !TLI.isTypeLegal(Concat1Op1.getValueType())) 13794 return SDValue(); 13795 13796 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13797 Op0.getOperand(0), Op1.getOperand(0)); 13798 // Translate the shuffle mask. 13799 SmallVector<int, 16> NewMask; 13800 unsigned NumElts = VT.getVectorNumElements(); 13801 unsigned HalfElts = NumElts/2; 13802 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13803 for (unsigned n = 0; n < NumElts; ++n) { 13804 int MaskElt = SVN->getMaskElt(n); 13805 int NewElt = -1; 13806 if (MaskElt < (int)HalfElts) 13807 NewElt = MaskElt; 13808 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 13809 NewElt = HalfElts + MaskElt - NumElts; 13810 NewMask.push_back(NewElt); 13811 } 13812 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 13813 DAG.getUNDEF(VT), NewMask); 13814 } 13815 13816 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 13817 /// NEON load/store intrinsics, and generic vector load/stores, to merge 13818 /// base address updates. 13819 /// For generic load/stores, the memory type is assumed to be a vector. 13820 /// The caller is assumed to have checked legality. 13821 static SDValue CombineBaseUpdate(SDNode *N, 13822 TargetLowering::DAGCombinerInfo &DCI) { 13823 SelectionDAG &DAG = DCI.DAG; 13824 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 13825 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 13826 const bool isStore = N->getOpcode() == ISD::STORE; 13827 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 13828 SDValue Addr = N->getOperand(AddrOpIdx); 13829 MemSDNode *MemN = cast<MemSDNode>(N); 13830 SDLoc dl(N); 13831 13832 // Search for a use of the address operand that is an increment. 13833 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 13834 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 13835 SDNode *User = *UI; 13836 if (User->getOpcode() != ISD::ADD || 13837 UI.getUse().getResNo() != Addr.getResNo()) 13838 continue; 13839 13840 // Check that the add is independent of the load/store. Otherwise, folding 13841 // it would create a cycle. We can avoid searching through Addr as it's a 13842 // predecessor to both. 13843 SmallPtrSet<const SDNode *, 32> Visited; 13844 SmallVector<const SDNode *, 16> Worklist; 13845 Visited.insert(Addr.getNode()); 13846 Worklist.push_back(N); 13847 Worklist.push_back(User); 13848 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 13849 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 13850 continue; 13851 13852 // Find the new opcode for the updating load/store. 13853 bool isLoadOp = true; 13854 bool isLaneOp = false; 13855 unsigned NewOpc = 0; 13856 unsigned NumVecs = 0; 13857 if (isIntrinsic) { 13858 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 13859 switch (IntNo) { 13860 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 13861 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 13862 NumVecs = 1; break; 13863 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 13864 NumVecs = 2; break; 13865 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 13866 NumVecs = 3; break; 13867 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 13868 NumVecs = 4; break; 13869 case Intrinsic::arm_neon_vld2dup: 13870 case Intrinsic::arm_neon_vld3dup: 13871 case Intrinsic::arm_neon_vld4dup: 13872 // TODO: Support updating VLDxDUP nodes. For now, we just skip 13873 // combining base updates for such intrinsics. 13874 continue; 13875 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 13876 NumVecs = 2; isLaneOp = true; break; 13877 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 13878 NumVecs = 3; isLaneOp = true; break; 13879 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 13880 NumVecs = 4; isLaneOp = true; break; 13881 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 13882 NumVecs = 1; isLoadOp = false; break; 13883 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 13884 NumVecs = 2; isLoadOp = false; break; 13885 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 13886 NumVecs = 3; isLoadOp = false; break; 13887 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 13888 NumVecs = 4; isLoadOp = false; break; 13889 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 13890 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 13891 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 13892 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 13893 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 13894 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 13895 } 13896 } else { 13897 isLaneOp = true; 13898 switch (N->getOpcode()) { 13899 default: llvm_unreachable("unexpected opcode for Neon base update"); 13900 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 13901 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 13902 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 13903 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 13904 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 13905 NumVecs = 1; isLaneOp = false; break; 13906 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 13907 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 13908 } 13909 } 13910 13911 // Find the size of memory referenced by the load/store. 13912 EVT VecTy; 13913 if (isLoadOp) { 13914 VecTy = N->getValueType(0); 13915 } else if (isIntrinsic) { 13916 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 13917 } else { 13918 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 13919 VecTy = N->getOperand(1).getValueType(); 13920 } 13921 13922 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 13923 if (isLaneOp) 13924 NumBytes /= VecTy.getVectorNumElements(); 13925 13926 // If the increment is a constant, it must match the memory ref size. 13927 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 13928 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 13929 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 13930 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 13931 // separate instructions that make it harder to use a non-constant update. 13932 continue; 13933 } 13934 13935 // OK, we found an ADD we can fold into the base update. 13936 // Now, create a _UPD node, taking care of not breaking alignment. 13937 13938 EVT AlignedVecTy = VecTy; 13939 unsigned Alignment = MemN->getAlignment(); 13940 13941 // If this is a less-than-standard-aligned load/store, change the type to 13942 // match the standard alignment. 13943 // The alignment is overlooked when selecting _UPD variants; and it's 13944 // easier to introduce bitcasts here than fix that. 13945 // There are 3 ways to get to this base-update combine: 13946 // - intrinsics: they are assumed to be properly aligned (to the standard 13947 // alignment of the memory type), so we don't need to do anything. 13948 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 13949 // intrinsics, so, likewise, there's nothing to do. 13950 // - generic load/store instructions: the alignment is specified as an 13951 // explicit operand, rather than implicitly as the standard alignment 13952 // of the memory type (like the intrisics). We need to change the 13953 // memory type to match the explicit alignment. That way, we don't 13954 // generate non-standard-aligned ARMISD::VLDx nodes. 13955 if (isa<LSBaseSDNode>(N)) { 13956 if (Alignment == 0) 13957 Alignment = 1; 13958 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 13959 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 13960 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 13961 assert(!isLaneOp && "Unexpected generic load/store lane."); 13962 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 13963 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 13964 } 13965 // Don't set an explicit alignment on regular load/stores that we want 13966 // to transform to VLD/VST 1_UPD nodes. 13967 // This matches the behavior of regular load/stores, which only get an 13968 // explicit alignment if the MMO alignment is larger than the standard 13969 // alignment of the memory type. 13970 // Intrinsics, however, always get an explicit alignment, set to the 13971 // alignment of the MMO. 13972 Alignment = 1; 13973 } 13974 13975 // Create the new updating load/store node. 13976 // First, create an SDVTList for the new updating node's results. 13977 EVT Tys[6]; 13978 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 13979 unsigned n; 13980 for (n = 0; n < NumResultVecs; ++n) 13981 Tys[n] = AlignedVecTy; 13982 Tys[n++] = MVT::i32; 13983 Tys[n] = MVT::Other; 13984 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 13985 13986 // Then, gather the new node's operands. 13987 SmallVector<SDValue, 8> Ops; 13988 Ops.push_back(N->getOperand(0)); // incoming chain 13989 Ops.push_back(N->getOperand(AddrOpIdx)); 13990 Ops.push_back(Inc); 13991 13992 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 13993 // Try to match the intrinsic's signature 13994 Ops.push_back(StN->getValue()); 13995 } else { 13996 // Loads (and of course intrinsics) match the intrinsics' signature, 13997 // so just add all but the alignment operand. 13998 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 13999 Ops.push_back(N->getOperand(i)); 14000 } 14001 14002 // For all node types, the alignment operand is always the last one. 14003 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 14004 14005 // If this is a non-standard-aligned STORE, the penultimate operand is the 14006 // stored value. Bitcast it to the aligned type. 14007 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 14008 SDValue &StVal = Ops[Ops.size()-2]; 14009 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 14010 } 14011 14012 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 14013 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 14014 MemN->getMemOperand()); 14015 14016 // Update the uses. 14017 SmallVector<SDValue, 5> NewResults; 14018 for (unsigned i = 0; i < NumResultVecs; ++i) 14019 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14020 14021 // If this is an non-standard-aligned LOAD, the first result is the loaded 14022 // value. Bitcast it to the expected result type. 14023 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 14024 SDValue &LdVal = NewResults[0]; 14025 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 14026 } 14027 14028 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 14029 DCI.CombineTo(N, NewResults); 14030 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14031 14032 break; 14033 } 14034 return SDValue(); 14035 } 14036 14037 static SDValue PerformVLDCombine(SDNode *N, 14038 TargetLowering::DAGCombinerInfo &DCI) { 14039 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14040 return SDValue(); 14041 14042 return CombineBaseUpdate(N, DCI); 14043 } 14044 14045 static SDValue PerformMVEVLDCombine(SDNode *N, 14046 TargetLowering::DAGCombinerInfo &DCI) { 14047 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14048 return SDValue(); 14049 14050 SelectionDAG &DAG = DCI.DAG; 14051 SDValue Addr = N->getOperand(2); 14052 MemSDNode *MemN = cast<MemSDNode>(N); 14053 SDLoc dl(N); 14054 14055 // For the stores, where there are multiple intrinsics we only actually want 14056 // to post-inc the last of the them. 14057 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 14058 if (IntNo == Intrinsic::arm_mve_vst2q && 14059 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1) 14060 return SDValue(); 14061 if (IntNo == Intrinsic::arm_mve_vst4q && 14062 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3) 14063 return SDValue(); 14064 14065 // Search for a use of the address operand that is an increment. 14066 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 14067 UE = Addr.getNode()->use_end(); 14068 UI != UE; ++UI) { 14069 SDNode *User = *UI; 14070 if (User->getOpcode() != ISD::ADD || 14071 UI.getUse().getResNo() != Addr.getResNo()) 14072 continue; 14073 14074 // Check that the add is independent of the load/store. Otherwise, folding 14075 // it would create a cycle. We can avoid searching through Addr as it's a 14076 // predecessor to both. 14077 SmallPtrSet<const SDNode *, 32> Visited; 14078 SmallVector<const SDNode *, 16> Worklist; 14079 Visited.insert(Addr.getNode()); 14080 Worklist.push_back(N); 14081 Worklist.push_back(User); 14082 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 14083 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14084 continue; 14085 14086 // Find the new opcode for the updating load/store. 14087 bool isLoadOp = true; 14088 unsigned NewOpc = 0; 14089 unsigned NumVecs = 0; 14090 switch (IntNo) { 14091 default: 14092 llvm_unreachable("unexpected intrinsic for MVE VLDn combine"); 14093 case Intrinsic::arm_mve_vld2q: 14094 NewOpc = ARMISD::VLD2_UPD; 14095 NumVecs = 2; 14096 break; 14097 case Intrinsic::arm_mve_vld4q: 14098 NewOpc = ARMISD::VLD4_UPD; 14099 NumVecs = 4; 14100 break; 14101 case Intrinsic::arm_mve_vst2q: 14102 NewOpc = ARMISD::VST2_UPD; 14103 NumVecs = 2; 14104 isLoadOp = false; 14105 break; 14106 case Intrinsic::arm_mve_vst4q: 14107 NewOpc = ARMISD::VST4_UPD; 14108 NumVecs = 4; 14109 isLoadOp = false; 14110 break; 14111 } 14112 14113 // Find the size of memory referenced by the load/store. 14114 EVT VecTy; 14115 if (isLoadOp) { 14116 VecTy = N->getValueType(0); 14117 } else { 14118 VecTy = N->getOperand(3).getValueType(); 14119 } 14120 14121 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14122 14123 // If the increment is a constant, it must match the memory ref size. 14124 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14125 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 14126 if (!CInc || CInc->getZExtValue() != NumBytes) 14127 continue; 14128 14129 // Create the new updating load/store node. 14130 // First, create an SDVTList for the new updating node's results. 14131 EVT Tys[6]; 14132 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 14133 unsigned n; 14134 for (n = 0; n < NumResultVecs; ++n) 14135 Tys[n] = VecTy; 14136 Tys[n++] = MVT::i32; 14137 Tys[n] = MVT::Other; 14138 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 14139 14140 // Then, gather the new node's operands. 14141 SmallVector<SDValue, 8> Ops; 14142 Ops.push_back(N->getOperand(0)); // incoming chain 14143 Ops.push_back(N->getOperand(2)); // ptr 14144 Ops.push_back(Inc); 14145 14146 for (unsigned i = 3; i < N->getNumOperands(); ++i) 14147 Ops.push_back(N->getOperand(i)); 14148 14149 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy, 14150 MemN->getMemOperand()); 14151 14152 // Update the uses. 14153 SmallVector<SDValue, 5> NewResults; 14154 for (unsigned i = 0; i < NumResultVecs; ++i) 14155 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14156 14157 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain 14158 DCI.CombineTo(N, NewResults); 14159 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14160 14161 break; 14162 } 14163 14164 return SDValue(); 14165 } 14166 14167 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 14168 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 14169 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 14170 /// return true. 14171 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 14172 SelectionDAG &DAG = DCI.DAG; 14173 EVT VT = N->getValueType(0); 14174 // vldN-dup instructions only support 64-bit vectors for N > 1. 14175 if (!VT.is64BitVector()) 14176 return false; 14177 14178 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 14179 SDNode *VLD = N->getOperand(0).getNode(); 14180 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 14181 return false; 14182 unsigned NumVecs = 0; 14183 unsigned NewOpc = 0; 14184 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 14185 if (IntNo == Intrinsic::arm_neon_vld2lane) { 14186 NumVecs = 2; 14187 NewOpc = ARMISD::VLD2DUP; 14188 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 14189 NumVecs = 3; 14190 NewOpc = ARMISD::VLD3DUP; 14191 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 14192 NumVecs = 4; 14193 NewOpc = ARMISD::VLD4DUP; 14194 } else { 14195 return false; 14196 } 14197 14198 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 14199 // numbers match the load. 14200 unsigned VLDLaneNo = 14201 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 14202 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 14203 UI != UE; ++UI) { 14204 // Ignore uses of the chain result. 14205 if (UI.getUse().getResNo() == NumVecs) 14206 continue; 14207 SDNode *User = *UI; 14208 if (User->getOpcode() != ARMISD::VDUPLANE || 14209 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 14210 return false; 14211 } 14212 14213 // Create the vldN-dup node. 14214 EVT Tys[5]; 14215 unsigned n; 14216 for (n = 0; n < NumVecs; ++n) 14217 Tys[n] = VT; 14218 Tys[n] = MVT::Other; 14219 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 14220 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 14221 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 14222 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 14223 Ops, VLDMemInt->getMemoryVT(), 14224 VLDMemInt->getMemOperand()); 14225 14226 // Update the uses. 14227 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 14228 UI != UE; ++UI) { 14229 unsigned ResNo = UI.getUse().getResNo(); 14230 // Ignore uses of the chain result. 14231 if (ResNo == NumVecs) 14232 continue; 14233 SDNode *User = *UI; 14234 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 14235 } 14236 14237 // Now the vldN-lane intrinsic is dead except for its chain result. 14238 // Update uses of the chain. 14239 std::vector<SDValue> VLDDupResults; 14240 for (unsigned n = 0; n < NumVecs; ++n) 14241 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 14242 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 14243 DCI.CombineTo(VLD, VLDDupResults); 14244 14245 return true; 14246 } 14247 14248 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 14249 /// ARMISD::VDUPLANE. 14250 static SDValue PerformVDUPLANECombine(SDNode *N, 14251 TargetLowering::DAGCombinerInfo &DCI, 14252 const ARMSubtarget *Subtarget) { 14253 SDValue Op = N->getOperand(0); 14254 EVT VT = N->getValueType(0); 14255 14256 // On MVE, we just convert the VDUPLANE to a VDUP with an extract. 14257 if (Subtarget->hasMVEIntegerOps()) { 14258 EVT ExtractVT = VT.getVectorElementType(); 14259 // We need to ensure we are creating a legal type. 14260 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT)) 14261 ExtractVT = MVT::i32; 14262 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT, 14263 N->getOperand(0), N->getOperand(1)); 14264 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract); 14265 } 14266 14267 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 14268 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 14269 if (CombineVLDDUP(N, DCI)) 14270 return SDValue(N, 0); 14271 14272 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 14273 // redundant. Ignore bit_converts for now; element sizes are checked below. 14274 while (Op.getOpcode() == ISD::BITCAST) 14275 Op = Op.getOperand(0); 14276 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 14277 return SDValue(); 14278 14279 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 14280 unsigned EltSize = Op.getScalarValueSizeInBits(); 14281 // The canonical VMOV for a zero vector uses a 32-bit element size. 14282 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14283 unsigned EltBits; 14284 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 14285 EltSize = 8; 14286 if (EltSize > VT.getScalarSizeInBits()) 14287 return SDValue(); 14288 14289 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 14290 } 14291 14292 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 14293 static SDValue PerformVDUPCombine(SDNode *N, 14294 TargetLowering::DAGCombinerInfo &DCI, 14295 const ARMSubtarget *Subtarget) { 14296 SelectionDAG &DAG = DCI.DAG; 14297 SDValue Op = N->getOperand(0); 14298 SDLoc dl(N); 14299 14300 if (Subtarget->hasMVEIntegerOps()) { 14301 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will 14302 // need to come from a GPR. 14303 if (Op.getValueType() == MVT::f32) 14304 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 14305 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op)); 14306 else if (Op.getValueType() == MVT::f16) 14307 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 14308 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op)); 14309 } 14310 14311 if (!Subtarget->hasNEON()) 14312 return SDValue(); 14313 14314 // Match VDUP(LOAD) -> VLD1DUP. 14315 // We match this pattern here rather than waiting for isel because the 14316 // transform is only legal for unindexed loads. 14317 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 14318 if (LD && Op.hasOneUse() && LD->isUnindexed() && 14319 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 14320 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 14321 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 14322 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 14323 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 14324 Ops, LD->getMemoryVT(), 14325 LD->getMemOperand()); 14326 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 14327 return VLDDup; 14328 } 14329 14330 return SDValue(); 14331 } 14332 14333 static SDValue PerformLOADCombine(SDNode *N, 14334 TargetLowering::DAGCombinerInfo &DCI) { 14335 EVT VT = N->getValueType(0); 14336 14337 // If this is a legal vector load, try to combine it into a VLD1_UPD. 14338 if (ISD::isNormalLoad(N) && VT.isVector() && 14339 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 14340 return CombineBaseUpdate(N, DCI); 14341 14342 return SDValue(); 14343 } 14344 14345 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 14346 // pack all of the elements in one place. Next, store to memory in fewer 14347 // chunks. 14348 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St, 14349 SelectionDAG &DAG) { 14350 SDValue StVal = St->getValue(); 14351 EVT VT = StVal.getValueType(); 14352 if (!St->isTruncatingStore() || !VT.isVector()) 14353 return SDValue(); 14354 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14355 EVT StVT = St->getMemoryVT(); 14356 unsigned NumElems = VT.getVectorNumElements(); 14357 assert(StVT != VT && "Cannot truncate to the same type"); 14358 unsigned FromEltSz = VT.getScalarSizeInBits(); 14359 unsigned ToEltSz = StVT.getScalarSizeInBits(); 14360 14361 // From, To sizes and ElemCount must be pow of two 14362 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) 14363 return SDValue(); 14364 14365 // We are going to use the original vector elt for storing. 14366 // Accumulated smaller vector elements must be a multiple of the store size. 14367 if (0 != (NumElems * FromEltSz) % ToEltSz) 14368 return SDValue(); 14369 14370 unsigned SizeRatio = FromEltSz / ToEltSz; 14371 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 14372 14373 // Create a type on which we perform the shuffle. 14374 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 14375 NumElems * SizeRatio); 14376 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 14377 14378 SDLoc DL(St); 14379 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 14380 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14381 for (unsigned i = 0; i < NumElems; ++i) 14382 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1 14383 : i * SizeRatio; 14384 14385 // Can't shuffle using an illegal type. 14386 if (!TLI.isTypeLegal(WideVecVT)) 14387 return SDValue(); 14388 14389 SDValue Shuff = DAG.getVectorShuffle( 14390 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec); 14391 // At this point all of the data is stored at the bottom of the 14392 // register. We now need to save it to mem. 14393 14394 // Find the largest store unit 14395 MVT StoreType = MVT::i8; 14396 for (MVT Tp : MVT::integer_valuetypes()) { 14397 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 14398 StoreType = Tp; 14399 } 14400 // Didn't find a legal store type. 14401 if (!TLI.isTypeLegal(StoreType)) 14402 return SDValue(); 14403 14404 // Bitcast the original vector into a vector of store-size units 14405 EVT StoreVecVT = 14406 EVT::getVectorVT(*DAG.getContext(), StoreType, 14407 VT.getSizeInBits() / EVT(StoreType).getSizeInBits()); 14408 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 14409 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 14410 SmallVector<SDValue, 8> Chains; 14411 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 14412 TLI.getPointerTy(DAG.getDataLayout())); 14413 SDValue BasePtr = St->getBasePtr(); 14414 14415 // Perform one or more big stores into memory. 14416 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits(); 14417 for (unsigned I = 0; I < E; I++) { 14418 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType, 14419 ShuffWide, DAG.getIntPtrConstant(I, DL)); 14420 SDValue Ch = 14421 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(), 14422 St->getAlignment(), St->getMemOperand()->getFlags()); 14423 BasePtr = 14424 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment); 14425 Chains.push_back(Ch); 14426 } 14427 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 14428 } 14429 14430 // Try taking a single vector store from an truncate (which would otherwise turn 14431 // into an expensive buildvector) and splitting it into a series of narrowing 14432 // stores. 14433 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St, 14434 SelectionDAG &DAG) { 14435 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed()) 14436 return SDValue(); 14437 SDValue Trunc = St->getValue(); 14438 if (Trunc->getOpcode() != ISD::TRUNCATE && Trunc->getOpcode() != ISD::FP_ROUND) 14439 return SDValue(); 14440 EVT FromVT = Trunc->getOperand(0).getValueType(); 14441 EVT ToVT = Trunc.getValueType(); 14442 if (!ToVT.isVector()) 14443 return SDValue(); 14444 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 14445 EVT ToEltVT = ToVT.getVectorElementType(); 14446 EVT FromEltVT = FromVT.getVectorElementType(); 14447 14448 unsigned NumElements = 0; 14449 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8)) 14450 NumElements = 4; 14451 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8) 14452 NumElements = 8; 14453 if (FromEltVT == MVT::f32 && ToEltVT == MVT::f16) 14454 NumElements = 4; 14455 if (NumElements == 0 || 14456 (FromEltVT != MVT::f32 && FromVT.getVectorNumElements() == NumElements) || 14457 FromVT.getVectorNumElements() % NumElements != 0) 14458 return SDValue(); 14459 14460 // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so 14461 // use the VMOVN over splitting the store. We are looking for patterns of: 14462 // !rev: 0 N 1 N+1 2 N+2 ... 14463 // rev: N 0 N+1 1 N+2 2 ... 14464 auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) { 14465 unsigned NumElts = ToVT.getVectorNumElements(); 14466 if (NumElts != M.size()) 14467 return false; 14468 14469 unsigned Off0 = rev ? NumElts : 0; 14470 unsigned Off1 = rev ? 0 : NumElts; 14471 14472 for (unsigned i = 0; i < NumElts; i += 2) { 14473 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2)) 14474 return false; 14475 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2)) 14476 return false; 14477 } 14478 14479 return true; 14480 }; 14481 14482 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0))) 14483 if (isVMOVNOriginalMask(Shuffle->getMask(), false) || 14484 isVMOVNOriginalMask(Shuffle->getMask(), true)) 14485 return SDValue(); 14486 14487 LLVMContext &C = *DAG.getContext(); 14488 SDLoc DL(St); 14489 // Details about the old store 14490 SDValue Ch = St->getChain(); 14491 SDValue BasePtr = St->getBasePtr(); 14492 Align Alignment = St->getOriginalAlign(); 14493 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags(); 14494 AAMDNodes AAInfo = St->getAAInfo(); 14495 14496 // We split the store into slices of NumElements. fp16 trunc stores are vcvt 14497 // and then stored as truncating integer stores. 14498 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements); 14499 EVT NewToVT = EVT::getVectorVT( 14500 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements); 14501 14502 SmallVector<SDValue, 4> Stores; 14503 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 14504 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8; 14505 SDValue NewPtr = 14506 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset)); 14507 14508 SDValue Extract = 14509 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0), 14510 DAG.getConstant(i * NumElements, DL, MVT::i32)); 14511 14512 if (ToEltVT == MVT::f16) { 14513 SDValue FPTrunc = 14514 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16), 14515 Extract, DAG.getConstant(0, DL, MVT::i32)); 14516 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc); 14517 } 14518 14519 SDValue Store = DAG.getTruncStore( 14520 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset), 14521 NewToVT, Alignment.value(), MMOFlags, AAInfo); 14522 Stores.push_back(Store); 14523 } 14524 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores); 14525 } 14526 14527 /// PerformSTORECombine - Target-specific dag combine xforms for 14528 /// ISD::STORE. 14529 static SDValue PerformSTORECombine(SDNode *N, 14530 TargetLowering::DAGCombinerInfo &DCI, 14531 const ARMSubtarget *Subtarget) { 14532 StoreSDNode *St = cast<StoreSDNode>(N); 14533 if (St->isVolatile()) 14534 return SDValue(); 14535 SDValue StVal = St->getValue(); 14536 EVT VT = StVal.getValueType(); 14537 14538 if (Subtarget->hasNEON()) 14539 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG)) 14540 return Store; 14541 14542 if (Subtarget->hasMVEIntegerOps()) 14543 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG)) 14544 return NewToken; 14545 14546 if (!ISD::isNormalStore(St)) 14547 return SDValue(); 14548 14549 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 14550 // ARM stores of arguments in the same cache line. 14551 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 14552 StVal.getNode()->hasOneUse()) { 14553 SelectionDAG &DAG = DCI.DAG; 14554 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 14555 SDLoc DL(St); 14556 SDValue BasePtr = St->getBasePtr(); 14557 SDValue NewST1 = DAG.getStore( 14558 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 14559 BasePtr, St->getPointerInfo(), St->getAlignment(), 14560 St->getMemOperand()->getFlags()); 14561 14562 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 14563 DAG.getConstant(4, DL, MVT::i32)); 14564 return DAG.getStore(NewST1.getValue(0), DL, 14565 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 14566 OffsetPtr, St->getPointerInfo(), 14567 std::min(4U, St->getAlignment() / 2), 14568 St->getMemOperand()->getFlags()); 14569 } 14570 14571 if (StVal.getValueType() == MVT::i64 && 14572 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14573 14574 // Bitcast an i64 store extracted from a vector to f64. 14575 // Otherwise, the i64 value will be legalized to a pair of i32 values. 14576 SelectionDAG &DAG = DCI.DAG; 14577 SDLoc dl(StVal); 14578 SDValue IntVec = StVal.getOperand(0); 14579 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 14580 IntVec.getValueType().getVectorNumElements()); 14581 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 14582 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 14583 Vec, StVal.getOperand(1)); 14584 dl = SDLoc(N); 14585 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 14586 // Make the DAGCombiner fold the bitcasts. 14587 DCI.AddToWorklist(Vec.getNode()); 14588 DCI.AddToWorklist(ExtElt.getNode()); 14589 DCI.AddToWorklist(V.getNode()); 14590 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 14591 St->getPointerInfo(), St->getAlignment(), 14592 St->getMemOperand()->getFlags(), St->getAAInfo()); 14593 } 14594 14595 // If this is a legal vector store, try to combine it into a VST1_UPD. 14596 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() && 14597 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 14598 return CombineBaseUpdate(N, DCI); 14599 14600 return SDValue(); 14601 } 14602 14603 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 14604 /// can replace combinations of VMUL and VCVT (floating-point to integer) 14605 /// when the VMUL has a constant operand that is a power of 2. 14606 /// 14607 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 14608 /// vmul.f32 d16, d17, d16 14609 /// vcvt.s32.f32 d16, d16 14610 /// becomes: 14611 /// vcvt.s32.f32 d16, d16, #3 14612 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 14613 const ARMSubtarget *Subtarget) { 14614 if (!Subtarget->hasNEON()) 14615 return SDValue(); 14616 14617 SDValue Op = N->getOperand(0); 14618 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 14619 Op.getOpcode() != ISD::FMUL) 14620 return SDValue(); 14621 14622 SDValue ConstVec = Op->getOperand(1); 14623 if (!isa<BuildVectorSDNode>(ConstVec)) 14624 return SDValue(); 14625 14626 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 14627 uint32_t FloatBits = FloatTy.getSizeInBits(); 14628 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 14629 uint32_t IntBits = IntTy.getSizeInBits(); 14630 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 14631 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 14632 // These instructions only exist converting from f32 to i32. We can handle 14633 // smaller integers by generating an extra truncate, but larger ones would 14634 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 14635 // these intructions only support v2i32/v4i32 types. 14636 return SDValue(); 14637 } 14638 14639 BitVector UndefElements; 14640 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 14641 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 14642 if (C == -1 || C == 0 || C > 32) 14643 return SDValue(); 14644 14645 SDLoc dl(N); 14646 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 14647 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 14648 Intrinsic::arm_neon_vcvtfp2fxu; 14649 SDValue FixConv = DAG.getNode( 14650 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 14651 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 14652 DAG.getConstant(C, dl, MVT::i32)); 14653 14654 if (IntBits < FloatBits) 14655 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 14656 14657 return FixConv; 14658 } 14659 14660 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 14661 /// can replace combinations of VCVT (integer to floating-point) and VDIV 14662 /// when the VDIV has a constant operand that is a power of 2. 14663 /// 14664 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 14665 /// vcvt.f32.s32 d16, d16 14666 /// vdiv.f32 d16, d17, d16 14667 /// becomes: 14668 /// vcvt.f32.s32 d16, d16, #3 14669 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 14670 const ARMSubtarget *Subtarget) { 14671 if (!Subtarget->hasNEON()) 14672 return SDValue(); 14673 14674 SDValue Op = N->getOperand(0); 14675 unsigned OpOpcode = Op.getNode()->getOpcode(); 14676 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 14677 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 14678 return SDValue(); 14679 14680 SDValue ConstVec = N->getOperand(1); 14681 if (!isa<BuildVectorSDNode>(ConstVec)) 14682 return SDValue(); 14683 14684 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 14685 uint32_t FloatBits = FloatTy.getSizeInBits(); 14686 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 14687 uint32_t IntBits = IntTy.getSizeInBits(); 14688 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 14689 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 14690 // These instructions only exist converting from i32 to f32. We can handle 14691 // smaller integers by generating an extra extend, but larger ones would 14692 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 14693 // these intructions only support v2i32/v4i32 types. 14694 return SDValue(); 14695 } 14696 14697 BitVector UndefElements; 14698 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 14699 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 14700 if (C == -1 || C == 0 || C > 32) 14701 return SDValue(); 14702 14703 SDLoc dl(N); 14704 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 14705 SDValue ConvInput = Op.getOperand(0); 14706 if (IntBits < FloatBits) 14707 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 14708 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 14709 ConvInput); 14710 14711 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 14712 Intrinsic::arm_neon_vcvtfxu2fp; 14713 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 14714 Op.getValueType(), 14715 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 14716 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 14717 } 14718 14719 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG, 14720 const ARMSubtarget *ST) { 14721 if (!ST->hasMVEIntegerOps()) 14722 return SDValue(); 14723 14724 assert(N->getOpcode() == ISD::VECREDUCE_ADD); 14725 EVT ResVT = N->getValueType(0); 14726 SDValue N0 = N->getOperand(0); 14727 SDLoc dl(N); 14728 14729 // We are looking for something that will have illegal types if left alone, 14730 // but that we can convert to a single instruction undef MVE. For example 14731 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A 14732 // or 14733 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B 14734 14735 // Cases: 14736 // VADDV u/s 8/16/32 14737 // VMLAV u/s 8/16/32 14738 // VADDLV u/s 32 14739 // VMLALV u/s 16/32 14740 14741 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) { 14742 if (ResVT != RetTy || N0->getOpcode() != ExtendCode) 14743 return SDValue(); 14744 SDValue A = N0->getOperand(0); 14745 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14746 return A; 14747 return SDValue(); 14748 }; 14749 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode, 14750 ArrayRef<MVT> ExtTypes, SDValue &Mask) { 14751 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT || 14752 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode())) 14753 return SDValue(); 14754 Mask = N0->getOperand(0); 14755 SDValue Ext = N0->getOperand(1); 14756 if (Ext->getOpcode() != ExtendCode) 14757 return SDValue(); 14758 SDValue A = Ext->getOperand(0); 14759 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14760 return A; 14761 return SDValue(); 14762 }; 14763 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 14764 SDValue &A, SDValue &B) { 14765 if (ResVT != RetTy || N0->getOpcode() != ISD::MUL) 14766 return false; 14767 SDValue ExtA = N0->getOperand(0); 14768 SDValue ExtB = N0->getOperand(1); 14769 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 14770 return false; 14771 A = ExtA->getOperand(0); 14772 B = ExtB->getOperand(0); 14773 if (A.getValueType() == B.getValueType() && 14774 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14775 return true; 14776 return false; 14777 }; 14778 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 14779 SDValue &A, SDValue &B, SDValue &Mask) { 14780 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT || 14781 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode())) 14782 return false; 14783 Mask = N0->getOperand(0); 14784 SDValue Mul = N0->getOperand(1); 14785 if (Mul->getOpcode() != ISD::MUL) 14786 return false; 14787 SDValue ExtA = Mul->getOperand(0); 14788 SDValue ExtB = Mul->getOperand(1); 14789 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 14790 return false; 14791 A = ExtA->getOperand(0); 14792 B = ExtB->getOperand(0); 14793 if (A.getValueType() == B.getValueType() && 14794 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14795 return true; 14796 return false; 14797 }; 14798 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) { 14799 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops); 14800 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node, 14801 SDValue(Node.getNode(), 1)); 14802 }; 14803 14804 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8})) 14805 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A); 14806 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8})) 14807 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A); 14808 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32})) 14809 return Create64bitNode(ARMISD::VADDLVs, {A}); 14810 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32})) 14811 return Create64bitNode(ARMISD::VADDLVu, {A}); 14812 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8})) 14813 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14814 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A)); 14815 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8})) 14816 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14817 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A)); 14818 14819 SDValue Mask; 14820 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask)) 14821 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask); 14822 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask)) 14823 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask); 14824 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask)) 14825 return Create64bitNode(ARMISD::VADDLVps, {A, Mask}); 14826 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask)) 14827 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask}); 14828 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask)) 14829 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14830 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask)); 14831 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask)) 14832 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14833 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask)); 14834 14835 SDValue A, B; 14836 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 14837 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B); 14838 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 14839 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B); 14840 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B)) 14841 return Create64bitNode(ARMISD::VMLALVs, {A, B}); 14842 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B)) 14843 return Create64bitNode(ARMISD::VMLALVu, {A, B}); 14844 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B)) 14845 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14846 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B)); 14847 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B)) 14848 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14849 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B)); 14850 14851 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask)) 14852 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask); 14853 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask)) 14854 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask); 14855 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask)) 14856 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask}); 14857 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask)) 14858 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask}); 14859 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask)) 14860 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14861 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask)); 14862 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask)) 14863 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14864 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask)); 14865 return SDValue(); 14866 } 14867 14868 static SDValue PerformVMOVNCombine(SDNode *N, 14869 TargetLowering::DAGCombinerInfo &DCI) { 14870 SDValue Op0 = N->getOperand(0); 14871 SDValue Op1 = N->getOperand(1); 14872 unsigned IsTop = N->getConstantOperandVal(2); 14873 14874 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b) 14875 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b) 14876 if ((Op1->getOpcode() == ARMISD::VQMOVNs || 14877 Op1->getOpcode() == ARMISD::VQMOVNu) && 14878 Op1->getConstantOperandVal(2) == 0) 14879 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0), 14880 Op0, Op1->getOperand(1), N->getOperand(2)); 14881 14882 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from 14883 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting 14884 // into the top or bottom lanes. 14885 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 14886 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1)); 14887 APInt Op0DemandedElts = 14888 IsTop ? Op1DemandedElts 14889 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1)); 14890 14891 APInt KnownUndef, KnownZero; 14892 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 14893 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef, 14894 KnownZero, DCI)) 14895 return SDValue(N, 0); 14896 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef, 14897 KnownZero, DCI)) 14898 return SDValue(N, 0); 14899 14900 return SDValue(); 14901 } 14902 14903 static SDValue PerformVQMOVNCombine(SDNode *N, 14904 TargetLowering::DAGCombinerInfo &DCI) { 14905 SDValue Op0 = N->getOperand(0); 14906 unsigned IsTop = N->getConstantOperandVal(2); 14907 14908 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 14909 APInt Op0DemandedElts = 14910 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1) 14911 : APInt::getHighBitsSet(2, 1)); 14912 14913 APInt KnownUndef, KnownZero; 14914 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 14915 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef, 14916 KnownZero, DCI)) 14917 return SDValue(N, 0); 14918 return SDValue(); 14919 } 14920 14921 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) { 14922 SDLoc DL(N); 14923 SDValue Op0 = N->getOperand(0); 14924 SDValue Op1 = N->getOperand(1); 14925 14926 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from 14927 // uses of the intrinsics. 14928 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 14929 int ShiftAmt = C->getSExtValue(); 14930 if (ShiftAmt == 0) { 14931 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL); 14932 DAG.ReplaceAllUsesWith(N, Merge.getNode()); 14933 return SDValue(); 14934 } 14935 14936 if (ShiftAmt >= -32 && ShiftAmt < 0) { 14937 unsigned NewOpcode = 14938 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL; 14939 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1, 14940 DAG.getConstant(-ShiftAmt, DL, MVT::i32)); 14941 DAG.ReplaceAllUsesWith(N, NewShift.getNode()); 14942 return NewShift; 14943 } 14944 } 14945 14946 return SDValue(); 14947 } 14948 14949 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 14950 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N, 14951 DAGCombinerInfo &DCI) const { 14952 SelectionDAG &DAG = DCI.DAG; 14953 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14954 switch (IntNo) { 14955 default: 14956 // Don't do anything for most intrinsics. 14957 break; 14958 14959 // Vector shifts: check for immediate versions and lower them. 14960 // Note: This is done during DAG combining instead of DAG legalizing because 14961 // the build_vectors for 64-bit vector element shift counts are generally 14962 // not legal, and it is hard to see their values after they get legalized to 14963 // loads from a constant pool. 14964 case Intrinsic::arm_neon_vshifts: 14965 case Intrinsic::arm_neon_vshiftu: 14966 case Intrinsic::arm_neon_vrshifts: 14967 case Intrinsic::arm_neon_vrshiftu: 14968 case Intrinsic::arm_neon_vrshiftn: 14969 case Intrinsic::arm_neon_vqshifts: 14970 case Intrinsic::arm_neon_vqshiftu: 14971 case Intrinsic::arm_neon_vqshiftsu: 14972 case Intrinsic::arm_neon_vqshiftns: 14973 case Intrinsic::arm_neon_vqshiftnu: 14974 case Intrinsic::arm_neon_vqshiftnsu: 14975 case Intrinsic::arm_neon_vqrshiftns: 14976 case Intrinsic::arm_neon_vqrshiftnu: 14977 case Intrinsic::arm_neon_vqrshiftnsu: { 14978 EVT VT = N->getOperand(1).getValueType(); 14979 int64_t Cnt; 14980 unsigned VShiftOpc = 0; 14981 14982 switch (IntNo) { 14983 case Intrinsic::arm_neon_vshifts: 14984 case Intrinsic::arm_neon_vshiftu: 14985 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 14986 VShiftOpc = ARMISD::VSHLIMM; 14987 break; 14988 } 14989 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 14990 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 14991 : ARMISD::VSHRuIMM); 14992 break; 14993 } 14994 return SDValue(); 14995 14996 case Intrinsic::arm_neon_vrshifts: 14997 case Intrinsic::arm_neon_vrshiftu: 14998 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 14999 break; 15000 return SDValue(); 15001 15002 case Intrinsic::arm_neon_vqshifts: 15003 case Intrinsic::arm_neon_vqshiftu: 15004 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 15005 break; 15006 return SDValue(); 15007 15008 case Intrinsic::arm_neon_vqshiftsu: 15009 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 15010 break; 15011 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 15012 15013 case Intrinsic::arm_neon_vrshiftn: 15014 case Intrinsic::arm_neon_vqshiftns: 15015 case Intrinsic::arm_neon_vqshiftnu: 15016 case Intrinsic::arm_neon_vqshiftnsu: 15017 case Intrinsic::arm_neon_vqrshiftns: 15018 case Intrinsic::arm_neon_vqrshiftnu: 15019 case Intrinsic::arm_neon_vqrshiftnsu: 15020 // Narrowing shifts require an immediate right shift. 15021 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 15022 break; 15023 llvm_unreachable("invalid shift count for narrowing vector shift " 15024 "intrinsic"); 15025 15026 default: 15027 llvm_unreachable("unhandled vector shift"); 15028 } 15029 15030 switch (IntNo) { 15031 case Intrinsic::arm_neon_vshifts: 15032 case Intrinsic::arm_neon_vshiftu: 15033 // Opcode already set above. 15034 break; 15035 case Intrinsic::arm_neon_vrshifts: 15036 VShiftOpc = ARMISD::VRSHRsIMM; 15037 break; 15038 case Intrinsic::arm_neon_vrshiftu: 15039 VShiftOpc = ARMISD::VRSHRuIMM; 15040 break; 15041 case Intrinsic::arm_neon_vrshiftn: 15042 VShiftOpc = ARMISD::VRSHRNIMM; 15043 break; 15044 case Intrinsic::arm_neon_vqshifts: 15045 VShiftOpc = ARMISD::VQSHLsIMM; 15046 break; 15047 case Intrinsic::arm_neon_vqshiftu: 15048 VShiftOpc = ARMISD::VQSHLuIMM; 15049 break; 15050 case Intrinsic::arm_neon_vqshiftsu: 15051 VShiftOpc = ARMISD::VQSHLsuIMM; 15052 break; 15053 case Intrinsic::arm_neon_vqshiftns: 15054 VShiftOpc = ARMISD::VQSHRNsIMM; 15055 break; 15056 case Intrinsic::arm_neon_vqshiftnu: 15057 VShiftOpc = ARMISD::VQSHRNuIMM; 15058 break; 15059 case Intrinsic::arm_neon_vqshiftnsu: 15060 VShiftOpc = ARMISD::VQSHRNsuIMM; 15061 break; 15062 case Intrinsic::arm_neon_vqrshiftns: 15063 VShiftOpc = ARMISD::VQRSHRNsIMM; 15064 break; 15065 case Intrinsic::arm_neon_vqrshiftnu: 15066 VShiftOpc = ARMISD::VQRSHRNuIMM; 15067 break; 15068 case Intrinsic::arm_neon_vqrshiftnsu: 15069 VShiftOpc = ARMISD::VQRSHRNsuIMM; 15070 break; 15071 } 15072 15073 SDLoc dl(N); 15074 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 15075 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 15076 } 15077 15078 case Intrinsic::arm_neon_vshiftins: { 15079 EVT VT = N->getOperand(1).getValueType(); 15080 int64_t Cnt; 15081 unsigned VShiftOpc = 0; 15082 15083 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 15084 VShiftOpc = ARMISD::VSLIIMM; 15085 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 15086 VShiftOpc = ARMISD::VSRIIMM; 15087 else { 15088 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 15089 } 15090 15091 SDLoc dl(N); 15092 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 15093 N->getOperand(1), N->getOperand(2), 15094 DAG.getConstant(Cnt, dl, MVT::i32)); 15095 } 15096 15097 case Intrinsic::arm_neon_vqrshifts: 15098 case Intrinsic::arm_neon_vqrshiftu: 15099 // No immediate versions of these to check for. 15100 break; 15101 15102 case Intrinsic::arm_mve_vqdmlah: 15103 case Intrinsic::arm_mve_vqdmlash: 15104 case Intrinsic::arm_mve_vqrdmlah: 15105 case Intrinsic::arm_mve_vqrdmlash: 15106 case Intrinsic::arm_mve_vmla_n_predicated: 15107 case Intrinsic::arm_mve_vmlas_n_predicated: 15108 case Intrinsic::arm_mve_vqdmlah_predicated: 15109 case Intrinsic::arm_mve_vqdmlash_predicated: 15110 case Intrinsic::arm_mve_vqrdmlah_predicated: 15111 case Intrinsic::arm_mve_vqrdmlash_predicated: { 15112 // These intrinsics all take an i32 scalar operand which is narrowed to the 15113 // size of a single lane of the vector type they return. So we don't need 15114 // any bits of that operand above that point, which allows us to eliminate 15115 // uxth/sxth. 15116 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits(); 15117 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 15118 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI)) 15119 return SDValue(); 15120 break; 15121 } 15122 15123 case Intrinsic::arm_mve_minv: 15124 case Intrinsic::arm_mve_maxv: 15125 case Intrinsic::arm_mve_minav: 15126 case Intrinsic::arm_mve_maxav: 15127 case Intrinsic::arm_mve_minv_predicated: 15128 case Intrinsic::arm_mve_maxv_predicated: 15129 case Intrinsic::arm_mve_minav_predicated: 15130 case Intrinsic::arm_mve_maxav_predicated: { 15131 // These intrinsics all take an i32 scalar operand which is narrowed to the 15132 // size of a single lane of the vector type they take as the other input. 15133 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits(); 15134 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 15135 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 15136 return SDValue(); 15137 break; 15138 } 15139 15140 case Intrinsic::arm_mve_addv: { 15141 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node, 15142 // which allow PerformADDVecReduce to turn it into VADDLV when possible. 15143 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15144 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs; 15145 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1)); 15146 } 15147 15148 case Intrinsic::arm_mve_addlv: 15149 case Intrinsic::arm_mve_addlv_predicated: { 15150 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR 15151 // which recombines the two outputs into an i64 15152 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15153 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ? 15154 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) : 15155 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps); 15156 15157 SmallVector<SDValue, 4> Ops; 15158 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++) 15159 if (i != 2) // skip the unsigned flag 15160 Ops.push_back(N->getOperand(i)); 15161 15162 SDLoc dl(N); 15163 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops); 15164 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0), 15165 val.getValue(1)); 15166 } 15167 } 15168 15169 return SDValue(); 15170 } 15171 15172 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 15173 /// lowers them. As with the vector shift intrinsics, this is done during DAG 15174 /// combining instead of DAG legalizing because the build_vectors for 64-bit 15175 /// vector element shift counts are generally not legal, and it is hard to see 15176 /// their values after they get legalized to loads from a constant pool. 15177 static SDValue PerformShiftCombine(SDNode *N, 15178 TargetLowering::DAGCombinerInfo &DCI, 15179 const ARMSubtarget *ST) { 15180 SelectionDAG &DAG = DCI.DAG; 15181 EVT VT = N->getValueType(0); 15182 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 15183 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 15184 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 15185 SDValue N1 = N->getOperand(1); 15186 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 15187 SDValue N0 = N->getOperand(0); 15188 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 15189 DAG.MaskedValueIsZero(N0.getOperand(0), 15190 APInt::getHighBitsSet(32, 16))) 15191 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 15192 } 15193 } 15194 15195 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 15196 N->getOperand(0)->getOpcode() == ISD::AND && 15197 N->getOperand(0)->hasOneUse()) { 15198 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 15199 return SDValue(); 15200 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 15201 // usually show up because instcombine prefers to canonicalize it to 15202 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 15203 // out of GEP lowering in some cases. 15204 SDValue N0 = N->getOperand(0); 15205 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15206 if (!ShiftAmtNode) 15207 return SDValue(); 15208 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 15209 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 15210 if (!AndMaskNode) 15211 return SDValue(); 15212 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 15213 // Don't transform uxtb/uxth. 15214 if (AndMask == 255 || AndMask == 65535) 15215 return SDValue(); 15216 if (isMask_32(AndMask)) { 15217 uint32_t MaskedBits = countLeadingZeros(AndMask); 15218 if (MaskedBits > ShiftAmt) { 15219 SDLoc DL(N); 15220 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 15221 DAG.getConstant(MaskedBits, DL, MVT::i32)); 15222 return DAG.getNode( 15223 ISD::SRL, DL, MVT::i32, SHL, 15224 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 15225 } 15226 } 15227 } 15228 15229 // Nothing to be done for scalar shifts. 15230 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15231 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 15232 return SDValue(); 15233 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 15234 return SDValue(); 15235 15236 int64_t Cnt; 15237 15238 switch (N->getOpcode()) { 15239 default: llvm_unreachable("unexpected shift opcode"); 15240 15241 case ISD::SHL: 15242 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 15243 SDLoc dl(N); 15244 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 15245 DAG.getConstant(Cnt, dl, MVT::i32)); 15246 } 15247 break; 15248 15249 case ISD::SRA: 15250 case ISD::SRL: 15251 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 15252 unsigned VShiftOpc = 15253 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 15254 SDLoc dl(N); 15255 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 15256 DAG.getConstant(Cnt, dl, MVT::i32)); 15257 } 15258 } 15259 return SDValue(); 15260 } 15261 15262 // Look for a sign/zero/fpextend extend of a larger than legal load. This can be 15263 // split into multiple extending loads, which are simpler to deal with than an 15264 // arbitrary extend. For fp extends we use an integer extending load and a VCVTL 15265 // to convert the type to an f32. 15266 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) { 15267 SDValue N0 = N->getOperand(0); 15268 if (N0.getOpcode() != ISD::LOAD) 15269 return SDValue(); 15270 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode()); 15271 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() || 15272 LD->getExtensionType() != ISD::NON_EXTLOAD) 15273 return SDValue(); 15274 EVT FromVT = LD->getValueType(0); 15275 EVT ToVT = N->getValueType(0); 15276 if (!ToVT.isVector()) 15277 return SDValue(); 15278 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 15279 EVT ToEltVT = ToVT.getVectorElementType(); 15280 EVT FromEltVT = FromVT.getVectorElementType(); 15281 15282 unsigned NumElements = 0; 15283 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8)) 15284 NumElements = 4; 15285 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8) 15286 NumElements = 8; 15287 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16) 15288 NumElements = 4; 15289 if (NumElements == 0 || 15290 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) || 15291 FromVT.getVectorNumElements() % NumElements != 0 || 15292 !isPowerOf2_32(NumElements)) 15293 return SDValue(); 15294 15295 LLVMContext &C = *DAG.getContext(); 15296 SDLoc DL(LD); 15297 // Details about the old load 15298 SDValue Ch = LD->getChain(); 15299 SDValue BasePtr = LD->getBasePtr(); 15300 Align Alignment = LD->getOriginalAlign(); 15301 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 15302 AAMDNodes AAInfo = LD->getAAInfo(); 15303 15304 ISD::LoadExtType NewExtType = 15305 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 15306 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType()); 15307 EVT NewFromVT = EVT::getVectorVT( 15308 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements); 15309 EVT NewToVT = EVT::getVectorVT( 15310 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements); 15311 15312 SmallVector<SDValue, 4> Loads; 15313 SmallVector<SDValue, 4> Chains; 15314 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 15315 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8; 15316 SDValue NewPtr = 15317 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset)); 15318 15319 SDValue NewLoad = 15320 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset, 15321 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT, 15322 Alignment.value(), MMOFlags, AAInfo); 15323 Loads.push_back(NewLoad); 15324 Chains.push_back(SDValue(NewLoad.getNode(), 1)); 15325 } 15326 15327 // Float truncs need to extended with VCVTB's into their floating point types. 15328 if (FromEltVT == MVT::f16) { 15329 SmallVector<SDValue, 4> Extends; 15330 15331 for (unsigned i = 0; i < Loads.size(); i++) { 15332 SDValue LoadBC = 15333 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]); 15334 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC, 15335 DAG.getConstant(0, DL, MVT::i32)); 15336 Extends.push_back(FPExt); 15337 } 15338 15339 Loads = Extends; 15340 } 15341 15342 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 15343 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain); 15344 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads); 15345 } 15346 15347 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 15348 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 15349 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 15350 const ARMSubtarget *ST) { 15351 SDValue N0 = N->getOperand(0); 15352 15353 // Check for sign- and zero-extensions of vector extract operations of 8- and 15354 // 16-bit vector elements. NEON and MVE support these directly. They are 15355 // handled during DAG combining because type legalization will promote them 15356 // to 32-bit types and it is messy to recognize the operations after that. 15357 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) && 15358 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 15359 SDValue Vec = N0.getOperand(0); 15360 SDValue Lane = N0.getOperand(1); 15361 EVT VT = N->getValueType(0); 15362 EVT EltVT = N0.getValueType(); 15363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15364 15365 if (VT == MVT::i32 && 15366 (EltVT == MVT::i8 || EltVT == MVT::i16) && 15367 TLI.isTypeLegal(Vec.getValueType()) && 15368 isa<ConstantSDNode>(Lane)) { 15369 15370 unsigned Opc = 0; 15371 switch (N->getOpcode()) { 15372 default: llvm_unreachable("unexpected opcode"); 15373 case ISD::SIGN_EXTEND: 15374 Opc = ARMISD::VGETLANEs; 15375 break; 15376 case ISD::ZERO_EXTEND: 15377 case ISD::ANY_EXTEND: 15378 Opc = ARMISD::VGETLANEu; 15379 break; 15380 } 15381 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 15382 } 15383 } 15384 15385 if (ST->hasMVEIntegerOps()) 15386 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 15387 return NewLoad; 15388 15389 return SDValue(); 15390 } 15391 15392 static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG, 15393 const ARMSubtarget *ST) { 15394 if (ST->hasMVEFloatOps()) 15395 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 15396 return NewLoad; 15397 15398 return SDValue(); 15399 } 15400 15401 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating 15402 /// saturates. 15403 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG, 15404 const ARMSubtarget *ST) { 15405 EVT VT = N->getValueType(0); 15406 SDValue N0 = N->getOperand(0); 15407 if (!ST->hasMVEIntegerOps()) 15408 return SDValue(); 15409 15410 if (VT != MVT::v4i32 && VT != MVT::v8i16) 15411 return SDValue(); 15412 15413 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) { 15414 // Check one is a smin and the other is a smax 15415 if (Min->getOpcode() != ISD::SMIN) 15416 std::swap(Min, Max); 15417 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX) 15418 return false; 15419 15420 APInt SaturateC; 15421 if (VT == MVT::v4i32) 15422 SaturateC = APInt(32, (1 << 15) - 1, true); 15423 else //if (VT == MVT::v8i16) 15424 SaturateC = APInt(16, (1 << 7) - 1, true); 15425 15426 APInt MinC, MaxC; 15427 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) || 15428 MinC != SaturateC) 15429 return false; 15430 if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) || 15431 MaxC != ~SaturateC) 15432 return false; 15433 return true; 15434 }; 15435 15436 if (IsSignedSaturate(N, N0.getNode())) { 15437 SDLoc DL(N); 15438 MVT ExtVT, HalfVT; 15439 if (VT == MVT::v4i32) { 15440 HalfVT = MVT::v8i16; 15441 ExtVT = MVT::v4i16; 15442 } else { // if (VT == MVT::v8i16) 15443 HalfVT = MVT::v16i8; 15444 ExtVT = MVT::v8i8; 15445 } 15446 15447 // Create a VQMOVNB with undef top lanes, then signed extended into the top 15448 // half. That extend will hopefully be removed if only the bottom bits are 15449 // demanded (though a truncating store, for example). 15450 SDValue VQMOVN = 15451 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT), 15452 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32)); 15453 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN); 15454 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast, 15455 DAG.getValueType(ExtVT)); 15456 } 15457 15458 auto IsUnsignedSaturate = [&](SDNode *Min) { 15459 // For unsigned, we just need to check for <= 0xffff 15460 if (Min->getOpcode() != ISD::UMIN) 15461 return false; 15462 15463 APInt SaturateC; 15464 if (VT == MVT::v4i32) 15465 SaturateC = APInt(32, (1 << 16) - 1, true); 15466 else //if (VT == MVT::v8i16) 15467 SaturateC = APInt(16, (1 << 8) - 1, true); 15468 15469 APInt MinC; 15470 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) || 15471 MinC != SaturateC) 15472 return false; 15473 return true; 15474 }; 15475 15476 if (IsUnsignedSaturate(N)) { 15477 SDLoc DL(N); 15478 MVT HalfVT; 15479 unsigned ExtConst; 15480 if (VT == MVT::v4i32) { 15481 HalfVT = MVT::v8i16; 15482 ExtConst = 0x0000FFFF; 15483 } else { //if (VT == MVT::v8i16) 15484 HalfVT = MVT::v16i8; 15485 ExtConst = 0x00FF; 15486 } 15487 15488 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with 15489 // an AND. That extend will hopefully be removed if only the bottom bits are 15490 // demanded (though a truncating store, for example). 15491 SDValue VQMOVN = 15492 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0, 15493 DAG.getConstant(0, DL, MVT::i32)); 15494 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN); 15495 return DAG.getNode(ISD::AND, DL, VT, Bitcast, 15496 DAG.getConstant(ExtConst, DL, VT)); 15497 } 15498 15499 return SDValue(); 15500 } 15501 15502 static const APInt *isPowerOf2Constant(SDValue V) { 15503 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 15504 if (!C) 15505 return nullptr; 15506 const APInt *CV = &C->getAPIntValue(); 15507 return CV->isPowerOf2() ? CV : nullptr; 15508 } 15509 15510 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 15511 // If we have a CMOV, OR and AND combination such as: 15512 // if (x & CN) 15513 // y |= CM; 15514 // 15515 // And: 15516 // * CN is a single bit; 15517 // * All bits covered by CM are known zero in y 15518 // 15519 // Then we can convert this into a sequence of BFI instructions. This will 15520 // always be a win if CM is a single bit, will always be no worse than the 15521 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 15522 // three bits (due to the extra IT instruction). 15523 15524 SDValue Op0 = CMOV->getOperand(0); 15525 SDValue Op1 = CMOV->getOperand(1); 15526 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 15527 auto CC = CCNode->getAPIntValue().getLimitedValue(); 15528 SDValue CmpZ = CMOV->getOperand(4); 15529 15530 // The compare must be against zero. 15531 if (!isNullConstant(CmpZ->getOperand(1))) 15532 return SDValue(); 15533 15534 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 15535 SDValue And = CmpZ->getOperand(0); 15536 if (And->getOpcode() != ISD::AND) 15537 return SDValue(); 15538 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 15539 if (!AndC) 15540 return SDValue(); 15541 SDValue X = And->getOperand(0); 15542 15543 if (CC == ARMCC::EQ) { 15544 // We're performing an "equal to zero" compare. Swap the operands so we 15545 // canonicalize on a "not equal to zero" compare. 15546 std::swap(Op0, Op1); 15547 } else { 15548 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 15549 } 15550 15551 if (Op1->getOpcode() != ISD::OR) 15552 return SDValue(); 15553 15554 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 15555 if (!OrC) 15556 return SDValue(); 15557 SDValue Y = Op1->getOperand(0); 15558 15559 if (Op0 != Y) 15560 return SDValue(); 15561 15562 // Now, is it profitable to continue? 15563 APInt OrCI = OrC->getAPIntValue(); 15564 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 15565 if (OrCI.countPopulation() > Heuristic) 15566 return SDValue(); 15567 15568 // Lastly, can we determine that the bits defined by OrCI 15569 // are zero in Y? 15570 KnownBits Known = DAG.computeKnownBits(Y); 15571 if ((OrCI & Known.Zero) != OrCI) 15572 return SDValue(); 15573 15574 // OK, we can do the combine. 15575 SDValue V = Y; 15576 SDLoc dl(X); 15577 EVT VT = X.getValueType(); 15578 unsigned BitInX = AndC->logBase2(); 15579 15580 if (BitInX != 0) { 15581 // We must shift X first. 15582 X = DAG.getNode(ISD::SRL, dl, VT, X, 15583 DAG.getConstant(BitInX, dl, VT)); 15584 } 15585 15586 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 15587 BitInY < NumActiveBits; ++BitInY) { 15588 if (OrCI[BitInY] == 0) 15589 continue; 15590 APInt Mask(VT.getSizeInBits(), 0); 15591 Mask.setBit(BitInY); 15592 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 15593 // Confusingly, the operand is an *inverted* mask. 15594 DAG.getConstant(~Mask, dl, VT)); 15595 } 15596 15597 return V; 15598 } 15599 15600 // Given N, the value controlling the conditional branch, search for the loop 15601 // intrinsic, returning it, along with how the value is used. We need to handle 15602 // patterns such as the following: 15603 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 15604 // (brcond (setcc (loop.decrement), 0, eq), exit) 15605 // (brcond (setcc (loop.decrement), 0, ne), header) 15606 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 15607 bool &Negate) { 15608 switch (N->getOpcode()) { 15609 default: 15610 break; 15611 case ISD::XOR: { 15612 if (!isa<ConstantSDNode>(N.getOperand(1))) 15613 return SDValue(); 15614 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 15615 return SDValue(); 15616 Negate = !Negate; 15617 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 15618 } 15619 case ISD::SETCC: { 15620 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 15621 if (!Const) 15622 return SDValue(); 15623 if (Const->isNullValue()) 15624 Imm = 0; 15625 else if (Const->isOne()) 15626 Imm = 1; 15627 else 15628 return SDValue(); 15629 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 15630 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 15631 } 15632 case ISD::INTRINSIC_W_CHAIN: { 15633 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 15634 if (IntOp != Intrinsic::test_set_loop_iterations && 15635 IntOp != Intrinsic::loop_decrement_reg) 15636 return SDValue(); 15637 return N; 15638 } 15639 } 15640 return SDValue(); 15641 } 15642 15643 static SDValue PerformHWLoopCombine(SDNode *N, 15644 TargetLowering::DAGCombinerInfo &DCI, 15645 const ARMSubtarget *ST) { 15646 15647 // The hwloop intrinsics that we're interested are used for control-flow, 15648 // either for entering or exiting the loop: 15649 // - test.set.loop.iterations will test whether its operand is zero. If it 15650 // is zero, the proceeding branch should not enter the loop. 15651 // - loop.decrement.reg also tests whether its operand is zero. If it is 15652 // zero, the proceeding branch should not branch back to the beginning of 15653 // the loop. 15654 // So here, we need to check that how the brcond is using the result of each 15655 // of the intrinsics to ensure that we're branching to the right place at the 15656 // right time. 15657 15658 ISD::CondCode CC; 15659 SDValue Cond; 15660 int Imm = 1; 15661 bool Negate = false; 15662 SDValue Chain = N->getOperand(0); 15663 SDValue Dest; 15664 15665 if (N->getOpcode() == ISD::BRCOND) { 15666 CC = ISD::SETEQ; 15667 Cond = N->getOperand(1); 15668 Dest = N->getOperand(2); 15669 } else { 15670 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 15671 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15672 Cond = N->getOperand(2); 15673 Dest = N->getOperand(4); 15674 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 15675 if (!Const->isOne() && !Const->isNullValue()) 15676 return SDValue(); 15677 Imm = Const->getZExtValue(); 15678 } else 15679 return SDValue(); 15680 } 15681 15682 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 15683 if (!Int) 15684 return SDValue(); 15685 15686 if (Negate) 15687 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32); 15688 15689 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 15690 return (CC == ISD::SETEQ && Imm == 0) || 15691 (CC == ISD::SETNE && Imm == 1) || 15692 (CC == ISD::SETLT && Imm == 1) || 15693 (CC == ISD::SETULT && Imm == 1); 15694 }; 15695 15696 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 15697 return (CC == ISD::SETEQ && Imm == 1) || 15698 (CC == ISD::SETNE && Imm == 0) || 15699 (CC == ISD::SETGT && Imm == 0) || 15700 (CC == ISD::SETUGT && Imm == 0) || 15701 (CC == ISD::SETGE && Imm == 1) || 15702 (CC == ISD::SETUGE && Imm == 1); 15703 }; 15704 15705 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 15706 "unsupported condition"); 15707 15708 SDLoc dl(Int); 15709 SelectionDAG &DAG = DCI.DAG; 15710 SDValue Elements = Int.getOperand(2); 15711 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 15712 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 15713 && "expected single br user"); 15714 SDNode *Br = *N->use_begin(); 15715 SDValue OtherTarget = Br->getOperand(1); 15716 15717 // Update the unconditional branch to branch to the given Dest. 15718 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 15719 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 15720 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 15721 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 15722 }; 15723 15724 if (IntOp == Intrinsic::test_set_loop_iterations) { 15725 SDValue Res; 15726 // We expect this 'instruction' to branch when the counter is zero. 15727 if (IsTrueIfZero(CC, Imm)) { 15728 SDValue Ops[] = { Chain, Elements, Dest }; 15729 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 15730 } else { 15731 // The logic is the reverse of what we need for WLS, so find the other 15732 // basic block target: the target of the proceeding br. 15733 UpdateUncondBr(Br, Dest, DAG); 15734 15735 SDValue Ops[] = { Chain, Elements, OtherTarget }; 15736 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 15737 } 15738 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 15739 return Res; 15740 } else { 15741 SDValue Size = DAG.getTargetConstant( 15742 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 15743 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 15744 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 15745 DAG.getVTList(MVT::i32, MVT::Other), Args); 15746 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 15747 15748 // We expect this instruction to branch when the count is not zero. 15749 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 15750 15751 // Update the unconditional branch to target the loop preheader if we've 15752 // found the condition has been reversed. 15753 if (Target == OtherTarget) 15754 UpdateUncondBr(Br, Dest, DAG); 15755 15756 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15757 SDValue(LoopDec.getNode(), 1), Chain); 15758 15759 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 15760 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 15761 } 15762 return SDValue(); 15763 } 15764 15765 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 15766 SDValue 15767 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 15768 SDValue Cmp = N->getOperand(4); 15769 if (Cmp.getOpcode() != ARMISD::CMPZ) 15770 // Only looking at NE cases. 15771 return SDValue(); 15772 15773 EVT VT = N->getValueType(0); 15774 SDLoc dl(N); 15775 SDValue LHS = Cmp.getOperand(0); 15776 SDValue RHS = Cmp.getOperand(1); 15777 SDValue Chain = N->getOperand(0); 15778 SDValue BB = N->getOperand(1); 15779 SDValue ARMcc = N->getOperand(2); 15780 ARMCC::CondCodes CC = 15781 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 15782 15783 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 15784 // -> (brcond Chain BB CC CPSR Cmp) 15785 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 15786 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 15787 LHS->getOperand(0)->hasOneUse()) { 15788 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 15789 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 15790 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 15791 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 15792 if ((LHS00C && LHS00C->getZExtValue() == 0) && 15793 (LHS01C && LHS01C->getZExtValue() == 1) && 15794 (LHS1C && LHS1C->getZExtValue() == 1) && 15795 (RHSC && RHSC->getZExtValue() == 0)) { 15796 return DAG.getNode( 15797 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 15798 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 15799 } 15800 } 15801 15802 return SDValue(); 15803 } 15804 15805 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 15806 SDValue 15807 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 15808 SDValue Cmp = N->getOperand(4); 15809 if (Cmp.getOpcode() != ARMISD::CMPZ) 15810 // Only looking at EQ and NE cases. 15811 return SDValue(); 15812 15813 EVT VT = N->getValueType(0); 15814 SDLoc dl(N); 15815 SDValue LHS = Cmp.getOperand(0); 15816 SDValue RHS = Cmp.getOperand(1); 15817 SDValue FalseVal = N->getOperand(0); 15818 SDValue TrueVal = N->getOperand(1); 15819 SDValue ARMcc = N->getOperand(2); 15820 ARMCC::CondCodes CC = 15821 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 15822 15823 // BFI is only available on V6T2+. 15824 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 15825 SDValue R = PerformCMOVToBFICombine(N, DAG); 15826 if (R) 15827 return R; 15828 } 15829 15830 // Simplify 15831 // mov r1, r0 15832 // cmp r1, x 15833 // mov r0, y 15834 // moveq r0, x 15835 // to 15836 // cmp r0, x 15837 // movne r0, y 15838 // 15839 // mov r1, r0 15840 // cmp r1, x 15841 // mov r0, x 15842 // movne r0, y 15843 // to 15844 // cmp r0, x 15845 // movne r0, y 15846 /// FIXME: Turn this into a target neutral optimization? 15847 SDValue Res; 15848 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 15849 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 15850 N->getOperand(3), Cmp); 15851 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 15852 SDValue ARMcc; 15853 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 15854 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 15855 N->getOperand(3), NewCmp); 15856 } 15857 15858 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 15859 // -> (cmov F T CC CPSR Cmp) 15860 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 15861 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 15862 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 15863 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 15864 if ((LHS0C && LHS0C->getZExtValue() == 0) && 15865 (LHS1C && LHS1C->getZExtValue() == 1) && 15866 (RHSC && RHSC->getZExtValue() == 0)) { 15867 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 15868 LHS->getOperand(2), LHS->getOperand(3), 15869 LHS->getOperand(4)); 15870 } 15871 } 15872 15873 if (!VT.isInteger()) 15874 return SDValue(); 15875 15876 // Materialize a boolean comparison for integers so we can avoid branching. 15877 if (isNullConstant(FalseVal)) { 15878 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 15879 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 15880 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 15881 // right 5 bits will make that 32 be 1, otherwise it will be 0. 15882 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 15883 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 15884 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 15885 DAG.getConstant(5, dl, MVT::i32)); 15886 } else { 15887 // CMOV 0, 1, ==, (CMPZ x, y) -> 15888 // (ADDCARRY (SUB x, y), t:0, t:1) 15889 // where t = (SUBCARRY 0, (SUB x, y), 0) 15890 // 15891 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 15892 // x != y. In other words, a carry C == 1 when x == y, C == 0 15893 // otherwise. 15894 // The final ADDCARRY computes 15895 // x - y + (0 - (x - y)) + C == C 15896 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 15897 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 15898 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 15899 // ISD::SUBCARRY returns a borrow but we want the carry here 15900 // actually. 15901 SDValue Carry = 15902 DAG.getNode(ISD::SUB, dl, MVT::i32, 15903 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 15904 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 15905 } 15906 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 15907 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 15908 // This seems pointless but will allow us to combine it further below. 15909 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 15910 SDValue Sub = 15911 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 15912 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 15913 Sub.getValue(1), SDValue()); 15914 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 15915 N->getOperand(3), CPSRGlue.getValue(1)); 15916 FalseVal = Sub; 15917 } 15918 } else if (isNullConstant(TrueVal)) { 15919 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 15920 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 15921 // This seems pointless but will allow us to combine it further below 15922 // Note that we change == for != as this is the dual for the case above. 15923 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 15924 SDValue Sub = 15925 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 15926 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 15927 Sub.getValue(1), SDValue()); 15928 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 15929 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 15930 N->getOperand(3), CPSRGlue.getValue(1)); 15931 FalseVal = Sub; 15932 } 15933 } 15934 15935 // On Thumb1, the DAG above may be further combined if z is a power of 2 15936 // (z == 2 ^ K). 15937 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 15938 // t1 = (USUBO (SUB x, y), 1) 15939 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 15940 // Result = if K != 0 then (SHL t2:0, K) else t2:0 15941 // 15942 // This also handles the special case of comparing against zero; it's 15943 // essentially, the same pattern, except there's no SUBS: 15944 // CMOV x, z, !=, (CMPZ x, 0) -> 15945 // t1 = (USUBO x, 1) 15946 // t2 = (SUBCARRY x, t1:0, t1:1) 15947 // Result = if K != 0 then (SHL t2:0, K) else t2:0 15948 const APInt *TrueConst; 15949 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 15950 ((FalseVal.getOpcode() == ARMISD::SUBS && 15951 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 15952 (FalseVal == LHS && isNullConstant(RHS))) && 15953 (TrueConst = isPowerOf2Constant(TrueVal))) { 15954 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 15955 unsigned ShiftAmount = TrueConst->logBase2(); 15956 if (ShiftAmount) 15957 TrueVal = DAG.getConstant(1, dl, VT); 15958 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 15959 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 15960 15961 if (ShiftAmount) 15962 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 15963 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 15964 } 15965 15966 if (Res.getNode()) { 15967 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 15968 // Capture demanded bits information that would be otherwise lost. 15969 if (Known.Zero == 0xfffffffe) 15970 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 15971 DAG.getValueType(MVT::i1)); 15972 else if (Known.Zero == 0xffffff00) 15973 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 15974 DAG.getValueType(MVT::i8)); 15975 else if (Known.Zero == 0xffff0000) 15976 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 15977 DAG.getValueType(MVT::i16)); 15978 } 15979 15980 return Res; 15981 } 15982 15983 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG, 15984 const ARMSubtarget *ST) { 15985 SDValue Src = N->getOperand(0); 15986 EVT DstVT = N->getValueType(0); 15987 15988 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE. 15989 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) { 15990 EVT SrcVT = Src.getValueType(); 15991 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits()) 15992 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0)); 15993 } 15994 15995 // We may have a bitcast of something that has already had this bitcast 15996 // combine performed on it, so skip past any VECTOR_REG_CASTs. 15997 while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST) 15998 Src = Src.getOperand(0); 15999 16000 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that 16001 // would be generated is at least the width of the element type. 16002 EVT SrcVT = Src.getValueType(); 16003 if ((Src.getOpcode() == ARMISD::VMOVIMM || 16004 Src.getOpcode() == ARMISD::VMVNIMM || 16005 Src.getOpcode() == ARMISD::VMOVFPIMM) && 16006 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() && 16007 DAG.getDataLayout().isBigEndian()) 16008 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src); 16009 16010 return SDValue(); 16011 } 16012 16013 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 16014 DAGCombinerInfo &DCI) const { 16015 switch (N->getOpcode()) { 16016 default: break; 16017 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget); 16018 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 16019 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 16020 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 16021 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 16022 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget); 16023 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 16024 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 16025 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 16026 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 16027 case ISD::BRCOND: 16028 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 16029 case ARMISD::ADDC: 16030 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 16031 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 16032 case ARMISD::BFI: return PerformBFICombine(N, DCI); 16033 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 16034 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 16035 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI); 16036 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI); 16037 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget); 16038 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 16039 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 16040 case ISD::EXTRACT_VECTOR_ELT: return PerformExtractEltCombine(N, DCI); 16041 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 16042 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget); 16043 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 16044 case ISD::FP_TO_SINT: 16045 case ISD::FP_TO_UINT: 16046 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 16047 case ISD::FDIV: 16048 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 16049 case ISD::INTRINSIC_WO_CHAIN: 16050 return PerformIntrinsicCombine(N, DCI); 16051 case ISD::SHL: 16052 case ISD::SRA: 16053 case ISD::SRL: 16054 return PerformShiftCombine(N, DCI, Subtarget); 16055 case ISD::SIGN_EXTEND: 16056 case ISD::ZERO_EXTEND: 16057 case ISD::ANY_EXTEND: 16058 return PerformExtendCombine(N, DCI.DAG, Subtarget); 16059 case ISD::FP_EXTEND: 16060 return PerformFPExtendCombine(N, DCI.DAG, Subtarget); 16061 case ISD::SMIN: 16062 case ISD::UMIN: 16063 case ISD::SMAX: 16064 case ISD::UMAX: 16065 return PerformMinMaxCombine(N, DCI.DAG, Subtarget); 16066 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 16067 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 16068 case ISD::LOAD: return PerformLOADCombine(N, DCI); 16069 case ARMISD::VLD1DUP: 16070 case ARMISD::VLD2DUP: 16071 case ARMISD::VLD3DUP: 16072 case ARMISD::VLD4DUP: 16073 return PerformVLDCombine(N, DCI); 16074 case ARMISD::BUILD_VECTOR: 16075 return PerformARMBUILD_VECTORCombine(N, DCI); 16076 case ISD::BITCAST: 16077 return PerformBITCASTCombine(N, DCI.DAG, Subtarget); 16078 case ARMISD::PREDICATE_CAST: 16079 return PerformPREDICATE_CASTCombine(N, DCI); 16080 case ARMISD::VECTOR_REG_CAST: 16081 return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget); 16082 case ARMISD::VCMP: 16083 return PerformVCMPCombine(N, DCI, Subtarget); 16084 case ISD::VECREDUCE_ADD: 16085 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget); 16086 case ARMISD::VMOVN: 16087 return PerformVMOVNCombine(N, DCI); 16088 case ARMISD::VQMOVNs: 16089 case ARMISD::VQMOVNu: 16090 return PerformVQMOVNCombine(N, DCI); 16091 case ARMISD::ASRL: 16092 case ARMISD::LSRL: 16093 case ARMISD::LSLL: 16094 return PerformLongShiftCombine(N, DCI.DAG); 16095 case ARMISD::SMULWB: { 16096 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16097 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 16098 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 16099 return SDValue(); 16100 break; 16101 } 16102 case ARMISD::SMULWT: { 16103 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16104 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 16105 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 16106 return SDValue(); 16107 break; 16108 } 16109 case ARMISD::SMLALBB: 16110 case ARMISD::QADD16b: 16111 case ARMISD::QSUB16b: { 16112 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16113 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 16114 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16115 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16116 return SDValue(); 16117 break; 16118 } 16119 case ARMISD::SMLALBT: { 16120 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 16121 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 16122 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 16123 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 16124 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 16125 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 16126 return SDValue(); 16127 break; 16128 } 16129 case ARMISD::SMLALTB: { 16130 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 16131 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 16132 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 16133 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 16134 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 16135 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 16136 return SDValue(); 16137 break; 16138 } 16139 case ARMISD::SMLALTT: { 16140 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16141 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 16142 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16143 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16144 return SDValue(); 16145 break; 16146 } 16147 case ARMISD::QADD8b: 16148 case ARMISD::QSUB8b: { 16149 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16150 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8); 16151 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16152 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16153 return SDValue(); 16154 break; 16155 } 16156 case ISD::INTRINSIC_VOID: 16157 case ISD::INTRINSIC_W_CHAIN: 16158 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 16159 case Intrinsic::arm_neon_vld1: 16160 case Intrinsic::arm_neon_vld1x2: 16161 case Intrinsic::arm_neon_vld1x3: 16162 case Intrinsic::arm_neon_vld1x4: 16163 case Intrinsic::arm_neon_vld2: 16164 case Intrinsic::arm_neon_vld3: 16165 case Intrinsic::arm_neon_vld4: 16166 case Intrinsic::arm_neon_vld2lane: 16167 case Intrinsic::arm_neon_vld3lane: 16168 case Intrinsic::arm_neon_vld4lane: 16169 case Intrinsic::arm_neon_vld2dup: 16170 case Intrinsic::arm_neon_vld3dup: 16171 case Intrinsic::arm_neon_vld4dup: 16172 case Intrinsic::arm_neon_vst1: 16173 case Intrinsic::arm_neon_vst1x2: 16174 case Intrinsic::arm_neon_vst1x3: 16175 case Intrinsic::arm_neon_vst1x4: 16176 case Intrinsic::arm_neon_vst2: 16177 case Intrinsic::arm_neon_vst3: 16178 case Intrinsic::arm_neon_vst4: 16179 case Intrinsic::arm_neon_vst2lane: 16180 case Intrinsic::arm_neon_vst3lane: 16181 case Intrinsic::arm_neon_vst4lane: 16182 return PerformVLDCombine(N, DCI); 16183 case Intrinsic::arm_mve_vld2q: 16184 case Intrinsic::arm_mve_vld4q: 16185 case Intrinsic::arm_mve_vst2q: 16186 case Intrinsic::arm_mve_vst4q: 16187 return PerformMVEVLDCombine(N, DCI); 16188 default: break; 16189 } 16190 break; 16191 } 16192 return SDValue(); 16193 } 16194 16195 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 16196 EVT VT) const { 16197 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 16198 } 16199 16200 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 16201 unsigned Alignment, 16202 MachineMemOperand::Flags, 16203 bool *Fast) const { 16204 // Depends what it gets converted into if the type is weird. 16205 if (!VT.isSimple()) 16206 return false; 16207 16208 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus 16209 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 16210 auto Ty = VT.getSimpleVT().SimpleTy; 16211 16212 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 16213 // Unaligned access can use (for example) LRDB, LRDH, LDR 16214 if (AllowsUnaligned) { 16215 if (Fast) 16216 *Fast = Subtarget->hasV7Ops(); 16217 return true; 16218 } 16219 } 16220 16221 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 16222 // For any little-endian targets with neon, we can support unaligned ld/st 16223 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 16224 // A big-endian target may also explicitly support unaligned accesses 16225 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 16226 if (Fast) 16227 *Fast = true; 16228 return true; 16229 } 16230 } 16231 16232 if (!Subtarget->hasMVEIntegerOps()) 16233 return false; 16234 16235 // These are for predicates 16236 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 16237 if (Fast) 16238 *Fast = true; 16239 return true; 16240 } 16241 16242 // These are for truncated stores/narrowing loads. They are fine so long as 16243 // the alignment is at least the size of the item being loaded 16244 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) && 16245 Alignment >= VT.getScalarSizeInBits() / 8) { 16246 if (Fast) 16247 *Fast = true; 16248 return true; 16249 } 16250 16251 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and 16252 // VSTRW.U32 all store the vector register in exactly the same format, and 16253 // differ only in the range of their immediate offset field and the required 16254 // alignment. So there is always a store that can be used, regardless of 16255 // actual type. 16256 // 16257 // For big endian, that is not the case. But can still emit a (VSTRB.U8; 16258 // VREV64.8) pair and get the same effect. This will likely be better than 16259 // aligning the vector through the stack. 16260 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 || 16261 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 || 16262 Ty == MVT::v2f64) { 16263 if (Fast) 16264 *Fast = true; 16265 return true; 16266 } 16267 16268 return false; 16269 } 16270 16271 16272 EVT ARMTargetLowering::getOptimalMemOpType( 16273 const MemOp &Op, const AttributeList &FuncAttributes) const { 16274 // See if we can use NEON instructions for this... 16275 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() && 16276 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 16277 bool Fast; 16278 if (Op.size() >= 16 && 16279 (Op.isAligned(Align(16)) || 16280 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 16281 MachineMemOperand::MONone, &Fast) && 16282 Fast))) { 16283 return MVT::v2f64; 16284 } else if (Op.size() >= 8 && 16285 (Op.isAligned(Align(8)) || 16286 (allowsMisalignedMemoryAccesses( 16287 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 16288 Fast))) { 16289 return MVT::f64; 16290 } 16291 } 16292 16293 // Let the target-independent logic figure it out. 16294 return MVT::Other; 16295 } 16296 16297 // 64-bit integers are split into their high and low parts and held in two 16298 // different registers, so the trunc is free since the low register can just 16299 // be used. 16300 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 16301 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 16302 return false; 16303 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 16304 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 16305 return (SrcBits == 64 && DestBits == 32); 16306 } 16307 16308 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 16309 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 16310 !DstVT.isInteger()) 16311 return false; 16312 unsigned SrcBits = SrcVT.getSizeInBits(); 16313 unsigned DestBits = DstVT.getSizeInBits(); 16314 return (SrcBits == 64 && DestBits == 32); 16315 } 16316 16317 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16318 if (Val.getOpcode() != ISD::LOAD) 16319 return false; 16320 16321 EVT VT1 = Val.getValueType(); 16322 if (!VT1.isSimple() || !VT1.isInteger() || 16323 !VT2.isSimple() || !VT2.isInteger()) 16324 return false; 16325 16326 switch (VT1.getSimpleVT().SimpleTy) { 16327 default: break; 16328 case MVT::i1: 16329 case MVT::i8: 16330 case MVT::i16: 16331 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 16332 return true; 16333 } 16334 16335 return false; 16336 } 16337 16338 bool ARMTargetLowering::isFNegFree(EVT VT) const { 16339 if (!VT.isSimple()) 16340 return false; 16341 16342 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 16343 // negate values directly (fneg is free). So, we don't want to let the DAG 16344 // combiner rewrite fneg into xors and some other instructions. For f16 and 16345 // FullFP16 argument passing, some bitcast nodes may be introduced, 16346 // triggering this DAG combine rewrite, so we are avoiding that with this. 16347 switch (VT.getSimpleVT().SimpleTy) { 16348 default: break; 16349 case MVT::f16: 16350 return Subtarget->hasFullFP16(); 16351 } 16352 16353 return false; 16354 } 16355 16356 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 16357 /// of the vector elements. 16358 static bool areExtractExts(Value *Ext1, Value *Ext2) { 16359 auto areExtDoubled = [](Instruction *Ext) { 16360 return Ext->getType()->getScalarSizeInBits() == 16361 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 16362 }; 16363 16364 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 16365 !match(Ext2, m_ZExtOrSExt(m_Value())) || 16366 !areExtDoubled(cast<Instruction>(Ext1)) || 16367 !areExtDoubled(cast<Instruction>(Ext2))) 16368 return false; 16369 16370 return true; 16371 } 16372 16373 /// Check if sinking \p I's operands to I's basic block is profitable, because 16374 /// the operands can be folded into a target instruction, e.g. 16375 /// sext/zext can be folded into vsubl. 16376 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 16377 SmallVectorImpl<Use *> &Ops) const { 16378 if (!I->getType()->isVectorTy()) 16379 return false; 16380 16381 if (Subtarget->hasNEON()) { 16382 switch (I->getOpcode()) { 16383 case Instruction::Sub: 16384 case Instruction::Add: { 16385 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 16386 return false; 16387 Ops.push_back(&I->getOperandUse(0)); 16388 Ops.push_back(&I->getOperandUse(1)); 16389 return true; 16390 } 16391 default: 16392 return false; 16393 } 16394 } 16395 16396 if (!Subtarget->hasMVEIntegerOps()) 16397 return false; 16398 16399 auto IsFMSMul = [&](Instruction *I) { 16400 if (!I->hasOneUse()) 16401 return false; 16402 auto *Sub = cast<Instruction>(*I->users().begin()); 16403 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I; 16404 }; 16405 auto IsFMS = [&](Instruction *I) { 16406 if (match(I->getOperand(0), m_FNeg(m_Value())) || 16407 match(I->getOperand(1), m_FNeg(m_Value()))) 16408 return true; 16409 return false; 16410 }; 16411 16412 auto IsSinker = [&](Instruction *I, int Operand) { 16413 switch (I->getOpcode()) { 16414 case Instruction::Add: 16415 case Instruction::Mul: 16416 case Instruction::FAdd: 16417 case Instruction::ICmp: 16418 case Instruction::FCmp: 16419 return true; 16420 case Instruction::FMul: 16421 return !IsFMSMul(I); 16422 case Instruction::Sub: 16423 case Instruction::FSub: 16424 case Instruction::Shl: 16425 case Instruction::LShr: 16426 case Instruction::AShr: 16427 return Operand == 1; 16428 case Instruction::Call: 16429 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 16430 switch (II->getIntrinsicID()) { 16431 case Intrinsic::fma: 16432 return !IsFMS(I); 16433 default: 16434 return false; 16435 } 16436 } 16437 return false; 16438 default: 16439 return false; 16440 } 16441 }; 16442 16443 for (auto OpIdx : enumerate(I->operands())) { 16444 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 16445 // Make sure we are not already sinking this operand 16446 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 16447 continue; 16448 16449 Instruction *Shuffle = Op; 16450 if (Shuffle->getOpcode() == Instruction::BitCast) 16451 Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0)); 16452 // We are looking for a splat that can be sunk. 16453 if (!Shuffle || 16454 !match(Shuffle, m_Shuffle( 16455 m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 16456 m_Undef(), m_ZeroMask()))) 16457 continue; 16458 if (!IsSinker(I, OpIdx.index())) 16459 continue; 16460 16461 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 16462 // and vector registers 16463 for (Use &U : Op->uses()) { 16464 Instruction *Insn = cast<Instruction>(U.getUser()); 16465 if (!IsSinker(Insn, U.getOperandNo())) 16466 return false; 16467 } 16468 16469 Ops.push_back(&Shuffle->getOperandUse(0)); 16470 if (Shuffle != Op) 16471 Ops.push_back(&Op->getOperandUse(0)); 16472 Ops.push_back(&OpIdx.value()); 16473 } 16474 return true; 16475 } 16476 16477 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const { 16478 if (!Subtarget->hasMVEIntegerOps()) 16479 return nullptr; 16480 Type *SVIType = SVI->getType(); 16481 Type *ScalarType = SVIType->getScalarType(); 16482 16483 if (ScalarType->isFloatTy()) 16484 return Type::getInt32Ty(SVIType->getContext()); 16485 if (ScalarType->isHalfTy()) 16486 return Type::getInt16Ty(SVIType->getContext()); 16487 return nullptr; 16488 } 16489 16490 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 16491 EVT VT = ExtVal.getValueType(); 16492 16493 if (!isTypeLegal(VT)) 16494 return false; 16495 16496 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) { 16497 if (Ld->isExpandingLoad()) 16498 return false; 16499 } 16500 16501 if (Subtarget->hasMVEIntegerOps()) 16502 return true; 16503 16504 // Don't create a loadext if we can fold the extension into a wide/long 16505 // instruction. 16506 // If there's more than one user instruction, the loadext is desirable no 16507 // matter what. There can be two uses by the same instruction. 16508 if (ExtVal->use_empty() || 16509 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 16510 return true; 16511 16512 SDNode *U = *ExtVal->use_begin(); 16513 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 16514 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 16515 return false; 16516 16517 return true; 16518 } 16519 16520 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 16521 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16522 return false; 16523 16524 if (!isTypeLegal(EVT::getEVT(Ty1))) 16525 return false; 16526 16527 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 16528 16529 // Assuming the caller doesn't have a zeroext or signext return parameter, 16530 // truncation all the way down to i1 is valid. 16531 return true; 16532 } 16533 16534 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 16535 const AddrMode &AM, Type *Ty, 16536 unsigned AS) const { 16537 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 16538 if (Subtarget->hasFPAO()) 16539 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 16540 return 0; 16541 } 16542 return -1; 16543 } 16544 16545 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster 16546 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be 16547 /// expanded to FMAs when this method returns true, otherwise fmuladd is 16548 /// expanded to fmul + fadd. 16549 /// 16550 /// ARM supports both fused and unfused multiply-add operations; we already 16551 /// lower a pair of fmul and fadd to the latter so it's not clear that there 16552 /// would be a gain or that the gain would be worthwhile enough to risk 16553 /// correctness bugs. 16554 /// 16555 /// For MVE, we set this to true as it helps simplify the need for some 16556 /// patterns (and we don't have the non-fused floating point instruction). 16557 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16558 EVT VT) const { 16559 if (!VT.isSimple()) 16560 return false; 16561 16562 switch (VT.getSimpleVT().SimpleTy) { 16563 case MVT::v4f32: 16564 case MVT::v8f16: 16565 return Subtarget->hasMVEFloatOps(); 16566 case MVT::f16: 16567 return Subtarget->useFPVFMx16(); 16568 case MVT::f32: 16569 return Subtarget->useFPVFMx(); 16570 case MVT::f64: 16571 return Subtarget->useFPVFMx64(); 16572 default: 16573 break; 16574 } 16575 16576 return false; 16577 } 16578 16579 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 16580 if (V < 0) 16581 return false; 16582 16583 unsigned Scale = 1; 16584 switch (VT.getSimpleVT().SimpleTy) { 16585 case MVT::i1: 16586 case MVT::i8: 16587 // Scale == 1; 16588 break; 16589 case MVT::i16: 16590 // Scale == 2; 16591 Scale = 2; 16592 break; 16593 default: 16594 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 16595 // Scale == 4; 16596 Scale = 4; 16597 break; 16598 } 16599 16600 if ((V & (Scale - 1)) != 0) 16601 return false; 16602 return isUInt<5>(V / Scale); 16603 } 16604 16605 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 16606 const ARMSubtarget *Subtarget) { 16607 if (!VT.isInteger() && !VT.isFloatingPoint()) 16608 return false; 16609 if (VT.isVector() && Subtarget->hasNEON()) 16610 return false; 16611 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 16612 !Subtarget->hasMVEFloatOps()) 16613 return false; 16614 16615 bool IsNeg = false; 16616 if (V < 0) { 16617 IsNeg = true; 16618 V = -V; 16619 } 16620 16621 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U); 16622 16623 // MVE: size * imm7 16624 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 16625 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 16626 case MVT::i32: 16627 case MVT::f32: 16628 return isShiftedUInt<7,2>(V); 16629 case MVT::i16: 16630 case MVT::f16: 16631 return isShiftedUInt<7,1>(V); 16632 case MVT::i8: 16633 return isUInt<7>(V); 16634 default: 16635 return false; 16636 } 16637 } 16638 16639 // half VLDR: 2 * imm8 16640 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 16641 return isShiftedUInt<8, 1>(V); 16642 // VLDR and LDRD: 4 * imm8 16643 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 16644 return isShiftedUInt<8, 2>(V); 16645 16646 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 16647 // + imm12 or - imm8 16648 if (IsNeg) 16649 return isUInt<8>(V); 16650 return isUInt<12>(V); 16651 } 16652 16653 return false; 16654 } 16655 16656 /// isLegalAddressImmediate - Return true if the integer value can be used 16657 /// as the offset of the target addressing mode for load / store of the 16658 /// given type. 16659 static bool isLegalAddressImmediate(int64_t V, EVT VT, 16660 const ARMSubtarget *Subtarget) { 16661 if (V == 0) 16662 return true; 16663 16664 if (!VT.isSimple()) 16665 return false; 16666 16667 if (Subtarget->isThumb1Only()) 16668 return isLegalT1AddressImmediate(V, VT); 16669 else if (Subtarget->isThumb2()) 16670 return isLegalT2AddressImmediate(V, VT, Subtarget); 16671 16672 // ARM mode. 16673 if (V < 0) 16674 V = - V; 16675 switch (VT.getSimpleVT().SimpleTy) { 16676 default: return false; 16677 case MVT::i1: 16678 case MVT::i8: 16679 case MVT::i32: 16680 // +- imm12 16681 return isUInt<12>(V); 16682 case MVT::i16: 16683 // +- imm8 16684 return isUInt<8>(V); 16685 case MVT::f32: 16686 case MVT::f64: 16687 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 16688 return false; 16689 return isShiftedUInt<8, 2>(V); 16690 } 16691 } 16692 16693 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 16694 EVT VT) const { 16695 int Scale = AM.Scale; 16696 if (Scale < 0) 16697 return false; 16698 16699 switch (VT.getSimpleVT().SimpleTy) { 16700 default: return false; 16701 case MVT::i1: 16702 case MVT::i8: 16703 case MVT::i16: 16704 case MVT::i32: 16705 if (Scale == 1) 16706 return true; 16707 // r + r << imm 16708 Scale = Scale & ~1; 16709 return Scale == 2 || Scale == 4 || Scale == 8; 16710 case MVT::i64: 16711 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 16712 // version in Thumb mode. 16713 // r + r 16714 if (Scale == 1) 16715 return true; 16716 // r * 2 (this can be lowered to r + r). 16717 if (!AM.HasBaseReg && Scale == 2) 16718 return true; 16719 return false; 16720 case MVT::isVoid: 16721 // Note, we allow "void" uses (basically, uses that aren't loads or 16722 // stores), because arm allows folding a scale into many arithmetic 16723 // operations. This should be made more precise and revisited later. 16724 16725 // Allow r << imm, but the imm has to be a multiple of two. 16726 if (Scale & 1) return false; 16727 return isPowerOf2_32(Scale); 16728 } 16729 } 16730 16731 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 16732 EVT VT) const { 16733 const int Scale = AM.Scale; 16734 16735 // Negative scales are not supported in Thumb1. 16736 if (Scale < 0) 16737 return false; 16738 16739 // Thumb1 addressing modes do not support register scaling excepting the 16740 // following cases: 16741 // 1. Scale == 1 means no scaling. 16742 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 16743 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 16744 } 16745 16746 /// isLegalAddressingMode - Return true if the addressing mode represented 16747 /// by AM is legal for this target, for a load/store of the specified type. 16748 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 16749 const AddrMode &AM, Type *Ty, 16750 unsigned AS, Instruction *I) const { 16751 EVT VT = getValueType(DL, Ty, true); 16752 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 16753 return false; 16754 16755 // Can never fold addr of global into load/store. 16756 if (AM.BaseGV) 16757 return false; 16758 16759 switch (AM.Scale) { 16760 case 0: // no scale reg, must be "r+i" or "r", or "i". 16761 break; 16762 default: 16763 // ARM doesn't support any R+R*scale+imm addr modes. 16764 if (AM.BaseOffs) 16765 return false; 16766 16767 if (!VT.isSimple()) 16768 return false; 16769 16770 if (Subtarget->isThumb1Only()) 16771 return isLegalT1ScaledAddressingMode(AM, VT); 16772 16773 if (Subtarget->isThumb2()) 16774 return isLegalT2ScaledAddressingMode(AM, VT); 16775 16776 int Scale = AM.Scale; 16777 switch (VT.getSimpleVT().SimpleTy) { 16778 default: return false; 16779 case MVT::i1: 16780 case MVT::i8: 16781 case MVT::i32: 16782 if (Scale < 0) Scale = -Scale; 16783 if (Scale == 1) 16784 return true; 16785 // r + r << imm 16786 return isPowerOf2_32(Scale & ~1); 16787 case MVT::i16: 16788 case MVT::i64: 16789 // r +/- r 16790 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 16791 return true; 16792 // r * 2 (this can be lowered to r + r). 16793 if (!AM.HasBaseReg && Scale == 2) 16794 return true; 16795 return false; 16796 16797 case MVT::isVoid: 16798 // Note, we allow "void" uses (basically, uses that aren't loads or 16799 // stores), because arm allows folding a scale into many arithmetic 16800 // operations. This should be made more precise and revisited later. 16801 16802 // Allow r << imm, but the imm has to be a multiple of two. 16803 if (Scale & 1) return false; 16804 return isPowerOf2_32(Scale); 16805 } 16806 } 16807 return true; 16808 } 16809 16810 /// isLegalICmpImmediate - Return true if the specified immediate is legal 16811 /// icmp immediate, that is the target has icmp instructions which can compare 16812 /// a register against the immediate without having to materialize the 16813 /// immediate into a register. 16814 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16815 // Thumb2 and ARM modes can use cmn for negative immediates. 16816 if (!Subtarget->isThumb()) 16817 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 16818 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 16819 if (Subtarget->isThumb2()) 16820 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 16821 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 16822 // Thumb1 doesn't have cmn, and only 8-bit immediates. 16823 return Imm >= 0 && Imm <= 255; 16824 } 16825 16826 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 16827 /// *or sub* immediate, that is the target has add or sub instructions which can 16828 /// add a register with the immediate without having to materialize the 16829 /// immediate into a register. 16830 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16831 // Same encoding for add/sub, just flip the sign. 16832 int64_t AbsImm = std::abs(Imm); 16833 if (!Subtarget->isThumb()) 16834 return ARM_AM::getSOImmVal(AbsImm) != -1; 16835 if (Subtarget->isThumb2()) 16836 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 16837 // Thumb1 only has 8-bit unsigned immediate. 16838 return AbsImm >= 0 && AbsImm <= 255; 16839 } 16840 16841 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 16842 bool isSEXTLoad, SDValue &Base, 16843 SDValue &Offset, bool &isInc, 16844 SelectionDAG &DAG) { 16845 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 16846 return false; 16847 16848 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 16849 // AddressingMode 3 16850 Base = Ptr->getOperand(0); 16851 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 16852 int RHSC = (int)RHS->getZExtValue(); 16853 if (RHSC < 0 && RHSC > -256) { 16854 assert(Ptr->getOpcode() == ISD::ADD); 16855 isInc = false; 16856 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16857 return true; 16858 } 16859 } 16860 isInc = (Ptr->getOpcode() == ISD::ADD); 16861 Offset = Ptr->getOperand(1); 16862 return true; 16863 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 16864 // AddressingMode 2 16865 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 16866 int RHSC = (int)RHS->getZExtValue(); 16867 if (RHSC < 0 && RHSC > -0x1000) { 16868 assert(Ptr->getOpcode() == ISD::ADD); 16869 isInc = false; 16870 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16871 Base = Ptr->getOperand(0); 16872 return true; 16873 } 16874 } 16875 16876 if (Ptr->getOpcode() == ISD::ADD) { 16877 isInc = true; 16878 ARM_AM::ShiftOpc ShOpcVal= 16879 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 16880 if (ShOpcVal != ARM_AM::no_shift) { 16881 Base = Ptr->getOperand(1); 16882 Offset = Ptr->getOperand(0); 16883 } else { 16884 Base = Ptr->getOperand(0); 16885 Offset = Ptr->getOperand(1); 16886 } 16887 return true; 16888 } 16889 16890 isInc = (Ptr->getOpcode() == ISD::ADD); 16891 Base = Ptr->getOperand(0); 16892 Offset = Ptr->getOperand(1); 16893 return true; 16894 } 16895 16896 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 16897 return false; 16898 } 16899 16900 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 16901 bool isSEXTLoad, SDValue &Base, 16902 SDValue &Offset, bool &isInc, 16903 SelectionDAG &DAG) { 16904 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 16905 return false; 16906 16907 Base = Ptr->getOperand(0); 16908 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 16909 int RHSC = (int)RHS->getZExtValue(); 16910 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 16911 assert(Ptr->getOpcode() == ISD::ADD); 16912 isInc = false; 16913 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16914 return true; 16915 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 16916 isInc = Ptr->getOpcode() == ISD::ADD; 16917 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16918 return true; 16919 } 16920 } 16921 16922 return false; 16923 } 16924 16925 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment, 16926 bool isSEXTLoad, bool IsMasked, bool isLE, 16927 SDValue &Base, SDValue &Offset, 16928 bool &isInc, SelectionDAG &DAG) { 16929 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 16930 return false; 16931 if (!isa<ConstantSDNode>(Ptr->getOperand(1))) 16932 return false; 16933 16934 // We allow LE non-masked loads to change the type (for example use a vldrb.8 16935 // as opposed to a vldrw.32). This can allow extra addressing modes or 16936 // alignments for what is otherwise an equivalent instruction. 16937 bool CanChangeType = isLE && !IsMasked; 16938 16939 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1)); 16940 int RHSC = (int)RHS->getZExtValue(); 16941 16942 auto IsInRange = [&](int RHSC, int Limit, int Scale) { 16943 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) { 16944 assert(Ptr->getOpcode() == ISD::ADD); 16945 isInc = false; 16946 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16947 return true; 16948 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) { 16949 isInc = Ptr->getOpcode() == ISD::ADD; 16950 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16951 return true; 16952 } 16953 return false; 16954 }; 16955 16956 // Try to find a matching instruction based on s/zext, Alignment, Offset and 16957 // (in BE/masked) type. 16958 Base = Ptr->getOperand(0); 16959 if (VT == MVT::v4i16) { 16960 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2)) 16961 return true; 16962 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) { 16963 if (IsInRange(RHSC, 0x80, 1)) 16964 return true; 16965 } else if (Alignment >= 4 && 16966 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) && 16967 IsInRange(RHSC, 0x80, 4)) 16968 return true; 16969 else if (Alignment >= 2 && 16970 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) && 16971 IsInRange(RHSC, 0x80, 2)) 16972 return true; 16973 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1)) 16974 return true; 16975 return false; 16976 } 16977 16978 /// getPreIndexedAddressParts - returns true by value, base pointer and 16979 /// offset pointer and addressing mode by reference if the node's address 16980 /// can be legally represented as pre-indexed load / store address. 16981 bool 16982 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 16983 SDValue &Offset, 16984 ISD::MemIndexedMode &AM, 16985 SelectionDAG &DAG) const { 16986 if (Subtarget->isThumb1Only()) 16987 return false; 16988 16989 EVT VT; 16990 SDValue Ptr; 16991 Align Alignment; 16992 bool isSEXTLoad = false; 16993 bool IsMasked = false; 16994 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 16995 Ptr = LD->getBasePtr(); 16996 VT = LD->getMemoryVT(); 16997 Alignment = LD->getAlign(); 16998 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 16999 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 17000 Ptr = ST->getBasePtr(); 17001 VT = ST->getMemoryVT(); 17002 Alignment = ST->getAlign(); 17003 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 17004 Ptr = LD->getBasePtr(); 17005 VT = LD->getMemoryVT(); 17006 Alignment = LD->getAlign(); 17007 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17008 IsMasked = true; 17009 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 17010 Ptr = ST->getBasePtr(); 17011 VT = ST->getMemoryVT(); 17012 Alignment = ST->getAlign(); 17013 IsMasked = true; 17014 } else 17015 return false; 17016 17017 bool isInc; 17018 bool isLegal = false; 17019 if (VT.isVector()) 17020 isLegal = Subtarget->hasMVEIntegerOps() && 17021 getMVEIndexedAddressParts( 17022 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked, 17023 Subtarget->isLittle(), Base, Offset, isInc, DAG); 17024 else { 17025 if (Subtarget->isThumb2()) 17026 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 17027 Offset, isInc, DAG); 17028 else 17029 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 17030 Offset, isInc, DAG); 17031 } 17032 if (!isLegal) 17033 return false; 17034 17035 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 17036 return true; 17037 } 17038 17039 /// getPostIndexedAddressParts - returns true by value, base pointer and 17040 /// offset pointer and addressing mode by reference if this node can be 17041 /// combined with a load / store to form a post-indexed load / store. 17042 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 17043 SDValue &Base, 17044 SDValue &Offset, 17045 ISD::MemIndexedMode &AM, 17046 SelectionDAG &DAG) const { 17047 EVT VT; 17048 SDValue Ptr; 17049 Align Alignment; 17050 bool isSEXTLoad = false, isNonExt; 17051 bool IsMasked = false; 17052 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 17053 VT = LD->getMemoryVT(); 17054 Ptr = LD->getBasePtr(); 17055 Alignment = LD->getAlign(); 17056 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17057 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 17058 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 17059 VT = ST->getMemoryVT(); 17060 Ptr = ST->getBasePtr(); 17061 Alignment = ST->getAlign(); 17062 isNonExt = !ST->isTruncatingStore(); 17063 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 17064 VT = LD->getMemoryVT(); 17065 Ptr = LD->getBasePtr(); 17066 Alignment = LD->getAlign(); 17067 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17068 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 17069 IsMasked = true; 17070 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 17071 VT = ST->getMemoryVT(); 17072 Ptr = ST->getBasePtr(); 17073 Alignment = ST->getAlign(); 17074 isNonExt = !ST->isTruncatingStore(); 17075 IsMasked = true; 17076 } else 17077 return false; 17078 17079 if (Subtarget->isThumb1Only()) { 17080 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 17081 // must be non-extending/truncating, i32, with an offset of 4. 17082 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 17083 if (Op->getOpcode() != ISD::ADD || !isNonExt) 17084 return false; 17085 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 17086 if (!RHS || RHS->getZExtValue() != 4) 17087 return false; 17088 17089 Offset = Op->getOperand(1); 17090 Base = Op->getOperand(0); 17091 AM = ISD::POST_INC; 17092 return true; 17093 } 17094 17095 bool isInc; 17096 bool isLegal = false; 17097 if (VT.isVector()) 17098 isLegal = Subtarget->hasMVEIntegerOps() && 17099 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked, 17100 Subtarget->isLittle(), Base, Offset, 17101 isInc, DAG); 17102 else { 17103 if (Subtarget->isThumb2()) 17104 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 17105 isInc, DAG); 17106 else 17107 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 17108 isInc, DAG); 17109 } 17110 if (!isLegal) 17111 return false; 17112 17113 if (Ptr != Base) { 17114 // Swap base ptr and offset to catch more post-index load / store when 17115 // it's legal. In Thumb2 mode, offset must be an immediate. 17116 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 17117 !Subtarget->isThumb2()) 17118 std::swap(Base, Offset); 17119 17120 // Post-indexed load / store update the base pointer. 17121 if (Ptr != Base) 17122 return false; 17123 } 17124 17125 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 17126 return true; 17127 } 17128 17129 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 17130 KnownBits &Known, 17131 const APInt &DemandedElts, 17132 const SelectionDAG &DAG, 17133 unsigned Depth) const { 17134 unsigned BitWidth = Known.getBitWidth(); 17135 Known.resetAll(); 17136 switch (Op.getOpcode()) { 17137 default: break; 17138 case ARMISD::ADDC: 17139 case ARMISD::ADDE: 17140 case ARMISD::SUBC: 17141 case ARMISD::SUBE: 17142 // Special cases when we convert a carry to a boolean. 17143 if (Op.getResNo() == 0) { 17144 SDValue LHS = Op.getOperand(0); 17145 SDValue RHS = Op.getOperand(1); 17146 // (ADDE 0, 0, C) will give us a single bit. 17147 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 17148 isNullConstant(RHS)) { 17149 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 17150 return; 17151 } 17152 } 17153 break; 17154 case ARMISD::CMOV: { 17155 // Bits are known zero/one if known on the LHS and RHS. 17156 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 17157 if (Known.isUnknown()) 17158 return; 17159 17160 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 17161 Known.Zero &= KnownRHS.Zero; 17162 Known.One &= KnownRHS.One; 17163 return; 17164 } 17165 case ISD::INTRINSIC_W_CHAIN: { 17166 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 17167 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 17168 switch (IntID) { 17169 default: return; 17170 case Intrinsic::arm_ldaex: 17171 case Intrinsic::arm_ldrex: { 17172 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 17173 unsigned MemBits = VT.getScalarSizeInBits(); 17174 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 17175 return; 17176 } 17177 } 17178 } 17179 case ARMISD::BFI: { 17180 // Conservatively, we can recurse down the first operand 17181 // and just mask out all affected bits. 17182 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 17183 17184 // The operand to BFI is already a mask suitable for removing the bits it 17185 // sets. 17186 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 17187 const APInt &Mask = CI->getAPIntValue(); 17188 Known.Zero &= Mask; 17189 Known.One &= Mask; 17190 return; 17191 } 17192 case ARMISD::VGETLANEs: 17193 case ARMISD::VGETLANEu: { 17194 const SDValue &SrcSV = Op.getOperand(0); 17195 EVT VecVT = SrcSV.getValueType(); 17196 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 17197 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 17198 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 17199 assert(Pos->getAPIntValue().ult(NumSrcElts) && 17200 "VGETLANE index out of bounds"); 17201 unsigned Idx = Pos->getZExtValue(); 17202 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 17203 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 17204 17205 EVT VT = Op.getValueType(); 17206 const unsigned DstSz = VT.getScalarSizeInBits(); 17207 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 17208 (void)SrcSz; 17209 assert(SrcSz == Known.getBitWidth()); 17210 assert(DstSz > SrcSz); 17211 if (Op.getOpcode() == ARMISD::VGETLANEs) 17212 Known = Known.sext(DstSz); 17213 else { 17214 Known = Known.zext(DstSz); 17215 } 17216 assert(DstSz == Known.getBitWidth()); 17217 break; 17218 } 17219 case ARMISD::VMOVrh: { 17220 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 17221 assert(KnownOp.getBitWidth() == 16); 17222 Known = KnownOp.zext(32); 17223 break; 17224 } 17225 } 17226 } 17227 17228 bool ARMTargetLowering::targetShrinkDemandedConstant( 17229 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 17230 TargetLoweringOpt &TLO) const { 17231 // Delay optimization, so we don't have to deal with illegal types, or block 17232 // optimizations. 17233 if (!TLO.LegalOps) 17234 return false; 17235 17236 // Only optimize AND for now. 17237 if (Op.getOpcode() != ISD::AND) 17238 return false; 17239 17240 EVT VT = Op.getValueType(); 17241 17242 // Ignore vectors. 17243 if (VT.isVector()) 17244 return false; 17245 17246 assert(VT == MVT::i32 && "Unexpected integer type"); 17247 17248 // Make sure the RHS really is a constant. 17249 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 17250 if (!C) 17251 return false; 17252 17253 unsigned Mask = C->getZExtValue(); 17254 17255 unsigned Demanded = DemandedBits.getZExtValue(); 17256 unsigned ShrunkMask = Mask & Demanded; 17257 unsigned ExpandedMask = Mask | ~Demanded; 17258 17259 // If the mask is all zeros, let the target-independent code replace the 17260 // result with zero. 17261 if (ShrunkMask == 0) 17262 return false; 17263 17264 // If the mask is all ones, erase the AND. (Currently, the target-independent 17265 // code won't do this, so we have to do it explicitly to avoid an infinite 17266 // loop in obscure cases.) 17267 if (ExpandedMask == ~0U) 17268 return TLO.CombineTo(Op, Op.getOperand(0)); 17269 17270 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 17271 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 17272 }; 17273 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 17274 if (NewMask == Mask) 17275 return true; 17276 SDLoc DL(Op); 17277 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 17278 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 17279 return TLO.CombineTo(Op, NewOp); 17280 }; 17281 17282 // Prefer uxtb mask. 17283 if (IsLegalMask(0xFF)) 17284 return UseMask(0xFF); 17285 17286 // Prefer uxth mask. 17287 if (IsLegalMask(0xFFFF)) 17288 return UseMask(0xFFFF); 17289 17290 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 17291 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 17292 if (ShrunkMask < 256) 17293 return UseMask(ShrunkMask); 17294 17295 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 17296 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 17297 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 17298 return UseMask(ExpandedMask); 17299 17300 // Potential improvements: 17301 // 17302 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 17303 // We could try to prefer Thumb1 immediates which can be lowered to a 17304 // two-instruction sequence. 17305 // We could try to recognize more legal ARM/Thumb2 immediates here. 17306 17307 return false; 17308 } 17309 17310 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode( 17311 SDValue Op, const APInt &OriginalDemandedBits, 17312 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 17313 unsigned Depth) const { 17314 unsigned Opc = Op.getOpcode(); 17315 17316 switch (Opc) { 17317 case ARMISD::ASRL: 17318 case ARMISD::LSRL: { 17319 // If this is result 0 and the other result is unused, see if the demand 17320 // bits allow us to shrink this long shift into a standard small shift in 17321 // the opposite direction. 17322 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) && 17323 isa<ConstantSDNode>(Op->getOperand(2))) { 17324 unsigned ShAmt = Op->getConstantOperandVal(2); 17325 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf( 17326 APInt::getAllOnesValue(32) << (32 - ShAmt))) 17327 return TLO.CombineTo( 17328 Op, TLO.DAG.getNode( 17329 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1), 17330 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32))); 17331 } 17332 break; 17333 } 17334 } 17335 17336 return TargetLowering::SimplifyDemandedBitsForTargetNode( 17337 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth); 17338 } 17339 17340 //===----------------------------------------------------------------------===// 17341 // ARM Inline Assembly Support 17342 //===----------------------------------------------------------------------===// 17343 17344 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 17345 // Looking for "rev" which is V6+. 17346 if (!Subtarget->hasV6Ops()) 17347 return false; 17348 17349 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand()); 17350 std::string AsmStr = IA->getAsmString(); 17351 SmallVector<StringRef, 4> AsmPieces; 17352 SplitString(AsmStr, AsmPieces, ";\n"); 17353 17354 switch (AsmPieces.size()) { 17355 default: return false; 17356 case 1: 17357 AsmStr = std::string(AsmPieces[0]); 17358 AsmPieces.clear(); 17359 SplitString(AsmStr, AsmPieces, " \t,"); 17360 17361 // rev $0, $1 17362 if (AsmPieces.size() == 3 && 17363 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 17364 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 17365 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 17366 if (Ty && Ty->getBitWidth() == 32) 17367 return IntrinsicLowering::LowerToByteSwap(CI); 17368 } 17369 break; 17370 } 17371 17372 return false; 17373 } 17374 17375 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 17376 // At this point, we have to lower this constraint to something else, so we 17377 // lower it to an "r" or "w". However, by doing this we will force the result 17378 // to be in register, while the X constraint is much more permissive. 17379 // 17380 // Although we are correct (we are free to emit anything, without 17381 // constraints), we might break use cases that would expect us to be more 17382 // efficient and emit something else. 17383 if (!Subtarget->hasVFP2Base()) 17384 return "r"; 17385 if (ConstraintVT.isFloatingPoint()) 17386 return "w"; 17387 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 17388 (ConstraintVT.getSizeInBits() == 64 || 17389 ConstraintVT.getSizeInBits() == 128)) 17390 return "w"; 17391 17392 return "r"; 17393 } 17394 17395 /// getConstraintType - Given a constraint letter, return the type of 17396 /// constraint it is for this target. 17397 ARMTargetLowering::ConstraintType 17398 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 17399 unsigned S = Constraint.size(); 17400 if (S == 1) { 17401 switch (Constraint[0]) { 17402 default: break; 17403 case 'l': return C_RegisterClass; 17404 case 'w': return C_RegisterClass; 17405 case 'h': return C_RegisterClass; 17406 case 'x': return C_RegisterClass; 17407 case 't': return C_RegisterClass; 17408 case 'j': return C_Immediate; // Constant for movw. 17409 // An address with a single base register. Due to the way we 17410 // currently handle addresses it is the same as an 'r' memory constraint. 17411 case 'Q': return C_Memory; 17412 } 17413 } else if (S == 2) { 17414 switch (Constraint[0]) { 17415 default: break; 17416 case 'T': return C_RegisterClass; 17417 // All 'U+' constraints are addresses. 17418 case 'U': return C_Memory; 17419 } 17420 } 17421 return TargetLowering::getConstraintType(Constraint); 17422 } 17423 17424 /// Examine constraint type and operand type and determine a weight value. 17425 /// This object must already have been set up with the operand type 17426 /// and the current alternative constraint selected. 17427 TargetLowering::ConstraintWeight 17428 ARMTargetLowering::getSingleConstraintMatchWeight( 17429 AsmOperandInfo &info, const char *constraint) const { 17430 ConstraintWeight weight = CW_Invalid; 17431 Value *CallOperandVal = info.CallOperandVal; 17432 // If we don't have a value, we can't do a match, 17433 // but allow it at the lowest weight. 17434 if (!CallOperandVal) 17435 return CW_Default; 17436 Type *type = CallOperandVal->getType(); 17437 // Look at the constraint type. 17438 switch (*constraint) { 17439 default: 17440 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 17441 break; 17442 case 'l': 17443 if (type->isIntegerTy()) { 17444 if (Subtarget->isThumb()) 17445 weight = CW_SpecificReg; 17446 else 17447 weight = CW_Register; 17448 } 17449 break; 17450 case 'w': 17451 if (type->isFloatingPointTy()) 17452 weight = CW_Register; 17453 break; 17454 } 17455 return weight; 17456 } 17457 17458 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 17459 17460 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 17461 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 17462 switch (Constraint.size()) { 17463 case 1: 17464 // GCC ARM Constraint Letters 17465 switch (Constraint[0]) { 17466 case 'l': // Low regs or general regs. 17467 if (Subtarget->isThumb()) 17468 return RCPair(0U, &ARM::tGPRRegClass); 17469 return RCPair(0U, &ARM::GPRRegClass); 17470 case 'h': // High regs or no regs. 17471 if (Subtarget->isThumb()) 17472 return RCPair(0U, &ARM::hGPRRegClass); 17473 break; 17474 case 'r': 17475 if (Subtarget->isThumb1Only()) 17476 return RCPair(0U, &ARM::tGPRRegClass); 17477 return RCPair(0U, &ARM::GPRRegClass); 17478 case 'w': 17479 if (VT == MVT::Other) 17480 break; 17481 if (VT == MVT::f32) 17482 return RCPair(0U, &ARM::SPRRegClass); 17483 if (VT.getSizeInBits() == 64) 17484 return RCPair(0U, &ARM::DPRRegClass); 17485 if (VT.getSizeInBits() == 128) 17486 return RCPair(0U, &ARM::QPRRegClass); 17487 break; 17488 case 'x': 17489 if (VT == MVT::Other) 17490 break; 17491 if (VT == MVT::f32) 17492 return RCPair(0U, &ARM::SPR_8RegClass); 17493 if (VT.getSizeInBits() == 64) 17494 return RCPair(0U, &ARM::DPR_8RegClass); 17495 if (VT.getSizeInBits() == 128) 17496 return RCPair(0U, &ARM::QPR_8RegClass); 17497 break; 17498 case 't': 17499 if (VT == MVT::Other) 17500 break; 17501 if (VT == MVT::f32 || VT == MVT::i32) 17502 return RCPair(0U, &ARM::SPRRegClass); 17503 if (VT.getSizeInBits() == 64) 17504 return RCPair(0U, &ARM::DPR_VFP2RegClass); 17505 if (VT.getSizeInBits() == 128) 17506 return RCPair(0U, &ARM::QPR_VFP2RegClass); 17507 break; 17508 } 17509 break; 17510 17511 case 2: 17512 if (Constraint[0] == 'T') { 17513 switch (Constraint[1]) { 17514 default: 17515 break; 17516 case 'e': 17517 return RCPair(0U, &ARM::tGPREvenRegClass); 17518 case 'o': 17519 return RCPair(0U, &ARM::tGPROddRegClass); 17520 } 17521 } 17522 break; 17523 17524 default: 17525 break; 17526 } 17527 17528 if (StringRef("{cc}").equals_lower(Constraint)) 17529 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 17530 17531 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 17532 } 17533 17534 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 17535 /// vector. If it is invalid, don't add anything to Ops. 17536 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 17537 std::string &Constraint, 17538 std::vector<SDValue>&Ops, 17539 SelectionDAG &DAG) const { 17540 SDValue Result; 17541 17542 // Currently only support length 1 constraints. 17543 if (Constraint.length() != 1) return; 17544 17545 char ConstraintLetter = Constraint[0]; 17546 switch (ConstraintLetter) { 17547 default: break; 17548 case 'j': 17549 case 'I': case 'J': case 'K': case 'L': 17550 case 'M': case 'N': case 'O': 17551 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 17552 if (!C) 17553 return; 17554 17555 int64_t CVal64 = C->getSExtValue(); 17556 int CVal = (int) CVal64; 17557 // None of these constraints allow values larger than 32 bits. Check 17558 // that the value fits in an int. 17559 if (CVal != CVal64) 17560 return; 17561 17562 switch (ConstraintLetter) { 17563 case 'j': 17564 // Constant suitable for movw, must be between 0 and 17565 // 65535. 17566 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps())) 17567 if (CVal >= 0 && CVal <= 65535) 17568 break; 17569 return; 17570 case 'I': 17571 if (Subtarget->isThumb1Only()) { 17572 // This must be a constant between 0 and 255, for ADD 17573 // immediates. 17574 if (CVal >= 0 && CVal <= 255) 17575 break; 17576 } else if (Subtarget->isThumb2()) { 17577 // A constant that can be used as an immediate value in a 17578 // data-processing instruction. 17579 if (ARM_AM::getT2SOImmVal(CVal) != -1) 17580 break; 17581 } else { 17582 // A constant that can be used as an immediate value in a 17583 // data-processing instruction. 17584 if (ARM_AM::getSOImmVal(CVal) != -1) 17585 break; 17586 } 17587 return; 17588 17589 case 'J': 17590 if (Subtarget->isThumb1Only()) { 17591 // This must be a constant between -255 and -1, for negated ADD 17592 // immediates. This can be used in GCC with an "n" modifier that 17593 // prints the negated value, for use with SUB instructions. It is 17594 // not useful otherwise but is implemented for compatibility. 17595 if (CVal >= -255 && CVal <= -1) 17596 break; 17597 } else { 17598 // This must be a constant between -4095 and 4095. It is not clear 17599 // what this constraint is intended for. Implemented for 17600 // compatibility with GCC. 17601 if (CVal >= -4095 && CVal <= 4095) 17602 break; 17603 } 17604 return; 17605 17606 case 'K': 17607 if (Subtarget->isThumb1Only()) { 17608 // A 32-bit value where only one byte has a nonzero value. Exclude 17609 // zero to match GCC. This constraint is used by GCC internally for 17610 // constants that can be loaded with a move/shift combination. 17611 // It is not useful otherwise but is implemented for compatibility. 17612 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 17613 break; 17614 } else if (Subtarget->isThumb2()) { 17615 // A constant whose bitwise inverse can be used as an immediate 17616 // value in a data-processing instruction. This can be used in GCC 17617 // with a "B" modifier that prints the inverted value, for use with 17618 // BIC and MVN instructions. It is not useful otherwise but is 17619 // implemented for compatibility. 17620 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 17621 break; 17622 } else { 17623 // A constant whose bitwise inverse can be used as an immediate 17624 // value in a data-processing instruction. This can be used in GCC 17625 // with a "B" modifier that prints the inverted value, for use with 17626 // BIC and MVN instructions. It is not useful otherwise but is 17627 // implemented for compatibility. 17628 if (ARM_AM::getSOImmVal(~CVal) != -1) 17629 break; 17630 } 17631 return; 17632 17633 case 'L': 17634 if (Subtarget->isThumb1Only()) { 17635 // This must be a constant between -7 and 7, 17636 // for 3-operand ADD/SUB immediate instructions. 17637 if (CVal >= -7 && CVal < 7) 17638 break; 17639 } else if (Subtarget->isThumb2()) { 17640 // A constant whose negation can be used as an immediate value in a 17641 // data-processing instruction. This can be used in GCC with an "n" 17642 // modifier that prints the negated value, for use with SUB 17643 // instructions. It is not useful otherwise but is implemented for 17644 // compatibility. 17645 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 17646 break; 17647 } else { 17648 // A constant whose negation can be used as an immediate value in a 17649 // data-processing instruction. This can be used in GCC with an "n" 17650 // modifier that prints the negated value, for use with SUB 17651 // instructions. It is not useful otherwise but is implemented for 17652 // compatibility. 17653 if (ARM_AM::getSOImmVal(-CVal) != -1) 17654 break; 17655 } 17656 return; 17657 17658 case 'M': 17659 if (Subtarget->isThumb1Only()) { 17660 // This must be a multiple of 4 between 0 and 1020, for 17661 // ADD sp + immediate. 17662 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 17663 break; 17664 } else { 17665 // A power of two or a constant between 0 and 32. This is used in 17666 // GCC for the shift amount on shifted register operands, but it is 17667 // useful in general for any shift amounts. 17668 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 17669 break; 17670 } 17671 return; 17672 17673 case 'N': 17674 if (Subtarget->isThumb1Only()) { 17675 // This must be a constant between 0 and 31, for shift amounts. 17676 if (CVal >= 0 && CVal <= 31) 17677 break; 17678 } 17679 return; 17680 17681 case 'O': 17682 if (Subtarget->isThumb1Only()) { 17683 // This must be a multiple of 4 between -508 and 508, for 17684 // ADD/SUB sp = sp + immediate. 17685 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 17686 break; 17687 } 17688 return; 17689 } 17690 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 17691 break; 17692 } 17693 17694 if (Result.getNode()) { 17695 Ops.push_back(Result); 17696 return; 17697 } 17698 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 17699 } 17700 17701 static RTLIB::Libcall getDivRemLibcall( 17702 const SDNode *N, MVT::SimpleValueType SVT) { 17703 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 17704 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 17705 "Unhandled Opcode in getDivRemLibcall"); 17706 bool isSigned = N->getOpcode() == ISD::SDIVREM || 17707 N->getOpcode() == ISD::SREM; 17708 RTLIB::Libcall LC; 17709 switch (SVT) { 17710 default: llvm_unreachable("Unexpected request for libcall!"); 17711 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 17712 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 17713 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 17714 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 17715 } 17716 return LC; 17717 } 17718 17719 static TargetLowering::ArgListTy getDivRemArgList( 17720 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 17721 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 17722 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 17723 "Unhandled Opcode in getDivRemArgList"); 17724 bool isSigned = N->getOpcode() == ISD::SDIVREM || 17725 N->getOpcode() == ISD::SREM; 17726 TargetLowering::ArgListTy Args; 17727 TargetLowering::ArgListEntry Entry; 17728 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 17729 EVT ArgVT = N->getOperand(i).getValueType(); 17730 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 17731 Entry.Node = N->getOperand(i); 17732 Entry.Ty = ArgTy; 17733 Entry.IsSExt = isSigned; 17734 Entry.IsZExt = !isSigned; 17735 Args.push_back(Entry); 17736 } 17737 if (Subtarget->isTargetWindows() && Args.size() >= 2) 17738 std::swap(Args[0], Args[1]); 17739 return Args; 17740 } 17741 17742 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 17743 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 17744 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 17745 Subtarget->isTargetWindows()) && 17746 "Register-based DivRem lowering only"); 17747 unsigned Opcode = Op->getOpcode(); 17748 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 17749 "Invalid opcode for Div/Rem lowering"); 17750 bool isSigned = (Opcode == ISD::SDIVREM); 17751 EVT VT = Op->getValueType(0); 17752 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 17753 SDLoc dl(Op); 17754 17755 // If the target has hardware divide, use divide + multiply + subtract: 17756 // div = a / b 17757 // rem = a - b * div 17758 // return {div, rem} 17759 // This should be lowered into UDIV/SDIV + MLS later on. 17760 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 17761 : Subtarget->hasDivideInARMMode(); 17762 if (hasDivide && Op->getValueType(0).isSimple() && 17763 Op->getSimpleValueType(0) == MVT::i32) { 17764 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 17765 const SDValue Dividend = Op->getOperand(0); 17766 const SDValue Divisor = Op->getOperand(1); 17767 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 17768 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 17769 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 17770 17771 SDValue Values[2] = {Div, Rem}; 17772 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 17773 } 17774 17775 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 17776 VT.getSimpleVT().SimpleTy); 17777 SDValue InChain = DAG.getEntryNode(); 17778 17779 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 17780 DAG.getContext(), 17781 Subtarget); 17782 17783 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 17784 getPointerTy(DAG.getDataLayout())); 17785 17786 Type *RetTy = StructType::get(Ty, Ty); 17787 17788 if (Subtarget->isTargetWindows()) 17789 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 17790 17791 TargetLowering::CallLoweringInfo CLI(DAG); 17792 CLI.setDebugLoc(dl).setChain(InChain) 17793 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 17794 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 17795 17796 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 17797 return CallInfo.first; 17798 } 17799 17800 // Lowers REM using divmod helpers 17801 // see RTABI section 4.2/4.3 17802 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 17803 // Build return types (div and rem) 17804 std::vector<Type*> RetTyParams; 17805 Type *RetTyElement; 17806 17807 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 17808 default: llvm_unreachable("Unexpected request for libcall!"); 17809 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 17810 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 17811 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 17812 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 17813 } 17814 17815 RetTyParams.push_back(RetTyElement); 17816 RetTyParams.push_back(RetTyElement); 17817 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 17818 Type *RetTy = StructType::get(*DAG.getContext(), ret); 17819 17820 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 17821 SimpleTy); 17822 SDValue InChain = DAG.getEntryNode(); 17823 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 17824 Subtarget); 17825 bool isSigned = N->getOpcode() == ISD::SREM; 17826 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 17827 getPointerTy(DAG.getDataLayout())); 17828 17829 if (Subtarget->isTargetWindows()) 17830 InChain = WinDBZCheckDenominator(DAG, N, InChain); 17831 17832 // Lower call 17833 CallLoweringInfo CLI(DAG); 17834 CLI.setChain(InChain) 17835 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 17836 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 17837 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 17838 17839 // Return second (rem) result operand (first contains div) 17840 SDNode *ResNode = CallResult.first.getNode(); 17841 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 17842 return ResNode->getOperand(1); 17843 } 17844 17845 SDValue 17846 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 17847 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 17848 SDLoc DL(Op); 17849 17850 // Get the inputs. 17851 SDValue Chain = Op.getOperand(0); 17852 SDValue Size = Op.getOperand(1); 17853 17854 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 17855 "no-stack-arg-probe")) { 17856 MaybeAlign Align = 17857 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue(); 17858 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 17859 Chain = SP.getValue(1); 17860 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 17861 if (Align) 17862 SP = 17863 DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 17864 DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32)); 17865 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 17866 SDValue Ops[2] = { SP, Chain }; 17867 return DAG.getMergeValues(Ops, DL); 17868 } 17869 17870 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 17871 DAG.getConstant(2, DL, MVT::i32)); 17872 17873 SDValue Flag; 17874 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 17875 Flag = Chain.getValue(1); 17876 17877 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 17878 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 17879 17880 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 17881 Chain = NewSP.getValue(1); 17882 17883 SDValue Ops[2] = { NewSP, Chain }; 17884 return DAG.getMergeValues(Ops, DL); 17885 } 17886 17887 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 17888 bool IsStrict = Op->isStrictFPOpcode(); 17889 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 17890 const unsigned DstSz = Op.getValueType().getSizeInBits(); 17891 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 17892 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 17893 "Unexpected type for custom-lowering FP_EXTEND"); 17894 17895 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 17896 "With both FP DP and 16, any FP conversion is legal!"); 17897 17898 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 17899 "With FP16, 16 to 32 conversion is legal!"); 17900 17901 // Converting from 32 -> 64 is valid if we have FP64. 17902 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) { 17903 // FIXME: Remove this when we have strict fp instruction selection patterns 17904 if (IsStrict) { 17905 SDLoc Loc(Op); 17906 SDValue Result = DAG.getNode(ISD::FP_EXTEND, 17907 Loc, Op.getValueType(), SrcVal); 17908 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 17909 } 17910 return Op; 17911 } 17912 17913 // Either we are converting from 16 -> 64, without FP16 and/or 17914 // FP.double-precision or without Armv8-fp. So we must do it in two 17915 // steps. 17916 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 17917 // without FP16. So we must do a function call. 17918 SDLoc Loc(Op); 17919 RTLIB::Libcall LC; 17920 MakeLibCallOptions CallOptions; 17921 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 17922 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) { 17923 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64()); 17924 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32); 17925 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64); 17926 if (Supported) { 17927 if (IsStrict) { 17928 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc, 17929 {DstVT, MVT::Other}, {Chain, SrcVal}); 17930 Chain = SrcVal.getValue(1); 17931 } else { 17932 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal); 17933 } 17934 } else { 17935 LC = RTLIB::getFPEXT(SrcVT, DstVT); 17936 assert(LC != RTLIB::UNKNOWN_LIBCALL && 17937 "Unexpected type for custom-lowering FP_EXTEND"); 17938 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 17939 Loc, Chain); 17940 } 17941 } 17942 17943 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal; 17944 } 17945 17946 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 17947 bool IsStrict = Op->isStrictFPOpcode(); 17948 17949 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 17950 EVT SrcVT = SrcVal.getValueType(); 17951 EVT DstVT = Op.getValueType(); 17952 const unsigned DstSz = Op.getValueType().getSizeInBits(); 17953 const unsigned SrcSz = SrcVT.getSizeInBits(); 17954 (void)DstSz; 17955 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 17956 "Unexpected type for custom-lowering FP_ROUND"); 17957 17958 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 17959 "With both FP DP and 16, any FP conversion is legal!"); 17960 17961 SDLoc Loc(Op); 17962 17963 // Instruction from 32 -> 16 if hasFP16 is valid 17964 if (SrcSz == 32 && Subtarget->hasFP16()) 17965 return Op; 17966 17967 // Lib call from 32 -> 16 / 64 -> [32, 16] 17968 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 17969 assert(LC != RTLIB::UNKNOWN_LIBCALL && 17970 "Unexpected type for custom-lowering FP_ROUND"); 17971 MakeLibCallOptions CallOptions; 17972 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 17973 SDValue Result; 17974 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 17975 Loc, Chain); 17976 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 17977 } 17978 17979 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 17980 SelectionDAG &DAG) const { 17981 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 17982 MVT HalfT = MVT::i32; 17983 SDLoc dl(N); 17984 SDValue Hi, Lo, Tmp; 17985 17986 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 17987 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 17988 return ; 17989 17990 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 17991 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 17992 17993 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 17994 DAG.getConstant(0, dl, HalfT)); 17995 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 17996 DAG.getConstant(1, dl, HalfT)); 17997 17998 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 17999 DAG.getConstant(OpTypeBits - 1, dl, 18000 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 18001 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 18002 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 18003 SDValue(Lo.getNode(), 1)); 18004 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 18005 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 18006 18007 Results.push_back(Lo); 18008 Results.push_back(Hi); 18009 } 18010 18011 bool 18012 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 18013 // The ARM target isn't yet aware of offsets. 18014 return false; 18015 } 18016 18017 bool ARM::isBitFieldInvertedMask(unsigned v) { 18018 if (v == 0xffffffff) 18019 return false; 18020 18021 // there can be 1's on either or both "outsides", all the "inside" 18022 // bits must be 0's 18023 return isShiftedMask_32(~v); 18024 } 18025 18026 /// isFPImmLegal - Returns true if the target can instruction select the 18027 /// specified FP immediate natively. If false, the legalizer will 18028 /// materialize the FP immediate as a load from a constant pool. 18029 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 18030 bool ForCodeSize) const { 18031 if (!Subtarget->hasVFP3Base()) 18032 return false; 18033 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 18034 return ARM_AM::getFP16Imm(Imm) != -1; 18035 if (VT == MVT::f32) 18036 return ARM_AM::getFP32Imm(Imm) != -1; 18037 if (VT == MVT::f64 && Subtarget->hasFP64()) 18038 return ARM_AM::getFP64Imm(Imm) != -1; 18039 return false; 18040 } 18041 18042 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 18043 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 18044 /// specified in the intrinsic calls. 18045 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 18046 const CallInst &I, 18047 MachineFunction &MF, 18048 unsigned Intrinsic) const { 18049 switch (Intrinsic) { 18050 case Intrinsic::arm_neon_vld1: 18051 case Intrinsic::arm_neon_vld2: 18052 case Intrinsic::arm_neon_vld3: 18053 case Intrinsic::arm_neon_vld4: 18054 case Intrinsic::arm_neon_vld2lane: 18055 case Intrinsic::arm_neon_vld3lane: 18056 case Intrinsic::arm_neon_vld4lane: 18057 case Intrinsic::arm_neon_vld2dup: 18058 case Intrinsic::arm_neon_vld3dup: 18059 case Intrinsic::arm_neon_vld4dup: { 18060 Info.opc = ISD::INTRINSIC_W_CHAIN; 18061 // Conservatively set memVT to the entire set of vectors loaded. 18062 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18063 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 18064 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18065 Info.ptrVal = I.getArgOperand(0); 18066 Info.offset = 0; 18067 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 18068 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue(); 18069 // volatile loads with NEON intrinsics not supported 18070 Info.flags = MachineMemOperand::MOLoad; 18071 return true; 18072 } 18073 case Intrinsic::arm_neon_vld1x2: 18074 case Intrinsic::arm_neon_vld1x3: 18075 case Intrinsic::arm_neon_vld1x4: { 18076 Info.opc = ISD::INTRINSIC_W_CHAIN; 18077 // Conservatively set memVT to the entire set of vectors loaded. 18078 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18079 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 18080 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18081 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 18082 Info.offset = 0; 18083 Info.align.reset(); 18084 // volatile loads with NEON intrinsics not supported 18085 Info.flags = MachineMemOperand::MOLoad; 18086 return true; 18087 } 18088 case Intrinsic::arm_neon_vst1: 18089 case Intrinsic::arm_neon_vst2: 18090 case Intrinsic::arm_neon_vst3: 18091 case Intrinsic::arm_neon_vst4: 18092 case Intrinsic::arm_neon_vst2lane: 18093 case Intrinsic::arm_neon_vst3lane: 18094 case Intrinsic::arm_neon_vst4lane: { 18095 Info.opc = ISD::INTRINSIC_VOID; 18096 // Conservatively set memVT to the entire set of vectors stored. 18097 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18098 unsigned NumElts = 0; 18099 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 18100 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 18101 if (!ArgTy->isVectorTy()) 18102 break; 18103 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 18104 } 18105 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18106 Info.ptrVal = I.getArgOperand(0); 18107 Info.offset = 0; 18108 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 18109 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue(); 18110 // volatile stores with NEON intrinsics not supported 18111 Info.flags = MachineMemOperand::MOStore; 18112 return true; 18113 } 18114 case Intrinsic::arm_neon_vst1x2: 18115 case Intrinsic::arm_neon_vst1x3: 18116 case Intrinsic::arm_neon_vst1x4: { 18117 Info.opc = ISD::INTRINSIC_VOID; 18118 // Conservatively set memVT to the entire set of vectors stored. 18119 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18120 unsigned NumElts = 0; 18121 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 18122 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 18123 if (!ArgTy->isVectorTy()) 18124 break; 18125 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 18126 } 18127 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18128 Info.ptrVal = I.getArgOperand(0); 18129 Info.offset = 0; 18130 Info.align.reset(); 18131 // volatile stores with NEON intrinsics not supported 18132 Info.flags = MachineMemOperand::MOStore; 18133 return true; 18134 } 18135 case Intrinsic::arm_mve_vld2q: 18136 case Intrinsic::arm_mve_vld4q: { 18137 Info.opc = ISD::INTRINSIC_W_CHAIN; 18138 // Conservatively set memVT to the entire set of vectors loaded. 18139 Type *VecTy = cast<StructType>(I.getType())->getElementType(1); 18140 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4; 18141 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 18142 Info.ptrVal = I.getArgOperand(0); 18143 Info.offset = 0; 18144 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 18145 // volatile loads with MVE intrinsics not supported 18146 Info.flags = MachineMemOperand::MOLoad; 18147 return true; 18148 } 18149 case Intrinsic::arm_mve_vst2q: 18150 case Intrinsic::arm_mve_vst4q: { 18151 Info.opc = ISD::INTRINSIC_VOID; 18152 // Conservatively set memVT to the entire set of vectors stored. 18153 Type *VecTy = I.getArgOperand(1)->getType(); 18154 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4; 18155 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 18156 Info.ptrVal = I.getArgOperand(0); 18157 Info.offset = 0; 18158 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 18159 // volatile stores with MVE intrinsics not supported 18160 Info.flags = MachineMemOperand::MOStore; 18161 return true; 18162 } 18163 case Intrinsic::arm_ldaex: 18164 case Intrinsic::arm_ldrex: { 18165 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18166 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 18167 Info.opc = ISD::INTRINSIC_W_CHAIN; 18168 Info.memVT = MVT::getVT(PtrTy->getElementType()); 18169 Info.ptrVal = I.getArgOperand(0); 18170 Info.offset = 0; 18171 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 18172 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 18173 return true; 18174 } 18175 case Intrinsic::arm_stlex: 18176 case Intrinsic::arm_strex: { 18177 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18178 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 18179 Info.opc = ISD::INTRINSIC_W_CHAIN; 18180 Info.memVT = MVT::getVT(PtrTy->getElementType()); 18181 Info.ptrVal = I.getArgOperand(1); 18182 Info.offset = 0; 18183 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 18184 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 18185 return true; 18186 } 18187 case Intrinsic::arm_stlexd: 18188 case Intrinsic::arm_strexd: 18189 Info.opc = ISD::INTRINSIC_W_CHAIN; 18190 Info.memVT = MVT::i64; 18191 Info.ptrVal = I.getArgOperand(2); 18192 Info.offset = 0; 18193 Info.align = Align(8); 18194 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 18195 return true; 18196 18197 case Intrinsic::arm_ldaexd: 18198 case Intrinsic::arm_ldrexd: 18199 Info.opc = ISD::INTRINSIC_W_CHAIN; 18200 Info.memVT = MVT::i64; 18201 Info.ptrVal = I.getArgOperand(0); 18202 Info.offset = 0; 18203 Info.align = Align(8); 18204 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 18205 return true; 18206 18207 default: 18208 break; 18209 } 18210 18211 return false; 18212 } 18213 18214 /// Returns true if it is beneficial to convert a load of a constant 18215 /// to just the constant itself. 18216 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 18217 Type *Ty) const { 18218 assert(Ty->isIntegerTy()); 18219 18220 unsigned Bits = Ty->getPrimitiveSizeInBits(); 18221 if (Bits == 0 || Bits > 32) 18222 return false; 18223 return true; 18224 } 18225 18226 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 18227 unsigned Index) const { 18228 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 18229 return false; 18230 18231 return (Index == 0 || Index == ResVT.getVectorNumElements()); 18232 } 18233 18234 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 18235 ARM_MB::MemBOpt Domain) const { 18236 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18237 18238 // First, if the target has no DMB, see what fallback we can use. 18239 if (!Subtarget->hasDataBarrier()) { 18240 // Some ARMv6 cpus can support data barriers with an mcr instruction. 18241 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 18242 // here. 18243 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 18244 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 18245 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 18246 Builder.getInt32(0), Builder.getInt32(7), 18247 Builder.getInt32(10), Builder.getInt32(5)}; 18248 return Builder.CreateCall(MCR, args); 18249 } else { 18250 // Instead of using barriers, atomic accesses on these subtargets use 18251 // libcalls. 18252 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 18253 } 18254 } else { 18255 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 18256 // Only a full system barrier exists in the M-class architectures. 18257 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 18258 Constant *CDomain = Builder.getInt32(Domain); 18259 return Builder.CreateCall(DMB, CDomain); 18260 } 18261 } 18262 18263 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 18264 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 18265 Instruction *Inst, 18266 AtomicOrdering Ord) const { 18267 switch (Ord) { 18268 case AtomicOrdering::NotAtomic: 18269 case AtomicOrdering::Unordered: 18270 llvm_unreachable("Invalid fence: unordered/non-atomic"); 18271 case AtomicOrdering::Monotonic: 18272 case AtomicOrdering::Acquire: 18273 return nullptr; // Nothing to do 18274 case AtomicOrdering::SequentiallyConsistent: 18275 if (!Inst->hasAtomicStore()) 18276 return nullptr; // Nothing to do 18277 LLVM_FALLTHROUGH; 18278 case AtomicOrdering::Release: 18279 case AtomicOrdering::AcquireRelease: 18280 if (Subtarget->preferISHSTBarriers()) 18281 return makeDMB(Builder, ARM_MB::ISHST); 18282 // FIXME: add a comment with a link to documentation justifying this. 18283 else 18284 return makeDMB(Builder, ARM_MB::ISH); 18285 } 18286 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 18287 } 18288 18289 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 18290 Instruction *Inst, 18291 AtomicOrdering Ord) const { 18292 switch (Ord) { 18293 case AtomicOrdering::NotAtomic: 18294 case AtomicOrdering::Unordered: 18295 llvm_unreachable("Invalid fence: unordered/not-atomic"); 18296 case AtomicOrdering::Monotonic: 18297 case AtomicOrdering::Release: 18298 return nullptr; // Nothing to do 18299 case AtomicOrdering::Acquire: 18300 case AtomicOrdering::AcquireRelease: 18301 case AtomicOrdering::SequentiallyConsistent: 18302 return makeDMB(Builder, ARM_MB::ISH); 18303 } 18304 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 18305 } 18306 18307 // Loads and stores less than 64-bits are already atomic; ones above that 18308 // are doomed anyway, so defer to the default libcall and blame the OS when 18309 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 18310 // anything for those. 18311 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 18312 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 18313 return (Size == 64) && !Subtarget->isMClass(); 18314 } 18315 18316 // Loads and stores less than 64-bits are already atomic; ones above that 18317 // are doomed anyway, so defer to the default libcall and blame the OS when 18318 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 18319 // anything for those. 18320 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 18321 // guarantee, see DDI0406C ARM architecture reference manual, 18322 // sections A8.8.72-74 LDRD) 18323 TargetLowering::AtomicExpansionKind 18324 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 18325 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 18326 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 18327 : AtomicExpansionKind::None; 18328 } 18329 18330 // For the real atomic operations, we have ldrex/strex up to 32 bits, 18331 // and up to 64 bits on the non-M profiles 18332 TargetLowering::AtomicExpansionKind 18333 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 18334 if (AI->isFloatingPointOperation()) 18335 return AtomicExpansionKind::CmpXChg; 18336 18337 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 18338 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 18339 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 18340 ? AtomicExpansionKind::LLSC 18341 : AtomicExpansionKind::None; 18342 } 18343 18344 TargetLowering::AtomicExpansionKind 18345 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 18346 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 18347 // implement cmpxchg without spilling. If the address being exchanged is also 18348 // on the stack and close enough to the spill slot, this can lead to a 18349 // situation where the monitor always gets cleared and the atomic operation 18350 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 18351 bool HasAtomicCmpXchg = 18352 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 18353 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 18354 return AtomicExpansionKind::LLSC; 18355 return AtomicExpansionKind::None; 18356 } 18357 18358 bool ARMTargetLowering::shouldInsertFencesForAtomic( 18359 const Instruction *I) const { 18360 return InsertFencesForAtomic; 18361 } 18362 18363 // This has so far only been implemented for MachO. 18364 bool ARMTargetLowering::useLoadStackGuardNode() const { 18365 return Subtarget->isTargetMachO(); 18366 } 18367 18368 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 18369 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18370 return TargetLowering::insertSSPDeclarations(M); 18371 18372 // MSVC CRT has a global variable holding security cookie. 18373 M.getOrInsertGlobal("__security_cookie", 18374 Type::getInt8PtrTy(M.getContext())); 18375 18376 // MSVC CRT has a function to validate security cookie. 18377 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 18378 "__security_check_cookie", Type::getVoidTy(M.getContext()), 18379 Type::getInt8PtrTy(M.getContext())); 18380 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 18381 F->addAttribute(1, Attribute::AttrKind::InReg); 18382 } 18383 18384 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 18385 // MSVC CRT has a global variable holding security cookie. 18386 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18387 return M.getGlobalVariable("__security_cookie"); 18388 return TargetLowering::getSDagStackGuard(M); 18389 } 18390 18391 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 18392 // MSVC CRT has a function to validate security cookie. 18393 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18394 return M.getFunction("__security_check_cookie"); 18395 return TargetLowering::getSSPStackGuardCheck(M); 18396 } 18397 18398 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 18399 unsigned &Cost) const { 18400 // If we do not have NEON, vector types are not natively supported. 18401 if (!Subtarget->hasNEON()) 18402 return false; 18403 18404 // Floating point values and vector values map to the same register file. 18405 // Therefore, although we could do a store extract of a vector type, this is 18406 // better to leave at float as we have more freedom in the addressing mode for 18407 // those. 18408 if (VectorTy->isFPOrFPVectorTy()) 18409 return false; 18410 18411 // If the index is unknown at compile time, this is very expensive to lower 18412 // and it is not possible to combine the store with the extract. 18413 if (!isa<ConstantInt>(Idx)) 18414 return false; 18415 18416 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 18417 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize(); 18418 // We can do a store + vector extract on any vector that fits perfectly in a D 18419 // or Q register. 18420 if (BitWidth == 64 || BitWidth == 128) { 18421 Cost = 0; 18422 return true; 18423 } 18424 return false; 18425 } 18426 18427 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 18428 return Subtarget->hasV6T2Ops(); 18429 } 18430 18431 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 18432 return Subtarget->hasV6T2Ops(); 18433 } 18434 18435 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 18436 return !Subtarget->hasMinSize() || Subtarget->isTargetWindows(); 18437 } 18438 18439 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 18440 AtomicOrdering Ord) const { 18441 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18442 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 18443 bool IsAcquire = isAcquireOrStronger(Ord); 18444 18445 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 18446 // intrinsic must return {i32, i32} and we have to recombine them into a 18447 // single i64 here. 18448 if (ValTy->getPrimitiveSizeInBits() == 64) { 18449 Intrinsic::ID Int = 18450 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 18451 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 18452 18453 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 18454 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 18455 18456 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18457 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18458 if (!Subtarget->isLittle()) 18459 std::swap (Lo, Hi); 18460 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18461 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18462 return Builder.CreateOr( 18463 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 18464 } 18465 18466 Type *Tys[] = { Addr->getType() }; 18467 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 18468 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 18469 18470 return Builder.CreateTruncOrBitCast( 18471 Builder.CreateCall(Ldrex, Addr), 18472 cast<PointerType>(Addr->getType())->getElementType()); 18473 } 18474 18475 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 18476 IRBuilder<> &Builder) const { 18477 if (!Subtarget->hasV7Ops()) 18478 return; 18479 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18480 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 18481 } 18482 18483 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 18484 Value *Addr, 18485 AtomicOrdering Ord) const { 18486 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18487 bool IsRelease = isReleaseOrStronger(Ord); 18488 18489 // Since the intrinsics must have legal type, the i64 intrinsics take two 18490 // parameters: "i32, i32". We must marshal Val into the appropriate form 18491 // before the call. 18492 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 18493 Intrinsic::ID Int = 18494 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 18495 Function *Strex = Intrinsic::getDeclaration(M, Int); 18496 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 18497 18498 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 18499 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 18500 if (!Subtarget->isLittle()) 18501 std::swap(Lo, Hi); 18502 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 18503 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 18504 } 18505 18506 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 18507 Type *Tys[] = { Addr->getType() }; 18508 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 18509 18510 return Builder.CreateCall( 18511 Strex, {Builder.CreateZExtOrBitCast( 18512 Val, Strex->getFunctionType()->getParamType(0)), 18513 Addr}); 18514 } 18515 18516 18517 bool ARMTargetLowering::alignLoopsWithOptSize() const { 18518 return Subtarget->isMClass(); 18519 } 18520 18521 /// A helper function for determining the number of interleaved accesses we 18522 /// will generate when lowering accesses of the given type. 18523 unsigned 18524 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 18525 const DataLayout &DL) const { 18526 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 18527 } 18528 18529 bool ARMTargetLowering::isLegalInterleavedAccessType( 18530 unsigned Factor, FixedVectorType *VecTy, const DataLayout &DL) const { 18531 18532 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 18533 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 18534 18535 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) 18536 return false; 18537 18538 // Ensure the vector doesn't have f16 elements. Even though we could do an 18539 // i16 vldN, we can't hold the f16 vectors and will end up converting via 18540 // f32. 18541 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy()) 18542 return false; 18543 if (Subtarget->hasMVEIntegerOps() && Factor == 3) 18544 return false; 18545 18546 // Ensure the number of vector elements is greater than 1. 18547 if (VecTy->getNumElements() < 2) 18548 return false; 18549 18550 // Ensure the element type is legal. 18551 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 18552 return false; 18553 18554 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 18555 // 128 will be split into multiple interleaved accesses. 18556 if (Subtarget->hasNEON() && VecSize == 64) 18557 return true; 18558 return VecSize % 128 == 0; 18559 } 18560 18561 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const { 18562 if (Subtarget->hasNEON()) 18563 return 4; 18564 if (Subtarget->hasMVEIntegerOps()) 18565 return MVEMaxSupportedInterleaveFactor; 18566 return TargetLoweringBase::getMaxSupportedInterleaveFactor(); 18567 } 18568 18569 /// Lower an interleaved load into a vldN intrinsic. 18570 /// 18571 /// E.g. Lower an interleaved load (Factor = 2): 18572 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 18573 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 18574 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 18575 /// 18576 /// Into: 18577 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 18578 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 18579 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 18580 bool ARMTargetLowering::lowerInterleavedLoad( 18581 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 18582 ArrayRef<unsigned> Indices, unsigned Factor) const { 18583 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 18584 "Invalid interleave factor"); 18585 assert(!Shuffles.empty() && "Empty shufflevector input"); 18586 assert(Shuffles.size() == Indices.size() && 18587 "Unmatched number of shufflevectors and indices"); 18588 18589 auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType()); 18590 Type *EltTy = VecTy->getElementType(); 18591 18592 const DataLayout &DL = LI->getModule()->getDataLayout(); 18593 18594 // Skip if we do not have NEON and skip illegal vector types. We can 18595 // "legalize" wide vector types into multiple interleaved accesses as long as 18596 // the vector types are divisible by 128. 18597 if (!isLegalInterleavedAccessType(Factor, VecTy, DL)) 18598 return false; 18599 18600 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 18601 18602 // A pointer vector can not be the return type of the ldN intrinsics. Need to 18603 // load integer vectors first and then convert to pointer vectors. 18604 if (EltTy->isPointerTy()) 18605 VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy); 18606 18607 IRBuilder<> Builder(LI); 18608 18609 // The base address of the load. 18610 Value *BaseAddr = LI->getPointerOperand(); 18611 18612 if (NumLoads > 1) { 18613 // If we're going to generate more than one load, reset the sub-vector type 18614 // to something legal. 18615 VecTy = FixedVectorType::get(VecTy->getElementType(), 18616 VecTy->getNumElements() / NumLoads); 18617 18618 // We will compute the pointer operand of each load from the original base 18619 // address using GEPs. Cast the base address to a pointer to the scalar 18620 // element type. 18621 BaseAddr = Builder.CreateBitCast( 18622 BaseAddr, 18623 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())); 18624 } 18625 18626 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 18627 18628 auto createLoadIntrinsic = [&](Value *BaseAddr) { 18629 if (Subtarget->hasNEON()) { 18630 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 18631 Type *Tys[] = {VecTy, Int8Ptr}; 18632 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 18633 Intrinsic::arm_neon_vld3, 18634 Intrinsic::arm_neon_vld4}; 18635 Function *VldnFunc = 18636 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 18637 18638 SmallVector<Value *, 2> Ops; 18639 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 18640 Ops.push_back(Builder.getInt32(LI->getAlignment())); 18641 18642 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 18643 } else { 18644 assert((Factor == 2 || Factor == 4) && 18645 "expected interleave factor of 2 or 4 for MVE"); 18646 Intrinsic::ID LoadInts = 18647 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q; 18648 Type *VecEltTy = 18649 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()); 18650 Type *Tys[] = {VecTy, VecEltTy}; 18651 Function *VldnFunc = 18652 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys); 18653 18654 SmallVector<Value *, 2> Ops; 18655 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy)); 18656 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 18657 } 18658 }; 18659 18660 // Holds sub-vectors extracted from the load intrinsic return values. The 18661 // sub-vectors are associated with the shufflevector instructions they will 18662 // replace. 18663 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 18664 18665 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 18666 // If we're generating more than one load, compute the base address of 18667 // subsequent loads as an offset from the previous. 18668 if (LoadCount > 0) 18669 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr, 18670 VecTy->getNumElements() * Factor); 18671 18672 CallInst *VldN = createLoadIntrinsic(BaseAddr); 18673 18674 // Replace uses of each shufflevector with the corresponding vector loaded 18675 // by ldN. 18676 for (unsigned i = 0; i < Shuffles.size(); i++) { 18677 ShuffleVectorInst *SV = Shuffles[i]; 18678 unsigned Index = Indices[i]; 18679 18680 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 18681 18682 // Convert the integer vector to pointer vector if the element is pointer. 18683 if (EltTy->isPointerTy()) 18684 SubVec = Builder.CreateIntToPtr( 18685 SubVec, 18686 FixedVectorType::get(SV->getType()->getElementType(), VecTy)); 18687 18688 SubVecs[SV].push_back(SubVec); 18689 } 18690 } 18691 18692 // Replace uses of the shufflevector instructions with the sub-vectors 18693 // returned by the load intrinsic. If a shufflevector instruction is 18694 // associated with more than one sub-vector, those sub-vectors will be 18695 // concatenated into a single wide vector. 18696 for (ShuffleVectorInst *SVI : Shuffles) { 18697 auto &SubVec = SubVecs[SVI]; 18698 auto *WideVec = 18699 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 18700 SVI->replaceAllUsesWith(WideVec); 18701 } 18702 18703 return true; 18704 } 18705 18706 /// Lower an interleaved store into a vstN intrinsic. 18707 /// 18708 /// E.g. Lower an interleaved store (Factor = 3): 18709 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 18710 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 18711 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 18712 /// 18713 /// Into: 18714 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 18715 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 18716 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 18717 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 18718 /// 18719 /// Note that the new shufflevectors will be removed and we'll only generate one 18720 /// vst3 instruction in CodeGen. 18721 /// 18722 /// Example for a more general valid mask (Factor 3). Lower: 18723 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 18724 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 18725 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 18726 /// 18727 /// Into: 18728 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 18729 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 18730 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 18731 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 18732 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 18733 ShuffleVectorInst *SVI, 18734 unsigned Factor) const { 18735 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 18736 "Invalid interleave factor"); 18737 18738 auto *VecTy = cast<FixedVectorType>(SVI->getType()); 18739 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store"); 18740 18741 unsigned LaneLen = VecTy->getNumElements() / Factor; 18742 Type *EltTy = VecTy->getElementType(); 18743 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen); 18744 18745 const DataLayout &DL = SI->getModule()->getDataLayout(); 18746 18747 // Skip if we do not have NEON and skip illegal vector types. We can 18748 // "legalize" wide vector types into multiple interleaved accesses as long as 18749 // the vector types are divisible by 128. 18750 if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL)) 18751 return false; 18752 18753 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 18754 18755 Value *Op0 = SVI->getOperand(0); 18756 Value *Op1 = SVI->getOperand(1); 18757 IRBuilder<> Builder(SI); 18758 18759 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 18760 // vectors to integer vectors. 18761 if (EltTy->isPointerTy()) { 18762 Type *IntTy = DL.getIntPtrType(EltTy); 18763 18764 // Convert to the corresponding integer vector. 18765 auto *IntVecTy = 18766 FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType())); 18767 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 18768 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 18769 18770 SubVecTy = FixedVectorType::get(IntTy, LaneLen); 18771 } 18772 18773 // The base address of the store. 18774 Value *BaseAddr = SI->getPointerOperand(); 18775 18776 if (NumStores > 1) { 18777 // If we're going to generate more than one store, reset the lane length 18778 // and sub-vector type to something legal. 18779 LaneLen /= NumStores; 18780 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen); 18781 18782 // We will compute the pointer operand of each store 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 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())); 18788 } 18789 18790 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 18791 18792 auto Mask = SVI->getShuffleMask(); 18793 18794 auto createStoreIntrinsic = [&](Value *BaseAddr, 18795 SmallVectorImpl<Value *> &Shuffles) { 18796 if (Subtarget->hasNEON()) { 18797 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 18798 Intrinsic::arm_neon_vst3, 18799 Intrinsic::arm_neon_vst4}; 18800 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 18801 Type *Tys[] = {Int8Ptr, SubVecTy}; 18802 18803 Function *VstNFunc = Intrinsic::getDeclaration( 18804 SI->getModule(), StoreInts[Factor - 2], Tys); 18805 18806 SmallVector<Value *, 6> Ops; 18807 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 18808 for (auto S : Shuffles) 18809 Ops.push_back(S); 18810 Ops.push_back(Builder.getInt32(SI->getAlignment())); 18811 Builder.CreateCall(VstNFunc, Ops); 18812 } else { 18813 assert((Factor == 2 || Factor == 4) && 18814 "expected interleave factor of 2 or 4 for MVE"); 18815 Intrinsic::ID StoreInts = 18816 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q; 18817 Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo( 18818 SI->getPointerAddressSpace()); 18819 Type *Tys[] = {EltPtrTy, SubVecTy}; 18820 Function *VstNFunc = 18821 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys); 18822 18823 SmallVector<Value *, 6> Ops; 18824 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy)); 18825 for (auto S : Shuffles) 18826 Ops.push_back(S); 18827 for (unsigned F = 0; F < Factor; F++) { 18828 Ops.push_back(Builder.getInt32(F)); 18829 Builder.CreateCall(VstNFunc, Ops); 18830 Ops.pop_back(); 18831 } 18832 } 18833 }; 18834 18835 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 18836 // If we generating more than one store, we compute the base address of 18837 // subsequent stores as an offset from the previous. 18838 if (StoreCount > 0) 18839 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(), 18840 BaseAddr, LaneLen * Factor); 18841 18842 SmallVector<Value *, 4> Shuffles; 18843 18844 // Split the shufflevector operands into sub vectors for the new vstN call. 18845 for (unsigned i = 0; i < Factor; i++) { 18846 unsigned IdxI = StoreCount * LaneLen * Factor + i; 18847 if (Mask[IdxI] >= 0) { 18848 Shuffles.push_back(Builder.CreateShuffleVector( 18849 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0))); 18850 } else { 18851 unsigned StartMask = 0; 18852 for (unsigned j = 1; j < LaneLen; j++) { 18853 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 18854 if (Mask[IdxJ * Factor + IdxI] >= 0) { 18855 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 18856 break; 18857 } 18858 } 18859 // Note: If all elements in a chunk are undefs, StartMask=0! 18860 // Note: Filling undef gaps with random elements is ok, since 18861 // those elements were being written anyway (with undefs). 18862 // In the case of all undefs we're defaulting to using elems from 0 18863 // Note: StartMask cannot be negative, it's checked in 18864 // isReInterleaveMask 18865 Shuffles.push_back(Builder.CreateShuffleVector( 18866 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0))); 18867 } 18868 } 18869 18870 createStoreIntrinsic(BaseAddr, Shuffles); 18871 } 18872 return true; 18873 } 18874 18875 enum HABaseType { 18876 HA_UNKNOWN = 0, 18877 HA_FLOAT, 18878 HA_DOUBLE, 18879 HA_VECT64, 18880 HA_VECT128 18881 }; 18882 18883 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 18884 uint64_t &Members) { 18885 if (auto *ST = dyn_cast<StructType>(Ty)) { 18886 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 18887 uint64_t SubMembers = 0; 18888 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 18889 return false; 18890 Members += SubMembers; 18891 } 18892 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 18893 uint64_t SubMembers = 0; 18894 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 18895 return false; 18896 Members += SubMembers * AT->getNumElements(); 18897 } else if (Ty->isFloatTy()) { 18898 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 18899 return false; 18900 Members = 1; 18901 Base = HA_FLOAT; 18902 } else if (Ty->isDoubleTy()) { 18903 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 18904 return false; 18905 Members = 1; 18906 Base = HA_DOUBLE; 18907 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 18908 Members = 1; 18909 switch (Base) { 18910 case HA_FLOAT: 18911 case HA_DOUBLE: 18912 return false; 18913 case HA_VECT64: 18914 return VT->getPrimitiveSizeInBits().getFixedSize() == 64; 18915 case HA_VECT128: 18916 return VT->getPrimitiveSizeInBits().getFixedSize() == 128; 18917 case HA_UNKNOWN: 18918 switch (VT->getPrimitiveSizeInBits().getFixedSize()) { 18919 case 64: 18920 Base = HA_VECT64; 18921 return true; 18922 case 128: 18923 Base = HA_VECT128; 18924 return true; 18925 default: 18926 return false; 18927 } 18928 } 18929 } 18930 18931 return (Members > 0 && Members <= 4); 18932 } 18933 18934 /// Return the correct alignment for the current calling convention. 18935 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 18936 DataLayout DL) const { 18937 const Align ABITypeAlign = DL.getABITypeAlign(ArgTy); 18938 if (!ArgTy->isVectorTy()) 18939 return ABITypeAlign; 18940 18941 // Avoid over-aligning vector parameters. It would require realigning the 18942 // stack and waste space for no real benefit. 18943 return std::min(ABITypeAlign, DL.getStackAlignment()); 18944 } 18945 18946 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 18947 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 18948 /// passing according to AAPCS rules. 18949 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 18950 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 18951 if (getEffectiveCallingConv(CallConv, isVarArg) != 18952 CallingConv::ARM_AAPCS_VFP) 18953 return false; 18954 18955 HABaseType Base = HA_UNKNOWN; 18956 uint64_t Members = 0; 18957 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 18958 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 18959 18960 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 18961 return IsHA || IsIntArray; 18962 } 18963 18964 Register ARMTargetLowering::getExceptionPointerRegister( 18965 const Constant *PersonalityFn) const { 18966 // Platforms which do not use SjLj EH may return values in these registers 18967 // via the personality function. 18968 return Subtarget->useSjLjEH() ? Register() : ARM::R0; 18969 } 18970 18971 Register ARMTargetLowering::getExceptionSelectorRegister( 18972 const Constant *PersonalityFn) const { 18973 // Platforms which do not use SjLj EH may return values in these registers 18974 // via the personality function. 18975 return Subtarget->useSjLjEH() ? Register() : ARM::R1; 18976 } 18977 18978 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 18979 // Update IsSplitCSR in ARMFunctionInfo. 18980 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 18981 AFI->setIsSplitCSR(true); 18982 } 18983 18984 void ARMTargetLowering::insertCopiesSplitCSR( 18985 MachineBasicBlock *Entry, 18986 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 18987 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 18988 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 18989 if (!IStart) 18990 return; 18991 18992 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 18993 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 18994 MachineBasicBlock::iterator MBBI = Entry->begin(); 18995 for (const MCPhysReg *I = IStart; *I; ++I) { 18996 const TargetRegisterClass *RC = nullptr; 18997 if (ARM::GPRRegClass.contains(*I)) 18998 RC = &ARM::GPRRegClass; 18999 else if (ARM::DPRRegClass.contains(*I)) 19000 RC = &ARM::DPRRegClass; 19001 else 19002 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 19003 19004 Register NewVR = MRI->createVirtualRegister(RC); 19005 // Create copy from CSR to a virtual register. 19006 // FIXME: this currently does not emit CFI pseudo-instructions, it works 19007 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 19008 // nounwind. If we want to generalize this later, we may need to emit 19009 // CFI pseudo-instructions. 19010 assert(Entry->getParent()->getFunction().hasFnAttribute( 19011 Attribute::NoUnwind) && 19012 "Function should be nounwind in insertCopiesSplitCSR!"); 19013 Entry->addLiveIn(*I); 19014 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 19015 .addReg(*I); 19016 19017 // Insert the copy-back instructions right before the terminator. 19018 for (auto *Exit : Exits) 19019 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 19020 TII->get(TargetOpcode::COPY), *I) 19021 .addReg(NewVR); 19022 } 19023 } 19024 19025 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 19026 MF.getFrameInfo().computeMaxCallFrameSize(MF); 19027 TargetLoweringBase::finalizeLowering(MF); 19028 } 19029