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 214 if (!VT.isFloatingPoint() && 215 VT != MVT::v2i64 && VT != MVT::v1i64) 216 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 217 setOperationAction(Opcode, VT, Legal); 218 if (!VT.isFloatingPoint()) 219 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}) 220 setOperationAction(Opcode, VT, Legal); 221 } 222 223 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 224 addRegisterClass(VT, &ARM::DPRRegClass); 225 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 226 } 227 228 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 229 addRegisterClass(VT, &ARM::DPairRegClass); 230 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 231 } 232 233 void ARMTargetLowering::setAllExpand(MVT VT) { 234 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc) 235 setOperationAction(Opc, VT, Expand); 236 237 // We support these really simple operations even on types where all 238 // the actual arithmetic has to be broken down into simpler 239 // operations or turned into library calls. 240 setOperationAction(ISD::BITCAST, VT, Legal); 241 setOperationAction(ISD::LOAD, VT, Legal); 242 setOperationAction(ISD::STORE, VT, Legal); 243 setOperationAction(ISD::UNDEF, VT, Legal); 244 } 245 246 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To, 247 LegalizeAction Action) { 248 setLoadExtAction(ISD::EXTLOAD, From, To, Action); 249 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action); 250 setLoadExtAction(ISD::SEXTLOAD, From, To, Action); 251 } 252 253 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) { 254 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 }; 255 256 for (auto VT : IntTypes) { 257 addRegisterClass(VT, &ARM::MQPRRegClass); 258 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 259 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 260 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 261 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 262 setOperationAction(ISD::SHL, VT, Custom); 263 setOperationAction(ISD::SRA, VT, Custom); 264 setOperationAction(ISD::SRL, VT, Custom); 265 setOperationAction(ISD::SMIN, VT, Legal); 266 setOperationAction(ISD::SMAX, VT, Legal); 267 setOperationAction(ISD::UMIN, VT, Legal); 268 setOperationAction(ISD::UMAX, VT, Legal); 269 setOperationAction(ISD::ABS, VT, Legal); 270 setOperationAction(ISD::SETCC, VT, Custom); 271 setOperationAction(ISD::MLOAD, VT, Custom); 272 setOperationAction(ISD::MSTORE, VT, Legal); 273 setOperationAction(ISD::CTLZ, VT, Legal); 274 setOperationAction(ISD::CTTZ, VT, Custom); 275 setOperationAction(ISD::BITREVERSE, VT, Legal); 276 setOperationAction(ISD::BSWAP, VT, Legal); 277 setOperationAction(ISD::SADDSAT, VT, Legal); 278 setOperationAction(ISD::UADDSAT, VT, Legal); 279 setOperationAction(ISD::SSUBSAT, VT, Legal); 280 setOperationAction(ISD::USUBSAT, VT, Legal); 281 282 // No native support for these. 283 setOperationAction(ISD::UDIV, VT, Expand); 284 setOperationAction(ISD::SDIV, VT, Expand); 285 setOperationAction(ISD::UREM, VT, Expand); 286 setOperationAction(ISD::SREM, VT, Expand); 287 setOperationAction(ISD::CTPOP, VT, Expand); 288 289 // Vector reductions 290 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal); 291 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal); 292 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal); 293 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal); 294 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal); 295 296 if (!HasMVEFP) { 297 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 298 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 299 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 300 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 301 } 302 303 // Pre and Post inc are supported on loads and stores 304 for (unsigned im = (unsigned)ISD::PRE_INC; 305 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 306 setIndexedLoadAction(im, VT, Legal); 307 setIndexedStoreAction(im, VT, Legal); 308 setIndexedMaskedLoadAction(im, VT, Legal); 309 setIndexedMaskedStoreAction(im, VT, Legal); 310 } 311 } 312 313 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 }; 314 for (auto VT : FloatTypes) { 315 addRegisterClass(VT, &ARM::MQPRRegClass); 316 if (!HasMVEFP) 317 setAllExpand(VT); 318 319 // These are legal or custom whether we have MVE.fp or not 320 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 321 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 322 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom); 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 324 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 325 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom); 326 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal); 327 setOperationAction(ISD::SETCC, VT, Custom); 328 setOperationAction(ISD::MLOAD, VT, Custom); 329 setOperationAction(ISD::MSTORE, VT, Legal); 330 331 // Pre and Post inc are supported on loads and stores 332 for (unsigned im = (unsigned)ISD::PRE_INC; 333 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 334 setIndexedLoadAction(im, VT, Legal); 335 setIndexedStoreAction(im, VT, Legal); 336 setIndexedMaskedLoadAction(im, VT, Legal); 337 setIndexedMaskedStoreAction(im, VT, Legal); 338 } 339 340 if (HasMVEFP) { 341 setOperationAction(ISD::FMINNUM, VT, Legal); 342 setOperationAction(ISD::FMAXNUM, VT, Legal); 343 setOperationAction(ISD::FROUND, VT, Legal); 344 345 // No native support for these. 346 setOperationAction(ISD::FDIV, VT, Expand); 347 setOperationAction(ISD::FREM, VT, Expand); 348 setOperationAction(ISD::FSQRT, VT, Expand); 349 setOperationAction(ISD::FSIN, VT, Expand); 350 setOperationAction(ISD::FCOS, VT, Expand); 351 setOperationAction(ISD::FPOW, VT, Expand); 352 setOperationAction(ISD::FLOG, VT, Expand); 353 setOperationAction(ISD::FLOG2, VT, Expand); 354 setOperationAction(ISD::FLOG10, VT, Expand); 355 setOperationAction(ISD::FEXP, VT, Expand); 356 setOperationAction(ISD::FEXP2, VT, Expand); 357 setOperationAction(ISD::FNEARBYINT, VT, Expand); 358 } 359 } 360 361 // We 'support' these types up to bitcast/load/store level, regardless of 362 // MVE integer-only / float support. Only doing FP data processing on the FP 363 // vector types is inhibited at integer-only level. 364 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 }; 365 for (auto VT : LongTypes) { 366 addRegisterClass(VT, &ARM::MQPRRegClass); 367 setAllExpand(VT); 368 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 369 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 370 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 371 } 372 // We can do bitwise operations on v2i64 vectors 373 setOperationAction(ISD::AND, MVT::v2i64, Legal); 374 setOperationAction(ISD::OR, MVT::v2i64, Legal); 375 setOperationAction(ISD::XOR, MVT::v2i64, Legal); 376 377 // It is legal to extload from v4i8 to v4i16 or v4i32. 378 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal); 379 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal); 380 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal); 381 382 // Some truncating stores are legal too. 383 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal); 384 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal); 385 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal); 386 387 // Pre and Post inc on these are legal, given the correct extends 388 for (unsigned im = (unsigned)ISD::PRE_INC; 389 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 390 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) { 391 setIndexedLoadAction(im, VT, Legal); 392 setIndexedStoreAction(im, VT, Legal); 393 setIndexedMaskedLoadAction(im, VT, Legal); 394 setIndexedMaskedStoreAction(im, VT, Legal); 395 } 396 } 397 398 // Predicate types 399 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1}; 400 for (auto VT : pTypes) { 401 addRegisterClass(VT, &ARM::VCCRRegClass); 402 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 403 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 404 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 405 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 406 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 407 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 408 setOperationAction(ISD::SETCC, VT, Custom); 409 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 410 setOperationAction(ISD::LOAD, VT, Custom); 411 setOperationAction(ISD::STORE, VT, Custom); 412 } 413 } 414 415 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 416 const ARMSubtarget &STI) 417 : TargetLowering(TM), Subtarget(&STI) { 418 RegInfo = Subtarget->getRegisterInfo(); 419 Itins = Subtarget->getInstrItineraryData(); 420 421 setBooleanContents(ZeroOrOneBooleanContent); 422 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 423 424 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 425 !Subtarget->isTargetWatchOS()) { 426 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 427 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 428 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 429 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 430 : CallingConv::ARM_AAPCS); 431 } 432 433 if (Subtarget->isTargetMachO()) { 434 // Uses VFP for Thumb libfuncs if available. 435 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 436 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 437 static const struct { 438 const RTLIB::Libcall Op; 439 const char * const Name; 440 const ISD::CondCode Cond; 441 } LibraryCalls[] = { 442 // Single-precision floating-point arithmetic. 443 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 444 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 445 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 446 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 447 448 // Double-precision floating-point arithmetic. 449 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 450 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 451 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 452 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 453 454 // Single-precision comparisons. 455 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 456 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 457 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 458 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 459 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 460 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 461 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 462 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 463 464 // Double-precision comparisons. 465 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 466 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 467 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 468 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 469 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 470 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 471 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 472 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 473 474 // Floating-point to integer conversions. 475 // i64 conversions are done via library routines even when generating VFP 476 // instructions, so use the same ones. 477 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 478 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 479 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 480 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 481 482 // Conversions between floating types. 483 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 484 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 485 486 // Integer to floating-point conversions. 487 // i64 conversions are done via library routines even when generating VFP 488 // instructions, so use the same ones. 489 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 490 // e.g., __floatunsidf vs. __floatunssidfvfp. 491 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 492 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 493 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 494 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 495 }; 496 497 for (const auto &LC : LibraryCalls) { 498 setLibcallName(LC.Op, LC.Name); 499 if (LC.Cond != ISD::SETCC_INVALID) 500 setCmpLibcallCC(LC.Op, LC.Cond); 501 } 502 } 503 } 504 505 // These libcalls are not available in 32-bit. 506 setLibcallName(RTLIB::SHL_I128, nullptr); 507 setLibcallName(RTLIB::SRL_I128, nullptr); 508 setLibcallName(RTLIB::SRA_I128, nullptr); 509 510 // RTLIB 511 if (Subtarget->isAAPCS_ABI() && 512 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 513 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 514 static const struct { 515 const RTLIB::Libcall Op; 516 const char * const Name; 517 const CallingConv::ID CC; 518 const ISD::CondCode Cond; 519 } LibraryCalls[] = { 520 // Double-precision floating-point arithmetic helper functions 521 // RTABI chapter 4.1.2, Table 2 522 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 523 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 524 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 525 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 526 527 // Double-precision floating-point comparison helper functions 528 // RTABI chapter 4.1.2, Table 3 529 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 530 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 531 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 532 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 533 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 534 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 535 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 536 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 537 538 // Single-precision floating-point arithmetic helper functions 539 // RTABI chapter 4.1.2, Table 4 540 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 541 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 542 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 543 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 544 545 // Single-precision floating-point comparison helper functions 546 // RTABI chapter 4.1.2, Table 5 547 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 548 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 549 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 550 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 551 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 552 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 553 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 554 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 555 556 // Floating-point to integer conversions. 557 // RTABI chapter 4.1.2, Table 6 558 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 559 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 560 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 561 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 562 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 563 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 564 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 565 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 566 567 // Conversions between floating types. 568 // RTABI chapter 4.1.2, Table 7 569 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 570 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 571 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 572 573 // Integer to floating-point conversions. 574 // RTABI chapter 4.1.2, Table 8 575 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 576 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 577 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 578 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 579 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 580 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 581 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 582 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 583 584 // Long long helper functions 585 // RTABI chapter 4.2, Table 9 586 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 587 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 588 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 589 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 590 591 // Integer division functions 592 // RTABI chapter 4.3.1 593 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 594 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 595 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 596 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 597 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 598 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 599 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 600 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 601 }; 602 603 for (const auto &LC : LibraryCalls) { 604 setLibcallName(LC.Op, LC.Name); 605 setLibcallCallingConv(LC.Op, LC.CC); 606 if (LC.Cond != ISD::SETCC_INVALID) 607 setCmpLibcallCC(LC.Op, LC.Cond); 608 } 609 610 // EABI dependent RTLIB 611 if (TM.Options.EABIVersion == EABI::EABI4 || 612 TM.Options.EABIVersion == EABI::EABI5) { 613 static const struct { 614 const RTLIB::Libcall Op; 615 const char *const Name; 616 const CallingConv::ID CC; 617 const ISD::CondCode Cond; 618 } MemOpsLibraryCalls[] = { 619 // Memory operations 620 // RTABI chapter 4.3.4 621 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 622 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 623 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 624 }; 625 626 for (const auto &LC : MemOpsLibraryCalls) { 627 setLibcallName(LC.Op, LC.Name); 628 setLibcallCallingConv(LC.Op, LC.CC); 629 if (LC.Cond != ISD::SETCC_INVALID) 630 setCmpLibcallCC(LC.Op, LC.Cond); 631 } 632 } 633 } 634 635 if (Subtarget->isTargetWindows()) { 636 static const struct { 637 const RTLIB::Libcall Op; 638 const char * const Name; 639 const CallingConv::ID CC; 640 } LibraryCalls[] = { 641 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 642 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 643 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 644 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 645 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 646 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 647 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 648 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 649 }; 650 651 for (const auto &LC : LibraryCalls) { 652 setLibcallName(LC.Op, LC.Name); 653 setLibcallCallingConv(LC.Op, LC.CC); 654 } 655 } 656 657 // Use divmod compiler-rt calls for iOS 5.0 and later. 658 if (Subtarget->isTargetMachO() && 659 !(Subtarget->isTargetIOS() && 660 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 661 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 662 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 663 } 664 665 // The half <-> float conversion functions are always soft-float on 666 // non-watchos platforms, but are needed for some targets which use a 667 // hard-float calling convention by default. 668 if (!Subtarget->isTargetWatchABI()) { 669 if (Subtarget->isAAPCS_ABI()) { 670 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 671 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 672 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 673 } else { 674 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 675 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 676 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 677 } 678 } 679 680 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 681 // a __gnu_ prefix (which is the default). 682 if (Subtarget->isTargetAEABI()) { 683 static const struct { 684 const RTLIB::Libcall Op; 685 const char * const Name; 686 const CallingConv::ID CC; 687 } LibraryCalls[] = { 688 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 689 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 690 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 691 }; 692 693 for (const auto &LC : LibraryCalls) { 694 setLibcallName(LC.Op, LC.Name); 695 setLibcallCallingConv(LC.Op, LC.CC); 696 } 697 } 698 699 if (Subtarget->isThumb1Only()) 700 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 701 else 702 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 703 704 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() && 705 Subtarget->hasFPRegs()) { 706 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 707 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 708 if (!Subtarget->hasVFP2Base()) 709 setAllExpand(MVT::f32); 710 if (!Subtarget->hasFP64()) 711 setAllExpand(MVT::f64); 712 } 713 714 if (Subtarget->hasFullFP16()) { 715 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 716 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 717 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 718 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 719 720 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 721 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 722 } 723 724 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 725 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 726 setTruncStoreAction(VT, InnerVT, Expand); 727 addAllExtLoads(VT, InnerVT, Expand); 728 } 729 730 setOperationAction(ISD::MULHS, VT, Expand); 731 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 732 setOperationAction(ISD::MULHU, VT, Expand); 733 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 734 735 setOperationAction(ISD::BSWAP, VT, Expand); 736 } 737 738 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 739 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 740 741 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 742 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 743 744 if (Subtarget->hasMVEIntegerOps()) 745 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 746 747 // Combine low-overhead loop intrinsics so that we can lower i1 types. 748 if (Subtarget->hasLOB()) { 749 setTargetDAGCombine(ISD::BRCOND); 750 setTargetDAGCombine(ISD::BR_CC); 751 } 752 753 if (Subtarget->hasNEON()) { 754 addDRTypeForNEON(MVT::v2f32); 755 addDRTypeForNEON(MVT::v8i8); 756 addDRTypeForNEON(MVT::v4i16); 757 addDRTypeForNEON(MVT::v2i32); 758 addDRTypeForNEON(MVT::v1i64); 759 760 addQRTypeForNEON(MVT::v4f32); 761 addQRTypeForNEON(MVT::v2f64); 762 addQRTypeForNEON(MVT::v16i8); 763 addQRTypeForNEON(MVT::v8i16); 764 addQRTypeForNEON(MVT::v4i32); 765 addQRTypeForNEON(MVT::v2i64); 766 767 if (Subtarget->hasFullFP16()) { 768 addQRTypeForNEON(MVT::v8f16); 769 addDRTypeForNEON(MVT::v4f16); 770 } 771 } 772 773 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 774 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 775 // none of Neon, MVE or VFP supports any arithmetic operations on it. 776 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 777 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 778 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 779 // FIXME: Code duplication: FDIV and FREM are expanded always, see 780 // ARMTargetLowering::addTypeForNEON method for details. 781 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 782 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 783 // FIXME: Create unittest. 784 // In another words, find a way when "copysign" appears in DAG with vector 785 // operands. 786 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 787 // FIXME: Code duplication: SETCC has custom operation action, see 788 // ARMTargetLowering::addTypeForNEON method for details. 789 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 790 // FIXME: Create unittest for FNEG and for FABS. 791 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 792 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 793 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 794 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 795 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 796 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 797 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 798 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 799 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 800 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 801 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 802 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 803 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 804 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 805 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 806 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 807 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 808 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 809 } 810 811 if (Subtarget->hasNEON()) { 812 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 813 // supported for v4f32. 814 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 815 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 816 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 817 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 818 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 819 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 820 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 821 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 822 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 823 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 824 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 825 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 826 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 827 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 828 829 // Mark v2f32 intrinsics. 830 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 831 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 832 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 833 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 834 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 835 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 836 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 837 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 838 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 839 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 840 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 841 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 842 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 843 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 844 845 // Neon does not support some operations on v1i64 and v2i64 types. 846 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 847 // Custom handling for some quad-vector types to detect VMULL. 848 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 849 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 850 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 851 // Custom handling for some vector types to avoid expensive expansions 852 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 853 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 854 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 855 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 856 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 857 // a destination type that is wider than the source, and nor does 858 // it have a FP_TO_[SU]INT instruction with a narrower destination than 859 // source. 860 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 861 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 862 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 863 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 864 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 865 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 866 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 867 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 868 869 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 870 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 871 872 // NEON does not have single instruction CTPOP for vectors with element 873 // types wider than 8-bits. However, custom lowering can leverage the 874 // v8i8/v16i8 vcnt instruction. 875 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 876 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 877 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 878 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 879 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 880 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 881 882 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 883 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 884 885 // NEON does not have single instruction CTTZ for vectors. 886 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 887 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 888 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 889 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 890 891 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 892 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 893 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 894 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 895 896 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 897 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 898 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 899 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 900 901 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 902 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 903 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 904 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 905 906 // NEON only has FMA instructions as of VFP4. 907 if (!Subtarget->hasVFP4Base()) { 908 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 909 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 910 } 911 912 setTargetDAGCombine(ISD::INTRINSIC_VOID); 913 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 914 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 915 setTargetDAGCombine(ISD::SHL); 916 setTargetDAGCombine(ISD::SRL); 917 setTargetDAGCombine(ISD::SRA); 918 setTargetDAGCombine(ISD::FP_TO_SINT); 919 setTargetDAGCombine(ISD::FP_TO_UINT); 920 setTargetDAGCombine(ISD::FDIV); 921 setTargetDAGCombine(ISD::LOAD); 922 923 // It is legal to extload from v4i8 to v4i16 or v4i32. 924 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 925 MVT::v2i32}) { 926 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 927 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 928 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 929 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 930 } 931 } 932 } 933 934 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 935 setTargetDAGCombine(ISD::BUILD_VECTOR); 936 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 937 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 938 setTargetDAGCombine(ISD::STORE); 939 setTargetDAGCombine(ISD::SIGN_EXTEND); 940 setTargetDAGCombine(ISD::ZERO_EXTEND); 941 setTargetDAGCombine(ISD::ANY_EXTEND); 942 } 943 944 if (!Subtarget->hasFP64()) { 945 // When targeting a floating-point unit with only single-precision 946 // operations, f64 is legal for the few double-precision instructions which 947 // are present However, no double-precision operations other than moves, 948 // loads and stores are provided by the hardware. 949 setOperationAction(ISD::FADD, MVT::f64, Expand); 950 setOperationAction(ISD::FSUB, MVT::f64, Expand); 951 setOperationAction(ISD::FMUL, MVT::f64, Expand); 952 setOperationAction(ISD::FMA, MVT::f64, Expand); 953 setOperationAction(ISD::FDIV, MVT::f64, Expand); 954 setOperationAction(ISD::FREM, MVT::f64, Expand); 955 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 956 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 957 setOperationAction(ISD::FNEG, MVT::f64, Expand); 958 setOperationAction(ISD::FABS, MVT::f64, Expand); 959 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 960 setOperationAction(ISD::FSIN, MVT::f64, Expand); 961 setOperationAction(ISD::FCOS, MVT::f64, Expand); 962 setOperationAction(ISD::FPOW, MVT::f64, Expand); 963 setOperationAction(ISD::FLOG, MVT::f64, Expand); 964 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 965 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 966 setOperationAction(ISD::FEXP, MVT::f64, Expand); 967 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 968 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 969 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 970 setOperationAction(ISD::FRINT, MVT::f64, Expand); 971 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 972 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 973 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 974 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 975 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 976 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 977 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 978 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 979 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 980 } 981 982 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) { 983 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 984 if (Subtarget->hasFullFP16()) 985 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 986 } 987 988 if (!Subtarget->hasFP16()) 989 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 990 991 if (!Subtarget->hasFP64()) 992 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 993 994 computeRegisterProperties(Subtarget->getRegisterInfo()); 995 996 // ARM does not have floating-point extending loads. 997 for (MVT VT : MVT::fp_valuetypes()) { 998 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 999 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 1000 } 1001 1002 // ... or truncating stores 1003 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 1004 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 1005 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 1006 1007 // ARM does not have i1 sign extending load. 1008 for (MVT VT : MVT::integer_valuetypes()) 1009 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 1010 1011 // ARM supports all 4 flavors of integer indexed load / store. 1012 if (!Subtarget->isThumb1Only()) { 1013 for (unsigned im = (unsigned)ISD::PRE_INC; 1014 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 1015 setIndexedLoadAction(im, MVT::i1, Legal); 1016 setIndexedLoadAction(im, MVT::i8, Legal); 1017 setIndexedLoadAction(im, MVT::i16, Legal); 1018 setIndexedLoadAction(im, MVT::i32, Legal); 1019 setIndexedStoreAction(im, MVT::i1, Legal); 1020 setIndexedStoreAction(im, MVT::i8, Legal); 1021 setIndexedStoreAction(im, MVT::i16, Legal); 1022 setIndexedStoreAction(im, MVT::i32, Legal); 1023 } 1024 } else { 1025 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 1026 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 1027 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 1028 } 1029 1030 setOperationAction(ISD::SADDO, MVT::i32, Custom); 1031 setOperationAction(ISD::UADDO, MVT::i32, Custom); 1032 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 1033 setOperationAction(ISD::USUBO, MVT::i32, Custom); 1034 1035 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 1036 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 1037 if (Subtarget->hasDSP()) { 1038 setOperationAction(ISD::SADDSAT, MVT::i8, Custom); 1039 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom); 1040 setOperationAction(ISD::SADDSAT, MVT::i16, Custom); 1041 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom); 1042 } 1043 if (Subtarget->hasBaseDSP()) { 1044 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 1045 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 1046 } 1047 1048 // i64 operation support. 1049 setOperationAction(ISD::MUL, MVT::i64, Expand); 1050 setOperationAction(ISD::MULHU, MVT::i32, Expand); 1051 if (Subtarget->isThumb1Only()) { 1052 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 1053 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 1054 } 1055 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 1056 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 1057 setOperationAction(ISD::MULHS, MVT::i32, Expand); 1058 1059 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 1060 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 1061 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 1062 setOperationAction(ISD::SRL, MVT::i64, Custom); 1063 setOperationAction(ISD::SRA, MVT::i64, Custom); 1064 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 1065 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 1066 1067 // MVE lowers 64 bit shifts to lsll and lsrl 1068 // assuming that ISD::SRL and SRA of i64 are already marked custom 1069 if (Subtarget->hasMVEIntegerOps()) 1070 setOperationAction(ISD::SHL, MVT::i64, Custom); 1071 1072 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 1073 if (Subtarget->isThumb1Only()) { 1074 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 1075 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 1076 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 1077 } 1078 1079 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 1080 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 1081 1082 // ARM does not have ROTL. 1083 setOperationAction(ISD::ROTL, MVT::i32, Expand); 1084 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 1085 setOperationAction(ISD::ROTL, VT, Expand); 1086 setOperationAction(ISD::ROTR, VT, Expand); 1087 } 1088 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1089 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1090 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1091 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1092 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1093 } 1094 1095 // @llvm.readcyclecounter requires the Performance Monitors extension. 1096 // Default to the 0 expansion on unsupported platforms. 1097 // FIXME: Technically there are older ARM CPUs that have 1098 // implementation-specific ways of obtaining this information. 1099 if (Subtarget->hasPerfMon()) 1100 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1101 1102 // Only ARMv6 has BSWAP. 1103 if (!Subtarget->hasV6Ops()) 1104 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1105 1106 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1107 : Subtarget->hasDivideInARMMode(); 1108 if (!hasDivide) { 1109 // These are expanded into libcalls if the cpu doesn't have HW divider. 1110 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1111 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1112 } 1113 1114 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1115 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1116 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1117 1118 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1119 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1120 } 1121 1122 setOperationAction(ISD::SREM, MVT::i32, Expand); 1123 setOperationAction(ISD::UREM, MVT::i32, Expand); 1124 1125 // Register based DivRem for AEABI (RTABI 4.2) 1126 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1127 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1128 Subtarget->isTargetWindows()) { 1129 setOperationAction(ISD::SREM, MVT::i64, Custom); 1130 setOperationAction(ISD::UREM, MVT::i64, Custom); 1131 HasStandaloneRem = false; 1132 1133 if (Subtarget->isTargetWindows()) { 1134 const struct { 1135 const RTLIB::Libcall Op; 1136 const char * const Name; 1137 const CallingConv::ID CC; 1138 } LibraryCalls[] = { 1139 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1140 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1141 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1142 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1143 1144 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1145 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1146 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1147 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1148 }; 1149 1150 for (const auto &LC : LibraryCalls) { 1151 setLibcallName(LC.Op, LC.Name); 1152 setLibcallCallingConv(LC.Op, LC.CC); 1153 } 1154 } else { 1155 const struct { 1156 const RTLIB::Libcall Op; 1157 const char * const Name; 1158 const CallingConv::ID CC; 1159 } LibraryCalls[] = { 1160 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1161 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1162 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1163 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1164 1165 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1166 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1167 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1168 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1169 }; 1170 1171 for (const auto &LC : LibraryCalls) { 1172 setLibcallName(LC.Op, LC.Name); 1173 setLibcallCallingConv(LC.Op, LC.CC); 1174 } 1175 } 1176 1177 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1178 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1179 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1180 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1181 } else { 1182 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1183 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1184 } 1185 1186 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 1187 // MSVCRT doesn't have powi; fall back to pow 1188 setLibcallName(RTLIB::POWI_F32, nullptr); 1189 setLibcallName(RTLIB::POWI_F64, nullptr); 1190 } 1191 1192 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1193 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1194 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1195 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1196 1197 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1198 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1199 1200 // Use the default implementation. 1201 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1202 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1203 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1204 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1205 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1206 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1207 1208 if (Subtarget->isTargetWindows()) 1209 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1210 else 1211 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1212 1213 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1214 // the default expansion. 1215 InsertFencesForAtomic = false; 1216 if (Subtarget->hasAnyDataBarrier() && 1217 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1218 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1219 // to ldrex/strex loops already. 1220 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1221 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1222 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1223 1224 // On v8, we have particularly efficient implementations of atomic fences 1225 // if they can be combined with nearby atomic loads and stores. 1226 if (!Subtarget->hasAcquireRelease() || 1227 getTargetMachine().getOptLevel() == 0) { 1228 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1229 InsertFencesForAtomic = true; 1230 } 1231 } else { 1232 // If there's anything we can use as a barrier, go through custom lowering 1233 // for ATOMIC_FENCE. 1234 // If target has DMB in thumb, Fences can be inserted. 1235 if (Subtarget->hasDataBarrier()) 1236 InsertFencesForAtomic = true; 1237 1238 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1239 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1240 1241 // Set them all for expansion, which will force libcalls. 1242 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1243 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1244 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1245 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1246 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1247 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1248 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1249 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1250 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1251 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1252 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1253 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1254 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1255 // Unordered/Monotonic case. 1256 if (!InsertFencesForAtomic) { 1257 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1258 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1259 } 1260 } 1261 1262 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1263 1264 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1265 if (!Subtarget->hasV6Ops()) { 1266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1267 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1268 } 1269 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1270 1271 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1272 !Subtarget->isThumb1Only()) { 1273 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1274 // iff target supports vfp2. 1275 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1276 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1277 } 1278 1279 // We want to custom lower some of our intrinsics. 1280 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1281 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1282 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1283 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1284 if (Subtarget->useSjLjEH()) 1285 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1286 1287 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1288 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1289 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1290 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1291 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1292 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1293 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1294 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1295 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1296 if (Subtarget->hasFullFP16()) { 1297 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1298 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1299 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1300 } 1301 1302 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1303 1304 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1305 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1306 if (Subtarget->hasFullFP16()) 1307 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1308 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1309 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1310 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1311 1312 // We don't support sin/cos/fmod/copysign/pow 1313 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1314 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1315 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1316 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1317 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1318 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1319 setOperationAction(ISD::FREM, MVT::f64, Expand); 1320 setOperationAction(ISD::FREM, MVT::f32, Expand); 1321 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1322 !Subtarget->isThumb1Only()) { 1323 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1324 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1325 } 1326 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1327 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1328 1329 if (!Subtarget->hasVFP4Base()) { 1330 setOperationAction(ISD::FMA, MVT::f64, Expand); 1331 setOperationAction(ISD::FMA, MVT::f32, Expand); 1332 } 1333 1334 // Various VFP goodness 1335 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1336 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1337 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1338 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1339 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1340 } 1341 1342 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1343 if (!Subtarget->hasFP16()) { 1344 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1345 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1346 } 1347 } 1348 1349 // Use __sincos_stret if available. 1350 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1351 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1352 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1353 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1354 } 1355 1356 // FP-ARMv8 implements a lot of rounding-like FP operations. 1357 if (Subtarget->hasFPARMv8Base()) { 1358 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1359 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1360 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1361 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1362 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1363 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1364 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1365 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1366 if (Subtarget->hasNEON()) { 1367 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1368 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1369 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1370 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1371 } 1372 1373 if (Subtarget->hasFP64()) { 1374 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1375 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1376 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1377 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1378 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1379 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1380 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1381 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1382 } 1383 } 1384 1385 // FP16 often need to be promoted to call lib functions 1386 if (Subtarget->hasFullFP16()) { 1387 setOperationAction(ISD::FREM, MVT::f16, Promote); 1388 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1389 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1390 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1391 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1392 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1393 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1394 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1395 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1396 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1397 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1398 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1399 1400 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1401 } 1402 1403 if (Subtarget->hasNEON()) { 1404 // vmin and vmax aren't available in a scalar form, so we use 1405 // a NEON instruction with an undef lane instead. 1406 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1407 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1408 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1409 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1410 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1411 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1412 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1413 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1414 1415 if (Subtarget->hasFullFP16()) { 1416 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1417 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1418 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1419 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1420 1421 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1422 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1423 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1424 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1425 } 1426 } 1427 1428 // We have target-specific dag combine patterns for the following nodes: 1429 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1430 setTargetDAGCombine(ISD::ADD); 1431 setTargetDAGCombine(ISD::SUB); 1432 setTargetDAGCombine(ISD::MUL); 1433 setTargetDAGCombine(ISD::AND); 1434 setTargetDAGCombine(ISD::OR); 1435 setTargetDAGCombine(ISD::XOR); 1436 1437 if (Subtarget->hasV6Ops()) 1438 setTargetDAGCombine(ISD::SRL); 1439 if (Subtarget->isThumb1Only()) 1440 setTargetDAGCombine(ISD::SHL); 1441 1442 setStackPointerRegisterToSaveRestore(ARM::SP); 1443 1444 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1445 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1446 setSchedulingPreference(Sched::RegPressure); 1447 else 1448 setSchedulingPreference(Sched::Hybrid); 1449 1450 //// temporary - rewrite interface to use type 1451 MaxStoresPerMemset = 8; 1452 MaxStoresPerMemsetOptSize = 4; 1453 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1454 MaxStoresPerMemcpyOptSize = 2; 1455 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1456 MaxStoresPerMemmoveOptSize = 2; 1457 1458 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1459 // are at least 4 bytes aligned. 1460 setMinStackArgumentAlignment(Align(4)); 1461 1462 // Prefer likely predicted branches to selects on out-of-order cores. 1463 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1464 1465 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment())); 1466 1467 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4)); 1468 1469 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1470 setTargetDAGCombine(ISD::ABS); 1471 } 1472 1473 bool ARMTargetLowering::useSoftFloat() const { 1474 return Subtarget->useSoftFloat(); 1475 } 1476 1477 // FIXME: It might make sense to define the representative register class as the 1478 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1479 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1480 // SPR's representative would be DPR_VFP2. This should work well if register 1481 // pressure tracking were modified such that a register use would increment the 1482 // pressure of the register class's representative and all of it's super 1483 // classes' representatives transitively. We have not implemented this because 1484 // of the difficulty prior to coalescing of modeling operand register classes 1485 // due to the common occurrence of cross class copies and subregister insertions 1486 // and extractions. 1487 std::pair<const TargetRegisterClass *, uint8_t> 1488 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1489 MVT VT) const { 1490 const TargetRegisterClass *RRC = nullptr; 1491 uint8_t Cost = 1; 1492 switch (VT.SimpleTy) { 1493 default: 1494 return TargetLowering::findRepresentativeClass(TRI, VT); 1495 // Use DPR as representative register class for all floating point 1496 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1497 // the cost is 1 for both f32 and f64. 1498 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1499 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1500 RRC = &ARM::DPRRegClass; 1501 // When NEON is used for SP, only half of the register file is available 1502 // because operations that define both SP and DP results will be constrained 1503 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1504 // coalescing by double-counting the SP regs. See the FIXME above. 1505 if (Subtarget->useNEONForSinglePrecisionFP()) 1506 Cost = 2; 1507 break; 1508 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1509 case MVT::v4f32: case MVT::v2f64: 1510 RRC = &ARM::DPRRegClass; 1511 Cost = 2; 1512 break; 1513 case MVT::v4i64: 1514 RRC = &ARM::DPRRegClass; 1515 Cost = 4; 1516 break; 1517 case MVT::v8i64: 1518 RRC = &ARM::DPRRegClass; 1519 Cost = 8; 1520 break; 1521 } 1522 return std::make_pair(RRC, Cost); 1523 } 1524 1525 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1526 switch ((ARMISD::NodeType)Opcode) { 1527 case ARMISD::FIRST_NUMBER: break; 1528 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1529 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1530 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1531 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1532 case ARMISD::CALL: return "ARMISD::CALL"; 1533 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1534 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1535 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1536 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1537 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1538 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1539 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1540 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1541 case ARMISD::CMP: return "ARMISD::CMP"; 1542 case ARMISD::CMN: return "ARMISD::CMN"; 1543 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1544 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1545 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1546 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1547 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1548 1549 case ARMISD::CMOV: return "ARMISD::CMOV"; 1550 case ARMISD::SUBS: return "ARMISD::SUBS"; 1551 1552 case ARMISD::SSAT: return "ARMISD::SSAT"; 1553 case ARMISD::USAT: return "ARMISD::USAT"; 1554 1555 case ARMISD::ASRL: return "ARMISD::ASRL"; 1556 case ARMISD::LSRL: return "ARMISD::LSRL"; 1557 case ARMISD::LSLL: return "ARMISD::LSLL"; 1558 1559 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1560 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1561 case ARMISD::RRX: return "ARMISD::RRX"; 1562 1563 case ARMISD::ADDC: return "ARMISD::ADDC"; 1564 case ARMISD::ADDE: return "ARMISD::ADDE"; 1565 case ARMISD::SUBC: return "ARMISD::SUBC"; 1566 case ARMISD::SUBE: return "ARMISD::SUBE"; 1567 case ARMISD::LSLS: return "ARMISD::LSLS"; 1568 1569 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1570 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1571 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1572 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1573 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1574 1575 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1576 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1577 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1578 1579 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1580 1581 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1582 1583 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1584 1585 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1586 1587 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1588 1589 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1590 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1591 1592 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST"; 1593 case ARMISD::VCMP: return "ARMISD::VCMP"; 1594 case ARMISD::VCMPZ: return "ARMISD::VCMPZ"; 1595 case ARMISD::VTST: return "ARMISD::VTST"; 1596 1597 case ARMISD::VSHLs: return "ARMISD::VSHLs"; 1598 case ARMISD::VSHLu: return "ARMISD::VSHLu"; 1599 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM"; 1600 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM"; 1601 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM"; 1602 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM"; 1603 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM"; 1604 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM"; 1605 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM"; 1606 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM"; 1607 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM"; 1608 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM"; 1609 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM"; 1610 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM"; 1611 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM"; 1612 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM"; 1613 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM"; 1614 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM"; 1615 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM"; 1616 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1617 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1618 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1619 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1620 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1621 case ARMISD::VDUP: return "ARMISD::VDUP"; 1622 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1623 case ARMISD::VEXT: return "ARMISD::VEXT"; 1624 case ARMISD::VREV64: return "ARMISD::VREV64"; 1625 case ARMISD::VREV32: return "ARMISD::VREV32"; 1626 case ARMISD::VREV16: return "ARMISD::VREV16"; 1627 case ARMISD::VZIP: return "ARMISD::VZIP"; 1628 case ARMISD::VUZP: return "ARMISD::VUZP"; 1629 case ARMISD::VTRN: return "ARMISD::VTRN"; 1630 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1631 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1632 case ARMISD::VMOVN: return "ARMISD::VMOVN"; 1633 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1634 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1635 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1636 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1637 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1638 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1639 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1640 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1641 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1642 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1643 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1644 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1645 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1646 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1647 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1648 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1649 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1650 case ARMISD::QADD16b: return "ARMISD::QADD16b"; 1651 case ARMISD::QSUB16b: return "ARMISD::QSUB16b"; 1652 case ARMISD::QADD8b: return "ARMISD::QADD8b"; 1653 case ARMISD::QSUB8b: return "ARMISD::QSUB8b"; 1654 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1655 case ARMISD::BFI: return "ARMISD::BFI"; 1656 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1657 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1658 case ARMISD::VBSL: return "ARMISD::VBSL"; 1659 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1660 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1661 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1662 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1663 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1664 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1665 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1666 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1667 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1668 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1669 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1670 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1671 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1672 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1673 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1674 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1675 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1676 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1677 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1678 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1679 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1680 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1681 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1682 case ARMISD::WLS: return "ARMISD::WLS"; 1683 case ARMISD::LE: return "ARMISD::LE"; 1684 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1685 case ARMISD::CSINV: return "ARMISD::CSINV"; 1686 case ARMISD::CSNEG: return "ARMISD::CSNEG"; 1687 case ARMISD::CSINC: return "ARMISD::CSINC"; 1688 } 1689 return nullptr; 1690 } 1691 1692 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1693 EVT VT) const { 1694 if (!VT.isVector()) 1695 return getPointerTy(DL); 1696 1697 // MVE has a predicate register. 1698 if (Subtarget->hasMVEIntegerOps() && 1699 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1700 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1701 return VT.changeVectorElementTypeToInteger(); 1702 } 1703 1704 /// getRegClassFor - Return the register class that should be used for the 1705 /// specified value type. 1706 const TargetRegisterClass * 1707 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1708 (void)isDivergent; 1709 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1710 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1711 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1712 // MVE Q registers. 1713 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1714 if (VT == MVT::v4i64) 1715 return &ARM::QQPRRegClass; 1716 if (VT == MVT::v8i64) 1717 return &ARM::QQQQPRRegClass; 1718 } 1719 return TargetLowering::getRegClassFor(VT); 1720 } 1721 1722 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1723 // source/dest is aligned and the copy size is large enough. We therefore want 1724 // to align such objects passed to memory intrinsics. 1725 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1726 unsigned &PrefAlign) const { 1727 if (!isa<MemIntrinsic>(CI)) 1728 return false; 1729 MinSize = 8; 1730 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1731 // cycle faster than 4-byte aligned LDM. 1732 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1733 return true; 1734 } 1735 1736 // Create a fast isel object. 1737 FastISel * 1738 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1739 const TargetLibraryInfo *libInfo) const { 1740 return ARM::createFastISel(funcInfo, libInfo); 1741 } 1742 1743 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1744 unsigned NumVals = N->getNumValues(); 1745 if (!NumVals) 1746 return Sched::RegPressure; 1747 1748 for (unsigned i = 0; i != NumVals; ++i) { 1749 EVT VT = N->getValueType(i); 1750 if (VT == MVT::Glue || VT == MVT::Other) 1751 continue; 1752 if (VT.isFloatingPoint() || VT.isVector()) 1753 return Sched::ILP; 1754 } 1755 1756 if (!N->isMachineOpcode()) 1757 return Sched::RegPressure; 1758 1759 // Load are scheduled for latency even if there instruction itinerary 1760 // is not available. 1761 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1762 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1763 1764 if (MCID.getNumDefs() == 0) 1765 return Sched::RegPressure; 1766 if (!Itins->isEmpty() && 1767 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1768 return Sched::ILP; 1769 1770 return Sched::RegPressure; 1771 } 1772 1773 //===----------------------------------------------------------------------===// 1774 // Lowering Code 1775 //===----------------------------------------------------------------------===// 1776 1777 static bool isSRL16(const SDValue &Op) { 1778 if (Op.getOpcode() != ISD::SRL) 1779 return false; 1780 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1781 return Const->getZExtValue() == 16; 1782 return false; 1783 } 1784 1785 static bool isSRA16(const SDValue &Op) { 1786 if (Op.getOpcode() != ISD::SRA) 1787 return false; 1788 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1789 return Const->getZExtValue() == 16; 1790 return false; 1791 } 1792 1793 static bool isSHL16(const SDValue &Op) { 1794 if (Op.getOpcode() != ISD::SHL) 1795 return false; 1796 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1797 return Const->getZExtValue() == 16; 1798 return false; 1799 } 1800 1801 // Check for a signed 16-bit value. We special case SRA because it makes it 1802 // more simple when also looking for SRAs that aren't sign extending a 1803 // smaller value. Without the check, we'd need to take extra care with 1804 // checking order for some operations. 1805 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1806 if (isSRA16(Op)) 1807 return isSHL16(Op.getOperand(0)); 1808 return DAG.ComputeNumSignBits(Op) == 17; 1809 } 1810 1811 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1812 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1813 switch (CC) { 1814 default: llvm_unreachable("Unknown condition code!"); 1815 case ISD::SETNE: return ARMCC::NE; 1816 case ISD::SETEQ: return ARMCC::EQ; 1817 case ISD::SETGT: return ARMCC::GT; 1818 case ISD::SETGE: return ARMCC::GE; 1819 case ISD::SETLT: return ARMCC::LT; 1820 case ISD::SETLE: return ARMCC::LE; 1821 case ISD::SETUGT: return ARMCC::HI; 1822 case ISD::SETUGE: return ARMCC::HS; 1823 case ISD::SETULT: return ARMCC::LO; 1824 case ISD::SETULE: return ARMCC::LS; 1825 } 1826 } 1827 1828 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1829 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1830 ARMCC::CondCodes &CondCode2) { 1831 CondCode2 = ARMCC::AL; 1832 switch (CC) { 1833 default: llvm_unreachable("Unknown FP condition!"); 1834 case ISD::SETEQ: 1835 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1836 case ISD::SETGT: 1837 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1838 case ISD::SETGE: 1839 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1840 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1841 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1842 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1843 case ISD::SETO: CondCode = ARMCC::VC; break; 1844 case ISD::SETUO: CondCode = ARMCC::VS; break; 1845 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1846 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1847 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1848 case ISD::SETLT: 1849 case ISD::SETULT: CondCode = ARMCC::LT; break; 1850 case ISD::SETLE: 1851 case ISD::SETULE: CondCode = ARMCC::LE; break; 1852 case ISD::SETNE: 1853 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1854 } 1855 } 1856 1857 //===----------------------------------------------------------------------===// 1858 // Calling Convention Implementation 1859 //===----------------------------------------------------------------------===// 1860 1861 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1862 /// account presence of floating point hardware and calling convention 1863 /// limitations, such as support for variadic functions. 1864 CallingConv::ID 1865 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1866 bool isVarArg) const { 1867 switch (CC) { 1868 default: 1869 report_fatal_error("Unsupported calling convention"); 1870 case CallingConv::ARM_AAPCS: 1871 case CallingConv::ARM_APCS: 1872 case CallingConv::GHC: 1873 case CallingConv::CFGuard_Check: 1874 return CC; 1875 case CallingConv::PreserveMost: 1876 return CallingConv::PreserveMost; 1877 case CallingConv::ARM_AAPCS_VFP: 1878 case CallingConv::Swift: 1879 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1880 case CallingConv::C: 1881 if (!Subtarget->isAAPCS_ABI()) 1882 return CallingConv::ARM_APCS; 1883 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1884 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1885 !isVarArg) 1886 return CallingConv::ARM_AAPCS_VFP; 1887 else 1888 return CallingConv::ARM_AAPCS; 1889 case CallingConv::Fast: 1890 case CallingConv::CXX_FAST_TLS: 1891 if (!Subtarget->isAAPCS_ABI()) { 1892 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 1893 return CallingConv::Fast; 1894 return CallingConv::ARM_APCS; 1895 } else if (Subtarget->hasVFP2Base() && 1896 !Subtarget->isThumb1Only() && !isVarArg) 1897 return CallingConv::ARM_AAPCS_VFP; 1898 else 1899 return CallingConv::ARM_AAPCS; 1900 } 1901 } 1902 1903 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1904 bool isVarArg) const { 1905 return CCAssignFnForNode(CC, false, isVarArg); 1906 } 1907 1908 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1909 bool isVarArg) const { 1910 return CCAssignFnForNode(CC, true, isVarArg); 1911 } 1912 1913 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1914 /// CallingConvention. 1915 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1916 bool Return, 1917 bool isVarArg) const { 1918 switch (getEffectiveCallingConv(CC, isVarArg)) { 1919 default: 1920 report_fatal_error("Unsupported calling convention"); 1921 case CallingConv::ARM_APCS: 1922 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1923 case CallingConv::ARM_AAPCS: 1924 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1925 case CallingConv::ARM_AAPCS_VFP: 1926 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1927 case CallingConv::Fast: 1928 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1929 case CallingConv::GHC: 1930 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1931 case CallingConv::PreserveMost: 1932 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1933 case CallingConv::CFGuard_Check: 1934 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check); 1935 } 1936 } 1937 1938 /// LowerCallResult - Lower the result values of a call into the 1939 /// appropriate copies out of appropriate physical registers. 1940 SDValue ARMTargetLowering::LowerCallResult( 1941 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1942 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1943 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1944 SDValue ThisVal) const { 1945 // Assign locations to each value returned by this call. 1946 SmallVector<CCValAssign, 16> RVLocs; 1947 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1948 *DAG.getContext()); 1949 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1950 1951 // Copy all of the result registers out of their specified physreg. 1952 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1953 CCValAssign VA = RVLocs[i]; 1954 1955 // Pass 'this' value directly from the argument to return value, to avoid 1956 // reg unit interference 1957 if (i == 0 && isThisReturn) { 1958 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1959 "unexpected return calling convention register assignment"); 1960 InVals.push_back(ThisVal); 1961 continue; 1962 } 1963 1964 SDValue Val; 1965 if (VA.needsCustom()) { 1966 // Handle f64 or half of a v2f64. 1967 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1968 InFlag); 1969 Chain = Lo.getValue(1); 1970 InFlag = Lo.getValue(2); 1971 VA = RVLocs[++i]; // skip ahead to next loc 1972 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1973 InFlag); 1974 Chain = Hi.getValue(1); 1975 InFlag = Hi.getValue(2); 1976 if (!Subtarget->isLittle()) 1977 std::swap (Lo, Hi); 1978 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1979 1980 if (VA.getLocVT() == MVT::v2f64) { 1981 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1982 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1983 DAG.getConstant(0, dl, MVT::i32)); 1984 1985 VA = RVLocs[++i]; // skip ahead to next loc 1986 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1987 Chain = Lo.getValue(1); 1988 InFlag = Lo.getValue(2); 1989 VA = RVLocs[++i]; // skip ahead to next loc 1990 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1991 Chain = Hi.getValue(1); 1992 InFlag = Hi.getValue(2); 1993 if (!Subtarget->isLittle()) 1994 std::swap (Lo, Hi); 1995 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1996 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1997 DAG.getConstant(1, dl, MVT::i32)); 1998 } 1999 } else { 2000 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 2001 InFlag); 2002 Chain = Val.getValue(1); 2003 InFlag = Val.getValue(2); 2004 } 2005 2006 switch (VA.getLocInfo()) { 2007 default: llvm_unreachable("Unknown loc info!"); 2008 case CCValAssign::Full: break; 2009 case CCValAssign::BCvt: 2010 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 2011 break; 2012 } 2013 2014 InVals.push_back(Val); 2015 } 2016 2017 return Chain; 2018 } 2019 2020 /// LowerMemOpCallTo - Store the argument to the stack. 2021 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 2022 SDValue Arg, const SDLoc &dl, 2023 SelectionDAG &DAG, 2024 const CCValAssign &VA, 2025 ISD::ArgFlagsTy Flags) const { 2026 unsigned LocMemOffset = VA.getLocMemOffset(); 2027 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2028 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 2029 StackPtr, PtrOff); 2030 return DAG.getStore( 2031 Chain, dl, Arg, PtrOff, 2032 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 2033 } 2034 2035 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 2036 SDValue Chain, SDValue &Arg, 2037 RegsToPassVector &RegsToPass, 2038 CCValAssign &VA, CCValAssign &NextVA, 2039 SDValue &StackPtr, 2040 SmallVectorImpl<SDValue> &MemOpChains, 2041 ISD::ArgFlagsTy Flags) const { 2042 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2043 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2044 unsigned id = Subtarget->isLittle() ? 0 : 1; 2045 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 2046 2047 if (NextVA.isRegLoc()) 2048 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 2049 else { 2050 assert(NextVA.isMemLoc()); 2051 if (!StackPtr.getNode()) 2052 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 2053 getPointerTy(DAG.getDataLayout())); 2054 2055 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 2056 dl, DAG, NextVA, 2057 Flags)); 2058 } 2059 } 2060 2061 /// LowerCall - Lowering a call into a callseq_start <- 2062 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 2063 /// nodes. 2064 SDValue 2065 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2066 SmallVectorImpl<SDValue> &InVals) const { 2067 SelectionDAG &DAG = CLI.DAG; 2068 SDLoc &dl = CLI.DL; 2069 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2070 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2071 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2072 SDValue Chain = CLI.Chain; 2073 SDValue Callee = CLI.Callee; 2074 bool &isTailCall = CLI.IsTailCall; 2075 CallingConv::ID CallConv = CLI.CallConv; 2076 bool doesNotRet = CLI.DoesNotReturn; 2077 bool isVarArg = CLI.IsVarArg; 2078 2079 MachineFunction &MF = DAG.getMachineFunction(); 2080 MachineFunction::CallSiteInfo CSInfo; 2081 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2082 bool isThisReturn = false; 2083 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 2084 bool PreferIndirect = false; 2085 2086 // Disable tail calls if they're not supported. 2087 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 2088 isTailCall = false; 2089 2090 if (isa<GlobalAddressSDNode>(Callee)) { 2091 // If we're optimizing for minimum size and the function is called three or 2092 // more times in this block, we can improve codesize by calling indirectly 2093 // as BLXr has a 16-bit encoding. 2094 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2095 if (CLI.CS) { 2096 auto *BB = CLI.CS.getParent(); 2097 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2098 count_if(GV->users(), [&BB](const User *U) { 2099 return isa<Instruction>(U) && 2100 cast<Instruction>(U)->getParent() == BB; 2101 }) > 2; 2102 } 2103 } 2104 if (isTailCall) { 2105 // Check if it's really possible to do a tail call. 2106 isTailCall = IsEligibleForTailCallOptimization( 2107 Callee, CallConv, isVarArg, isStructRet, 2108 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2109 PreferIndirect); 2110 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 2111 report_fatal_error("failed to perform tail call elimination on a call " 2112 "site marked musttail"); 2113 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2114 // detected sibcalls. 2115 if (isTailCall) 2116 ++NumTailCalls; 2117 } 2118 2119 // Analyze operands of the call, assigning locations to each operand. 2120 SmallVector<CCValAssign, 16> ArgLocs; 2121 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2122 *DAG.getContext()); 2123 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2124 2125 // Get a count of how many bytes are to be pushed on the stack. 2126 unsigned NumBytes = CCInfo.getNextStackOffset(); 2127 2128 if (isTailCall) { 2129 // For tail calls, memory operands are available in our caller's stack. 2130 NumBytes = 0; 2131 } else { 2132 // Adjust the stack pointer for the new arguments... 2133 // These operations are automatically eliminated by the prolog/epilog pass 2134 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2135 } 2136 2137 SDValue StackPtr = 2138 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2139 2140 RegsToPassVector RegsToPass; 2141 SmallVector<SDValue, 8> MemOpChains; 2142 2143 // Walk the register/memloc assignments, inserting copies/loads. In the case 2144 // of tail call optimization, arguments are handled later. 2145 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2146 i != e; 2147 ++i, ++realArgIdx) { 2148 CCValAssign &VA = ArgLocs[i]; 2149 SDValue Arg = OutVals[realArgIdx]; 2150 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2151 bool isByVal = Flags.isByVal(); 2152 2153 // Promote the value if needed. 2154 switch (VA.getLocInfo()) { 2155 default: llvm_unreachable("Unknown loc info!"); 2156 case CCValAssign::Full: break; 2157 case CCValAssign::SExt: 2158 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2159 break; 2160 case CCValAssign::ZExt: 2161 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2162 break; 2163 case CCValAssign::AExt: 2164 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2165 break; 2166 case CCValAssign::BCvt: 2167 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2168 break; 2169 } 2170 2171 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2172 if (VA.needsCustom()) { 2173 if (VA.getLocVT() == MVT::v2f64) { 2174 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2175 DAG.getConstant(0, dl, MVT::i32)); 2176 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2177 DAG.getConstant(1, dl, MVT::i32)); 2178 2179 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 2180 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2181 2182 VA = ArgLocs[++i]; // skip ahead to next loc 2183 if (VA.isRegLoc()) { 2184 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 2185 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2186 } else { 2187 assert(VA.isMemLoc()); 2188 2189 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 2190 dl, DAG, VA, Flags)); 2191 } 2192 } else { 2193 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2194 StackPtr, MemOpChains, Flags); 2195 } 2196 } else if (VA.isRegLoc()) { 2197 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2198 Outs[0].VT == MVT::i32) { 2199 assert(VA.getLocVT() == MVT::i32 && 2200 "unexpected calling convention register assignment"); 2201 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2202 "unexpected use of 'returned'"); 2203 isThisReturn = true; 2204 } 2205 const TargetOptions &Options = DAG.getTarget().Options; 2206 if (Options.EnableDebugEntryValues) 2207 CSInfo.emplace_back(VA.getLocReg(), i); 2208 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2209 } else if (isByVal) { 2210 assert(VA.isMemLoc()); 2211 unsigned offset = 0; 2212 2213 // True if this byval aggregate will be split between registers 2214 // and memory. 2215 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2216 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2217 2218 if (CurByValIdx < ByValArgsCount) { 2219 2220 unsigned RegBegin, RegEnd; 2221 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2222 2223 EVT PtrVT = 2224 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2225 unsigned int i, j; 2226 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2227 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2228 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2229 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 2230 MachinePointerInfo(), 2231 DAG.InferPtrAlignment(AddArg)); 2232 MemOpChains.push_back(Load.getValue(1)); 2233 RegsToPass.push_back(std::make_pair(j, Load)); 2234 } 2235 2236 // If parameter size outsides register area, "offset" value 2237 // helps us to calculate stack slot for remained part properly. 2238 offset = RegEnd - RegBegin; 2239 2240 CCInfo.nextInRegsParam(); 2241 } 2242 2243 if (Flags.getByValSize() > 4*offset) { 2244 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2245 unsigned LocMemOffset = VA.getLocMemOffset(); 2246 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2247 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2248 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2249 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2250 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2251 MVT::i32); 2252 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 2253 MVT::i32); 2254 2255 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2256 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2257 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2258 Ops)); 2259 } 2260 } else if (!isTailCall) { 2261 assert(VA.isMemLoc()); 2262 2263 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2264 dl, DAG, VA, Flags)); 2265 } 2266 } 2267 2268 if (!MemOpChains.empty()) 2269 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2270 2271 // Build a sequence of copy-to-reg nodes chained together with token chain 2272 // and flag operands which copy the outgoing args into the appropriate regs. 2273 SDValue InFlag; 2274 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2275 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2276 RegsToPass[i].second, InFlag); 2277 InFlag = Chain.getValue(1); 2278 } 2279 2280 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2281 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2282 // node so that legalize doesn't hack it. 2283 bool isDirect = false; 2284 2285 const TargetMachine &TM = getTargetMachine(); 2286 const Module *Mod = MF.getFunction().getParent(); 2287 const GlobalValue *GV = nullptr; 2288 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2289 GV = G->getGlobal(); 2290 bool isStub = 2291 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2292 2293 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2294 bool isLocalARMFunc = false; 2295 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2296 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2297 2298 if (Subtarget->genLongCalls()) { 2299 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2300 "long-calls codegen is not position independent!"); 2301 // Handle a global address or an external symbol. If it's not one of 2302 // those, the target's already in a register, so we don't need to do 2303 // anything extra. 2304 if (isa<GlobalAddressSDNode>(Callee)) { 2305 // Create a constant pool entry for the callee address 2306 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2307 ARMConstantPoolValue *CPV = 2308 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2309 2310 // Get the address of the callee into a register 2311 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2312 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2313 Callee = DAG.getLoad( 2314 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2315 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2316 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2317 const char *Sym = S->getSymbol(); 2318 2319 // Create a constant pool entry for the callee address 2320 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2321 ARMConstantPoolValue *CPV = 2322 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2323 ARMPCLabelIndex, 0); 2324 // Get the address of the callee into a register 2325 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2326 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2327 Callee = DAG.getLoad( 2328 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2329 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2330 } 2331 } else if (isa<GlobalAddressSDNode>(Callee)) { 2332 if (!PreferIndirect) { 2333 isDirect = true; 2334 bool isDef = GV->isStrongDefinitionForLinker(); 2335 2336 // ARM call to a local ARM function is predicable. 2337 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2338 // tBX takes a register source operand. 2339 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2340 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2341 Callee = DAG.getNode( 2342 ARMISD::WrapperPIC, dl, PtrVt, 2343 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2344 Callee = DAG.getLoad( 2345 PtrVt, dl, DAG.getEntryNode(), Callee, 2346 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2347 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2348 MachineMemOperand::MOInvariant); 2349 } else if (Subtarget->isTargetCOFF()) { 2350 assert(Subtarget->isTargetWindows() && 2351 "Windows is the only supported COFF target"); 2352 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2353 ? ARMII::MO_DLLIMPORT 2354 : ARMII::MO_NO_FLAG; 2355 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2356 TargetFlags); 2357 if (GV->hasDLLImportStorageClass()) 2358 Callee = 2359 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2360 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2361 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2362 } else { 2363 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2364 } 2365 } 2366 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2367 isDirect = true; 2368 // tBX takes a register source operand. 2369 const char *Sym = S->getSymbol(); 2370 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2371 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2372 ARMConstantPoolValue *CPV = 2373 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2374 ARMPCLabelIndex, 4); 2375 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2376 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2377 Callee = DAG.getLoad( 2378 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2379 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2380 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2381 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2382 } else { 2383 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2384 } 2385 } 2386 2387 // FIXME: handle tail calls differently. 2388 unsigned CallOpc; 2389 if (Subtarget->isThumb()) { 2390 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2391 CallOpc = ARMISD::CALL_NOLINK; 2392 else 2393 CallOpc = ARMISD::CALL; 2394 } else { 2395 if (!isDirect && !Subtarget->hasV5TOps()) 2396 CallOpc = ARMISD::CALL_NOLINK; 2397 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2398 // Emit regular call when code size is the priority 2399 !Subtarget->hasMinSize()) 2400 // "mov lr, pc; b _foo" to avoid confusing the RSP 2401 CallOpc = ARMISD::CALL_NOLINK; 2402 else 2403 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2404 } 2405 2406 std::vector<SDValue> Ops; 2407 Ops.push_back(Chain); 2408 Ops.push_back(Callee); 2409 2410 // Add argument registers to the end of the list so that they are known live 2411 // into the call. 2412 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2413 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2414 RegsToPass[i].second.getValueType())); 2415 2416 // Add a register mask operand representing the call-preserved registers. 2417 if (!isTailCall) { 2418 const uint32_t *Mask; 2419 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2420 if (isThisReturn) { 2421 // For 'this' returns, use the R0-preserving mask if applicable 2422 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2423 if (!Mask) { 2424 // Set isThisReturn to false if the calling convention is not one that 2425 // allows 'returned' to be modeled in this way, so LowerCallResult does 2426 // not try to pass 'this' straight through 2427 isThisReturn = false; 2428 Mask = ARI->getCallPreservedMask(MF, CallConv); 2429 } 2430 } else 2431 Mask = ARI->getCallPreservedMask(MF, CallConv); 2432 2433 assert(Mask && "Missing call preserved mask for calling convention"); 2434 Ops.push_back(DAG.getRegisterMask(Mask)); 2435 } 2436 2437 if (InFlag.getNode()) 2438 Ops.push_back(InFlag); 2439 2440 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2441 if (isTailCall) { 2442 MF.getFrameInfo().setHasTailCall(); 2443 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2444 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 2445 return Ret; 2446 } 2447 2448 // Returns a chain and a flag for retval copy to use. 2449 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2450 InFlag = Chain.getValue(1); 2451 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 2452 2453 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2454 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2455 if (!Ins.empty()) 2456 InFlag = Chain.getValue(1); 2457 2458 // Handle result values, copying them out of physregs into vregs that we 2459 // return. 2460 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2461 InVals, isThisReturn, 2462 isThisReturn ? OutVals[0] : SDValue()); 2463 } 2464 2465 /// HandleByVal - Every parameter *after* a byval parameter is passed 2466 /// on the stack. Remember the next parameter register to allocate, 2467 /// and then confiscate the rest of the parameter registers to insure 2468 /// this. 2469 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2470 unsigned Align) const { 2471 // Byval (as with any stack) slots are always at least 4 byte aligned. 2472 Align = std::max(Align, 4U); 2473 2474 unsigned Reg = State->AllocateReg(GPRArgRegs); 2475 if (!Reg) 2476 return; 2477 2478 unsigned AlignInRegs = Align / 4; 2479 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2480 for (unsigned i = 0; i < Waste; ++i) 2481 Reg = State->AllocateReg(GPRArgRegs); 2482 2483 if (!Reg) 2484 return; 2485 2486 unsigned Excess = 4 * (ARM::R4 - Reg); 2487 2488 // Special case when NSAA != SP and parameter size greater than size of 2489 // all remained GPR regs. In that case we can't split parameter, we must 2490 // send it to stack. We also must set NCRN to R4, so waste all 2491 // remained registers. 2492 const unsigned NSAAOffset = State->getNextStackOffset(); 2493 if (NSAAOffset != 0 && Size > Excess) { 2494 while (State->AllocateReg(GPRArgRegs)) 2495 ; 2496 return; 2497 } 2498 2499 // First register for byval parameter is the first register that wasn't 2500 // allocated before this method call, so it would be "reg". 2501 // If parameter is small enough to be saved in range [reg, r4), then 2502 // the end (first after last) register would be reg + param-size-in-regs, 2503 // else parameter would be splitted between registers and stack, 2504 // end register would be r4 in this case. 2505 unsigned ByValRegBegin = Reg; 2506 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2507 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2508 // Note, first register is allocated in the beginning of function already, 2509 // allocate remained amount of registers we need. 2510 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2511 State->AllocateReg(GPRArgRegs); 2512 // A byval parameter that is split between registers and memory needs its 2513 // size truncated here. 2514 // In the case where the entire structure fits in registers, we set the 2515 // size in memory to zero. 2516 Size = std::max<int>(Size - Excess, 0); 2517 } 2518 2519 /// MatchingStackOffset - Return true if the given stack call argument is 2520 /// already available in the same position (relatively) of the caller's 2521 /// incoming argument stack. 2522 static 2523 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2524 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2525 const TargetInstrInfo *TII) { 2526 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2527 int FI = std::numeric_limits<int>::max(); 2528 if (Arg.getOpcode() == ISD::CopyFromReg) { 2529 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2530 if (!Register::isVirtualRegister(VR)) 2531 return false; 2532 MachineInstr *Def = MRI->getVRegDef(VR); 2533 if (!Def) 2534 return false; 2535 if (!Flags.isByVal()) { 2536 if (!TII->isLoadFromStackSlot(*Def, FI)) 2537 return false; 2538 } else { 2539 return false; 2540 } 2541 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2542 if (Flags.isByVal()) 2543 // ByVal argument is passed in as a pointer but it's now being 2544 // dereferenced. e.g. 2545 // define @foo(%struct.X* %A) { 2546 // tail call @bar(%struct.X* byval %A) 2547 // } 2548 return false; 2549 SDValue Ptr = Ld->getBasePtr(); 2550 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2551 if (!FINode) 2552 return false; 2553 FI = FINode->getIndex(); 2554 } else 2555 return false; 2556 2557 assert(FI != std::numeric_limits<int>::max()); 2558 if (!MFI.isFixedObjectIndex(FI)) 2559 return false; 2560 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2561 } 2562 2563 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2564 /// for tail call optimization. Targets which want to do tail call 2565 /// optimization should implement this function. 2566 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2567 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2568 bool isCalleeStructRet, bool isCallerStructRet, 2569 const SmallVectorImpl<ISD::OutputArg> &Outs, 2570 const SmallVectorImpl<SDValue> &OutVals, 2571 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2572 const bool isIndirect) const { 2573 MachineFunction &MF = DAG.getMachineFunction(); 2574 const Function &CallerF = MF.getFunction(); 2575 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2576 2577 assert(Subtarget->supportsTailCall()); 2578 2579 // Indirect tail calls cannot be optimized for Thumb1 if the args 2580 // to the call take up r0-r3. The reason is that there are no legal registers 2581 // left to hold the pointer to the function to be called. 2582 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2583 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2584 return false; 2585 2586 // Look for obvious safe cases to perform tail call optimization that do not 2587 // require ABI changes. This is what gcc calls sibcall. 2588 2589 // Exception-handling functions need a special set of instructions to indicate 2590 // a return to the hardware. Tail-calling another function would probably 2591 // break this. 2592 if (CallerF.hasFnAttribute("interrupt")) 2593 return false; 2594 2595 // Also avoid sibcall optimization if either caller or callee uses struct 2596 // return semantics. 2597 if (isCalleeStructRet || isCallerStructRet) 2598 return false; 2599 2600 // Externally-defined functions with weak linkage should not be 2601 // tail-called on ARM when the OS does not support dynamic 2602 // pre-emption of symbols, as the AAELF spec requires normal calls 2603 // to undefined weak functions to be replaced with a NOP or jump to the 2604 // next instruction. The behaviour of branch instructions in this 2605 // situation (as used for tail calls) is implementation-defined, so we 2606 // cannot rely on the linker replacing the tail call with a return. 2607 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2608 const GlobalValue *GV = G->getGlobal(); 2609 const Triple &TT = getTargetMachine().getTargetTriple(); 2610 if (GV->hasExternalWeakLinkage() && 2611 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2612 return false; 2613 } 2614 2615 // Check that the call results are passed in the same way. 2616 LLVMContext &C = *DAG.getContext(); 2617 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2618 CCAssignFnForReturn(CalleeCC, isVarArg), 2619 CCAssignFnForReturn(CallerCC, isVarArg))) 2620 return false; 2621 // The callee has to preserve all registers the caller needs to preserve. 2622 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2623 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2624 if (CalleeCC != CallerCC) { 2625 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2626 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2627 return false; 2628 } 2629 2630 // If Caller's vararg or byval argument has been split between registers and 2631 // stack, do not perform tail call, since part of the argument is in caller's 2632 // local frame. 2633 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2634 if (AFI_Caller->getArgRegsSaveSize()) 2635 return false; 2636 2637 // If the callee takes no arguments then go on to check the results of the 2638 // call. 2639 if (!Outs.empty()) { 2640 // Check if stack adjustment is needed. For now, do not do this if any 2641 // argument is passed on the stack. 2642 SmallVector<CCValAssign, 16> ArgLocs; 2643 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2644 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2645 if (CCInfo.getNextStackOffset()) { 2646 // Check if the arguments are already laid out in the right way as 2647 // the caller's fixed stack objects. 2648 MachineFrameInfo &MFI = MF.getFrameInfo(); 2649 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2650 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2651 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2652 i != e; 2653 ++i, ++realArgIdx) { 2654 CCValAssign &VA = ArgLocs[i]; 2655 EVT RegVT = VA.getLocVT(); 2656 SDValue Arg = OutVals[realArgIdx]; 2657 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2658 if (VA.getLocInfo() == CCValAssign::Indirect) 2659 return false; 2660 if (VA.needsCustom()) { 2661 // f64 and vector types are split into multiple registers or 2662 // register/stack-slot combinations. The types will not match 2663 // the registers; give up on memory f64 refs until we figure 2664 // out what to do about this. 2665 if (!VA.isRegLoc()) 2666 return false; 2667 if (!ArgLocs[++i].isRegLoc()) 2668 return false; 2669 if (RegVT == MVT::v2f64) { 2670 if (!ArgLocs[++i].isRegLoc()) 2671 return false; 2672 if (!ArgLocs[++i].isRegLoc()) 2673 return false; 2674 } 2675 } else if (!VA.isRegLoc()) { 2676 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2677 MFI, MRI, TII)) 2678 return false; 2679 } 2680 } 2681 } 2682 2683 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2684 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2685 return false; 2686 } 2687 2688 return true; 2689 } 2690 2691 bool 2692 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2693 MachineFunction &MF, bool isVarArg, 2694 const SmallVectorImpl<ISD::OutputArg> &Outs, 2695 LLVMContext &Context) const { 2696 SmallVector<CCValAssign, 16> RVLocs; 2697 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2698 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2699 } 2700 2701 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2702 const SDLoc &DL, SelectionDAG &DAG) { 2703 const MachineFunction &MF = DAG.getMachineFunction(); 2704 const Function &F = MF.getFunction(); 2705 2706 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2707 2708 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2709 // version of the "preferred return address". These offsets affect the return 2710 // instruction if this is a return from PL1 without hypervisor extensions. 2711 // IRQ/FIQ: +4 "subs pc, lr, #4" 2712 // SWI: 0 "subs pc, lr, #0" 2713 // ABORT: +4 "subs pc, lr, #4" 2714 // UNDEF: +4/+2 "subs pc, lr, #0" 2715 // UNDEF varies depending on where the exception came from ARM or Thumb 2716 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2717 2718 int64_t LROffset; 2719 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2720 IntKind == "ABORT") 2721 LROffset = 4; 2722 else if (IntKind == "SWI" || IntKind == "UNDEF") 2723 LROffset = 0; 2724 else 2725 report_fatal_error("Unsupported interrupt attribute. If present, value " 2726 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2727 2728 RetOps.insert(RetOps.begin() + 1, 2729 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2730 2731 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2732 } 2733 2734 SDValue 2735 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2736 bool isVarArg, 2737 const SmallVectorImpl<ISD::OutputArg> &Outs, 2738 const SmallVectorImpl<SDValue> &OutVals, 2739 const SDLoc &dl, SelectionDAG &DAG) const { 2740 // CCValAssign - represent the assignment of the return value to a location. 2741 SmallVector<CCValAssign, 16> RVLocs; 2742 2743 // CCState - Info about the registers and stack slots. 2744 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2745 *DAG.getContext()); 2746 2747 // Analyze outgoing return values. 2748 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2749 2750 SDValue Flag; 2751 SmallVector<SDValue, 4> RetOps; 2752 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2753 bool isLittleEndian = Subtarget->isLittle(); 2754 2755 MachineFunction &MF = DAG.getMachineFunction(); 2756 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2757 AFI->setReturnRegsCount(RVLocs.size()); 2758 2759 // Copy the result values into the output registers. 2760 for (unsigned i = 0, realRVLocIdx = 0; 2761 i != RVLocs.size(); 2762 ++i, ++realRVLocIdx) { 2763 CCValAssign &VA = RVLocs[i]; 2764 assert(VA.isRegLoc() && "Can only return in registers!"); 2765 2766 SDValue Arg = OutVals[realRVLocIdx]; 2767 bool ReturnF16 = false; 2768 2769 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2770 // Half-precision return values can be returned like this: 2771 // 2772 // t11 f16 = fadd ... 2773 // t12: i16 = bitcast t11 2774 // t13: i32 = zero_extend t12 2775 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2776 // 2777 // to avoid code generation for bitcasts, we simply set Arg to the node 2778 // that produces the f16 value, t11 in this case. 2779 // 2780 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2781 SDValue ZE = Arg.getOperand(0); 2782 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2783 SDValue BC = ZE.getOperand(0); 2784 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2785 Arg = BC.getOperand(0); 2786 ReturnF16 = true; 2787 } 2788 } 2789 } 2790 } 2791 2792 switch (VA.getLocInfo()) { 2793 default: llvm_unreachable("Unknown loc info!"); 2794 case CCValAssign::Full: break; 2795 case CCValAssign::BCvt: 2796 if (!ReturnF16) 2797 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2798 break; 2799 } 2800 2801 if (VA.needsCustom()) { 2802 if (VA.getLocVT() == MVT::v2f64) { 2803 // Extract the first half and return it in two registers. 2804 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2805 DAG.getConstant(0, dl, MVT::i32)); 2806 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2807 DAG.getVTList(MVT::i32, MVT::i32), Half); 2808 2809 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2810 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2811 Flag); 2812 Flag = Chain.getValue(1); 2813 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2814 VA = RVLocs[++i]; // skip ahead to next loc 2815 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2816 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2817 Flag); 2818 Flag = Chain.getValue(1); 2819 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2820 VA = RVLocs[++i]; // skip ahead to next loc 2821 2822 // Extract the 2nd half and fall through to handle it as an f64 value. 2823 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2824 DAG.getConstant(1, dl, MVT::i32)); 2825 } 2826 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2827 // available. 2828 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2829 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2830 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2831 fmrrd.getValue(isLittleEndian ? 0 : 1), 2832 Flag); 2833 Flag = Chain.getValue(1); 2834 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2835 VA = RVLocs[++i]; // skip ahead to next loc 2836 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2837 fmrrd.getValue(isLittleEndian ? 1 : 0), 2838 Flag); 2839 } else 2840 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2841 2842 // Guarantee that all emitted copies are 2843 // stuck together, avoiding something bad. 2844 Flag = Chain.getValue(1); 2845 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2846 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2847 } 2848 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2849 const MCPhysReg *I = 2850 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2851 if (I) { 2852 for (; *I; ++I) { 2853 if (ARM::GPRRegClass.contains(*I)) 2854 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2855 else if (ARM::DPRRegClass.contains(*I)) 2856 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2857 else 2858 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2859 } 2860 } 2861 2862 // Update chain and glue. 2863 RetOps[0] = Chain; 2864 if (Flag.getNode()) 2865 RetOps.push_back(Flag); 2866 2867 // CPUs which aren't M-class use a special sequence to return from 2868 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2869 // though we use "subs pc, lr, #N"). 2870 // 2871 // M-class CPUs actually use a normal return sequence with a special 2872 // (hardware-provided) value in LR, so the normal code path works. 2873 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2874 !Subtarget->isMClass()) { 2875 if (Subtarget->isThumb1Only()) 2876 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2877 return LowerInterruptReturn(RetOps, dl, DAG); 2878 } 2879 2880 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2881 } 2882 2883 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2884 if (N->getNumValues() != 1) 2885 return false; 2886 if (!N->hasNUsesOfValue(1, 0)) 2887 return false; 2888 2889 SDValue TCChain = Chain; 2890 SDNode *Copy = *N->use_begin(); 2891 if (Copy->getOpcode() == ISD::CopyToReg) { 2892 // If the copy has a glue operand, we conservatively assume it isn't safe to 2893 // perform a tail call. 2894 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2895 return false; 2896 TCChain = Copy->getOperand(0); 2897 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2898 SDNode *VMov = Copy; 2899 // f64 returned in a pair of GPRs. 2900 SmallPtrSet<SDNode*, 2> Copies; 2901 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2902 UI != UE; ++UI) { 2903 if (UI->getOpcode() != ISD::CopyToReg) 2904 return false; 2905 Copies.insert(*UI); 2906 } 2907 if (Copies.size() > 2) 2908 return false; 2909 2910 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2911 UI != UE; ++UI) { 2912 SDValue UseChain = UI->getOperand(0); 2913 if (Copies.count(UseChain.getNode())) 2914 // Second CopyToReg 2915 Copy = *UI; 2916 else { 2917 // We are at the top of this chain. 2918 // If the copy has a glue operand, we conservatively assume it 2919 // isn't safe to perform a tail call. 2920 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2921 return false; 2922 // First CopyToReg 2923 TCChain = UseChain; 2924 } 2925 } 2926 } else if (Copy->getOpcode() == ISD::BITCAST) { 2927 // f32 returned in a single GPR. 2928 if (!Copy->hasOneUse()) 2929 return false; 2930 Copy = *Copy->use_begin(); 2931 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2932 return false; 2933 // If the copy has a glue operand, we conservatively assume it isn't safe to 2934 // perform a tail call. 2935 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2936 return false; 2937 TCChain = Copy->getOperand(0); 2938 } else { 2939 return false; 2940 } 2941 2942 bool HasRet = false; 2943 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2944 UI != UE; ++UI) { 2945 if (UI->getOpcode() != ARMISD::RET_FLAG && 2946 UI->getOpcode() != ARMISD::INTRET_FLAG) 2947 return false; 2948 HasRet = true; 2949 } 2950 2951 if (!HasRet) 2952 return false; 2953 2954 Chain = TCChain; 2955 return true; 2956 } 2957 2958 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2959 if (!Subtarget->supportsTailCall()) 2960 return false; 2961 2962 auto Attr = 2963 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2964 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2965 return false; 2966 2967 return true; 2968 } 2969 2970 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2971 // and pass the lower and high parts through. 2972 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2973 SDLoc DL(Op); 2974 SDValue WriteValue = Op->getOperand(2); 2975 2976 // This function is only supposed to be called for i64 type argument. 2977 assert(WriteValue.getValueType() == MVT::i64 2978 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2979 2980 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2981 DAG.getConstant(0, DL, MVT::i32)); 2982 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2983 DAG.getConstant(1, DL, MVT::i32)); 2984 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2985 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2986 } 2987 2988 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2989 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2990 // one of the above mentioned nodes. It has to be wrapped because otherwise 2991 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2992 // be used to form addressing mode. These wrapped nodes will be selected 2993 // into MOVi. 2994 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2995 SelectionDAG &DAG) const { 2996 EVT PtrVT = Op.getValueType(); 2997 // FIXME there is no actual debug info here 2998 SDLoc dl(Op); 2999 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3000 SDValue Res; 3001 3002 // When generating execute-only code Constant Pools must be promoted to the 3003 // global data section. It's a bit ugly that we can't share them across basic 3004 // blocks, but this way we guarantee that execute-only behaves correct with 3005 // position-independent addressing modes. 3006 if (Subtarget->genExecuteOnly()) { 3007 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 3008 auto T = const_cast<Type*>(CP->getType()); 3009 auto C = const_cast<Constant*>(CP->getConstVal()); 3010 auto M = const_cast<Module*>(DAG.getMachineFunction(). 3011 getFunction().getParent()); 3012 auto GV = new GlobalVariable( 3013 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 3014 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 3015 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 3016 Twine(AFI->createPICLabelUId()) 3017 ); 3018 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 3019 dl, PtrVT); 3020 return LowerGlobalAddress(GA, DAG); 3021 } 3022 3023 if (CP->isMachineConstantPoolEntry()) 3024 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 3025 CP->getAlignment()); 3026 else 3027 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 3028 CP->getAlignment()); 3029 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 3030 } 3031 3032 unsigned ARMTargetLowering::getJumpTableEncoding() const { 3033 return MachineJumpTableInfo::EK_Inline; 3034 } 3035 3036 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 3037 SelectionDAG &DAG) const { 3038 MachineFunction &MF = DAG.getMachineFunction(); 3039 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3040 unsigned ARMPCLabelIndex = 0; 3041 SDLoc DL(Op); 3042 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3043 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 3044 SDValue CPAddr; 3045 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 3046 if (!IsPositionIndependent) { 3047 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 3048 } else { 3049 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3050 ARMPCLabelIndex = AFI->createPICLabelUId(); 3051 ARMConstantPoolValue *CPV = 3052 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 3053 ARMCP::CPBlockAddress, PCAdj); 3054 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3055 } 3056 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 3057 SDValue Result = DAG.getLoad( 3058 PtrVT, DL, DAG.getEntryNode(), CPAddr, 3059 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3060 if (!IsPositionIndependent) 3061 return Result; 3062 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 3063 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 3064 } 3065 3066 /// Convert a TLS address reference into the correct sequence of loads 3067 /// and calls to compute the variable's address for Darwin, and return an 3068 /// SDValue containing the final node. 3069 3070 /// Darwin only has one TLS scheme which must be capable of dealing with the 3071 /// fully general situation, in the worst case. This means: 3072 /// + "extern __thread" declaration. 3073 /// + Defined in a possibly unknown dynamic library. 3074 /// 3075 /// The general system is that each __thread variable has a [3 x i32] descriptor 3076 /// which contains information used by the runtime to calculate the address. The 3077 /// only part of this the compiler needs to know about is the first word, which 3078 /// contains a function pointer that must be called with the address of the 3079 /// entire descriptor in "r0". 3080 /// 3081 /// Since this descriptor may be in a different unit, in general access must 3082 /// proceed along the usual ARM rules. A common sequence to produce is: 3083 /// 3084 /// movw rT1, :lower16:_var$non_lazy_ptr 3085 /// movt rT1, :upper16:_var$non_lazy_ptr 3086 /// ldr r0, [rT1] 3087 /// ldr rT2, [r0] 3088 /// blx rT2 3089 /// [...address now in r0...] 3090 SDValue 3091 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3092 SelectionDAG &DAG) const { 3093 assert(Subtarget->isTargetDarwin() && 3094 "This function expects a Darwin target"); 3095 SDLoc DL(Op); 3096 3097 // First step is to get the address of the actua global symbol. This is where 3098 // the TLS descriptor lives. 3099 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3100 3101 // The first entry in the descriptor is a function pointer that we must call 3102 // to obtain the address of the variable. 3103 SDValue Chain = DAG.getEntryNode(); 3104 SDValue FuncTLVGet = DAG.getLoad( 3105 MVT::i32, DL, Chain, DescAddr, 3106 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3107 /* Alignment = */ 4, 3108 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3109 MachineMemOperand::MOInvariant); 3110 Chain = FuncTLVGet.getValue(1); 3111 3112 MachineFunction &F = DAG.getMachineFunction(); 3113 MachineFrameInfo &MFI = F.getFrameInfo(); 3114 MFI.setAdjustsStack(true); 3115 3116 // TLS calls preserve all registers except those that absolutely must be 3117 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3118 // silly). 3119 auto TRI = 3120 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3121 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3122 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3123 3124 // Finally, we can make the call. This is just a degenerate version of a 3125 // normal AArch64 call node: r0 takes the address of the descriptor, and 3126 // returns the address of the variable in this thread. 3127 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3128 Chain = 3129 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3130 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3131 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3132 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3133 } 3134 3135 SDValue 3136 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3137 SelectionDAG &DAG) const { 3138 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3139 3140 SDValue Chain = DAG.getEntryNode(); 3141 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3142 SDLoc DL(Op); 3143 3144 // Load the current TEB (thread environment block) 3145 SDValue Ops[] = {Chain, 3146 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3147 DAG.getTargetConstant(15, DL, MVT::i32), 3148 DAG.getTargetConstant(0, DL, MVT::i32), 3149 DAG.getTargetConstant(13, DL, MVT::i32), 3150 DAG.getTargetConstant(0, DL, MVT::i32), 3151 DAG.getTargetConstant(2, DL, MVT::i32)}; 3152 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3153 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3154 3155 SDValue TEB = CurrentTEB.getValue(0); 3156 Chain = CurrentTEB.getValue(1); 3157 3158 // Load the ThreadLocalStoragePointer from the TEB 3159 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3160 SDValue TLSArray = 3161 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3162 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3163 3164 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3165 // offset into the TLSArray. 3166 3167 // Load the TLS index from the C runtime 3168 SDValue TLSIndex = 3169 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3170 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3171 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3172 3173 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3174 DAG.getConstant(2, DL, MVT::i32)); 3175 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3176 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3177 MachinePointerInfo()); 3178 3179 // Get the offset of the start of the .tls section (section base) 3180 const auto *GA = cast<GlobalAddressSDNode>(Op); 3181 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3182 SDValue Offset = DAG.getLoad( 3183 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3184 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 3185 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3186 3187 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3188 } 3189 3190 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3191 SDValue 3192 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3193 SelectionDAG &DAG) const { 3194 SDLoc dl(GA); 3195 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3196 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3197 MachineFunction &MF = DAG.getMachineFunction(); 3198 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3199 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3200 ARMConstantPoolValue *CPV = 3201 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3202 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3203 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3204 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3205 Argument = DAG.getLoad( 3206 PtrVT, dl, DAG.getEntryNode(), Argument, 3207 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3208 SDValue Chain = Argument.getValue(1); 3209 3210 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3211 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3212 3213 // call __tls_get_addr. 3214 ArgListTy Args; 3215 ArgListEntry Entry; 3216 Entry.Node = Argument; 3217 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3218 Args.push_back(Entry); 3219 3220 // FIXME: is there useful debug info available here? 3221 TargetLowering::CallLoweringInfo CLI(DAG); 3222 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3223 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3224 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3225 3226 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3227 return CallResult.first; 3228 } 3229 3230 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3231 // "local exec" model. 3232 SDValue 3233 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3234 SelectionDAG &DAG, 3235 TLSModel::Model model) const { 3236 const GlobalValue *GV = GA->getGlobal(); 3237 SDLoc dl(GA); 3238 SDValue Offset; 3239 SDValue Chain = DAG.getEntryNode(); 3240 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3241 // Get the Thread Pointer 3242 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3243 3244 if (model == TLSModel::InitialExec) { 3245 MachineFunction &MF = DAG.getMachineFunction(); 3246 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3247 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3248 // Initial exec model. 3249 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3250 ARMConstantPoolValue *CPV = 3251 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3252 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3253 true); 3254 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3255 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3256 Offset = DAG.getLoad( 3257 PtrVT, dl, Chain, Offset, 3258 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3259 Chain = Offset.getValue(1); 3260 3261 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3262 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3263 3264 Offset = DAG.getLoad( 3265 PtrVT, dl, Chain, Offset, 3266 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3267 } else { 3268 // local exec model 3269 assert(model == TLSModel::LocalExec); 3270 ARMConstantPoolValue *CPV = 3271 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3272 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3273 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3274 Offset = DAG.getLoad( 3275 PtrVT, dl, Chain, Offset, 3276 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3277 } 3278 3279 // The address of the thread local variable is the add of the thread 3280 // pointer with the offset of the variable. 3281 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3282 } 3283 3284 SDValue 3285 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3286 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3287 if (DAG.getTarget().useEmulatedTLS()) 3288 return LowerToTLSEmulatedModel(GA, DAG); 3289 3290 if (Subtarget->isTargetDarwin()) 3291 return LowerGlobalTLSAddressDarwin(Op, DAG); 3292 3293 if (Subtarget->isTargetWindows()) 3294 return LowerGlobalTLSAddressWindows(Op, DAG); 3295 3296 // TODO: implement the "local dynamic" model 3297 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3298 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3299 3300 switch (model) { 3301 case TLSModel::GeneralDynamic: 3302 case TLSModel::LocalDynamic: 3303 return LowerToTLSGeneralDynamicModel(GA, DAG); 3304 case TLSModel::InitialExec: 3305 case TLSModel::LocalExec: 3306 return LowerToTLSExecModels(GA, DAG, model); 3307 } 3308 llvm_unreachable("bogus TLS model"); 3309 } 3310 3311 /// Return true if all users of V are within function F, looking through 3312 /// ConstantExprs. 3313 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3314 SmallVector<const User*,4> Worklist; 3315 for (auto *U : V->users()) 3316 Worklist.push_back(U); 3317 while (!Worklist.empty()) { 3318 auto *U = Worklist.pop_back_val(); 3319 if (isa<ConstantExpr>(U)) { 3320 for (auto *UU : U->users()) 3321 Worklist.push_back(UU); 3322 continue; 3323 } 3324 3325 auto *I = dyn_cast<Instruction>(U); 3326 if (!I || I->getParent()->getParent() != F) 3327 return false; 3328 } 3329 return true; 3330 } 3331 3332 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3333 const GlobalValue *GV, SelectionDAG &DAG, 3334 EVT PtrVT, const SDLoc &dl) { 3335 // If we're creating a pool entry for a constant global with unnamed address, 3336 // and the global is small enough, we can emit it inline into the constant pool 3337 // to save ourselves an indirection. 3338 // 3339 // This is a win if the constant is only used in one function (so it doesn't 3340 // need to be duplicated) or duplicating the constant wouldn't increase code 3341 // size (implying the constant is no larger than 4 bytes). 3342 const Function &F = DAG.getMachineFunction().getFunction(); 3343 3344 // We rely on this decision to inline being idemopotent and unrelated to the 3345 // use-site. We know that if we inline a variable at one use site, we'll 3346 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3347 // doesn't know about this optimization, so bail out if it's enabled else 3348 // we could decide to inline here (and thus never emit the GV) but require 3349 // the GV from fast-isel generated code. 3350 if (!EnableConstpoolPromotion || 3351 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3352 return SDValue(); 3353 3354 auto *GVar = dyn_cast<GlobalVariable>(GV); 3355 if (!GVar || !GVar->hasInitializer() || 3356 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3357 !GVar->hasLocalLinkage()) 3358 return SDValue(); 3359 3360 // If we inline a value that contains relocations, we move the relocations 3361 // from .data to .text. This is not allowed in position-independent code. 3362 auto *Init = GVar->getInitializer(); 3363 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3364 Init->needsRelocation()) 3365 return SDValue(); 3366 3367 // The constant islands pass can only really deal with alignment requests 3368 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3369 // any type wanting greater alignment requirements than 4 bytes. We also 3370 // can only promote constants that are multiples of 4 bytes in size or 3371 // are paddable to a multiple of 4. Currently we only try and pad constants 3372 // that are strings for simplicity. 3373 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3374 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3375 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3376 unsigned RequiredPadding = 4 - (Size % 4); 3377 bool PaddingPossible = 3378 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3379 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3380 Size == 0) 3381 return SDValue(); 3382 3383 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3384 MachineFunction &MF = DAG.getMachineFunction(); 3385 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3386 3387 // We can't bloat the constant pool too much, else the ConstantIslands pass 3388 // may fail to converge. If we haven't promoted this global yet (it may have 3389 // multiple uses), and promoting it would increase the constant pool size (Sz 3390 // > 4), ensure we have space to do so up to MaxTotal. 3391 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3392 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3393 ConstpoolPromotionMaxTotal) 3394 return SDValue(); 3395 3396 // This is only valid if all users are in a single function; we can't clone 3397 // the constant in general. The LLVM IR unnamed_addr allows merging 3398 // constants, but not cloning them. 3399 // 3400 // We could potentially allow cloning if we could prove all uses of the 3401 // constant in the current function don't care about the address, like 3402 // printf format strings. But that isn't implemented for now. 3403 if (!allUsersAreInFunction(GVar, &F)) 3404 return SDValue(); 3405 3406 // We're going to inline this global. Pad it out if needed. 3407 if (RequiredPadding != 4) { 3408 StringRef S = CDAInit->getAsString(); 3409 3410 SmallVector<uint8_t,16> V(S.size()); 3411 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3412 while (RequiredPadding--) 3413 V.push_back(0); 3414 Init = ConstantDataArray::get(*DAG.getContext(), V); 3415 } 3416 3417 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3418 SDValue CPAddr = 3419 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3420 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3421 AFI->markGlobalAsPromotedToConstantPool(GVar); 3422 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3423 PaddedSize - 4); 3424 } 3425 ++NumConstpoolPromoted; 3426 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3427 } 3428 3429 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3430 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3431 if (!(GV = GA->getBaseObject())) 3432 return false; 3433 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3434 return V->isConstant(); 3435 return isa<Function>(GV); 3436 } 3437 3438 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3439 SelectionDAG &DAG) const { 3440 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3441 default: llvm_unreachable("unknown object format"); 3442 case Triple::COFF: 3443 return LowerGlobalAddressWindows(Op, DAG); 3444 case Triple::ELF: 3445 return LowerGlobalAddressELF(Op, DAG); 3446 case Triple::MachO: 3447 return LowerGlobalAddressDarwin(Op, DAG); 3448 } 3449 } 3450 3451 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3452 SelectionDAG &DAG) const { 3453 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3454 SDLoc dl(Op); 3455 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3456 const TargetMachine &TM = getTargetMachine(); 3457 bool IsRO = isReadOnly(GV); 3458 3459 // promoteToConstantPool only if not generating XO text section 3460 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3461 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3462 return V; 3463 3464 if (isPositionIndependent()) { 3465 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3466 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3467 UseGOT_PREL ? ARMII::MO_GOT : 0); 3468 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3469 if (UseGOT_PREL) 3470 Result = 3471 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3472 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3473 return Result; 3474 } else if (Subtarget->isROPI() && IsRO) { 3475 // PC-relative. 3476 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3477 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3478 return Result; 3479 } else if (Subtarget->isRWPI() && !IsRO) { 3480 // SB-relative. 3481 SDValue RelAddr; 3482 if (Subtarget->useMovt()) { 3483 ++NumMovwMovt; 3484 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3485 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3486 } else { // use literal pool for address constant 3487 ARMConstantPoolValue *CPV = 3488 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3489 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3490 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3491 RelAddr = DAG.getLoad( 3492 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3493 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3494 } 3495 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3496 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3497 return Result; 3498 } 3499 3500 // If we have T2 ops, we can materialize the address directly via movt/movw 3501 // pair. This is always cheaper. 3502 if (Subtarget->useMovt()) { 3503 ++NumMovwMovt; 3504 // FIXME: Once remat is capable of dealing with instructions with register 3505 // operands, expand this into two nodes. 3506 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3507 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3508 } else { 3509 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3510 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3511 return DAG.getLoad( 3512 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3513 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3514 } 3515 } 3516 3517 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3518 SelectionDAG &DAG) const { 3519 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3520 "ROPI/RWPI not currently supported for Darwin"); 3521 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3522 SDLoc dl(Op); 3523 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3524 3525 if (Subtarget->useMovt()) 3526 ++NumMovwMovt; 3527 3528 // FIXME: Once remat is capable of dealing with instructions with register 3529 // operands, expand this into multiple nodes 3530 unsigned Wrapper = 3531 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3532 3533 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3534 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3535 3536 if (Subtarget->isGVIndirectSymbol(GV)) 3537 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3538 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3539 return Result; 3540 } 3541 3542 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3543 SelectionDAG &DAG) const { 3544 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3545 assert(Subtarget->useMovt() && 3546 "Windows on ARM expects to use movw/movt"); 3547 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3548 "ROPI/RWPI not currently supported for Windows"); 3549 3550 const TargetMachine &TM = getTargetMachine(); 3551 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3552 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3553 if (GV->hasDLLImportStorageClass()) 3554 TargetFlags = ARMII::MO_DLLIMPORT; 3555 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3556 TargetFlags = ARMII::MO_COFFSTUB; 3557 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3558 SDValue Result; 3559 SDLoc DL(Op); 3560 3561 ++NumMovwMovt; 3562 3563 // FIXME: Once remat is capable of dealing with instructions with register 3564 // operands, expand this into two nodes. 3565 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3566 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3567 TargetFlags)); 3568 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3569 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3570 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3571 return Result; 3572 } 3573 3574 SDValue 3575 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3576 SDLoc dl(Op); 3577 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3578 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3579 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3580 Op.getOperand(1), Val); 3581 } 3582 3583 SDValue 3584 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3585 SDLoc dl(Op); 3586 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3587 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3588 } 3589 3590 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3591 SelectionDAG &DAG) const { 3592 SDLoc dl(Op); 3593 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3594 Op.getOperand(0)); 3595 } 3596 3597 SDValue ARMTargetLowering::LowerINTRINSIC_VOID( 3598 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const { 3599 unsigned IntNo = 3600 cast<ConstantSDNode>( 3601 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other)) 3602 ->getZExtValue(); 3603 switch (IntNo) { 3604 default: 3605 return SDValue(); // Don't custom lower most intrinsics. 3606 case Intrinsic::arm_gnu_eabi_mcount: { 3607 MachineFunction &MF = DAG.getMachineFunction(); 3608 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3609 SDLoc dl(Op); 3610 SDValue Chain = Op.getOperand(0); 3611 // call "\01__gnu_mcount_nc" 3612 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 3613 const uint32_t *Mask = 3614 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 3615 assert(Mask && "Missing call preserved mask for calling convention"); 3616 // Mark LR an implicit live-in. 3617 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 3618 SDValue ReturnAddress = 3619 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT); 3620 std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue}; 3621 SDValue Callee = 3622 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0); 3623 SDValue RegisterMask = DAG.getRegisterMask(Mask); 3624 if (Subtarget->isThumb()) 3625 return SDValue( 3626 DAG.getMachineNode( 3627 ARM::tBL_PUSHLR, dl, ResultTys, 3628 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT), 3629 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}), 3630 0); 3631 return SDValue( 3632 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys, 3633 {ReturnAddress, Callee, RegisterMask, Chain}), 3634 0); 3635 } 3636 } 3637 } 3638 3639 SDValue 3640 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3641 const ARMSubtarget *Subtarget) const { 3642 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3643 SDLoc dl(Op); 3644 switch (IntNo) { 3645 default: return SDValue(); // Don't custom lower most intrinsics. 3646 case Intrinsic::thread_pointer: { 3647 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3648 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3649 } 3650 case Intrinsic::arm_cls: { 3651 const SDValue &Operand = Op.getOperand(1); 3652 const EVT VTy = Op.getValueType(); 3653 SDValue SRA = 3654 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy)); 3655 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand); 3656 SDValue SHL = 3657 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy)); 3658 SDValue OR = 3659 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy)); 3660 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR); 3661 return Result; 3662 } 3663 case Intrinsic::arm_cls64: { 3664 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x)) 3665 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x))) 3666 const SDValue &Operand = Op.getOperand(1); 3667 const EVT VTy = Op.getValueType(); 3668 3669 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3670 DAG.getConstant(1, dl, VTy)); 3671 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3672 DAG.getConstant(0, dl, VTy)); 3673 SDValue Constant0 = DAG.getConstant(0, dl, VTy); 3674 SDValue Constant1 = DAG.getConstant(1, dl, VTy); 3675 SDValue Constant31 = DAG.getConstant(31, dl, VTy); 3676 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31); 3677 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi); 3678 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1); 3679 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1); 3680 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi); 3681 SDValue CheckLo = 3682 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ); 3683 SDValue HiIsZero = 3684 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ); 3685 SDValue AdjustedLo = 3686 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy)); 3687 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo); 3688 SDValue Result = 3689 DAG.getSelect(dl, VTy, CheckLo, 3690 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi); 3691 return Result; 3692 } 3693 case Intrinsic::eh_sjlj_lsda: { 3694 MachineFunction &MF = DAG.getMachineFunction(); 3695 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3696 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3697 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3698 SDValue CPAddr; 3699 bool IsPositionIndependent = isPositionIndependent(); 3700 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3701 ARMConstantPoolValue *CPV = 3702 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3703 ARMCP::CPLSDA, PCAdj); 3704 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3705 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3706 SDValue Result = DAG.getLoad( 3707 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3708 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3709 3710 if (IsPositionIndependent) { 3711 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3712 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3713 } 3714 return Result; 3715 } 3716 case Intrinsic::arm_neon_vabs: 3717 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3718 Op.getOperand(1)); 3719 case Intrinsic::arm_neon_vmulls: 3720 case Intrinsic::arm_neon_vmullu: { 3721 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3722 ? ARMISD::VMULLs : ARMISD::VMULLu; 3723 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3724 Op.getOperand(1), Op.getOperand(2)); 3725 } 3726 case Intrinsic::arm_neon_vminnm: 3727 case Intrinsic::arm_neon_vmaxnm: { 3728 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3729 ? ISD::FMINNUM : ISD::FMAXNUM; 3730 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3731 Op.getOperand(1), Op.getOperand(2)); 3732 } 3733 case Intrinsic::arm_neon_vminu: 3734 case Intrinsic::arm_neon_vmaxu: { 3735 if (Op.getValueType().isFloatingPoint()) 3736 return SDValue(); 3737 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3738 ? ISD::UMIN : ISD::UMAX; 3739 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3740 Op.getOperand(1), Op.getOperand(2)); 3741 } 3742 case Intrinsic::arm_neon_vmins: 3743 case Intrinsic::arm_neon_vmaxs: { 3744 // v{min,max}s is overloaded between signed integers and floats. 3745 if (!Op.getValueType().isFloatingPoint()) { 3746 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3747 ? ISD::SMIN : ISD::SMAX; 3748 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3749 Op.getOperand(1), Op.getOperand(2)); 3750 } 3751 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3752 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3753 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3754 Op.getOperand(1), Op.getOperand(2)); 3755 } 3756 case Intrinsic::arm_neon_vtbl1: 3757 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3758 Op.getOperand(1), Op.getOperand(2)); 3759 case Intrinsic::arm_neon_vtbl2: 3760 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3761 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3762 case Intrinsic::arm_mve_pred_i2v: 3763 case Intrinsic::arm_mve_pred_v2i: 3764 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(), 3765 Op.getOperand(1)); 3766 } 3767 } 3768 3769 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3770 const ARMSubtarget *Subtarget) { 3771 SDLoc dl(Op); 3772 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3773 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3774 if (SSID == SyncScope::SingleThread) 3775 return Op; 3776 3777 if (!Subtarget->hasDataBarrier()) { 3778 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3779 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3780 // here. 3781 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3782 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3783 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3784 DAG.getConstant(0, dl, MVT::i32)); 3785 } 3786 3787 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3788 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3789 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3790 if (Subtarget->isMClass()) { 3791 // Only a full system barrier exists in the M-class architectures. 3792 Domain = ARM_MB::SY; 3793 } else if (Subtarget->preferISHSTBarriers() && 3794 Ord == AtomicOrdering::Release) { 3795 // Swift happens to implement ISHST barriers in a way that's compatible with 3796 // Release semantics but weaker than ISH so we'd be fools not to use 3797 // it. Beware: other processors probably don't! 3798 Domain = ARM_MB::ISHST; 3799 } 3800 3801 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3802 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3803 DAG.getConstant(Domain, dl, MVT::i32)); 3804 } 3805 3806 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3807 const ARMSubtarget *Subtarget) { 3808 // ARM pre v5TE and Thumb1 does not have preload instructions. 3809 if (!(Subtarget->isThumb2() || 3810 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3811 // Just preserve the chain. 3812 return Op.getOperand(0); 3813 3814 SDLoc dl(Op); 3815 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3816 if (!isRead && 3817 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3818 // ARMv7 with MP extension has PLDW. 3819 return Op.getOperand(0); 3820 3821 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3822 if (Subtarget->isThumb()) { 3823 // Invert the bits. 3824 isRead = ~isRead & 1; 3825 isData = ~isData & 1; 3826 } 3827 3828 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3829 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3830 DAG.getConstant(isData, dl, MVT::i32)); 3831 } 3832 3833 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3834 MachineFunction &MF = DAG.getMachineFunction(); 3835 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3836 3837 // vastart just stores the address of the VarArgsFrameIndex slot into the 3838 // memory location argument. 3839 SDLoc dl(Op); 3840 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3841 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3842 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3843 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3844 MachinePointerInfo(SV)); 3845 } 3846 3847 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3848 CCValAssign &NextVA, 3849 SDValue &Root, 3850 SelectionDAG &DAG, 3851 const SDLoc &dl) const { 3852 MachineFunction &MF = DAG.getMachineFunction(); 3853 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3854 3855 const TargetRegisterClass *RC; 3856 if (AFI->isThumb1OnlyFunction()) 3857 RC = &ARM::tGPRRegClass; 3858 else 3859 RC = &ARM::GPRRegClass; 3860 3861 // Transform the arguments stored in physical registers into virtual ones. 3862 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3863 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3864 3865 SDValue ArgValue2; 3866 if (NextVA.isMemLoc()) { 3867 MachineFrameInfo &MFI = MF.getFrameInfo(); 3868 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3869 3870 // Create load node to retrieve arguments from the stack. 3871 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3872 ArgValue2 = DAG.getLoad( 3873 MVT::i32, dl, Root, FIN, 3874 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3875 } else { 3876 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3877 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3878 } 3879 if (!Subtarget->isLittle()) 3880 std::swap (ArgValue, ArgValue2); 3881 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3882 } 3883 3884 // The remaining GPRs hold either the beginning of variable-argument 3885 // data, or the beginning of an aggregate passed by value (usually 3886 // byval). Either way, we allocate stack slots adjacent to the data 3887 // provided by our caller, and store the unallocated registers there. 3888 // If this is a variadic function, the va_list pointer will begin with 3889 // these values; otherwise, this reassembles a (byval) structure that 3890 // was split between registers and memory. 3891 // Return: The frame index registers were stored into. 3892 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3893 const SDLoc &dl, SDValue &Chain, 3894 const Value *OrigArg, 3895 unsigned InRegsParamRecordIdx, 3896 int ArgOffset, unsigned ArgSize) const { 3897 // Currently, two use-cases possible: 3898 // Case #1. Non-var-args function, and we meet first byval parameter. 3899 // Setup first unallocated register as first byval register; 3900 // eat all remained registers 3901 // (these two actions are performed by HandleByVal method). 3902 // Then, here, we initialize stack frame with 3903 // "store-reg" instructions. 3904 // Case #2. Var-args function, that doesn't contain byval parameters. 3905 // The same: eat all remained unallocated registers, 3906 // initialize stack frame. 3907 3908 MachineFunction &MF = DAG.getMachineFunction(); 3909 MachineFrameInfo &MFI = MF.getFrameInfo(); 3910 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3911 unsigned RBegin, REnd; 3912 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3913 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3914 } else { 3915 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3916 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3917 REnd = ARM::R4; 3918 } 3919 3920 if (REnd != RBegin) 3921 ArgOffset = -4 * (ARM::R4 - RBegin); 3922 3923 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3924 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3925 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3926 3927 SmallVector<SDValue, 4> MemOps; 3928 const TargetRegisterClass *RC = 3929 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3930 3931 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3932 unsigned VReg = MF.addLiveIn(Reg, RC); 3933 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3934 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3935 MachinePointerInfo(OrigArg, 4 * i)); 3936 MemOps.push_back(Store); 3937 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3938 } 3939 3940 if (!MemOps.empty()) 3941 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3942 return FrameIndex; 3943 } 3944 3945 // Setup stack frame, the va_list pointer will start from. 3946 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3947 const SDLoc &dl, SDValue &Chain, 3948 unsigned ArgOffset, 3949 unsigned TotalArgRegsSaveSize, 3950 bool ForceMutable) const { 3951 MachineFunction &MF = DAG.getMachineFunction(); 3952 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3953 3954 // Try to store any remaining integer argument regs 3955 // to their spots on the stack so that they may be loaded by dereferencing 3956 // the result of va_next. 3957 // If there is no regs to be stored, just point address after last 3958 // argument passed via stack. 3959 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3960 CCInfo.getInRegsParamsCount(), 3961 CCInfo.getNextStackOffset(), 3962 std::max(4U, TotalArgRegsSaveSize)); 3963 AFI->setVarArgsFrameIndex(FrameIndex); 3964 } 3965 3966 SDValue ARMTargetLowering::LowerFormalArguments( 3967 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3968 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3969 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3970 MachineFunction &MF = DAG.getMachineFunction(); 3971 MachineFrameInfo &MFI = MF.getFrameInfo(); 3972 3973 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3974 3975 // Assign locations to all of the incoming arguments. 3976 SmallVector<CCValAssign, 16> ArgLocs; 3977 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3978 *DAG.getContext()); 3979 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3980 3981 SmallVector<SDValue, 16> ArgValues; 3982 SDValue ArgValue; 3983 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3984 unsigned CurArgIdx = 0; 3985 3986 // Initially ArgRegsSaveSize is zero. 3987 // Then we increase this value each time we meet byval parameter. 3988 // We also increase this value in case of varargs function. 3989 AFI->setArgRegsSaveSize(0); 3990 3991 // Calculate the amount of stack space that we need to allocate to store 3992 // byval and variadic arguments that are passed in registers. 3993 // We need to know this before we allocate the first byval or variadic 3994 // argument, as they will be allocated a stack slot below the CFA (Canonical 3995 // Frame Address, the stack pointer at entry to the function). 3996 unsigned ArgRegBegin = ARM::R4; 3997 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3998 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3999 break; 4000 4001 CCValAssign &VA = ArgLocs[i]; 4002 unsigned Index = VA.getValNo(); 4003 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 4004 if (!Flags.isByVal()) 4005 continue; 4006 4007 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 4008 unsigned RBegin, REnd; 4009 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 4010 ArgRegBegin = std::min(ArgRegBegin, RBegin); 4011 4012 CCInfo.nextInRegsParam(); 4013 } 4014 CCInfo.rewindByValRegsInfo(); 4015 4016 int lastInsIndex = -1; 4017 if (isVarArg && MFI.hasVAStart()) { 4018 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4019 if (RegIdx != array_lengthof(GPRArgRegs)) 4020 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 4021 } 4022 4023 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 4024 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 4025 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4026 4027 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4028 CCValAssign &VA = ArgLocs[i]; 4029 if (Ins[VA.getValNo()].isOrigArg()) { 4030 std::advance(CurOrigArg, 4031 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 4032 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 4033 } 4034 // Arguments stored in registers. 4035 if (VA.isRegLoc()) { 4036 EVT RegVT = VA.getLocVT(); 4037 4038 if (VA.needsCustom()) { 4039 // f64 and vector types are split up into multiple registers or 4040 // combinations of registers and stack slots. 4041 if (VA.getLocVT() == MVT::v2f64) { 4042 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 4043 Chain, DAG, dl); 4044 VA = ArgLocs[++i]; // skip ahead to next loc 4045 SDValue ArgValue2; 4046 if (VA.isMemLoc()) { 4047 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 4048 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4049 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 4050 MachinePointerInfo::getFixedStack( 4051 DAG.getMachineFunction(), FI)); 4052 } else { 4053 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 4054 Chain, DAG, dl); 4055 } 4056 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 4057 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 4058 ArgValue, ArgValue1, 4059 DAG.getIntPtrConstant(0, dl)); 4060 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 4061 ArgValue, ArgValue2, 4062 DAG.getIntPtrConstant(1, dl)); 4063 } else 4064 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4065 } else { 4066 const TargetRegisterClass *RC; 4067 4068 4069 if (RegVT == MVT::f16) 4070 RC = &ARM::HPRRegClass; 4071 else if (RegVT == MVT::f32) 4072 RC = &ARM::SPRRegClass; 4073 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 4074 RC = &ARM::DPRRegClass; 4075 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 4076 RC = &ARM::QPRRegClass; 4077 else if (RegVT == MVT::i32) 4078 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 4079 : &ARM::GPRRegClass; 4080 else 4081 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4082 4083 // Transform the arguments in physical registers into virtual ones. 4084 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4085 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 4086 4087 // If this value is passed in r0 and has the returned attribute (e.g. 4088 // C++ 'structors), record this fact for later use. 4089 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 4090 AFI->setPreservesR0(); 4091 } 4092 } 4093 4094 // If this is an 8 or 16-bit value, it is really passed promoted 4095 // to 32 bits. Insert an assert[sz]ext to capture this, then 4096 // truncate to the right size. 4097 switch (VA.getLocInfo()) { 4098 default: llvm_unreachable("Unknown loc info!"); 4099 case CCValAssign::Full: break; 4100 case CCValAssign::BCvt: 4101 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 4102 break; 4103 case CCValAssign::SExt: 4104 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 4105 DAG.getValueType(VA.getValVT())); 4106 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4107 break; 4108 case CCValAssign::ZExt: 4109 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 4110 DAG.getValueType(VA.getValVT())); 4111 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4112 break; 4113 } 4114 4115 InVals.push_back(ArgValue); 4116 } else { // VA.isRegLoc() 4117 // sanity check 4118 assert(VA.isMemLoc()); 4119 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 4120 4121 int index = VA.getValNo(); 4122 4123 // Some Ins[] entries become multiple ArgLoc[] entries. 4124 // Process them only once. 4125 if (index != lastInsIndex) 4126 { 4127 ISD::ArgFlagsTy Flags = Ins[index].Flags; 4128 // FIXME: For now, all byval parameter objects are marked mutable. 4129 // This can be changed with more analysis. 4130 // In case of tail call optimization mark all arguments mutable. 4131 // Since they could be overwritten by lowering of arguments in case of 4132 // a tail call. 4133 if (Flags.isByVal()) { 4134 assert(Ins[index].isOrigArg() && 4135 "Byval arguments cannot be implicit"); 4136 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 4137 4138 int FrameIndex = StoreByValRegs( 4139 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 4140 VA.getLocMemOffset(), Flags.getByValSize()); 4141 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 4142 CCInfo.nextInRegsParam(); 4143 } else { 4144 unsigned FIOffset = VA.getLocMemOffset(); 4145 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 4146 FIOffset, true); 4147 4148 // Create load nodes to retrieve arguments from the stack. 4149 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4150 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 4151 MachinePointerInfo::getFixedStack( 4152 DAG.getMachineFunction(), FI))); 4153 } 4154 lastInsIndex = index; 4155 } 4156 } 4157 } 4158 4159 // varargs 4160 if (isVarArg && MFI.hasVAStart()) 4161 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 4162 CCInfo.getNextStackOffset(), 4163 TotalArgRegsSaveSize); 4164 4165 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4166 4167 return Chain; 4168 } 4169 4170 /// isFloatingPointZero - Return true if this is +0.0. 4171 static bool isFloatingPointZero(SDValue Op) { 4172 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4173 return CFP->getValueAPF().isPosZero(); 4174 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4175 // Maybe this has already been legalized into the constant pool? 4176 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4177 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4178 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4179 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4180 return CFP->getValueAPF().isPosZero(); 4181 } 4182 } else if (Op->getOpcode() == ISD::BITCAST && 4183 Op->getValueType(0) == MVT::f64) { 4184 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4185 // created by LowerConstantFP(). 4186 SDValue BitcastOp = Op->getOperand(0); 4187 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4188 isNullConstant(BitcastOp->getOperand(0))) 4189 return true; 4190 } 4191 return false; 4192 } 4193 4194 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4195 /// the given operands. 4196 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4197 SDValue &ARMcc, SelectionDAG &DAG, 4198 const SDLoc &dl) const { 4199 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4200 unsigned C = RHSC->getZExtValue(); 4201 if (!isLegalICmpImmediate((int32_t)C)) { 4202 // Constant does not fit, try adjusting it by one. 4203 switch (CC) { 4204 default: break; 4205 case ISD::SETLT: 4206 case ISD::SETGE: 4207 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4208 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4209 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4210 } 4211 break; 4212 case ISD::SETULT: 4213 case ISD::SETUGE: 4214 if (C != 0 && isLegalICmpImmediate(C-1)) { 4215 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4216 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4217 } 4218 break; 4219 case ISD::SETLE: 4220 case ISD::SETGT: 4221 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4222 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4223 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4224 } 4225 break; 4226 case ISD::SETULE: 4227 case ISD::SETUGT: 4228 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4229 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4230 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4231 } 4232 break; 4233 } 4234 } 4235 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4236 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4237 // In ARM and Thumb-2, the compare instructions can shift their second 4238 // operand. 4239 CC = ISD::getSetCCSwappedOperands(CC); 4240 std::swap(LHS, RHS); 4241 } 4242 4243 // Thumb1 has very limited immediate modes, so turning an "and" into a 4244 // shift can save multiple instructions. 4245 // 4246 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4247 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4248 // own. If it's the operand to an unsigned comparison with an immediate, 4249 // we can eliminate one of the shifts: we transform 4250 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4251 // 4252 // We avoid transforming cases which aren't profitable due to encoding 4253 // details: 4254 // 4255 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4256 // would not; in that case, we're essentially trading one immediate load for 4257 // another. 4258 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4259 // 3. C2 is zero; we have other code for this special case. 4260 // 4261 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4262 // instruction, since the AND is always one instruction anyway, but we could 4263 // use narrow instructions in some cases. 4264 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4265 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4266 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4267 !isSignedIntSetCC(CC)) { 4268 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4269 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4270 uint64_t RHSV = RHSC->getZExtValue(); 4271 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4272 unsigned ShiftBits = countLeadingZeros(Mask); 4273 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4274 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4275 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4276 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4277 } 4278 } 4279 } 4280 4281 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4282 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4283 // way a cmp would. 4284 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4285 // some tweaks to the heuristics for the previous and->shift transform. 4286 // FIXME: Optimize cases where the LHS isn't a shift. 4287 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4288 isa<ConstantSDNode>(RHS) && 4289 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4290 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4291 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4292 unsigned ShiftAmt = 4293 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4294 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4295 DAG.getVTList(MVT::i32, MVT::i32), 4296 LHS.getOperand(0), 4297 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4298 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4299 Shift.getValue(1), SDValue()); 4300 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4301 return Chain.getValue(1); 4302 } 4303 4304 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4305 4306 // If the RHS is a constant zero then the V (overflow) flag will never be 4307 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4308 // simpler for other passes (like the peephole optimiser) to deal with. 4309 if (isNullConstant(RHS)) { 4310 switch (CondCode) { 4311 default: break; 4312 case ARMCC::GE: 4313 CondCode = ARMCC::PL; 4314 break; 4315 case ARMCC::LT: 4316 CondCode = ARMCC::MI; 4317 break; 4318 } 4319 } 4320 4321 ARMISD::NodeType CompareType; 4322 switch (CondCode) { 4323 default: 4324 CompareType = ARMISD::CMP; 4325 break; 4326 case ARMCC::EQ: 4327 case ARMCC::NE: 4328 // Uses only Z Flag 4329 CompareType = ARMISD::CMPZ; 4330 break; 4331 } 4332 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4333 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4334 } 4335 4336 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4337 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4338 SelectionDAG &DAG, const SDLoc &dl) const { 4339 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4340 SDValue Cmp; 4341 if (!isFloatingPointZero(RHS)) 4342 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 4343 else 4344 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 4345 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4346 } 4347 4348 /// duplicateCmp - Glue values can have only one use, so this function 4349 /// duplicates a comparison node. 4350 SDValue 4351 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4352 unsigned Opc = Cmp.getOpcode(); 4353 SDLoc DL(Cmp); 4354 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4355 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4356 4357 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4358 Cmp = Cmp.getOperand(0); 4359 Opc = Cmp.getOpcode(); 4360 if (Opc == ARMISD::CMPFP) 4361 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4362 else { 4363 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4364 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 4365 } 4366 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4367 } 4368 4369 // This function returns three things: the arithmetic computation itself 4370 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4371 // comparison and the condition code define the case in which the arithmetic 4372 // computation *does not* overflow. 4373 std::pair<SDValue, SDValue> 4374 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4375 SDValue &ARMcc) const { 4376 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4377 4378 SDValue Value, OverflowCmp; 4379 SDValue LHS = Op.getOperand(0); 4380 SDValue RHS = Op.getOperand(1); 4381 SDLoc dl(Op); 4382 4383 // FIXME: We are currently always generating CMPs because we don't support 4384 // generating CMN through the backend. This is not as good as the natural 4385 // CMP case because it causes a register dependency and cannot be folded 4386 // later. 4387 4388 switch (Op.getOpcode()) { 4389 default: 4390 llvm_unreachable("Unknown overflow instruction!"); 4391 case ISD::SADDO: 4392 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4393 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4394 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4395 break; 4396 case ISD::UADDO: 4397 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4398 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4399 // We do not use it in the USUBO case as Value may not be used. 4400 Value = DAG.getNode(ARMISD::ADDC, dl, 4401 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4402 .getValue(0); 4403 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4404 break; 4405 case ISD::SSUBO: 4406 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4407 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4408 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4409 break; 4410 case ISD::USUBO: 4411 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4412 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4413 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4414 break; 4415 case ISD::UMULO: 4416 // We generate a UMUL_LOHI and then check if the high word is 0. 4417 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4418 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4419 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4420 LHS, RHS); 4421 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4422 DAG.getConstant(0, dl, MVT::i32)); 4423 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4424 break; 4425 case ISD::SMULO: 4426 // We generate a SMUL_LOHI and then check if all the bits of the high word 4427 // are the same as the sign bit of the low word. 4428 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4429 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4430 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4431 LHS, RHS); 4432 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4433 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4434 Value.getValue(0), 4435 DAG.getConstant(31, dl, MVT::i32))); 4436 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4437 break; 4438 } // switch (...) 4439 4440 return std::make_pair(Value, OverflowCmp); 4441 } 4442 4443 SDValue 4444 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4445 // Let legalize expand this if it isn't a legal type yet. 4446 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4447 return SDValue(); 4448 4449 SDValue Value, OverflowCmp; 4450 SDValue ARMcc; 4451 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4452 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4453 SDLoc dl(Op); 4454 // We use 0 and 1 as false and true values. 4455 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4456 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4457 EVT VT = Op.getValueType(); 4458 4459 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4460 ARMcc, CCR, OverflowCmp); 4461 4462 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4463 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4464 } 4465 4466 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4467 SelectionDAG &DAG) { 4468 SDLoc DL(BoolCarry); 4469 EVT CarryVT = BoolCarry.getValueType(); 4470 4471 // This converts the boolean value carry into the carry flag by doing 4472 // ARMISD::SUBC Carry, 1 4473 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4474 DAG.getVTList(CarryVT, MVT::i32), 4475 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4476 return Carry.getValue(1); 4477 } 4478 4479 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4480 SelectionDAG &DAG) { 4481 SDLoc DL(Flags); 4482 4483 // Now convert the carry flag into a boolean carry. We do this 4484 // using ARMISD:ADDE 0, 0, Carry 4485 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4486 DAG.getConstant(0, DL, MVT::i32), 4487 DAG.getConstant(0, DL, MVT::i32), Flags); 4488 } 4489 4490 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4491 SelectionDAG &DAG) const { 4492 // Let legalize expand this if it isn't a legal type yet. 4493 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4494 return SDValue(); 4495 4496 SDValue LHS = Op.getOperand(0); 4497 SDValue RHS = Op.getOperand(1); 4498 SDLoc dl(Op); 4499 4500 EVT VT = Op.getValueType(); 4501 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4502 SDValue Value; 4503 SDValue Overflow; 4504 switch (Op.getOpcode()) { 4505 default: 4506 llvm_unreachable("Unknown overflow instruction!"); 4507 case ISD::UADDO: 4508 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4509 // Convert the carry flag into a boolean value. 4510 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4511 break; 4512 case ISD::USUBO: { 4513 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4514 // Convert the carry flag into a boolean value. 4515 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4516 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4517 // value. So compute 1 - C. 4518 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4519 DAG.getConstant(1, dl, MVT::i32), Overflow); 4520 break; 4521 } 4522 } 4523 4524 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4525 } 4526 4527 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG, 4528 const ARMSubtarget *Subtarget) { 4529 EVT VT = Op.getValueType(); 4530 if (!Subtarget->hasDSP()) 4531 return SDValue(); 4532 if (!VT.isSimple()) 4533 return SDValue(); 4534 4535 unsigned NewOpcode; 4536 bool IsAdd = Op->getOpcode() == ISD::SADDSAT; 4537 switch (VT.getSimpleVT().SimpleTy) { 4538 default: 4539 return SDValue(); 4540 case MVT::i8: 4541 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b; 4542 break; 4543 case MVT::i16: 4544 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b; 4545 break; 4546 } 4547 4548 SDLoc dl(Op); 4549 SDValue Add = 4550 DAG.getNode(NewOpcode, dl, MVT::i32, 4551 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32), 4552 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32)); 4553 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add); 4554 } 4555 4556 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4557 SDValue Cond = Op.getOperand(0); 4558 SDValue SelectTrue = Op.getOperand(1); 4559 SDValue SelectFalse = Op.getOperand(2); 4560 SDLoc dl(Op); 4561 unsigned Opc = Cond.getOpcode(); 4562 4563 if (Cond.getResNo() == 1 && 4564 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4565 Opc == ISD::USUBO)) { 4566 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4567 return SDValue(); 4568 4569 SDValue Value, OverflowCmp; 4570 SDValue ARMcc; 4571 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4572 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4573 EVT VT = Op.getValueType(); 4574 4575 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4576 OverflowCmp, DAG); 4577 } 4578 4579 // Convert: 4580 // 4581 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4582 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4583 // 4584 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4585 const ConstantSDNode *CMOVTrue = 4586 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4587 const ConstantSDNode *CMOVFalse = 4588 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4589 4590 if (CMOVTrue && CMOVFalse) { 4591 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4592 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4593 4594 SDValue True; 4595 SDValue False; 4596 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4597 True = SelectTrue; 4598 False = SelectFalse; 4599 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4600 True = SelectFalse; 4601 False = SelectTrue; 4602 } 4603 4604 if (True.getNode() && False.getNode()) { 4605 EVT VT = Op.getValueType(); 4606 SDValue ARMcc = Cond.getOperand(2); 4607 SDValue CCR = Cond.getOperand(3); 4608 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4609 assert(True.getValueType() == VT); 4610 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4611 } 4612 } 4613 } 4614 4615 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4616 // undefined bits before doing a full-word comparison with zero. 4617 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4618 DAG.getConstant(1, dl, Cond.getValueType())); 4619 4620 return DAG.getSelectCC(dl, Cond, 4621 DAG.getConstant(0, dl, Cond.getValueType()), 4622 SelectTrue, SelectFalse, ISD::SETNE); 4623 } 4624 4625 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4626 bool &swpCmpOps, bool &swpVselOps) { 4627 // Start by selecting the GE condition code for opcodes that return true for 4628 // 'equality' 4629 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4630 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4631 CondCode = ARMCC::GE; 4632 4633 // and GT for opcodes that return false for 'equality'. 4634 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4635 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4636 CondCode = ARMCC::GT; 4637 4638 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4639 // to swap the compare operands. 4640 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4641 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4642 swpCmpOps = true; 4643 4644 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4645 // If we have an unordered opcode, we need to swap the operands to the VSEL 4646 // instruction (effectively negating the condition). 4647 // 4648 // This also has the effect of swapping which one of 'less' or 'greater' 4649 // returns true, so we also swap the compare operands. It also switches 4650 // whether we return true for 'equality', so we compensate by picking the 4651 // opposite condition code to our original choice. 4652 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4653 CC == ISD::SETUGT) { 4654 swpCmpOps = !swpCmpOps; 4655 swpVselOps = !swpVselOps; 4656 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4657 } 4658 4659 // 'ordered' is 'anything but unordered', so use the VS condition code and 4660 // swap the VSEL operands. 4661 if (CC == ISD::SETO) { 4662 CondCode = ARMCC::VS; 4663 swpVselOps = true; 4664 } 4665 4666 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4667 // code and swap the VSEL operands. Also do this if we don't care about the 4668 // unordered case. 4669 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4670 CondCode = ARMCC::EQ; 4671 swpVselOps = true; 4672 } 4673 } 4674 4675 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4676 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4677 SDValue Cmp, SelectionDAG &DAG) const { 4678 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4679 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4680 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4681 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4682 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4683 4684 SDValue TrueLow = TrueVal.getValue(0); 4685 SDValue TrueHigh = TrueVal.getValue(1); 4686 SDValue FalseLow = FalseVal.getValue(0); 4687 SDValue FalseHigh = FalseVal.getValue(1); 4688 4689 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4690 ARMcc, CCR, Cmp); 4691 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4692 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4693 4694 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4695 } else { 4696 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4697 Cmp); 4698 } 4699 } 4700 4701 static bool isGTorGE(ISD::CondCode CC) { 4702 return CC == ISD::SETGT || CC == ISD::SETGE; 4703 } 4704 4705 static bool isLTorLE(ISD::CondCode CC) { 4706 return CC == ISD::SETLT || CC == ISD::SETLE; 4707 } 4708 4709 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4710 // All of these conditions (and their <= and >= counterparts) will do: 4711 // x < k ? k : x 4712 // x > k ? x : k 4713 // k < x ? x : k 4714 // k > x ? k : x 4715 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4716 const SDValue TrueVal, const SDValue FalseVal, 4717 const ISD::CondCode CC, const SDValue K) { 4718 return (isGTorGE(CC) && 4719 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4720 (isLTorLE(CC) && 4721 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4722 } 4723 4724 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4725 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4726 const SDValue TrueVal, const SDValue FalseVal, 4727 const ISD::CondCode CC, const SDValue K) { 4728 return (isGTorGE(CC) && 4729 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4730 (isLTorLE(CC) && 4731 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4732 } 4733 4734 // Check if two chained conditionals could be converted into SSAT or USAT. 4735 // 4736 // SSAT can replace a set of two conditional selectors that bound a number to an 4737 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4738 // 4739 // x < -k ? -k : (x > k ? k : x) 4740 // x < -k ? -k : (x < k ? x : k) 4741 // x > -k ? (x > k ? k : x) : -k 4742 // x < k ? (x < -k ? -k : x) : k 4743 // etc. 4744 // 4745 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4746 // a power of 2. 4747 // 4748 // It returns true if the conversion can be done, false otherwise. 4749 // Additionally, the variable is returned in parameter V, the constant in K and 4750 // usat is set to true if the conditional represents an unsigned saturation 4751 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4752 uint64_t &K, bool &usat) { 4753 SDValue LHS1 = Op.getOperand(0); 4754 SDValue RHS1 = Op.getOperand(1); 4755 SDValue TrueVal1 = Op.getOperand(2); 4756 SDValue FalseVal1 = Op.getOperand(3); 4757 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4758 4759 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4760 if (Op2.getOpcode() != ISD::SELECT_CC) 4761 return false; 4762 4763 SDValue LHS2 = Op2.getOperand(0); 4764 SDValue RHS2 = Op2.getOperand(1); 4765 SDValue TrueVal2 = Op2.getOperand(2); 4766 SDValue FalseVal2 = Op2.getOperand(3); 4767 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4768 4769 // Find out which are the constants and which are the variables 4770 // in each conditional 4771 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4772 ? &RHS1 4773 : nullptr; 4774 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4775 ? &RHS2 4776 : nullptr; 4777 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4778 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4779 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4780 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4781 4782 // We must detect cases where the original operations worked with 16- or 4783 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4784 // must work with sign-extended values but the select operations return 4785 // the original non-extended value. 4786 SDValue V2TmpReg = V2Tmp; 4787 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4788 V2TmpReg = V2Tmp->getOperand(0); 4789 4790 // Check that the registers and the constants have the correct values 4791 // in both conditionals 4792 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4793 V2TmpReg != V2) 4794 return false; 4795 4796 // Figure out which conditional is saturating the lower/upper bound. 4797 const SDValue *LowerCheckOp = 4798 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4799 ? &Op 4800 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4801 ? &Op2 4802 : nullptr; 4803 const SDValue *UpperCheckOp = 4804 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4805 ? &Op 4806 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4807 ? &Op2 4808 : nullptr; 4809 4810 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4811 return false; 4812 4813 // Check that the constant in the lower-bound check is 4814 // the opposite of the constant in the upper-bound check 4815 // in 1's complement. 4816 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4817 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4818 int64_t PosVal = std::max(Val1, Val2); 4819 int64_t NegVal = std::min(Val1, Val2); 4820 4821 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4822 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4823 isPowerOf2_64(PosVal + 1)) { 4824 4825 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4826 if (Val1 == ~Val2) 4827 usat = false; 4828 else if (NegVal == 0) 4829 usat = true; 4830 else 4831 return false; 4832 4833 V = V2; 4834 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4835 4836 return true; 4837 } 4838 4839 return false; 4840 } 4841 4842 // Check if a condition of the type x < k ? k : x can be converted into a 4843 // bit operation instead of conditional moves. 4844 // Currently this is allowed given: 4845 // - The conditions and values match up 4846 // - k is 0 or -1 (all ones) 4847 // This function will not check the last condition, thats up to the caller 4848 // It returns true if the transformation can be made, and in such case 4849 // returns x in V, and k in SatK. 4850 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4851 SDValue &SatK) 4852 { 4853 SDValue LHS = Op.getOperand(0); 4854 SDValue RHS = Op.getOperand(1); 4855 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4856 SDValue TrueVal = Op.getOperand(2); 4857 SDValue FalseVal = Op.getOperand(3); 4858 4859 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4860 ? &RHS 4861 : nullptr; 4862 4863 // No constant operation in comparison, early out 4864 if (!K) 4865 return false; 4866 4867 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4868 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4869 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4870 4871 // If the constant on left and right side, or variable on left and right, 4872 // does not match, early out 4873 if (*K != KTmp || V != VTmp) 4874 return false; 4875 4876 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4877 SatK = *K; 4878 return true; 4879 } 4880 4881 return false; 4882 } 4883 4884 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 4885 if (VT == MVT::f32) 4886 return !Subtarget->hasVFP2Base(); 4887 if (VT == MVT::f64) 4888 return !Subtarget->hasFP64(); 4889 if (VT == MVT::f16) 4890 return !Subtarget->hasFullFP16(); 4891 return false; 4892 } 4893 4894 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4895 EVT VT = Op.getValueType(); 4896 SDLoc dl(Op); 4897 4898 // Try to convert two saturating conditional selects into a single SSAT 4899 SDValue SatValue; 4900 uint64_t SatConstant; 4901 bool SatUSat; 4902 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4903 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4904 if (SatUSat) 4905 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4906 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4907 else 4908 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4909 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4910 } 4911 4912 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4913 // into more efficient bit operations, which is possible when k is 0 or -1 4914 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4915 // single instructions. On Thumb the shift and the bit operation will be two 4916 // instructions. 4917 // Only allow this transformation on full-width (32-bit) operations 4918 SDValue LowerSatConstant; 4919 if (VT == MVT::i32 && 4920 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4921 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4922 DAG.getConstant(31, dl, VT)); 4923 if (isNullConstant(LowerSatConstant)) { 4924 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4925 DAG.getAllOnesConstant(dl, VT)); 4926 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4927 } else if (isAllOnesConstant(LowerSatConstant)) 4928 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4929 } 4930 4931 SDValue LHS = Op.getOperand(0); 4932 SDValue RHS = Op.getOperand(1); 4933 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4934 SDValue TrueVal = Op.getOperand(2); 4935 SDValue FalseVal = Op.getOperand(3); 4936 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal); 4937 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal); 4938 4939 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal && 4940 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) { 4941 unsigned TVal = CTVal->getZExtValue(); 4942 unsigned FVal = CFVal->getZExtValue(); 4943 unsigned Opcode = 0; 4944 4945 if (TVal == ~FVal) { 4946 Opcode = ARMISD::CSINV; 4947 } else if (TVal == ~FVal + 1) { 4948 Opcode = ARMISD::CSNEG; 4949 } else if (TVal + 1 == FVal) { 4950 Opcode = ARMISD::CSINC; 4951 } else if (TVal == FVal + 1) { 4952 Opcode = ARMISD::CSINC; 4953 std::swap(TrueVal, FalseVal); 4954 std::swap(TVal, FVal); 4955 CC = ISD::getSetCCInverse(CC, true); 4956 } 4957 4958 if (Opcode) { 4959 // If one of the constants is cheaper than another, materialise the 4960 // cheaper one and let the csel generate the other. 4961 if (Opcode != ARMISD::CSINC && 4962 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) { 4963 std::swap(TrueVal, FalseVal); 4964 std::swap(TVal, FVal); 4965 CC = ISD::getSetCCInverse(CC, true); 4966 } 4967 4968 // Attempt to use ZR checking TVal is 0, possibly inverting the condition 4969 // to get there. CSINC not is invertable like the other two (~(~a) == a, 4970 // -(-a) == a, but (a+1)+1 != a). 4971 if (FVal == 0 && Opcode != ARMISD::CSINC) { 4972 std::swap(TrueVal, FalseVal); 4973 std::swap(TVal, FVal); 4974 CC = ISD::getSetCCInverse(CC, true); 4975 } 4976 if (TVal == 0) 4977 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32); 4978 4979 // Drops F's value because we can get it by inverting/negating TVal. 4980 FalseVal = TrueVal; 4981 4982 SDValue ARMcc; 4983 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4984 EVT VT = TrueVal.getValueType(); 4985 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp); 4986 } 4987 } 4988 4989 if (isUnsupportedFloatingType(LHS.getValueType())) { 4990 DAG.getTargetLoweringInfo().softenSetCCOperands( 4991 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 4992 4993 // If softenSetCCOperands only returned one value, we should compare it to 4994 // zero. 4995 if (!RHS.getNode()) { 4996 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4997 CC = ISD::SETNE; 4998 } 4999 } 5000 5001 if (LHS.getValueType() == MVT::i32) { 5002 // Try to generate VSEL on ARMv8. 5003 // The VSEL instruction can't use all the usual ARM condition 5004 // codes: it only has two bits to select the condition code, so it's 5005 // constrained to use only GE, GT, VS and EQ. 5006 // 5007 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 5008 // swap the operands of the previous compare instruction (effectively 5009 // inverting the compare condition, swapping 'less' and 'greater') and 5010 // sometimes need to swap the operands to the VSEL (which inverts the 5011 // condition in the sense of firing whenever the previous condition didn't) 5012 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 5013 TrueVal.getValueType() == MVT::f32 || 5014 TrueVal.getValueType() == MVT::f64)) { 5015 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5016 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 5017 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 5018 CC = ISD::getSetCCInverse(CC, true); 5019 std::swap(TrueVal, FalseVal); 5020 } 5021 } 5022 5023 SDValue ARMcc; 5024 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5025 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5026 // Choose GE over PL, which vsel does now support 5027 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 5028 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 5029 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5030 } 5031 5032 ARMCC::CondCodes CondCode, CondCode2; 5033 FPCCToARMCC(CC, CondCode, CondCode2); 5034 5035 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 5036 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 5037 // must use VSEL (limited condition codes), due to not having conditional f16 5038 // moves. 5039 if (Subtarget->hasFPARMv8Base() && 5040 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 5041 (TrueVal.getValueType() == MVT::f16 || 5042 TrueVal.getValueType() == MVT::f32 || 5043 TrueVal.getValueType() == MVT::f64)) { 5044 bool swpCmpOps = false; 5045 bool swpVselOps = false; 5046 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 5047 5048 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 5049 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 5050 if (swpCmpOps) 5051 std::swap(LHS, RHS); 5052 if (swpVselOps) 5053 std::swap(TrueVal, FalseVal); 5054 } 5055 } 5056 5057 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5058 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5059 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5060 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5061 if (CondCode2 != ARMCC::AL) { 5062 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 5063 // FIXME: Needs another CMP because flag can have but one use. 5064 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 5065 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 5066 } 5067 return Result; 5068 } 5069 5070 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 5071 /// to morph to an integer compare sequence. 5072 static bool canChangeToInt(SDValue Op, bool &SeenZero, 5073 const ARMSubtarget *Subtarget) { 5074 SDNode *N = Op.getNode(); 5075 if (!N->hasOneUse()) 5076 // Otherwise it requires moving the value from fp to integer registers. 5077 return false; 5078 if (!N->getNumValues()) 5079 return false; 5080 EVT VT = Op.getValueType(); 5081 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 5082 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 5083 // vmrs are very slow, e.g. cortex-a8. 5084 return false; 5085 5086 if (isFloatingPointZero(Op)) { 5087 SeenZero = true; 5088 return true; 5089 } 5090 return ISD::isNormalLoad(N); 5091 } 5092 5093 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 5094 if (isFloatingPointZero(Op)) 5095 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 5096 5097 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 5098 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 5099 Ld->getPointerInfo(), Ld->getAlignment(), 5100 Ld->getMemOperand()->getFlags()); 5101 5102 llvm_unreachable("Unknown VFP cmp argument!"); 5103 } 5104 5105 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 5106 SDValue &RetVal1, SDValue &RetVal2) { 5107 SDLoc dl(Op); 5108 5109 if (isFloatingPointZero(Op)) { 5110 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 5111 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 5112 return; 5113 } 5114 5115 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 5116 SDValue Ptr = Ld->getBasePtr(); 5117 RetVal1 = 5118 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 5119 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 5120 5121 EVT PtrType = Ptr.getValueType(); 5122 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 5123 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 5124 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 5125 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 5126 Ld->getPointerInfo().getWithOffset(4), NewAlign, 5127 Ld->getMemOperand()->getFlags()); 5128 return; 5129 } 5130 5131 llvm_unreachable("Unknown VFP cmp argument!"); 5132 } 5133 5134 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 5135 /// f32 and even f64 comparisons to integer ones. 5136 SDValue 5137 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 5138 SDValue Chain = Op.getOperand(0); 5139 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5140 SDValue LHS = Op.getOperand(2); 5141 SDValue RHS = Op.getOperand(3); 5142 SDValue Dest = Op.getOperand(4); 5143 SDLoc dl(Op); 5144 5145 bool LHSSeenZero = false; 5146 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 5147 bool RHSSeenZero = false; 5148 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 5149 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 5150 // If unsafe fp math optimization is enabled and there are no other uses of 5151 // the CMP operands, and the condition code is EQ or NE, we can optimize it 5152 // to an integer comparison. 5153 if (CC == ISD::SETOEQ) 5154 CC = ISD::SETEQ; 5155 else if (CC == ISD::SETUNE) 5156 CC = ISD::SETNE; 5157 5158 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5159 SDValue ARMcc; 5160 if (LHS.getValueType() == MVT::f32) { 5161 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5162 bitcastf32Toi32(LHS, DAG), Mask); 5163 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5164 bitcastf32Toi32(RHS, DAG), Mask); 5165 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5166 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5167 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5168 Chain, Dest, ARMcc, CCR, Cmp); 5169 } 5170 5171 SDValue LHS1, LHS2; 5172 SDValue RHS1, RHS2; 5173 expandf64Toi32(LHS, DAG, LHS1, LHS2); 5174 expandf64Toi32(RHS, DAG, RHS1, RHS2); 5175 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 5176 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 5177 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5178 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5179 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5180 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 5181 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 5182 } 5183 5184 return SDValue(); 5185 } 5186 5187 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 5188 SDValue Chain = Op.getOperand(0); 5189 SDValue Cond = Op.getOperand(1); 5190 SDValue Dest = Op.getOperand(2); 5191 SDLoc dl(Op); 5192 5193 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5194 // instruction. 5195 unsigned Opc = Cond.getOpcode(); 5196 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5197 !Subtarget->isThumb1Only(); 5198 if (Cond.getResNo() == 1 && 5199 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5200 Opc == ISD::USUBO || OptimizeMul)) { 5201 // Only lower legal XALUO ops. 5202 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 5203 return SDValue(); 5204 5205 // The actual operation with overflow check. 5206 SDValue Value, OverflowCmp; 5207 SDValue ARMcc; 5208 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 5209 5210 // Reverse the condition code. 5211 ARMCC::CondCodes CondCode = 5212 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5213 CondCode = ARMCC::getOppositeCondition(CondCode); 5214 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5215 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5216 5217 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5218 OverflowCmp); 5219 } 5220 5221 return SDValue(); 5222 } 5223 5224 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5225 SDValue Chain = Op.getOperand(0); 5226 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5227 SDValue LHS = Op.getOperand(2); 5228 SDValue RHS = Op.getOperand(3); 5229 SDValue Dest = Op.getOperand(4); 5230 SDLoc dl(Op); 5231 5232 if (isUnsupportedFloatingType(LHS.getValueType())) { 5233 DAG.getTargetLoweringInfo().softenSetCCOperands( 5234 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5235 5236 // If softenSetCCOperands only returned one value, we should compare it to 5237 // zero. 5238 if (!RHS.getNode()) { 5239 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5240 CC = ISD::SETNE; 5241 } 5242 } 5243 5244 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5245 // instruction. 5246 unsigned Opc = LHS.getOpcode(); 5247 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5248 !Subtarget->isThumb1Only(); 5249 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5250 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5251 Opc == ISD::USUBO || OptimizeMul) && 5252 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5253 // Only lower legal XALUO ops. 5254 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5255 return SDValue(); 5256 5257 // The actual operation with overflow check. 5258 SDValue Value, OverflowCmp; 5259 SDValue ARMcc; 5260 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5261 5262 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5263 // Reverse the condition code. 5264 ARMCC::CondCodes CondCode = 5265 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5266 CondCode = ARMCC::getOppositeCondition(CondCode); 5267 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5268 } 5269 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5270 5271 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5272 OverflowCmp); 5273 } 5274 5275 if (LHS.getValueType() == MVT::i32) { 5276 SDValue ARMcc; 5277 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5278 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5279 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5280 Chain, Dest, ARMcc, CCR, Cmp); 5281 } 5282 5283 if (getTargetMachine().Options.UnsafeFPMath && 5284 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5285 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5286 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5287 return Result; 5288 } 5289 5290 ARMCC::CondCodes CondCode, CondCode2; 5291 FPCCToARMCC(CC, CondCode, CondCode2); 5292 5293 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5294 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5295 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5296 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5297 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5298 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5299 if (CondCode2 != ARMCC::AL) { 5300 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5301 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5302 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5303 } 5304 return Res; 5305 } 5306 5307 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5308 SDValue Chain = Op.getOperand(0); 5309 SDValue Table = Op.getOperand(1); 5310 SDValue Index = Op.getOperand(2); 5311 SDLoc dl(Op); 5312 5313 EVT PTy = getPointerTy(DAG.getDataLayout()); 5314 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5315 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5316 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5317 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5318 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5319 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5320 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5321 // which does another jump to the destination. This also makes it easier 5322 // to translate it to TBB / TBH later (Thumb2 only). 5323 // FIXME: This might not work if the function is extremely large. 5324 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5325 Addr, Op.getOperand(2), JTI); 5326 } 5327 if (isPositionIndependent() || Subtarget->isROPI()) { 5328 Addr = 5329 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5330 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5331 Chain = Addr.getValue(1); 5332 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5333 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5334 } else { 5335 Addr = 5336 DAG.getLoad(PTy, dl, Chain, Addr, 5337 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5338 Chain = Addr.getValue(1); 5339 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5340 } 5341 } 5342 5343 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5344 EVT VT = Op.getValueType(); 5345 SDLoc dl(Op); 5346 5347 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5348 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5349 return Op; 5350 return DAG.UnrollVectorOp(Op.getNode()); 5351 } 5352 5353 const bool HasFullFP16 = 5354 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5355 5356 EVT NewTy; 5357 const EVT OpTy = Op.getOperand(0).getValueType(); 5358 if (OpTy == MVT::v4f32) 5359 NewTy = MVT::v4i32; 5360 else if (OpTy == MVT::v4f16 && HasFullFP16) 5361 NewTy = MVT::v4i16; 5362 else if (OpTy == MVT::v8f16 && HasFullFP16) 5363 NewTy = MVT::v8i16; 5364 else 5365 llvm_unreachable("Invalid type for custom lowering!"); 5366 5367 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5368 return DAG.UnrollVectorOp(Op.getNode()); 5369 5370 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5371 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5372 } 5373 5374 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5375 EVT VT = Op.getValueType(); 5376 if (VT.isVector()) 5377 return LowerVectorFP_TO_INT(Op, DAG); 5378 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) { 5379 RTLIB::Libcall LC; 5380 if (Op.getOpcode() == ISD::FP_TO_SINT) 5381 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 5382 Op.getValueType()); 5383 else 5384 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 5385 Op.getValueType()); 5386 MakeLibCallOptions CallOptions; 5387 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5388 CallOptions, SDLoc(Op)).first; 5389 } 5390 5391 return Op; 5392 } 5393 5394 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5395 EVT VT = Op.getValueType(); 5396 SDLoc dl(Op); 5397 5398 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5399 if (VT.getVectorElementType() == MVT::f32) 5400 return Op; 5401 return DAG.UnrollVectorOp(Op.getNode()); 5402 } 5403 5404 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5405 Op.getOperand(0).getValueType() == MVT::v8i16) && 5406 "Invalid type for custom lowering!"); 5407 5408 const bool HasFullFP16 = 5409 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5410 5411 EVT DestVecType; 5412 if (VT == MVT::v4f32) 5413 DestVecType = MVT::v4i32; 5414 else if (VT == MVT::v4f16 && HasFullFP16) 5415 DestVecType = MVT::v4i16; 5416 else if (VT == MVT::v8f16 && HasFullFP16) 5417 DestVecType = MVT::v8i16; 5418 else 5419 return DAG.UnrollVectorOp(Op.getNode()); 5420 5421 unsigned CastOpc; 5422 unsigned Opc; 5423 switch (Op.getOpcode()) { 5424 default: llvm_unreachable("Invalid opcode!"); 5425 case ISD::SINT_TO_FP: 5426 CastOpc = ISD::SIGN_EXTEND; 5427 Opc = ISD::SINT_TO_FP; 5428 break; 5429 case ISD::UINT_TO_FP: 5430 CastOpc = ISD::ZERO_EXTEND; 5431 Opc = ISD::UINT_TO_FP; 5432 break; 5433 } 5434 5435 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5436 return DAG.getNode(Opc, dl, VT, Op); 5437 } 5438 5439 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5440 EVT VT = Op.getValueType(); 5441 if (VT.isVector()) 5442 return LowerVectorINT_TO_FP(Op, DAG); 5443 if (isUnsupportedFloatingType(VT)) { 5444 RTLIB::Libcall LC; 5445 if (Op.getOpcode() == ISD::SINT_TO_FP) 5446 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5447 Op.getValueType()); 5448 else 5449 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5450 Op.getValueType()); 5451 MakeLibCallOptions CallOptions; 5452 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5453 CallOptions, SDLoc(Op)).first; 5454 } 5455 5456 return Op; 5457 } 5458 5459 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5460 // Implement fcopysign with a fabs and a conditional fneg. 5461 SDValue Tmp0 = Op.getOperand(0); 5462 SDValue Tmp1 = Op.getOperand(1); 5463 SDLoc dl(Op); 5464 EVT VT = Op.getValueType(); 5465 EVT SrcVT = Tmp1.getValueType(); 5466 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5467 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5468 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5469 5470 if (UseNEON) { 5471 // Use VBSL to copy the sign bit. 5472 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5473 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5474 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5475 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5476 if (VT == MVT::f64) 5477 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5478 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5479 DAG.getConstant(32, dl, MVT::i32)); 5480 else /*if (VT == MVT::f32)*/ 5481 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5482 if (SrcVT == MVT::f32) { 5483 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5484 if (VT == MVT::f64) 5485 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5486 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5487 DAG.getConstant(32, dl, MVT::i32)); 5488 } else if (VT == MVT::f32) 5489 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5490 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5491 DAG.getConstant(32, dl, MVT::i32)); 5492 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5493 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5494 5495 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5496 dl, MVT::i32); 5497 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5498 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5499 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5500 5501 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5502 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5503 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5504 if (VT == MVT::f32) { 5505 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5506 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5507 DAG.getConstant(0, dl, MVT::i32)); 5508 } else { 5509 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5510 } 5511 5512 return Res; 5513 } 5514 5515 // Bitcast operand 1 to i32. 5516 if (SrcVT == MVT::f64) 5517 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5518 Tmp1).getValue(1); 5519 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5520 5521 // Or in the signbit with integer operations. 5522 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5523 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5524 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5525 if (VT == MVT::f32) { 5526 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5527 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5528 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5529 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5530 } 5531 5532 // f64: Or the high part with signbit and then combine two parts. 5533 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5534 Tmp0); 5535 SDValue Lo = Tmp0.getValue(0); 5536 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5537 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5538 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5539 } 5540 5541 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5542 MachineFunction &MF = DAG.getMachineFunction(); 5543 MachineFrameInfo &MFI = MF.getFrameInfo(); 5544 MFI.setReturnAddressIsTaken(true); 5545 5546 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5547 return SDValue(); 5548 5549 EVT VT = Op.getValueType(); 5550 SDLoc dl(Op); 5551 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5552 if (Depth) { 5553 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5554 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5555 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5556 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5557 MachinePointerInfo()); 5558 } 5559 5560 // Return LR, which contains the return address. Mark it an implicit live-in. 5561 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5562 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5563 } 5564 5565 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5566 const ARMBaseRegisterInfo &ARI = 5567 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5568 MachineFunction &MF = DAG.getMachineFunction(); 5569 MachineFrameInfo &MFI = MF.getFrameInfo(); 5570 MFI.setFrameAddressIsTaken(true); 5571 5572 EVT VT = Op.getValueType(); 5573 SDLoc dl(Op); // FIXME probably not meaningful 5574 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5575 Register FrameReg = ARI.getFrameRegister(MF); 5576 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5577 while (Depth--) 5578 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5579 MachinePointerInfo()); 5580 return FrameAddr; 5581 } 5582 5583 // FIXME? Maybe this could be a TableGen attribute on some registers and 5584 // this table could be generated automatically from RegInfo. 5585 Register ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5586 const MachineFunction &MF) const { 5587 Register Reg = StringSwitch<unsigned>(RegName) 5588 .Case("sp", ARM::SP) 5589 .Default(0); 5590 if (Reg) 5591 return Reg; 5592 report_fatal_error(Twine("Invalid register name \"" 5593 + StringRef(RegName) + "\".")); 5594 } 5595 5596 // Result is 64 bit value so split into two 32 bit values and return as a 5597 // pair of values. 5598 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5599 SelectionDAG &DAG) { 5600 SDLoc DL(N); 5601 5602 // This function is only supposed to be called for i64 type destination. 5603 assert(N->getValueType(0) == MVT::i64 5604 && "ExpandREAD_REGISTER called for non-i64 type result."); 5605 5606 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5607 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5608 N->getOperand(0), 5609 N->getOperand(1)); 5610 5611 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5612 Read.getValue(1))); 5613 Results.push_back(Read.getOperand(0)); 5614 } 5615 5616 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5617 /// When \p DstVT, the destination type of \p BC, is on the vector 5618 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5619 /// it might be possible to combine them, such that everything stays on the 5620 /// vector register bank. 5621 /// \p return The node that would replace \p BT, if the combine 5622 /// is possible. 5623 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5624 SelectionDAG &DAG) { 5625 SDValue Op = BC->getOperand(0); 5626 EVT DstVT = BC->getValueType(0); 5627 5628 // The only vector instruction that can produce a scalar (remember, 5629 // since the bitcast was about to be turned into VMOVDRR, the source 5630 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5631 // Moreover, we can do this combine only if there is one use. 5632 // Finally, if the destination type is not a vector, there is not 5633 // much point on forcing everything on the vector bank. 5634 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5635 !Op.hasOneUse()) 5636 return SDValue(); 5637 5638 // If the index is not constant, we will introduce an additional 5639 // multiply that will stick. 5640 // Give up in that case. 5641 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5642 if (!Index) 5643 return SDValue(); 5644 unsigned DstNumElt = DstVT.getVectorNumElements(); 5645 5646 // Compute the new index. 5647 const APInt &APIntIndex = Index->getAPIntValue(); 5648 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5649 NewIndex *= APIntIndex; 5650 // Check if the new constant index fits into i32. 5651 if (NewIndex.getBitWidth() > 32) 5652 return SDValue(); 5653 5654 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5655 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5656 SDLoc dl(Op); 5657 SDValue ExtractSrc = Op.getOperand(0); 5658 EVT VecVT = EVT::getVectorVT( 5659 *DAG.getContext(), DstVT.getScalarType(), 5660 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5661 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5662 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5663 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5664 } 5665 5666 /// ExpandBITCAST - If the target supports VFP, this function is called to 5667 /// expand a bit convert where either the source or destination type is i64 to 5668 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5669 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5670 /// vectors), since the legalizer won't know what to do with that. 5671 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5672 const ARMSubtarget *Subtarget) { 5673 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5674 SDLoc dl(N); 5675 SDValue Op = N->getOperand(0); 5676 5677 // This function is only supposed to be called for i64 types, either as the 5678 // source or destination of the bit convert. 5679 EVT SrcVT = Op.getValueType(); 5680 EVT DstVT = N->getValueType(0); 5681 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5682 5683 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5684 // FullFP16: half values are passed in S-registers, and we don't 5685 // need any of the bitcast and moves: 5686 // 5687 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5688 // t5: i32 = bitcast t2 5689 // t18: f16 = ARMISD::VMOVhr t5 5690 if (Op.getOpcode() != ISD::CopyFromReg || 5691 Op.getValueType() != MVT::f32) 5692 return SDValue(); 5693 5694 auto Move = N->use_begin(); 5695 if (Move->getOpcode() != ARMISD::VMOVhr) 5696 return SDValue(); 5697 5698 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5699 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5700 DAG.ReplaceAllUsesWith(*Move, &Copy); 5701 return Copy; 5702 } 5703 5704 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5705 if (!HasFullFP16) 5706 return SDValue(); 5707 // SoftFP: read half-precision arguments: 5708 // 5709 // t2: i32,ch = ... 5710 // t7: i16 = truncate t2 <~~~~ Op 5711 // t8: f16 = bitcast t7 <~~~~ N 5712 // 5713 if (Op.getOperand(0).getValueType() == MVT::i32) 5714 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5715 MVT::f16, Op.getOperand(0)); 5716 5717 return SDValue(); 5718 } 5719 5720 // Half-precision return values 5721 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5722 if (!HasFullFP16) 5723 return SDValue(); 5724 // 5725 // t11: f16 = fadd t8, t10 5726 // t12: i16 = bitcast t11 <~~~ SDNode N 5727 // t13: i32 = zero_extend t12 5728 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5729 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5730 // 5731 // transform this into: 5732 // 5733 // t20: i32 = ARMISD::VMOVrh t11 5734 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5735 // 5736 auto ZeroExtend = N->use_begin(); 5737 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5738 ZeroExtend->getValueType(0) != MVT::i32) 5739 return SDValue(); 5740 5741 auto Copy = ZeroExtend->use_begin(); 5742 if (Copy->getOpcode() == ISD::CopyToReg && 5743 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5744 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5745 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5746 return Cvt; 5747 } 5748 return SDValue(); 5749 } 5750 5751 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5752 return SDValue(); 5753 5754 // Turn i64->f64 into VMOVDRR. 5755 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5756 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5757 // if we can combine the bitcast with its source. 5758 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5759 return Val; 5760 5761 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5762 DAG.getConstant(0, dl, MVT::i32)); 5763 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5764 DAG.getConstant(1, dl, MVT::i32)); 5765 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5766 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5767 } 5768 5769 // Turn f64->i64 into VMOVRRD. 5770 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5771 SDValue Cvt; 5772 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5773 SrcVT.getVectorNumElements() > 1) 5774 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5775 DAG.getVTList(MVT::i32, MVT::i32), 5776 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5777 else 5778 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5779 DAG.getVTList(MVT::i32, MVT::i32), Op); 5780 // Merge the pieces into a single i64 value. 5781 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5782 } 5783 5784 return SDValue(); 5785 } 5786 5787 /// getZeroVector - Returns a vector of specified type with all zero elements. 5788 /// Zero vectors are used to represent vector negation and in those cases 5789 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5790 /// not support i64 elements, so sometimes the zero vectors will need to be 5791 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5792 /// zero vector. 5793 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5794 assert(VT.isVector() && "Expected a vector type"); 5795 // The canonical modified immediate encoding of a zero vector is....0! 5796 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5797 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5798 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5799 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5800 } 5801 5802 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5803 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5804 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5805 SelectionDAG &DAG) const { 5806 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5807 EVT VT = Op.getValueType(); 5808 unsigned VTBits = VT.getSizeInBits(); 5809 SDLoc dl(Op); 5810 SDValue ShOpLo = Op.getOperand(0); 5811 SDValue ShOpHi = Op.getOperand(1); 5812 SDValue ShAmt = Op.getOperand(2); 5813 SDValue ARMcc; 5814 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5815 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5816 5817 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5818 5819 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5820 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5821 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5822 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5823 DAG.getConstant(VTBits, dl, MVT::i32)); 5824 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5825 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5826 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5827 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5828 ISD::SETGE, ARMcc, DAG, dl); 5829 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5830 ARMcc, CCR, CmpLo); 5831 5832 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5833 SDValue HiBigShift = Opc == ISD::SRA 5834 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5835 DAG.getConstant(VTBits - 1, dl, VT)) 5836 : DAG.getConstant(0, dl, VT); 5837 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5838 ISD::SETGE, ARMcc, DAG, dl); 5839 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5840 ARMcc, CCR, CmpHi); 5841 5842 SDValue Ops[2] = { Lo, Hi }; 5843 return DAG.getMergeValues(Ops, dl); 5844 } 5845 5846 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5847 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5848 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5849 SelectionDAG &DAG) const { 5850 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5851 EVT VT = Op.getValueType(); 5852 unsigned VTBits = VT.getSizeInBits(); 5853 SDLoc dl(Op); 5854 SDValue ShOpLo = Op.getOperand(0); 5855 SDValue ShOpHi = Op.getOperand(1); 5856 SDValue ShAmt = Op.getOperand(2); 5857 SDValue ARMcc; 5858 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5859 5860 assert(Op.getOpcode() == ISD::SHL_PARTS); 5861 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5862 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5863 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5864 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5865 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5866 5867 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5868 DAG.getConstant(VTBits, dl, MVT::i32)); 5869 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5870 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5871 ISD::SETGE, ARMcc, DAG, dl); 5872 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5873 ARMcc, CCR, CmpHi); 5874 5875 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5876 ISD::SETGE, ARMcc, DAG, dl); 5877 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5878 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5879 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5880 5881 SDValue Ops[2] = { Lo, Hi }; 5882 return DAG.getMergeValues(Ops, dl); 5883 } 5884 5885 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5886 SelectionDAG &DAG) const { 5887 // The rounding mode is in bits 23:22 of the FPSCR. 5888 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5889 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5890 // so that the shift + and get folded into a bitfield extract. 5891 SDLoc dl(Op); 5892 SDValue Ops[] = { DAG.getEntryNode(), 5893 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5894 5895 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5896 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5897 DAG.getConstant(1U << 22, dl, MVT::i32)); 5898 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5899 DAG.getConstant(22, dl, MVT::i32)); 5900 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5901 DAG.getConstant(3, dl, MVT::i32)); 5902 } 5903 5904 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5905 const ARMSubtarget *ST) { 5906 SDLoc dl(N); 5907 EVT VT = N->getValueType(0); 5908 if (VT.isVector() && ST->hasNEON()) { 5909 5910 // Compute the least significant set bit: LSB = X & -X 5911 SDValue X = N->getOperand(0); 5912 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5913 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5914 5915 EVT ElemTy = VT.getVectorElementType(); 5916 5917 if (ElemTy == MVT::i8) { 5918 // Compute with: cttz(x) = ctpop(lsb - 1) 5919 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5920 DAG.getTargetConstant(1, dl, ElemTy)); 5921 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5922 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5923 } 5924 5925 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5926 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5927 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5928 unsigned NumBits = ElemTy.getSizeInBits(); 5929 SDValue WidthMinus1 = 5930 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5931 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5932 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5933 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5934 } 5935 5936 // Compute with: cttz(x) = ctpop(lsb - 1) 5937 5938 // Compute LSB - 1. 5939 SDValue Bits; 5940 if (ElemTy == MVT::i64) { 5941 // Load constant 0xffff'ffff'ffff'ffff to register. 5942 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5943 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5944 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5945 } else { 5946 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5947 DAG.getTargetConstant(1, dl, ElemTy)); 5948 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5949 } 5950 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5951 } 5952 5953 if (!ST->hasV6T2Ops()) 5954 return SDValue(); 5955 5956 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5957 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5958 } 5959 5960 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5961 const ARMSubtarget *ST) { 5962 EVT VT = N->getValueType(0); 5963 SDLoc DL(N); 5964 5965 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5966 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5967 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5968 "Unexpected type for custom ctpop lowering"); 5969 5970 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5971 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5972 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 5973 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 5974 5975 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5976 unsigned EltSize = 8; 5977 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5978 while (EltSize != VT.getScalarSizeInBits()) { 5979 SmallVector<SDValue, 8> Ops; 5980 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 5981 TLI.getPointerTy(DAG.getDataLayout()))); 5982 Ops.push_back(Res); 5983 5984 EltSize *= 2; 5985 NumElts /= 2; 5986 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5987 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 5988 } 5989 5990 return Res; 5991 } 5992 5993 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 5994 /// operand of a vector shift operation, where all the elements of the 5995 /// build_vector must have the same constant integer value. 5996 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 5997 // Ignore bit_converts. 5998 while (Op.getOpcode() == ISD::BITCAST) 5999 Op = Op.getOperand(0); 6000 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6001 APInt SplatBits, SplatUndef; 6002 unsigned SplatBitSize; 6003 bool HasAnyUndefs; 6004 if (!BVN || 6005 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 6006 ElementBits) || 6007 SplatBitSize > ElementBits) 6008 return false; 6009 Cnt = SplatBits.getSExtValue(); 6010 return true; 6011 } 6012 6013 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6014 /// operand of a vector shift left operation. That value must be in the range: 6015 /// 0 <= Value < ElementBits for a left shift; or 6016 /// 0 <= Value <= ElementBits for a long left shift. 6017 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6018 assert(VT.isVector() && "vector shift count is not a vector type"); 6019 int64_t ElementBits = VT.getScalarSizeInBits(); 6020 if (!getVShiftImm(Op, ElementBits, Cnt)) 6021 return false; 6022 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6023 } 6024 6025 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6026 /// operand of a vector shift right operation. For a shift opcode, the value 6027 /// is positive, but for an intrinsic the value count must be negative. The 6028 /// absolute value must be in the range: 6029 /// 1 <= |Value| <= ElementBits for a right shift; or 6030 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 6031 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 6032 int64_t &Cnt) { 6033 assert(VT.isVector() && "vector shift count is not a vector type"); 6034 int64_t ElementBits = VT.getScalarSizeInBits(); 6035 if (!getVShiftImm(Op, ElementBits, Cnt)) 6036 return false; 6037 if (!isIntrinsic) 6038 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6039 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 6040 Cnt = -Cnt; 6041 return true; 6042 } 6043 return false; 6044 } 6045 6046 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 6047 const ARMSubtarget *ST) { 6048 EVT VT = N->getValueType(0); 6049 SDLoc dl(N); 6050 int64_t Cnt; 6051 6052 if (!VT.isVector()) 6053 return SDValue(); 6054 6055 // We essentially have two forms here. Shift by an immediate and shift by a 6056 // vector register (there are also shift by a gpr, but that is just handled 6057 // with a tablegen pattern). We cannot easily match shift by an immediate in 6058 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 6059 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 6060 // signed or unsigned, and a negative shift indicates a shift right). 6061 if (N->getOpcode() == ISD::SHL) { 6062 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 6063 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 6064 DAG.getConstant(Cnt, dl, MVT::i32)); 6065 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 6066 N->getOperand(1)); 6067 } 6068 6069 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 6070 "unexpected vector shift opcode"); 6071 6072 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 6073 unsigned VShiftOpc = 6074 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 6075 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 6076 DAG.getConstant(Cnt, dl, MVT::i32)); 6077 } 6078 6079 // Other right shifts we don't have operations for (we use a shift left by a 6080 // negative number). 6081 EVT ShiftVT = N->getOperand(1).getValueType(); 6082 SDValue NegatedCount = DAG.getNode( 6083 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 6084 unsigned VShiftOpc = 6085 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 6086 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 6087 } 6088 6089 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 6090 const ARMSubtarget *ST) { 6091 EVT VT = N->getValueType(0); 6092 SDLoc dl(N); 6093 6094 // We can get here for a node like i32 = ISD::SHL i32, i64 6095 if (VT != MVT::i64) 6096 return SDValue(); 6097 6098 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 6099 N->getOpcode() == ISD::SHL) && 6100 "Unknown shift to lower!"); 6101 6102 unsigned ShOpc = N->getOpcode(); 6103 if (ST->hasMVEIntegerOps()) { 6104 SDValue ShAmt = N->getOperand(1); 6105 unsigned ShPartsOpc = ARMISD::LSLL; 6106 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 6107 6108 // If the shift amount is greater than 32 or has a greater bitwidth than 64 6109 // then do the default optimisation 6110 if (ShAmt->getValueType(0).getSizeInBits() > 64 || 6111 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32))) 6112 return SDValue(); 6113 6114 // Extract the lower 32 bits of the shift amount if it's not an i32 6115 if (ShAmt->getValueType(0) != MVT::i32) 6116 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32); 6117 6118 if (ShOpc == ISD::SRL) { 6119 if (!Con) 6120 // There is no t2LSRLr instruction so negate and perform an lsll if the 6121 // shift amount is in a register, emulating a right shift. 6122 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6123 DAG.getConstant(0, dl, MVT::i32), ShAmt); 6124 else 6125 // Else generate an lsrl on the immediate shift amount 6126 ShPartsOpc = ARMISD::LSRL; 6127 } else if (ShOpc == ISD::SRA) 6128 ShPartsOpc = ARMISD::ASRL; 6129 6130 // Lower 32 bits of the destination/source 6131 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6132 DAG.getConstant(0, dl, MVT::i32)); 6133 // Upper 32 bits of the destination/source 6134 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6135 DAG.getConstant(1, dl, MVT::i32)); 6136 6137 // Generate the shift operation as computed above 6138 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 6139 ShAmt); 6140 // The upper 32 bits come from the second return value of lsll 6141 Hi = SDValue(Lo.getNode(), 1); 6142 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6143 } 6144 6145 // We only lower SRA, SRL of 1 here, all others use generic lowering. 6146 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 6147 return SDValue(); 6148 6149 // If we are in thumb mode, we don't have RRX. 6150 if (ST->isThumb1Only()) 6151 return SDValue(); 6152 6153 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 6154 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6155 DAG.getConstant(0, dl, MVT::i32)); 6156 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6157 DAG.getConstant(1, dl, MVT::i32)); 6158 6159 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 6160 // captures the result into a carry flag. 6161 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 6162 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 6163 6164 // The low part is an ARMISD::RRX operand, which shifts the carry in. 6165 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 6166 6167 // Merge the pieces into a single i64 value. 6168 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6169 } 6170 6171 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 6172 const ARMSubtarget *ST) { 6173 bool Invert = false; 6174 bool Swap = false; 6175 unsigned Opc = ARMCC::AL; 6176 6177 SDValue Op0 = Op.getOperand(0); 6178 SDValue Op1 = Op.getOperand(1); 6179 SDValue CC = Op.getOperand(2); 6180 EVT VT = Op.getValueType(); 6181 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 6182 SDLoc dl(Op); 6183 6184 EVT CmpVT; 6185 if (ST->hasNEON()) 6186 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 6187 else { 6188 assert(ST->hasMVEIntegerOps() && 6189 "No hardware support for integer vector comparison!"); 6190 6191 if (Op.getValueType().getVectorElementType() != MVT::i1) 6192 return SDValue(); 6193 6194 // Make sure we expand floating point setcc to scalar if we do not have 6195 // mve.fp, so that we can handle them from there. 6196 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 6197 return SDValue(); 6198 6199 CmpVT = VT; 6200 } 6201 6202 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 6203 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 6204 // Special-case integer 64-bit equality comparisons. They aren't legal, 6205 // but they can be lowered with a few vector instructions. 6206 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 6207 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 6208 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 6209 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 6210 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 6211 DAG.getCondCode(ISD::SETEQ)); 6212 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 6213 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 6214 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 6215 if (SetCCOpcode == ISD::SETNE) 6216 Merged = DAG.getNOT(dl, Merged, CmpVT); 6217 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 6218 return Merged; 6219 } 6220 6221 if (CmpVT.getVectorElementType() == MVT::i64) 6222 // 64-bit comparisons are not legal in general. 6223 return SDValue(); 6224 6225 if (Op1.getValueType().isFloatingPoint()) { 6226 switch (SetCCOpcode) { 6227 default: llvm_unreachable("Illegal FP comparison"); 6228 case ISD::SETUNE: 6229 case ISD::SETNE: 6230 if (ST->hasMVEFloatOps()) { 6231 Opc = ARMCC::NE; break; 6232 } else { 6233 Invert = true; LLVM_FALLTHROUGH; 6234 } 6235 case ISD::SETOEQ: 6236 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6237 case ISD::SETOLT: 6238 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6239 case ISD::SETOGT: 6240 case ISD::SETGT: Opc = ARMCC::GT; break; 6241 case ISD::SETOLE: 6242 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6243 case ISD::SETOGE: 6244 case ISD::SETGE: Opc = ARMCC::GE; break; 6245 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6246 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6247 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6248 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6249 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6250 case ISD::SETONE: { 6251 // Expand this to (OLT | OGT). 6252 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6253 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6254 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6255 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6256 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6257 if (Invert) 6258 Result = DAG.getNOT(dl, Result, VT); 6259 return Result; 6260 } 6261 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6262 case ISD::SETO: { 6263 // Expand this to (OLT | OGE). 6264 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6265 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6266 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6267 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6268 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6269 if (Invert) 6270 Result = DAG.getNOT(dl, Result, VT); 6271 return Result; 6272 } 6273 } 6274 } else { 6275 // Integer comparisons. 6276 switch (SetCCOpcode) { 6277 default: llvm_unreachable("Illegal integer comparison"); 6278 case ISD::SETNE: 6279 if (ST->hasMVEIntegerOps()) { 6280 Opc = ARMCC::NE; break; 6281 } else { 6282 Invert = true; LLVM_FALLTHROUGH; 6283 } 6284 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6285 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6286 case ISD::SETGT: Opc = ARMCC::GT; break; 6287 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6288 case ISD::SETGE: Opc = ARMCC::GE; break; 6289 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6290 case ISD::SETUGT: Opc = ARMCC::HI; break; 6291 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6292 case ISD::SETUGE: Opc = ARMCC::HS; break; 6293 } 6294 6295 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6296 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6297 SDValue AndOp; 6298 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6299 AndOp = Op0; 6300 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6301 AndOp = Op1; 6302 6303 // Ignore bitconvert. 6304 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6305 AndOp = AndOp.getOperand(0); 6306 6307 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6308 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6309 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6310 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6311 if (!Invert) 6312 Result = DAG.getNOT(dl, Result, VT); 6313 return Result; 6314 } 6315 } 6316 } 6317 6318 if (Swap) 6319 std::swap(Op0, Op1); 6320 6321 // If one of the operands is a constant vector zero, attempt to fold the 6322 // comparison to a specialized compare-against-zero form. 6323 SDValue SingleOp; 6324 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6325 SingleOp = Op0; 6326 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6327 if (Opc == ARMCC::GE) 6328 Opc = ARMCC::LE; 6329 else if (Opc == ARMCC::GT) 6330 Opc = ARMCC::LT; 6331 SingleOp = Op1; 6332 } 6333 6334 SDValue Result; 6335 if (SingleOp.getNode()) { 6336 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6337 DAG.getConstant(Opc, dl, MVT::i32)); 6338 } else { 6339 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6340 DAG.getConstant(Opc, dl, MVT::i32)); 6341 } 6342 6343 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6344 6345 if (Invert) 6346 Result = DAG.getNOT(dl, Result, VT); 6347 6348 return Result; 6349 } 6350 6351 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6352 SDValue LHS = Op.getOperand(0); 6353 SDValue RHS = Op.getOperand(1); 6354 SDValue Carry = Op.getOperand(2); 6355 SDValue Cond = Op.getOperand(3); 6356 SDLoc DL(Op); 6357 6358 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6359 6360 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6361 // have to invert the carry first. 6362 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6363 DAG.getConstant(1, DL, MVT::i32), Carry); 6364 // This converts the boolean value carry into the carry flag. 6365 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6366 6367 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6368 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6369 6370 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6371 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6372 SDValue ARMcc = DAG.getConstant( 6373 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6374 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6375 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6376 Cmp.getValue(1), SDValue()); 6377 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6378 CCR, Chain.getValue(1)); 6379 } 6380 6381 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6382 /// valid vector constant for a NEON or MVE instruction with a "modified 6383 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6384 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6385 unsigned SplatBitSize, SelectionDAG &DAG, 6386 const SDLoc &dl, EVT &VT, bool is128Bits, 6387 VMOVModImmType type) { 6388 unsigned OpCmode, Imm; 6389 6390 // SplatBitSize is set to the smallest size that splats the vector, so a 6391 // zero vector will always have SplatBitSize == 8. However, NEON modified 6392 // immediate instructions others than VMOV do not support the 8-bit encoding 6393 // of a zero vector, and the default encoding of zero is supposed to be the 6394 // 32-bit version. 6395 if (SplatBits == 0) 6396 SplatBitSize = 32; 6397 6398 switch (SplatBitSize) { 6399 case 8: 6400 if (type != VMOVModImm) 6401 return SDValue(); 6402 // Any 1-byte value is OK. Op=0, Cmode=1110. 6403 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6404 OpCmode = 0xe; 6405 Imm = SplatBits; 6406 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6407 break; 6408 6409 case 16: 6410 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6411 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6412 if ((SplatBits & ~0xff) == 0) { 6413 // Value = 0x00nn: Op=x, Cmode=100x. 6414 OpCmode = 0x8; 6415 Imm = SplatBits; 6416 break; 6417 } 6418 if ((SplatBits & ~0xff00) == 0) { 6419 // Value = 0xnn00: Op=x, Cmode=101x. 6420 OpCmode = 0xa; 6421 Imm = SplatBits >> 8; 6422 break; 6423 } 6424 return SDValue(); 6425 6426 case 32: 6427 // NEON's 32-bit VMOV supports splat values where: 6428 // * only one byte is nonzero, or 6429 // * the least significant byte is 0xff and the second byte is nonzero, or 6430 // * the least significant 2 bytes are 0xff and the third is nonzero. 6431 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6432 if ((SplatBits & ~0xff) == 0) { 6433 // Value = 0x000000nn: Op=x, Cmode=000x. 6434 OpCmode = 0; 6435 Imm = SplatBits; 6436 break; 6437 } 6438 if ((SplatBits & ~0xff00) == 0) { 6439 // Value = 0x0000nn00: Op=x, Cmode=001x. 6440 OpCmode = 0x2; 6441 Imm = SplatBits >> 8; 6442 break; 6443 } 6444 if ((SplatBits & ~0xff0000) == 0) { 6445 // Value = 0x00nn0000: Op=x, Cmode=010x. 6446 OpCmode = 0x4; 6447 Imm = SplatBits >> 16; 6448 break; 6449 } 6450 if ((SplatBits & ~0xff000000) == 0) { 6451 // Value = 0xnn000000: Op=x, Cmode=011x. 6452 OpCmode = 0x6; 6453 Imm = SplatBits >> 24; 6454 break; 6455 } 6456 6457 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6458 if (type == OtherModImm) return SDValue(); 6459 6460 if ((SplatBits & ~0xffff) == 0 && 6461 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6462 // Value = 0x0000nnff: Op=x, Cmode=1100. 6463 OpCmode = 0xc; 6464 Imm = SplatBits >> 8; 6465 break; 6466 } 6467 6468 // cmode == 0b1101 is not supported for MVE VMVN 6469 if (type == MVEVMVNModImm) 6470 return SDValue(); 6471 6472 if ((SplatBits & ~0xffffff) == 0 && 6473 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6474 // Value = 0x00nnffff: Op=x, Cmode=1101. 6475 OpCmode = 0xd; 6476 Imm = SplatBits >> 16; 6477 break; 6478 } 6479 6480 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6481 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6482 // VMOV.I32. A (very) minor optimization would be to replicate the value 6483 // and fall through here to test for a valid 64-bit splat. But, then the 6484 // caller would also need to check and handle the change in size. 6485 return SDValue(); 6486 6487 case 64: { 6488 if (type != VMOVModImm) 6489 return SDValue(); 6490 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6491 uint64_t BitMask = 0xff; 6492 uint64_t Val = 0; 6493 unsigned ImmMask = 1; 6494 Imm = 0; 6495 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6496 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6497 Val |= BitMask; 6498 Imm |= ImmMask; 6499 } else if ((SplatBits & BitMask) != 0) { 6500 return SDValue(); 6501 } 6502 BitMask <<= 8; 6503 ImmMask <<= 1; 6504 } 6505 6506 if (DAG.getDataLayout().isBigEndian()) 6507 // swap higher and lower 32 bit word 6508 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 6509 6510 // Op=1, Cmode=1110. 6511 OpCmode = 0x1e; 6512 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6513 break; 6514 } 6515 6516 default: 6517 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6518 } 6519 6520 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6521 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6522 } 6523 6524 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6525 const ARMSubtarget *ST) const { 6526 EVT VT = Op.getValueType(); 6527 bool IsDouble = (VT == MVT::f64); 6528 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6529 const APFloat &FPVal = CFP->getValueAPF(); 6530 6531 // Prevent floating-point constants from using literal loads 6532 // when execute-only is enabled. 6533 if (ST->genExecuteOnly()) { 6534 // If we can represent the constant as an immediate, don't lower it 6535 if (isFPImmLegal(FPVal, VT)) 6536 return Op; 6537 // Otherwise, construct as integer, and move to float register 6538 APInt INTVal = FPVal.bitcastToAPInt(); 6539 SDLoc DL(CFP); 6540 switch (VT.getSimpleVT().SimpleTy) { 6541 default: 6542 llvm_unreachable("Unknown floating point type!"); 6543 break; 6544 case MVT::f64: { 6545 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6546 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6547 if (!ST->isLittle()) 6548 std::swap(Lo, Hi); 6549 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6550 } 6551 case MVT::f32: 6552 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6553 DAG.getConstant(INTVal, DL, MVT::i32)); 6554 } 6555 } 6556 6557 if (!ST->hasVFP3Base()) 6558 return SDValue(); 6559 6560 // Use the default (constant pool) lowering for double constants when we have 6561 // an SP-only FPU 6562 if (IsDouble && !Subtarget->hasFP64()) 6563 return SDValue(); 6564 6565 // Try splatting with a VMOV.f32... 6566 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6567 6568 if (ImmVal != -1) { 6569 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6570 // We have code in place to select a valid ConstantFP already, no need to 6571 // do any mangling. 6572 return Op; 6573 } 6574 6575 // It's a float and we are trying to use NEON operations where 6576 // possible. Lower it to a splat followed by an extract. 6577 SDLoc DL(Op); 6578 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6579 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6580 NewVal); 6581 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6582 DAG.getConstant(0, DL, MVT::i32)); 6583 } 6584 6585 // The rest of our options are NEON only, make sure that's allowed before 6586 // proceeding.. 6587 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6588 return SDValue(); 6589 6590 EVT VMovVT; 6591 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6592 6593 // It wouldn't really be worth bothering for doubles except for one very 6594 // important value, which does happen to match: 0.0. So make sure we don't do 6595 // anything stupid. 6596 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6597 return SDValue(); 6598 6599 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6600 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6601 VMovVT, false, VMOVModImm); 6602 if (NewVal != SDValue()) { 6603 SDLoc DL(Op); 6604 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6605 NewVal); 6606 if (IsDouble) 6607 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6608 6609 // It's a float: cast and extract a vector element. 6610 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6611 VecConstant); 6612 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6613 DAG.getConstant(0, DL, MVT::i32)); 6614 } 6615 6616 // Finally, try a VMVN.i32 6617 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6618 false, VMVNModImm); 6619 if (NewVal != SDValue()) { 6620 SDLoc DL(Op); 6621 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6622 6623 if (IsDouble) 6624 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6625 6626 // It's a float: cast and extract a vector element. 6627 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6628 VecConstant); 6629 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6630 DAG.getConstant(0, DL, MVT::i32)); 6631 } 6632 6633 return SDValue(); 6634 } 6635 6636 // check if an VEXT instruction can handle the shuffle mask when the 6637 // vector sources of the shuffle are the same. 6638 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6639 unsigned NumElts = VT.getVectorNumElements(); 6640 6641 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6642 if (M[0] < 0) 6643 return false; 6644 6645 Imm = M[0]; 6646 6647 // If this is a VEXT shuffle, the immediate value is the index of the first 6648 // element. The other shuffle indices must be the successive elements after 6649 // the first one. 6650 unsigned ExpectedElt = Imm; 6651 for (unsigned i = 1; i < NumElts; ++i) { 6652 // Increment the expected index. If it wraps around, just follow it 6653 // back to index zero and keep going. 6654 ++ExpectedElt; 6655 if (ExpectedElt == NumElts) 6656 ExpectedElt = 0; 6657 6658 if (M[i] < 0) continue; // ignore UNDEF indices 6659 if (ExpectedElt != static_cast<unsigned>(M[i])) 6660 return false; 6661 } 6662 6663 return true; 6664 } 6665 6666 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6667 bool &ReverseVEXT, unsigned &Imm) { 6668 unsigned NumElts = VT.getVectorNumElements(); 6669 ReverseVEXT = false; 6670 6671 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6672 if (M[0] < 0) 6673 return false; 6674 6675 Imm = M[0]; 6676 6677 // If this is a VEXT shuffle, the immediate value is the index of the first 6678 // element. The other shuffle indices must be the successive elements after 6679 // the first one. 6680 unsigned ExpectedElt = Imm; 6681 for (unsigned i = 1; i < NumElts; ++i) { 6682 // Increment the expected index. If it wraps around, it may still be 6683 // a VEXT but the source vectors must be swapped. 6684 ExpectedElt += 1; 6685 if (ExpectedElt == NumElts * 2) { 6686 ExpectedElt = 0; 6687 ReverseVEXT = true; 6688 } 6689 6690 if (M[i] < 0) continue; // ignore UNDEF indices 6691 if (ExpectedElt != static_cast<unsigned>(M[i])) 6692 return false; 6693 } 6694 6695 // Adjust the index value if the source operands will be swapped. 6696 if (ReverseVEXT) 6697 Imm -= NumElts; 6698 6699 return true; 6700 } 6701 6702 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6703 /// instruction with the specified blocksize. (The order of the elements 6704 /// within each block of the vector is reversed.) 6705 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6706 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6707 "Only possible block sizes for VREV are: 16, 32, 64"); 6708 6709 unsigned EltSz = VT.getScalarSizeInBits(); 6710 if (EltSz == 64) 6711 return false; 6712 6713 unsigned NumElts = VT.getVectorNumElements(); 6714 unsigned BlockElts = M[0] + 1; 6715 // If the first shuffle index is UNDEF, be optimistic. 6716 if (M[0] < 0) 6717 BlockElts = BlockSize / EltSz; 6718 6719 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6720 return false; 6721 6722 for (unsigned i = 0; i < NumElts; ++i) { 6723 if (M[i] < 0) continue; // ignore UNDEF indices 6724 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6725 return false; 6726 } 6727 6728 return true; 6729 } 6730 6731 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6732 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6733 // range, then 0 is placed into the resulting vector. So pretty much any mask 6734 // of 8 elements can work here. 6735 return VT == MVT::v8i8 && M.size() == 8; 6736 } 6737 6738 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6739 unsigned Index) { 6740 if (Mask.size() == Elements * 2) 6741 return Index / Elements; 6742 return Mask[Index] == 0 ? 0 : 1; 6743 } 6744 6745 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6746 // checking that pairs of elements in the shuffle mask represent the same index 6747 // in each vector, incrementing the expected index by 2 at each step. 6748 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6749 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6750 // v2={e,f,g,h} 6751 // WhichResult gives the offset for each element in the mask based on which 6752 // of the two results it belongs to. 6753 // 6754 // The transpose can be represented either as: 6755 // result1 = shufflevector v1, v2, result1_shuffle_mask 6756 // result2 = shufflevector v1, v2, result2_shuffle_mask 6757 // where v1/v2 and the shuffle masks have the same number of elements 6758 // (here WhichResult (see below) indicates which result is being checked) 6759 // 6760 // or as: 6761 // results = shufflevector v1, v2, shuffle_mask 6762 // where both results are returned in one vector and the shuffle mask has twice 6763 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6764 // want to check the low half and high half of the shuffle mask as if it were 6765 // the other case 6766 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6767 unsigned EltSz = VT.getScalarSizeInBits(); 6768 if (EltSz == 64) 6769 return false; 6770 6771 unsigned NumElts = VT.getVectorNumElements(); 6772 if (M.size() != NumElts && M.size() != NumElts*2) 6773 return false; 6774 6775 // If the mask is twice as long as the input vector then we need to check the 6776 // upper and lower parts of the mask with a matching value for WhichResult 6777 // FIXME: A mask with only even values will be rejected in case the first 6778 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6779 // M[0] is used to determine WhichResult 6780 for (unsigned i = 0; i < M.size(); i += NumElts) { 6781 WhichResult = SelectPairHalf(NumElts, M, i); 6782 for (unsigned j = 0; j < NumElts; j += 2) { 6783 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6784 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6785 return false; 6786 } 6787 } 6788 6789 if (M.size() == NumElts*2) 6790 WhichResult = 0; 6791 6792 return true; 6793 } 6794 6795 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6796 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6797 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6798 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6799 unsigned EltSz = VT.getScalarSizeInBits(); 6800 if (EltSz == 64) 6801 return false; 6802 6803 unsigned NumElts = VT.getVectorNumElements(); 6804 if (M.size() != NumElts && M.size() != NumElts*2) 6805 return false; 6806 6807 for (unsigned i = 0; i < M.size(); i += NumElts) { 6808 WhichResult = SelectPairHalf(NumElts, M, i); 6809 for (unsigned j = 0; j < NumElts; j += 2) { 6810 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6811 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6812 return false; 6813 } 6814 } 6815 6816 if (M.size() == NumElts*2) 6817 WhichResult = 0; 6818 6819 return true; 6820 } 6821 6822 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6823 // that the mask elements are either all even and in steps of size 2 or all odd 6824 // and in steps of size 2. 6825 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6826 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6827 // v2={e,f,g,h} 6828 // Requires similar checks to that of isVTRNMask with 6829 // respect the how results are returned. 6830 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6831 unsigned EltSz = VT.getScalarSizeInBits(); 6832 if (EltSz == 64) 6833 return false; 6834 6835 unsigned NumElts = VT.getVectorNumElements(); 6836 if (M.size() != NumElts && M.size() != NumElts*2) 6837 return false; 6838 6839 for (unsigned i = 0; i < M.size(); i += NumElts) { 6840 WhichResult = SelectPairHalf(NumElts, M, i); 6841 for (unsigned j = 0; j < NumElts; ++j) { 6842 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6843 return false; 6844 } 6845 } 6846 6847 if (M.size() == NumElts*2) 6848 WhichResult = 0; 6849 6850 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6851 if (VT.is64BitVector() && EltSz == 32) 6852 return false; 6853 6854 return true; 6855 } 6856 6857 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6858 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6859 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6860 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6861 unsigned EltSz = VT.getScalarSizeInBits(); 6862 if (EltSz == 64) 6863 return false; 6864 6865 unsigned NumElts = VT.getVectorNumElements(); 6866 if (M.size() != NumElts && M.size() != NumElts*2) 6867 return false; 6868 6869 unsigned Half = NumElts / 2; 6870 for (unsigned i = 0; i < M.size(); i += NumElts) { 6871 WhichResult = SelectPairHalf(NumElts, M, i); 6872 for (unsigned j = 0; j < NumElts; j += Half) { 6873 unsigned Idx = WhichResult; 6874 for (unsigned k = 0; k < Half; ++k) { 6875 int MIdx = M[i + j + k]; 6876 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6877 return false; 6878 Idx += 2; 6879 } 6880 } 6881 } 6882 6883 if (M.size() == NumElts*2) 6884 WhichResult = 0; 6885 6886 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6887 if (VT.is64BitVector() && EltSz == 32) 6888 return false; 6889 6890 return true; 6891 } 6892 6893 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6894 // that pairs of elements of the shufflemask represent the same index in each 6895 // vector incrementing sequentially through the vectors. 6896 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6897 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6898 // v2={e,f,g,h} 6899 // Requires similar checks to that of isVTRNMask with respect the how results 6900 // are returned. 6901 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6902 unsigned EltSz = VT.getScalarSizeInBits(); 6903 if (EltSz == 64) 6904 return false; 6905 6906 unsigned NumElts = VT.getVectorNumElements(); 6907 if (M.size() != NumElts && M.size() != NumElts*2) 6908 return false; 6909 6910 for (unsigned i = 0; i < M.size(); i += NumElts) { 6911 WhichResult = SelectPairHalf(NumElts, M, i); 6912 unsigned Idx = WhichResult * NumElts / 2; 6913 for (unsigned j = 0; j < NumElts; j += 2) { 6914 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6915 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6916 return false; 6917 Idx += 1; 6918 } 6919 } 6920 6921 if (M.size() == NumElts*2) 6922 WhichResult = 0; 6923 6924 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6925 if (VT.is64BitVector() && EltSz == 32) 6926 return false; 6927 6928 return true; 6929 } 6930 6931 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6932 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6933 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6934 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6935 unsigned EltSz = VT.getScalarSizeInBits(); 6936 if (EltSz == 64) 6937 return false; 6938 6939 unsigned NumElts = VT.getVectorNumElements(); 6940 if (M.size() != NumElts && M.size() != NumElts*2) 6941 return false; 6942 6943 for (unsigned i = 0; i < M.size(); i += NumElts) { 6944 WhichResult = SelectPairHalf(NumElts, M, i); 6945 unsigned Idx = WhichResult * NumElts / 2; 6946 for (unsigned j = 0; j < NumElts; j += 2) { 6947 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6948 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6949 return false; 6950 Idx += 1; 6951 } 6952 } 6953 6954 if (M.size() == NumElts*2) 6955 WhichResult = 0; 6956 6957 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6958 if (VT.is64BitVector() && EltSz == 32) 6959 return false; 6960 6961 return true; 6962 } 6963 6964 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6965 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6966 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6967 unsigned &WhichResult, 6968 bool &isV_UNDEF) { 6969 isV_UNDEF = false; 6970 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6971 return ARMISD::VTRN; 6972 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6973 return ARMISD::VUZP; 6974 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6975 return ARMISD::VZIP; 6976 6977 isV_UNDEF = true; 6978 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6979 return ARMISD::VTRN; 6980 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6981 return ARMISD::VUZP; 6982 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6983 return ARMISD::VZIP; 6984 6985 return 0; 6986 } 6987 6988 /// \return true if this is a reverse operation on an vector. 6989 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6990 unsigned NumElts = VT.getVectorNumElements(); 6991 // Make sure the mask has the right size. 6992 if (NumElts != M.size()) 6993 return false; 6994 6995 // Look for <15, ..., 3, -1, 1, 0>. 6996 for (unsigned i = 0; i != NumElts; ++i) 6997 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6998 return false; 6999 7000 return true; 7001 } 7002 7003 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) { 7004 unsigned NumElts = VT.getVectorNumElements(); 7005 // Make sure the mask has the right size. 7006 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8)) 7007 return false; 7008 7009 // If Top 7010 // Look for <0, N, 2, N+2, 4, N+4, ..>. 7011 // This inserts Input2 into Input1 7012 // else if not Top 7013 // Look for <0, N+1, 2, N+3, 4, N+5, ..> 7014 // This inserts Input1 into Input2 7015 unsigned Offset = Top ? 0 : 1; 7016 for (unsigned i = 0; i < NumElts; i+=2) { 7017 if (M[i] >= 0 && M[i] != (int)i) 7018 return false; 7019 if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset)) 7020 return false; 7021 } 7022 7023 return true; 7024 } 7025 7026 // If N is an integer constant that can be moved into a register in one 7027 // instruction, return an SDValue of such a constant (will become a MOV 7028 // instruction). Otherwise return null. 7029 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 7030 const ARMSubtarget *ST, const SDLoc &dl) { 7031 uint64_t Val; 7032 if (!isa<ConstantSDNode>(N)) 7033 return SDValue(); 7034 Val = cast<ConstantSDNode>(N)->getZExtValue(); 7035 7036 if (ST->isThumb1Only()) { 7037 if (Val <= 255 || ~Val <= 255) 7038 return DAG.getConstant(Val, dl, MVT::i32); 7039 } else { 7040 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 7041 return DAG.getConstant(Val, dl, MVT::i32); 7042 } 7043 return SDValue(); 7044 } 7045 7046 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 7047 const ARMSubtarget *ST) { 7048 SDLoc dl(Op); 7049 EVT VT = Op.getValueType(); 7050 7051 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 7052 7053 unsigned NumElts = VT.getVectorNumElements(); 7054 unsigned BoolMask; 7055 unsigned BitsPerBool; 7056 if (NumElts == 4) { 7057 BitsPerBool = 4; 7058 BoolMask = 0xf; 7059 } else if (NumElts == 8) { 7060 BitsPerBool = 2; 7061 BoolMask = 0x3; 7062 } else if (NumElts == 16) { 7063 BitsPerBool = 1; 7064 BoolMask = 0x1; 7065 } else 7066 return SDValue(); 7067 7068 // If this is a single value copied into all lanes (a splat), we can just sign 7069 // extend that single value 7070 SDValue FirstOp = Op.getOperand(0); 7071 if (!isa<ConstantSDNode>(FirstOp) && 7072 std::all_of(std::next(Op->op_begin()), Op->op_end(), 7073 [&FirstOp](SDUse &U) { 7074 return U.get().isUndef() || U.get() == FirstOp; 7075 })) { 7076 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp, 7077 DAG.getValueType(MVT::i1)); 7078 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext); 7079 } 7080 7081 // First create base with bits set where known 7082 unsigned Bits32 = 0; 7083 for (unsigned i = 0; i < NumElts; ++i) { 7084 SDValue V = Op.getOperand(i); 7085 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 7086 continue; 7087 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 7088 if (BitSet) 7089 Bits32 |= BoolMask << (i * BitsPerBool); 7090 } 7091 7092 // Add in unknown nodes 7093 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 7094 DAG.getConstant(Bits32, dl, MVT::i32)); 7095 for (unsigned i = 0; i < NumElts; ++i) { 7096 SDValue V = Op.getOperand(i); 7097 if (isa<ConstantSDNode>(V) || V.isUndef()) 7098 continue; 7099 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 7100 DAG.getConstant(i, dl, MVT::i32)); 7101 } 7102 7103 return Base; 7104 } 7105 7106 // If this is a case we can't handle, return null and let the default 7107 // expansion code take care of it. 7108 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 7109 const ARMSubtarget *ST) const { 7110 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7111 SDLoc dl(Op); 7112 EVT VT = Op.getValueType(); 7113 7114 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7115 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 7116 7117 APInt SplatBits, SplatUndef; 7118 unsigned SplatBitSize; 7119 bool HasAnyUndefs; 7120 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7121 if (SplatUndef.isAllOnesValue()) 7122 return DAG.getUNDEF(VT); 7123 7124 if ((ST->hasNEON() && SplatBitSize <= 64) || 7125 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) { 7126 // Check if an immediate VMOV works. 7127 EVT VmovVT; 7128 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 7129 SplatUndef.getZExtValue(), SplatBitSize, 7130 DAG, dl, VmovVT, VT.is128BitVector(), 7131 VMOVModImm); 7132 7133 if (Val.getNode()) { 7134 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 7135 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7136 } 7137 7138 // Try an immediate VMVN. 7139 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 7140 Val = isVMOVModifiedImm( 7141 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, 7142 DAG, dl, VmovVT, VT.is128BitVector(), 7143 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 7144 if (Val.getNode()) { 7145 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 7146 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7147 } 7148 7149 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 7150 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 7151 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 7152 if (ImmVal != -1) { 7153 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 7154 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 7155 } 7156 } 7157 } 7158 } 7159 7160 // Scan through the operands to see if only one value is used. 7161 // 7162 // As an optimisation, even if more than one value is used it may be more 7163 // profitable to splat with one value then change some lanes. 7164 // 7165 // Heuristically we decide to do this if the vector has a "dominant" value, 7166 // defined as splatted to more than half of the lanes. 7167 unsigned NumElts = VT.getVectorNumElements(); 7168 bool isOnlyLowElement = true; 7169 bool usesOnlyOneValue = true; 7170 bool hasDominantValue = false; 7171 bool isConstant = true; 7172 7173 // Map of the number of times a particular SDValue appears in the 7174 // element list. 7175 DenseMap<SDValue, unsigned> ValueCounts; 7176 SDValue Value; 7177 for (unsigned i = 0; i < NumElts; ++i) { 7178 SDValue V = Op.getOperand(i); 7179 if (V.isUndef()) 7180 continue; 7181 if (i > 0) 7182 isOnlyLowElement = false; 7183 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 7184 isConstant = false; 7185 7186 ValueCounts.insert(std::make_pair(V, 0)); 7187 unsigned &Count = ValueCounts[V]; 7188 7189 // Is this value dominant? (takes up more than half of the lanes) 7190 if (++Count > (NumElts / 2)) { 7191 hasDominantValue = true; 7192 Value = V; 7193 } 7194 } 7195 if (ValueCounts.size() != 1) 7196 usesOnlyOneValue = false; 7197 if (!Value.getNode() && !ValueCounts.empty()) 7198 Value = ValueCounts.begin()->first; 7199 7200 if (ValueCounts.empty()) 7201 return DAG.getUNDEF(VT); 7202 7203 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 7204 // Keep going if we are hitting this case. 7205 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 7206 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7207 7208 unsigned EltSize = VT.getScalarSizeInBits(); 7209 7210 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 7211 // i32 and try again. 7212 if (hasDominantValue && EltSize <= 32) { 7213 if (!isConstant) { 7214 SDValue N; 7215 7216 // If we are VDUPing a value that comes directly from a vector, that will 7217 // cause an unnecessary move to and from a GPR, where instead we could 7218 // just use VDUPLANE. We can only do this if the lane being extracted 7219 // is at a constant index, as the VDUP from lane instructions only have 7220 // constant-index forms. 7221 ConstantSDNode *constIndex; 7222 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7223 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 7224 // We need to create a new undef vector to use for the VDUPLANE if the 7225 // size of the vector from which we get the value is different than the 7226 // size of the vector that we need to create. We will insert the element 7227 // such that the register coalescer will remove unnecessary copies. 7228 if (VT != Value->getOperand(0).getValueType()) { 7229 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 7230 VT.getVectorNumElements(); 7231 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7232 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 7233 Value, DAG.getConstant(index, dl, MVT::i32)), 7234 DAG.getConstant(index, dl, MVT::i32)); 7235 } else 7236 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7237 Value->getOperand(0), Value->getOperand(1)); 7238 } else 7239 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 7240 7241 if (!usesOnlyOneValue) { 7242 // The dominant value was splatted as 'N', but we now have to insert 7243 // all differing elements. 7244 for (unsigned I = 0; I < NumElts; ++I) { 7245 if (Op.getOperand(I) == Value) 7246 continue; 7247 SmallVector<SDValue, 3> Ops; 7248 Ops.push_back(N); 7249 Ops.push_back(Op.getOperand(I)); 7250 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 7251 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 7252 } 7253 } 7254 return N; 7255 } 7256 if (VT.getVectorElementType().isFloatingPoint()) { 7257 SmallVector<SDValue, 8> Ops; 7258 MVT FVT = VT.getVectorElementType().getSimpleVT(); 7259 assert(FVT == MVT::f32 || FVT == MVT::f16); 7260 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 7261 for (unsigned i = 0; i < NumElts; ++i) 7262 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 7263 Op.getOperand(i))); 7264 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 7265 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7266 Val = LowerBUILD_VECTOR(Val, DAG, ST); 7267 if (Val.getNode()) 7268 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7269 } 7270 if (usesOnlyOneValue) { 7271 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 7272 if (isConstant && Val.getNode()) 7273 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 7274 } 7275 } 7276 7277 // If all elements are constants and the case above didn't get hit, fall back 7278 // to the default expansion, which will generate a load from the constant 7279 // pool. 7280 if (isConstant) 7281 return SDValue(); 7282 7283 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 7284 if (NumElts >= 4) { 7285 SDValue shuffle = ReconstructShuffle(Op, DAG); 7286 if (shuffle != SDValue()) 7287 return shuffle; 7288 } 7289 7290 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7291 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7292 // into two 64-bit vectors; we might discover a better way to lower it. 7293 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7294 EVT ExtVT = VT.getVectorElementType(); 7295 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7296 SDValue Lower = 7297 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7298 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7299 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7300 SDValue Upper = DAG.getBuildVector( 7301 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7302 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7303 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7304 if (Lower && Upper) 7305 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7306 } 7307 7308 // Vectors with 32- or 64-bit elements can be built by directly assigning 7309 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7310 // will be legalized. 7311 if (EltSize >= 32) { 7312 // Do the expansion with floating-point types, since that is what the VFP 7313 // registers are defined to use, and since i64 is not legal. 7314 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7315 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7316 SmallVector<SDValue, 8> Ops; 7317 for (unsigned i = 0; i < NumElts; ++i) 7318 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7319 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7320 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7321 } 7322 7323 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7324 // know the default expansion would otherwise fall back on something even 7325 // worse. For a vector with one or two non-undef values, that's 7326 // scalar_to_vector for the elements followed by a shuffle (provided the 7327 // shuffle is valid for the target) and materialization element by element 7328 // on the stack followed by a load for everything else. 7329 if (!isConstant && !usesOnlyOneValue) { 7330 SDValue Vec = DAG.getUNDEF(VT); 7331 for (unsigned i = 0 ; i < NumElts; ++i) { 7332 SDValue V = Op.getOperand(i); 7333 if (V.isUndef()) 7334 continue; 7335 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7336 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7337 } 7338 return Vec; 7339 } 7340 7341 return SDValue(); 7342 } 7343 7344 // Gather data to see if the operation can be modelled as a 7345 // shuffle in combination with VEXTs. 7346 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7347 SelectionDAG &DAG) const { 7348 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7349 SDLoc dl(Op); 7350 EVT VT = Op.getValueType(); 7351 unsigned NumElts = VT.getVectorNumElements(); 7352 7353 struct ShuffleSourceInfo { 7354 SDValue Vec; 7355 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7356 unsigned MaxElt = 0; 7357 7358 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7359 // be compatible with the shuffle we intend to construct. As a result 7360 // ShuffleVec will be some sliding window into the original Vec. 7361 SDValue ShuffleVec; 7362 7363 // Code should guarantee that element i in Vec starts at element "WindowBase 7364 // + i * WindowScale in ShuffleVec". 7365 int WindowBase = 0; 7366 int WindowScale = 1; 7367 7368 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7369 7370 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7371 }; 7372 7373 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7374 // node. 7375 SmallVector<ShuffleSourceInfo, 2> Sources; 7376 for (unsigned i = 0; i < NumElts; ++i) { 7377 SDValue V = Op.getOperand(i); 7378 if (V.isUndef()) 7379 continue; 7380 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7381 // A shuffle can only come from building a vector from various 7382 // elements of other vectors. 7383 return SDValue(); 7384 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7385 // Furthermore, shuffles require a constant mask, whereas extractelts 7386 // accept variable indices. 7387 return SDValue(); 7388 } 7389 7390 // Add this element source to the list if it's not already there. 7391 SDValue SourceVec = V.getOperand(0); 7392 auto Source = llvm::find(Sources, SourceVec); 7393 if (Source == Sources.end()) 7394 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7395 7396 // Update the minimum and maximum lane number seen. 7397 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7398 Source->MinElt = std::min(Source->MinElt, EltNo); 7399 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7400 } 7401 7402 // Currently only do something sane when at most two source vectors 7403 // are involved. 7404 if (Sources.size() > 2) 7405 return SDValue(); 7406 7407 // Find out the smallest element size among result and two sources, and use 7408 // it as element size to build the shuffle_vector. 7409 EVT SmallestEltTy = VT.getVectorElementType(); 7410 for (auto &Source : Sources) { 7411 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7412 if (SrcEltTy.bitsLT(SmallestEltTy)) 7413 SmallestEltTy = SrcEltTy; 7414 } 7415 unsigned ResMultiplier = 7416 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7417 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7418 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7419 7420 // If the source vector is too wide or too narrow, we may nevertheless be able 7421 // to construct a compatible shuffle either by concatenating it with UNDEF or 7422 // extracting a suitable range of elements. 7423 for (auto &Src : Sources) { 7424 EVT SrcVT = Src.ShuffleVec.getValueType(); 7425 7426 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 7427 continue; 7428 7429 // This stage of the search produces a source with the same element type as 7430 // the original, but with a total width matching the BUILD_VECTOR output. 7431 EVT EltVT = SrcVT.getVectorElementType(); 7432 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 7433 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7434 7435 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 7436 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 7437 return SDValue(); 7438 // We can pad out the smaller vector for free, so if it's part of a 7439 // shuffle... 7440 Src.ShuffleVec = 7441 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7442 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7443 continue; 7444 } 7445 7446 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 7447 return SDValue(); 7448 7449 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7450 // Span too large for a VEXT to cope 7451 return SDValue(); 7452 } 7453 7454 if (Src.MinElt >= NumSrcElts) { 7455 // The extraction can just take the second half 7456 Src.ShuffleVec = 7457 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7458 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7459 Src.WindowBase = -NumSrcElts; 7460 } else if (Src.MaxElt < NumSrcElts) { 7461 // The extraction can just take the first half 7462 Src.ShuffleVec = 7463 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7464 DAG.getConstant(0, dl, MVT::i32)); 7465 } else { 7466 // An actual VEXT is needed 7467 SDValue VEXTSrc1 = 7468 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7469 DAG.getConstant(0, dl, MVT::i32)); 7470 SDValue VEXTSrc2 = 7471 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7472 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7473 7474 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7475 VEXTSrc2, 7476 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7477 Src.WindowBase = -Src.MinElt; 7478 } 7479 } 7480 7481 // Another possible incompatibility occurs from the vector element types. We 7482 // can fix this by bitcasting the source vectors to the same type we intend 7483 // for the shuffle. 7484 for (auto &Src : Sources) { 7485 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7486 if (SrcEltTy == SmallestEltTy) 7487 continue; 7488 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7489 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 7490 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7491 Src.WindowBase *= Src.WindowScale; 7492 } 7493 7494 // Final sanity check before we try to actually produce a shuffle. 7495 LLVM_DEBUG(for (auto Src 7496 : Sources) 7497 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7498 7499 // The stars all align, our next step is to produce the mask for the shuffle. 7500 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7501 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7502 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7503 SDValue Entry = Op.getOperand(i); 7504 if (Entry.isUndef()) 7505 continue; 7506 7507 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7508 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7509 7510 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7511 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7512 // segment. 7513 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7514 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 7515 VT.getScalarSizeInBits()); 7516 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7517 7518 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7519 // starting at the appropriate offset. 7520 int *LaneMask = &Mask[i * ResMultiplier]; 7521 7522 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7523 ExtractBase += NumElts * (Src - Sources.begin()); 7524 for (int j = 0; j < LanesDefined; ++j) 7525 LaneMask[j] = ExtractBase + j; 7526 } 7527 7528 7529 // We can't handle more than two sources. This should have already 7530 // been checked before this point. 7531 assert(Sources.size() <= 2 && "Too many sources!"); 7532 7533 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7534 for (unsigned i = 0; i < Sources.size(); ++i) 7535 ShuffleOps[i] = Sources[i].ShuffleVec; 7536 7537 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7538 ShuffleOps[1], Mask, DAG); 7539 if (!Shuffle) 7540 return SDValue(); 7541 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 7542 } 7543 7544 enum ShuffleOpCodes { 7545 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7546 OP_VREV, 7547 OP_VDUP0, 7548 OP_VDUP1, 7549 OP_VDUP2, 7550 OP_VDUP3, 7551 OP_VEXT1, 7552 OP_VEXT2, 7553 OP_VEXT3, 7554 OP_VUZPL, // VUZP, left result 7555 OP_VUZPR, // VUZP, right result 7556 OP_VZIPL, // VZIP, left result 7557 OP_VZIPR, // VZIP, right result 7558 OP_VTRNL, // VTRN, left result 7559 OP_VTRNR // VTRN, right result 7560 }; 7561 7562 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7563 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7564 switch (OpNum) { 7565 case OP_COPY: 7566 case OP_VREV: 7567 case OP_VDUP0: 7568 case OP_VDUP1: 7569 case OP_VDUP2: 7570 case OP_VDUP3: 7571 return true; 7572 } 7573 return false; 7574 } 7575 7576 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7577 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7578 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7579 /// are assumed to be legal. 7580 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7581 if (VT.getVectorNumElements() == 4 && 7582 (VT.is128BitVector() || VT.is64BitVector())) { 7583 unsigned PFIndexes[4]; 7584 for (unsigned i = 0; i != 4; ++i) { 7585 if (M[i] < 0) 7586 PFIndexes[i] = 8; 7587 else 7588 PFIndexes[i] = M[i]; 7589 } 7590 7591 // Compute the index in the perfect shuffle table. 7592 unsigned PFTableIndex = 7593 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7594 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7595 unsigned Cost = (PFEntry >> 30); 7596 7597 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7598 return true; 7599 } 7600 7601 bool ReverseVEXT, isV_UNDEF; 7602 unsigned Imm, WhichResult; 7603 7604 unsigned EltSize = VT.getScalarSizeInBits(); 7605 if (EltSize >= 32 || 7606 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7607 ShuffleVectorInst::isIdentityMask(M) || 7608 isVREVMask(M, VT, 64) || 7609 isVREVMask(M, VT, 32) || 7610 isVREVMask(M, VT, 16)) 7611 return true; 7612 else if (Subtarget->hasNEON() && 7613 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7614 isVTBLMask(M, VT) || 7615 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7616 return true; 7617 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7618 isReverseMask(M, VT)) 7619 return true; 7620 else if (Subtarget->hasMVEIntegerOps() && 7621 (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1))) 7622 return true; 7623 else 7624 return false; 7625 } 7626 7627 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7628 /// the specified operations to build the shuffle. 7629 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7630 SDValue RHS, SelectionDAG &DAG, 7631 const SDLoc &dl) { 7632 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7633 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7634 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7635 7636 if (OpNum == OP_COPY) { 7637 if (LHSID == (1*9+2)*9+3) return LHS; 7638 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7639 return RHS; 7640 } 7641 7642 SDValue OpLHS, OpRHS; 7643 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7644 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7645 EVT VT = OpLHS.getValueType(); 7646 7647 switch (OpNum) { 7648 default: llvm_unreachable("Unknown shuffle opcode!"); 7649 case OP_VREV: 7650 // VREV divides the vector in half and swaps within the half. 7651 if (VT.getVectorElementType() == MVT::i32 || 7652 VT.getVectorElementType() == MVT::f32) 7653 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7654 // vrev <4 x i16> -> VREV32 7655 if (VT.getVectorElementType() == MVT::i16) 7656 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7657 // vrev <4 x i8> -> VREV16 7658 assert(VT.getVectorElementType() == MVT::i8); 7659 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 7660 case OP_VDUP0: 7661 case OP_VDUP1: 7662 case OP_VDUP2: 7663 case OP_VDUP3: 7664 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7665 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 7666 case OP_VEXT1: 7667 case OP_VEXT2: 7668 case OP_VEXT3: 7669 return DAG.getNode(ARMISD::VEXT, dl, VT, 7670 OpLHS, OpRHS, 7671 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 7672 case OP_VUZPL: 7673 case OP_VUZPR: 7674 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 7675 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 7676 case OP_VZIPL: 7677 case OP_VZIPR: 7678 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 7679 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 7680 case OP_VTRNL: 7681 case OP_VTRNR: 7682 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7683 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7684 } 7685 } 7686 7687 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7688 ArrayRef<int> ShuffleMask, 7689 SelectionDAG &DAG) { 7690 // Check to see if we can use the VTBL instruction. 7691 SDValue V1 = Op.getOperand(0); 7692 SDValue V2 = Op.getOperand(1); 7693 SDLoc DL(Op); 7694 7695 SmallVector<SDValue, 8> VTBLMask; 7696 for (ArrayRef<int>::iterator 7697 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7698 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7699 7700 if (V2.getNode()->isUndef()) 7701 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7702 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7703 7704 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7705 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7706 } 7707 7708 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7709 SelectionDAG &DAG) { 7710 SDLoc DL(Op); 7711 SDValue OpLHS = Op.getOperand(0); 7712 EVT VT = OpLHS.getValueType(); 7713 7714 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7715 "Expect an v8i16/v16i8 type"); 7716 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7717 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7718 // extract the first 8 bytes into the top double word and the last 8 bytes 7719 // into the bottom double word. The v8i16 case is similar. 7720 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7721 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7722 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7723 } 7724 7725 static EVT getVectorTyFromPredicateVector(EVT VT) { 7726 switch (VT.getSimpleVT().SimpleTy) { 7727 case MVT::v4i1: 7728 return MVT::v4i32; 7729 case MVT::v8i1: 7730 return MVT::v8i16; 7731 case MVT::v16i1: 7732 return MVT::v16i8; 7733 default: 7734 llvm_unreachable("Unexpected vector predicate type"); 7735 } 7736 } 7737 7738 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 7739 SelectionDAG &DAG) { 7740 // Converting from boolean predicates to integers involves creating a vector 7741 // of all ones or all zeroes and selecting the lanes based upon the real 7742 // predicate. 7743 SDValue AllOnes = 7744 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 7745 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 7746 7747 SDValue AllZeroes = 7748 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 7749 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 7750 7751 // Get full vector type from predicate type 7752 EVT NewVT = getVectorTyFromPredicateVector(VT); 7753 7754 SDValue RecastV1; 7755 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 7756 // this to a v16i1. This cannot be done with an ordinary bitcast because the 7757 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 7758 // since we know in hardware the sizes are really the same. 7759 if (VT != MVT::v16i1) 7760 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 7761 else 7762 RecastV1 = Pred; 7763 7764 // Select either all ones or zeroes depending upon the real predicate bits. 7765 SDValue PredAsVector = 7766 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 7767 7768 // Recast our new predicate-as-integer v16i8 vector into something 7769 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 7770 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 7771 } 7772 7773 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 7774 const ARMSubtarget *ST) { 7775 EVT VT = Op.getValueType(); 7776 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7777 ArrayRef<int> ShuffleMask = SVN->getMask(); 7778 7779 assert(ST->hasMVEIntegerOps() && 7780 "No support for vector shuffle of boolean predicates"); 7781 7782 SDValue V1 = Op.getOperand(0); 7783 SDLoc dl(Op); 7784 if (isReverseMask(ShuffleMask, VT)) { 7785 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 7786 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 7787 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 7788 DAG.getConstant(16, dl, MVT::i32)); 7789 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 7790 } 7791 7792 // Until we can come up with optimised cases for every single vector 7793 // shuffle in existence we have chosen the least painful strategy. This is 7794 // to essentially promote the boolean predicate to a 8-bit integer, where 7795 // each predicate represents a byte. Then we fall back on a normal integer 7796 // vector shuffle and convert the result back into a predicate vector. In 7797 // many cases the generated code might be even better than scalar code 7798 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 7799 // fields in a register into 8 other arbitrary 2-bit fields! 7800 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 7801 EVT NewVT = PredAsVector.getValueType(); 7802 7803 // Do the shuffle! 7804 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 7805 DAG.getUNDEF(NewVT), ShuffleMask); 7806 7807 // Now return the result of comparing the shuffled vector with zero, 7808 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7809 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 7810 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7811 } 7812 7813 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op, 7814 ArrayRef<int> ShuffleMask, 7815 SelectionDAG &DAG) { 7816 // Attempt to lower the vector shuffle using as many whole register movs as 7817 // possible. This is useful for types smaller than 32bits, which would 7818 // often otherwise become a series for grp movs. 7819 SDLoc dl(Op); 7820 EVT VT = Op.getValueType(); 7821 if (VT.getScalarSizeInBits() >= 32) 7822 return SDValue(); 7823 7824 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && 7825 "Unexpected vector type"); 7826 int NumElts = VT.getVectorNumElements(); 7827 int QuarterSize = NumElts / 4; 7828 // The four final parts of the vector, as i32's 7829 SDValue Parts[4]; 7830 7831 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not 7832 // <u,u,u,u>), returning the vmov lane index 7833 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) { 7834 // Detect which mov lane this would be from the first non-undef element. 7835 int MovIdx = -1; 7836 for (int i = 0; i < Length; i++) { 7837 if (ShuffleMask[Start + i] >= 0) { 7838 if (ShuffleMask[Start + i] % Length != i) 7839 return -1; 7840 MovIdx = ShuffleMask[Start + i] / Length; 7841 break; 7842 } 7843 } 7844 // If all items are undef, leave this for other combines 7845 if (MovIdx == -1) 7846 return -1; 7847 // Check the remaining values are the correct part of the same mov 7848 for (int i = 1; i < Length; i++) { 7849 if (ShuffleMask[Start + i] >= 0 && 7850 (ShuffleMask[Start + i] / Length != MovIdx || 7851 ShuffleMask[Start + i] % Length != i)) 7852 return -1; 7853 } 7854 return MovIdx; 7855 }; 7856 7857 for (int Part = 0; Part < 4; ++Part) { 7858 // Does this part look like a mov 7859 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize); 7860 if (Elt != -1) { 7861 SDValue Input = Op->getOperand(0); 7862 if (Elt >= 4) { 7863 Input = Op->getOperand(1); 7864 Elt -= 4; 7865 } 7866 SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input); 7867 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast, 7868 DAG.getConstant(Elt, dl, MVT::i32)); 7869 } 7870 } 7871 7872 // Nothing interesting found, just return 7873 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3]) 7874 return SDValue(); 7875 7876 // The other parts need to be built with the old shuffle vector, cast to a 7877 // v4i32 and extract_vector_elts 7878 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) { 7879 SmallVector<int, 16> NewShuffleMask; 7880 for (int Part = 0; Part < 4; ++Part) 7881 for (int i = 0; i < QuarterSize; i++) 7882 NewShuffleMask.push_back( 7883 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]); 7884 SDValue NewShuffle = DAG.getVectorShuffle( 7885 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask); 7886 SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle); 7887 7888 for (int Part = 0; Part < 4; ++Part) 7889 if (!Parts[Part]) 7890 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7891 BitCast, DAG.getConstant(Part, dl, MVT::i32)); 7892 } 7893 // Build a vector out of the various parts and bitcast it back to the original 7894 // type. 7895 SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts); 7896 return DAG.getBitcast(VT, NewVec); 7897 } 7898 7899 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 7900 const ARMSubtarget *ST) { 7901 SDValue V1 = Op.getOperand(0); 7902 SDValue V2 = Op.getOperand(1); 7903 SDLoc dl(Op); 7904 EVT VT = Op.getValueType(); 7905 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7906 unsigned EltSize = VT.getScalarSizeInBits(); 7907 7908 if (ST->hasMVEIntegerOps() && EltSize == 1) 7909 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 7910 7911 // Convert shuffles that are directly supported on NEON to target-specific 7912 // DAG nodes, instead of keeping them as shuffles and matching them again 7913 // during code selection. This is more efficient and avoids the possibility 7914 // of inconsistencies between legalization and selection. 7915 // FIXME: floating-point vectors should be canonicalized to integer vectors 7916 // of the same time so that they get CSEd properly. 7917 ArrayRef<int> ShuffleMask = SVN->getMask(); 7918 7919 if (EltSize <= 32) { 7920 if (SVN->isSplat()) { 7921 int Lane = SVN->getSplatIndex(); 7922 // If this is undef splat, generate it via "just" vdup, if possible. 7923 if (Lane == -1) Lane = 0; 7924 7925 // Test if V1 is a SCALAR_TO_VECTOR. 7926 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7927 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7928 } 7929 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7930 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7931 // reaches it). 7932 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7933 !isa<ConstantSDNode>(V1.getOperand(0))) { 7934 bool IsScalarToVector = true; 7935 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7936 if (!V1.getOperand(i).isUndef()) { 7937 IsScalarToVector = false; 7938 break; 7939 } 7940 if (IsScalarToVector) 7941 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7942 } 7943 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7944 DAG.getConstant(Lane, dl, MVT::i32)); 7945 } 7946 7947 bool ReverseVEXT = false; 7948 unsigned Imm = 0; 7949 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7950 if (ReverseVEXT) 7951 std::swap(V1, V2); 7952 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7953 DAG.getConstant(Imm, dl, MVT::i32)); 7954 } 7955 7956 if (isVREVMask(ShuffleMask, VT, 64)) 7957 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7958 if (isVREVMask(ShuffleMask, VT, 32)) 7959 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7960 if (isVREVMask(ShuffleMask, VT, 16)) 7961 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7962 7963 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7964 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7965 DAG.getConstant(Imm, dl, MVT::i32)); 7966 } 7967 7968 // Check for Neon shuffles that modify both input vectors in place. 7969 // If both results are used, i.e., if there are two shuffles with the same 7970 // source operands and with masks corresponding to both results of one of 7971 // these operations, DAG memoization will ensure that a single node is 7972 // used for both shuffles. 7973 unsigned WhichResult = 0; 7974 bool isV_UNDEF = false; 7975 if (ST->hasNEON()) { 7976 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7977 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7978 if (isV_UNDEF) 7979 V2 = V1; 7980 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7981 .getValue(WhichResult); 7982 } 7983 } 7984 if (ST->hasMVEIntegerOps()) { 7985 if (isVMOVNMask(ShuffleMask, VT, 0)) 7986 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1, 7987 DAG.getConstant(0, dl, MVT::i32)); 7988 if (isVMOVNMask(ShuffleMask, VT, 1)) 7989 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2, 7990 DAG.getConstant(1, dl, MVT::i32)); 7991 } 7992 7993 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7994 // shuffles that produce a result larger than their operands with: 7995 // shuffle(concat(v1, undef), concat(v2, undef)) 7996 // -> 7997 // shuffle(concat(v1, v2), undef) 7998 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7999 // 8000 // This is useful in the general case, but there are special cases where 8001 // native shuffles produce larger results: the two-result ops. 8002 // 8003 // Look through the concat when lowering them: 8004 // shuffle(concat(v1, v2), undef) 8005 // -> 8006 // concat(VZIP(v1, v2):0, :1) 8007 // 8008 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 8009 SDValue SubV1 = V1->getOperand(0); 8010 SDValue SubV2 = V1->getOperand(1); 8011 EVT SubVT = SubV1.getValueType(); 8012 8013 // We expect these to have been canonicalized to -1. 8014 assert(llvm::all_of(ShuffleMask, [&](int i) { 8015 return i < (int)VT.getVectorNumElements(); 8016 }) && "Unexpected shuffle index into UNDEF operand!"); 8017 8018 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8019 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 8020 if (isV_UNDEF) 8021 SubV2 = SubV1; 8022 assert((WhichResult == 0) && 8023 "In-place shuffle of concat can only have one result!"); 8024 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 8025 SubV1, SubV2); 8026 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 8027 Res.getValue(1)); 8028 } 8029 } 8030 } 8031 8032 // If the shuffle is not directly supported and it has 4 elements, use 8033 // the PerfectShuffle-generated table to synthesize it from other shuffles. 8034 unsigned NumElts = VT.getVectorNumElements(); 8035 if (NumElts == 4) { 8036 unsigned PFIndexes[4]; 8037 for (unsigned i = 0; i != 4; ++i) { 8038 if (ShuffleMask[i] < 0) 8039 PFIndexes[i] = 8; 8040 else 8041 PFIndexes[i] = ShuffleMask[i]; 8042 } 8043 8044 // Compute the index in the perfect shuffle table. 8045 unsigned PFTableIndex = 8046 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8047 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8048 unsigned Cost = (PFEntry >> 30); 8049 8050 if (Cost <= 4) { 8051 if (ST->hasNEON()) 8052 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8053 else if (isLegalMVEShuffleOp(PFEntry)) { 8054 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8055 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8056 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 8057 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 8058 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 8059 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8060 } 8061 } 8062 } 8063 8064 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 8065 if (EltSize >= 32) { 8066 // Do the expansion with floating-point types, since that is what the VFP 8067 // registers are defined to use, and since i64 is not legal. 8068 EVT EltVT = EVT::getFloatingPointVT(EltSize); 8069 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 8070 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 8071 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 8072 SmallVector<SDValue, 8> Ops; 8073 for (unsigned i = 0; i < NumElts; ++i) { 8074 if (ShuffleMask[i] < 0) 8075 Ops.push_back(DAG.getUNDEF(EltVT)); 8076 else 8077 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 8078 ShuffleMask[i] < (int)NumElts ? V1 : V2, 8079 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 8080 dl, MVT::i32))); 8081 } 8082 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 8083 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8084 } 8085 8086 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 8087 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 8088 8089 if (ST->hasNEON() && VT == MVT::v8i8) 8090 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 8091 return NewOp; 8092 8093 if (ST->hasMVEIntegerOps()) 8094 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG)) 8095 return NewOp; 8096 8097 return SDValue(); 8098 } 8099 8100 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8101 const ARMSubtarget *ST) { 8102 EVT VecVT = Op.getOperand(0).getValueType(); 8103 SDLoc dl(Op); 8104 8105 assert(ST->hasMVEIntegerOps() && 8106 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8107 8108 SDValue Conv = 8109 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8110 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8111 unsigned LaneWidth = 8112 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8113 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 8114 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 8115 Op.getOperand(1), DAG.getValueType(MVT::i1)); 8116 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 8117 DAG.getConstant(~Mask, dl, MVT::i32)); 8118 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 8119 } 8120 8121 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8122 SelectionDAG &DAG) const { 8123 // INSERT_VECTOR_ELT is legal only for immediate indexes. 8124 SDValue Lane = Op.getOperand(2); 8125 if (!isa<ConstantSDNode>(Lane)) 8126 return SDValue(); 8127 8128 SDValue Elt = Op.getOperand(1); 8129 EVT EltVT = Elt.getValueType(); 8130 8131 if (Subtarget->hasMVEIntegerOps() && 8132 Op.getValueType().getScalarSizeInBits() == 1) 8133 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 8134 8135 if (getTypeAction(*DAG.getContext(), EltVT) == 8136 TargetLowering::TypePromoteFloat) { 8137 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 8138 // but the type system will try to do that if we don't intervene. 8139 // Reinterpret any such vector-element insertion as one with the 8140 // corresponding integer types. 8141 8142 SDLoc dl(Op); 8143 8144 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 8145 assert(getTypeAction(*DAG.getContext(), IEltVT) != 8146 TargetLowering::TypePromoteFloat); 8147 8148 SDValue VecIn = Op.getOperand(0); 8149 EVT VecVT = VecIn.getValueType(); 8150 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 8151 VecVT.getVectorNumElements()); 8152 8153 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 8154 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 8155 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 8156 IVecIn, IElt, Lane); 8157 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 8158 } 8159 8160 return Op; 8161 } 8162 8163 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8164 const ARMSubtarget *ST) { 8165 EVT VecVT = Op.getOperand(0).getValueType(); 8166 SDLoc dl(Op); 8167 8168 assert(ST->hasMVEIntegerOps() && 8169 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8170 8171 SDValue Conv = 8172 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8173 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8174 unsigned LaneWidth = 8175 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8176 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 8177 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 8178 return Shift; 8179 } 8180 8181 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 8182 const ARMSubtarget *ST) { 8183 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 8184 SDValue Lane = Op.getOperand(1); 8185 if (!isa<ConstantSDNode>(Lane)) 8186 return SDValue(); 8187 8188 SDValue Vec = Op.getOperand(0); 8189 EVT VT = Vec.getValueType(); 8190 8191 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8192 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 8193 8194 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 8195 SDLoc dl(Op); 8196 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 8197 } 8198 8199 return Op; 8200 } 8201 8202 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 8203 const ARMSubtarget *ST) { 8204 SDValue V1 = Op.getOperand(0); 8205 SDValue V2 = Op.getOperand(1); 8206 SDLoc dl(Op); 8207 EVT VT = Op.getValueType(); 8208 EVT Op1VT = V1.getValueType(); 8209 EVT Op2VT = V2.getValueType(); 8210 unsigned NumElts = VT.getVectorNumElements(); 8211 8212 assert(Op1VT == Op2VT && "Operand types don't match!"); 8213 assert(VT.getScalarSizeInBits() == 1 && 8214 "Unexpected custom CONCAT_VECTORS lowering"); 8215 assert(ST->hasMVEIntegerOps() && 8216 "CONCAT_VECTORS lowering only supported for MVE"); 8217 8218 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8219 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 8220 8221 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 8222 // promoted to v8i16, etc. 8223 8224 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8225 8226 // Extract the vector elements from Op1 and Op2 one by one and truncate them 8227 // to be the right size for the destination. For example, if Op1 is v4i1 then 8228 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 8229 // which when promoted is v8i16. That means each i32 element from Op1 needs 8230 // truncating to i16 and inserting in the result. 8231 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 8232 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 8233 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 8234 EVT NewVT = NewV.getValueType(); 8235 EVT ConcatVT = ConVec.getValueType(); 8236 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 8237 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 8238 DAG.getIntPtrConstant(i, dl)); 8239 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 8240 DAG.getConstant(j, dl, MVT::i32)); 8241 } 8242 return ConVec; 8243 }; 8244 unsigned j = 0; 8245 ConVec = ExractInto(NewV1, ConVec, j); 8246 ConVec = ExractInto(NewV2, ConVec, j); 8247 8248 // Now return the result of comparing the subvector with zero, 8249 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8250 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 8251 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8252 } 8253 8254 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 8255 const ARMSubtarget *ST) { 8256 EVT VT = Op->getValueType(0); 8257 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8258 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 8259 8260 // The only time a CONCAT_VECTORS operation can have legal types is when 8261 // two 64-bit vectors are concatenated to a 128-bit vector. 8262 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 8263 "unexpected CONCAT_VECTORS"); 8264 SDLoc dl(Op); 8265 SDValue Val = DAG.getUNDEF(MVT::v2f64); 8266 SDValue Op0 = Op.getOperand(0); 8267 SDValue Op1 = Op.getOperand(1); 8268 if (!Op0.isUndef()) 8269 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8270 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 8271 DAG.getIntPtrConstant(0, dl)); 8272 if (!Op1.isUndef()) 8273 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8274 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 8275 DAG.getIntPtrConstant(1, dl)); 8276 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 8277 } 8278 8279 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 8280 const ARMSubtarget *ST) { 8281 SDValue V1 = Op.getOperand(0); 8282 SDValue V2 = Op.getOperand(1); 8283 SDLoc dl(Op); 8284 EVT VT = Op.getValueType(); 8285 EVT Op1VT = V1.getValueType(); 8286 unsigned NumElts = VT.getVectorNumElements(); 8287 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 8288 8289 assert(VT.getScalarSizeInBits() == 1 && 8290 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 8291 assert(ST->hasMVEIntegerOps() && 8292 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 8293 8294 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8295 8296 // We now have Op1 promoted to a vector of integers, where v8i1 gets 8297 // promoted to v8i16, etc. 8298 8299 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8300 8301 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 8302 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 8303 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 8304 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 8305 DAG.getIntPtrConstant(i, dl)); 8306 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 8307 DAG.getConstant(j, dl, MVT::i32)); 8308 } 8309 8310 // Now return the result of comparing the subvector with zero, 8311 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8312 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 8313 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8314 } 8315 8316 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 8317 /// element has been zero/sign-extended, depending on the isSigned parameter, 8318 /// from an integer type half its size. 8319 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 8320 bool isSigned) { 8321 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 8322 EVT VT = N->getValueType(0); 8323 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 8324 SDNode *BVN = N->getOperand(0).getNode(); 8325 if (BVN->getValueType(0) != MVT::v4i32 || 8326 BVN->getOpcode() != ISD::BUILD_VECTOR) 8327 return false; 8328 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8329 unsigned HiElt = 1 - LoElt; 8330 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 8331 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 8332 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 8333 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 8334 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 8335 return false; 8336 if (isSigned) { 8337 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 8338 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 8339 return true; 8340 } else { 8341 if (Hi0->isNullValue() && Hi1->isNullValue()) 8342 return true; 8343 } 8344 return false; 8345 } 8346 8347 if (N->getOpcode() != ISD::BUILD_VECTOR) 8348 return false; 8349 8350 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 8351 SDNode *Elt = N->getOperand(i).getNode(); 8352 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 8353 unsigned EltSize = VT.getScalarSizeInBits(); 8354 unsigned HalfSize = EltSize / 2; 8355 if (isSigned) { 8356 if (!isIntN(HalfSize, C->getSExtValue())) 8357 return false; 8358 } else { 8359 if (!isUIntN(HalfSize, C->getZExtValue())) 8360 return false; 8361 } 8362 continue; 8363 } 8364 return false; 8365 } 8366 8367 return true; 8368 } 8369 8370 /// isSignExtended - Check if a node is a vector value that is sign-extended 8371 /// or a constant BUILD_VECTOR with sign-extended elements. 8372 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 8373 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 8374 return true; 8375 if (isExtendedBUILD_VECTOR(N, DAG, true)) 8376 return true; 8377 return false; 8378 } 8379 8380 /// isZeroExtended - Check if a node is a vector value that is zero-extended 8381 /// or a constant BUILD_VECTOR with zero-extended elements. 8382 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8383 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 8384 return true; 8385 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8386 return true; 8387 return false; 8388 } 8389 8390 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8391 if (OrigVT.getSizeInBits() >= 64) 8392 return OrigVT; 8393 8394 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8395 8396 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8397 switch (OrigSimpleTy) { 8398 default: llvm_unreachable("Unexpected Vector Type"); 8399 case MVT::v2i8: 8400 case MVT::v2i16: 8401 return MVT::v2i32; 8402 case MVT::v4i8: 8403 return MVT::v4i16; 8404 } 8405 } 8406 8407 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8408 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8409 /// We insert the required extension here to get the vector to fill a D register. 8410 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8411 const EVT &OrigTy, 8412 const EVT &ExtTy, 8413 unsigned ExtOpcode) { 8414 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8415 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8416 // 64-bits we need to insert a new extension so that it will be 64-bits. 8417 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8418 if (OrigTy.getSizeInBits() >= 64) 8419 return N; 8420 8421 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8422 EVT NewVT = getExtensionTo64Bits(OrigTy); 8423 8424 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8425 } 8426 8427 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8428 /// does not do any sign/zero extension. If the original vector is less 8429 /// than 64 bits, an appropriate extension will be added after the load to 8430 /// reach a total size of 64 bits. We have to add the extension separately 8431 /// because ARM does not have a sign/zero extending load for vectors. 8432 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8433 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8434 8435 // The load already has the right type. 8436 if (ExtendedTy == LD->getMemoryVT()) 8437 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8438 LD->getBasePtr(), LD->getPointerInfo(), 8439 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8440 8441 // We need to create a zextload/sextload. We cannot just create a load 8442 // followed by a zext/zext node because LowerMUL is also run during normal 8443 // operation legalization where we can't create illegal types. 8444 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8445 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8446 LD->getMemoryVT(), LD->getAlignment(), 8447 LD->getMemOperand()->getFlags()); 8448 } 8449 8450 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8451 /// extending load, or BUILD_VECTOR with extended elements, return the 8452 /// unextended value. The unextended vector should be 64 bits so that it can 8453 /// be used as an operand to a VMULL instruction. If the original vector size 8454 /// before extension is less than 64 bits we add a an extension to resize 8455 /// the vector to 64 bits. 8456 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8457 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 8458 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8459 N->getOperand(0)->getValueType(0), 8460 N->getValueType(0), 8461 N->getOpcode()); 8462 8463 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8464 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8465 "Expected extending load"); 8466 8467 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8468 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8469 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8470 SDValue extLoad = 8471 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8472 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8473 8474 return newLoad; 8475 } 8476 8477 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8478 // have been legalized as a BITCAST from v4i32. 8479 if (N->getOpcode() == ISD::BITCAST) { 8480 SDNode *BVN = N->getOperand(0).getNode(); 8481 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8482 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8483 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8484 return DAG.getBuildVector( 8485 MVT::v2i32, SDLoc(N), 8486 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8487 } 8488 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8489 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8490 EVT VT = N->getValueType(0); 8491 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8492 unsigned NumElts = VT.getVectorNumElements(); 8493 MVT TruncVT = MVT::getIntegerVT(EltSize); 8494 SmallVector<SDValue, 8> Ops; 8495 SDLoc dl(N); 8496 for (unsigned i = 0; i != NumElts; ++i) { 8497 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8498 const APInt &CInt = C->getAPIntValue(); 8499 // Element types smaller than 32 bits are not legal, so use i32 elements. 8500 // The values are implicitly truncated so sext vs. zext doesn't matter. 8501 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8502 } 8503 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8504 } 8505 8506 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8507 unsigned Opcode = N->getOpcode(); 8508 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8509 SDNode *N0 = N->getOperand(0).getNode(); 8510 SDNode *N1 = N->getOperand(1).getNode(); 8511 return N0->hasOneUse() && N1->hasOneUse() && 8512 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8513 } 8514 return false; 8515 } 8516 8517 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8518 unsigned Opcode = N->getOpcode(); 8519 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8520 SDNode *N0 = N->getOperand(0).getNode(); 8521 SDNode *N1 = N->getOperand(1).getNode(); 8522 return N0->hasOneUse() && N1->hasOneUse() && 8523 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8524 } 8525 return false; 8526 } 8527 8528 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8529 // Multiplications are only custom-lowered for 128-bit vectors so that 8530 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8531 EVT VT = Op.getValueType(); 8532 assert(VT.is128BitVector() && VT.isInteger() && 8533 "unexpected type for custom-lowering ISD::MUL"); 8534 SDNode *N0 = Op.getOperand(0).getNode(); 8535 SDNode *N1 = Op.getOperand(1).getNode(); 8536 unsigned NewOpc = 0; 8537 bool isMLA = false; 8538 bool isN0SExt = isSignExtended(N0, DAG); 8539 bool isN1SExt = isSignExtended(N1, DAG); 8540 if (isN0SExt && isN1SExt) 8541 NewOpc = ARMISD::VMULLs; 8542 else { 8543 bool isN0ZExt = isZeroExtended(N0, DAG); 8544 bool isN1ZExt = isZeroExtended(N1, DAG); 8545 if (isN0ZExt && isN1ZExt) 8546 NewOpc = ARMISD::VMULLu; 8547 else if (isN1SExt || isN1ZExt) { 8548 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8549 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8550 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8551 NewOpc = ARMISD::VMULLs; 8552 isMLA = true; 8553 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8554 NewOpc = ARMISD::VMULLu; 8555 isMLA = true; 8556 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8557 std::swap(N0, N1); 8558 NewOpc = ARMISD::VMULLu; 8559 isMLA = true; 8560 } 8561 } 8562 8563 if (!NewOpc) { 8564 if (VT == MVT::v2i64) 8565 // Fall through to expand this. It is not legal. 8566 return SDValue(); 8567 else 8568 // Other vector multiplications are legal. 8569 return Op; 8570 } 8571 } 8572 8573 // Legalize to a VMULL instruction. 8574 SDLoc DL(Op); 8575 SDValue Op0; 8576 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8577 if (!isMLA) { 8578 Op0 = SkipExtensionForVMULL(N0, DAG); 8579 assert(Op0.getValueType().is64BitVector() && 8580 Op1.getValueType().is64BitVector() && 8581 "unexpected types for extended operands to VMULL"); 8582 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8583 } 8584 8585 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8586 // isel lowering to take advantage of no-stall back to back vmul + vmla. 8587 // vmull q0, d4, d6 8588 // vmlal q0, d5, d6 8589 // is faster than 8590 // vaddl q0, d4, d5 8591 // vmovl q1, d6 8592 // vmul q0, q0, q1 8593 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 8594 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 8595 EVT Op1VT = Op1.getValueType(); 8596 return DAG.getNode(N0->getOpcode(), DL, VT, 8597 DAG.getNode(NewOpc, DL, VT, 8598 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 8599 DAG.getNode(NewOpc, DL, VT, 8600 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 8601 } 8602 8603 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 8604 SelectionDAG &DAG) { 8605 // TODO: Should this propagate fast-math-flags? 8606 8607 // Convert to float 8608 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 8609 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 8610 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 8611 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 8612 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 8613 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 8614 // Get reciprocal estimate. 8615 // float4 recip = vrecpeq_f32(yf); 8616 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8617 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8618 Y); 8619 // Because char has a smaller range than uchar, we can actually get away 8620 // without any newton steps. This requires that we use a weird bias 8621 // of 0xb000, however (again, this has been exhaustively tested). 8622 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 8623 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 8624 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 8625 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 8626 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 8627 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 8628 // Convert back to short. 8629 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 8630 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 8631 return X; 8632 } 8633 8634 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 8635 SelectionDAG &DAG) { 8636 // TODO: Should this propagate fast-math-flags? 8637 8638 SDValue N2; 8639 // Convert to float. 8640 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 8641 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 8642 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 8643 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 8644 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8645 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8646 8647 // Use reciprocal estimate and one refinement step. 8648 // float4 recip = vrecpeq_f32(yf); 8649 // recip *= vrecpsq_f32(yf, recip); 8650 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8651 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8652 N1); 8653 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8654 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8655 N1, N2); 8656 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8657 // Because short has a smaller range than ushort, we can actually get away 8658 // with only a single newton step. This requires that we use a weird bias 8659 // of 89, however (again, this has been exhaustively tested). 8660 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 8661 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8662 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8663 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 8664 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8665 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8666 // Convert back to integer and return. 8667 // return vmovn_s32(vcvt_s32_f32(result)); 8668 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8669 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8670 return N0; 8671 } 8672 8673 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 8674 const ARMSubtarget *ST) { 8675 EVT VT = Op.getValueType(); 8676 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8677 "unexpected type for custom-lowering ISD::SDIV"); 8678 8679 SDLoc dl(Op); 8680 SDValue N0 = Op.getOperand(0); 8681 SDValue N1 = Op.getOperand(1); 8682 SDValue N2, N3; 8683 8684 if (VT == MVT::v8i8) { 8685 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 8686 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 8687 8688 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8689 DAG.getIntPtrConstant(4, dl)); 8690 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8691 DAG.getIntPtrConstant(4, dl)); 8692 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8693 DAG.getIntPtrConstant(0, dl)); 8694 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8695 DAG.getIntPtrConstant(0, dl)); 8696 8697 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 8698 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 8699 8700 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8701 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8702 8703 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 8704 return N0; 8705 } 8706 return LowerSDIV_v4i16(N0, N1, dl, DAG); 8707 } 8708 8709 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 8710 const ARMSubtarget *ST) { 8711 // TODO: Should this propagate fast-math-flags? 8712 EVT VT = Op.getValueType(); 8713 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8714 "unexpected type for custom-lowering ISD::UDIV"); 8715 8716 SDLoc dl(Op); 8717 SDValue N0 = Op.getOperand(0); 8718 SDValue N1 = Op.getOperand(1); 8719 SDValue N2, N3; 8720 8721 if (VT == MVT::v8i8) { 8722 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 8723 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 8724 8725 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8726 DAG.getIntPtrConstant(4, dl)); 8727 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8728 DAG.getIntPtrConstant(4, dl)); 8729 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8730 DAG.getIntPtrConstant(0, dl)); 8731 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8732 DAG.getIntPtrConstant(0, dl)); 8733 8734 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 8735 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 8736 8737 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8738 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8739 8740 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 8741 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 8742 MVT::i32), 8743 N0); 8744 return N0; 8745 } 8746 8747 // v4i16 sdiv ... Convert to float. 8748 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 8749 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 8750 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 8751 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 8752 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8753 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8754 8755 // Use reciprocal estimate and two refinement steps. 8756 // float4 recip = vrecpeq_f32(yf); 8757 // recip *= vrecpsq_f32(yf, recip); 8758 // recip *= vrecpsq_f32(yf, recip); 8759 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8760 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8761 BN1); 8762 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8763 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8764 BN1, N2); 8765 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8766 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8767 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8768 BN1, N2); 8769 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8770 // Simply multiplying by the reciprocal estimate can leave us a few ulps 8771 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 8772 // and that it will never cause us to return an answer too large). 8773 // float4 result = as_float4(as_int4(xf*recip) + 2); 8774 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8775 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8776 N1 = DAG.getConstant(2, dl, MVT::v4i32); 8777 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8778 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8779 // Convert back to integer and return. 8780 // return vmovn_u32(vcvt_s32_f32(result)); 8781 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8782 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8783 return N0; 8784 } 8785 8786 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 8787 SDNode *N = Op.getNode(); 8788 EVT VT = N->getValueType(0); 8789 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 8790 8791 SDValue Carry = Op.getOperand(2); 8792 8793 SDLoc DL(Op); 8794 8795 SDValue Result; 8796 if (Op.getOpcode() == ISD::ADDCARRY) { 8797 // This converts the boolean value carry into the carry flag. 8798 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8799 8800 // Do the addition proper using the carry flag we wanted. 8801 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 8802 Op.getOperand(1), Carry); 8803 8804 // Now convert the carry flag into a boolean value. 8805 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8806 } else { 8807 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 8808 // have to invert the carry first. 8809 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8810 DAG.getConstant(1, DL, MVT::i32), Carry); 8811 // This converts the boolean value carry into the carry flag. 8812 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8813 8814 // Do the subtraction proper using the carry flag we wanted. 8815 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 8816 Op.getOperand(1), Carry); 8817 8818 // Now convert the carry flag into a boolean value. 8819 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8820 // But the carry returned by ARMISD::SUBE is not a borrow as expected 8821 // by ISD::SUBCARRY, so compute 1 - C. 8822 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8823 DAG.getConstant(1, DL, MVT::i32), Carry); 8824 } 8825 8826 // Return both values. 8827 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 8828 } 8829 8830 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 8831 assert(Subtarget->isTargetDarwin()); 8832 8833 // For iOS, we want to call an alternative entry point: __sincos_stret, 8834 // return values are passed via sret. 8835 SDLoc dl(Op); 8836 SDValue Arg = Op.getOperand(0); 8837 EVT ArgVT = Arg.getValueType(); 8838 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 8839 auto PtrVT = getPointerTy(DAG.getDataLayout()); 8840 8841 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8843 8844 // Pair of floats / doubles used to pass the result. 8845 Type *RetTy = StructType::get(ArgTy, ArgTy); 8846 auto &DL = DAG.getDataLayout(); 8847 8848 ArgListTy Args; 8849 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 8850 SDValue SRet; 8851 if (ShouldUseSRet) { 8852 // Create stack object for sret. 8853 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 8854 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 8855 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 8856 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 8857 8858 ArgListEntry Entry; 8859 Entry.Node = SRet; 8860 Entry.Ty = RetTy->getPointerTo(); 8861 Entry.IsSExt = false; 8862 Entry.IsZExt = false; 8863 Entry.IsSRet = true; 8864 Args.push_back(Entry); 8865 RetTy = Type::getVoidTy(*DAG.getContext()); 8866 } 8867 8868 ArgListEntry Entry; 8869 Entry.Node = Arg; 8870 Entry.Ty = ArgTy; 8871 Entry.IsSExt = false; 8872 Entry.IsZExt = false; 8873 Args.push_back(Entry); 8874 8875 RTLIB::Libcall LC = 8876 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 8877 const char *LibcallName = getLibcallName(LC); 8878 CallingConv::ID CC = getLibcallCallingConv(LC); 8879 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 8880 8881 TargetLowering::CallLoweringInfo CLI(DAG); 8882 CLI.setDebugLoc(dl) 8883 .setChain(DAG.getEntryNode()) 8884 .setCallee(CC, RetTy, Callee, std::move(Args)) 8885 .setDiscardResult(ShouldUseSRet); 8886 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8887 8888 if (!ShouldUseSRet) 8889 return CallResult.first; 8890 8891 SDValue LoadSin = 8892 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 8893 8894 // Address of cos field. 8895 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 8896 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 8897 SDValue LoadCos = 8898 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 8899 8900 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 8901 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 8902 LoadSin.getValue(0), LoadCos.getValue(0)); 8903 } 8904 8905 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 8906 bool Signed, 8907 SDValue &Chain) const { 8908 EVT VT = Op.getValueType(); 8909 assert((VT == MVT::i32 || VT == MVT::i64) && 8910 "unexpected type for custom lowering DIV"); 8911 SDLoc dl(Op); 8912 8913 const auto &DL = DAG.getDataLayout(); 8914 const auto &TLI = DAG.getTargetLoweringInfo(); 8915 8916 const char *Name = nullptr; 8917 if (Signed) 8918 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 8919 else 8920 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 8921 8922 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 8923 8924 ARMTargetLowering::ArgListTy Args; 8925 8926 for (auto AI : {1, 0}) { 8927 ArgListEntry Arg; 8928 Arg.Node = Op.getOperand(AI); 8929 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 8930 Args.push_back(Arg); 8931 } 8932 8933 CallLoweringInfo CLI(DAG); 8934 CLI.setDebugLoc(dl) 8935 .setChain(Chain) 8936 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 8937 ES, std::move(Args)); 8938 8939 return LowerCallTo(CLI).first; 8940 } 8941 8942 // This is a code size optimisation: return the original SDIV node to 8943 // DAGCombiner when we don't want to expand SDIV into a sequence of 8944 // instructions, and an empty node otherwise which will cause the 8945 // SDIV to be expanded in DAGCombine. 8946 SDValue 8947 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8948 SelectionDAG &DAG, 8949 SmallVectorImpl<SDNode *> &Created) const { 8950 // TODO: Support SREM 8951 if (N->getOpcode() != ISD::SDIV) 8952 return SDValue(); 8953 8954 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 8955 const bool MinSize = ST.hasMinSize(); 8956 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 8957 : ST.hasDivideInARMMode(); 8958 8959 // Don't touch vector types; rewriting this may lead to scalarizing 8960 // the int divs. 8961 if (N->getOperand(0).getValueType().isVector()) 8962 return SDValue(); 8963 8964 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 8965 // hwdiv support for this to be really profitable. 8966 if (!(MinSize && HasDivide)) 8967 return SDValue(); 8968 8969 // ARM mode is a bit simpler than Thumb: we can handle large power 8970 // of 2 immediates with 1 mov instruction; no further checks required, 8971 // just return the sdiv node. 8972 if (!ST.isThumb()) 8973 return SDValue(N, 0); 8974 8975 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 8976 // and thus lose the code size benefits of a MOVS that requires only 2. 8977 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 8978 // but as it's doing exactly this, it's not worth the trouble to get TTI. 8979 if (Divisor.sgt(128)) 8980 return SDValue(); 8981 8982 return SDValue(N, 0); 8983 } 8984 8985 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 8986 bool Signed) const { 8987 assert(Op.getValueType() == MVT::i32 && 8988 "unexpected type for custom lowering DIV"); 8989 SDLoc dl(Op); 8990 8991 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 8992 DAG.getEntryNode(), Op.getOperand(1)); 8993 8994 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8995 } 8996 8997 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 8998 SDLoc DL(N); 8999 SDValue Op = N->getOperand(1); 9000 if (N->getValueType(0) == MVT::i32) 9001 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 9002 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9003 DAG.getConstant(0, DL, MVT::i32)); 9004 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9005 DAG.getConstant(1, DL, MVT::i32)); 9006 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 9007 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 9008 } 9009 9010 void ARMTargetLowering::ExpandDIV_Windows( 9011 SDValue Op, SelectionDAG &DAG, bool Signed, 9012 SmallVectorImpl<SDValue> &Results) const { 9013 const auto &DL = DAG.getDataLayout(); 9014 const auto &TLI = DAG.getTargetLoweringInfo(); 9015 9016 assert(Op.getValueType() == MVT::i64 && 9017 "unexpected type for custom lowering DIV"); 9018 SDLoc dl(Op); 9019 9020 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 9021 9022 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9023 9024 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 9025 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 9026 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 9027 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 9028 9029 Results.push_back(Lower); 9030 Results.push_back(Upper); 9031 } 9032 9033 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) { 9034 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode()); 9035 EVT MemVT = LD->getMemoryVT(); 9036 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9037 "Expected a predicate type!"); 9038 assert(MemVT == Op.getValueType()); 9039 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && 9040 "Expected a non-extending load"); 9041 assert(LD->isUnindexed() && "Expected a unindexed load"); 9042 9043 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit 9044 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We 9045 // need to make sure that 8/4 bits are actually loaded into the correct 9046 // place, which means loading the value and then shuffling the values into 9047 // the bottom bits of the predicate. 9048 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect 9049 // for BE). 9050 9051 SDLoc dl(Op); 9052 SDValue Load = DAG.getExtLoad( 9053 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(), 9054 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9055 LD->getMemOperand()); 9056 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load); 9057 if (MemVT != MVT::v16i1) 9058 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred, 9059 DAG.getConstant(0, dl, MVT::i32)); 9060 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl); 9061 } 9062 9063 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) { 9064 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9065 EVT MemVT = ST->getMemoryVT(); 9066 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9067 "Expected a predicate type!"); 9068 assert(MemVT == ST->getValue().getValueType()); 9069 assert(!ST->isTruncatingStore() && "Expected a non-extending store"); 9070 assert(ST->isUnindexed() && "Expected a unindexed store"); 9071 9072 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits 9073 // unset and a scalar store. 9074 SDLoc dl(Op); 9075 SDValue Build = ST->getValue(); 9076 if (MemVT != MVT::v16i1) { 9077 SmallVector<SDValue, 16> Ops; 9078 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) 9079 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build, 9080 DAG.getConstant(I, dl, MVT::i32))); 9081 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++) 9082 Ops.push_back(DAG.getUNDEF(MVT::i32)); 9083 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops); 9084 } 9085 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build); 9086 return DAG.getTruncStore( 9087 ST->getChain(), dl, GRP, ST->getBasePtr(), 9088 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9089 ST->getMemOperand()); 9090 } 9091 9092 static bool isZeroVector(SDValue N) { 9093 return (ISD::isBuildVectorAllZeros(N.getNode()) || 9094 (N->getOpcode() == ARMISD::VMOVIMM && 9095 isNullConstant(N->getOperand(0)))); 9096 } 9097 9098 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) { 9099 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode()); 9100 MVT VT = Op.getSimpleValueType(); 9101 SDValue Mask = N->getMask(); 9102 SDValue PassThru = N->getPassThru(); 9103 SDLoc dl(Op); 9104 9105 if (isZeroVector(PassThru)) 9106 return Op; 9107 9108 // MVE Masked loads use zero as the passthru value. Here we convert undef to 9109 // zero too, and other values are lowered to a select. 9110 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 9111 DAG.getTargetConstant(0, dl, MVT::i32)); 9112 SDValue NewLoad = DAG.getMaskedLoad( 9113 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec, 9114 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(), 9115 N->getExtensionType(), N->isExpandingLoad()); 9116 SDValue Combo = NewLoad; 9117 if (!PassThru.isUndef() && 9118 (PassThru.getOpcode() != ISD::BITCAST || 9119 !isZeroVector(PassThru->getOperand(0)))) 9120 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru); 9121 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl); 9122 } 9123 9124 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 9125 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 9126 // Acquire/Release load/store is not legal for targets without a dmb or 9127 // equivalent available. 9128 return SDValue(); 9129 9130 // Monotonic load/store is legal for all targets. 9131 return Op; 9132 } 9133 9134 static void ReplaceREADCYCLECOUNTER(SDNode *N, 9135 SmallVectorImpl<SDValue> &Results, 9136 SelectionDAG &DAG, 9137 const ARMSubtarget *Subtarget) { 9138 SDLoc DL(N); 9139 // Under Power Management extensions, the cycle-count is: 9140 // mrc p15, #0, <Rt>, c9, c13, #0 9141 SDValue Ops[] = { N->getOperand(0), // Chain 9142 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 9143 DAG.getTargetConstant(15, DL, MVT::i32), 9144 DAG.getTargetConstant(0, DL, MVT::i32), 9145 DAG.getTargetConstant(9, DL, MVT::i32), 9146 DAG.getTargetConstant(13, DL, MVT::i32), 9147 DAG.getTargetConstant(0, DL, MVT::i32) 9148 }; 9149 9150 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 9151 DAG.getVTList(MVT::i32, MVT::Other), Ops); 9152 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 9153 DAG.getConstant(0, DL, MVT::i32))); 9154 Results.push_back(Cycles32.getValue(1)); 9155 } 9156 9157 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 9158 SDLoc dl(V.getNode()); 9159 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 9160 SDValue VHi = DAG.getAnyExtOrTrunc( 9161 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 9162 dl, MVT::i32); 9163 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9164 if (isBigEndian) 9165 std::swap (VLo, VHi); 9166 SDValue RegClass = 9167 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 9168 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 9169 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 9170 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 9171 return SDValue( 9172 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 9173 } 9174 9175 static void ReplaceCMP_SWAP_64Results(SDNode *N, 9176 SmallVectorImpl<SDValue> & Results, 9177 SelectionDAG &DAG) { 9178 assert(N->getValueType(0) == MVT::i64 && 9179 "AtomicCmpSwap on types less than 64 should be legal"); 9180 SDValue Ops[] = {N->getOperand(1), 9181 createGPRPairNode(DAG, N->getOperand(2)), 9182 createGPRPairNode(DAG, N->getOperand(3)), 9183 N->getOperand(0)}; 9184 SDNode *CmpSwap = DAG.getMachineNode( 9185 ARM::CMP_SWAP_64, SDLoc(N), 9186 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 9187 9188 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 9189 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 9190 9191 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9192 9193 Results.push_back( 9194 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 9195 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 9196 Results.push_back( 9197 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 9198 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 9199 Results.push_back(SDValue(CmpSwap, 2)); 9200 } 9201 9202 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9203 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 9204 switch (Op.getOpcode()) { 9205 default: llvm_unreachable("Don't know how to custom lower this!"); 9206 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 9207 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9208 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9209 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9210 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9211 case ISD::SELECT: return LowerSELECT(Op, DAG); 9212 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9213 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9214 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 9215 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 9216 case ISD::VASTART: return LowerVASTART(Op, DAG); 9217 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 9218 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 9219 case ISD::SINT_TO_FP: 9220 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9221 case ISD::FP_TO_SINT: 9222 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 9223 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9224 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9225 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9226 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 9227 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 9228 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 9229 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget); 9230 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 9231 Subtarget); 9232 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 9233 case ISD::SHL: 9234 case ISD::SRL: 9235 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 9236 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 9237 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 9238 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 9239 case ISD::SRL_PARTS: 9240 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 9241 case ISD::CTTZ: 9242 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 9243 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 9244 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 9245 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 9246 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 9247 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 9248 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 9249 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 9250 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9251 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 9252 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 9253 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9254 case ISD::MUL: return LowerMUL(Op, DAG); 9255 case ISD::SDIV: 9256 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9257 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 9258 return LowerSDIV(Op, DAG, Subtarget); 9259 case ISD::UDIV: 9260 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9261 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 9262 return LowerUDIV(Op, DAG, Subtarget); 9263 case ISD::ADDCARRY: 9264 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 9265 case ISD::SADDO: 9266 case ISD::SSUBO: 9267 return LowerSignedALUO(Op, DAG); 9268 case ISD::UADDO: 9269 case ISD::USUBO: 9270 return LowerUnsignedALUO(Op, DAG); 9271 case ISD::SADDSAT: 9272 case ISD::SSUBSAT: 9273 return LowerSADDSUBSAT(Op, DAG, Subtarget); 9274 case ISD::LOAD: 9275 return LowerPredicateLoad(Op, DAG); 9276 case ISD::STORE: 9277 return LowerPredicateStore(Op, DAG); 9278 case ISD::MLOAD: 9279 return LowerMLOAD(Op, DAG); 9280 case ISD::ATOMIC_LOAD: 9281 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 9282 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 9283 case ISD::SDIVREM: 9284 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 9285 case ISD::DYNAMIC_STACKALLOC: 9286 if (Subtarget->isTargetWindows()) 9287 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9288 llvm_unreachable("Don't know how to custom lower this!"); 9289 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 9290 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9291 case ARMISD::WIN__DBZCHK: return SDValue(); 9292 } 9293 } 9294 9295 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 9296 SelectionDAG &DAG) { 9297 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9298 unsigned Opc = 0; 9299 if (IntNo == Intrinsic::arm_smlald) 9300 Opc = ARMISD::SMLALD; 9301 else if (IntNo == Intrinsic::arm_smlaldx) 9302 Opc = ARMISD::SMLALDX; 9303 else if (IntNo == Intrinsic::arm_smlsld) 9304 Opc = ARMISD::SMLSLD; 9305 else if (IntNo == Intrinsic::arm_smlsldx) 9306 Opc = ARMISD::SMLSLDX; 9307 else 9308 return; 9309 9310 SDLoc dl(N); 9311 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9312 N->getOperand(3), 9313 DAG.getConstant(0, dl, MVT::i32)); 9314 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9315 N->getOperand(3), 9316 DAG.getConstant(1, dl, MVT::i32)); 9317 9318 SDValue LongMul = DAG.getNode(Opc, dl, 9319 DAG.getVTList(MVT::i32, MVT::i32), 9320 N->getOperand(1), N->getOperand(2), 9321 Lo, Hi); 9322 Results.push_back(LongMul.getValue(0)); 9323 Results.push_back(LongMul.getValue(1)); 9324 } 9325 9326 /// ReplaceNodeResults - Replace the results of node with an illegal result 9327 /// type with new values built out of custom code. 9328 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 9329 SmallVectorImpl<SDValue> &Results, 9330 SelectionDAG &DAG) const { 9331 SDValue Res; 9332 switch (N->getOpcode()) { 9333 default: 9334 llvm_unreachable("Don't know how to custom expand this!"); 9335 case ISD::READ_REGISTER: 9336 ExpandREAD_REGISTER(N, Results, DAG); 9337 break; 9338 case ISD::BITCAST: 9339 Res = ExpandBITCAST(N, DAG, Subtarget); 9340 break; 9341 case ISD::SRL: 9342 case ISD::SRA: 9343 case ISD::SHL: 9344 Res = Expand64BitShift(N, DAG, Subtarget); 9345 break; 9346 case ISD::SREM: 9347 case ISD::UREM: 9348 Res = LowerREM(N, DAG); 9349 break; 9350 case ISD::SDIVREM: 9351 case ISD::UDIVREM: 9352 Res = LowerDivRem(SDValue(N, 0), DAG); 9353 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 9354 Results.push_back(Res.getValue(0)); 9355 Results.push_back(Res.getValue(1)); 9356 return; 9357 case ISD::SADDSAT: 9358 case ISD::SSUBSAT: 9359 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget); 9360 break; 9361 case ISD::READCYCLECOUNTER: 9362 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 9363 return; 9364 case ISD::UDIV: 9365 case ISD::SDIV: 9366 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 9367 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 9368 Results); 9369 case ISD::ATOMIC_CMP_SWAP: 9370 ReplaceCMP_SWAP_64Results(N, Results, DAG); 9371 return; 9372 case ISD::INTRINSIC_WO_CHAIN: 9373 return ReplaceLongIntrinsic(N, Results, DAG); 9374 case ISD::ABS: 9375 lowerABS(N, Results, DAG); 9376 return ; 9377 9378 } 9379 if (Res.getNode()) 9380 Results.push_back(Res); 9381 } 9382 9383 //===----------------------------------------------------------------------===// 9384 // ARM Scheduler Hooks 9385 //===----------------------------------------------------------------------===// 9386 9387 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 9388 /// registers the function context. 9389 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 9390 MachineBasicBlock *MBB, 9391 MachineBasicBlock *DispatchBB, 9392 int FI) const { 9393 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 9394 "ROPI/RWPI not currently supported with SjLj"); 9395 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9396 DebugLoc dl = MI.getDebugLoc(); 9397 MachineFunction *MF = MBB->getParent(); 9398 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9399 MachineConstantPool *MCP = MF->getConstantPool(); 9400 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 9401 const Function &F = MF->getFunction(); 9402 9403 bool isThumb = Subtarget->isThumb(); 9404 bool isThumb2 = Subtarget->isThumb2(); 9405 9406 unsigned PCLabelId = AFI->createPICLabelUId(); 9407 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 9408 ARMConstantPoolValue *CPV = 9409 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 9410 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 9411 9412 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 9413 : &ARM::GPRRegClass; 9414 9415 // Grab constant pool and fixed stack memory operands. 9416 MachineMemOperand *CPMMO = 9417 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9418 MachineMemOperand::MOLoad, 4, 4); 9419 9420 MachineMemOperand *FIMMOSt = 9421 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 9422 MachineMemOperand::MOStore, 4, 4); 9423 9424 // Load the address of the dispatch MBB into the jump buffer. 9425 if (isThumb2) { 9426 // Incoming value: jbuf 9427 // ldr.n r5, LCPI1_1 9428 // orr r5, r5, #1 9429 // add r5, pc 9430 // str r5, [$jbuf, #+4] ; &jbuf[1] 9431 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9432 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 9433 .addConstantPoolIndex(CPI) 9434 .addMemOperand(CPMMO) 9435 .add(predOps(ARMCC::AL)); 9436 // Set the low bit because of thumb mode. 9437 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9438 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 9439 .addReg(NewVReg1, RegState::Kill) 9440 .addImm(0x01) 9441 .add(predOps(ARMCC::AL)) 9442 .add(condCodeOp()); 9443 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9444 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 9445 .addReg(NewVReg2, RegState::Kill) 9446 .addImm(PCLabelId); 9447 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 9448 .addReg(NewVReg3, RegState::Kill) 9449 .addFrameIndex(FI) 9450 .addImm(36) // &jbuf[1] :: pc 9451 .addMemOperand(FIMMOSt) 9452 .add(predOps(ARMCC::AL)); 9453 } else if (isThumb) { 9454 // Incoming value: jbuf 9455 // ldr.n r1, LCPI1_4 9456 // add r1, pc 9457 // mov r2, #1 9458 // orrs r1, r2 9459 // add r2, $jbuf, #+4 ; &jbuf[1] 9460 // str r1, [r2] 9461 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9462 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 9463 .addConstantPoolIndex(CPI) 9464 .addMemOperand(CPMMO) 9465 .add(predOps(ARMCC::AL)); 9466 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9467 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 9468 .addReg(NewVReg1, RegState::Kill) 9469 .addImm(PCLabelId); 9470 // Set the low bit because of thumb mode. 9471 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9472 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 9473 .addReg(ARM::CPSR, RegState::Define) 9474 .addImm(1) 9475 .add(predOps(ARMCC::AL)); 9476 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9477 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 9478 .addReg(ARM::CPSR, RegState::Define) 9479 .addReg(NewVReg2, RegState::Kill) 9480 .addReg(NewVReg3, RegState::Kill) 9481 .add(predOps(ARMCC::AL)); 9482 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9483 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 9484 .addFrameIndex(FI) 9485 .addImm(36); // &jbuf[1] :: pc 9486 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 9487 .addReg(NewVReg4, RegState::Kill) 9488 .addReg(NewVReg5, RegState::Kill) 9489 .addImm(0) 9490 .addMemOperand(FIMMOSt) 9491 .add(predOps(ARMCC::AL)); 9492 } else { 9493 // Incoming value: jbuf 9494 // ldr r1, LCPI1_1 9495 // add r1, pc, r1 9496 // str r1, [$jbuf, #+4] ; &jbuf[1] 9497 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9498 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 9499 .addConstantPoolIndex(CPI) 9500 .addImm(0) 9501 .addMemOperand(CPMMO) 9502 .add(predOps(ARMCC::AL)); 9503 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9504 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 9505 .addReg(NewVReg1, RegState::Kill) 9506 .addImm(PCLabelId) 9507 .add(predOps(ARMCC::AL)); 9508 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 9509 .addReg(NewVReg2, RegState::Kill) 9510 .addFrameIndex(FI) 9511 .addImm(36) // &jbuf[1] :: pc 9512 .addMemOperand(FIMMOSt) 9513 .add(predOps(ARMCC::AL)); 9514 } 9515 } 9516 9517 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 9518 MachineBasicBlock *MBB) const { 9519 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9520 DebugLoc dl = MI.getDebugLoc(); 9521 MachineFunction *MF = MBB->getParent(); 9522 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9523 MachineFrameInfo &MFI = MF->getFrameInfo(); 9524 int FI = MFI.getFunctionContextIndex(); 9525 9526 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 9527 : &ARM::GPRnopcRegClass; 9528 9529 // Get a mapping of the call site numbers to all of the landing pads they're 9530 // associated with. 9531 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 9532 unsigned MaxCSNum = 0; 9533 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 9534 ++BB) { 9535 if (!BB->isEHPad()) continue; 9536 9537 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 9538 // pad. 9539 for (MachineBasicBlock::iterator 9540 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 9541 if (!II->isEHLabel()) continue; 9542 9543 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 9544 if (!MF->hasCallSiteLandingPad(Sym)) continue; 9545 9546 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 9547 for (SmallVectorImpl<unsigned>::iterator 9548 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 9549 CSI != CSE; ++CSI) { 9550 CallSiteNumToLPad[*CSI].push_back(&*BB); 9551 MaxCSNum = std::max(MaxCSNum, *CSI); 9552 } 9553 break; 9554 } 9555 } 9556 9557 // Get an ordered list of the machine basic blocks for the jump table. 9558 std::vector<MachineBasicBlock*> LPadList; 9559 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 9560 LPadList.reserve(CallSiteNumToLPad.size()); 9561 for (unsigned I = 1; I <= MaxCSNum; ++I) { 9562 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 9563 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9564 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 9565 LPadList.push_back(*II); 9566 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 9567 } 9568 } 9569 9570 assert(!LPadList.empty() && 9571 "No landing pad destinations for the dispatch jump table!"); 9572 9573 // Create the jump table and associated information. 9574 MachineJumpTableInfo *JTI = 9575 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 9576 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 9577 9578 // Create the MBBs for the dispatch code. 9579 9580 // Shove the dispatch's address into the return slot in the function context. 9581 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 9582 DispatchBB->setIsEHPad(); 9583 9584 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9585 unsigned trap_opcode; 9586 if (Subtarget->isThumb()) 9587 trap_opcode = ARM::tTRAP; 9588 else 9589 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 9590 9591 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 9592 DispatchBB->addSuccessor(TrapBB); 9593 9594 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 9595 DispatchBB->addSuccessor(DispContBB); 9596 9597 // Insert and MBBs. 9598 MF->insert(MF->end(), DispatchBB); 9599 MF->insert(MF->end(), DispContBB); 9600 MF->insert(MF->end(), TrapBB); 9601 9602 // Insert code into the entry block that creates and registers the function 9603 // context. 9604 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 9605 9606 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 9607 MachinePointerInfo::getFixedStack(*MF, FI), 9608 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 9609 9610 MachineInstrBuilder MIB; 9611 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 9612 9613 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 9614 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 9615 9616 // Add a register mask with no preserved registers. This results in all 9617 // registers being marked as clobbered. This can't work if the dispatch block 9618 // is in a Thumb1 function and is linked with ARM code which uses the FP 9619 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 9620 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 9621 9622 bool IsPositionIndependent = isPositionIndependent(); 9623 unsigned NumLPads = LPadList.size(); 9624 if (Subtarget->isThumb2()) { 9625 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9626 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 9627 .addFrameIndex(FI) 9628 .addImm(4) 9629 .addMemOperand(FIMMOLd) 9630 .add(predOps(ARMCC::AL)); 9631 9632 if (NumLPads < 256) { 9633 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 9634 .addReg(NewVReg1) 9635 .addImm(LPadList.size()) 9636 .add(predOps(ARMCC::AL)); 9637 } else { 9638 Register VReg1 = MRI->createVirtualRegister(TRC); 9639 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 9640 .addImm(NumLPads & 0xFFFF) 9641 .add(predOps(ARMCC::AL)); 9642 9643 unsigned VReg2 = VReg1; 9644 if ((NumLPads & 0xFFFF0000) != 0) { 9645 VReg2 = MRI->createVirtualRegister(TRC); 9646 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 9647 .addReg(VReg1) 9648 .addImm(NumLPads >> 16) 9649 .add(predOps(ARMCC::AL)); 9650 } 9651 9652 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 9653 .addReg(NewVReg1) 9654 .addReg(VReg2) 9655 .add(predOps(ARMCC::AL)); 9656 } 9657 9658 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 9659 .addMBB(TrapBB) 9660 .addImm(ARMCC::HI) 9661 .addReg(ARM::CPSR); 9662 9663 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9664 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 9665 .addJumpTableIndex(MJTI) 9666 .add(predOps(ARMCC::AL)); 9667 9668 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9669 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 9670 .addReg(NewVReg3, RegState::Kill) 9671 .addReg(NewVReg1) 9672 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9673 .add(predOps(ARMCC::AL)) 9674 .add(condCodeOp()); 9675 9676 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 9677 .addReg(NewVReg4, RegState::Kill) 9678 .addReg(NewVReg1) 9679 .addJumpTableIndex(MJTI); 9680 } else if (Subtarget->isThumb()) { 9681 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9682 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 9683 .addFrameIndex(FI) 9684 .addImm(1) 9685 .addMemOperand(FIMMOLd) 9686 .add(predOps(ARMCC::AL)); 9687 9688 if (NumLPads < 256) { 9689 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 9690 .addReg(NewVReg1) 9691 .addImm(NumLPads) 9692 .add(predOps(ARMCC::AL)); 9693 } else { 9694 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9695 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9696 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9697 9698 // MachineConstantPool wants an explicit alignment. 9699 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9700 if (Align == 0) 9701 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9702 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9703 9704 Register VReg1 = MRI->createVirtualRegister(TRC); 9705 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 9706 .addReg(VReg1, RegState::Define) 9707 .addConstantPoolIndex(Idx) 9708 .add(predOps(ARMCC::AL)); 9709 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 9710 .addReg(NewVReg1) 9711 .addReg(VReg1) 9712 .add(predOps(ARMCC::AL)); 9713 } 9714 9715 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 9716 .addMBB(TrapBB) 9717 .addImm(ARMCC::HI) 9718 .addReg(ARM::CPSR); 9719 9720 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9721 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 9722 .addReg(ARM::CPSR, RegState::Define) 9723 .addReg(NewVReg1) 9724 .addImm(2) 9725 .add(predOps(ARMCC::AL)); 9726 9727 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9728 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 9729 .addJumpTableIndex(MJTI) 9730 .add(predOps(ARMCC::AL)); 9731 9732 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9733 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 9734 .addReg(ARM::CPSR, RegState::Define) 9735 .addReg(NewVReg2, RegState::Kill) 9736 .addReg(NewVReg3) 9737 .add(predOps(ARMCC::AL)); 9738 9739 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9740 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9741 9742 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9743 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 9744 .addReg(NewVReg4, RegState::Kill) 9745 .addImm(0) 9746 .addMemOperand(JTMMOLd) 9747 .add(predOps(ARMCC::AL)); 9748 9749 unsigned NewVReg6 = NewVReg5; 9750 if (IsPositionIndependent) { 9751 NewVReg6 = MRI->createVirtualRegister(TRC); 9752 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 9753 .addReg(ARM::CPSR, RegState::Define) 9754 .addReg(NewVReg5, RegState::Kill) 9755 .addReg(NewVReg3) 9756 .add(predOps(ARMCC::AL)); 9757 } 9758 9759 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 9760 .addReg(NewVReg6, RegState::Kill) 9761 .addJumpTableIndex(MJTI); 9762 } else { 9763 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9764 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 9765 .addFrameIndex(FI) 9766 .addImm(4) 9767 .addMemOperand(FIMMOLd) 9768 .add(predOps(ARMCC::AL)); 9769 9770 if (NumLPads < 256) { 9771 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 9772 .addReg(NewVReg1) 9773 .addImm(NumLPads) 9774 .add(predOps(ARMCC::AL)); 9775 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 9776 Register VReg1 = MRI->createVirtualRegister(TRC); 9777 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 9778 .addImm(NumLPads & 0xFFFF) 9779 .add(predOps(ARMCC::AL)); 9780 9781 unsigned VReg2 = VReg1; 9782 if ((NumLPads & 0xFFFF0000) != 0) { 9783 VReg2 = MRI->createVirtualRegister(TRC); 9784 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 9785 .addReg(VReg1) 9786 .addImm(NumLPads >> 16) 9787 .add(predOps(ARMCC::AL)); 9788 } 9789 9790 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9791 .addReg(NewVReg1) 9792 .addReg(VReg2) 9793 .add(predOps(ARMCC::AL)); 9794 } else { 9795 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9796 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9797 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9798 9799 // MachineConstantPool wants an explicit alignment. 9800 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9801 if (Align == 0) 9802 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9803 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9804 9805 Register VReg1 = MRI->createVirtualRegister(TRC); 9806 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 9807 .addReg(VReg1, RegState::Define) 9808 .addConstantPoolIndex(Idx) 9809 .addImm(0) 9810 .add(predOps(ARMCC::AL)); 9811 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9812 .addReg(NewVReg1) 9813 .addReg(VReg1, RegState::Kill) 9814 .add(predOps(ARMCC::AL)); 9815 } 9816 9817 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 9818 .addMBB(TrapBB) 9819 .addImm(ARMCC::HI) 9820 .addReg(ARM::CPSR); 9821 9822 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9823 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 9824 .addReg(NewVReg1) 9825 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9826 .add(predOps(ARMCC::AL)) 9827 .add(condCodeOp()); 9828 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9829 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 9830 .addJumpTableIndex(MJTI) 9831 .add(predOps(ARMCC::AL)); 9832 9833 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9834 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9835 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9836 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 9837 .addReg(NewVReg3, RegState::Kill) 9838 .addReg(NewVReg4) 9839 .addImm(0) 9840 .addMemOperand(JTMMOLd) 9841 .add(predOps(ARMCC::AL)); 9842 9843 if (IsPositionIndependent) { 9844 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 9845 .addReg(NewVReg5, RegState::Kill) 9846 .addReg(NewVReg4) 9847 .addJumpTableIndex(MJTI); 9848 } else { 9849 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 9850 .addReg(NewVReg5, RegState::Kill) 9851 .addJumpTableIndex(MJTI); 9852 } 9853 } 9854 9855 // Add the jump table entries as successors to the MBB. 9856 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 9857 for (std::vector<MachineBasicBlock*>::iterator 9858 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 9859 MachineBasicBlock *CurMBB = *I; 9860 if (SeenMBBs.insert(CurMBB).second) 9861 DispContBB->addSuccessor(CurMBB); 9862 } 9863 9864 // N.B. the order the invoke BBs are processed in doesn't matter here. 9865 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 9866 SmallVector<MachineBasicBlock*, 64> MBBLPads; 9867 for (MachineBasicBlock *BB : InvokeBBs) { 9868 9869 // Remove the landing pad successor from the invoke block and replace it 9870 // with the new dispatch block. 9871 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 9872 BB->succ_end()); 9873 while (!Successors.empty()) { 9874 MachineBasicBlock *SMBB = Successors.pop_back_val(); 9875 if (SMBB->isEHPad()) { 9876 BB->removeSuccessor(SMBB); 9877 MBBLPads.push_back(SMBB); 9878 } 9879 } 9880 9881 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 9882 BB->normalizeSuccProbs(); 9883 9884 // Find the invoke call and mark all of the callee-saved registers as 9885 // 'implicit defined' so that they're spilled. This prevents code from 9886 // moving instructions to before the EH block, where they will never be 9887 // executed. 9888 for (MachineBasicBlock::reverse_iterator 9889 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 9890 if (!II->isCall()) continue; 9891 9892 DenseMap<unsigned, bool> DefRegs; 9893 for (MachineInstr::mop_iterator 9894 OI = II->operands_begin(), OE = II->operands_end(); 9895 OI != OE; ++OI) { 9896 if (!OI->isReg()) continue; 9897 DefRegs[OI->getReg()] = true; 9898 } 9899 9900 MachineInstrBuilder MIB(*MF, &*II); 9901 9902 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 9903 unsigned Reg = SavedRegs[i]; 9904 if (Subtarget->isThumb2() && 9905 !ARM::tGPRRegClass.contains(Reg) && 9906 !ARM::hGPRRegClass.contains(Reg)) 9907 continue; 9908 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 9909 continue; 9910 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 9911 continue; 9912 if (!DefRegs[Reg]) 9913 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 9914 } 9915 9916 break; 9917 } 9918 } 9919 9920 // Mark all former landing pads as non-landing pads. The dispatch is the only 9921 // landing pad now. 9922 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9923 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 9924 (*I)->setIsEHPad(false); 9925 9926 // The instruction is gone now. 9927 MI.eraseFromParent(); 9928 } 9929 9930 static 9931 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 9932 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 9933 E = MBB->succ_end(); I != E; ++I) 9934 if (*I != Succ) 9935 return *I; 9936 llvm_unreachable("Expecting a BB with two successors!"); 9937 } 9938 9939 /// Return the load opcode for a given load size. If load size >= 8, 9940 /// neon opcode will be returned. 9941 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 9942 if (LdSize >= 8) 9943 return LdSize == 16 ? ARM::VLD1q32wb_fixed 9944 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 9945 if (IsThumb1) 9946 return LdSize == 4 ? ARM::tLDRi 9947 : LdSize == 2 ? ARM::tLDRHi 9948 : LdSize == 1 ? ARM::tLDRBi : 0; 9949 if (IsThumb2) 9950 return LdSize == 4 ? ARM::t2LDR_POST 9951 : LdSize == 2 ? ARM::t2LDRH_POST 9952 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 9953 return LdSize == 4 ? ARM::LDR_POST_IMM 9954 : LdSize == 2 ? ARM::LDRH_POST 9955 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 9956 } 9957 9958 /// Return the store opcode for a given store size. If store size >= 8, 9959 /// neon opcode will be returned. 9960 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 9961 if (StSize >= 8) 9962 return StSize == 16 ? ARM::VST1q32wb_fixed 9963 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 9964 if (IsThumb1) 9965 return StSize == 4 ? ARM::tSTRi 9966 : StSize == 2 ? ARM::tSTRHi 9967 : StSize == 1 ? ARM::tSTRBi : 0; 9968 if (IsThumb2) 9969 return StSize == 4 ? ARM::t2STR_POST 9970 : StSize == 2 ? ARM::t2STRH_POST 9971 : StSize == 1 ? ARM::t2STRB_POST : 0; 9972 return StSize == 4 ? ARM::STR_POST_IMM 9973 : StSize == 2 ? ARM::STRH_POST 9974 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 9975 } 9976 9977 /// Emit a post-increment load operation with given size. The instructions 9978 /// will be added to BB at Pos. 9979 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9980 const TargetInstrInfo *TII, const DebugLoc &dl, 9981 unsigned LdSize, unsigned Data, unsigned AddrIn, 9982 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9983 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 9984 assert(LdOpc != 0 && "Should have a load opcode"); 9985 if (LdSize >= 8) { 9986 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9987 .addReg(AddrOut, RegState::Define) 9988 .addReg(AddrIn) 9989 .addImm(0) 9990 .add(predOps(ARMCC::AL)); 9991 } else if (IsThumb1) { 9992 // load + update AddrIn 9993 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9994 .addReg(AddrIn) 9995 .addImm(0) 9996 .add(predOps(ARMCC::AL)); 9997 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9998 .add(t1CondCodeOp()) 9999 .addReg(AddrIn) 10000 .addImm(LdSize) 10001 .add(predOps(ARMCC::AL)); 10002 } else if (IsThumb2) { 10003 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10004 .addReg(AddrOut, RegState::Define) 10005 .addReg(AddrIn) 10006 .addImm(LdSize) 10007 .add(predOps(ARMCC::AL)); 10008 } else { // arm 10009 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10010 .addReg(AddrOut, RegState::Define) 10011 .addReg(AddrIn) 10012 .addReg(0) 10013 .addImm(LdSize) 10014 .add(predOps(ARMCC::AL)); 10015 } 10016 } 10017 10018 /// Emit a post-increment store operation with given size. The instructions 10019 /// will be added to BB at Pos. 10020 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10021 const TargetInstrInfo *TII, const DebugLoc &dl, 10022 unsigned StSize, unsigned Data, unsigned AddrIn, 10023 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10024 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 10025 assert(StOpc != 0 && "Should have a store opcode"); 10026 if (StSize >= 8) { 10027 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10028 .addReg(AddrIn) 10029 .addImm(0) 10030 .addReg(Data) 10031 .add(predOps(ARMCC::AL)); 10032 } else if (IsThumb1) { 10033 // store + update AddrIn 10034 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 10035 .addReg(Data) 10036 .addReg(AddrIn) 10037 .addImm(0) 10038 .add(predOps(ARMCC::AL)); 10039 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10040 .add(t1CondCodeOp()) 10041 .addReg(AddrIn) 10042 .addImm(StSize) 10043 .add(predOps(ARMCC::AL)); 10044 } else if (IsThumb2) { 10045 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10046 .addReg(Data) 10047 .addReg(AddrIn) 10048 .addImm(StSize) 10049 .add(predOps(ARMCC::AL)); 10050 } else { // arm 10051 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10052 .addReg(Data) 10053 .addReg(AddrIn) 10054 .addReg(0) 10055 .addImm(StSize) 10056 .add(predOps(ARMCC::AL)); 10057 } 10058 } 10059 10060 MachineBasicBlock * 10061 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 10062 MachineBasicBlock *BB) const { 10063 // This pseudo instruction has 3 operands: dst, src, size 10064 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 10065 // Otherwise, we will generate unrolled scalar copies. 10066 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10067 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10068 MachineFunction::iterator It = ++BB->getIterator(); 10069 10070 Register dest = MI.getOperand(0).getReg(); 10071 Register src = MI.getOperand(1).getReg(); 10072 unsigned SizeVal = MI.getOperand(2).getImm(); 10073 unsigned Align = MI.getOperand(3).getImm(); 10074 DebugLoc dl = MI.getDebugLoc(); 10075 10076 MachineFunction *MF = BB->getParent(); 10077 MachineRegisterInfo &MRI = MF->getRegInfo(); 10078 unsigned UnitSize = 0; 10079 const TargetRegisterClass *TRC = nullptr; 10080 const TargetRegisterClass *VecTRC = nullptr; 10081 10082 bool IsThumb1 = Subtarget->isThumb1Only(); 10083 bool IsThumb2 = Subtarget->isThumb2(); 10084 bool IsThumb = Subtarget->isThumb(); 10085 10086 if (Align & 1) { 10087 UnitSize = 1; 10088 } else if (Align & 2) { 10089 UnitSize = 2; 10090 } else { 10091 // Check whether we can use NEON instructions. 10092 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 10093 Subtarget->hasNEON()) { 10094 if ((Align % 16 == 0) && SizeVal >= 16) 10095 UnitSize = 16; 10096 else if ((Align % 8 == 0) && SizeVal >= 8) 10097 UnitSize = 8; 10098 } 10099 // Can't use NEON instructions. 10100 if (UnitSize == 0) 10101 UnitSize = 4; 10102 } 10103 10104 // Select the correct opcode and register class for unit size load/store 10105 bool IsNeon = UnitSize >= 8; 10106 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 10107 if (IsNeon) 10108 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 10109 : UnitSize == 8 ? &ARM::DPRRegClass 10110 : nullptr; 10111 10112 unsigned BytesLeft = SizeVal % UnitSize; 10113 unsigned LoopSize = SizeVal - BytesLeft; 10114 10115 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 10116 // Use LDR and STR to copy. 10117 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 10118 // [destOut] = STR_POST(scratch, destIn, UnitSize) 10119 unsigned srcIn = src; 10120 unsigned destIn = dest; 10121 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 10122 Register srcOut = MRI.createVirtualRegister(TRC); 10123 Register destOut = MRI.createVirtualRegister(TRC); 10124 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10125 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 10126 IsThumb1, IsThumb2); 10127 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 10128 IsThumb1, IsThumb2); 10129 srcIn = srcOut; 10130 destIn = destOut; 10131 } 10132 10133 // Handle the leftover bytes with LDRB and STRB. 10134 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 10135 // [destOut] = STRB_POST(scratch, destIn, 1) 10136 for (unsigned i = 0; i < BytesLeft; i++) { 10137 Register srcOut = MRI.createVirtualRegister(TRC); 10138 Register destOut = MRI.createVirtualRegister(TRC); 10139 Register scratch = MRI.createVirtualRegister(TRC); 10140 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 10141 IsThumb1, IsThumb2); 10142 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 10143 IsThumb1, IsThumb2); 10144 srcIn = srcOut; 10145 destIn = destOut; 10146 } 10147 MI.eraseFromParent(); // The instruction is gone now. 10148 return BB; 10149 } 10150 10151 // Expand the pseudo op to a loop. 10152 // thisMBB: 10153 // ... 10154 // movw varEnd, # --> with thumb2 10155 // movt varEnd, # 10156 // ldrcp varEnd, idx --> without thumb2 10157 // fallthrough --> loopMBB 10158 // loopMBB: 10159 // PHI varPhi, varEnd, varLoop 10160 // PHI srcPhi, src, srcLoop 10161 // PHI destPhi, dst, destLoop 10162 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10163 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 10164 // subs varLoop, varPhi, #UnitSize 10165 // bne loopMBB 10166 // fallthrough --> exitMBB 10167 // exitMBB: 10168 // epilogue to handle left-over bytes 10169 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10170 // [destOut] = STRB_POST(scratch, destLoop, 1) 10171 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10172 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10173 MF->insert(It, loopMBB); 10174 MF->insert(It, exitMBB); 10175 10176 // Transfer the remainder of BB and its successor edges to exitMBB. 10177 exitMBB->splice(exitMBB->begin(), BB, 10178 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10179 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10180 10181 // Load an immediate to varEnd. 10182 Register varEnd = MRI.createVirtualRegister(TRC); 10183 if (Subtarget->useMovt()) { 10184 unsigned Vtmp = varEnd; 10185 if ((LoopSize & 0xFFFF0000) != 0) 10186 Vtmp = MRI.createVirtualRegister(TRC); 10187 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 10188 .addImm(LoopSize & 0xFFFF) 10189 .add(predOps(ARMCC::AL)); 10190 10191 if ((LoopSize & 0xFFFF0000) != 0) 10192 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 10193 .addReg(Vtmp) 10194 .addImm(LoopSize >> 16) 10195 .add(predOps(ARMCC::AL)); 10196 } else { 10197 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10198 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10199 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 10200 10201 // MachineConstantPool wants an explicit alignment. 10202 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 10203 if (Align == 0) 10204 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 10205 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 10206 MachineMemOperand *CPMMO = 10207 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 10208 MachineMemOperand::MOLoad, 4, 4); 10209 10210 if (IsThumb) 10211 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 10212 .addReg(varEnd, RegState::Define) 10213 .addConstantPoolIndex(Idx) 10214 .add(predOps(ARMCC::AL)) 10215 .addMemOperand(CPMMO); 10216 else 10217 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 10218 .addReg(varEnd, RegState::Define) 10219 .addConstantPoolIndex(Idx) 10220 .addImm(0) 10221 .add(predOps(ARMCC::AL)) 10222 .addMemOperand(CPMMO); 10223 } 10224 BB->addSuccessor(loopMBB); 10225 10226 // Generate the loop body: 10227 // varPhi = PHI(varLoop, varEnd) 10228 // srcPhi = PHI(srcLoop, src) 10229 // destPhi = PHI(destLoop, dst) 10230 MachineBasicBlock *entryBB = BB; 10231 BB = loopMBB; 10232 Register varLoop = MRI.createVirtualRegister(TRC); 10233 Register varPhi = MRI.createVirtualRegister(TRC); 10234 Register srcLoop = MRI.createVirtualRegister(TRC); 10235 Register srcPhi = MRI.createVirtualRegister(TRC); 10236 Register destLoop = MRI.createVirtualRegister(TRC); 10237 Register destPhi = MRI.createVirtualRegister(TRC); 10238 10239 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 10240 .addReg(varLoop).addMBB(loopMBB) 10241 .addReg(varEnd).addMBB(entryBB); 10242 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 10243 .addReg(srcLoop).addMBB(loopMBB) 10244 .addReg(src).addMBB(entryBB); 10245 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 10246 .addReg(destLoop).addMBB(loopMBB) 10247 .addReg(dest).addMBB(entryBB); 10248 10249 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10250 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 10251 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10252 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 10253 IsThumb1, IsThumb2); 10254 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 10255 IsThumb1, IsThumb2); 10256 10257 // Decrement loop variable by UnitSize. 10258 if (IsThumb1) { 10259 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 10260 .add(t1CondCodeOp()) 10261 .addReg(varPhi) 10262 .addImm(UnitSize) 10263 .add(predOps(ARMCC::AL)); 10264 } else { 10265 MachineInstrBuilder MIB = 10266 BuildMI(*BB, BB->end(), dl, 10267 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 10268 MIB.addReg(varPhi) 10269 .addImm(UnitSize) 10270 .add(predOps(ARMCC::AL)) 10271 .add(condCodeOp()); 10272 MIB->getOperand(5).setReg(ARM::CPSR); 10273 MIB->getOperand(5).setIsDef(true); 10274 } 10275 BuildMI(*BB, BB->end(), dl, 10276 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10277 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 10278 10279 // loopMBB can loop back to loopMBB or fall through to exitMBB. 10280 BB->addSuccessor(loopMBB); 10281 BB->addSuccessor(exitMBB); 10282 10283 // Add epilogue to handle BytesLeft. 10284 BB = exitMBB; 10285 auto StartOfExit = exitMBB->begin(); 10286 10287 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10288 // [destOut] = STRB_POST(scratch, destLoop, 1) 10289 unsigned srcIn = srcLoop; 10290 unsigned destIn = destLoop; 10291 for (unsigned i = 0; i < BytesLeft; i++) { 10292 Register srcOut = MRI.createVirtualRegister(TRC); 10293 Register destOut = MRI.createVirtualRegister(TRC); 10294 Register scratch = MRI.createVirtualRegister(TRC); 10295 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 10296 IsThumb1, IsThumb2); 10297 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 10298 IsThumb1, IsThumb2); 10299 srcIn = srcOut; 10300 destIn = destOut; 10301 } 10302 10303 MI.eraseFromParent(); // The instruction is gone now. 10304 return BB; 10305 } 10306 10307 MachineBasicBlock * 10308 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 10309 MachineBasicBlock *MBB) const { 10310 const TargetMachine &TM = getTargetMachine(); 10311 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 10312 DebugLoc DL = MI.getDebugLoc(); 10313 10314 assert(Subtarget->isTargetWindows() && 10315 "__chkstk is only supported on Windows"); 10316 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 10317 10318 // __chkstk takes the number of words to allocate on the stack in R4, and 10319 // returns the stack adjustment in number of bytes in R4. This will not 10320 // clober any other registers (other than the obvious lr). 10321 // 10322 // Although, technically, IP should be considered a register which may be 10323 // clobbered, the call itself will not touch it. Windows on ARM is a pure 10324 // thumb-2 environment, so there is no interworking required. As a result, we 10325 // do not expect a veneer to be emitted by the linker, clobbering IP. 10326 // 10327 // Each module receives its own copy of __chkstk, so no import thunk is 10328 // required, again, ensuring that IP is not clobbered. 10329 // 10330 // Finally, although some linkers may theoretically provide a trampoline for 10331 // out of range calls (which is quite common due to a 32M range limitation of 10332 // branches for Thumb), we can generate the long-call version via 10333 // -mcmodel=large, alleviating the need for the trampoline which may clobber 10334 // IP. 10335 10336 switch (TM.getCodeModel()) { 10337 case CodeModel::Tiny: 10338 llvm_unreachable("Tiny code model not available on ARM."); 10339 case CodeModel::Small: 10340 case CodeModel::Medium: 10341 case CodeModel::Kernel: 10342 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 10343 .add(predOps(ARMCC::AL)) 10344 .addExternalSymbol("__chkstk") 10345 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10346 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10347 .addReg(ARM::R12, 10348 RegState::Implicit | RegState::Define | RegState::Dead) 10349 .addReg(ARM::CPSR, 10350 RegState::Implicit | RegState::Define | RegState::Dead); 10351 break; 10352 case CodeModel::Large: { 10353 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 10354 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 10355 10356 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 10357 .addExternalSymbol("__chkstk"); 10358 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 10359 .add(predOps(ARMCC::AL)) 10360 .addReg(Reg, RegState::Kill) 10361 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10362 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10363 .addReg(ARM::R12, 10364 RegState::Implicit | RegState::Define | RegState::Dead) 10365 .addReg(ARM::CPSR, 10366 RegState::Implicit | RegState::Define | RegState::Dead); 10367 break; 10368 } 10369 } 10370 10371 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 10372 .addReg(ARM::SP, RegState::Kill) 10373 .addReg(ARM::R4, RegState::Kill) 10374 .setMIFlags(MachineInstr::FrameSetup) 10375 .add(predOps(ARMCC::AL)) 10376 .add(condCodeOp()); 10377 10378 MI.eraseFromParent(); 10379 return MBB; 10380 } 10381 10382 MachineBasicBlock * 10383 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 10384 MachineBasicBlock *MBB) const { 10385 DebugLoc DL = MI.getDebugLoc(); 10386 MachineFunction *MF = MBB->getParent(); 10387 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10388 10389 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 10390 MF->insert(++MBB->getIterator(), ContBB); 10391 ContBB->splice(ContBB->begin(), MBB, 10392 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10393 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 10394 MBB->addSuccessor(ContBB); 10395 10396 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10397 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 10398 MF->push_back(TrapBB); 10399 MBB->addSuccessor(TrapBB); 10400 10401 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 10402 .addReg(MI.getOperand(0).getReg()) 10403 .addImm(0) 10404 .add(predOps(ARMCC::AL)); 10405 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 10406 .addMBB(TrapBB) 10407 .addImm(ARMCC::EQ) 10408 .addReg(ARM::CPSR); 10409 10410 MI.eraseFromParent(); 10411 return ContBB; 10412 } 10413 10414 // The CPSR operand of SelectItr might be missing a kill marker 10415 // because there were multiple uses of CPSR, and ISel didn't know 10416 // which to mark. Figure out whether SelectItr should have had a 10417 // kill marker, and set it if it should. Returns the correct kill 10418 // marker value. 10419 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 10420 MachineBasicBlock* BB, 10421 const TargetRegisterInfo* TRI) { 10422 // Scan forward through BB for a use/def of CPSR. 10423 MachineBasicBlock::iterator miI(std::next(SelectItr)); 10424 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 10425 const MachineInstr& mi = *miI; 10426 if (mi.readsRegister(ARM::CPSR)) 10427 return false; 10428 if (mi.definesRegister(ARM::CPSR)) 10429 break; // Should have kill-flag - update below. 10430 } 10431 10432 // If we hit the end of the block, check whether CPSR is live into a 10433 // successor. 10434 if (miI == BB->end()) { 10435 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 10436 sEnd = BB->succ_end(); 10437 sItr != sEnd; ++sItr) { 10438 MachineBasicBlock* succ = *sItr; 10439 if (succ->isLiveIn(ARM::CPSR)) 10440 return false; 10441 } 10442 } 10443 10444 // We found a def, or hit the end of the basic block and CPSR wasn't live 10445 // out. SelectMI should have a kill flag on CPSR. 10446 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 10447 return true; 10448 } 10449 10450 MachineBasicBlock * 10451 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10452 MachineBasicBlock *BB) const { 10453 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10454 DebugLoc dl = MI.getDebugLoc(); 10455 bool isThumb2 = Subtarget->isThumb2(); 10456 switch (MI.getOpcode()) { 10457 default: { 10458 MI.print(errs()); 10459 llvm_unreachable("Unexpected instr type to insert"); 10460 } 10461 10462 // Thumb1 post-indexed loads are really just single-register LDMs. 10463 case ARM::tLDR_postidx: { 10464 MachineOperand Def(MI.getOperand(1)); 10465 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 10466 .add(Def) // Rn_wb 10467 .add(MI.getOperand(2)) // Rn 10468 .add(MI.getOperand(3)) // PredImm 10469 .add(MI.getOperand(4)) // PredReg 10470 .add(MI.getOperand(0)) // Rt 10471 .cloneMemRefs(MI); 10472 MI.eraseFromParent(); 10473 return BB; 10474 } 10475 10476 // The Thumb2 pre-indexed stores have the same MI operands, they just 10477 // define them differently in the .td files from the isel patterns, so 10478 // they need pseudos. 10479 case ARM::t2STR_preidx: 10480 MI.setDesc(TII->get(ARM::t2STR_PRE)); 10481 return BB; 10482 case ARM::t2STRB_preidx: 10483 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 10484 return BB; 10485 case ARM::t2STRH_preidx: 10486 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 10487 return BB; 10488 10489 case ARM::STRi_preidx: 10490 case ARM::STRBi_preidx: { 10491 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 10492 : ARM::STRB_PRE_IMM; 10493 // Decode the offset. 10494 unsigned Offset = MI.getOperand(4).getImm(); 10495 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 10496 Offset = ARM_AM::getAM2Offset(Offset); 10497 if (isSub) 10498 Offset = -Offset; 10499 10500 MachineMemOperand *MMO = *MI.memoperands_begin(); 10501 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 10502 .add(MI.getOperand(0)) // Rn_wb 10503 .add(MI.getOperand(1)) // Rt 10504 .add(MI.getOperand(2)) // Rn 10505 .addImm(Offset) // offset (skip GPR==zero_reg) 10506 .add(MI.getOperand(5)) // pred 10507 .add(MI.getOperand(6)) 10508 .addMemOperand(MMO); 10509 MI.eraseFromParent(); 10510 return BB; 10511 } 10512 case ARM::STRr_preidx: 10513 case ARM::STRBr_preidx: 10514 case ARM::STRH_preidx: { 10515 unsigned NewOpc; 10516 switch (MI.getOpcode()) { 10517 default: llvm_unreachable("unexpected opcode!"); 10518 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 10519 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 10520 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 10521 } 10522 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 10523 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 10524 MIB.add(MI.getOperand(i)); 10525 MI.eraseFromParent(); 10526 return BB; 10527 } 10528 10529 case ARM::tMOVCCr_pseudo: { 10530 // To "insert" a SELECT_CC instruction, we actually have to insert the 10531 // diamond control-flow pattern. The incoming instruction knows the 10532 // destination vreg to set, the condition code register to branch on, the 10533 // true/false values to select between, and a branch opcode to use. 10534 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10535 MachineFunction::iterator It = ++BB->getIterator(); 10536 10537 // thisMBB: 10538 // ... 10539 // TrueVal = ... 10540 // cmpTY ccX, r1, r2 10541 // bCC copy1MBB 10542 // fallthrough --> copy0MBB 10543 MachineBasicBlock *thisMBB = BB; 10544 MachineFunction *F = BB->getParent(); 10545 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10546 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10547 F->insert(It, copy0MBB); 10548 F->insert(It, sinkMBB); 10549 10550 // Check whether CPSR is live past the tMOVCCr_pseudo. 10551 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10552 if (!MI.killsRegister(ARM::CPSR) && 10553 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 10554 copy0MBB->addLiveIn(ARM::CPSR); 10555 sinkMBB->addLiveIn(ARM::CPSR); 10556 } 10557 10558 // Transfer the remainder of BB and its successor edges to sinkMBB. 10559 sinkMBB->splice(sinkMBB->begin(), BB, 10560 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10561 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10562 10563 BB->addSuccessor(copy0MBB); 10564 BB->addSuccessor(sinkMBB); 10565 10566 BuildMI(BB, dl, TII->get(ARM::tBcc)) 10567 .addMBB(sinkMBB) 10568 .addImm(MI.getOperand(3).getImm()) 10569 .addReg(MI.getOperand(4).getReg()); 10570 10571 // copy0MBB: 10572 // %FalseValue = ... 10573 // # fallthrough to sinkMBB 10574 BB = copy0MBB; 10575 10576 // Update machine-CFG edges 10577 BB->addSuccessor(sinkMBB); 10578 10579 // sinkMBB: 10580 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10581 // ... 10582 BB = sinkMBB; 10583 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 10584 .addReg(MI.getOperand(1).getReg()) 10585 .addMBB(copy0MBB) 10586 .addReg(MI.getOperand(2).getReg()) 10587 .addMBB(thisMBB); 10588 10589 MI.eraseFromParent(); // The pseudo instruction is gone now. 10590 return BB; 10591 } 10592 10593 case ARM::BCCi64: 10594 case ARM::BCCZi64: { 10595 // If there is an unconditional branch to the other successor, remove it. 10596 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10597 10598 // Compare both parts that make up the double comparison separately for 10599 // equality. 10600 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 10601 10602 Register LHS1 = MI.getOperand(1).getReg(); 10603 Register LHS2 = MI.getOperand(2).getReg(); 10604 if (RHSisZero) { 10605 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10606 .addReg(LHS1) 10607 .addImm(0) 10608 .add(predOps(ARMCC::AL)); 10609 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10610 .addReg(LHS2).addImm(0) 10611 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10612 } else { 10613 Register RHS1 = MI.getOperand(3).getReg(); 10614 Register RHS2 = MI.getOperand(4).getReg(); 10615 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10616 .addReg(LHS1) 10617 .addReg(RHS1) 10618 .add(predOps(ARMCC::AL)); 10619 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10620 .addReg(LHS2).addReg(RHS2) 10621 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10622 } 10623 10624 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 10625 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 10626 if (MI.getOperand(0).getImm() == ARMCC::NE) 10627 std::swap(destMBB, exitMBB); 10628 10629 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10630 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 10631 if (isThumb2) 10632 BuildMI(BB, dl, TII->get(ARM::t2B)) 10633 .addMBB(exitMBB) 10634 .add(predOps(ARMCC::AL)); 10635 else 10636 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 10637 10638 MI.eraseFromParent(); // The pseudo instruction is gone now. 10639 return BB; 10640 } 10641 10642 case ARM::Int_eh_sjlj_setjmp: 10643 case ARM::Int_eh_sjlj_setjmp_nofp: 10644 case ARM::tInt_eh_sjlj_setjmp: 10645 case ARM::t2Int_eh_sjlj_setjmp: 10646 case ARM::t2Int_eh_sjlj_setjmp_nofp: 10647 return BB; 10648 10649 case ARM::Int_eh_sjlj_setup_dispatch: 10650 EmitSjLjDispatchBlock(MI, BB); 10651 return BB; 10652 10653 case ARM::ABS: 10654 case ARM::t2ABS: { 10655 // To insert an ABS instruction, we have to insert the 10656 // diamond control-flow pattern. The incoming instruction knows the 10657 // source vreg to test against 0, the destination vreg to set, 10658 // the condition code register to branch on, the 10659 // true/false values to select between, and a branch opcode to use. 10660 // It transforms 10661 // V1 = ABS V0 10662 // into 10663 // V2 = MOVS V0 10664 // BCC (branch to SinkBB if V0 >= 0) 10665 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 10666 // SinkBB: V1 = PHI(V2, V3) 10667 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10668 MachineFunction::iterator BBI = ++BB->getIterator(); 10669 MachineFunction *Fn = BB->getParent(); 10670 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10671 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10672 Fn->insert(BBI, RSBBB); 10673 Fn->insert(BBI, SinkBB); 10674 10675 Register ABSSrcReg = MI.getOperand(1).getReg(); 10676 Register ABSDstReg = MI.getOperand(0).getReg(); 10677 bool ABSSrcKIll = MI.getOperand(1).isKill(); 10678 bool isThumb2 = Subtarget->isThumb2(); 10679 MachineRegisterInfo &MRI = Fn->getRegInfo(); 10680 // In Thumb mode S must not be specified if source register is the SP or 10681 // PC and if destination register is the SP, so restrict register class 10682 Register NewRsbDstReg = MRI.createVirtualRegister( 10683 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 10684 10685 // Transfer the remainder of BB and its successor edges to sinkMBB. 10686 SinkBB->splice(SinkBB->begin(), BB, 10687 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10688 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 10689 10690 BB->addSuccessor(RSBBB); 10691 BB->addSuccessor(SinkBB); 10692 10693 // fall through to SinkMBB 10694 RSBBB->addSuccessor(SinkBB); 10695 10696 // insert a cmp at the end of BB 10697 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10698 .addReg(ABSSrcReg) 10699 .addImm(0) 10700 .add(predOps(ARMCC::AL)); 10701 10702 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 10703 BuildMI(BB, dl, 10704 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 10705 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 10706 10707 // insert rsbri in RSBBB 10708 // Note: BCC and rsbri will be converted into predicated rsbmi 10709 // by if-conversion pass 10710 BuildMI(*RSBBB, RSBBB->begin(), dl, 10711 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 10712 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 10713 .addImm(0) 10714 .add(predOps(ARMCC::AL)) 10715 .add(condCodeOp()); 10716 10717 // insert PHI in SinkBB, 10718 // reuse ABSDstReg to not change uses of ABS instruction 10719 BuildMI(*SinkBB, SinkBB->begin(), dl, 10720 TII->get(ARM::PHI), ABSDstReg) 10721 .addReg(NewRsbDstReg).addMBB(RSBBB) 10722 .addReg(ABSSrcReg).addMBB(BB); 10723 10724 // remove ABS instruction 10725 MI.eraseFromParent(); 10726 10727 // return last added BB 10728 return SinkBB; 10729 } 10730 case ARM::COPY_STRUCT_BYVAL_I32: 10731 ++NumLoopByVals; 10732 return EmitStructByval(MI, BB); 10733 case ARM::WIN__CHKSTK: 10734 return EmitLowered__chkstk(MI, BB); 10735 case ARM::WIN__DBZCHK: 10736 return EmitLowered__dbzchk(MI, BB); 10737 } 10738 } 10739 10740 /// Attaches vregs to MEMCPY that it will use as scratch registers 10741 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 10742 /// instead of as a custom inserter because we need the use list from the SDNode. 10743 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 10744 MachineInstr &MI, const SDNode *Node) { 10745 bool isThumb1 = Subtarget->isThumb1Only(); 10746 10747 DebugLoc DL = MI.getDebugLoc(); 10748 MachineFunction *MF = MI.getParent()->getParent(); 10749 MachineRegisterInfo &MRI = MF->getRegInfo(); 10750 MachineInstrBuilder MIB(*MF, MI); 10751 10752 // If the new dst/src is unused mark it as dead. 10753 if (!Node->hasAnyUseOfValue(0)) { 10754 MI.getOperand(0).setIsDead(true); 10755 } 10756 if (!Node->hasAnyUseOfValue(1)) { 10757 MI.getOperand(1).setIsDead(true); 10758 } 10759 10760 // The MEMCPY both defines and kills the scratch registers. 10761 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 10762 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 10763 : &ARM::GPRRegClass); 10764 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 10765 } 10766 } 10767 10768 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10769 SDNode *Node) const { 10770 if (MI.getOpcode() == ARM::MEMCPY) { 10771 attachMEMCPYScratchRegs(Subtarget, MI, Node); 10772 return; 10773 } 10774 10775 const MCInstrDesc *MCID = &MI.getDesc(); 10776 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 10777 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 10778 // operand is still set to noreg. If needed, set the optional operand's 10779 // register to CPSR, and remove the redundant implicit def. 10780 // 10781 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 10782 10783 // Rename pseudo opcodes. 10784 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 10785 unsigned ccOutIdx; 10786 if (NewOpc) { 10787 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 10788 MCID = &TII->get(NewOpc); 10789 10790 assert(MCID->getNumOperands() == 10791 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 10792 && "converted opcode should be the same except for cc_out" 10793 " (and, on Thumb1, pred)"); 10794 10795 MI.setDesc(*MCID); 10796 10797 // Add the optional cc_out operand 10798 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 10799 10800 // On Thumb1, move all input operands to the end, then add the predicate 10801 if (Subtarget->isThumb1Only()) { 10802 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 10803 MI.addOperand(MI.getOperand(1)); 10804 MI.RemoveOperand(1); 10805 } 10806 10807 // Restore the ties 10808 for (unsigned i = MI.getNumOperands(); i--;) { 10809 const MachineOperand& op = MI.getOperand(i); 10810 if (op.isReg() && op.isUse()) { 10811 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 10812 if (DefIdx != -1) 10813 MI.tieOperands(DefIdx, i); 10814 } 10815 } 10816 10817 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 10818 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 10819 ccOutIdx = 1; 10820 } else 10821 ccOutIdx = MCID->getNumOperands() - 1; 10822 } else 10823 ccOutIdx = MCID->getNumOperands() - 1; 10824 10825 // Any ARM instruction that sets the 's' bit should specify an optional 10826 // "cc_out" operand in the last operand position. 10827 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 10828 assert(!NewOpc && "Optional cc_out operand required"); 10829 return; 10830 } 10831 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 10832 // since we already have an optional CPSR def. 10833 bool definesCPSR = false; 10834 bool deadCPSR = false; 10835 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 10836 ++i) { 10837 const MachineOperand &MO = MI.getOperand(i); 10838 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 10839 definesCPSR = true; 10840 if (MO.isDead()) 10841 deadCPSR = true; 10842 MI.RemoveOperand(i); 10843 break; 10844 } 10845 } 10846 if (!definesCPSR) { 10847 assert(!NewOpc && "Optional cc_out operand required"); 10848 return; 10849 } 10850 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 10851 if (deadCPSR) { 10852 assert(!MI.getOperand(ccOutIdx).getReg() && 10853 "expect uninitialized optional cc_out operand"); 10854 // Thumb1 instructions must have the S bit even if the CPSR is dead. 10855 if (!Subtarget->isThumb1Only()) 10856 return; 10857 } 10858 10859 // If this instruction was defined with an optional CPSR def and its dag node 10860 // had a live implicit CPSR def, then activate the optional CPSR def. 10861 MachineOperand &MO = MI.getOperand(ccOutIdx); 10862 MO.setReg(ARM::CPSR); 10863 MO.setIsDef(true); 10864 } 10865 10866 //===----------------------------------------------------------------------===// 10867 // ARM Optimization Hooks 10868 //===----------------------------------------------------------------------===// 10869 10870 // Helper function that checks if N is a null or all ones constant. 10871 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 10872 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 10873 } 10874 10875 // Return true if N is conditionally 0 or all ones. 10876 // Detects these expressions where cc is an i1 value: 10877 // 10878 // (select cc 0, y) [AllOnes=0] 10879 // (select cc y, 0) [AllOnes=0] 10880 // (zext cc) [AllOnes=0] 10881 // (sext cc) [AllOnes=0/1] 10882 // (select cc -1, y) [AllOnes=1] 10883 // (select cc y, -1) [AllOnes=1] 10884 // 10885 // Invert is set when N is the null/all ones constant when CC is false. 10886 // OtherOp is set to the alternative value of N. 10887 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 10888 SDValue &CC, bool &Invert, 10889 SDValue &OtherOp, 10890 SelectionDAG &DAG) { 10891 switch (N->getOpcode()) { 10892 default: return false; 10893 case ISD::SELECT: { 10894 CC = N->getOperand(0); 10895 SDValue N1 = N->getOperand(1); 10896 SDValue N2 = N->getOperand(2); 10897 if (isZeroOrAllOnes(N1, AllOnes)) { 10898 Invert = false; 10899 OtherOp = N2; 10900 return true; 10901 } 10902 if (isZeroOrAllOnes(N2, AllOnes)) { 10903 Invert = true; 10904 OtherOp = N1; 10905 return true; 10906 } 10907 return false; 10908 } 10909 case ISD::ZERO_EXTEND: 10910 // (zext cc) can never be the all ones value. 10911 if (AllOnes) 10912 return false; 10913 LLVM_FALLTHROUGH; 10914 case ISD::SIGN_EXTEND: { 10915 SDLoc dl(N); 10916 EVT VT = N->getValueType(0); 10917 CC = N->getOperand(0); 10918 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 10919 return false; 10920 Invert = !AllOnes; 10921 if (AllOnes) 10922 // When looking for an AllOnes constant, N is an sext, and the 'other' 10923 // value is 0. 10924 OtherOp = DAG.getConstant(0, dl, VT); 10925 else if (N->getOpcode() == ISD::ZERO_EXTEND) 10926 // When looking for a 0 constant, N can be zext or sext. 10927 OtherOp = DAG.getConstant(1, dl, VT); 10928 else 10929 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 10930 VT); 10931 return true; 10932 } 10933 } 10934 } 10935 10936 // Combine a constant select operand into its use: 10937 // 10938 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10939 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10940 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 10941 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10942 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10943 // 10944 // The transform is rejected if the select doesn't have a constant operand that 10945 // is null, or all ones when AllOnes is set. 10946 // 10947 // Also recognize sext/zext from i1: 10948 // 10949 // (add (zext cc), x) -> (select cc (add x, 1), x) 10950 // (add (sext cc), x) -> (select cc (add x, -1), x) 10951 // 10952 // These transformations eventually create predicated instructions. 10953 // 10954 // @param N The node to transform. 10955 // @param Slct The N operand that is a select. 10956 // @param OtherOp The other N operand (x above). 10957 // @param DCI Context. 10958 // @param AllOnes Require the select constant to be all ones instead of null. 10959 // @returns The new node, or SDValue() on failure. 10960 static 10961 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 10962 TargetLowering::DAGCombinerInfo &DCI, 10963 bool AllOnes = false) { 10964 SelectionDAG &DAG = DCI.DAG; 10965 EVT VT = N->getValueType(0); 10966 SDValue NonConstantVal; 10967 SDValue CCOp; 10968 bool SwapSelectOps; 10969 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 10970 NonConstantVal, DAG)) 10971 return SDValue(); 10972 10973 // Slct is now know to be the desired identity constant when CC is true. 10974 SDValue TrueVal = OtherOp; 10975 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 10976 OtherOp, NonConstantVal); 10977 // Unless SwapSelectOps says CC should be false. 10978 if (SwapSelectOps) 10979 std::swap(TrueVal, FalseVal); 10980 10981 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 10982 CCOp, TrueVal, FalseVal); 10983 } 10984 10985 // Attempt combineSelectAndUse on each operand of a commutative operator N. 10986 static 10987 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 10988 TargetLowering::DAGCombinerInfo &DCI) { 10989 SDValue N0 = N->getOperand(0); 10990 SDValue N1 = N->getOperand(1); 10991 if (N0.getNode()->hasOneUse()) 10992 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 10993 return Result; 10994 if (N1.getNode()->hasOneUse()) 10995 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 10996 return Result; 10997 return SDValue(); 10998 } 10999 11000 static bool IsVUZPShuffleNode(SDNode *N) { 11001 // VUZP shuffle node. 11002 if (N->getOpcode() == ARMISD::VUZP) 11003 return true; 11004 11005 // "VUZP" on i32 is an alias for VTRN. 11006 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 11007 return true; 11008 11009 return false; 11010 } 11011 11012 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 11013 TargetLowering::DAGCombinerInfo &DCI, 11014 const ARMSubtarget *Subtarget) { 11015 // Look for ADD(VUZP.0, VUZP.1). 11016 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 11017 N0 == N1) 11018 return SDValue(); 11019 11020 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 11021 if (!N->getValueType(0).is64BitVector()) 11022 return SDValue(); 11023 11024 // Generate vpadd. 11025 SelectionDAG &DAG = DCI.DAG; 11026 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11027 SDLoc dl(N); 11028 SDNode *Unzip = N0.getNode(); 11029 EVT VT = N->getValueType(0); 11030 11031 SmallVector<SDValue, 8> Ops; 11032 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 11033 TLI.getPointerTy(DAG.getDataLayout()))); 11034 Ops.push_back(Unzip->getOperand(0)); 11035 Ops.push_back(Unzip->getOperand(1)); 11036 11037 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11038 } 11039 11040 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11041 TargetLowering::DAGCombinerInfo &DCI, 11042 const ARMSubtarget *Subtarget) { 11043 // Check for two extended operands. 11044 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 11045 N1.getOpcode() == ISD::SIGN_EXTEND) && 11046 !(N0.getOpcode() == ISD::ZERO_EXTEND && 11047 N1.getOpcode() == ISD::ZERO_EXTEND)) 11048 return SDValue(); 11049 11050 SDValue N00 = N0.getOperand(0); 11051 SDValue N10 = N1.getOperand(0); 11052 11053 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 11054 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 11055 N00 == N10) 11056 return SDValue(); 11057 11058 // We only recognize Q register paddl here; this can't be reached until 11059 // after type legalization. 11060 if (!N00.getValueType().is64BitVector() || 11061 !N0.getValueType().is128BitVector()) 11062 return SDValue(); 11063 11064 // Generate vpaddl. 11065 SelectionDAG &DAG = DCI.DAG; 11066 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11067 SDLoc dl(N); 11068 EVT VT = N->getValueType(0); 11069 11070 SmallVector<SDValue, 8> Ops; 11071 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 11072 unsigned Opcode; 11073 if (N0.getOpcode() == ISD::SIGN_EXTEND) 11074 Opcode = Intrinsic::arm_neon_vpaddls; 11075 else 11076 Opcode = Intrinsic::arm_neon_vpaddlu; 11077 Ops.push_back(DAG.getConstant(Opcode, dl, 11078 TLI.getPointerTy(DAG.getDataLayout()))); 11079 EVT ElemTy = N00.getValueType().getVectorElementType(); 11080 unsigned NumElts = VT.getVectorNumElements(); 11081 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 11082 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 11083 N00.getOperand(0), N00.getOperand(1)); 11084 Ops.push_back(Concat); 11085 11086 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11087 } 11088 11089 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 11090 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 11091 // much easier to match. 11092 static SDValue 11093 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11094 TargetLowering::DAGCombinerInfo &DCI, 11095 const ARMSubtarget *Subtarget) { 11096 // Only perform optimization if after legalize, and if NEON is available. We 11097 // also expected both operands to be BUILD_VECTORs. 11098 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 11099 || N0.getOpcode() != ISD::BUILD_VECTOR 11100 || N1.getOpcode() != ISD::BUILD_VECTOR) 11101 return SDValue(); 11102 11103 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 11104 EVT VT = N->getValueType(0); 11105 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 11106 return SDValue(); 11107 11108 // Check that the vector operands are of the right form. 11109 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 11110 // operands, where N is the size of the formed vector. 11111 // Each EXTRACT_VECTOR should have the same input vector and odd or even 11112 // index such that we have a pair wise add pattern. 11113 11114 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 11115 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11116 return SDValue(); 11117 SDValue Vec = N0->getOperand(0)->getOperand(0); 11118 SDNode *V = Vec.getNode(); 11119 unsigned nextIndex = 0; 11120 11121 // For each operands to the ADD which are BUILD_VECTORs, 11122 // check to see if each of their operands are an EXTRACT_VECTOR with 11123 // the same vector and appropriate index. 11124 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 11125 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 11126 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11127 11128 SDValue ExtVec0 = N0->getOperand(i); 11129 SDValue ExtVec1 = N1->getOperand(i); 11130 11131 // First operand is the vector, verify its the same. 11132 if (V != ExtVec0->getOperand(0).getNode() || 11133 V != ExtVec1->getOperand(0).getNode()) 11134 return SDValue(); 11135 11136 // Second is the constant, verify its correct. 11137 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 11138 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 11139 11140 // For the constant, we want to see all the even or all the odd. 11141 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 11142 || C1->getZExtValue() != nextIndex+1) 11143 return SDValue(); 11144 11145 // Increment index. 11146 nextIndex+=2; 11147 } else 11148 return SDValue(); 11149 } 11150 11151 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 11152 // we're using the entire input vector, otherwise there's a size/legality 11153 // mismatch somewhere. 11154 if (nextIndex != Vec.getValueType().getVectorNumElements() || 11155 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 11156 return SDValue(); 11157 11158 // Create VPADDL node. 11159 SelectionDAG &DAG = DCI.DAG; 11160 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11161 11162 SDLoc dl(N); 11163 11164 // Build operand list. 11165 SmallVector<SDValue, 8> Ops; 11166 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 11167 TLI.getPointerTy(DAG.getDataLayout()))); 11168 11169 // Input is the vector. 11170 Ops.push_back(Vec); 11171 11172 // Get widened type and narrowed type. 11173 MVT widenType; 11174 unsigned numElem = VT.getVectorNumElements(); 11175 11176 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 11177 switch (inputLaneType.getSimpleVT().SimpleTy) { 11178 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 11179 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 11180 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 11181 default: 11182 llvm_unreachable("Invalid vector element type for padd optimization."); 11183 } 11184 11185 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 11186 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 11187 return DAG.getNode(ExtOp, dl, VT, tmp); 11188 } 11189 11190 static SDValue findMUL_LOHI(SDValue V) { 11191 if (V->getOpcode() == ISD::UMUL_LOHI || 11192 V->getOpcode() == ISD::SMUL_LOHI) 11193 return V; 11194 return SDValue(); 11195 } 11196 11197 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 11198 TargetLowering::DAGCombinerInfo &DCI, 11199 const ARMSubtarget *Subtarget) { 11200 if (!Subtarget->hasBaseDSP()) 11201 return SDValue(); 11202 11203 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 11204 // accumulates the product into a 64-bit value. The 16-bit values will 11205 // be sign extended somehow or SRA'd into 32-bit values 11206 // (addc (adde (mul 16bit, 16bit), lo), hi) 11207 SDValue Mul = AddcNode->getOperand(0); 11208 SDValue Lo = AddcNode->getOperand(1); 11209 if (Mul.getOpcode() != ISD::MUL) { 11210 Lo = AddcNode->getOperand(0); 11211 Mul = AddcNode->getOperand(1); 11212 if (Mul.getOpcode() != ISD::MUL) 11213 return SDValue(); 11214 } 11215 11216 SDValue SRA = AddeNode->getOperand(0); 11217 SDValue Hi = AddeNode->getOperand(1); 11218 if (SRA.getOpcode() != ISD::SRA) { 11219 SRA = AddeNode->getOperand(1); 11220 Hi = AddeNode->getOperand(0); 11221 if (SRA.getOpcode() != ISD::SRA) 11222 return SDValue(); 11223 } 11224 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 11225 if (Const->getZExtValue() != 31) 11226 return SDValue(); 11227 } else 11228 return SDValue(); 11229 11230 if (SRA.getOperand(0) != Mul) 11231 return SDValue(); 11232 11233 SelectionDAG &DAG = DCI.DAG; 11234 SDLoc dl(AddcNode); 11235 unsigned Opcode = 0; 11236 SDValue Op0; 11237 SDValue Op1; 11238 11239 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 11240 Opcode = ARMISD::SMLALBB; 11241 Op0 = Mul.getOperand(0); 11242 Op1 = Mul.getOperand(1); 11243 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 11244 Opcode = ARMISD::SMLALBT; 11245 Op0 = Mul.getOperand(0); 11246 Op1 = Mul.getOperand(1).getOperand(0); 11247 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 11248 Opcode = ARMISD::SMLALTB; 11249 Op0 = Mul.getOperand(0).getOperand(0); 11250 Op1 = Mul.getOperand(1); 11251 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 11252 Opcode = ARMISD::SMLALTT; 11253 Op0 = Mul->getOperand(0).getOperand(0); 11254 Op1 = Mul->getOperand(1).getOperand(0); 11255 } 11256 11257 if (!Op0 || !Op1) 11258 return SDValue(); 11259 11260 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 11261 Op0, Op1, Lo, Hi); 11262 // Replace the ADDs' nodes uses by the MLA node's values. 11263 SDValue HiMLALResult(SMLAL.getNode(), 1); 11264 SDValue LoMLALResult(SMLAL.getNode(), 0); 11265 11266 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 11267 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 11268 11269 // Return original node to notify the driver to stop replacing. 11270 SDValue resNode(AddcNode, 0); 11271 return resNode; 11272 } 11273 11274 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 11275 TargetLowering::DAGCombinerInfo &DCI, 11276 const ARMSubtarget *Subtarget) { 11277 // Look for multiply add opportunities. 11278 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 11279 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 11280 // a glue link from the first add to the second add. 11281 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 11282 // a S/UMLAL instruction. 11283 // UMUL_LOHI 11284 // / :lo \ :hi 11285 // V \ [no multiline comment] 11286 // loAdd -> ADDC | 11287 // \ :carry / 11288 // V V 11289 // ADDE <- hiAdd 11290 // 11291 // In the special case where only the higher part of a signed result is used 11292 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 11293 // a constant with the exact value of 0x80000000, we recognize we are dealing 11294 // with a "rounded multiply and add" (or subtract) and transform it into 11295 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 11296 11297 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 11298 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 11299 "Expect an ADDE or SUBE"); 11300 11301 assert(AddeSubeNode->getNumOperands() == 3 && 11302 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 11303 "ADDE node has the wrong inputs"); 11304 11305 // Check that we are chained to the right ADDC or SUBC node. 11306 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 11307 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 11308 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 11309 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 11310 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 11311 return SDValue(); 11312 11313 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 11314 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 11315 11316 // Check if the two operands are from the same mul_lohi node. 11317 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 11318 return SDValue(); 11319 11320 assert(AddcSubcNode->getNumValues() == 2 && 11321 AddcSubcNode->getValueType(0) == MVT::i32 && 11322 "Expect ADDC with two result values. First: i32"); 11323 11324 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 11325 // maybe a SMLAL which multiplies two 16-bit values. 11326 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 11327 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 11328 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 11329 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 11330 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 11331 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 11332 11333 // Check for the triangle shape. 11334 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 11335 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 11336 11337 // Make sure that the ADDE/SUBE operands are not coming from the same node. 11338 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 11339 return SDValue(); 11340 11341 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 11342 bool IsLeftOperandMUL = false; 11343 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 11344 if (MULOp == SDValue()) 11345 MULOp = findMUL_LOHI(AddeSubeOp1); 11346 else 11347 IsLeftOperandMUL = true; 11348 if (MULOp == SDValue()) 11349 return SDValue(); 11350 11351 // Figure out the right opcode. 11352 unsigned Opc = MULOp->getOpcode(); 11353 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 11354 11355 // Figure out the high and low input values to the MLAL node. 11356 SDValue *HiAddSub = nullptr; 11357 SDValue *LoMul = nullptr; 11358 SDValue *LowAddSub = nullptr; 11359 11360 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 11361 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 11362 return SDValue(); 11363 11364 if (IsLeftOperandMUL) 11365 HiAddSub = &AddeSubeOp1; 11366 else 11367 HiAddSub = &AddeSubeOp0; 11368 11369 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 11370 // whose low result is fed to the ADDC/SUBC we are checking. 11371 11372 if (AddcSubcOp0 == MULOp.getValue(0)) { 11373 LoMul = &AddcSubcOp0; 11374 LowAddSub = &AddcSubcOp1; 11375 } 11376 if (AddcSubcOp1 == MULOp.getValue(0)) { 11377 LoMul = &AddcSubcOp1; 11378 LowAddSub = &AddcSubcOp0; 11379 } 11380 11381 if (!LoMul) 11382 return SDValue(); 11383 11384 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 11385 // the replacement below will create a cycle. 11386 if (AddcSubcNode == HiAddSub->getNode() || 11387 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 11388 return SDValue(); 11389 11390 // Create the merged node. 11391 SelectionDAG &DAG = DCI.DAG; 11392 11393 // Start building operand list. 11394 SmallVector<SDValue, 8> Ops; 11395 Ops.push_back(LoMul->getOperand(0)); 11396 Ops.push_back(LoMul->getOperand(1)); 11397 11398 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 11399 // the case, we must be doing signed multiplication and only use the higher 11400 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 11401 // addition or subtraction with the value of 0x800000. 11402 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 11403 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 11404 LowAddSub->getNode()->getOpcode() == ISD::Constant && 11405 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 11406 0x80000000) { 11407 Ops.push_back(*HiAddSub); 11408 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 11409 FinalOpc = ARMISD::SMMLSR; 11410 } else { 11411 FinalOpc = ARMISD::SMMLAR; 11412 } 11413 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 11414 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 11415 11416 return SDValue(AddeSubeNode, 0); 11417 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 11418 // SMMLS is generated during instruction selection and the rest of this 11419 // function can not handle the case where AddcSubcNode is a SUBC. 11420 return SDValue(); 11421 11422 // Finish building the operand list for {U/S}MLAL 11423 Ops.push_back(*LowAddSub); 11424 Ops.push_back(*HiAddSub); 11425 11426 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 11427 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11428 11429 // Replace the ADDs' nodes uses by the MLA node's values. 11430 SDValue HiMLALResult(MLALNode.getNode(), 1); 11431 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 11432 11433 SDValue LoMLALResult(MLALNode.getNode(), 0); 11434 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 11435 11436 // Return original node to notify the driver to stop replacing. 11437 return SDValue(AddeSubeNode, 0); 11438 } 11439 11440 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 11441 TargetLowering::DAGCombinerInfo &DCI, 11442 const ARMSubtarget *Subtarget) { 11443 // UMAAL is similar to UMLAL except that it adds two unsigned values. 11444 // While trying to combine for the other MLAL nodes, first search for the 11445 // chance to use UMAAL. Check if Addc uses a node which has already 11446 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 11447 // as the addend, and it's handled in PerformUMLALCombine. 11448 11449 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11450 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11451 11452 // Check that we have a glued ADDC node. 11453 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 11454 if (AddcNode->getOpcode() != ARMISD::ADDC) 11455 return SDValue(); 11456 11457 // Find the converted UMAAL or quit if it doesn't exist. 11458 SDNode *UmlalNode = nullptr; 11459 SDValue AddHi; 11460 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 11461 UmlalNode = AddcNode->getOperand(0).getNode(); 11462 AddHi = AddcNode->getOperand(1); 11463 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 11464 UmlalNode = AddcNode->getOperand(1).getNode(); 11465 AddHi = AddcNode->getOperand(0); 11466 } else { 11467 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11468 } 11469 11470 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 11471 // the ADDC as well as Zero. 11472 if (!isNullConstant(UmlalNode->getOperand(3))) 11473 return SDValue(); 11474 11475 if ((isNullConstant(AddeNode->getOperand(0)) && 11476 AddeNode->getOperand(1).getNode() == UmlalNode) || 11477 (AddeNode->getOperand(0).getNode() == UmlalNode && 11478 isNullConstant(AddeNode->getOperand(1)))) { 11479 SelectionDAG &DAG = DCI.DAG; 11480 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 11481 UmlalNode->getOperand(2), AddHi }; 11482 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 11483 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11484 11485 // Replace the ADDs' nodes uses by the UMAAL node's values. 11486 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 11487 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 11488 11489 // Return original node to notify the driver to stop replacing. 11490 return SDValue(AddeNode, 0); 11491 } 11492 return SDValue(); 11493 } 11494 11495 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 11496 const ARMSubtarget *Subtarget) { 11497 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11498 return SDValue(); 11499 11500 // Check that we have a pair of ADDC and ADDE as operands. 11501 // Both addends of the ADDE must be zero. 11502 SDNode* AddcNode = N->getOperand(2).getNode(); 11503 SDNode* AddeNode = N->getOperand(3).getNode(); 11504 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 11505 (AddeNode->getOpcode() == ARMISD::ADDE) && 11506 isNullConstant(AddeNode->getOperand(0)) && 11507 isNullConstant(AddeNode->getOperand(1)) && 11508 (AddeNode->getOperand(2).getNode() == AddcNode)) 11509 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 11510 DAG.getVTList(MVT::i32, MVT::i32), 11511 {N->getOperand(0), N->getOperand(1), 11512 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 11513 else 11514 return SDValue(); 11515 } 11516 11517 static SDValue PerformAddcSubcCombine(SDNode *N, 11518 TargetLowering::DAGCombinerInfo &DCI, 11519 const ARMSubtarget *Subtarget) { 11520 SelectionDAG &DAG(DCI.DAG); 11521 11522 if (N->getOpcode() == ARMISD::SUBC) { 11523 // (SUBC (ADDE 0, 0, C), 1) -> C 11524 SDValue LHS = N->getOperand(0); 11525 SDValue RHS = N->getOperand(1); 11526 if (LHS->getOpcode() == ARMISD::ADDE && 11527 isNullConstant(LHS->getOperand(0)) && 11528 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 11529 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 11530 } 11531 } 11532 11533 if (Subtarget->isThumb1Only()) { 11534 SDValue RHS = N->getOperand(1); 11535 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11536 int32_t imm = C->getSExtValue(); 11537 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 11538 SDLoc DL(N); 11539 RHS = DAG.getConstant(-imm, DL, MVT::i32); 11540 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 11541 : ARMISD::ADDC; 11542 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 11543 } 11544 } 11545 } 11546 11547 return SDValue(); 11548 } 11549 11550 static SDValue PerformAddeSubeCombine(SDNode *N, 11551 TargetLowering::DAGCombinerInfo &DCI, 11552 const ARMSubtarget *Subtarget) { 11553 if (Subtarget->isThumb1Only()) { 11554 SelectionDAG &DAG = DCI.DAG; 11555 SDValue RHS = N->getOperand(1); 11556 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11557 int64_t imm = C->getSExtValue(); 11558 if (imm < 0) { 11559 SDLoc DL(N); 11560 11561 // The with-carry-in form matches bitwise not instead of the negation. 11562 // Effectively, the inverse interpretation of the carry flag already 11563 // accounts for part of the negation. 11564 RHS = DAG.getConstant(~imm, DL, MVT::i32); 11565 11566 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 11567 : ARMISD::ADDE; 11568 return DAG.getNode(Opcode, DL, N->getVTList(), 11569 N->getOperand(0), RHS, N->getOperand(2)); 11570 } 11571 } 11572 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 11573 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 11574 } 11575 return SDValue(); 11576 } 11577 11578 static SDValue PerformABSCombine(SDNode *N, 11579 TargetLowering::DAGCombinerInfo &DCI, 11580 const ARMSubtarget *Subtarget) { 11581 SDValue res; 11582 SelectionDAG &DAG = DCI.DAG; 11583 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11584 11585 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 11586 return SDValue(); 11587 11588 if (!TLI.expandABS(N, res, DAG)) 11589 return SDValue(); 11590 11591 return res; 11592 } 11593 11594 /// PerformADDECombine - Target-specific dag combine transform from 11595 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 11596 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 11597 static SDValue PerformADDECombine(SDNode *N, 11598 TargetLowering::DAGCombinerInfo &DCI, 11599 const ARMSubtarget *Subtarget) { 11600 // Only ARM and Thumb2 support UMLAL/SMLAL. 11601 if (Subtarget->isThumb1Only()) 11602 return PerformAddeSubeCombine(N, DCI, Subtarget); 11603 11604 // Only perform the checks after legalize when the pattern is available. 11605 if (DCI.isBeforeLegalize()) return SDValue(); 11606 11607 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 11608 } 11609 11610 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 11611 /// operands N0 and N1. This is a helper for PerformADDCombine that is 11612 /// called with the default operands, and if that fails, with commuted 11613 /// operands. 11614 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 11615 TargetLowering::DAGCombinerInfo &DCI, 11616 const ARMSubtarget *Subtarget){ 11617 // Attempt to create vpadd for this add. 11618 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 11619 return Result; 11620 11621 // Attempt to create vpaddl for this add. 11622 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 11623 return Result; 11624 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 11625 Subtarget)) 11626 return Result; 11627 11628 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11629 if (N0.getNode()->hasOneUse()) 11630 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 11631 return Result; 11632 return SDValue(); 11633 } 11634 11635 bool 11636 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 11637 CombineLevel Level) const { 11638 if (Level == BeforeLegalizeTypes) 11639 return true; 11640 11641 if (N->getOpcode() != ISD::SHL) 11642 return true; 11643 11644 if (Subtarget->isThumb1Only()) { 11645 // Avoid making expensive immediates by commuting shifts. (This logic 11646 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 11647 // for free.) 11648 if (N->getOpcode() != ISD::SHL) 11649 return true; 11650 SDValue N1 = N->getOperand(0); 11651 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 11652 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 11653 return true; 11654 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 11655 if (Const->getAPIntValue().ult(256)) 11656 return false; 11657 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 11658 Const->getAPIntValue().sgt(-256)) 11659 return false; 11660 } 11661 return true; 11662 } 11663 11664 // Turn off commute-with-shift transform after legalization, so it doesn't 11665 // conflict with PerformSHLSimplify. (We could try to detect when 11666 // PerformSHLSimplify would trigger more precisely, but it isn't 11667 // really necessary.) 11668 return false; 11669 } 11670 11671 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 11672 const SDNode *N, CombineLevel Level) const { 11673 if (!Subtarget->isThumb1Only()) 11674 return true; 11675 11676 if (Level == BeforeLegalizeTypes) 11677 return true; 11678 11679 return false; 11680 } 11681 11682 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 11683 if (!Subtarget->hasNEON()) { 11684 if (Subtarget->isThumb1Only()) 11685 return VT.getScalarSizeInBits() <= 32; 11686 return true; 11687 } 11688 return VT.isScalarInteger(); 11689 } 11690 11691 static SDValue PerformSHLSimplify(SDNode *N, 11692 TargetLowering::DAGCombinerInfo &DCI, 11693 const ARMSubtarget *ST) { 11694 // Allow the generic combiner to identify potential bswaps. 11695 if (DCI.isBeforeLegalize()) 11696 return SDValue(); 11697 11698 // DAG combiner will fold: 11699 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 11700 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 11701 // Other code patterns that can be also be modified have the following form: 11702 // b + ((a << 1) | 510) 11703 // b + ((a << 1) & 510) 11704 // b + ((a << 1) ^ 510) 11705 // b + ((a << 1) + 510) 11706 11707 // Many instructions can perform the shift for free, but it requires both 11708 // the operands to be registers. If c1 << c2 is too large, a mov immediate 11709 // instruction will needed. So, unfold back to the original pattern if: 11710 // - if c1 and c2 are small enough that they don't require mov imms. 11711 // - the user(s) of the node can perform an shl 11712 11713 // No shifted operands for 16-bit instructions. 11714 if (ST->isThumb() && ST->isThumb1Only()) 11715 return SDValue(); 11716 11717 // Check that all the users could perform the shl themselves. 11718 for (auto U : N->uses()) { 11719 switch(U->getOpcode()) { 11720 default: 11721 return SDValue(); 11722 case ISD::SUB: 11723 case ISD::ADD: 11724 case ISD::AND: 11725 case ISD::OR: 11726 case ISD::XOR: 11727 case ISD::SETCC: 11728 case ARMISD::CMP: 11729 // Check that the user isn't already using a constant because there 11730 // aren't any instructions that support an immediate operand and a 11731 // shifted operand. 11732 if (isa<ConstantSDNode>(U->getOperand(0)) || 11733 isa<ConstantSDNode>(U->getOperand(1))) 11734 return SDValue(); 11735 11736 // Check that it's not already using a shift. 11737 if (U->getOperand(0).getOpcode() == ISD::SHL || 11738 U->getOperand(1).getOpcode() == ISD::SHL) 11739 return SDValue(); 11740 break; 11741 } 11742 } 11743 11744 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 11745 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 11746 return SDValue(); 11747 11748 if (N->getOperand(0).getOpcode() != ISD::SHL) 11749 return SDValue(); 11750 11751 SDValue SHL = N->getOperand(0); 11752 11753 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11754 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 11755 if (!C1ShlC2 || !C2) 11756 return SDValue(); 11757 11758 APInt C2Int = C2->getAPIntValue(); 11759 APInt C1Int = C1ShlC2->getAPIntValue(); 11760 11761 // Check that performing a lshr will not lose any information. 11762 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 11763 C2Int.getBitWidth() - C2->getZExtValue()); 11764 if ((C1Int & Mask) != C1Int) 11765 return SDValue(); 11766 11767 // Shift the first constant. 11768 C1Int.lshrInPlace(C2Int); 11769 11770 // The immediates are encoded as an 8-bit value that can be rotated. 11771 auto LargeImm = [](const APInt &Imm) { 11772 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 11773 return Imm.getBitWidth() - Zeros > 8; 11774 }; 11775 11776 if (LargeImm(C1Int) || LargeImm(C2Int)) 11777 return SDValue(); 11778 11779 SelectionDAG &DAG = DCI.DAG; 11780 SDLoc dl(N); 11781 SDValue X = SHL.getOperand(0); 11782 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 11783 DAG.getConstant(C1Int, dl, MVT::i32)); 11784 // Shift left to compensate for the lshr of C1Int. 11785 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 11786 11787 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 11788 SHL.dump(); N->dump()); 11789 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 11790 return Res; 11791 } 11792 11793 11794 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 11795 /// 11796 static SDValue PerformADDCombine(SDNode *N, 11797 TargetLowering::DAGCombinerInfo &DCI, 11798 const ARMSubtarget *Subtarget) { 11799 SDValue N0 = N->getOperand(0); 11800 SDValue N1 = N->getOperand(1); 11801 11802 // Only works one way, because it needs an immediate operand. 11803 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11804 return Result; 11805 11806 // First try with the default operand order. 11807 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 11808 return Result; 11809 11810 // If that didn't work, try again with the operands commuted. 11811 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 11812 } 11813 11814 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 11815 /// 11816 static SDValue PerformSUBCombine(SDNode *N, 11817 TargetLowering::DAGCombinerInfo &DCI, 11818 const ARMSubtarget *Subtarget) { 11819 SDValue N0 = N->getOperand(0); 11820 SDValue N1 = N->getOperand(1); 11821 11822 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11823 if (N1.getNode()->hasOneUse()) 11824 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 11825 return Result; 11826 11827 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector()) 11828 return SDValue(); 11829 11830 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x)) 11831 // so that we can readily pattern match more mve instructions which can use 11832 // a scalar operand. 11833 SDValue VDup = N->getOperand(1); 11834 if (VDup->getOpcode() != ARMISD::VDUP) 11835 return SDValue(); 11836 11837 SDValue VMov = N->getOperand(0); 11838 if (VMov->getOpcode() == ISD::BITCAST) 11839 VMov = VMov->getOperand(0); 11840 11841 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov)) 11842 return SDValue(); 11843 11844 SDLoc dl(N); 11845 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32, 11846 DCI.DAG.getConstant(0, dl, MVT::i32), 11847 VDup->getOperand(0)); 11848 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate); 11849 } 11850 11851 /// PerformVMULCombine 11852 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 11853 /// special multiplier accumulator forwarding. 11854 /// vmul d3, d0, d2 11855 /// vmla d3, d1, d2 11856 /// is faster than 11857 /// vadd d3, d0, d1 11858 /// vmul d3, d3, d2 11859 // However, for (A + B) * (A + B), 11860 // vadd d2, d0, d1 11861 // vmul d3, d0, d2 11862 // vmla d3, d1, d2 11863 // is slower than 11864 // vadd d2, d0, d1 11865 // vmul d3, d2, d2 11866 static SDValue PerformVMULCombine(SDNode *N, 11867 TargetLowering::DAGCombinerInfo &DCI, 11868 const ARMSubtarget *Subtarget) { 11869 if (!Subtarget->hasVMLxForwarding()) 11870 return SDValue(); 11871 11872 SelectionDAG &DAG = DCI.DAG; 11873 SDValue N0 = N->getOperand(0); 11874 SDValue N1 = N->getOperand(1); 11875 unsigned Opcode = N0.getOpcode(); 11876 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11877 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 11878 Opcode = N1.getOpcode(); 11879 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11880 Opcode != ISD::FADD && Opcode != ISD::FSUB) 11881 return SDValue(); 11882 std::swap(N0, N1); 11883 } 11884 11885 if (N0 == N1) 11886 return SDValue(); 11887 11888 EVT VT = N->getValueType(0); 11889 SDLoc DL(N); 11890 SDValue N00 = N0->getOperand(0); 11891 SDValue N01 = N0->getOperand(1); 11892 return DAG.getNode(Opcode, DL, VT, 11893 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 11894 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 11895 } 11896 11897 static SDValue PerformMULCombine(SDNode *N, 11898 TargetLowering::DAGCombinerInfo &DCI, 11899 const ARMSubtarget *Subtarget) { 11900 SelectionDAG &DAG = DCI.DAG; 11901 11902 if (Subtarget->isThumb1Only()) 11903 return SDValue(); 11904 11905 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11906 return SDValue(); 11907 11908 EVT VT = N->getValueType(0); 11909 if (VT.is64BitVector() || VT.is128BitVector()) 11910 return PerformVMULCombine(N, DCI, Subtarget); 11911 if (VT != MVT::i32) 11912 return SDValue(); 11913 11914 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11915 if (!C) 11916 return SDValue(); 11917 11918 int64_t MulAmt = C->getSExtValue(); 11919 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 11920 11921 ShiftAmt = ShiftAmt & (32 - 1); 11922 SDValue V = N->getOperand(0); 11923 SDLoc DL(N); 11924 11925 SDValue Res; 11926 MulAmt >>= ShiftAmt; 11927 11928 if (MulAmt >= 0) { 11929 if (isPowerOf2_32(MulAmt - 1)) { 11930 // (mul x, 2^N + 1) => (add (shl x, N), x) 11931 Res = DAG.getNode(ISD::ADD, DL, VT, 11932 V, 11933 DAG.getNode(ISD::SHL, DL, VT, 11934 V, 11935 DAG.getConstant(Log2_32(MulAmt - 1), DL, 11936 MVT::i32))); 11937 } else if (isPowerOf2_32(MulAmt + 1)) { 11938 // (mul x, 2^N - 1) => (sub (shl x, N), x) 11939 Res = DAG.getNode(ISD::SUB, DL, VT, 11940 DAG.getNode(ISD::SHL, DL, VT, 11941 V, 11942 DAG.getConstant(Log2_32(MulAmt + 1), DL, 11943 MVT::i32)), 11944 V); 11945 } else 11946 return SDValue(); 11947 } else { 11948 uint64_t MulAmtAbs = -MulAmt; 11949 if (isPowerOf2_32(MulAmtAbs + 1)) { 11950 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 11951 Res = DAG.getNode(ISD::SUB, DL, VT, 11952 V, 11953 DAG.getNode(ISD::SHL, DL, VT, 11954 V, 11955 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 11956 MVT::i32))); 11957 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 11958 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 11959 Res = DAG.getNode(ISD::ADD, DL, VT, 11960 V, 11961 DAG.getNode(ISD::SHL, DL, VT, 11962 V, 11963 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 11964 MVT::i32))); 11965 Res = DAG.getNode(ISD::SUB, DL, VT, 11966 DAG.getConstant(0, DL, MVT::i32), Res); 11967 } else 11968 return SDValue(); 11969 } 11970 11971 if (ShiftAmt != 0) 11972 Res = DAG.getNode(ISD::SHL, DL, VT, 11973 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 11974 11975 // Do not add new nodes to DAG combiner worklist. 11976 DCI.CombineTo(N, Res, false); 11977 return SDValue(); 11978 } 11979 11980 static SDValue CombineANDShift(SDNode *N, 11981 TargetLowering::DAGCombinerInfo &DCI, 11982 const ARMSubtarget *Subtarget) { 11983 // Allow DAGCombine to pattern-match before we touch the canonical form. 11984 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11985 return SDValue(); 11986 11987 if (N->getValueType(0) != MVT::i32) 11988 return SDValue(); 11989 11990 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11991 if (!N1C) 11992 return SDValue(); 11993 11994 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 11995 // Don't transform uxtb/uxth. 11996 if (C1 == 255 || C1 == 65535) 11997 return SDValue(); 11998 11999 SDNode *N0 = N->getOperand(0).getNode(); 12000 if (!N0->hasOneUse()) 12001 return SDValue(); 12002 12003 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 12004 return SDValue(); 12005 12006 bool LeftShift = N0->getOpcode() == ISD::SHL; 12007 12008 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12009 if (!N01C) 12010 return SDValue(); 12011 12012 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 12013 if (!C2 || C2 >= 32) 12014 return SDValue(); 12015 12016 // Clear irrelevant bits in the mask. 12017 if (LeftShift) 12018 C1 &= (-1U << C2); 12019 else 12020 C1 &= (-1U >> C2); 12021 12022 SelectionDAG &DAG = DCI.DAG; 12023 SDLoc DL(N); 12024 12025 // We have a pattern of the form "(and (shl x, c2) c1)" or 12026 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 12027 // transform to a pair of shifts, to save materializing c1. 12028 12029 // First pattern: right shift, then mask off leading bits. 12030 // FIXME: Use demanded bits? 12031 if (!LeftShift && isMask_32(C1)) { 12032 uint32_t C3 = countLeadingZeros(C1); 12033 if (C2 < C3) { 12034 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12035 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12036 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12037 DAG.getConstant(C3, DL, MVT::i32)); 12038 } 12039 } 12040 12041 // First pattern, reversed: left shift, then mask off trailing bits. 12042 if (LeftShift && isMask_32(~C1)) { 12043 uint32_t C3 = countTrailingZeros(C1); 12044 if (C2 < C3) { 12045 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12046 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12047 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12048 DAG.getConstant(C3, DL, MVT::i32)); 12049 } 12050 } 12051 12052 // Second pattern: left shift, then mask off leading bits. 12053 // FIXME: Use demanded bits? 12054 if (LeftShift && isShiftedMask_32(C1)) { 12055 uint32_t Trailing = countTrailingZeros(C1); 12056 uint32_t C3 = countLeadingZeros(C1); 12057 if (Trailing == C2 && C2 + C3 < 32) { 12058 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12059 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12060 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12061 DAG.getConstant(C3, DL, MVT::i32)); 12062 } 12063 } 12064 12065 // Second pattern, reversed: right shift, then mask off trailing bits. 12066 // FIXME: Handle other patterns of known/demanded bits. 12067 if (!LeftShift && isShiftedMask_32(C1)) { 12068 uint32_t Leading = countLeadingZeros(C1); 12069 uint32_t C3 = countTrailingZeros(C1); 12070 if (Leading == C2 && C2 + C3 < 32) { 12071 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12072 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12073 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12074 DAG.getConstant(C3, DL, MVT::i32)); 12075 } 12076 } 12077 12078 // FIXME: Transform "(and (shl x, c2) c1)" -> 12079 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 12080 // c1. 12081 return SDValue(); 12082 } 12083 12084 static SDValue PerformANDCombine(SDNode *N, 12085 TargetLowering::DAGCombinerInfo &DCI, 12086 const ARMSubtarget *Subtarget) { 12087 // Attempt to use immediate-form VBIC 12088 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12089 SDLoc dl(N); 12090 EVT VT = N->getValueType(0); 12091 SelectionDAG &DAG = DCI.DAG; 12092 12093 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12094 return SDValue(); 12095 12096 APInt SplatBits, SplatUndef; 12097 unsigned SplatBitSize; 12098 bool HasAnyUndefs; 12099 if (BVN && Subtarget->hasNEON() && 12100 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 12101 if (SplatBitSize <= 64) { 12102 EVT VbicVT; 12103 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 12104 SplatUndef.getZExtValue(), SplatBitSize, 12105 DAG, dl, VbicVT, VT.is128BitVector(), 12106 OtherModImm); 12107 if (Val.getNode()) { 12108 SDValue Input = 12109 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 12110 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 12111 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 12112 } 12113 } 12114 } 12115 12116 if (!Subtarget->isThumb1Only()) { 12117 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 12118 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 12119 return Result; 12120 12121 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12122 return Result; 12123 } 12124 12125 if (Subtarget->isThumb1Only()) 12126 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 12127 return Result; 12128 12129 return SDValue(); 12130 } 12131 12132 // Try combining OR nodes to SMULWB, SMULWT. 12133 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 12134 TargetLowering::DAGCombinerInfo &DCI, 12135 const ARMSubtarget *Subtarget) { 12136 if (!Subtarget->hasV6Ops() || 12137 (Subtarget->isThumb() && 12138 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 12139 return SDValue(); 12140 12141 SDValue SRL = OR->getOperand(0); 12142 SDValue SHL = OR->getOperand(1); 12143 12144 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 12145 SRL = OR->getOperand(1); 12146 SHL = OR->getOperand(0); 12147 } 12148 if (!isSRL16(SRL) || !isSHL16(SHL)) 12149 return SDValue(); 12150 12151 // The first operands to the shifts need to be the two results from the 12152 // same smul_lohi node. 12153 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 12154 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 12155 return SDValue(); 12156 12157 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 12158 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 12159 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 12160 return SDValue(); 12161 12162 // Now we have: 12163 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 12164 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 12165 // For SMUWB the 16-bit value will signed extended somehow. 12166 // For SMULWT only the SRA is required. 12167 // Check both sides of SMUL_LOHI 12168 SDValue OpS16 = SMULLOHI->getOperand(0); 12169 SDValue OpS32 = SMULLOHI->getOperand(1); 12170 12171 SelectionDAG &DAG = DCI.DAG; 12172 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 12173 OpS16 = OpS32; 12174 OpS32 = SMULLOHI->getOperand(0); 12175 } 12176 12177 SDLoc dl(OR); 12178 unsigned Opcode = 0; 12179 if (isS16(OpS16, DAG)) 12180 Opcode = ARMISD::SMULWB; 12181 else if (isSRA16(OpS16)) { 12182 Opcode = ARMISD::SMULWT; 12183 OpS16 = OpS16->getOperand(0); 12184 } 12185 else 12186 return SDValue(); 12187 12188 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 12189 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 12190 return SDValue(OR, 0); 12191 } 12192 12193 static SDValue PerformORCombineToBFI(SDNode *N, 12194 TargetLowering::DAGCombinerInfo &DCI, 12195 const ARMSubtarget *Subtarget) { 12196 // BFI is only available on V6T2+ 12197 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 12198 return SDValue(); 12199 12200 EVT VT = N->getValueType(0); 12201 SDValue N0 = N->getOperand(0); 12202 SDValue N1 = N->getOperand(1); 12203 SelectionDAG &DAG = DCI.DAG; 12204 SDLoc DL(N); 12205 // 1) or (and A, mask), val => ARMbfi A, val, mask 12206 // iff (val & mask) == val 12207 // 12208 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 12209 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 12210 // && mask == ~mask2 12211 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 12212 // && ~mask == mask2 12213 // (i.e., copy a bitfield value into another bitfield of the same width) 12214 12215 if (VT != MVT::i32) 12216 return SDValue(); 12217 12218 SDValue N00 = N0.getOperand(0); 12219 12220 // The value and the mask need to be constants so we can verify this is 12221 // actually a bitfield set. If the mask is 0xffff, we can do better 12222 // via a movt instruction, so don't use BFI in that case. 12223 SDValue MaskOp = N0.getOperand(1); 12224 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 12225 if (!MaskC) 12226 return SDValue(); 12227 unsigned Mask = MaskC->getZExtValue(); 12228 if (Mask == 0xffff) 12229 return SDValue(); 12230 SDValue Res; 12231 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 12232 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 12233 if (N1C) { 12234 unsigned Val = N1C->getZExtValue(); 12235 if ((Val & ~Mask) != Val) 12236 return SDValue(); 12237 12238 if (ARM::isBitFieldInvertedMask(Mask)) { 12239 Val >>= countTrailingZeros(~Mask); 12240 12241 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 12242 DAG.getConstant(Val, DL, MVT::i32), 12243 DAG.getConstant(Mask, DL, MVT::i32)); 12244 12245 DCI.CombineTo(N, Res, false); 12246 // Return value from the original node to inform the combiner than N is 12247 // now dead. 12248 return SDValue(N, 0); 12249 } 12250 } else if (N1.getOpcode() == ISD::AND) { 12251 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 12252 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 12253 if (!N11C) 12254 return SDValue(); 12255 unsigned Mask2 = N11C->getZExtValue(); 12256 12257 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 12258 // as is to match. 12259 if (ARM::isBitFieldInvertedMask(Mask) && 12260 (Mask == ~Mask2)) { 12261 // The pack halfword instruction works better for masks that fit it, 12262 // so use that when it's available. 12263 if (Subtarget->hasDSP() && 12264 (Mask == 0xffff || Mask == 0xffff0000)) 12265 return SDValue(); 12266 // 2a 12267 unsigned amt = countTrailingZeros(Mask2); 12268 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 12269 DAG.getConstant(amt, DL, MVT::i32)); 12270 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 12271 DAG.getConstant(Mask, DL, MVT::i32)); 12272 DCI.CombineTo(N, Res, false); 12273 // Return value from the original node to inform the combiner than N is 12274 // now dead. 12275 return SDValue(N, 0); 12276 } else if (ARM::isBitFieldInvertedMask(~Mask) && 12277 (~Mask == Mask2)) { 12278 // The pack halfword instruction works better for masks that fit it, 12279 // so use that when it's available. 12280 if (Subtarget->hasDSP() && 12281 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 12282 return SDValue(); 12283 // 2b 12284 unsigned lsb = countTrailingZeros(Mask); 12285 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 12286 DAG.getConstant(lsb, DL, MVT::i32)); 12287 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 12288 DAG.getConstant(Mask2, DL, MVT::i32)); 12289 DCI.CombineTo(N, Res, false); 12290 // Return value from the original node to inform the combiner than N is 12291 // now dead. 12292 return SDValue(N, 0); 12293 } 12294 } 12295 12296 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 12297 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 12298 ARM::isBitFieldInvertedMask(~Mask)) { 12299 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 12300 // where lsb(mask) == #shamt and masked bits of B are known zero. 12301 SDValue ShAmt = N00.getOperand(1); 12302 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 12303 unsigned LSB = countTrailingZeros(Mask); 12304 if (ShAmtC != LSB) 12305 return SDValue(); 12306 12307 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 12308 DAG.getConstant(~Mask, DL, MVT::i32)); 12309 12310 DCI.CombineTo(N, Res, false); 12311 // Return value from the original node to inform the combiner than N is 12312 // now dead. 12313 return SDValue(N, 0); 12314 } 12315 12316 return SDValue(); 12317 } 12318 12319 static bool isValidMVECond(unsigned CC, bool IsFloat) { 12320 switch (CC) { 12321 case ARMCC::EQ: 12322 case ARMCC::NE: 12323 case ARMCC::LE: 12324 case ARMCC::GT: 12325 case ARMCC::GE: 12326 case ARMCC::LT: 12327 return true; 12328 case ARMCC::HS: 12329 case ARMCC::HI: 12330 return !IsFloat; 12331 default: 12332 return false; 12333 }; 12334 } 12335 12336 static SDValue PerformORCombine_i1(SDNode *N, 12337 TargetLowering::DAGCombinerInfo &DCI, 12338 const ARMSubtarget *Subtarget) { 12339 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 12340 // together with predicates 12341 EVT VT = N->getValueType(0); 12342 SDValue N0 = N->getOperand(0); 12343 SDValue N1 = N->getOperand(1); 12344 12345 ARMCC::CondCodes CondCode0 = ARMCC::AL; 12346 ARMCC::CondCodes CondCode1 = ARMCC::AL; 12347 if (N0->getOpcode() == ARMISD::VCMP) 12348 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2)) 12349 ->getZExtValue(); 12350 else if (N0->getOpcode() == ARMISD::VCMPZ) 12351 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1)) 12352 ->getZExtValue(); 12353 if (N1->getOpcode() == ARMISD::VCMP) 12354 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2)) 12355 ->getZExtValue(); 12356 else if (N1->getOpcode() == ARMISD::VCMPZ) 12357 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1)) 12358 ->getZExtValue(); 12359 12360 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL) 12361 return SDValue(); 12362 12363 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0); 12364 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1); 12365 12366 if (!isValidMVECond(Opposite0, 12367 N0->getOperand(0)->getValueType(0).isFloatingPoint()) || 12368 !isValidMVECond(Opposite1, 12369 N1->getOperand(0)->getValueType(0).isFloatingPoint())) 12370 return SDValue(); 12371 12372 SmallVector<SDValue, 4> Ops0; 12373 Ops0.push_back(N0->getOperand(0)); 12374 if (N0->getOpcode() == ARMISD::VCMP) 12375 Ops0.push_back(N0->getOperand(1)); 12376 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32)); 12377 SmallVector<SDValue, 4> Ops1; 12378 Ops1.push_back(N1->getOperand(0)); 12379 if (N1->getOpcode() == ARMISD::VCMP) 12380 Ops1.push_back(N1->getOperand(1)); 12381 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32)); 12382 12383 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0); 12384 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1); 12385 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1); 12386 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And, 12387 DCI.DAG.getAllOnesConstant(SDLoc(N), VT)); 12388 } 12389 12390 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 12391 static SDValue PerformORCombine(SDNode *N, 12392 TargetLowering::DAGCombinerInfo &DCI, 12393 const ARMSubtarget *Subtarget) { 12394 // Attempt to use immediate-form VORR 12395 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12396 SDLoc dl(N); 12397 EVT VT = N->getValueType(0); 12398 SelectionDAG &DAG = DCI.DAG; 12399 12400 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12401 return SDValue(); 12402 12403 APInt SplatBits, SplatUndef; 12404 unsigned SplatBitSize; 12405 bool HasAnyUndefs; 12406 if (BVN && Subtarget->hasNEON() && 12407 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 12408 if (SplatBitSize <= 64) { 12409 EVT VorrVT; 12410 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 12411 SplatUndef.getZExtValue(), SplatBitSize, 12412 DAG, dl, VorrVT, VT.is128BitVector(), 12413 OtherModImm); 12414 if (Val.getNode()) { 12415 SDValue Input = 12416 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 12417 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 12418 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 12419 } 12420 } 12421 } 12422 12423 if (!Subtarget->isThumb1Only()) { 12424 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 12425 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12426 return Result; 12427 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 12428 return Result; 12429 } 12430 12431 SDValue N0 = N->getOperand(0); 12432 SDValue N1 = N->getOperand(1); 12433 12434 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 12435 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 12436 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 12437 12438 // The code below optimizes (or (and X, Y), Z). 12439 // The AND operand needs to have a single user to make these optimizations 12440 // profitable. 12441 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 12442 return SDValue(); 12443 12444 APInt SplatUndef; 12445 unsigned SplatBitSize; 12446 bool HasAnyUndefs; 12447 12448 APInt SplatBits0, SplatBits1; 12449 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 12450 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 12451 // Ensure that the second operand of both ands are constants 12452 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 12453 HasAnyUndefs) && !HasAnyUndefs) { 12454 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 12455 HasAnyUndefs) && !HasAnyUndefs) { 12456 // Ensure that the bit width of the constants are the same and that 12457 // the splat arguments are logical inverses as per the pattern we 12458 // are trying to simplify. 12459 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 12460 SplatBits0 == ~SplatBits1) { 12461 // Canonicalize the vector type to make instruction selection 12462 // simpler. 12463 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 12464 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 12465 N0->getOperand(1), 12466 N0->getOperand(0), 12467 N1->getOperand(0)); 12468 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 12469 } 12470 } 12471 } 12472 } 12473 12474 if (Subtarget->hasMVEIntegerOps() && 12475 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 12476 return PerformORCombine_i1(N, DCI, Subtarget); 12477 12478 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 12479 // reasonable. 12480 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 12481 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 12482 return Res; 12483 } 12484 12485 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12486 return Result; 12487 12488 return SDValue(); 12489 } 12490 12491 static SDValue PerformXORCombine(SDNode *N, 12492 TargetLowering::DAGCombinerInfo &DCI, 12493 const ARMSubtarget *Subtarget) { 12494 EVT VT = N->getValueType(0); 12495 SelectionDAG &DAG = DCI.DAG; 12496 12497 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12498 return SDValue(); 12499 12500 if (!Subtarget->isThumb1Only()) { 12501 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 12502 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12503 return Result; 12504 12505 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12506 return Result; 12507 } 12508 12509 return SDValue(); 12510 } 12511 12512 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 12513 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 12514 // their position in "to" (Rd). 12515 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 12516 assert(N->getOpcode() == ARMISD::BFI); 12517 12518 SDValue From = N->getOperand(1); 12519 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 12520 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 12521 12522 // If the Base came from a SHR #C, we can deduce that it is really testing bit 12523 // #C in the base of the SHR. 12524 if (From->getOpcode() == ISD::SRL && 12525 isa<ConstantSDNode>(From->getOperand(1))) { 12526 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 12527 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 12528 FromMask <<= Shift.getLimitedValue(31); 12529 From = From->getOperand(0); 12530 } 12531 12532 return From; 12533 } 12534 12535 // If A and B contain one contiguous set of bits, does A | B == A . B? 12536 // 12537 // Neither A nor B must be zero. 12538 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 12539 unsigned LastActiveBitInA = A.countTrailingZeros(); 12540 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 12541 return LastActiveBitInA - 1 == FirstActiveBitInB; 12542 } 12543 12544 static SDValue FindBFIToCombineWith(SDNode *N) { 12545 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 12546 // if one exists. 12547 APInt ToMask, FromMask; 12548 SDValue From = ParseBFI(N, ToMask, FromMask); 12549 SDValue To = N->getOperand(0); 12550 12551 // Now check for a compatible BFI to merge with. We can pass through BFIs that 12552 // aren't compatible, but not if they set the same bit in their destination as 12553 // we do (or that of any BFI we're going to combine with). 12554 SDValue V = To; 12555 APInt CombinedToMask = ToMask; 12556 while (V.getOpcode() == ARMISD::BFI) { 12557 APInt NewToMask, NewFromMask; 12558 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 12559 if (NewFrom != From) { 12560 // This BFI has a different base. Keep going. 12561 CombinedToMask |= NewToMask; 12562 V = V.getOperand(0); 12563 continue; 12564 } 12565 12566 // Do the written bits conflict with any we've seen so far? 12567 if ((NewToMask & CombinedToMask).getBoolValue()) 12568 // Conflicting bits - bail out because going further is unsafe. 12569 return SDValue(); 12570 12571 // Are the new bits contiguous when combined with the old bits? 12572 if (BitsProperlyConcatenate(ToMask, NewToMask) && 12573 BitsProperlyConcatenate(FromMask, NewFromMask)) 12574 return V; 12575 if (BitsProperlyConcatenate(NewToMask, ToMask) && 12576 BitsProperlyConcatenate(NewFromMask, FromMask)) 12577 return V; 12578 12579 // We've seen a write to some bits, so track it. 12580 CombinedToMask |= NewToMask; 12581 // Keep going... 12582 V = V.getOperand(0); 12583 } 12584 12585 return SDValue(); 12586 } 12587 12588 static SDValue PerformBFICombine(SDNode *N, 12589 TargetLowering::DAGCombinerInfo &DCI) { 12590 SDValue N1 = N->getOperand(1); 12591 if (N1.getOpcode() == ISD::AND) { 12592 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 12593 // the bits being cleared by the AND are not demanded by the BFI. 12594 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 12595 if (!N11C) 12596 return SDValue(); 12597 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12598 unsigned LSB = countTrailingZeros(~InvMask); 12599 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 12600 assert(Width < 12601 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 12602 "undefined behavior"); 12603 unsigned Mask = (1u << Width) - 1; 12604 unsigned Mask2 = N11C->getZExtValue(); 12605 if ((Mask & (~Mask2)) == 0) 12606 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 12607 N->getOperand(0), N1.getOperand(0), 12608 N->getOperand(2)); 12609 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 12610 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 12611 // Keep track of any consecutive bits set that all come from the same base 12612 // value. We can combine these together into a single BFI. 12613 SDValue CombineBFI = FindBFIToCombineWith(N); 12614 if (CombineBFI == SDValue()) 12615 return SDValue(); 12616 12617 // We've found a BFI. 12618 APInt ToMask1, FromMask1; 12619 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 12620 12621 APInt ToMask2, FromMask2; 12622 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 12623 assert(From1 == From2); 12624 (void)From2; 12625 12626 // First, unlink CombineBFI. 12627 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 12628 // Then create a new BFI, combining the two together. 12629 APInt NewFromMask = FromMask1 | FromMask2; 12630 APInt NewToMask = ToMask1 | ToMask2; 12631 12632 EVT VT = N->getValueType(0); 12633 SDLoc dl(N); 12634 12635 if (NewFromMask[0] == 0) 12636 From1 = DCI.DAG.getNode( 12637 ISD::SRL, dl, VT, From1, 12638 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 12639 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 12640 DCI.DAG.getConstant(~NewToMask, dl, VT)); 12641 } 12642 return SDValue(); 12643 } 12644 12645 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 12646 /// ARMISD::VMOVRRD. 12647 static SDValue PerformVMOVRRDCombine(SDNode *N, 12648 TargetLowering::DAGCombinerInfo &DCI, 12649 const ARMSubtarget *Subtarget) { 12650 // vmovrrd(vmovdrr x, y) -> x,y 12651 SDValue InDouble = N->getOperand(0); 12652 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 12653 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 12654 12655 // vmovrrd(load f64) -> (load i32), (load i32) 12656 SDNode *InNode = InDouble.getNode(); 12657 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 12658 InNode->getValueType(0) == MVT::f64 && 12659 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 12660 !cast<LoadSDNode>(InNode)->isVolatile()) { 12661 // TODO: Should this be done for non-FrameIndex operands? 12662 LoadSDNode *LD = cast<LoadSDNode>(InNode); 12663 12664 SelectionDAG &DAG = DCI.DAG; 12665 SDLoc DL(LD); 12666 SDValue BasePtr = LD->getBasePtr(); 12667 SDValue NewLD1 = 12668 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 12669 LD->getAlignment(), LD->getMemOperand()->getFlags()); 12670 12671 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12672 DAG.getConstant(4, DL, MVT::i32)); 12673 12674 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 12675 LD->getPointerInfo().getWithOffset(4), 12676 std::min(4U, LD->getAlignment()), 12677 LD->getMemOperand()->getFlags()); 12678 12679 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 12680 if (DCI.DAG.getDataLayout().isBigEndian()) 12681 std::swap (NewLD1, NewLD2); 12682 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 12683 return Result; 12684 } 12685 12686 return SDValue(); 12687 } 12688 12689 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 12690 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 12691 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 12692 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 12693 SDValue Op0 = N->getOperand(0); 12694 SDValue Op1 = N->getOperand(1); 12695 if (Op0.getOpcode() == ISD::BITCAST) 12696 Op0 = Op0.getOperand(0); 12697 if (Op1.getOpcode() == ISD::BITCAST) 12698 Op1 = Op1.getOperand(0); 12699 if (Op0.getOpcode() == ARMISD::VMOVRRD && 12700 Op0.getNode() == Op1.getNode() && 12701 Op0.getResNo() == 0 && Op1.getResNo() == 1) 12702 return DAG.getNode(ISD::BITCAST, SDLoc(N), 12703 N->getValueType(0), Op0.getOperand(0)); 12704 return SDValue(); 12705 } 12706 12707 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 12708 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 12709 /// i64 vector to have f64 elements, since the value can then be loaded 12710 /// directly into a VFP register. 12711 static bool hasNormalLoadOperand(SDNode *N) { 12712 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 12713 for (unsigned i = 0; i < NumElts; ++i) { 12714 SDNode *Elt = N->getOperand(i).getNode(); 12715 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 12716 return true; 12717 } 12718 return false; 12719 } 12720 12721 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 12722 /// ISD::BUILD_VECTOR. 12723 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 12724 TargetLowering::DAGCombinerInfo &DCI, 12725 const ARMSubtarget *Subtarget) { 12726 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 12727 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 12728 // into a pair of GPRs, which is fine when the value is used as a scalar, 12729 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 12730 SelectionDAG &DAG = DCI.DAG; 12731 if (N->getNumOperands() == 2) 12732 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 12733 return RV; 12734 12735 // Load i64 elements as f64 values so that type legalization does not split 12736 // them up into i32 values. 12737 EVT VT = N->getValueType(0); 12738 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 12739 return SDValue(); 12740 SDLoc dl(N); 12741 SmallVector<SDValue, 8> Ops; 12742 unsigned NumElts = VT.getVectorNumElements(); 12743 for (unsigned i = 0; i < NumElts; ++i) { 12744 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 12745 Ops.push_back(V); 12746 // Make the DAGCombiner fold the bitcast. 12747 DCI.AddToWorklist(V.getNode()); 12748 } 12749 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 12750 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 12751 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12752 } 12753 12754 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 12755 static SDValue 12756 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12757 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 12758 // At that time, we may have inserted bitcasts from integer to float. 12759 // If these bitcasts have survived DAGCombine, change the lowering of this 12760 // BUILD_VECTOR in something more vector friendly, i.e., that does not 12761 // force to use floating point types. 12762 12763 // Make sure we can change the type of the vector. 12764 // This is possible iff: 12765 // 1. The vector is only used in a bitcast to a integer type. I.e., 12766 // 1.1. Vector is used only once. 12767 // 1.2. Use is a bit convert to an integer type. 12768 // 2. The size of its operands are 32-bits (64-bits are not legal). 12769 EVT VT = N->getValueType(0); 12770 EVT EltVT = VT.getVectorElementType(); 12771 12772 // Check 1.1. and 2. 12773 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 12774 return SDValue(); 12775 12776 // By construction, the input type must be float. 12777 assert(EltVT == MVT::f32 && "Unexpected type!"); 12778 12779 // Check 1.2. 12780 SDNode *Use = *N->use_begin(); 12781 if (Use->getOpcode() != ISD::BITCAST || 12782 Use->getValueType(0).isFloatingPoint()) 12783 return SDValue(); 12784 12785 // Check profitability. 12786 // Model is, if more than half of the relevant operands are bitcast from 12787 // i32, turn the build_vector into a sequence of insert_vector_elt. 12788 // Relevant operands are everything that is not statically 12789 // (i.e., at compile time) bitcasted. 12790 unsigned NumOfBitCastedElts = 0; 12791 unsigned NumElts = VT.getVectorNumElements(); 12792 unsigned NumOfRelevantElts = NumElts; 12793 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 12794 SDValue Elt = N->getOperand(Idx); 12795 if (Elt->getOpcode() == ISD::BITCAST) { 12796 // Assume only bit cast to i32 will go away. 12797 if (Elt->getOperand(0).getValueType() == MVT::i32) 12798 ++NumOfBitCastedElts; 12799 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 12800 // Constants are statically casted, thus do not count them as 12801 // relevant operands. 12802 --NumOfRelevantElts; 12803 } 12804 12805 // Check if more than half of the elements require a non-free bitcast. 12806 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 12807 return SDValue(); 12808 12809 SelectionDAG &DAG = DCI.DAG; 12810 // Create the new vector type. 12811 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 12812 // Check if the type is legal. 12813 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12814 if (!TLI.isTypeLegal(VecVT)) 12815 return SDValue(); 12816 12817 // Combine: 12818 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 12819 // => BITCAST INSERT_VECTOR_ELT 12820 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 12821 // (BITCAST EN), N. 12822 SDValue Vec = DAG.getUNDEF(VecVT); 12823 SDLoc dl(N); 12824 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 12825 SDValue V = N->getOperand(Idx); 12826 if (V.isUndef()) 12827 continue; 12828 if (V.getOpcode() == ISD::BITCAST && 12829 V->getOperand(0).getValueType() == MVT::i32) 12830 // Fold obvious case. 12831 V = V.getOperand(0); 12832 else { 12833 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 12834 // Make the DAGCombiner fold the bitcasts. 12835 DCI.AddToWorklist(V.getNode()); 12836 } 12837 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 12838 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 12839 } 12840 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 12841 // Make the DAGCombiner fold the bitcasts. 12842 DCI.AddToWorklist(Vec.getNode()); 12843 return Vec; 12844 } 12845 12846 static SDValue 12847 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12848 EVT VT = N->getValueType(0); 12849 SDValue Op = N->getOperand(0); 12850 SDLoc dl(N); 12851 12852 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x) 12853 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) { 12854 // If the valuetypes are the same, we can remove the cast entirely. 12855 if (Op->getOperand(0).getValueType() == VT) 12856 return Op->getOperand(0); 12857 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, 12858 Op->getOperand(0).getValueType(), Op->getOperand(0)); 12859 } 12860 12861 return SDValue(); 12862 } 12863 12864 static SDValue PerformVCMPCombine(SDNode *N, 12865 TargetLowering::DAGCombinerInfo &DCI, 12866 const ARMSubtarget *Subtarget) { 12867 if (!Subtarget->hasMVEIntegerOps()) 12868 return SDValue(); 12869 12870 EVT VT = N->getValueType(0); 12871 SDValue Op0 = N->getOperand(0); 12872 SDValue Op1 = N->getOperand(1); 12873 ARMCC::CondCodes Cond = 12874 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12875 SDLoc dl(N); 12876 12877 // vcmp X, 0, cc -> vcmpz X, cc 12878 if (isZeroVector(Op1)) 12879 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, 12880 N->getOperand(2)); 12881 12882 unsigned SwappedCond = getSwappedCondition(Cond); 12883 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) { 12884 // vcmp 0, X, cc -> vcmpz X, reversed(cc) 12885 if (isZeroVector(Op0)) 12886 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1, 12887 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 12888 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc) 12889 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP) 12890 return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0, 12891 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 12892 } 12893 12894 return SDValue(); 12895 } 12896 12897 /// PerformInsertEltCombine - Target-specific dag combine xforms for 12898 /// ISD::INSERT_VECTOR_ELT. 12899 static SDValue PerformInsertEltCombine(SDNode *N, 12900 TargetLowering::DAGCombinerInfo &DCI) { 12901 // Bitcast an i64 load inserted into a vector to f64. 12902 // Otherwise, the i64 value will be legalized to a pair of i32 values. 12903 EVT VT = N->getValueType(0); 12904 SDNode *Elt = N->getOperand(1).getNode(); 12905 if (VT.getVectorElementType() != MVT::i64 || 12906 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 12907 return SDValue(); 12908 12909 SelectionDAG &DAG = DCI.DAG; 12910 SDLoc dl(N); 12911 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 12912 VT.getVectorNumElements()); 12913 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 12914 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 12915 // Make the DAGCombiner fold the bitcasts. 12916 DCI.AddToWorklist(Vec.getNode()); 12917 DCI.AddToWorklist(V.getNode()); 12918 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 12919 Vec, V, N->getOperand(2)); 12920 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 12921 } 12922 12923 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 12924 /// ISD::VECTOR_SHUFFLE. 12925 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 12926 // The LLVM shufflevector instruction does not require the shuffle mask 12927 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 12928 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 12929 // operands do not match the mask length, they are extended by concatenating 12930 // them with undef vectors. That is probably the right thing for other 12931 // targets, but for NEON it is better to concatenate two double-register 12932 // size vector operands into a single quad-register size vector. Do that 12933 // transformation here: 12934 // shuffle(concat(v1, undef), concat(v2, undef)) -> 12935 // shuffle(concat(v1, v2), undef) 12936 SDValue Op0 = N->getOperand(0); 12937 SDValue Op1 = N->getOperand(1); 12938 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 12939 Op1.getOpcode() != ISD::CONCAT_VECTORS || 12940 Op0.getNumOperands() != 2 || 12941 Op1.getNumOperands() != 2) 12942 return SDValue(); 12943 SDValue Concat0Op1 = Op0.getOperand(1); 12944 SDValue Concat1Op1 = Op1.getOperand(1); 12945 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 12946 return SDValue(); 12947 // Skip the transformation if any of the types are illegal. 12948 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12949 EVT VT = N->getValueType(0); 12950 if (!TLI.isTypeLegal(VT) || 12951 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 12952 !TLI.isTypeLegal(Concat1Op1.getValueType())) 12953 return SDValue(); 12954 12955 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12956 Op0.getOperand(0), Op1.getOperand(0)); 12957 // Translate the shuffle mask. 12958 SmallVector<int, 16> NewMask; 12959 unsigned NumElts = VT.getVectorNumElements(); 12960 unsigned HalfElts = NumElts/2; 12961 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12962 for (unsigned n = 0; n < NumElts; ++n) { 12963 int MaskElt = SVN->getMaskElt(n); 12964 int NewElt = -1; 12965 if (MaskElt < (int)HalfElts) 12966 NewElt = MaskElt; 12967 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 12968 NewElt = HalfElts + MaskElt - NumElts; 12969 NewMask.push_back(NewElt); 12970 } 12971 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 12972 DAG.getUNDEF(VT), NewMask); 12973 } 12974 12975 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 12976 /// NEON load/store intrinsics, and generic vector load/stores, to merge 12977 /// base address updates. 12978 /// For generic load/stores, the memory type is assumed to be a vector. 12979 /// The caller is assumed to have checked legality. 12980 static SDValue CombineBaseUpdate(SDNode *N, 12981 TargetLowering::DAGCombinerInfo &DCI) { 12982 SelectionDAG &DAG = DCI.DAG; 12983 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 12984 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 12985 const bool isStore = N->getOpcode() == ISD::STORE; 12986 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 12987 SDValue Addr = N->getOperand(AddrOpIdx); 12988 MemSDNode *MemN = cast<MemSDNode>(N); 12989 SDLoc dl(N); 12990 12991 // Search for a use of the address operand that is an increment. 12992 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 12993 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 12994 SDNode *User = *UI; 12995 if (User->getOpcode() != ISD::ADD || 12996 UI.getUse().getResNo() != Addr.getResNo()) 12997 continue; 12998 12999 // Check that the add is independent of the load/store. Otherwise, folding 13000 // it would create a cycle. We can avoid searching through Addr as it's a 13001 // predecessor to both. 13002 SmallPtrSet<const SDNode *, 32> Visited; 13003 SmallVector<const SDNode *, 16> Worklist; 13004 Visited.insert(Addr.getNode()); 13005 Worklist.push_back(N); 13006 Worklist.push_back(User); 13007 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 13008 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 13009 continue; 13010 13011 // Find the new opcode for the updating load/store. 13012 bool isLoadOp = true; 13013 bool isLaneOp = false; 13014 unsigned NewOpc = 0; 13015 unsigned NumVecs = 0; 13016 if (isIntrinsic) { 13017 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 13018 switch (IntNo) { 13019 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 13020 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 13021 NumVecs = 1; break; 13022 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 13023 NumVecs = 2; break; 13024 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 13025 NumVecs = 3; break; 13026 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 13027 NumVecs = 4; break; 13028 case Intrinsic::arm_neon_vld2dup: 13029 case Intrinsic::arm_neon_vld3dup: 13030 case Intrinsic::arm_neon_vld4dup: 13031 // TODO: Support updating VLDxDUP nodes. For now, we just skip 13032 // combining base updates for such intrinsics. 13033 continue; 13034 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 13035 NumVecs = 2; isLaneOp = true; break; 13036 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 13037 NumVecs = 3; isLaneOp = true; break; 13038 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 13039 NumVecs = 4; isLaneOp = true; break; 13040 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 13041 NumVecs = 1; isLoadOp = false; break; 13042 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 13043 NumVecs = 2; isLoadOp = false; break; 13044 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 13045 NumVecs = 3; isLoadOp = false; break; 13046 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 13047 NumVecs = 4; isLoadOp = false; break; 13048 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 13049 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 13050 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 13051 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 13052 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 13053 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 13054 } 13055 } else { 13056 isLaneOp = true; 13057 switch (N->getOpcode()) { 13058 default: llvm_unreachable("unexpected opcode for Neon base update"); 13059 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 13060 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 13061 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 13062 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 13063 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 13064 NumVecs = 1; isLaneOp = false; break; 13065 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 13066 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 13067 } 13068 } 13069 13070 // Find the size of memory referenced by the load/store. 13071 EVT VecTy; 13072 if (isLoadOp) { 13073 VecTy = N->getValueType(0); 13074 } else if (isIntrinsic) { 13075 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 13076 } else { 13077 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 13078 VecTy = N->getOperand(1).getValueType(); 13079 } 13080 13081 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 13082 if (isLaneOp) 13083 NumBytes /= VecTy.getVectorNumElements(); 13084 13085 // If the increment is a constant, it must match the memory ref size. 13086 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 13087 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 13088 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 13089 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 13090 // separate instructions that make it harder to use a non-constant update. 13091 continue; 13092 } 13093 13094 // OK, we found an ADD we can fold into the base update. 13095 // Now, create a _UPD node, taking care of not breaking alignment. 13096 13097 EVT AlignedVecTy = VecTy; 13098 unsigned Alignment = MemN->getAlignment(); 13099 13100 // If this is a less-than-standard-aligned load/store, change the type to 13101 // match the standard alignment. 13102 // The alignment is overlooked when selecting _UPD variants; and it's 13103 // easier to introduce bitcasts here than fix that. 13104 // There are 3 ways to get to this base-update combine: 13105 // - intrinsics: they are assumed to be properly aligned (to the standard 13106 // alignment of the memory type), so we don't need to do anything. 13107 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 13108 // intrinsics, so, likewise, there's nothing to do. 13109 // - generic load/store instructions: the alignment is specified as an 13110 // explicit operand, rather than implicitly as the standard alignment 13111 // of the memory type (like the intrisics). We need to change the 13112 // memory type to match the explicit alignment. That way, we don't 13113 // generate non-standard-aligned ARMISD::VLDx nodes. 13114 if (isa<LSBaseSDNode>(N)) { 13115 if (Alignment == 0) 13116 Alignment = 1; 13117 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 13118 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 13119 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 13120 assert(!isLaneOp && "Unexpected generic load/store lane."); 13121 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 13122 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 13123 } 13124 // Don't set an explicit alignment on regular load/stores that we want 13125 // to transform to VLD/VST 1_UPD nodes. 13126 // This matches the behavior of regular load/stores, which only get an 13127 // explicit alignment if the MMO alignment is larger than the standard 13128 // alignment of the memory type. 13129 // Intrinsics, however, always get an explicit alignment, set to the 13130 // alignment of the MMO. 13131 Alignment = 1; 13132 } 13133 13134 // Create the new updating load/store node. 13135 // First, create an SDVTList for the new updating node's results. 13136 EVT Tys[6]; 13137 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 13138 unsigned n; 13139 for (n = 0; n < NumResultVecs; ++n) 13140 Tys[n] = AlignedVecTy; 13141 Tys[n++] = MVT::i32; 13142 Tys[n] = MVT::Other; 13143 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 13144 13145 // Then, gather the new node's operands. 13146 SmallVector<SDValue, 8> Ops; 13147 Ops.push_back(N->getOperand(0)); // incoming chain 13148 Ops.push_back(N->getOperand(AddrOpIdx)); 13149 Ops.push_back(Inc); 13150 13151 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 13152 // Try to match the intrinsic's signature 13153 Ops.push_back(StN->getValue()); 13154 } else { 13155 // Loads (and of course intrinsics) match the intrinsics' signature, 13156 // so just add all but the alignment operand. 13157 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 13158 Ops.push_back(N->getOperand(i)); 13159 } 13160 13161 // For all node types, the alignment operand is always the last one. 13162 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 13163 13164 // If this is a non-standard-aligned STORE, the penultimate operand is the 13165 // stored value. Bitcast it to the aligned type. 13166 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 13167 SDValue &StVal = Ops[Ops.size()-2]; 13168 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 13169 } 13170 13171 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 13172 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 13173 MemN->getMemOperand()); 13174 13175 // Update the uses. 13176 SmallVector<SDValue, 5> NewResults; 13177 for (unsigned i = 0; i < NumResultVecs; ++i) 13178 NewResults.push_back(SDValue(UpdN.getNode(), i)); 13179 13180 // If this is an non-standard-aligned LOAD, the first result is the loaded 13181 // value. Bitcast it to the expected result type. 13182 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 13183 SDValue &LdVal = NewResults[0]; 13184 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 13185 } 13186 13187 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 13188 DCI.CombineTo(N, NewResults); 13189 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 13190 13191 break; 13192 } 13193 return SDValue(); 13194 } 13195 13196 static SDValue PerformVLDCombine(SDNode *N, 13197 TargetLowering::DAGCombinerInfo &DCI) { 13198 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13199 return SDValue(); 13200 13201 return CombineBaseUpdate(N, DCI); 13202 } 13203 13204 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 13205 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 13206 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 13207 /// return true. 13208 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13209 SelectionDAG &DAG = DCI.DAG; 13210 EVT VT = N->getValueType(0); 13211 // vldN-dup instructions only support 64-bit vectors for N > 1. 13212 if (!VT.is64BitVector()) 13213 return false; 13214 13215 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 13216 SDNode *VLD = N->getOperand(0).getNode(); 13217 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 13218 return false; 13219 unsigned NumVecs = 0; 13220 unsigned NewOpc = 0; 13221 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 13222 if (IntNo == Intrinsic::arm_neon_vld2lane) { 13223 NumVecs = 2; 13224 NewOpc = ARMISD::VLD2DUP; 13225 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 13226 NumVecs = 3; 13227 NewOpc = ARMISD::VLD3DUP; 13228 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 13229 NumVecs = 4; 13230 NewOpc = ARMISD::VLD4DUP; 13231 } else { 13232 return false; 13233 } 13234 13235 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 13236 // numbers match the load. 13237 unsigned VLDLaneNo = 13238 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 13239 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 13240 UI != UE; ++UI) { 13241 // Ignore uses of the chain result. 13242 if (UI.getUse().getResNo() == NumVecs) 13243 continue; 13244 SDNode *User = *UI; 13245 if (User->getOpcode() != ARMISD::VDUPLANE || 13246 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 13247 return false; 13248 } 13249 13250 // Create the vldN-dup node. 13251 EVT Tys[5]; 13252 unsigned n; 13253 for (n = 0; n < NumVecs; ++n) 13254 Tys[n] = VT; 13255 Tys[n] = MVT::Other; 13256 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 13257 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 13258 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 13259 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 13260 Ops, VLDMemInt->getMemoryVT(), 13261 VLDMemInt->getMemOperand()); 13262 13263 // Update the uses. 13264 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 13265 UI != UE; ++UI) { 13266 unsigned ResNo = UI.getUse().getResNo(); 13267 // Ignore uses of the chain result. 13268 if (ResNo == NumVecs) 13269 continue; 13270 SDNode *User = *UI; 13271 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 13272 } 13273 13274 // Now the vldN-lane intrinsic is dead except for its chain result. 13275 // Update uses of the chain. 13276 std::vector<SDValue> VLDDupResults; 13277 for (unsigned n = 0; n < NumVecs; ++n) 13278 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 13279 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 13280 DCI.CombineTo(VLD, VLDDupResults); 13281 13282 return true; 13283 } 13284 13285 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 13286 /// ARMISD::VDUPLANE. 13287 static SDValue PerformVDUPLANECombine(SDNode *N, 13288 TargetLowering::DAGCombinerInfo &DCI) { 13289 SDValue Op = N->getOperand(0); 13290 13291 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 13292 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 13293 if (CombineVLDDUP(N, DCI)) 13294 return SDValue(N, 0); 13295 13296 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 13297 // redundant. Ignore bit_converts for now; element sizes are checked below. 13298 while (Op.getOpcode() == ISD::BITCAST) 13299 Op = Op.getOperand(0); 13300 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 13301 return SDValue(); 13302 13303 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 13304 unsigned EltSize = Op.getScalarValueSizeInBits(); 13305 // The canonical VMOV for a zero vector uses a 32-bit element size. 13306 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13307 unsigned EltBits; 13308 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 13309 EltSize = 8; 13310 EVT VT = N->getValueType(0); 13311 if (EltSize > VT.getScalarSizeInBits()) 13312 return SDValue(); 13313 13314 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 13315 } 13316 13317 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 13318 static SDValue PerformVDUPCombine(SDNode *N, 13319 TargetLowering::DAGCombinerInfo &DCI, 13320 const ARMSubtarget *Subtarget) { 13321 SelectionDAG &DAG = DCI.DAG; 13322 SDValue Op = N->getOperand(0); 13323 13324 if (!Subtarget->hasNEON()) 13325 return SDValue(); 13326 13327 // Match VDUP(LOAD) -> VLD1DUP. 13328 // We match this pattern here rather than waiting for isel because the 13329 // transform is only legal for unindexed loads. 13330 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 13331 if (LD && Op.hasOneUse() && LD->isUnindexed() && 13332 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 13333 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 13334 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 13335 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 13336 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 13337 Ops, LD->getMemoryVT(), 13338 LD->getMemOperand()); 13339 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 13340 return VLDDup; 13341 } 13342 13343 return SDValue(); 13344 } 13345 13346 static SDValue PerformLOADCombine(SDNode *N, 13347 TargetLowering::DAGCombinerInfo &DCI) { 13348 EVT VT = N->getValueType(0); 13349 13350 // If this is a legal vector load, try to combine it into a VLD1_UPD. 13351 if (ISD::isNormalLoad(N) && VT.isVector() && 13352 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13353 return CombineBaseUpdate(N, DCI); 13354 13355 return SDValue(); 13356 } 13357 13358 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 13359 // pack all of the elements in one place. Next, store to memory in fewer 13360 // chunks. 13361 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St, 13362 SelectionDAG &DAG) { 13363 SDValue StVal = St->getValue(); 13364 EVT VT = StVal.getValueType(); 13365 if (!St->isTruncatingStore() || !VT.isVector()) 13366 return SDValue(); 13367 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13368 EVT StVT = St->getMemoryVT(); 13369 unsigned NumElems = VT.getVectorNumElements(); 13370 assert(StVT != VT && "Cannot truncate to the same type"); 13371 unsigned FromEltSz = VT.getScalarSizeInBits(); 13372 unsigned ToEltSz = StVT.getScalarSizeInBits(); 13373 13374 // From, To sizes and ElemCount must be pow of two 13375 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) 13376 return SDValue(); 13377 13378 // We are going to use the original vector elt for storing. 13379 // Accumulated smaller vector elements must be a multiple of the store size. 13380 if (0 != (NumElems * FromEltSz) % ToEltSz) 13381 return SDValue(); 13382 13383 unsigned SizeRatio = FromEltSz / ToEltSz; 13384 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 13385 13386 // Create a type on which we perform the shuffle. 13387 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 13388 NumElems * SizeRatio); 13389 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 13390 13391 SDLoc DL(St); 13392 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 13393 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 13394 for (unsigned i = 0; i < NumElems; ++i) 13395 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1 13396 : i * SizeRatio; 13397 13398 // Can't shuffle using an illegal type. 13399 if (!TLI.isTypeLegal(WideVecVT)) 13400 return SDValue(); 13401 13402 SDValue Shuff = DAG.getVectorShuffle( 13403 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec); 13404 // At this point all of the data is stored at the bottom of the 13405 // register. We now need to save it to mem. 13406 13407 // Find the largest store unit 13408 MVT StoreType = MVT::i8; 13409 for (MVT Tp : MVT::integer_valuetypes()) { 13410 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 13411 StoreType = Tp; 13412 } 13413 // Didn't find a legal store type. 13414 if (!TLI.isTypeLegal(StoreType)) 13415 return SDValue(); 13416 13417 // Bitcast the original vector into a vector of store-size units 13418 EVT StoreVecVT = 13419 EVT::getVectorVT(*DAG.getContext(), StoreType, 13420 VT.getSizeInBits() / EVT(StoreType).getSizeInBits()); 13421 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 13422 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 13423 SmallVector<SDValue, 8> Chains; 13424 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 13425 TLI.getPointerTy(DAG.getDataLayout())); 13426 SDValue BasePtr = St->getBasePtr(); 13427 13428 // Perform one or more big stores into memory. 13429 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits(); 13430 for (unsigned I = 0; I < E; I++) { 13431 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType, 13432 ShuffWide, DAG.getIntPtrConstant(I, DL)); 13433 SDValue Ch = 13434 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(), 13435 St->getAlignment(), St->getMemOperand()->getFlags()); 13436 BasePtr = 13437 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment); 13438 Chains.push_back(Ch); 13439 } 13440 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 13441 } 13442 13443 // Try taking a single vector store from an truncate (which would otherwise turn 13444 // into an expensive buildvector) and splitting it into a series of narrowing 13445 // stores. 13446 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St, 13447 SelectionDAG &DAG) { 13448 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed()) 13449 return SDValue(); 13450 SDValue Trunc = St->getValue(); 13451 if (Trunc->getOpcode() != ISD::TRUNCATE) 13452 return SDValue(); 13453 EVT FromVT = Trunc->getOperand(0).getValueType(); 13454 EVT ToVT = Trunc.getValueType(); 13455 if (!ToVT.isVector()) 13456 return SDValue(); 13457 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 13458 EVT ToEltVT = ToVT.getVectorElementType(); 13459 EVT FromEltVT = FromVT.getVectorElementType(); 13460 13461 unsigned NumElements = 0; 13462 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8)) 13463 NumElements = 4; 13464 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8) 13465 NumElements = 8; 13466 if (NumElements == 0 || FromVT.getVectorNumElements() == NumElements || 13467 FromVT.getVectorNumElements() % NumElements != 0) 13468 return SDValue(); 13469 13470 SDLoc DL(St); 13471 // Details about the old store 13472 SDValue Ch = St->getChain(); 13473 SDValue BasePtr = St->getBasePtr(); 13474 unsigned Alignment = St->getOriginalAlignment(); 13475 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags(); 13476 AAMDNodes AAInfo = St->getAAInfo(); 13477 13478 EVT NewFromVT = EVT::getVectorVT(*DAG.getContext(), FromEltVT, NumElements); 13479 EVT NewToVT = EVT::getVectorVT(*DAG.getContext(), ToEltVT, NumElements); 13480 13481 SmallVector<SDValue, 4> Stores; 13482 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 13483 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8; 13484 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset); 13485 13486 SDValue Extract = 13487 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0), 13488 DAG.getConstant(i * NumElements, DL, MVT::i32)); 13489 SDValue Store = DAG.getTruncStore( 13490 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset), 13491 NewToVT, Alignment, MMOFlags, AAInfo); 13492 Stores.push_back(Store); 13493 } 13494 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores); 13495 } 13496 13497 /// PerformSTORECombine - Target-specific dag combine xforms for 13498 /// ISD::STORE. 13499 static SDValue PerformSTORECombine(SDNode *N, 13500 TargetLowering::DAGCombinerInfo &DCI, 13501 const ARMSubtarget *Subtarget) { 13502 StoreSDNode *St = cast<StoreSDNode>(N); 13503 if (St->isVolatile()) 13504 return SDValue(); 13505 SDValue StVal = St->getValue(); 13506 EVT VT = StVal.getValueType(); 13507 13508 if (Subtarget->hasNEON()) 13509 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG)) 13510 return Store; 13511 13512 if (Subtarget->hasMVEIntegerOps()) 13513 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG)) 13514 return NewToken; 13515 13516 if (!ISD::isNormalStore(St)) 13517 return SDValue(); 13518 13519 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 13520 // ARM stores of arguments in the same cache line. 13521 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 13522 StVal.getNode()->hasOneUse()) { 13523 SelectionDAG &DAG = DCI.DAG; 13524 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 13525 SDLoc DL(St); 13526 SDValue BasePtr = St->getBasePtr(); 13527 SDValue NewST1 = DAG.getStore( 13528 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 13529 BasePtr, St->getPointerInfo(), St->getAlignment(), 13530 St->getMemOperand()->getFlags()); 13531 13532 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 13533 DAG.getConstant(4, DL, MVT::i32)); 13534 return DAG.getStore(NewST1.getValue(0), DL, 13535 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 13536 OffsetPtr, St->getPointerInfo(), 13537 std::min(4U, St->getAlignment() / 2), 13538 St->getMemOperand()->getFlags()); 13539 } 13540 13541 if (StVal.getValueType() == MVT::i64 && 13542 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13543 13544 // Bitcast an i64 store extracted from a vector to f64. 13545 // Otherwise, the i64 value will be legalized to a pair of i32 values. 13546 SelectionDAG &DAG = DCI.DAG; 13547 SDLoc dl(StVal); 13548 SDValue IntVec = StVal.getOperand(0); 13549 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 13550 IntVec.getValueType().getVectorNumElements()); 13551 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 13552 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 13553 Vec, StVal.getOperand(1)); 13554 dl = SDLoc(N); 13555 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 13556 // Make the DAGCombiner fold the bitcasts. 13557 DCI.AddToWorklist(Vec.getNode()); 13558 DCI.AddToWorklist(ExtElt.getNode()); 13559 DCI.AddToWorklist(V.getNode()); 13560 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 13561 St->getPointerInfo(), St->getAlignment(), 13562 St->getMemOperand()->getFlags(), St->getAAInfo()); 13563 } 13564 13565 // If this is a legal vector store, try to combine it into a VST1_UPD. 13566 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() && 13567 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13568 return CombineBaseUpdate(N, DCI); 13569 13570 return SDValue(); 13571 } 13572 13573 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 13574 /// can replace combinations of VMUL and VCVT (floating-point to integer) 13575 /// when the VMUL has a constant operand that is a power of 2. 13576 /// 13577 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 13578 /// vmul.f32 d16, d17, d16 13579 /// vcvt.s32.f32 d16, d16 13580 /// becomes: 13581 /// vcvt.s32.f32 d16, d16, #3 13582 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 13583 const ARMSubtarget *Subtarget) { 13584 if (!Subtarget->hasNEON()) 13585 return SDValue(); 13586 13587 SDValue Op = N->getOperand(0); 13588 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 13589 Op.getOpcode() != ISD::FMUL) 13590 return SDValue(); 13591 13592 SDValue ConstVec = Op->getOperand(1); 13593 if (!isa<BuildVectorSDNode>(ConstVec)) 13594 return SDValue(); 13595 13596 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 13597 uint32_t FloatBits = FloatTy.getSizeInBits(); 13598 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 13599 uint32_t IntBits = IntTy.getSizeInBits(); 13600 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 13601 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 13602 // These instructions only exist converting from f32 to i32. We can handle 13603 // smaller integers by generating an extra truncate, but larger ones would 13604 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 13605 // these intructions only support v2i32/v4i32 types. 13606 return SDValue(); 13607 } 13608 13609 BitVector UndefElements; 13610 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 13611 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 13612 if (C == -1 || C == 0 || C > 32) 13613 return SDValue(); 13614 13615 SDLoc dl(N); 13616 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 13617 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 13618 Intrinsic::arm_neon_vcvtfp2fxu; 13619 SDValue FixConv = DAG.getNode( 13620 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 13621 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 13622 DAG.getConstant(C, dl, MVT::i32)); 13623 13624 if (IntBits < FloatBits) 13625 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 13626 13627 return FixConv; 13628 } 13629 13630 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 13631 /// can replace combinations of VCVT (integer to floating-point) and VDIV 13632 /// when the VDIV has a constant operand that is a power of 2. 13633 /// 13634 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 13635 /// vcvt.f32.s32 d16, d16 13636 /// vdiv.f32 d16, d17, d16 13637 /// becomes: 13638 /// vcvt.f32.s32 d16, d16, #3 13639 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 13640 const ARMSubtarget *Subtarget) { 13641 if (!Subtarget->hasNEON()) 13642 return SDValue(); 13643 13644 SDValue Op = N->getOperand(0); 13645 unsigned OpOpcode = Op.getNode()->getOpcode(); 13646 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 13647 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 13648 return SDValue(); 13649 13650 SDValue ConstVec = N->getOperand(1); 13651 if (!isa<BuildVectorSDNode>(ConstVec)) 13652 return SDValue(); 13653 13654 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 13655 uint32_t FloatBits = FloatTy.getSizeInBits(); 13656 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 13657 uint32_t IntBits = IntTy.getSizeInBits(); 13658 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 13659 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 13660 // These instructions only exist converting from i32 to f32. We can handle 13661 // smaller integers by generating an extra extend, but larger ones would 13662 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 13663 // these intructions only support v2i32/v4i32 types. 13664 return SDValue(); 13665 } 13666 13667 BitVector UndefElements; 13668 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 13669 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 13670 if (C == -1 || C == 0 || C > 32) 13671 return SDValue(); 13672 13673 SDLoc dl(N); 13674 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 13675 SDValue ConvInput = Op.getOperand(0); 13676 if (IntBits < FloatBits) 13677 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 13678 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 13679 ConvInput); 13680 13681 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 13682 Intrinsic::arm_neon_vcvtfxu2fp; 13683 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 13684 Op.getValueType(), 13685 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 13686 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 13687 } 13688 13689 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 13690 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 13691 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13692 switch (IntNo) { 13693 default: 13694 // Don't do anything for most intrinsics. 13695 break; 13696 13697 // Vector shifts: check for immediate versions and lower them. 13698 // Note: This is done during DAG combining instead of DAG legalizing because 13699 // the build_vectors for 64-bit vector element shift counts are generally 13700 // not legal, and it is hard to see their values after they get legalized to 13701 // loads from a constant pool. 13702 case Intrinsic::arm_neon_vshifts: 13703 case Intrinsic::arm_neon_vshiftu: 13704 case Intrinsic::arm_neon_vrshifts: 13705 case Intrinsic::arm_neon_vrshiftu: 13706 case Intrinsic::arm_neon_vrshiftn: 13707 case Intrinsic::arm_neon_vqshifts: 13708 case Intrinsic::arm_neon_vqshiftu: 13709 case Intrinsic::arm_neon_vqshiftsu: 13710 case Intrinsic::arm_neon_vqshiftns: 13711 case Intrinsic::arm_neon_vqshiftnu: 13712 case Intrinsic::arm_neon_vqshiftnsu: 13713 case Intrinsic::arm_neon_vqrshiftns: 13714 case Intrinsic::arm_neon_vqrshiftnu: 13715 case Intrinsic::arm_neon_vqrshiftnsu: { 13716 EVT VT = N->getOperand(1).getValueType(); 13717 int64_t Cnt; 13718 unsigned VShiftOpc = 0; 13719 13720 switch (IntNo) { 13721 case Intrinsic::arm_neon_vshifts: 13722 case Intrinsic::arm_neon_vshiftu: 13723 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 13724 VShiftOpc = ARMISD::VSHLIMM; 13725 break; 13726 } 13727 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 13728 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 13729 : ARMISD::VSHRuIMM); 13730 break; 13731 } 13732 return SDValue(); 13733 13734 case Intrinsic::arm_neon_vrshifts: 13735 case Intrinsic::arm_neon_vrshiftu: 13736 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 13737 break; 13738 return SDValue(); 13739 13740 case Intrinsic::arm_neon_vqshifts: 13741 case Intrinsic::arm_neon_vqshiftu: 13742 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 13743 break; 13744 return SDValue(); 13745 13746 case Intrinsic::arm_neon_vqshiftsu: 13747 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 13748 break; 13749 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 13750 13751 case Intrinsic::arm_neon_vrshiftn: 13752 case Intrinsic::arm_neon_vqshiftns: 13753 case Intrinsic::arm_neon_vqshiftnu: 13754 case Intrinsic::arm_neon_vqshiftnsu: 13755 case Intrinsic::arm_neon_vqrshiftns: 13756 case Intrinsic::arm_neon_vqrshiftnu: 13757 case Intrinsic::arm_neon_vqrshiftnsu: 13758 // Narrowing shifts require an immediate right shift. 13759 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 13760 break; 13761 llvm_unreachable("invalid shift count for narrowing vector shift " 13762 "intrinsic"); 13763 13764 default: 13765 llvm_unreachable("unhandled vector shift"); 13766 } 13767 13768 switch (IntNo) { 13769 case Intrinsic::arm_neon_vshifts: 13770 case Intrinsic::arm_neon_vshiftu: 13771 // Opcode already set above. 13772 break; 13773 case Intrinsic::arm_neon_vrshifts: 13774 VShiftOpc = ARMISD::VRSHRsIMM; 13775 break; 13776 case Intrinsic::arm_neon_vrshiftu: 13777 VShiftOpc = ARMISD::VRSHRuIMM; 13778 break; 13779 case Intrinsic::arm_neon_vrshiftn: 13780 VShiftOpc = ARMISD::VRSHRNIMM; 13781 break; 13782 case Intrinsic::arm_neon_vqshifts: 13783 VShiftOpc = ARMISD::VQSHLsIMM; 13784 break; 13785 case Intrinsic::arm_neon_vqshiftu: 13786 VShiftOpc = ARMISD::VQSHLuIMM; 13787 break; 13788 case Intrinsic::arm_neon_vqshiftsu: 13789 VShiftOpc = ARMISD::VQSHLsuIMM; 13790 break; 13791 case Intrinsic::arm_neon_vqshiftns: 13792 VShiftOpc = ARMISD::VQSHRNsIMM; 13793 break; 13794 case Intrinsic::arm_neon_vqshiftnu: 13795 VShiftOpc = ARMISD::VQSHRNuIMM; 13796 break; 13797 case Intrinsic::arm_neon_vqshiftnsu: 13798 VShiftOpc = ARMISD::VQSHRNsuIMM; 13799 break; 13800 case Intrinsic::arm_neon_vqrshiftns: 13801 VShiftOpc = ARMISD::VQRSHRNsIMM; 13802 break; 13803 case Intrinsic::arm_neon_vqrshiftnu: 13804 VShiftOpc = ARMISD::VQRSHRNuIMM; 13805 break; 13806 case Intrinsic::arm_neon_vqrshiftnsu: 13807 VShiftOpc = ARMISD::VQRSHRNsuIMM; 13808 break; 13809 } 13810 13811 SDLoc dl(N); 13812 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 13813 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 13814 } 13815 13816 case Intrinsic::arm_neon_vshiftins: { 13817 EVT VT = N->getOperand(1).getValueType(); 13818 int64_t Cnt; 13819 unsigned VShiftOpc = 0; 13820 13821 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 13822 VShiftOpc = ARMISD::VSLIIMM; 13823 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 13824 VShiftOpc = ARMISD::VSRIIMM; 13825 else { 13826 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 13827 } 13828 13829 SDLoc dl(N); 13830 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 13831 N->getOperand(1), N->getOperand(2), 13832 DAG.getConstant(Cnt, dl, MVT::i32)); 13833 } 13834 13835 case Intrinsic::arm_neon_vqrshifts: 13836 case Intrinsic::arm_neon_vqrshiftu: 13837 // No immediate versions of these to check for. 13838 break; 13839 } 13840 13841 return SDValue(); 13842 } 13843 13844 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 13845 /// lowers them. As with the vector shift intrinsics, this is done during DAG 13846 /// combining instead of DAG legalizing because the build_vectors for 64-bit 13847 /// vector element shift counts are generally not legal, and it is hard to see 13848 /// their values after they get legalized to loads from a constant pool. 13849 static SDValue PerformShiftCombine(SDNode *N, 13850 TargetLowering::DAGCombinerInfo &DCI, 13851 const ARMSubtarget *ST) { 13852 SelectionDAG &DAG = DCI.DAG; 13853 EVT VT = N->getValueType(0); 13854 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 13855 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 13856 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 13857 SDValue N1 = N->getOperand(1); 13858 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 13859 SDValue N0 = N->getOperand(0); 13860 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 13861 DAG.MaskedValueIsZero(N0.getOperand(0), 13862 APInt::getHighBitsSet(32, 16))) 13863 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 13864 } 13865 } 13866 13867 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 13868 N->getOperand(0)->getOpcode() == ISD::AND && 13869 N->getOperand(0)->hasOneUse()) { 13870 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13871 return SDValue(); 13872 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 13873 // usually show up because instcombine prefers to canonicalize it to 13874 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 13875 // out of GEP lowering in some cases. 13876 SDValue N0 = N->getOperand(0); 13877 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13878 if (!ShiftAmtNode) 13879 return SDValue(); 13880 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 13881 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13882 if (!AndMaskNode) 13883 return SDValue(); 13884 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 13885 // Don't transform uxtb/uxth. 13886 if (AndMask == 255 || AndMask == 65535) 13887 return SDValue(); 13888 if (isMask_32(AndMask)) { 13889 uint32_t MaskedBits = countLeadingZeros(AndMask); 13890 if (MaskedBits > ShiftAmt) { 13891 SDLoc DL(N); 13892 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 13893 DAG.getConstant(MaskedBits, DL, MVT::i32)); 13894 return DAG.getNode( 13895 ISD::SRL, DL, MVT::i32, SHL, 13896 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 13897 } 13898 } 13899 } 13900 13901 // Nothing to be done for scalar shifts. 13902 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13903 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 13904 return SDValue(); 13905 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 13906 return SDValue(); 13907 13908 int64_t Cnt; 13909 13910 switch (N->getOpcode()) { 13911 default: llvm_unreachable("unexpected shift opcode"); 13912 13913 case ISD::SHL: 13914 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 13915 SDLoc dl(N); 13916 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 13917 DAG.getConstant(Cnt, dl, MVT::i32)); 13918 } 13919 break; 13920 13921 case ISD::SRA: 13922 case ISD::SRL: 13923 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 13924 unsigned VShiftOpc = 13925 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 13926 SDLoc dl(N); 13927 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 13928 DAG.getConstant(Cnt, dl, MVT::i32)); 13929 } 13930 } 13931 return SDValue(); 13932 } 13933 13934 // Look for a sign/zero extend of a larger than legal load. This can be split 13935 // into two extending loads, which are simpler to deal with than an arbitrary 13936 // sign extend. 13937 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) { 13938 SDValue N0 = N->getOperand(0); 13939 if (N0.getOpcode() != ISD::LOAD) 13940 return SDValue(); 13941 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode()); 13942 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() || 13943 LD->getExtensionType() != ISD::NON_EXTLOAD) 13944 return SDValue(); 13945 EVT FromVT = LD->getValueType(0); 13946 EVT ToVT = N->getValueType(0); 13947 if (!ToVT.isVector()) 13948 return SDValue(); 13949 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 13950 EVT ToEltVT = ToVT.getVectorElementType(); 13951 EVT FromEltVT = FromVT.getVectorElementType(); 13952 13953 unsigned NumElements = 0; 13954 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8)) 13955 NumElements = 4; 13956 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8) 13957 NumElements = 8; 13958 if (NumElements == 0 || 13959 FromVT.getVectorNumElements() == NumElements || 13960 FromVT.getVectorNumElements() % NumElements != 0 || 13961 !isPowerOf2_32(NumElements)) 13962 return SDValue(); 13963 13964 SDLoc DL(LD); 13965 // Details about the old load 13966 SDValue Ch = LD->getChain(); 13967 SDValue BasePtr = LD->getBasePtr(); 13968 unsigned Alignment = LD->getOriginalAlignment(); 13969 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 13970 AAMDNodes AAInfo = LD->getAAInfo(); 13971 13972 ISD::LoadExtType NewExtType = 13973 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 13974 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType()); 13975 EVT NewFromVT = FromVT.getHalfNumVectorElementsVT(*DAG.getContext()); 13976 EVT NewToVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext()); 13977 unsigned NewOffset = NewFromVT.getSizeInBits() / 8; 13978 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset); 13979 13980 // Split the load in half, each side of which is extended separately. This 13981 // is good enough, as legalisation will take it from there. They are either 13982 // already legal or they will be split further into something that is 13983 // legal. 13984 SDValue NewLoad1 = 13985 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, BasePtr, Offset, 13986 LD->getPointerInfo(), NewFromVT, Alignment, MMOFlags, AAInfo); 13987 SDValue NewLoad2 = 13988 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset, 13989 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT, 13990 Alignment, MMOFlags, AAInfo); 13991 13992 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 13993 SDValue(NewLoad1.getNode(), 1), 13994 SDValue(NewLoad2.getNode(), 1)); 13995 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain); 13996 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, NewLoad1, NewLoad2); 13997 } 13998 13999 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 14000 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 14001 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 14002 const ARMSubtarget *ST) { 14003 SDValue N0 = N->getOperand(0); 14004 14005 // Check for sign- and zero-extensions of vector extract operations of 8- and 14006 // 16-bit vector elements. NEON and MVE support these directly. They are 14007 // handled during DAG combining because type legalization will promote them 14008 // to 32-bit types and it is messy to recognize the operations after that. 14009 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) && 14010 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14011 SDValue Vec = N0.getOperand(0); 14012 SDValue Lane = N0.getOperand(1); 14013 EVT VT = N->getValueType(0); 14014 EVT EltVT = N0.getValueType(); 14015 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14016 14017 if (VT == MVT::i32 && 14018 (EltVT == MVT::i8 || EltVT == MVT::i16) && 14019 TLI.isTypeLegal(Vec.getValueType()) && 14020 isa<ConstantSDNode>(Lane)) { 14021 14022 unsigned Opc = 0; 14023 switch (N->getOpcode()) { 14024 default: llvm_unreachable("unexpected opcode"); 14025 case ISD::SIGN_EXTEND: 14026 Opc = ARMISD::VGETLANEs; 14027 break; 14028 case ISD::ZERO_EXTEND: 14029 case ISD::ANY_EXTEND: 14030 Opc = ARMISD::VGETLANEu; 14031 break; 14032 } 14033 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 14034 } 14035 } 14036 14037 if (ST->hasMVEIntegerOps()) 14038 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 14039 return NewLoad; 14040 14041 return SDValue(); 14042 } 14043 14044 static const APInt *isPowerOf2Constant(SDValue V) { 14045 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 14046 if (!C) 14047 return nullptr; 14048 const APInt *CV = &C->getAPIntValue(); 14049 return CV->isPowerOf2() ? CV : nullptr; 14050 } 14051 14052 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 14053 // If we have a CMOV, OR and AND combination such as: 14054 // if (x & CN) 14055 // y |= CM; 14056 // 14057 // And: 14058 // * CN is a single bit; 14059 // * All bits covered by CM are known zero in y 14060 // 14061 // Then we can convert this into a sequence of BFI instructions. This will 14062 // always be a win if CM is a single bit, will always be no worse than the 14063 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 14064 // three bits (due to the extra IT instruction). 14065 14066 SDValue Op0 = CMOV->getOperand(0); 14067 SDValue Op1 = CMOV->getOperand(1); 14068 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 14069 auto CC = CCNode->getAPIntValue().getLimitedValue(); 14070 SDValue CmpZ = CMOV->getOperand(4); 14071 14072 // The compare must be against zero. 14073 if (!isNullConstant(CmpZ->getOperand(1))) 14074 return SDValue(); 14075 14076 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 14077 SDValue And = CmpZ->getOperand(0); 14078 if (And->getOpcode() != ISD::AND) 14079 return SDValue(); 14080 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 14081 if (!AndC) 14082 return SDValue(); 14083 SDValue X = And->getOperand(0); 14084 14085 if (CC == ARMCC::EQ) { 14086 // We're performing an "equal to zero" compare. Swap the operands so we 14087 // canonicalize on a "not equal to zero" compare. 14088 std::swap(Op0, Op1); 14089 } else { 14090 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 14091 } 14092 14093 if (Op1->getOpcode() != ISD::OR) 14094 return SDValue(); 14095 14096 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 14097 if (!OrC) 14098 return SDValue(); 14099 SDValue Y = Op1->getOperand(0); 14100 14101 if (Op0 != Y) 14102 return SDValue(); 14103 14104 // Now, is it profitable to continue? 14105 APInt OrCI = OrC->getAPIntValue(); 14106 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 14107 if (OrCI.countPopulation() > Heuristic) 14108 return SDValue(); 14109 14110 // Lastly, can we determine that the bits defined by OrCI 14111 // are zero in Y? 14112 KnownBits Known = DAG.computeKnownBits(Y); 14113 if ((OrCI & Known.Zero) != OrCI) 14114 return SDValue(); 14115 14116 // OK, we can do the combine. 14117 SDValue V = Y; 14118 SDLoc dl(X); 14119 EVT VT = X.getValueType(); 14120 unsigned BitInX = AndC->logBase2(); 14121 14122 if (BitInX != 0) { 14123 // We must shift X first. 14124 X = DAG.getNode(ISD::SRL, dl, VT, X, 14125 DAG.getConstant(BitInX, dl, VT)); 14126 } 14127 14128 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 14129 BitInY < NumActiveBits; ++BitInY) { 14130 if (OrCI[BitInY] == 0) 14131 continue; 14132 APInt Mask(VT.getSizeInBits(), 0); 14133 Mask.setBit(BitInY); 14134 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 14135 // Confusingly, the operand is an *inverted* mask. 14136 DAG.getConstant(~Mask, dl, VT)); 14137 } 14138 14139 return V; 14140 } 14141 14142 // Given N, the value controlling the conditional branch, search for the loop 14143 // intrinsic, returning it, along with how the value is used. We need to handle 14144 // patterns such as the following: 14145 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 14146 // (brcond (setcc (loop.decrement), 0, eq), exit) 14147 // (brcond (setcc (loop.decrement), 0, ne), header) 14148 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 14149 bool &Negate) { 14150 switch (N->getOpcode()) { 14151 default: 14152 break; 14153 case ISD::XOR: { 14154 if (!isa<ConstantSDNode>(N.getOperand(1))) 14155 return SDValue(); 14156 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 14157 return SDValue(); 14158 Negate = !Negate; 14159 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 14160 } 14161 case ISD::SETCC: { 14162 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 14163 if (!Const) 14164 return SDValue(); 14165 if (Const->isNullValue()) 14166 Imm = 0; 14167 else if (Const->isOne()) 14168 Imm = 1; 14169 else 14170 return SDValue(); 14171 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 14172 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 14173 } 14174 case ISD::INTRINSIC_W_CHAIN: { 14175 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 14176 if (IntOp != Intrinsic::test_set_loop_iterations && 14177 IntOp != Intrinsic::loop_decrement_reg) 14178 return SDValue(); 14179 return N; 14180 } 14181 } 14182 return SDValue(); 14183 } 14184 14185 static SDValue PerformHWLoopCombine(SDNode *N, 14186 TargetLowering::DAGCombinerInfo &DCI, 14187 const ARMSubtarget *ST) { 14188 14189 // The hwloop intrinsics that we're interested are used for control-flow, 14190 // either for entering or exiting the loop: 14191 // - test.set.loop.iterations will test whether its operand is zero. If it 14192 // is zero, the proceeding branch should not enter the loop. 14193 // - loop.decrement.reg also tests whether its operand is zero. If it is 14194 // zero, the proceeding branch should not branch back to the beginning of 14195 // the loop. 14196 // So here, we need to check that how the brcond is using the result of each 14197 // of the intrinsics to ensure that we're branching to the right place at the 14198 // right time. 14199 14200 ISD::CondCode CC; 14201 SDValue Cond; 14202 int Imm = 1; 14203 bool Negate = false; 14204 SDValue Chain = N->getOperand(0); 14205 SDValue Dest; 14206 14207 if (N->getOpcode() == ISD::BRCOND) { 14208 CC = ISD::SETEQ; 14209 Cond = N->getOperand(1); 14210 Dest = N->getOperand(2); 14211 } else { 14212 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 14213 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14214 Cond = N->getOperand(2); 14215 Dest = N->getOperand(4); 14216 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 14217 if (!Const->isOne() && !Const->isNullValue()) 14218 return SDValue(); 14219 Imm = Const->getZExtValue(); 14220 } else 14221 return SDValue(); 14222 } 14223 14224 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 14225 if (!Int) 14226 return SDValue(); 14227 14228 if (Negate) 14229 CC = ISD::getSetCCInverse(CC, true); 14230 14231 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 14232 return (CC == ISD::SETEQ && Imm == 0) || 14233 (CC == ISD::SETNE && Imm == 1) || 14234 (CC == ISD::SETLT && Imm == 1) || 14235 (CC == ISD::SETULT && Imm == 1); 14236 }; 14237 14238 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 14239 return (CC == ISD::SETEQ && Imm == 1) || 14240 (CC == ISD::SETNE && Imm == 0) || 14241 (CC == ISD::SETGT && Imm == 0) || 14242 (CC == ISD::SETUGT && Imm == 0) || 14243 (CC == ISD::SETGE && Imm == 1) || 14244 (CC == ISD::SETUGE && Imm == 1); 14245 }; 14246 14247 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 14248 "unsupported condition"); 14249 14250 SDLoc dl(Int); 14251 SelectionDAG &DAG = DCI.DAG; 14252 SDValue Elements = Int.getOperand(2); 14253 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 14254 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 14255 && "expected single br user"); 14256 SDNode *Br = *N->use_begin(); 14257 SDValue OtherTarget = Br->getOperand(1); 14258 14259 // Update the unconditional branch to branch to the given Dest. 14260 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 14261 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 14262 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 14263 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 14264 }; 14265 14266 if (IntOp == Intrinsic::test_set_loop_iterations) { 14267 SDValue Res; 14268 // We expect this 'instruction' to branch when the counter is zero. 14269 if (IsTrueIfZero(CC, Imm)) { 14270 SDValue Ops[] = { Chain, Elements, Dest }; 14271 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 14272 } else { 14273 // The logic is the reverse of what we need for WLS, so find the other 14274 // basic block target: the target of the proceeding br. 14275 UpdateUncondBr(Br, Dest, DAG); 14276 14277 SDValue Ops[] = { Chain, Elements, OtherTarget }; 14278 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 14279 } 14280 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 14281 return Res; 14282 } else { 14283 SDValue Size = DAG.getTargetConstant( 14284 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 14285 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 14286 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 14287 DAG.getVTList(MVT::i32, MVT::Other), Args); 14288 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 14289 14290 // We expect this instruction to branch when the count is not zero. 14291 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 14292 14293 // Update the unconditional branch to target the loop preheader if we've 14294 // found the condition has been reversed. 14295 if (Target == OtherTarget) 14296 UpdateUncondBr(Br, Dest, DAG); 14297 14298 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14299 SDValue(LoopDec.getNode(), 1), Chain); 14300 14301 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 14302 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 14303 } 14304 return SDValue(); 14305 } 14306 14307 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 14308 SDValue 14309 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 14310 SDValue Cmp = N->getOperand(4); 14311 if (Cmp.getOpcode() != ARMISD::CMPZ) 14312 // Only looking at NE cases. 14313 return SDValue(); 14314 14315 EVT VT = N->getValueType(0); 14316 SDLoc dl(N); 14317 SDValue LHS = Cmp.getOperand(0); 14318 SDValue RHS = Cmp.getOperand(1); 14319 SDValue Chain = N->getOperand(0); 14320 SDValue BB = N->getOperand(1); 14321 SDValue ARMcc = N->getOperand(2); 14322 ARMCC::CondCodes CC = 14323 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 14324 14325 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 14326 // -> (brcond Chain BB CC CPSR Cmp) 14327 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 14328 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 14329 LHS->getOperand(0)->hasOneUse()) { 14330 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 14331 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 14332 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 14333 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 14334 if ((LHS00C && LHS00C->getZExtValue() == 0) && 14335 (LHS01C && LHS01C->getZExtValue() == 1) && 14336 (LHS1C && LHS1C->getZExtValue() == 1) && 14337 (RHSC && RHSC->getZExtValue() == 0)) { 14338 return DAG.getNode( 14339 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 14340 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 14341 } 14342 } 14343 14344 return SDValue(); 14345 } 14346 14347 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 14348 SDValue 14349 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 14350 SDValue Cmp = N->getOperand(4); 14351 if (Cmp.getOpcode() != ARMISD::CMPZ) 14352 // Only looking at EQ and NE cases. 14353 return SDValue(); 14354 14355 EVT VT = N->getValueType(0); 14356 SDLoc dl(N); 14357 SDValue LHS = Cmp.getOperand(0); 14358 SDValue RHS = Cmp.getOperand(1); 14359 SDValue FalseVal = N->getOperand(0); 14360 SDValue TrueVal = N->getOperand(1); 14361 SDValue ARMcc = N->getOperand(2); 14362 ARMCC::CondCodes CC = 14363 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 14364 14365 // BFI is only available on V6T2+. 14366 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 14367 SDValue R = PerformCMOVToBFICombine(N, DAG); 14368 if (R) 14369 return R; 14370 } 14371 14372 // Simplify 14373 // mov r1, r0 14374 // cmp r1, x 14375 // mov r0, y 14376 // moveq r0, x 14377 // to 14378 // cmp r0, x 14379 // movne r0, y 14380 // 14381 // mov r1, r0 14382 // cmp r1, x 14383 // mov r0, x 14384 // movne r0, y 14385 // to 14386 // cmp r0, x 14387 // movne r0, y 14388 /// FIXME: Turn this into a target neutral optimization? 14389 SDValue Res; 14390 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 14391 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 14392 N->getOperand(3), Cmp); 14393 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 14394 SDValue ARMcc; 14395 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 14396 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 14397 N->getOperand(3), NewCmp); 14398 } 14399 14400 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 14401 // -> (cmov F T CC CPSR Cmp) 14402 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 14403 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 14404 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 14405 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 14406 if ((LHS0C && LHS0C->getZExtValue() == 0) && 14407 (LHS1C && LHS1C->getZExtValue() == 1) && 14408 (RHSC && RHSC->getZExtValue() == 0)) { 14409 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 14410 LHS->getOperand(2), LHS->getOperand(3), 14411 LHS->getOperand(4)); 14412 } 14413 } 14414 14415 if (!VT.isInteger()) 14416 return SDValue(); 14417 14418 // Materialize a boolean comparison for integers so we can avoid branching. 14419 if (isNullConstant(FalseVal)) { 14420 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 14421 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 14422 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 14423 // right 5 bits will make that 32 be 1, otherwise it will be 0. 14424 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 14425 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 14426 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 14427 DAG.getConstant(5, dl, MVT::i32)); 14428 } else { 14429 // CMOV 0, 1, ==, (CMPZ x, y) -> 14430 // (ADDCARRY (SUB x, y), t:0, t:1) 14431 // where t = (SUBCARRY 0, (SUB x, y), 0) 14432 // 14433 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 14434 // x != y. In other words, a carry C == 1 when x == y, C == 0 14435 // otherwise. 14436 // The final ADDCARRY computes 14437 // x - y + (0 - (x - y)) + C == C 14438 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 14439 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 14440 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 14441 // ISD::SUBCARRY returns a borrow but we want the carry here 14442 // actually. 14443 SDValue Carry = 14444 DAG.getNode(ISD::SUB, dl, MVT::i32, 14445 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 14446 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 14447 } 14448 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 14449 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 14450 // This seems pointless but will allow us to combine it further below. 14451 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 14452 SDValue Sub = 14453 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 14454 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 14455 Sub.getValue(1), SDValue()); 14456 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 14457 N->getOperand(3), CPSRGlue.getValue(1)); 14458 FalseVal = Sub; 14459 } 14460 } else if (isNullConstant(TrueVal)) { 14461 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 14462 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 14463 // This seems pointless but will allow us to combine it further below 14464 // Note that we change == for != as this is the dual for the case above. 14465 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 14466 SDValue Sub = 14467 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 14468 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 14469 Sub.getValue(1), SDValue()); 14470 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 14471 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 14472 N->getOperand(3), CPSRGlue.getValue(1)); 14473 FalseVal = Sub; 14474 } 14475 } 14476 14477 // On Thumb1, the DAG above may be further combined if z is a power of 2 14478 // (z == 2 ^ K). 14479 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 14480 // t1 = (USUBO (SUB x, y), 1) 14481 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 14482 // Result = if K != 0 then (SHL t2:0, K) else t2:0 14483 // 14484 // This also handles the special case of comparing against zero; it's 14485 // essentially, the same pattern, except there's no SUBS: 14486 // CMOV x, z, !=, (CMPZ x, 0) -> 14487 // t1 = (USUBO x, 1) 14488 // t2 = (SUBCARRY x, t1:0, t1:1) 14489 // Result = if K != 0 then (SHL t2:0, K) else t2:0 14490 const APInt *TrueConst; 14491 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 14492 ((FalseVal.getOpcode() == ARMISD::SUBS && 14493 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 14494 (FalseVal == LHS && isNullConstant(RHS))) && 14495 (TrueConst = isPowerOf2Constant(TrueVal))) { 14496 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 14497 unsigned ShiftAmount = TrueConst->logBase2(); 14498 if (ShiftAmount) 14499 TrueVal = DAG.getConstant(1, dl, VT); 14500 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 14501 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 14502 14503 if (ShiftAmount) 14504 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 14505 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 14506 } 14507 14508 if (Res.getNode()) { 14509 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 14510 // Capture demanded bits information that would be otherwise lost. 14511 if (Known.Zero == 0xfffffffe) 14512 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 14513 DAG.getValueType(MVT::i1)); 14514 else if (Known.Zero == 0xffffff00) 14515 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 14516 DAG.getValueType(MVT::i8)); 14517 else if (Known.Zero == 0xffff0000) 14518 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 14519 DAG.getValueType(MVT::i16)); 14520 } 14521 14522 return Res; 14523 } 14524 14525 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 14526 DAGCombinerInfo &DCI) const { 14527 switch (N->getOpcode()) { 14528 default: break; 14529 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 14530 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 14531 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 14532 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 14533 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget); 14534 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 14535 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 14536 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 14537 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 14538 case ISD::BRCOND: 14539 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 14540 case ARMISD::ADDC: 14541 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 14542 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 14543 case ARMISD::BFI: return PerformBFICombine(N, DCI); 14544 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 14545 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 14546 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget); 14547 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 14548 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 14549 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 14550 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 14551 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 14552 case ISD::FP_TO_SINT: 14553 case ISD::FP_TO_UINT: 14554 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 14555 case ISD::FDIV: 14556 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 14557 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 14558 case ISD::SHL: 14559 case ISD::SRA: 14560 case ISD::SRL: 14561 return PerformShiftCombine(N, DCI, Subtarget); 14562 case ISD::SIGN_EXTEND: 14563 case ISD::ZERO_EXTEND: 14564 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 14565 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 14566 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 14567 case ISD::LOAD: return PerformLOADCombine(N, DCI); 14568 case ARMISD::VLD1DUP: 14569 case ARMISD::VLD2DUP: 14570 case ARMISD::VLD3DUP: 14571 case ARMISD::VLD4DUP: 14572 return PerformVLDCombine(N, DCI); 14573 case ARMISD::BUILD_VECTOR: 14574 return PerformARMBUILD_VECTORCombine(N, DCI); 14575 case ARMISD::PREDICATE_CAST: 14576 return PerformPREDICATE_CASTCombine(N, DCI); 14577 case ARMISD::VCMP: 14578 return PerformVCMPCombine(N, DCI, Subtarget); 14579 case ARMISD::SMULWB: { 14580 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14581 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 14582 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 14583 return SDValue(); 14584 break; 14585 } 14586 case ARMISD::SMULWT: { 14587 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14588 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 14589 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 14590 return SDValue(); 14591 break; 14592 } 14593 case ARMISD::SMLALBB: 14594 case ARMISD::QADD16b: 14595 case ARMISD::QSUB16b: { 14596 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14597 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 14598 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 14599 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 14600 return SDValue(); 14601 break; 14602 } 14603 case ARMISD::SMLALBT: { 14604 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 14605 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 14606 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 14607 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 14608 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 14609 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 14610 return SDValue(); 14611 break; 14612 } 14613 case ARMISD::SMLALTB: { 14614 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 14615 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 14616 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 14617 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 14618 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 14619 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 14620 return SDValue(); 14621 break; 14622 } 14623 case ARMISD::SMLALTT: { 14624 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14625 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 14626 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 14627 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 14628 return SDValue(); 14629 break; 14630 } 14631 case ARMISD::QADD8b: 14632 case ARMISD::QSUB8b: { 14633 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14634 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8); 14635 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 14636 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 14637 return SDValue(); 14638 break; 14639 } 14640 case ISD::INTRINSIC_VOID: 14641 case ISD::INTRINSIC_W_CHAIN: 14642 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14643 case Intrinsic::arm_neon_vld1: 14644 case Intrinsic::arm_neon_vld1x2: 14645 case Intrinsic::arm_neon_vld1x3: 14646 case Intrinsic::arm_neon_vld1x4: 14647 case Intrinsic::arm_neon_vld2: 14648 case Intrinsic::arm_neon_vld3: 14649 case Intrinsic::arm_neon_vld4: 14650 case Intrinsic::arm_neon_vld2lane: 14651 case Intrinsic::arm_neon_vld3lane: 14652 case Intrinsic::arm_neon_vld4lane: 14653 case Intrinsic::arm_neon_vld2dup: 14654 case Intrinsic::arm_neon_vld3dup: 14655 case Intrinsic::arm_neon_vld4dup: 14656 case Intrinsic::arm_neon_vst1: 14657 case Intrinsic::arm_neon_vst1x2: 14658 case Intrinsic::arm_neon_vst1x3: 14659 case Intrinsic::arm_neon_vst1x4: 14660 case Intrinsic::arm_neon_vst2: 14661 case Intrinsic::arm_neon_vst3: 14662 case Intrinsic::arm_neon_vst4: 14663 case Intrinsic::arm_neon_vst2lane: 14664 case Intrinsic::arm_neon_vst3lane: 14665 case Intrinsic::arm_neon_vst4lane: 14666 return PerformVLDCombine(N, DCI); 14667 default: break; 14668 } 14669 break; 14670 } 14671 return SDValue(); 14672 } 14673 14674 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 14675 EVT VT) const { 14676 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 14677 } 14678 14679 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 14680 unsigned Alignment, 14681 MachineMemOperand::Flags, 14682 bool *Fast) const { 14683 // Depends what it gets converted into if the type is weird. 14684 if (!VT.isSimple()) 14685 return false; 14686 14687 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 14688 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 14689 auto Ty = VT.getSimpleVT().SimpleTy; 14690 14691 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 14692 // Unaligned access can use (for example) LRDB, LRDH, LDR 14693 if (AllowsUnaligned) { 14694 if (Fast) 14695 *Fast = Subtarget->hasV7Ops(); 14696 return true; 14697 } 14698 } 14699 14700 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 14701 // For any little-endian targets with neon, we can support unaligned ld/st 14702 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 14703 // A big-endian target may also explicitly support unaligned accesses 14704 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 14705 if (Fast) 14706 *Fast = true; 14707 return true; 14708 } 14709 } 14710 14711 if (!Subtarget->hasMVEIntegerOps()) 14712 return false; 14713 14714 // These are for predicates 14715 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 14716 if (Fast) 14717 *Fast = true; 14718 return true; 14719 } 14720 14721 // These are for truncated stores/narrowing loads. They are fine so long as 14722 // the alignment is at least the size of the item being loaded 14723 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) && 14724 Alignment >= VT.getScalarSizeInBits() / 8) { 14725 if (Fast) 14726 *Fast = true; 14727 return true; 14728 } 14729 14730 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and 14731 // VSTRW.U32 all store the vector register in exactly the same format, and 14732 // differ only in the range of their immediate offset field and the required 14733 // alignment. So there is always a store that can be used, regardless of 14734 // actual type. 14735 // 14736 // For big endian, that is not the case. But can still emit a (VSTRB.U8; 14737 // VREV64.8) pair and get the same effect. This will likely be better than 14738 // aligning the vector through the stack. 14739 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 || 14740 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 || 14741 Ty == MVT::v2f64) { 14742 if (Fast) 14743 *Fast = true; 14744 return true; 14745 } 14746 14747 return false; 14748 } 14749 14750 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 14751 unsigned AlignCheck) { 14752 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 14753 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 14754 } 14755 14756 EVT ARMTargetLowering::getOptimalMemOpType( 14757 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14758 bool ZeroMemset, bool MemcpyStrSrc, 14759 const AttributeList &FuncAttributes) const { 14760 // See if we can use NEON instructions for this... 14761 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 14762 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14763 bool Fast; 14764 if (Size >= 16 && 14765 (memOpAlign(SrcAlign, DstAlign, 16) || 14766 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 14767 MachineMemOperand::MONone, &Fast) && 14768 Fast))) { 14769 return MVT::v2f64; 14770 } else if (Size >= 8 && 14771 (memOpAlign(SrcAlign, DstAlign, 8) || 14772 (allowsMisalignedMemoryAccesses( 14773 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 14774 Fast))) { 14775 return MVT::f64; 14776 } 14777 } 14778 14779 // Let the target-independent logic figure it out. 14780 return MVT::Other; 14781 } 14782 14783 // 64-bit integers are split into their high and low parts and held in two 14784 // different registers, so the trunc is free since the low register can just 14785 // be used. 14786 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 14787 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 14788 return false; 14789 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 14790 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 14791 return (SrcBits == 64 && DestBits == 32); 14792 } 14793 14794 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 14795 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 14796 !DstVT.isInteger()) 14797 return false; 14798 unsigned SrcBits = SrcVT.getSizeInBits(); 14799 unsigned DestBits = DstVT.getSizeInBits(); 14800 return (SrcBits == 64 && DestBits == 32); 14801 } 14802 14803 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14804 if (Val.getOpcode() != ISD::LOAD) 14805 return false; 14806 14807 EVT VT1 = Val.getValueType(); 14808 if (!VT1.isSimple() || !VT1.isInteger() || 14809 !VT2.isSimple() || !VT2.isInteger()) 14810 return false; 14811 14812 switch (VT1.getSimpleVT().SimpleTy) { 14813 default: break; 14814 case MVT::i1: 14815 case MVT::i8: 14816 case MVT::i16: 14817 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 14818 return true; 14819 } 14820 14821 return false; 14822 } 14823 14824 bool ARMTargetLowering::isFNegFree(EVT VT) const { 14825 if (!VT.isSimple()) 14826 return false; 14827 14828 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 14829 // negate values directly (fneg is free). So, we don't want to let the DAG 14830 // combiner rewrite fneg into xors and some other instructions. For f16 and 14831 // FullFP16 argument passing, some bitcast nodes may be introduced, 14832 // triggering this DAG combine rewrite, so we are avoiding that with this. 14833 switch (VT.getSimpleVT().SimpleTy) { 14834 default: break; 14835 case MVT::f16: 14836 return Subtarget->hasFullFP16(); 14837 } 14838 14839 return false; 14840 } 14841 14842 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 14843 /// of the vector elements. 14844 static bool areExtractExts(Value *Ext1, Value *Ext2) { 14845 auto areExtDoubled = [](Instruction *Ext) { 14846 return Ext->getType()->getScalarSizeInBits() == 14847 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 14848 }; 14849 14850 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 14851 !match(Ext2, m_ZExtOrSExt(m_Value())) || 14852 !areExtDoubled(cast<Instruction>(Ext1)) || 14853 !areExtDoubled(cast<Instruction>(Ext2))) 14854 return false; 14855 14856 return true; 14857 } 14858 14859 /// Check if sinking \p I's operands to I's basic block is profitable, because 14860 /// the operands can be folded into a target instruction, e.g. 14861 /// sext/zext can be folded into vsubl. 14862 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 14863 SmallVectorImpl<Use *> &Ops) const { 14864 if (!I->getType()->isVectorTy()) 14865 return false; 14866 14867 if (Subtarget->hasNEON()) { 14868 switch (I->getOpcode()) { 14869 case Instruction::Sub: 14870 case Instruction::Add: { 14871 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 14872 return false; 14873 Ops.push_back(&I->getOperandUse(0)); 14874 Ops.push_back(&I->getOperandUse(1)); 14875 return true; 14876 } 14877 default: 14878 return false; 14879 } 14880 } 14881 14882 if (!Subtarget->hasMVEIntegerOps()) 14883 return false; 14884 14885 auto IsSinker = [](Instruction *I, int Operand) { 14886 switch (I->getOpcode()) { 14887 case Instruction::Add: 14888 case Instruction::Mul: 14889 return true; 14890 case Instruction::Sub: 14891 case Instruction::Shl: 14892 case Instruction::LShr: 14893 case Instruction::AShr: 14894 return Operand == 1; 14895 default: 14896 return false; 14897 } 14898 }; 14899 14900 int Op = 0; 14901 if (!isa<ShuffleVectorInst>(I->getOperand(Op))) 14902 Op = 1; 14903 if (!IsSinker(I, Op)) 14904 return false; 14905 if (!match(I->getOperand(Op), 14906 m_ShuffleVector(m_InsertElement(m_Undef(), m_Value(), m_ZeroInt()), 14907 m_Undef(), m_Zero()))) { 14908 return false; 14909 } 14910 Instruction *Shuffle = cast<Instruction>(I->getOperand(Op)); 14911 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 14912 // and vector registers 14913 for (Use &U : Shuffle->uses()) { 14914 Instruction *Insn = cast<Instruction>(U.getUser()); 14915 if (!IsSinker(Insn, U.getOperandNo())) 14916 return false; 14917 } 14918 Ops.push_back(&Shuffle->getOperandUse(0)); 14919 Ops.push_back(&I->getOperandUse(Op)); 14920 return true; 14921 } 14922 14923 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 14924 EVT VT = ExtVal.getValueType(); 14925 14926 if (!isTypeLegal(VT)) 14927 return false; 14928 14929 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) { 14930 if (Ld->isExpandingLoad()) 14931 return false; 14932 } 14933 14934 // Don't create a loadext if we can fold the extension into a wide/long 14935 // instruction. 14936 // If there's more than one user instruction, the loadext is desirable no 14937 // matter what. There can be two uses by the same instruction. 14938 if (ExtVal->use_empty() || 14939 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 14940 return true; 14941 14942 SDNode *U = *ExtVal->use_begin(); 14943 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 14944 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 14945 return false; 14946 14947 return true; 14948 } 14949 14950 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 14951 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14952 return false; 14953 14954 if (!isTypeLegal(EVT::getEVT(Ty1))) 14955 return false; 14956 14957 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 14958 14959 // Assuming the caller doesn't have a zeroext or signext return parameter, 14960 // truncation all the way down to i1 is valid. 14961 return true; 14962 } 14963 14964 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 14965 const AddrMode &AM, Type *Ty, 14966 unsigned AS) const { 14967 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 14968 if (Subtarget->hasFPAO()) 14969 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 14970 return 0; 14971 } 14972 return -1; 14973 } 14974 14975 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster 14976 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be 14977 /// expanded to FMAs when this method returns true, otherwise fmuladd is 14978 /// expanded to fmul + fadd. 14979 /// 14980 /// ARM supports both fused and unfused multiply-add operations; we already 14981 /// lower a pair of fmul and fadd to the latter so it's not clear that there 14982 /// would be a gain or that the gain would be worthwhile enough to risk 14983 /// correctness bugs. 14984 /// 14985 /// For MVE, we set this to true as it helps simplify the need for some 14986 /// patterns (and we don't have the non-fused floating point instruction). 14987 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 14988 EVT VT) const { 14989 if (!Subtarget->hasMVEFloatOps()) 14990 return false; 14991 14992 if (!VT.isSimple()) 14993 return false; 14994 14995 switch (VT.getSimpleVT().SimpleTy) { 14996 case MVT::v4f32: 14997 case MVT::v8f16: 14998 return true; 14999 default: 15000 break; 15001 } 15002 15003 return false; 15004 } 15005 15006 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 15007 if (V < 0) 15008 return false; 15009 15010 unsigned Scale = 1; 15011 switch (VT.getSimpleVT().SimpleTy) { 15012 case MVT::i1: 15013 case MVT::i8: 15014 // Scale == 1; 15015 break; 15016 case MVT::i16: 15017 // Scale == 2; 15018 Scale = 2; 15019 break; 15020 default: 15021 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 15022 // Scale == 4; 15023 Scale = 4; 15024 break; 15025 } 15026 15027 if ((V & (Scale - 1)) != 0) 15028 return false; 15029 return isUInt<5>(V / Scale); 15030 } 15031 15032 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 15033 const ARMSubtarget *Subtarget) { 15034 if (!VT.isInteger() && !VT.isFloatingPoint()) 15035 return false; 15036 if (VT.isVector() && Subtarget->hasNEON()) 15037 return false; 15038 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 15039 !Subtarget->hasMVEFloatOps()) 15040 return false; 15041 15042 bool IsNeg = false; 15043 if (V < 0) { 15044 IsNeg = true; 15045 V = -V; 15046 } 15047 15048 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U); 15049 15050 // MVE: size * imm7 15051 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 15052 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 15053 case MVT::i32: 15054 case MVT::f32: 15055 return isShiftedUInt<7,2>(V); 15056 case MVT::i16: 15057 case MVT::f16: 15058 return isShiftedUInt<7,1>(V); 15059 case MVT::i8: 15060 return isUInt<7>(V); 15061 default: 15062 return false; 15063 } 15064 } 15065 15066 // half VLDR: 2 * imm8 15067 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 15068 return isShiftedUInt<8, 1>(V); 15069 // VLDR and LDRD: 4 * imm8 15070 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 15071 return isShiftedUInt<8, 2>(V); 15072 15073 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 15074 // + imm12 or - imm8 15075 if (IsNeg) 15076 return isUInt<8>(V); 15077 return isUInt<12>(V); 15078 } 15079 15080 return false; 15081 } 15082 15083 /// isLegalAddressImmediate - Return true if the integer value can be used 15084 /// as the offset of the target addressing mode for load / store of the 15085 /// given type. 15086 static bool isLegalAddressImmediate(int64_t V, EVT VT, 15087 const ARMSubtarget *Subtarget) { 15088 if (V == 0) 15089 return true; 15090 15091 if (!VT.isSimple()) 15092 return false; 15093 15094 if (Subtarget->isThumb1Only()) 15095 return isLegalT1AddressImmediate(V, VT); 15096 else if (Subtarget->isThumb2()) 15097 return isLegalT2AddressImmediate(V, VT, Subtarget); 15098 15099 // ARM mode. 15100 if (V < 0) 15101 V = - V; 15102 switch (VT.getSimpleVT().SimpleTy) { 15103 default: return false; 15104 case MVT::i1: 15105 case MVT::i8: 15106 case MVT::i32: 15107 // +- imm12 15108 return isUInt<12>(V); 15109 case MVT::i16: 15110 // +- imm8 15111 return isUInt<8>(V); 15112 case MVT::f32: 15113 case MVT::f64: 15114 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 15115 return false; 15116 return isShiftedUInt<8, 2>(V); 15117 } 15118 } 15119 15120 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 15121 EVT VT) const { 15122 int Scale = AM.Scale; 15123 if (Scale < 0) 15124 return false; 15125 15126 switch (VT.getSimpleVT().SimpleTy) { 15127 default: return false; 15128 case MVT::i1: 15129 case MVT::i8: 15130 case MVT::i16: 15131 case MVT::i32: 15132 if (Scale == 1) 15133 return true; 15134 // r + r << imm 15135 Scale = Scale & ~1; 15136 return Scale == 2 || Scale == 4 || Scale == 8; 15137 case MVT::i64: 15138 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 15139 // version in Thumb mode. 15140 // r + r 15141 if (Scale == 1) 15142 return true; 15143 // r * 2 (this can be lowered to r + r). 15144 if (!AM.HasBaseReg && Scale == 2) 15145 return true; 15146 return false; 15147 case MVT::isVoid: 15148 // Note, we allow "void" uses (basically, uses that aren't loads or 15149 // stores), because arm allows folding a scale into many arithmetic 15150 // operations. This should be made more precise and revisited later. 15151 15152 // Allow r << imm, but the imm has to be a multiple of two. 15153 if (Scale & 1) return false; 15154 return isPowerOf2_32(Scale); 15155 } 15156 } 15157 15158 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 15159 EVT VT) const { 15160 const int Scale = AM.Scale; 15161 15162 // Negative scales are not supported in Thumb1. 15163 if (Scale < 0) 15164 return false; 15165 15166 // Thumb1 addressing modes do not support register scaling excepting the 15167 // following cases: 15168 // 1. Scale == 1 means no scaling. 15169 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 15170 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 15171 } 15172 15173 /// isLegalAddressingMode - Return true if the addressing mode represented 15174 /// by AM is legal for this target, for a load/store of the specified type. 15175 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15176 const AddrMode &AM, Type *Ty, 15177 unsigned AS, Instruction *I) const { 15178 EVT VT = getValueType(DL, Ty, true); 15179 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 15180 return false; 15181 15182 // Can never fold addr of global into load/store. 15183 if (AM.BaseGV) 15184 return false; 15185 15186 switch (AM.Scale) { 15187 case 0: // no scale reg, must be "r+i" or "r", or "i". 15188 break; 15189 default: 15190 // ARM doesn't support any R+R*scale+imm addr modes. 15191 if (AM.BaseOffs) 15192 return false; 15193 15194 if (!VT.isSimple()) 15195 return false; 15196 15197 if (Subtarget->isThumb1Only()) 15198 return isLegalT1ScaledAddressingMode(AM, VT); 15199 15200 if (Subtarget->isThumb2()) 15201 return isLegalT2ScaledAddressingMode(AM, VT); 15202 15203 int Scale = AM.Scale; 15204 switch (VT.getSimpleVT().SimpleTy) { 15205 default: return false; 15206 case MVT::i1: 15207 case MVT::i8: 15208 case MVT::i32: 15209 if (Scale < 0) Scale = -Scale; 15210 if (Scale == 1) 15211 return true; 15212 // r + r << imm 15213 return isPowerOf2_32(Scale & ~1); 15214 case MVT::i16: 15215 case MVT::i64: 15216 // r +/- r 15217 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 15218 return true; 15219 // r * 2 (this can be lowered to r + r). 15220 if (!AM.HasBaseReg && Scale == 2) 15221 return true; 15222 return false; 15223 15224 case MVT::isVoid: 15225 // Note, we allow "void" uses (basically, uses that aren't loads or 15226 // stores), because arm allows folding a scale into many arithmetic 15227 // operations. This should be made more precise and revisited later. 15228 15229 // Allow r << imm, but the imm has to be a multiple of two. 15230 if (Scale & 1) return false; 15231 return isPowerOf2_32(Scale); 15232 } 15233 } 15234 return true; 15235 } 15236 15237 /// isLegalICmpImmediate - Return true if the specified immediate is legal 15238 /// icmp immediate, that is the target has icmp instructions which can compare 15239 /// a register against the immediate without having to materialize the 15240 /// immediate into a register. 15241 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15242 // Thumb2 and ARM modes can use cmn for negative immediates. 15243 if (!Subtarget->isThumb()) 15244 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 15245 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 15246 if (Subtarget->isThumb2()) 15247 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 15248 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 15249 // Thumb1 doesn't have cmn, and only 8-bit immediates. 15250 return Imm >= 0 && Imm <= 255; 15251 } 15252 15253 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 15254 /// *or sub* immediate, that is the target has add or sub instructions which can 15255 /// add a register with the immediate without having to materialize the 15256 /// immediate into a register. 15257 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15258 // Same encoding for add/sub, just flip the sign. 15259 int64_t AbsImm = std::abs(Imm); 15260 if (!Subtarget->isThumb()) 15261 return ARM_AM::getSOImmVal(AbsImm) != -1; 15262 if (Subtarget->isThumb2()) 15263 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 15264 // Thumb1 only has 8-bit unsigned immediate. 15265 return AbsImm >= 0 && AbsImm <= 255; 15266 } 15267 15268 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 15269 bool isSEXTLoad, SDValue &Base, 15270 SDValue &Offset, bool &isInc, 15271 SelectionDAG &DAG) { 15272 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 15273 return false; 15274 15275 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 15276 // AddressingMode 3 15277 Base = Ptr->getOperand(0); 15278 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 15279 int RHSC = (int)RHS->getZExtValue(); 15280 if (RHSC < 0 && RHSC > -256) { 15281 assert(Ptr->getOpcode() == ISD::ADD); 15282 isInc = false; 15283 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15284 return true; 15285 } 15286 } 15287 isInc = (Ptr->getOpcode() == ISD::ADD); 15288 Offset = Ptr->getOperand(1); 15289 return true; 15290 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 15291 // AddressingMode 2 15292 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 15293 int RHSC = (int)RHS->getZExtValue(); 15294 if (RHSC < 0 && RHSC > -0x1000) { 15295 assert(Ptr->getOpcode() == ISD::ADD); 15296 isInc = false; 15297 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15298 Base = Ptr->getOperand(0); 15299 return true; 15300 } 15301 } 15302 15303 if (Ptr->getOpcode() == ISD::ADD) { 15304 isInc = true; 15305 ARM_AM::ShiftOpc ShOpcVal= 15306 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 15307 if (ShOpcVal != ARM_AM::no_shift) { 15308 Base = Ptr->getOperand(1); 15309 Offset = Ptr->getOperand(0); 15310 } else { 15311 Base = Ptr->getOperand(0); 15312 Offset = Ptr->getOperand(1); 15313 } 15314 return true; 15315 } 15316 15317 isInc = (Ptr->getOpcode() == ISD::ADD); 15318 Base = Ptr->getOperand(0); 15319 Offset = Ptr->getOperand(1); 15320 return true; 15321 } 15322 15323 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 15324 return false; 15325 } 15326 15327 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 15328 bool isSEXTLoad, SDValue &Base, 15329 SDValue &Offset, bool &isInc, 15330 SelectionDAG &DAG) { 15331 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 15332 return false; 15333 15334 Base = Ptr->getOperand(0); 15335 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 15336 int RHSC = (int)RHS->getZExtValue(); 15337 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 15338 assert(Ptr->getOpcode() == ISD::ADD); 15339 isInc = false; 15340 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15341 return true; 15342 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 15343 isInc = Ptr->getOpcode() == ISD::ADD; 15344 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15345 return true; 15346 } 15347 } 15348 15349 return false; 15350 } 15351 15352 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align, 15353 bool isSEXTLoad, bool IsMasked, bool isLE, 15354 SDValue &Base, SDValue &Offset, 15355 bool &isInc, SelectionDAG &DAG) { 15356 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 15357 return false; 15358 if (!isa<ConstantSDNode>(Ptr->getOperand(1))) 15359 return false; 15360 15361 // We allow LE non-masked loads to change the type (for example use a vldrb.8 15362 // as opposed to a vldrw.32). This can allow extra addressing modes or 15363 // alignments for what is otherwise an equivalent instruction. 15364 bool CanChangeType = isLE && !IsMasked; 15365 15366 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1)); 15367 int RHSC = (int)RHS->getZExtValue(); 15368 15369 auto IsInRange = [&](int RHSC, int Limit, int Scale) { 15370 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) { 15371 assert(Ptr->getOpcode() == ISD::ADD); 15372 isInc = false; 15373 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15374 return true; 15375 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) { 15376 isInc = Ptr->getOpcode() == ISD::ADD; 15377 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15378 return true; 15379 } 15380 return false; 15381 }; 15382 15383 // Try to find a matching instruction based on s/zext, Alignment, Offset and 15384 // (in BE/masked) type. 15385 Base = Ptr->getOperand(0); 15386 if (VT == MVT::v4i16) { 15387 if (Align >= 2 && IsInRange(RHSC, 0x80, 2)) 15388 return true; 15389 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) { 15390 if (IsInRange(RHSC, 0x80, 1)) 15391 return true; 15392 } else if (Align >= 4 && 15393 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) && 15394 IsInRange(RHSC, 0x80, 4)) 15395 return true; 15396 else if (Align >= 2 && 15397 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) && 15398 IsInRange(RHSC, 0x80, 2)) 15399 return true; 15400 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1)) 15401 return true; 15402 return false; 15403 } 15404 15405 /// getPreIndexedAddressParts - returns true by value, base pointer and 15406 /// offset pointer and addressing mode by reference if the node's address 15407 /// can be legally represented as pre-indexed load / store address. 15408 bool 15409 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 15410 SDValue &Offset, 15411 ISD::MemIndexedMode &AM, 15412 SelectionDAG &DAG) const { 15413 if (Subtarget->isThumb1Only()) 15414 return false; 15415 15416 EVT VT; 15417 SDValue Ptr; 15418 unsigned Align; 15419 bool isSEXTLoad = false; 15420 bool IsMasked = false; 15421 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 15422 Ptr = LD->getBasePtr(); 15423 VT = LD->getMemoryVT(); 15424 Align = LD->getAlignment(); 15425 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 15426 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 15427 Ptr = ST->getBasePtr(); 15428 VT = ST->getMemoryVT(); 15429 Align = ST->getAlignment(); 15430 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 15431 Ptr = LD->getBasePtr(); 15432 VT = LD->getMemoryVT(); 15433 Align = LD->getAlignment(); 15434 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 15435 IsMasked = true; 15436 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 15437 Ptr = ST->getBasePtr(); 15438 VT = ST->getMemoryVT(); 15439 Align = ST->getAlignment(); 15440 IsMasked = true; 15441 } else 15442 return false; 15443 15444 bool isInc; 15445 bool isLegal = false; 15446 if (VT.isVector()) 15447 isLegal = Subtarget->hasMVEIntegerOps() && 15448 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad, 15449 IsMasked, Subtarget->isLittle(), Base, 15450 Offset, isInc, DAG); 15451 else { 15452 if (Subtarget->isThumb2()) 15453 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 15454 Offset, isInc, DAG); 15455 else 15456 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 15457 Offset, isInc, DAG); 15458 } 15459 if (!isLegal) 15460 return false; 15461 15462 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 15463 return true; 15464 } 15465 15466 /// getPostIndexedAddressParts - returns true by value, base pointer and 15467 /// offset pointer and addressing mode by reference if this node can be 15468 /// combined with a load / store to form a post-indexed load / store. 15469 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 15470 SDValue &Base, 15471 SDValue &Offset, 15472 ISD::MemIndexedMode &AM, 15473 SelectionDAG &DAG) const { 15474 EVT VT; 15475 SDValue Ptr; 15476 unsigned Align; 15477 bool isSEXTLoad = false, isNonExt; 15478 bool IsMasked = false; 15479 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 15480 VT = LD->getMemoryVT(); 15481 Ptr = LD->getBasePtr(); 15482 Align = LD->getAlignment(); 15483 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 15484 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 15485 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 15486 VT = ST->getMemoryVT(); 15487 Ptr = ST->getBasePtr(); 15488 Align = ST->getAlignment(); 15489 isNonExt = !ST->isTruncatingStore(); 15490 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 15491 VT = LD->getMemoryVT(); 15492 Ptr = LD->getBasePtr(); 15493 Align = LD->getAlignment(); 15494 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 15495 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 15496 IsMasked = true; 15497 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 15498 VT = ST->getMemoryVT(); 15499 Ptr = ST->getBasePtr(); 15500 Align = ST->getAlignment(); 15501 isNonExt = !ST->isTruncatingStore(); 15502 IsMasked = true; 15503 } else 15504 return false; 15505 15506 if (Subtarget->isThumb1Only()) { 15507 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 15508 // must be non-extending/truncating, i32, with an offset of 4. 15509 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 15510 if (Op->getOpcode() != ISD::ADD || !isNonExt) 15511 return false; 15512 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 15513 if (!RHS || RHS->getZExtValue() != 4) 15514 return false; 15515 15516 Offset = Op->getOperand(1); 15517 Base = Op->getOperand(0); 15518 AM = ISD::POST_INC; 15519 return true; 15520 } 15521 15522 bool isInc; 15523 bool isLegal = false; 15524 if (VT.isVector()) 15525 isLegal = Subtarget->hasMVEIntegerOps() && 15526 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad, IsMasked, 15527 Subtarget->isLittle(), Base, Offset, 15528 isInc, DAG); 15529 else { 15530 if (Subtarget->isThumb2()) 15531 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 15532 isInc, DAG); 15533 else 15534 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 15535 isInc, DAG); 15536 } 15537 if (!isLegal) 15538 return false; 15539 15540 if (Ptr != Base) { 15541 // Swap base ptr and offset to catch more post-index load / store when 15542 // it's legal. In Thumb2 mode, offset must be an immediate. 15543 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 15544 !Subtarget->isThumb2()) 15545 std::swap(Base, Offset); 15546 15547 // Post-indexed load / store update the base pointer. 15548 if (Ptr != Base) 15549 return false; 15550 } 15551 15552 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 15553 return true; 15554 } 15555 15556 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15557 KnownBits &Known, 15558 const APInt &DemandedElts, 15559 const SelectionDAG &DAG, 15560 unsigned Depth) const { 15561 unsigned BitWidth = Known.getBitWidth(); 15562 Known.resetAll(); 15563 switch (Op.getOpcode()) { 15564 default: break; 15565 case ARMISD::ADDC: 15566 case ARMISD::ADDE: 15567 case ARMISD::SUBC: 15568 case ARMISD::SUBE: 15569 // Special cases when we convert a carry to a boolean. 15570 if (Op.getResNo() == 0) { 15571 SDValue LHS = Op.getOperand(0); 15572 SDValue RHS = Op.getOperand(1); 15573 // (ADDE 0, 0, C) will give us a single bit. 15574 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 15575 isNullConstant(RHS)) { 15576 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 15577 return; 15578 } 15579 } 15580 break; 15581 case ARMISD::CMOV: { 15582 // Bits are known zero/one if known on the LHS and RHS. 15583 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 15584 if (Known.isUnknown()) 15585 return; 15586 15587 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 15588 Known.Zero &= KnownRHS.Zero; 15589 Known.One &= KnownRHS.One; 15590 return; 15591 } 15592 case ISD::INTRINSIC_W_CHAIN: { 15593 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 15594 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 15595 switch (IntID) { 15596 default: return; 15597 case Intrinsic::arm_ldaex: 15598 case Intrinsic::arm_ldrex: { 15599 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 15600 unsigned MemBits = VT.getScalarSizeInBits(); 15601 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 15602 return; 15603 } 15604 } 15605 } 15606 case ARMISD::BFI: { 15607 // Conservatively, we can recurse down the first operand 15608 // and just mask out all affected bits. 15609 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 15610 15611 // The operand to BFI is already a mask suitable for removing the bits it 15612 // sets. 15613 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 15614 const APInt &Mask = CI->getAPIntValue(); 15615 Known.Zero &= Mask; 15616 Known.One &= Mask; 15617 return; 15618 } 15619 case ARMISD::VGETLANEs: 15620 case ARMISD::VGETLANEu: { 15621 const SDValue &SrcSV = Op.getOperand(0); 15622 EVT VecVT = SrcSV.getValueType(); 15623 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 15624 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 15625 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 15626 assert(Pos->getAPIntValue().ult(NumSrcElts) && 15627 "VGETLANE index out of bounds"); 15628 unsigned Idx = Pos->getZExtValue(); 15629 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 15630 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 15631 15632 EVT VT = Op.getValueType(); 15633 const unsigned DstSz = VT.getScalarSizeInBits(); 15634 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 15635 (void)SrcSz; 15636 assert(SrcSz == Known.getBitWidth()); 15637 assert(DstSz > SrcSz); 15638 if (Op.getOpcode() == ARMISD::VGETLANEs) 15639 Known = Known.sext(DstSz); 15640 else { 15641 Known = Known.zext(DstSz, true /* extended bits are known zero */); 15642 } 15643 assert(DstSz == Known.getBitWidth()); 15644 break; 15645 } 15646 } 15647 } 15648 15649 bool 15650 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 15651 const APInt &DemandedAPInt, 15652 TargetLoweringOpt &TLO) const { 15653 // Delay optimization, so we don't have to deal with illegal types, or block 15654 // optimizations. 15655 if (!TLO.LegalOps) 15656 return false; 15657 15658 // Only optimize AND for now. 15659 if (Op.getOpcode() != ISD::AND) 15660 return false; 15661 15662 EVT VT = Op.getValueType(); 15663 15664 // Ignore vectors. 15665 if (VT.isVector()) 15666 return false; 15667 15668 assert(VT == MVT::i32 && "Unexpected integer type"); 15669 15670 // Make sure the RHS really is a constant. 15671 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 15672 if (!C) 15673 return false; 15674 15675 unsigned Mask = C->getZExtValue(); 15676 15677 unsigned Demanded = DemandedAPInt.getZExtValue(); 15678 unsigned ShrunkMask = Mask & Demanded; 15679 unsigned ExpandedMask = Mask | ~Demanded; 15680 15681 // If the mask is all zeros, let the target-independent code replace the 15682 // result with zero. 15683 if (ShrunkMask == 0) 15684 return false; 15685 15686 // If the mask is all ones, erase the AND. (Currently, the target-independent 15687 // code won't do this, so we have to do it explicitly to avoid an infinite 15688 // loop in obscure cases.) 15689 if (ExpandedMask == ~0U) 15690 return TLO.CombineTo(Op, Op.getOperand(0)); 15691 15692 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 15693 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 15694 }; 15695 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 15696 if (NewMask == Mask) 15697 return true; 15698 SDLoc DL(Op); 15699 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 15700 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 15701 return TLO.CombineTo(Op, NewOp); 15702 }; 15703 15704 // Prefer uxtb mask. 15705 if (IsLegalMask(0xFF)) 15706 return UseMask(0xFF); 15707 15708 // Prefer uxth mask. 15709 if (IsLegalMask(0xFFFF)) 15710 return UseMask(0xFFFF); 15711 15712 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 15713 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 15714 if (ShrunkMask < 256) 15715 return UseMask(ShrunkMask); 15716 15717 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 15718 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 15719 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 15720 return UseMask(ExpandedMask); 15721 15722 // Potential improvements: 15723 // 15724 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 15725 // We could try to prefer Thumb1 immediates which can be lowered to a 15726 // two-instruction sequence. 15727 // We could try to recognize more legal ARM/Thumb2 immediates here. 15728 15729 return false; 15730 } 15731 15732 15733 //===----------------------------------------------------------------------===// 15734 // ARM Inline Assembly Support 15735 //===----------------------------------------------------------------------===// 15736 15737 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 15738 // Looking for "rev" which is V6+. 15739 if (!Subtarget->hasV6Ops()) 15740 return false; 15741 15742 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 15743 std::string AsmStr = IA->getAsmString(); 15744 SmallVector<StringRef, 4> AsmPieces; 15745 SplitString(AsmStr, AsmPieces, ";\n"); 15746 15747 switch (AsmPieces.size()) { 15748 default: return false; 15749 case 1: 15750 AsmStr = AsmPieces[0]; 15751 AsmPieces.clear(); 15752 SplitString(AsmStr, AsmPieces, " \t,"); 15753 15754 // rev $0, $1 15755 if (AsmPieces.size() == 3 && 15756 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 15757 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 15758 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 15759 if (Ty && Ty->getBitWidth() == 32) 15760 return IntrinsicLowering::LowerToByteSwap(CI); 15761 } 15762 break; 15763 } 15764 15765 return false; 15766 } 15767 15768 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 15769 // At this point, we have to lower this constraint to something else, so we 15770 // lower it to an "r" or "w". However, by doing this we will force the result 15771 // to be in register, while the X constraint is much more permissive. 15772 // 15773 // Although we are correct (we are free to emit anything, without 15774 // constraints), we might break use cases that would expect us to be more 15775 // efficient and emit something else. 15776 if (!Subtarget->hasVFP2Base()) 15777 return "r"; 15778 if (ConstraintVT.isFloatingPoint()) 15779 return "w"; 15780 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 15781 (ConstraintVT.getSizeInBits() == 64 || 15782 ConstraintVT.getSizeInBits() == 128)) 15783 return "w"; 15784 15785 return "r"; 15786 } 15787 15788 /// getConstraintType - Given a constraint letter, return the type of 15789 /// constraint it is for this target. 15790 ARMTargetLowering::ConstraintType 15791 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 15792 unsigned S = Constraint.size(); 15793 if (S == 1) { 15794 switch (Constraint[0]) { 15795 default: break; 15796 case 'l': return C_RegisterClass; 15797 case 'w': return C_RegisterClass; 15798 case 'h': return C_RegisterClass; 15799 case 'x': return C_RegisterClass; 15800 case 't': return C_RegisterClass; 15801 case 'j': return C_Immediate; // Constant for movw. 15802 // An address with a single base register. Due to the way we 15803 // currently handle addresses it is the same as an 'r' memory constraint. 15804 case 'Q': return C_Memory; 15805 } 15806 } else if (S == 2) { 15807 switch (Constraint[0]) { 15808 default: break; 15809 case 'T': return C_RegisterClass; 15810 // All 'U+' constraints are addresses. 15811 case 'U': return C_Memory; 15812 } 15813 } 15814 return TargetLowering::getConstraintType(Constraint); 15815 } 15816 15817 /// Examine constraint type and operand type and determine a weight value. 15818 /// This object must already have been set up with the operand type 15819 /// and the current alternative constraint selected. 15820 TargetLowering::ConstraintWeight 15821 ARMTargetLowering::getSingleConstraintMatchWeight( 15822 AsmOperandInfo &info, const char *constraint) const { 15823 ConstraintWeight weight = CW_Invalid; 15824 Value *CallOperandVal = info.CallOperandVal; 15825 // If we don't have a value, we can't do a match, 15826 // but allow it at the lowest weight. 15827 if (!CallOperandVal) 15828 return CW_Default; 15829 Type *type = CallOperandVal->getType(); 15830 // Look at the constraint type. 15831 switch (*constraint) { 15832 default: 15833 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15834 break; 15835 case 'l': 15836 if (type->isIntegerTy()) { 15837 if (Subtarget->isThumb()) 15838 weight = CW_SpecificReg; 15839 else 15840 weight = CW_Register; 15841 } 15842 break; 15843 case 'w': 15844 if (type->isFloatingPointTy()) 15845 weight = CW_Register; 15846 break; 15847 } 15848 return weight; 15849 } 15850 15851 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 15852 15853 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 15854 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 15855 switch (Constraint.size()) { 15856 case 1: 15857 // GCC ARM Constraint Letters 15858 switch (Constraint[0]) { 15859 case 'l': // Low regs or general regs. 15860 if (Subtarget->isThumb()) 15861 return RCPair(0U, &ARM::tGPRRegClass); 15862 return RCPair(0U, &ARM::GPRRegClass); 15863 case 'h': // High regs or no regs. 15864 if (Subtarget->isThumb()) 15865 return RCPair(0U, &ARM::hGPRRegClass); 15866 break; 15867 case 'r': 15868 if (Subtarget->isThumb1Only()) 15869 return RCPair(0U, &ARM::tGPRRegClass); 15870 return RCPair(0U, &ARM::GPRRegClass); 15871 case 'w': 15872 if (VT == MVT::Other) 15873 break; 15874 if (VT == MVT::f32) 15875 return RCPair(0U, &ARM::SPRRegClass); 15876 if (VT.getSizeInBits() == 64) 15877 return RCPair(0U, &ARM::DPRRegClass); 15878 if (VT.getSizeInBits() == 128) 15879 return RCPair(0U, &ARM::QPRRegClass); 15880 break; 15881 case 'x': 15882 if (VT == MVT::Other) 15883 break; 15884 if (VT == MVT::f32) 15885 return RCPair(0U, &ARM::SPR_8RegClass); 15886 if (VT.getSizeInBits() == 64) 15887 return RCPair(0U, &ARM::DPR_8RegClass); 15888 if (VT.getSizeInBits() == 128) 15889 return RCPair(0U, &ARM::QPR_8RegClass); 15890 break; 15891 case 't': 15892 if (VT == MVT::Other) 15893 break; 15894 if (VT == MVT::f32 || VT == MVT::i32) 15895 return RCPair(0U, &ARM::SPRRegClass); 15896 if (VT.getSizeInBits() == 64) 15897 return RCPair(0U, &ARM::DPR_VFP2RegClass); 15898 if (VT.getSizeInBits() == 128) 15899 return RCPair(0U, &ARM::QPR_VFP2RegClass); 15900 break; 15901 } 15902 break; 15903 15904 case 2: 15905 if (Constraint[0] == 'T') { 15906 switch (Constraint[1]) { 15907 default: 15908 break; 15909 case 'e': 15910 return RCPair(0U, &ARM::tGPREvenRegClass); 15911 case 'o': 15912 return RCPair(0U, &ARM::tGPROddRegClass); 15913 } 15914 } 15915 break; 15916 15917 default: 15918 break; 15919 } 15920 15921 if (StringRef("{cc}").equals_lower(Constraint)) 15922 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 15923 15924 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15925 } 15926 15927 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15928 /// vector. If it is invalid, don't add anything to Ops. 15929 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15930 std::string &Constraint, 15931 std::vector<SDValue>&Ops, 15932 SelectionDAG &DAG) const { 15933 SDValue Result; 15934 15935 // Currently only support length 1 constraints. 15936 if (Constraint.length() != 1) return; 15937 15938 char ConstraintLetter = Constraint[0]; 15939 switch (ConstraintLetter) { 15940 default: break; 15941 case 'j': 15942 case 'I': case 'J': case 'K': case 'L': 15943 case 'M': case 'N': case 'O': 15944 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 15945 if (!C) 15946 return; 15947 15948 int64_t CVal64 = C->getSExtValue(); 15949 int CVal = (int) CVal64; 15950 // None of these constraints allow values larger than 32 bits. Check 15951 // that the value fits in an int. 15952 if (CVal != CVal64) 15953 return; 15954 15955 switch (ConstraintLetter) { 15956 case 'j': 15957 // Constant suitable for movw, must be between 0 and 15958 // 65535. 15959 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps())) 15960 if (CVal >= 0 && CVal <= 65535) 15961 break; 15962 return; 15963 case 'I': 15964 if (Subtarget->isThumb1Only()) { 15965 // This must be a constant between 0 and 255, for ADD 15966 // immediates. 15967 if (CVal >= 0 && CVal <= 255) 15968 break; 15969 } else if (Subtarget->isThumb2()) { 15970 // A constant that can be used as an immediate value in a 15971 // data-processing instruction. 15972 if (ARM_AM::getT2SOImmVal(CVal) != -1) 15973 break; 15974 } else { 15975 // A constant that can be used as an immediate value in a 15976 // data-processing instruction. 15977 if (ARM_AM::getSOImmVal(CVal) != -1) 15978 break; 15979 } 15980 return; 15981 15982 case 'J': 15983 if (Subtarget->isThumb1Only()) { 15984 // This must be a constant between -255 and -1, for negated ADD 15985 // immediates. This can be used in GCC with an "n" modifier that 15986 // prints the negated value, for use with SUB instructions. It is 15987 // not useful otherwise but is implemented for compatibility. 15988 if (CVal >= -255 && CVal <= -1) 15989 break; 15990 } else { 15991 // This must be a constant between -4095 and 4095. It is not clear 15992 // what this constraint is intended for. Implemented for 15993 // compatibility with GCC. 15994 if (CVal >= -4095 && CVal <= 4095) 15995 break; 15996 } 15997 return; 15998 15999 case 'K': 16000 if (Subtarget->isThumb1Only()) { 16001 // A 32-bit value where only one byte has a nonzero value. Exclude 16002 // zero to match GCC. This constraint is used by GCC internally for 16003 // constants that can be loaded with a move/shift combination. 16004 // It is not useful otherwise but is implemented for compatibility. 16005 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 16006 break; 16007 } else if (Subtarget->isThumb2()) { 16008 // A constant whose bitwise inverse can be used as an immediate 16009 // value in a data-processing instruction. This can be used in GCC 16010 // with a "B" modifier that prints the inverted value, for use with 16011 // BIC and MVN instructions. It is not useful otherwise but is 16012 // implemented for compatibility. 16013 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 16014 break; 16015 } else { 16016 // A constant whose bitwise inverse can be used as an immediate 16017 // value in a data-processing instruction. This can be used in GCC 16018 // with a "B" modifier that prints the inverted value, for use with 16019 // BIC and MVN instructions. It is not useful otherwise but is 16020 // implemented for compatibility. 16021 if (ARM_AM::getSOImmVal(~CVal) != -1) 16022 break; 16023 } 16024 return; 16025 16026 case 'L': 16027 if (Subtarget->isThumb1Only()) { 16028 // This must be a constant between -7 and 7, 16029 // for 3-operand ADD/SUB immediate instructions. 16030 if (CVal >= -7 && CVal < 7) 16031 break; 16032 } else if (Subtarget->isThumb2()) { 16033 // A constant whose negation can be used as an immediate value in a 16034 // data-processing instruction. This can be used in GCC with an "n" 16035 // modifier that prints the negated value, for use with SUB 16036 // instructions. It is not useful otherwise but is implemented for 16037 // compatibility. 16038 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 16039 break; 16040 } else { 16041 // A constant whose negation can be used as an immediate value in a 16042 // data-processing instruction. This can be used in GCC with an "n" 16043 // modifier that prints the negated value, for use with SUB 16044 // instructions. It is not useful otherwise but is implemented for 16045 // compatibility. 16046 if (ARM_AM::getSOImmVal(-CVal) != -1) 16047 break; 16048 } 16049 return; 16050 16051 case 'M': 16052 if (Subtarget->isThumb1Only()) { 16053 // This must be a multiple of 4 between 0 and 1020, for 16054 // ADD sp + immediate. 16055 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 16056 break; 16057 } else { 16058 // A power of two or a constant between 0 and 32. This is used in 16059 // GCC for the shift amount on shifted register operands, but it is 16060 // useful in general for any shift amounts. 16061 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 16062 break; 16063 } 16064 return; 16065 16066 case 'N': 16067 if (Subtarget->isThumb1Only()) { 16068 // This must be a constant between 0 and 31, for shift amounts. 16069 if (CVal >= 0 && CVal <= 31) 16070 break; 16071 } 16072 return; 16073 16074 case 'O': 16075 if (Subtarget->isThumb1Only()) { 16076 // This must be a multiple of 4 between -508 and 508, for 16077 // ADD/SUB sp = sp + immediate. 16078 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 16079 break; 16080 } 16081 return; 16082 } 16083 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 16084 break; 16085 } 16086 16087 if (Result.getNode()) { 16088 Ops.push_back(Result); 16089 return; 16090 } 16091 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 16092 } 16093 16094 static RTLIB::Libcall getDivRemLibcall( 16095 const SDNode *N, MVT::SimpleValueType SVT) { 16096 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 16097 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 16098 "Unhandled Opcode in getDivRemLibcall"); 16099 bool isSigned = N->getOpcode() == ISD::SDIVREM || 16100 N->getOpcode() == ISD::SREM; 16101 RTLIB::Libcall LC; 16102 switch (SVT) { 16103 default: llvm_unreachable("Unexpected request for libcall!"); 16104 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 16105 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 16106 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 16107 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 16108 } 16109 return LC; 16110 } 16111 16112 static TargetLowering::ArgListTy getDivRemArgList( 16113 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 16114 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 16115 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 16116 "Unhandled Opcode in getDivRemArgList"); 16117 bool isSigned = N->getOpcode() == ISD::SDIVREM || 16118 N->getOpcode() == ISD::SREM; 16119 TargetLowering::ArgListTy Args; 16120 TargetLowering::ArgListEntry Entry; 16121 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 16122 EVT ArgVT = N->getOperand(i).getValueType(); 16123 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 16124 Entry.Node = N->getOperand(i); 16125 Entry.Ty = ArgTy; 16126 Entry.IsSExt = isSigned; 16127 Entry.IsZExt = !isSigned; 16128 Args.push_back(Entry); 16129 } 16130 if (Subtarget->isTargetWindows() && Args.size() >= 2) 16131 std::swap(Args[0], Args[1]); 16132 return Args; 16133 } 16134 16135 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 16136 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 16137 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 16138 Subtarget->isTargetWindows()) && 16139 "Register-based DivRem lowering only"); 16140 unsigned Opcode = Op->getOpcode(); 16141 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 16142 "Invalid opcode for Div/Rem lowering"); 16143 bool isSigned = (Opcode == ISD::SDIVREM); 16144 EVT VT = Op->getValueType(0); 16145 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 16146 SDLoc dl(Op); 16147 16148 // If the target has hardware divide, use divide + multiply + subtract: 16149 // div = a / b 16150 // rem = a - b * div 16151 // return {div, rem} 16152 // This should be lowered into UDIV/SDIV + MLS later on. 16153 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 16154 : Subtarget->hasDivideInARMMode(); 16155 if (hasDivide && Op->getValueType(0).isSimple() && 16156 Op->getSimpleValueType(0) == MVT::i32) { 16157 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 16158 const SDValue Dividend = Op->getOperand(0); 16159 const SDValue Divisor = Op->getOperand(1); 16160 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 16161 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 16162 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 16163 16164 SDValue Values[2] = {Div, Rem}; 16165 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 16166 } 16167 16168 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 16169 VT.getSimpleVT().SimpleTy); 16170 SDValue InChain = DAG.getEntryNode(); 16171 16172 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 16173 DAG.getContext(), 16174 Subtarget); 16175 16176 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 16177 getPointerTy(DAG.getDataLayout())); 16178 16179 Type *RetTy = StructType::get(Ty, Ty); 16180 16181 if (Subtarget->isTargetWindows()) 16182 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 16183 16184 TargetLowering::CallLoweringInfo CLI(DAG); 16185 CLI.setDebugLoc(dl).setChain(InChain) 16186 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 16187 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 16188 16189 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 16190 return CallInfo.first; 16191 } 16192 16193 // Lowers REM using divmod helpers 16194 // see RTABI section 4.2/4.3 16195 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 16196 // Build return types (div and rem) 16197 std::vector<Type*> RetTyParams; 16198 Type *RetTyElement; 16199 16200 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 16201 default: llvm_unreachable("Unexpected request for libcall!"); 16202 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 16203 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 16204 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 16205 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 16206 } 16207 16208 RetTyParams.push_back(RetTyElement); 16209 RetTyParams.push_back(RetTyElement); 16210 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 16211 Type *RetTy = StructType::get(*DAG.getContext(), ret); 16212 16213 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 16214 SimpleTy); 16215 SDValue InChain = DAG.getEntryNode(); 16216 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 16217 Subtarget); 16218 bool isSigned = N->getOpcode() == ISD::SREM; 16219 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 16220 getPointerTy(DAG.getDataLayout())); 16221 16222 if (Subtarget->isTargetWindows()) 16223 InChain = WinDBZCheckDenominator(DAG, N, InChain); 16224 16225 // Lower call 16226 CallLoweringInfo CLI(DAG); 16227 CLI.setChain(InChain) 16228 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 16229 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 16230 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 16231 16232 // Return second (rem) result operand (first contains div) 16233 SDNode *ResNode = CallResult.first.getNode(); 16234 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 16235 return ResNode->getOperand(1); 16236 } 16237 16238 SDValue 16239 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 16240 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 16241 SDLoc DL(Op); 16242 16243 // Get the inputs. 16244 SDValue Chain = Op.getOperand(0); 16245 SDValue Size = Op.getOperand(1); 16246 16247 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 16248 "no-stack-arg-probe")) { 16249 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 16250 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 16251 Chain = SP.getValue(1); 16252 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 16253 if (Align) 16254 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 16255 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 16256 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 16257 SDValue Ops[2] = { SP, Chain }; 16258 return DAG.getMergeValues(Ops, DL); 16259 } 16260 16261 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 16262 DAG.getConstant(2, DL, MVT::i32)); 16263 16264 SDValue Flag; 16265 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 16266 Flag = Chain.getValue(1); 16267 16268 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 16269 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 16270 16271 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 16272 Chain = NewSP.getValue(1); 16273 16274 SDValue Ops[2] = { NewSP, Chain }; 16275 return DAG.getMergeValues(Ops, DL); 16276 } 16277 16278 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 16279 SDValue SrcVal = Op.getOperand(0); 16280 const unsigned DstSz = Op.getValueType().getSizeInBits(); 16281 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 16282 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 16283 "Unexpected type for custom-lowering FP_EXTEND"); 16284 16285 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 16286 "With both FP DP and 16, any FP conversion is legal!"); 16287 16288 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 16289 "With FP16, 16 to 32 conversion is legal!"); 16290 16291 // Either we are converting from 16 -> 64, without FP16 and/or 16292 // FP.double-precision or without Armv8-fp. So we must do it in two 16293 // steps. 16294 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 16295 // without FP16. So we must do a function call. 16296 SDLoc Loc(Op); 16297 RTLIB::Libcall LC; 16298 MakeLibCallOptions CallOptions; 16299 if (SrcSz == 16) { 16300 // Instruction from 16 -> 32 16301 if (Subtarget->hasFP16()) 16302 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal); 16303 // Lib call from 16 -> 32 16304 else { 16305 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32); 16306 assert(LC != RTLIB::UNKNOWN_LIBCALL && 16307 "Unexpected type for custom-lowering FP_EXTEND"); 16308 SrcVal = 16309 makeLibCall(DAG, LC, MVT::f32, SrcVal, CallOptions, Loc).first; 16310 } 16311 } 16312 16313 if (DstSz != 64) 16314 return SrcVal; 16315 // For sure now SrcVal is 32 bits 16316 if (Subtarget->hasFP64()) // Instruction from 32 -> 64 16317 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal); 16318 16319 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64); 16320 assert(LC != RTLIB::UNKNOWN_LIBCALL && 16321 "Unexpected type for custom-lowering FP_EXTEND"); 16322 return makeLibCall(DAG, LC, MVT::f64, SrcVal, CallOptions, Loc).first; 16323 } 16324 16325 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 16326 SDValue SrcVal = Op.getOperand(0); 16327 EVT SrcVT = SrcVal.getValueType(); 16328 EVT DstVT = Op.getValueType(); 16329 const unsigned DstSz = Op.getValueType().getSizeInBits(); 16330 const unsigned SrcSz = SrcVT.getSizeInBits(); 16331 (void)DstSz; 16332 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 16333 "Unexpected type for custom-lowering FP_ROUND"); 16334 16335 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 16336 "With both FP DP and 16, any FP conversion is legal!"); 16337 16338 SDLoc Loc(Op); 16339 16340 // Instruction from 32 -> 16 if hasFP16 is valid 16341 if (SrcSz == 32 && Subtarget->hasFP16()) 16342 return Op; 16343 16344 // Lib call from 32 -> 16 / 64 -> [32, 16] 16345 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 16346 assert(LC != RTLIB::UNKNOWN_LIBCALL && 16347 "Unexpected type for custom-lowering FP_ROUND"); 16348 MakeLibCallOptions CallOptions; 16349 return makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, Loc).first; 16350 } 16351 16352 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 16353 SelectionDAG &DAG) const { 16354 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 16355 MVT HalfT = MVT::i32; 16356 SDLoc dl(N); 16357 SDValue Hi, Lo, Tmp; 16358 16359 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 16360 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 16361 return ; 16362 16363 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 16364 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 16365 16366 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 16367 DAG.getConstant(0, dl, HalfT)); 16368 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 16369 DAG.getConstant(1, dl, HalfT)); 16370 16371 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 16372 DAG.getConstant(OpTypeBits - 1, dl, 16373 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 16374 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 16375 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 16376 SDValue(Lo.getNode(), 1)); 16377 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 16378 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 16379 16380 Results.push_back(Lo); 16381 Results.push_back(Hi); 16382 } 16383 16384 bool 16385 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 16386 // The ARM target isn't yet aware of offsets. 16387 return false; 16388 } 16389 16390 bool ARM::isBitFieldInvertedMask(unsigned v) { 16391 if (v == 0xffffffff) 16392 return false; 16393 16394 // there can be 1's on either or both "outsides", all the "inside" 16395 // bits must be 0's 16396 return isShiftedMask_32(~v); 16397 } 16398 16399 /// isFPImmLegal - Returns true if the target can instruction select the 16400 /// specified FP immediate natively. If false, the legalizer will 16401 /// materialize the FP immediate as a load from a constant pool. 16402 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16403 bool ForCodeSize) const { 16404 if (!Subtarget->hasVFP3Base()) 16405 return false; 16406 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 16407 return ARM_AM::getFP16Imm(Imm) != -1; 16408 if (VT == MVT::f32) 16409 return ARM_AM::getFP32Imm(Imm) != -1; 16410 if (VT == MVT::f64 && Subtarget->hasFP64()) 16411 return ARM_AM::getFP64Imm(Imm) != -1; 16412 return false; 16413 } 16414 16415 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 16416 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 16417 /// specified in the intrinsic calls. 16418 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 16419 const CallInst &I, 16420 MachineFunction &MF, 16421 unsigned Intrinsic) const { 16422 switch (Intrinsic) { 16423 case Intrinsic::arm_neon_vld1: 16424 case Intrinsic::arm_neon_vld2: 16425 case Intrinsic::arm_neon_vld3: 16426 case Intrinsic::arm_neon_vld4: 16427 case Intrinsic::arm_neon_vld2lane: 16428 case Intrinsic::arm_neon_vld3lane: 16429 case Intrinsic::arm_neon_vld4lane: 16430 case Intrinsic::arm_neon_vld2dup: 16431 case Intrinsic::arm_neon_vld3dup: 16432 case Intrinsic::arm_neon_vld4dup: { 16433 Info.opc = ISD::INTRINSIC_W_CHAIN; 16434 // Conservatively set memVT to the entire set of vectors loaded. 16435 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16436 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 16437 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 16438 Info.ptrVal = I.getArgOperand(0); 16439 Info.offset = 0; 16440 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 16441 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 16442 // volatile loads with NEON intrinsics not supported 16443 Info.flags = MachineMemOperand::MOLoad; 16444 return true; 16445 } 16446 case Intrinsic::arm_neon_vld1x2: 16447 case Intrinsic::arm_neon_vld1x3: 16448 case Intrinsic::arm_neon_vld1x4: { 16449 Info.opc = ISD::INTRINSIC_W_CHAIN; 16450 // Conservatively set memVT to the entire set of vectors loaded. 16451 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16452 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 16453 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 16454 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 16455 Info.offset = 0; 16456 Info.align.reset(); 16457 // volatile loads with NEON intrinsics not supported 16458 Info.flags = MachineMemOperand::MOLoad; 16459 return true; 16460 } 16461 case Intrinsic::arm_neon_vst1: 16462 case Intrinsic::arm_neon_vst2: 16463 case Intrinsic::arm_neon_vst3: 16464 case Intrinsic::arm_neon_vst4: 16465 case Intrinsic::arm_neon_vst2lane: 16466 case Intrinsic::arm_neon_vst3lane: 16467 case Intrinsic::arm_neon_vst4lane: { 16468 Info.opc = ISD::INTRINSIC_VOID; 16469 // Conservatively set memVT to the entire set of vectors stored. 16470 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16471 unsigned NumElts = 0; 16472 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 16473 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 16474 if (!ArgTy->isVectorTy()) 16475 break; 16476 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 16477 } 16478 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 16479 Info.ptrVal = I.getArgOperand(0); 16480 Info.offset = 0; 16481 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 16482 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 16483 // volatile stores with NEON intrinsics not supported 16484 Info.flags = MachineMemOperand::MOStore; 16485 return true; 16486 } 16487 case Intrinsic::arm_neon_vst1x2: 16488 case Intrinsic::arm_neon_vst1x3: 16489 case Intrinsic::arm_neon_vst1x4: { 16490 Info.opc = ISD::INTRINSIC_VOID; 16491 // Conservatively set memVT to the entire set of vectors stored. 16492 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16493 unsigned NumElts = 0; 16494 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 16495 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 16496 if (!ArgTy->isVectorTy()) 16497 break; 16498 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 16499 } 16500 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 16501 Info.ptrVal = I.getArgOperand(0); 16502 Info.offset = 0; 16503 Info.align.reset(); 16504 // volatile stores with NEON intrinsics not supported 16505 Info.flags = MachineMemOperand::MOStore; 16506 return true; 16507 } 16508 case Intrinsic::arm_ldaex: 16509 case Intrinsic::arm_ldrex: { 16510 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16511 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 16512 Info.opc = ISD::INTRINSIC_W_CHAIN; 16513 Info.memVT = MVT::getVT(PtrTy->getElementType()); 16514 Info.ptrVal = I.getArgOperand(0); 16515 Info.offset = 0; 16516 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 16517 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 16518 return true; 16519 } 16520 case Intrinsic::arm_stlex: 16521 case Intrinsic::arm_strex: { 16522 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16523 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 16524 Info.opc = ISD::INTRINSIC_W_CHAIN; 16525 Info.memVT = MVT::getVT(PtrTy->getElementType()); 16526 Info.ptrVal = I.getArgOperand(1); 16527 Info.offset = 0; 16528 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 16529 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16530 return true; 16531 } 16532 case Intrinsic::arm_stlexd: 16533 case Intrinsic::arm_strexd: 16534 Info.opc = ISD::INTRINSIC_W_CHAIN; 16535 Info.memVT = MVT::i64; 16536 Info.ptrVal = I.getArgOperand(2); 16537 Info.offset = 0; 16538 Info.align = Align(8); 16539 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16540 return true; 16541 16542 case Intrinsic::arm_ldaexd: 16543 case Intrinsic::arm_ldrexd: 16544 Info.opc = ISD::INTRINSIC_W_CHAIN; 16545 Info.memVT = MVT::i64; 16546 Info.ptrVal = I.getArgOperand(0); 16547 Info.offset = 0; 16548 Info.align = Align(8); 16549 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 16550 return true; 16551 16552 default: 16553 break; 16554 } 16555 16556 return false; 16557 } 16558 16559 /// Returns true if it is beneficial to convert a load of a constant 16560 /// to just the constant itself. 16561 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16562 Type *Ty) const { 16563 assert(Ty->isIntegerTy()); 16564 16565 unsigned Bits = Ty->getPrimitiveSizeInBits(); 16566 if (Bits == 0 || Bits > 32) 16567 return false; 16568 return true; 16569 } 16570 16571 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 16572 unsigned Index) const { 16573 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 16574 return false; 16575 16576 return (Index == 0 || Index == ResVT.getVectorNumElements()); 16577 } 16578 16579 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 16580 ARM_MB::MemBOpt Domain) const { 16581 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16582 16583 // First, if the target has no DMB, see what fallback we can use. 16584 if (!Subtarget->hasDataBarrier()) { 16585 // Some ARMv6 cpus can support data barriers with an mcr instruction. 16586 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 16587 // here. 16588 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 16589 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 16590 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 16591 Builder.getInt32(0), Builder.getInt32(7), 16592 Builder.getInt32(10), Builder.getInt32(5)}; 16593 return Builder.CreateCall(MCR, args); 16594 } else { 16595 // Instead of using barriers, atomic accesses on these subtargets use 16596 // libcalls. 16597 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 16598 } 16599 } else { 16600 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 16601 // Only a full system barrier exists in the M-class architectures. 16602 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 16603 Constant *CDomain = Builder.getInt32(Domain); 16604 return Builder.CreateCall(DMB, CDomain); 16605 } 16606 } 16607 16608 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 16609 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 16610 Instruction *Inst, 16611 AtomicOrdering Ord) const { 16612 switch (Ord) { 16613 case AtomicOrdering::NotAtomic: 16614 case AtomicOrdering::Unordered: 16615 llvm_unreachable("Invalid fence: unordered/non-atomic"); 16616 case AtomicOrdering::Monotonic: 16617 case AtomicOrdering::Acquire: 16618 return nullptr; // Nothing to do 16619 case AtomicOrdering::SequentiallyConsistent: 16620 if (!Inst->hasAtomicStore()) 16621 return nullptr; // Nothing to do 16622 LLVM_FALLTHROUGH; 16623 case AtomicOrdering::Release: 16624 case AtomicOrdering::AcquireRelease: 16625 if (Subtarget->preferISHSTBarriers()) 16626 return makeDMB(Builder, ARM_MB::ISHST); 16627 // FIXME: add a comment with a link to documentation justifying this. 16628 else 16629 return makeDMB(Builder, ARM_MB::ISH); 16630 } 16631 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 16632 } 16633 16634 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 16635 Instruction *Inst, 16636 AtomicOrdering Ord) const { 16637 switch (Ord) { 16638 case AtomicOrdering::NotAtomic: 16639 case AtomicOrdering::Unordered: 16640 llvm_unreachable("Invalid fence: unordered/not-atomic"); 16641 case AtomicOrdering::Monotonic: 16642 case AtomicOrdering::Release: 16643 return nullptr; // Nothing to do 16644 case AtomicOrdering::Acquire: 16645 case AtomicOrdering::AcquireRelease: 16646 case AtomicOrdering::SequentiallyConsistent: 16647 return makeDMB(Builder, ARM_MB::ISH); 16648 } 16649 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 16650 } 16651 16652 // Loads and stores less than 64-bits are already atomic; ones above that 16653 // are doomed anyway, so defer to the default libcall and blame the OS when 16654 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 16655 // anything for those. 16656 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 16657 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 16658 return (Size == 64) && !Subtarget->isMClass(); 16659 } 16660 16661 // Loads and stores less than 64-bits are already atomic; ones above that 16662 // are doomed anyway, so defer to the default libcall and blame the OS when 16663 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 16664 // anything for those. 16665 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 16666 // guarantee, see DDI0406C ARM architecture reference manual, 16667 // sections A8.8.72-74 LDRD) 16668 TargetLowering::AtomicExpansionKind 16669 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 16670 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 16671 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 16672 : AtomicExpansionKind::None; 16673 } 16674 16675 // For the real atomic operations, we have ldrex/strex up to 32 bits, 16676 // and up to 64 bits on the non-M profiles 16677 TargetLowering::AtomicExpansionKind 16678 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 16679 if (AI->isFloatingPointOperation()) 16680 return AtomicExpansionKind::CmpXChg; 16681 16682 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 16683 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 16684 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 16685 ? AtomicExpansionKind::LLSC 16686 : AtomicExpansionKind::None; 16687 } 16688 16689 TargetLowering::AtomicExpansionKind 16690 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 16691 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 16692 // implement cmpxchg without spilling. If the address being exchanged is also 16693 // on the stack and close enough to the spill slot, this can lead to a 16694 // situation where the monitor always gets cleared and the atomic operation 16695 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 16696 bool HasAtomicCmpXchg = 16697 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 16698 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 16699 return AtomicExpansionKind::LLSC; 16700 return AtomicExpansionKind::None; 16701 } 16702 16703 bool ARMTargetLowering::shouldInsertFencesForAtomic( 16704 const Instruction *I) const { 16705 return InsertFencesForAtomic; 16706 } 16707 16708 // This has so far only been implemented for MachO. 16709 bool ARMTargetLowering::useLoadStackGuardNode() const { 16710 return Subtarget->isTargetMachO(); 16711 } 16712 16713 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 16714 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16715 return TargetLowering::insertSSPDeclarations(M); 16716 16717 // MSVC CRT has a global variable holding security cookie. 16718 M.getOrInsertGlobal("__security_cookie", 16719 Type::getInt8PtrTy(M.getContext())); 16720 16721 // MSVC CRT has a function to validate security cookie. 16722 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 16723 "__security_check_cookie", Type::getVoidTy(M.getContext()), 16724 Type::getInt8PtrTy(M.getContext())); 16725 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 16726 F->addAttribute(1, Attribute::AttrKind::InReg); 16727 } 16728 16729 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 16730 // MSVC CRT has a global variable holding security cookie. 16731 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16732 return M.getGlobalVariable("__security_cookie"); 16733 return TargetLowering::getSDagStackGuard(M); 16734 } 16735 16736 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 16737 // MSVC CRT has a function to validate security cookie. 16738 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16739 return M.getFunction("__security_check_cookie"); 16740 return TargetLowering::getSSPStackGuardCheck(M); 16741 } 16742 16743 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 16744 unsigned &Cost) const { 16745 // If we do not have NEON, vector types are not natively supported. 16746 if (!Subtarget->hasNEON()) 16747 return false; 16748 16749 // Floating point values and vector values map to the same register file. 16750 // Therefore, although we could do a store extract of a vector type, this is 16751 // better to leave at float as we have more freedom in the addressing mode for 16752 // those. 16753 if (VectorTy->isFPOrFPVectorTy()) 16754 return false; 16755 16756 // If the index is unknown at compile time, this is very expensive to lower 16757 // and it is not possible to combine the store with the extract. 16758 if (!isa<ConstantInt>(Idx)) 16759 return false; 16760 16761 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 16762 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 16763 // We can do a store + vector extract on any vector that fits perfectly in a D 16764 // or Q register. 16765 if (BitWidth == 64 || BitWidth == 128) { 16766 Cost = 0; 16767 return true; 16768 } 16769 return false; 16770 } 16771 16772 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 16773 return Subtarget->hasV6T2Ops(); 16774 } 16775 16776 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 16777 return Subtarget->hasV6T2Ops(); 16778 } 16779 16780 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 16781 return !Subtarget->hasMinSize(); 16782 } 16783 16784 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 16785 AtomicOrdering Ord) const { 16786 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16787 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 16788 bool IsAcquire = isAcquireOrStronger(Ord); 16789 16790 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 16791 // intrinsic must return {i32, i32} and we have to recombine them into a 16792 // single i64 here. 16793 if (ValTy->getPrimitiveSizeInBits() == 64) { 16794 Intrinsic::ID Int = 16795 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 16796 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 16797 16798 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16799 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 16800 16801 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 16802 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 16803 if (!Subtarget->isLittle()) 16804 std::swap (Lo, Hi); 16805 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 16806 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 16807 return Builder.CreateOr( 16808 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 16809 } 16810 16811 Type *Tys[] = { Addr->getType() }; 16812 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 16813 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 16814 16815 return Builder.CreateTruncOrBitCast( 16816 Builder.CreateCall(Ldrex, Addr), 16817 cast<PointerType>(Addr->getType())->getElementType()); 16818 } 16819 16820 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 16821 IRBuilder<> &Builder) const { 16822 if (!Subtarget->hasV7Ops()) 16823 return; 16824 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16825 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 16826 } 16827 16828 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 16829 Value *Addr, 16830 AtomicOrdering Ord) const { 16831 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16832 bool IsRelease = isReleaseOrStronger(Ord); 16833 16834 // Since the intrinsics must have legal type, the i64 intrinsics take two 16835 // parameters: "i32, i32". We must marshal Val into the appropriate form 16836 // before the call. 16837 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 16838 Intrinsic::ID Int = 16839 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 16840 Function *Strex = Intrinsic::getDeclaration(M, Int); 16841 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 16842 16843 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 16844 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 16845 if (!Subtarget->isLittle()) 16846 std::swap(Lo, Hi); 16847 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16848 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 16849 } 16850 16851 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 16852 Type *Tys[] = { Addr->getType() }; 16853 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 16854 16855 return Builder.CreateCall( 16856 Strex, {Builder.CreateZExtOrBitCast( 16857 Val, Strex->getFunctionType()->getParamType(0)), 16858 Addr}); 16859 } 16860 16861 16862 bool ARMTargetLowering::alignLoopsWithOptSize() const { 16863 return Subtarget->isMClass(); 16864 } 16865 16866 /// A helper function for determining the number of interleaved accesses we 16867 /// will generate when lowering accesses of the given type. 16868 unsigned 16869 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 16870 const DataLayout &DL) const { 16871 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 16872 } 16873 16874 bool ARMTargetLowering::isLegalInterleavedAccessType( 16875 unsigned Factor, VectorType *VecTy, const DataLayout &DL) const { 16876 16877 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 16878 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 16879 16880 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) 16881 return false; 16882 16883 // Ensure the vector doesn't have f16 elements. Even though we could do an 16884 // i16 vldN, we can't hold the f16 vectors and will end up converting via 16885 // f32. 16886 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy()) 16887 return false; 16888 if (Subtarget->hasMVEIntegerOps() && Factor == 3) 16889 return false; 16890 16891 // Ensure the number of vector elements is greater than 1. 16892 if (VecTy->getNumElements() < 2) 16893 return false; 16894 16895 // Ensure the element type is legal. 16896 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 16897 return false; 16898 16899 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 16900 // 128 will be split into multiple interleaved accesses. 16901 if (Subtarget->hasNEON() && VecSize == 64) 16902 return true; 16903 return VecSize % 128 == 0; 16904 } 16905 16906 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const { 16907 if (Subtarget->hasNEON()) 16908 return 4; 16909 if (Subtarget->hasMVEIntegerOps()) 16910 return MVEMaxSupportedInterleaveFactor; 16911 return TargetLoweringBase::getMaxSupportedInterleaveFactor(); 16912 } 16913 16914 /// Lower an interleaved load into a vldN intrinsic. 16915 /// 16916 /// E.g. Lower an interleaved load (Factor = 2): 16917 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 16918 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 16919 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 16920 /// 16921 /// Into: 16922 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 16923 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 16924 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 16925 bool ARMTargetLowering::lowerInterleavedLoad( 16926 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 16927 ArrayRef<unsigned> Indices, unsigned Factor) const { 16928 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 16929 "Invalid interleave factor"); 16930 assert(!Shuffles.empty() && "Empty shufflevector input"); 16931 assert(Shuffles.size() == Indices.size() && 16932 "Unmatched number of shufflevectors and indices"); 16933 16934 VectorType *VecTy = Shuffles[0]->getType(); 16935 Type *EltTy = VecTy->getVectorElementType(); 16936 16937 const DataLayout &DL = LI->getModule()->getDataLayout(); 16938 16939 // Skip if we do not have NEON and skip illegal vector types. We can 16940 // "legalize" wide vector types into multiple interleaved accesses as long as 16941 // the vector types are divisible by 128. 16942 if (!isLegalInterleavedAccessType(Factor, VecTy, DL)) 16943 return false; 16944 16945 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 16946 16947 // A pointer vector can not be the return type of the ldN intrinsics. Need to 16948 // load integer vectors first and then convert to pointer vectors. 16949 if (EltTy->isPointerTy()) 16950 VecTy = 16951 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 16952 16953 IRBuilder<> Builder(LI); 16954 16955 // The base address of the load. 16956 Value *BaseAddr = LI->getPointerOperand(); 16957 16958 if (NumLoads > 1) { 16959 // If we're going to generate more than one load, reset the sub-vector type 16960 // to something legal. 16961 VecTy = VectorType::get(VecTy->getVectorElementType(), 16962 VecTy->getVectorNumElements() / NumLoads); 16963 16964 // We will compute the pointer operand of each load from the original base 16965 // address using GEPs. Cast the base address to a pointer to the scalar 16966 // element type. 16967 BaseAddr = Builder.CreateBitCast( 16968 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 16969 LI->getPointerAddressSpace())); 16970 } 16971 16972 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 16973 16974 auto createLoadIntrinsic = [&](Value *BaseAddr) { 16975 if (Subtarget->hasNEON()) { 16976 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 16977 Type *Tys[] = {VecTy, Int8Ptr}; 16978 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 16979 Intrinsic::arm_neon_vld3, 16980 Intrinsic::arm_neon_vld4}; 16981 Function *VldnFunc = 16982 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 16983 16984 SmallVector<Value *, 2> Ops; 16985 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 16986 Ops.push_back(Builder.getInt32(LI->getAlignment())); 16987 16988 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 16989 } else { 16990 assert((Factor == 2 || Factor == 4) && 16991 "expected interleave factor of 2 or 4 for MVE"); 16992 Intrinsic::ID LoadInts = 16993 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q; 16994 Type *VecEltTy = VecTy->getVectorElementType()->getPointerTo( 16995 LI->getPointerAddressSpace()); 16996 Type *Tys[] = {VecTy, VecEltTy}; 16997 Function *VldnFunc = 16998 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys); 16999 17000 SmallVector<Value *, 2> Ops; 17001 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy)); 17002 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 17003 } 17004 }; 17005 17006 // Holds sub-vectors extracted from the load intrinsic return values. The 17007 // sub-vectors are associated with the shufflevector instructions they will 17008 // replace. 17009 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 17010 17011 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 17012 // If we're generating more than one load, compute the base address of 17013 // subsequent loads as an offset from the previous. 17014 if (LoadCount > 0) 17015 BaseAddr = 17016 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 17017 VecTy->getVectorNumElements() * Factor); 17018 17019 CallInst *VldN = createLoadIntrinsic(BaseAddr); 17020 17021 // Replace uses of each shufflevector with the corresponding vector loaded 17022 // by ldN. 17023 for (unsigned i = 0; i < Shuffles.size(); i++) { 17024 ShuffleVectorInst *SV = Shuffles[i]; 17025 unsigned Index = Indices[i]; 17026 17027 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 17028 17029 // Convert the integer vector to pointer vector if the element is pointer. 17030 if (EltTy->isPointerTy()) 17031 SubVec = Builder.CreateIntToPtr( 17032 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 17033 VecTy->getVectorNumElements())); 17034 17035 SubVecs[SV].push_back(SubVec); 17036 } 17037 } 17038 17039 // Replace uses of the shufflevector instructions with the sub-vectors 17040 // returned by the load intrinsic. If a shufflevector instruction is 17041 // associated with more than one sub-vector, those sub-vectors will be 17042 // concatenated into a single wide vector. 17043 for (ShuffleVectorInst *SVI : Shuffles) { 17044 auto &SubVec = SubVecs[SVI]; 17045 auto *WideVec = 17046 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 17047 SVI->replaceAllUsesWith(WideVec); 17048 } 17049 17050 return true; 17051 } 17052 17053 /// Lower an interleaved store into a vstN intrinsic. 17054 /// 17055 /// E.g. Lower an interleaved store (Factor = 3): 17056 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 17057 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 17058 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 17059 /// 17060 /// Into: 17061 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 17062 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 17063 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 17064 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 17065 /// 17066 /// Note that the new shufflevectors will be removed and we'll only generate one 17067 /// vst3 instruction in CodeGen. 17068 /// 17069 /// Example for a more general valid mask (Factor 3). Lower: 17070 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 17071 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 17072 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 17073 /// 17074 /// Into: 17075 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 17076 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 17077 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 17078 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 17079 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 17080 ShuffleVectorInst *SVI, 17081 unsigned Factor) const { 17082 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 17083 "Invalid interleave factor"); 17084 17085 VectorType *VecTy = SVI->getType(); 17086 assert(VecTy->getVectorNumElements() % Factor == 0 && 17087 "Invalid interleaved store"); 17088 17089 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 17090 Type *EltTy = VecTy->getVectorElementType(); 17091 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 17092 17093 const DataLayout &DL = SI->getModule()->getDataLayout(); 17094 17095 // Skip if we do not have NEON and skip illegal vector types. We can 17096 // "legalize" wide vector types into multiple interleaved accesses as long as 17097 // the vector types are divisible by 128. 17098 if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL)) 17099 return false; 17100 17101 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 17102 17103 Value *Op0 = SVI->getOperand(0); 17104 Value *Op1 = SVI->getOperand(1); 17105 IRBuilder<> Builder(SI); 17106 17107 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 17108 // vectors to integer vectors. 17109 if (EltTy->isPointerTy()) { 17110 Type *IntTy = DL.getIntPtrType(EltTy); 17111 17112 // Convert to the corresponding integer vector. 17113 Type *IntVecTy = 17114 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 17115 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 17116 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 17117 17118 SubVecTy = VectorType::get(IntTy, LaneLen); 17119 } 17120 17121 // The base address of the store. 17122 Value *BaseAddr = SI->getPointerOperand(); 17123 17124 if (NumStores > 1) { 17125 // If we're going to generate more than one store, reset the lane length 17126 // and sub-vector type to something legal. 17127 LaneLen /= NumStores; 17128 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 17129 17130 // We will compute the pointer operand of each store from the original base 17131 // address using GEPs. Cast the base address to a pointer to the scalar 17132 // element type. 17133 BaseAddr = Builder.CreateBitCast( 17134 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 17135 SI->getPointerAddressSpace())); 17136 } 17137 17138 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 17139 17140 auto Mask = SVI->getShuffleMask(); 17141 17142 auto createStoreIntrinsic = [&](Value *BaseAddr, 17143 SmallVectorImpl<Value *> &Shuffles) { 17144 if (Subtarget->hasNEON()) { 17145 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 17146 Intrinsic::arm_neon_vst3, 17147 Intrinsic::arm_neon_vst4}; 17148 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 17149 Type *Tys[] = {Int8Ptr, SubVecTy}; 17150 17151 Function *VstNFunc = Intrinsic::getDeclaration( 17152 SI->getModule(), StoreInts[Factor - 2], Tys); 17153 17154 SmallVector<Value *, 6> Ops; 17155 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 17156 for (auto S : Shuffles) 17157 Ops.push_back(S); 17158 Ops.push_back(Builder.getInt32(SI->getAlignment())); 17159 Builder.CreateCall(VstNFunc, Ops); 17160 } else { 17161 assert((Factor == 2 || Factor == 4) && 17162 "expected interleave factor of 2 or 4 for MVE"); 17163 Intrinsic::ID StoreInts = 17164 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q; 17165 Type *EltPtrTy = SubVecTy->getVectorElementType()->getPointerTo( 17166 SI->getPointerAddressSpace()); 17167 Type *Tys[] = {EltPtrTy, SubVecTy}; 17168 Function *VstNFunc = 17169 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys); 17170 17171 SmallVector<Value *, 6> Ops; 17172 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy)); 17173 for (auto S : Shuffles) 17174 Ops.push_back(S); 17175 for (unsigned F = 0; F < Factor; F++) { 17176 Ops.push_back(Builder.getInt32(F)); 17177 Builder.CreateCall(VstNFunc, Ops); 17178 Ops.pop_back(); 17179 } 17180 } 17181 }; 17182 17183 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 17184 // If we generating more than one store, we compute the base address of 17185 // subsequent stores as an offset from the previous. 17186 if (StoreCount > 0) 17187 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 17188 BaseAddr, LaneLen * Factor); 17189 17190 SmallVector<Value *, 4> Shuffles; 17191 17192 // Split the shufflevector operands into sub vectors for the new vstN call. 17193 for (unsigned i = 0; i < Factor; i++) { 17194 unsigned IdxI = StoreCount * LaneLen * Factor + i; 17195 if (Mask[IdxI] >= 0) { 17196 Shuffles.push_back(Builder.CreateShuffleVector( 17197 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 17198 } else { 17199 unsigned StartMask = 0; 17200 for (unsigned j = 1; j < LaneLen; j++) { 17201 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 17202 if (Mask[IdxJ * Factor + IdxI] >= 0) { 17203 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 17204 break; 17205 } 17206 } 17207 // Note: If all elements in a chunk are undefs, StartMask=0! 17208 // Note: Filling undef gaps with random elements is ok, since 17209 // those elements were being written anyway (with undefs). 17210 // In the case of all undefs we're defaulting to using elems from 0 17211 // Note: StartMask cannot be negative, it's checked in 17212 // isReInterleaveMask 17213 Shuffles.push_back(Builder.CreateShuffleVector( 17214 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 17215 } 17216 } 17217 17218 createStoreIntrinsic(BaseAddr, Shuffles); 17219 } 17220 return true; 17221 } 17222 17223 enum HABaseType { 17224 HA_UNKNOWN = 0, 17225 HA_FLOAT, 17226 HA_DOUBLE, 17227 HA_VECT64, 17228 HA_VECT128 17229 }; 17230 17231 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 17232 uint64_t &Members) { 17233 if (auto *ST = dyn_cast<StructType>(Ty)) { 17234 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 17235 uint64_t SubMembers = 0; 17236 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 17237 return false; 17238 Members += SubMembers; 17239 } 17240 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 17241 uint64_t SubMembers = 0; 17242 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 17243 return false; 17244 Members += SubMembers * AT->getNumElements(); 17245 } else if (Ty->isFloatTy()) { 17246 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 17247 return false; 17248 Members = 1; 17249 Base = HA_FLOAT; 17250 } else if (Ty->isDoubleTy()) { 17251 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 17252 return false; 17253 Members = 1; 17254 Base = HA_DOUBLE; 17255 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 17256 Members = 1; 17257 switch (Base) { 17258 case HA_FLOAT: 17259 case HA_DOUBLE: 17260 return false; 17261 case HA_VECT64: 17262 return VT->getBitWidth() == 64; 17263 case HA_VECT128: 17264 return VT->getBitWidth() == 128; 17265 case HA_UNKNOWN: 17266 switch (VT->getBitWidth()) { 17267 case 64: 17268 Base = HA_VECT64; 17269 return true; 17270 case 128: 17271 Base = HA_VECT128; 17272 return true; 17273 default: 17274 return false; 17275 } 17276 } 17277 } 17278 17279 return (Members > 0 && Members <= 4); 17280 } 17281 17282 /// Return the correct alignment for the current calling convention. 17283 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 17284 DataLayout DL) const { 17285 const Align ABITypeAlign(DL.getABITypeAlignment(ArgTy)); 17286 if (!ArgTy->isVectorTy()) 17287 return ABITypeAlign; 17288 17289 // Avoid over-aligning vector parameters. It would require realigning the 17290 // stack and waste space for no real benefit. 17291 return std::min(ABITypeAlign, DL.getStackAlignment()); 17292 } 17293 17294 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 17295 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 17296 /// passing according to AAPCS rules. 17297 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 17298 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 17299 if (getEffectiveCallingConv(CallConv, isVarArg) != 17300 CallingConv::ARM_AAPCS_VFP) 17301 return false; 17302 17303 HABaseType Base = HA_UNKNOWN; 17304 uint64_t Members = 0; 17305 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 17306 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 17307 17308 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 17309 return IsHA || IsIntArray; 17310 } 17311 17312 unsigned ARMTargetLowering::getExceptionPointerRegister( 17313 const Constant *PersonalityFn) const { 17314 // Platforms which do not use SjLj EH may return values in these registers 17315 // via the personality function. 17316 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 17317 } 17318 17319 unsigned ARMTargetLowering::getExceptionSelectorRegister( 17320 const Constant *PersonalityFn) const { 17321 // Platforms which do not use SjLj EH may return values in these registers 17322 // via the personality function. 17323 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 17324 } 17325 17326 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 17327 // Update IsSplitCSR in ARMFunctionInfo. 17328 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 17329 AFI->setIsSplitCSR(true); 17330 } 17331 17332 void ARMTargetLowering::insertCopiesSplitCSR( 17333 MachineBasicBlock *Entry, 17334 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 17335 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 17336 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 17337 if (!IStart) 17338 return; 17339 17340 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 17341 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 17342 MachineBasicBlock::iterator MBBI = Entry->begin(); 17343 for (const MCPhysReg *I = IStart; *I; ++I) { 17344 const TargetRegisterClass *RC = nullptr; 17345 if (ARM::GPRRegClass.contains(*I)) 17346 RC = &ARM::GPRRegClass; 17347 else if (ARM::DPRRegClass.contains(*I)) 17348 RC = &ARM::DPRRegClass; 17349 else 17350 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 17351 17352 Register NewVR = MRI->createVirtualRegister(RC); 17353 // Create copy from CSR to a virtual register. 17354 // FIXME: this currently does not emit CFI pseudo-instructions, it works 17355 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 17356 // nounwind. If we want to generalize this later, we may need to emit 17357 // CFI pseudo-instructions. 17358 assert(Entry->getParent()->getFunction().hasFnAttribute( 17359 Attribute::NoUnwind) && 17360 "Function should be nounwind in insertCopiesSplitCSR!"); 17361 Entry->addLiveIn(*I); 17362 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 17363 .addReg(*I); 17364 17365 // Insert the copy-back instructions right before the terminator. 17366 for (auto *Exit : Exits) 17367 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 17368 TII->get(TargetOpcode::COPY), *I) 17369 .addReg(NewVR); 17370 } 17371 } 17372 17373 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 17374 MF.getFrameInfo().computeMaxCallFrameSize(MF); 17375 TargetLoweringBase::finalizeLowering(MF); 17376 } 17377