1 //===-- SystemZISelLowering.cpp - SystemZ 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 implements the SystemZTargetLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SystemZISelLowering.h" 14 #include "SystemZCallingConv.h" 15 #include "SystemZConstantPoolValue.h" 16 #include "SystemZMachineFunctionInfo.h" 17 #include "SystemZTargetMachine.h" 18 #include "llvm/CodeGen/CallingConvLower.h" 19 #include "llvm/CodeGen/MachineInstrBuilder.h" 20 #include "llvm/CodeGen/MachineRegisterInfo.h" 21 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 22 #include "llvm/IR/IntrinsicInst.h" 23 #include "llvm/IR/Intrinsics.h" 24 #include "llvm/IR/IntrinsicsS390.h" 25 #include "llvm/Support/CommandLine.h" 26 #include "llvm/Support/KnownBits.h" 27 #include <cctype> 28 #include <optional> 29 30 using namespace llvm; 31 32 #define DEBUG_TYPE "systemz-lower" 33 34 namespace { 35 // Represents information about a comparison. 36 struct Comparison { 37 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn) 38 : Op0(Op0In), Op1(Op1In), Chain(ChainIn), 39 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {} 40 41 // The operands to the comparison. 42 SDValue Op0, Op1; 43 44 // Chain if this is a strict floating-point comparison. 45 SDValue Chain; 46 47 // The opcode that should be used to compare Op0 and Op1. 48 unsigned Opcode; 49 50 // A SystemZICMP value. Only used for integer comparisons. 51 unsigned ICmpType; 52 53 // The mask of CC values that Opcode can produce. 54 unsigned CCValid; 55 56 // The mask of CC values for which the original condition is true. 57 unsigned CCMask; 58 }; 59 } // end anonymous namespace 60 61 // Classify VT as either 32 or 64 bit. 62 static bool is32Bit(EVT VT) { 63 switch (VT.getSimpleVT().SimpleTy) { 64 case MVT::i32: 65 return true; 66 case MVT::i64: 67 return false; 68 default: 69 llvm_unreachable("Unsupported type"); 70 } 71 } 72 73 // Return a version of MachineOperand that can be safely used before the 74 // final use. 75 static MachineOperand earlyUseOperand(MachineOperand Op) { 76 if (Op.isReg()) 77 Op.setIsKill(false); 78 return Op; 79 } 80 81 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &TM, 82 const SystemZSubtarget &STI) 83 : TargetLowering(TM), Subtarget(STI) { 84 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0)); 85 86 auto *Regs = STI.getSpecialRegisters(); 87 88 // Set up the register classes. 89 if (Subtarget.hasHighWord()) 90 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass); 91 else 92 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass); 93 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass); 94 if (!useSoftFloat()) { 95 if (Subtarget.hasVector()) { 96 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass); 97 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass); 98 } else { 99 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass); 100 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass); 101 } 102 if (Subtarget.hasVectorEnhancements1()) 103 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass); 104 else 105 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass); 106 107 if (Subtarget.hasVector()) { 108 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass); 109 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass); 110 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass); 111 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass); 112 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass); 113 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass); 114 } 115 116 if (Subtarget.hasVector()) 117 addRegisterClass(MVT::i128, &SystemZ::VR128BitRegClass); 118 } 119 120 // Compute derived properties from the register classes 121 computeRegisterProperties(Subtarget.getRegisterInfo()); 122 123 // Set up special registers. 124 setStackPointerRegisterToSaveRestore(Regs->getStackPointerRegister()); 125 126 // TODO: It may be better to default to latency-oriented scheduling, however 127 // LLVM's current latency-oriented scheduler can't handle physreg definitions 128 // such as SystemZ has with CC, so set this to the register-pressure 129 // scheduler, because it can. 130 setSchedulingPreference(Sched::RegPressure); 131 132 setBooleanContents(ZeroOrOneBooleanContent); 133 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 134 135 setMaxAtomicSizeInBitsSupported(128); 136 137 // Instructions are strings of 2-byte aligned 2-byte values. 138 setMinFunctionAlignment(Align(2)); 139 // For performance reasons we prefer 16-byte alignment. 140 setPrefFunctionAlignment(Align(16)); 141 142 // Handle operations that are handled in a similar way for all types. 143 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE; 144 I <= MVT::LAST_FP_VALUETYPE; 145 ++I) { 146 MVT VT = MVT::SimpleValueType(I); 147 if (isTypeLegal(VT)) { 148 // Lower SET_CC into an IPM-based sequence. 149 setOperationAction(ISD::SETCC, VT, Custom); 150 setOperationAction(ISD::STRICT_FSETCC, VT, Custom); 151 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom); 152 153 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE). 154 setOperationAction(ISD::SELECT, VT, Expand); 155 156 // Lower SELECT_CC and BR_CC into separate comparisons and branches. 157 setOperationAction(ISD::SELECT_CC, VT, Custom); 158 setOperationAction(ISD::BR_CC, VT, Custom); 159 } 160 } 161 162 // Expand jump table branches as address arithmetic followed by an 163 // indirect jump. 164 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 165 166 // Expand BRCOND into a BR_CC (see above). 167 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 168 169 // Handle integer types except i128. 170 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE; 171 I <= MVT::LAST_INTEGER_VALUETYPE; 172 ++I) { 173 MVT VT = MVT::SimpleValueType(I); 174 if (isTypeLegal(VT) && VT != MVT::i128) { 175 setOperationAction(ISD::ABS, VT, Legal); 176 177 // Expand individual DIV and REMs into DIVREMs. 178 setOperationAction(ISD::SDIV, VT, Expand); 179 setOperationAction(ISD::UDIV, VT, Expand); 180 setOperationAction(ISD::SREM, VT, Expand); 181 setOperationAction(ISD::UREM, VT, Expand); 182 setOperationAction(ISD::SDIVREM, VT, Custom); 183 setOperationAction(ISD::UDIVREM, VT, Custom); 184 185 // Support addition/subtraction with overflow. 186 setOperationAction(ISD::SADDO, VT, Custom); 187 setOperationAction(ISD::SSUBO, VT, Custom); 188 189 // Support addition/subtraction with carry. 190 setOperationAction(ISD::UADDO, VT, Custom); 191 setOperationAction(ISD::USUBO, VT, Custom); 192 193 // Support carry in as value rather than glue. 194 setOperationAction(ISD::UADDO_CARRY, VT, Custom); 195 setOperationAction(ISD::USUBO_CARRY, VT, Custom); 196 197 // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and 198 // stores, putting a serialization instruction after the stores. 199 setOperationAction(ISD::ATOMIC_LOAD, VT, Custom); 200 setOperationAction(ISD::ATOMIC_STORE, VT, Custom); 201 202 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are 203 // available, or if the operand is constant. 204 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 205 206 // Use POPCNT on z196 and above. 207 if (Subtarget.hasPopulationCount()) 208 setOperationAction(ISD::CTPOP, VT, Custom); 209 else 210 setOperationAction(ISD::CTPOP, VT, Expand); 211 212 // No special instructions for these. 213 setOperationAction(ISD::CTTZ, VT, Expand); 214 setOperationAction(ISD::ROTR, VT, Expand); 215 216 // Use *MUL_LOHI where possible instead of MULH*. 217 setOperationAction(ISD::MULHS, VT, Expand); 218 setOperationAction(ISD::MULHU, VT, Expand); 219 setOperationAction(ISD::SMUL_LOHI, VT, Custom); 220 setOperationAction(ISD::UMUL_LOHI, VT, Custom); 221 222 // Only z196 and above have native support for conversions to unsigned. 223 // On z10, promoting to i64 doesn't generate an inexact condition for 224 // values that are outside the i32 range but in the i64 range, so use 225 // the default expansion. 226 if (!Subtarget.hasFPExtension()) 227 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 228 229 // Mirror those settings for STRICT_FP_TO_[SU]INT. Note that these all 230 // default to Expand, so need to be modified to Legal where appropriate. 231 setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Legal); 232 if (Subtarget.hasFPExtension()) 233 setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Legal); 234 235 // And similarly for STRICT_[SU]INT_TO_FP. 236 setOperationAction(ISD::STRICT_SINT_TO_FP, VT, Legal); 237 if (Subtarget.hasFPExtension()) 238 setOperationAction(ISD::STRICT_UINT_TO_FP, VT, Legal); 239 } 240 } 241 242 // Handle i128 if legal. 243 if (isTypeLegal(MVT::i128)) { 244 // No special instructions for these. 245 setOperationAction(ISD::SDIVREM, MVT::i128, Expand); 246 setOperationAction(ISD::UDIVREM, MVT::i128, Expand); 247 setOperationAction(ISD::SMUL_LOHI, MVT::i128, Expand); 248 setOperationAction(ISD::UMUL_LOHI, MVT::i128, Expand); 249 setOperationAction(ISD::ROTR, MVT::i128, Expand); 250 setOperationAction(ISD::ROTL, MVT::i128, Expand); 251 setOperationAction(ISD::MUL, MVT::i128, Expand); 252 setOperationAction(ISD::MULHS, MVT::i128, Expand); 253 setOperationAction(ISD::MULHU, MVT::i128, Expand); 254 setOperationAction(ISD::SDIV, MVT::i128, Expand); 255 setOperationAction(ISD::UDIV, MVT::i128, Expand); 256 setOperationAction(ISD::SREM, MVT::i128, Expand); 257 setOperationAction(ISD::UREM, MVT::i128, Expand); 258 setOperationAction(ISD::CTLZ, MVT::i128, Expand); 259 setOperationAction(ISD::CTTZ, MVT::i128, Expand); 260 261 // Support addition/subtraction with carry. 262 setOperationAction(ISD::UADDO, MVT::i128, Custom); 263 setOperationAction(ISD::USUBO, MVT::i128, Custom); 264 setOperationAction(ISD::UADDO_CARRY, MVT::i128, Custom); 265 setOperationAction(ISD::USUBO_CARRY, MVT::i128, Custom); 266 267 // Use VPOPCT and add up partial results. 268 setOperationAction(ISD::CTPOP, MVT::i128, Custom); 269 270 // We have to use libcalls for these. 271 setOperationAction(ISD::FP_TO_UINT, MVT::i128, LibCall); 272 setOperationAction(ISD::FP_TO_SINT, MVT::i128, LibCall); 273 setOperationAction(ISD::UINT_TO_FP, MVT::i128, LibCall); 274 setOperationAction(ISD::SINT_TO_FP, MVT::i128, LibCall); 275 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, LibCall); 276 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, LibCall); 277 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, LibCall); 278 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, LibCall); 279 } 280 281 // Type legalization will convert 8- and 16-bit atomic operations into 282 // forms that operate on i32s (but still keeping the original memory VT). 283 // Lower them into full i32 operations. 284 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Custom); 285 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Custom); 286 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); 287 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); 288 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Custom); 289 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Custom); 290 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom); 291 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Custom); 292 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Custom); 293 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom); 294 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom); 295 296 // Whether or not i128 is not a legal type, we need to custom lower 297 // the atomic operations in order to exploit SystemZ instructions. 298 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom); 299 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom); 300 301 // We can use the CC result of compare-and-swap to implement 302 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS. 303 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Custom); 304 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Custom); 305 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom); 306 307 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 308 309 // Traps are legal, as we will convert them to "j .+2". 310 setOperationAction(ISD::TRAP, MVT::Other, Legal); 311 312 // z10 has instructions for signed but not unsigned FP conversion. 313 // Handle unsigned 32-bit types as signed 64-bit types. 314 if (!Subtarget.hasFPExtension()) { 315 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote); 316 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 317 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Promote); 318 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 319 } 320 321 // We have native support for a 64-bit CTLZ, via FLOGR. 322 setOperationAction(ISD::CTLZ, MVT::i32, Promote); 323 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Promote); 324 setOperationAction(ISD::CTLZ, MVT::i64, Legal); 325 326 // On z15 we have native support for a 64-bit CTPOP. 327 if (Subtarget.hasMiscellaneousExtensions3()) { 328 setOperationAction(ISD::CTPOP, MVT::i32, Promote); 329 setOperationAction(ISD::CTPOP, MVT::i64, Legal); 330 } 331 332 // Give LowerOperation the chance to replace 64-bit ORs with subregs. 333 setOperationAction(ISD::OR, MVT::i64, Custom); 334 335 // Expand 128 bit shifts without using a libcall. 336 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 337 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 338 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 339 setLibcallName(RTLIB::SRL_I128, nullptr); 340 setLibcallName(RTLIB::SHL_I128, nullptr); 341 setLibcallName(RTLIB::SRA_I128, nullptr); 342 343 // Handle bitcast from fp128 to i128. 344 if (!isTypeLegal(MVT::i128)) 345 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 346 347 // We have native instructions for i8, i16 and i32 extensions, but not i1. 348 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 349 for (MVT VT : MVT::integer_valuetypes()) { 350 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 351 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 352 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote); 353 } 354 355 // Handle the various types of symbolic address. 356 setOperationAction(ISD::ConstantPool, PtrVT, Custom); 357 setOperationAction(ISD::GlobalAddress, PtrVT, Custom); 358 setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom); 359 setOperationAction(ISD::BlockAddress, PtrVT, Custom); 360 setOperationAction(ISD::JumpTable, PtrVT, Custom); 361 362 // We need to handle dynamic allocations specially because of the 363 // 160-byte area at the bottom of the stack. 364 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom); 365 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, PtrVT, Custom); 366 367 setOperationAction(ISD::STACKSAVE, MVT::Other, Custom); 368 setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom); 369 370 // Handle prefetches with PFD or PFDRL. 371 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 372 373 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 374 // Assume by default that all vector operations need to be expanded. 375 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode) 376 if (getOperationAction(Opcode, VT) == Legal) 377 setOperationAction(Opcode, VT, Expand); 378 379 // Likewise all truncating stores and extending loads. 380 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 381 setTruncStoreAction(VT, InnerVT, Expand); 382 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 383 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 384 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 385 } 386 387 if (isTypeLegal(VT)) { 388 // These operations are legal for anything that can be stored in a 389 // vector register, even if there is no native support for the format 390 // as such. In particular, we can do these for v4f32 even though there 391 // are no specific instructions for that format. 392 setOperationAction(ISD::LOAD, VT, Legal); 393 setOperationAction(ISD::STORE, VT, Legal); 394 setOperationAction(ISD::VSELECT, VT, Legal); 395 setOperationAction(ISD::BITCAST, VT, Legal); 396 setOperationAction(ISD::UNDEF, VT, Legal); 397 398 // Likewise, except that we need to replace the nodes with something 399 // more specific. 400 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 401 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 402 } 403 } 404 405 // Handle integer vector types. 406 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 407 if (isTypeLegal(VT)) { 408 // These operations have direct equivalents. 409 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal); 410 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal); 411 setOperationAction(ISD::ADD, VT, Legal); 412 setOperationAction(ISD::SUB, VT, Legal); 413 if (VT != MVT::v2i64) 414 setOperationAction(ISD::MUL, VT, Legal); 415 setOperationAction(ISD::ABS, VT, Legal); 416 setOperationAction(ISD::AND, VT, Legal); 417 setOperationAction(ISD::OR, VT, Legal); 418 setOperationAction(ISD::XOR, VT, Legal); 419 if (Subtarget.hasVectorEnhancements1()) 420 setOperationAction(ISD::CTPOP, VT, Legal); 421 else 422 setOperationAction(ISD::CTPOP, VT, Custom); 423 setOperationAction(ISD::CTTZ, VT, Legal); 424 setOperationAction(ISD::CTLZ, VT, Legal); 425 426 // Convert a GPR scalar to a vector by inserting it into element 0. 427 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom); 428 429 // Use a series of unpacks for extensions. 430 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom); 431 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom); 432 433 // Detect shifts/rotates by a scalar amount and convert them into 434 // V*_BY_SCALAR. 435 setOperationAction(ISD::SHL, VT, Custom); 436 setOperationAction(ISD::SRA, VT, Custom); 437 setOperationAction(ISD::SRL, VT, Custom); 438 setOperationAction(ISD::ROTL, VT, Custom); 439 440 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands 441 // and inverting the result as necessary. 442 setOperationAction(ISD::SETCC, VT, Custom); 443 } 444 } 445 446 if (Subtarget.hasVector()) { 447 // There should be no need to check for float types other than v2f64 448 // since <2 x f32> isn't a legal type. 449 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 450 setOperationAction(ISD::FP_TO_SINT, MVT::v2f64, Legal); 451 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 452 setOperationAction(ISD::FP_TO_UINT, MVT::v2f64, Legal); 453 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 454 setOperationAction(ISD::SINT_TO_FP, MVT::v2f64, Legal); 455 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 456 setOperationAction(ISD::UINT_TO_FP, MVT::v2f64, Legal); 457 458 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 459 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f64, Legal); 460 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 461 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f64, Legal); 462 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 463 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f64, Legal); 464 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 465 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f64, Legal); 466 } 467 468 if (Subtarget.hasVectorEnhancements2()) { 469 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 470 setOperationAction(ISD::FP_TO_SINT, MVT::v4f32, Legal); 471 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 472 setOperationAction(ISD::FP_TO_UINT, MVT::v4f32, Legal); 473 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 474 setOperationAction(ISD::SINT_TO_FP, MVT::v4f32, Legal); 475 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 476 setOperationAction(ISD::UINT_TO_FP, MVT::v4f32, Legal); 477 478 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 479 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4f32, Legal); 480 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 481 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4f32, Legal); 482 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 483 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4f32, Legal); 484 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 485 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4f32, Legal); 486 } 487 488 // Handle floating-point types. 489 for (unsigned I = MVT::FIRST_FP_VALUETYPE; 490 I <= MVT::LAST_FP_VALUETYPE; 491 ++I) { 492 MVT VT = MVT::SimpleValueType(I); 493 if (isTypeLegal(VT)) { 494 // We can use FI for FRINT. 495 setOperationAction(ISD::FRINT, VT, Legal); 496 497 // We can use the extended form of FI for other rounding operations. 498 if (Subtarget.hasFPExtension()) { 499 setOperationAction(ISD::FNEARBYINT, VT, Legal); 500 setOperationAction(ISD::FFLOOR, VT, Legal); 501 setOperationAction(ISD::FCEIL, VT, Legal); 502 setOperationAction(ISD::FTRUNC, VT, Legal); 503 setOperationAction(ISD::FROUND, VT, Legal); 504 } 505 506 // No special instructions for these. 507 setOperationAction(ISD::FSIN, VT, Expand); 508 setOperationAction(ISD::FCOS, VT, Expand); 509 setOperationAction(ISD::FSINCOS, VT, Expand); 510 setOperationAction(ISD::FREM, VT, Expand); 511 setOperationAction(ISD::FPOW, VT, Expand); 512 513 // Special treatment. 514 setOperationAction(ISD::IS_FPCLASS, VT, Custom); 515 516 // Handle constrained floating-point operations. 517 setOperationAction(ISD::STRICT_FADD, VT, Legal); 518 setOperationAction(ISD::STRICT_FSUB, VT, Legal); 519 setOperationAction(ISD::STRICT_FMUL, VT, Legal); 520 setOperationAction(ISD::STRICT_FDIV, VT, Legal); 521 setOperationAction(ISD::STRICT_FMA, VT, Legal); 522 setOperationAction(ISD::STRICT_FSQRT, VT, Legal); 523 setOperationAction(ISD::STRICT_FRINT, VT, Legal); 524 setOperationAction(ISD::STRICT_FP_ROUND, VT, Legal); 525 setOperationAction(ISD::STRICT_FP_EXTEND, VT, Legal); 526 if (Subtarget.hasFPExtension()) { 527 setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal); 528 setOperationAction(ISD::STRICT_FFLOOR, VT, Legal); 529 setOperationAction(ISD::STRICT_FCEIL, VT, Legal); 530 setOperationAction(ISD::STRICT_FROUND, VT, Legal); 531 setOperationAction(ISD::STRICT_FTRUNC, VT, Legal); 532 } 533 } 534 } 535 536 // Handle floating-point vector types. 537 if (Subtarget.hasVector()) { 538 // Scalar-to-vector conversion is just a subreg. 539 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 540 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 541 542 // Some insertions and extractions can be done directly but others 543 // need to go via integers. 544 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 545 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 546 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 547 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 548 549 // These operations have direct equivalents. 550 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 551 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 552 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 553 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 554 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 555 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 556 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 557 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 558 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 559 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 560 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 561 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 562 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 563 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 564 565 // Handle constrained floating-point operations. 566 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 567 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 568 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 569 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 570 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 571 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 572 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 573 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal); 574 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 575 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 576 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 577 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 578 579 setOperationAction(ISD::SETCC, MVT::v2f64, Custom); 580 setOperationAction(ISD::SETCC, MVT::v4f32, Custom); 581 setOperationAction(ISD::STRICT_FSETCC, MVT::v2f64, Custom); 582 setOperationAction(ISD::STRICT_FSETCC, MVT::v4f32, Custom); 583 if (Subtarget.hasVectorEnhancements1()) { 584 setOperationAction(ISD::STRICT_FSETCCS, MVT::v2f64, Custom); 585 setOperationAction(ISD::STRICT_FSETCCS, MVT::v4f32, Custom); 586 } 587 } 588 589 // The vector enhancements facility 1 has instructions for these. 590 if (Subtarget.hasVectorEnhancements1()) { 591 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 592 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 593 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 594 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 595 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 596 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 597 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 598 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 599 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 600 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 601 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 602 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 603 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 604 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 605 606 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 607 setOperationAction(ISD::FMAXIMUM, MVT::f64, Legal); 608 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 609 setOperationAction(ISD::FMINIMUM, MVT::f64, Legal); 610 611 setOperationAction(ISD::FMAXNUM, MVT::v2f64, Legal); 612 setOperationAction(ISD::FMAXIMUM, MVT::v2f64, Legal); 613 setOperationAction(ISD::FMINNUM, MVT::v2f64, Legal); 614 setOperationAction(ISD::FMINIMUM, MVT::v2f64, Legal); 615 616 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 617 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 618 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 619 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 620 621 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 622 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 623 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 624 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 625 626 setOperationAction(ISD::FMAXNUM, MVT::f128, Legal); 627 setOperationAction(ISD::FMAXIMUM, MVT::f128, Legal); 628 setOperationAction(ISD::FMINNUM, MVT::f128, Legal); 629 setOperationAction(ISD::FMINIMUM, MVT::f128, Legal); 630 631 // Handle constrained floating-point operations. 632 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 633 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 634 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 635 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 636 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 637 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 638 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 639 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal); 640 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 641 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 642 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 643 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 644 for (auto VT : { MVT::f32, MVT::f64, MVT::f128, 645 MVT::v4f32, MVT::v2f64 }) { 646 setOperationAction(ISD::STRICT_FMAXNUM, VT, Legal); 647 setOperationAction(ISD::STRICT_FMINNUM, VT, Legal); 648 setOperationAction(ISD::STRICT_FMAXIMUM, VT, Legal); 649 setOperationAction(ISD::STRICT_FMINIMUM, VT, Legal); 650 } 651 } 652 653 // We only have fused f128 multiply-addition on vector registers. 654 if (!Subtarget.hasVectorEnhancements1()) { 655 setOperationAction(ISD::FMA, MVT::f128, Expand); 656 setOperationAction(ISD::STRICT_FMA, MVT::f128, Expand); 657 } 658 659 // We don't have a copysign instruction on vector registers. 660 if (Subtarget.hasVectorEnhancements1()) 661 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 662 663 // Needed so that we don't try to implement f128 constant loads using 664 // a load-and-extend of a f80 constant (in cases where the constant 665 // would fit in an f80). 666 for (MVT VT : MVT::fp_valuetypes()) 667 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 668 669 // We don't have extending load instruction on vector registers. 670 if (Subtarget.hasVectorEnhancements1()) { 671 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand); 672 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand); 673 } 674 675 // Floating-point truncation and stores need to be done separately. 676 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 677 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 678 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 679 680 // We have 64-bit FPR<->GPR moves, but need special handling for 681 // 32-bit forms. 682 if (!Subtarget.hasVector()) { 683 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 684 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 685 } 686 687 // VASTART and VACOPY need to deal with the SystemZ-specific varargs 688 // structure, but VAEND is a no-op. 689 setOperationAction(ISD::VASTART, MVT::Other, Custom); 690 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 691 setOperationAction(ISD::VAEND, MVT::Other, Expand); 692 693 setOperationAction(ISD::GET_ROUNDING, MVT::i32, Custom); 694 695 // Codes for which we want to perform some z-specific combinations. 696 setTargetDAGCombine({ISD::ZERO_EXTEND, 697 ISD::SIGN_EXTEND, 698 ISD::SIGN_EXTEND_INREG, 699 ISD::LOAD, 700 ISD::STORE, 701 ISD::VECTOR_SHUFFLE, 702 ISD::EXTRACT_VECTOR_ELT, 703 ISD::FP_ROUND, 704 ISD::STRICT_FP_ROUND, 705 ISD::FP_EXTEND, 706 ISD::SINT_TO_FP, 707 ISD::UINT_TO_FP, 708 ISD::STRICT_FP_EXTEND, 709 ISD::BSWAP, 710 ISD::SDIV, 711 ISD::UDIV, 712 ISD::SREM, 713 ISD::UREM, 714 ISD::INTRINSIC_VOID, 715 ISD::INTRINSIC_W_CHAIN}); 716 717 // Handle intrinsics. 718 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 719 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 720 721 // We want to use MVC in preference to even a single load/store pair. 722 MaxStoresPerMemcpy = Subtarget.hasVector() ? 2 : 0; 723 MaxStoresPerMemcpyOptSize = 0; 724 725 // The main memset sequence is a byte store followed by an MVC. 726 // Two STC or MV..I stores win over that, but the kind of fused stores 727 // generated by target-independent code don't when the byte value is 728 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better 729 // than "STC;MVC". Handle the choice in target-specific code instead. 730 MaxStoresPerMemset = Subtarget.hasVector() ? 2 : 0; 731 MaxStoresPerMemsetOptSize = 0; 732 733 // Default to having -disable-strictnode-mutation on 734 IsStrictFPEnabled = true; 735 736 if (Subtarget.isTargetzOS()) { 737 struct RTLibCallMapping { 738 RTLIB::Libcall Code; 739 const char *Name; 740 }; 741 static RTLibCallMapping RTLibCallCommon[] = { 742 #define HANDLE_LIBCALL(code, name) {RTLIB::code, name}, 743 #include "ZOSLibcallNames.def" 744 }; 745 for (auto &E : RTLibCallCommon) 746 setLibcallName(E.Code, E.Name); 747 } 748 } 749 750 bool SystemZTargetLowering::useSoftFloat() const { 751 return Subtarget.hasSoftFloat(); 752 } 753 754 EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL, 755 LLVMContext &, EVT VT) const { 756 if (!VT.isVector()) 757 return MVT::i32; 758 return VT.changeVectorElementTypeToInteger(); 759 } 760 761 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd( 762 const MachineFunction &MF, EVT VT) const { 763 VT = VT.getScalarType(); 764 765 if (!VT.isSimple()) 766 return false; 767 768 switch (VT.getSimpleVT().SimpleTy) { 769 case MVT::f32: 770 case MVT::f64: 771 return true; 772 case MVT::f128: 773 return Subtarget.hasVectorEnhancements1(); 774 default: 775 break; 776 } 777 778 return false; 779 } 780 781 // Return true if the constant can be generated with a vector instruction, 782 // such as VGM, VGMB or VREPI. 783 bool SystemZVectorConstantInfo::isVectorConstantLegal( 784 const SystemZSubtarget &Subtarget) { 785 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 786 if (!Subtarget.hasVector() || 787 (isFP128 && !Subtarget.hasVectorEnhancements1())) 788 return false; 789 790 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally- 791 // preferred way of creating all-zero and all-one vectors so give it 792 // priority over other methods below. 793 unsigned Mask = 0; 794 unsigned I = 0; 795 for (; I < SystemZ::VectorBytes; ++I) { 796 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue(); 797 if (Byte == 0xff) 798 Mask |= 1ULL << I; 799 else if (Byte != 0) 800 break; 801 } 802 if (I == SystemZ::VectorBytes) { 803 Opcode = SystemZISD::BYTE_MASK; 804 OpVals.push_back(Mask); 805 VecVT = MVT::getVectorVT(MVT::getIntegerVT(8), 16); 806 return true; 807 } 808 809 if (SplatBitSize > 64) 810 return false; 811 812 auto tryValue = [&](uint64_t Value) -> bool { 813 // Try VECTOR REPLICATE IMMEDIATE 814 int64_t SignedValue = SignExtend64(Value, SplatBitSize); 815 if (isInt<16>(SignedValue)) { 816 OpVals.push_back(((unsigned) SignedValue)); 817 Opcode = SystemZISD::REPLICATE; 818 VecVT = MVT::getVectorVT(MVT::getIntegerVT(SplatBitSize), 819 SystemZ::VectorBits / SplatBitSize); 820 return true; 821 } 822 // Try VECTOR GENERATE MASK 823 unsigned Start, End; 824 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) { 825 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0 826 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for 827 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1). 828 OpVals.push_back(Start - (64 - SplatBitSize)); 829 OpVals.push_back(End - (64 - SplatBitSize)); 830 Opcode = SystemZISD::ROTATE_MASK; 831 VecVT = MVT::getVectorVT(MVT::getIntegerVT(SplatBitSize), 832 SystemZ::VectorBits / SplatBitSize); 833 return true; 834 } 835 return false; 836 }; 837 838 // First try assuming that any undefined bits above the highest set bit 839 // and below the lowest set bit are 1s. This increases the likelihood of 840 // being able to use a sign-extended element value in VECTOR REPLICATE 841 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK. 842 uint64_t SplatBitsZ = SplatBits.getZExtValue(); 843 uint64_t SplatUndefZ = SplatUndef.getZExtValue(); 844 unsigned LowerBits = llvm::countr_zero(SplatBitsZ); 845 unsigned UpperBits = llvm::countl_zero(SplatBitsZ); 846 uint64_t Lower = SplatUndefZ & maskTrailingOnes<uint64_t>(LowerBits); 847 uint64_t Upper = SplatUndefZ & maskLeadingOnes<uint64_t>(UpperBits); 848 if (tryValue(SplatBitsZ | Upper | Lower)) 849 return true; 850 851 // Now try assuming that any undefined bits between the first and 852 // last defined set bits are set. This increases the chances of 853 // using a non-wraparound mask. 854 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower; 855 return tryValue(SplatBitsZ | Middle); 856 } 857 858 SystemZVectorConstantInfo::SystemZVectorConstantInfo(APInt IntImm) { 859 if (IntImm.isSingleWord()) { 860 IntBits = APInt(128, IntImm.getZExtValue()); 861 IntBits <<= (SystemZ::VectorBits - IntImm.getBitWidth()); 862 } else 863 IntBits = IntImm; 864 assert(IntBits.getBitWidth() == 128 && "Unsupported APInt."); 865 866 // Find the smallest splat. 867 SplatBits = IntImm; 868 unsigned Width = SplatBits.getBitWidth(); 869 while (Width > 8) { 870 unsigned HalfSize = Width / 2; 871 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize); 872 APInt LowValue = SplatBits.trunc(HalfSize); 873 874 // If the two halves do not match, stop here. 875 if (HighValue != LowValue || 8 > HalfSize) 876 break; 877 878 SplatBits = HighValue; 879 Width = HalfSize; 880 } 881 SplatUndef = 0; 882 SplatBitSize = Width; 883 } 884 885 SystemZVectorConstantInfo::SystemZVectorConstantInfo(BuildVectorSDNode *BVN) { 886 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR"); 887 bool HasAnyUndefs; 888 889 // Get IntBits by finding the 128 bit splat. 890 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128, 891 true); 892 893 // Get SplatBits by finding the 8 bit or greater splat. 894 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8, 895 true); 896 } 897 898 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 899 bool ForCodeSize) const { 900 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR. 901 if (Imm.isZero() || Imm.isNegZero()) 902 return true; 903 904 return SystemZVectorConstantInfo(Imm).isVectorConstantLegal(Subtarget); 905 } 906 907 /// Returns true if stack probing through inline assembly is requested. 908 bool SystemZTargetLowering::hasInlineStackProbe(const MachineFunction &MF) const { 909 // If the function specifically requests inline stack probes, emit them. 910 if (MF.getFunction().hasFnAttribute("probe-stack")) 911 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 912 "inline-asm"; 913 return false; 914 } 915 916 TargetLowering::AtomicExpansionKind 917 SystemZTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 918 // Don't expand subword operations as they require special treatment. 919 if (RMW->getType()->isIntegerTy(8) || RMW->getType()->isIntegerTy(16)) 920 return AtomicExpansionKind::None; 921 922 // Don't expand if there is a target instruction available. 923 if (Subtarget.hasInterlockedAccess1() && 924 (RMW->getType()->isIntegerTy(32) || RMW->getType()->isIntegerTy(64)) && 925 (RMW->getOperation() == AtomicRMWInst::BinOp::Add || 926 RMW->getOperation() == AtomicRMWInst::BinOp::Sub || 927 RMW->getOperation() == AtomicRMWInst::BinOp::And || 928 RMW->getOperation() == AtomicRMWInst::BinOp::Or || 929 RMW->getOperation() == AtomicRMWInst::BinOp::Xor)) 930 return AtomicExpansionKind::None; 931 932 return AtomicExpansionKind::CmpXChg; 933 } 934 935 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 936 // We can use CGFI or CLGFI. 937 return isInt<32>(Imm) || isUInt<32>(Imm); 938 } 939 940 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const { 941 // We can use ALGFI or SLGFI. 942 return isUInt<32>(Imm) || isUInt<32>(-Imm); 943 } 944 945 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses( 946 EVT VT, unsigned, Align, MachineMemOperand::Flags, unsigned *Fast) const { 947 // Unaligned accesses should never be slower than the expanded version. 948 // We check specifically for aligned accesses in the few cases where 949 // they are required. 950 if (Fast) 951 *Fast = 1; 952 return true; 953 } 954 955 // Information about the addressing mode for a memory access. 956 struct AddressingMode { 957 // True if a long displacement is supported. 958 bool LongDisplacement; 959 960 // True if use of index register is supported. 961 bool IndexReg; 962 963 AddressingMode(bool LongDispl, bool IdxReg) : 964 LongDisplacement(LongDispl), IndexReg(IdxReg) {} 965 }; 966 967 // Return the desired addressing mode for a Load which has only one use (in 968 // the same block) which is a Store. 969 static AddressingMode getLoadStoreAddrMode(bool HasVector, 970 Type *Ty) { 971 // With vector support a Load->Store combination may be combined to either 972 // an MVC or vector operations and it seems to work best to allow the 973 // vector addressing mode. 974 if (HasVector) 975 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/); 976 977 // Otherwise only the MVC case is special. 978 bool MVC = Ty->isIntegerTy(8); 979 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/); 980 } 981 982 // Return the addressing mode which seems most desirable given an LLVM 983 // Instruction pointer. 984 static AddressingMode 985 supportedAddressingMode(Instruction *I, bool HasVector) { 986 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 987 switch (II->getIntrinsicID()) { 988 default: break; 989 case Intrinsic::memset: 990 case Intrinsic::memmove: 991 case Intrinsic::memcpy: 992 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/); 993 } 994 } 995 996 if (isa<LoadInst>(I) && I->hasOneUse()) { 997 auto *SingleUser = cast<Instruction>(*I->user_begin()); 998 if (SingleUser->getParent() == I->getParent()) { 999 if (isa<ICmpInst>(SingleUser)) { 1000 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1))) 1001 if (C->getBitWidth() <= 64 && 1002 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue()))) 1003 // Comparison of memory with 16 bit signed / unsigned immediate 1004 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/); 1005 } else if (isa<StoreInst>(SingleUser)) 1006 // Load->Store 1007 return getLoadStoreAddrMode(HasVector, I->getType()); 1008 } 1009 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) { 1010 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand())) 1011 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent()) 1012 // Load->Store 1013 return getLoadStoreAddrMode(HasVector, LoadI->getType()); 1014 } 1015 1016 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) { 1017 1018 // * Use LDE instead of LE/LEY for z13 to avoid partial register 1019 // dependencies (LDE only supports small offsets). 1020 // * Utilize the vector registers to hold floating point 1021 // values (vector load / store instructions only support small 1022 // offsets). 1023 1024 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() : 1025 I->getOperand(0)->getType()); 1026 bool IsFPAccess = MemAccessTy->isFloatingPointTy(); 1027 bool IsVectorAccess = MemAccessTy->isVectorTy(); 1028 1029 // A store of an extracted vector element will be combined into a VSTE type 1030 // instruction. 1031 if (!IsVectorAccess && isa<StoreInst>(I)) { 1032 Value *DataOp = I->getOperand(0); 1033 if (isa<ExtractElementInst>(DataOp)) 1034 IsVectorAccess = true; 1035 } 1036 1037 // A load which gets inserted into a vector element will be combined into a 1038 // VLE type instruction. 1039 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) { 1040 User *LoadUser = *I->user_begin(); 1041 if (isa<InsertElementInst>(LoadUser)) 1042 IsVectorAccess = true; 1043 } 1044 1045 if (IsFPAccess || IsVectorAccess) 1046 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/); 1047 } 1048 1049 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/); 1050 } 1051 1052 bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1053 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const { 1054 // Punt on globals for now, although they can be used in limited 1055 // RELATIVE LONG cases. 1056 if (AM.BaseGV) 1057 return false; 1058 1059 // Require a 20-bit signed offset. 1060 if (!isInt<20>(AM.BaseOffs)) 1061 return false; 1062 1063 bool RequireD12 = Subtarget.hasVector() && Ty->isVectorTy(); 1064 AddressingMode SupportedAM(!RequireD12, true); 1065 if (I != nullptr) 1066 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector()); 1067 1068 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs)) 1069 return false; 1070 1071 if (!SupportedAM.IndexReg) 1072 // No indexing allowed. 1073 return AM.Scale == 0; 1074 else 1075 // Indexing is OK but no scale factor can be applied. 1076 return AM.Scale == 0 || AM.Scale == 1; 1077 } 1078 1079 bool SystemZTargetLowering::findOptimalMemOpLowering( 1080 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, 1081 unsigned SrcAS, const AttributeList &FuncAttributes) const { 1082 const int MVCFastLen = 16; 1083 1084 if (Limit != ~unsigned(0)) { 1085 // Don't expand Op into scalar loads/stores in these cases: 1086 if (Op.isMemcpy() && Op.allowOverlap() && Op.size() <= MVCFastLen) 1087 return false; // Small memcpy: Use MVC 1088 if (Op.isMemset() && Op.size() - 1 <= MVCFastLen) 1089 return false; // Small memset (first byte with STC/MVI): Use MVC 1090 if (Op.isZeroMemset()) 1091 return false; // Memset zero: Use XC 1092 } 1093 1094 return TargetLowering::findOptimalMemOpLowering(MemOps, Limit, Op, DstAS, 1095 SrcAS, FuncAttributes); 1096 } 1097 1098 EVT SystemZTargetLowering::getOptimalMemOpType(const MemOp &Op, 1099 const AttributeList &FuncAttributes) const { 1100 return Subtarget.hasVector() ? MVT::v2i64 : MVT::Other; 1101 } 1102 1103 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const { 1104 if (!FromType->isIntegerTy() || !ToType->isIntegerTy()) 1105 return false; 1106 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedValue(); 1107 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedValue(); 1108 return FromBits > ToBits; 1109 } 1110 1111 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const { 1112 if (!FromVT.isInteger() || !ToVT.isInteger()) 1113 return false; 1114 unsigned FromBits = FromVT.getFixedSizeInBits(); 1115 unsigned ToBits = ToVT.getFixedSizeInBits(); 1116 return FromBits > ToBits; 1117 } 1118 1119 //===----------------------------------------------------------------------===// 1120 // Inline asm support 1121 //===----------------------------------------------------------------------===// 1122 1123 TargetLowering::ConstraintType 1124 SystemZTargetLowering::getConstraintType(StringRef Constraint) const { 1125 if (Constraint.size() == 1) { 1126 switch (Constraint[0]) { 1127 case 'a': // Address register 1128 case 'd': // Data register (equivalent to 'r') 1129 case 'f': // Floating-point register 1130 case 'h': // High-part register 1131 case 'r': // General-purpose register 1132 case 'v': // Vector register 1133 return C_RegisterClass; 1134 1135 case 'Q': // Memory with base and unsigned 12-bit displacement 1136 case 'R': // Likewise, plus an index 1137 case 'S': // Memory with base and signed 20-bit displacement 1138 case 'T': // Likewise, plus an index 1139 case 'm': // Equivalent to 'T'. 1140 return C_Memory; 1141 1142 case 'I': // Unsigned 8-bit constant 1143 case 'J': // Unsigned 12-bit constant 1144 case 'K': // Signed 16-bit constant 1145 case 'L': // Signed 20-bit displacement (on all targets we support) 1146 case 'M': // 0x7fffffff 1147 return C_Immediate; 1148 1149 default: 1150 break; 1151 } 1152 } else if (Constraint.size() == 2 && Constraint[0] == 'Z') { 1153 switch (Constraint[1]) { 1154 case 'Q': // Address with base and unsigned 12-bit displacement 1155 case 'R': // Likewise, plus an index 1156 case 'S': // Address with base and signed 20-bit displacement 1157 case 'T': // Likewise, plus an index 1158 return C_Address; 1159 1160 default: 1161 break; 1162 } 1163 } 1164 return TargetLowering::getConstraintType(Constraint); 1165 } 1166 1167 TargetLowering::ConstraintWeight SystemZTargetLowering:: 1168 getSingleConstraintMatchWeight(AsmOperandInfo &info, 1169 const char *constraint) const { 1170 ConstraintWeight weight = CW_Invalid; 1171 Value *CallOperandVal = info.CallOperandVal; 1172 // If we don't have a value, we can't do a match, 1173 // but allow it at the lowest weight. 1174 if (!CallOperandVal) 1175 return CW_Default; 1176 Type *type = CallOperandVal->getType(); 1177 // Look at the constraint type. 1178 switch (*constraint) { 1179 default: 1180 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 1181 break; 1182 1183 case 'a': // Address register 1184 case 'd': // Data register (equivalent to 'r') 1185 case 'h': // High-part register 1186 case 'r': // General-purpose register 1187 weight = CallOperandVal->getType()->isIntegerTy() ? CW_Register : CW_Default; 1188 break; 1189 1190 case 'f': // Floating-point register 1191 if (!useSoftFloat()) 1192 weight = type->isFloatingPointTy() ? CW_Register : CW_Default; 1193 break; 1194 1195 case 'v': // Vector register 1196 if (Subtarget.hasVector()) 1197 weight = (type->isVectorTy() || type->isFloatingPointTy()) ? CW_Register 1198 : CW_Default; 1199 break; 1200 1201 case 'I': // Unsigned 8-bit constant 1202 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) 1203 if (isUInt<8>(C->getZExtValue())) 1204 weight = CW_Constant; 1205 break; 1206 1207 case 'J': // Unsigned 12-bit constant 1208 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) 1209 if (isUInt<12>(C->getZExtValue())) 1210 weight = CW_Constant; 1211 break; 1212 1213 case 'K': // Signed 16-bit constant 1214 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) 1215 if (isInt<16>(C->getSExtValue())) 1216 weight = CW_Constant; 1217 break; 1218 1219 case 'L': // Signed 20-bit displacement (on all targets we support) 1220 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) 1221 if (isInt<20>(C->getSExtValue())) 1222 weight = CW_Constant; 1223 break; 1224 1225 case 'M': // 0x7fffffff 1226 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) 1227 if (C->getZExtValue() == 0x7fffffff) 1228 weight = CW_Constant; 1229 break; 1230 } 1231 return weight; 1232 } 1233 1234 // Parse a "{tNNN}" register constraint for which the register type "t" 1235 // has already been verified. MC is the class associated with "t" and 1236 // Map maps 0-based register numbers to LLVM register numbers. 1237 static std::pair<unsigned, const TargetRegisterClass *> 1238 parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC, 1239 const unsigned *Map, unsigned Size) { 1240 assert(*(Constraint.end()-1) == '}' && "Missing '}'"); 1241 if (isdigit(Constraint[2])) { 1242 unsigned Index; 1243 bool Failed = 1244 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index); 1245 if (!Failed && Index < Size && Map[Index]) 1246 return std::make_pair(Map[Index], RC); 1247 } 1248 return std::make_pair(0U, nullptr); 1249 } 1250 1251 std::pair<unsigned, const TargetRegisterClass *> 1252 SystemZTargetLowering::getRegForInlineAsmConstraint( 1253 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 1254 if (Constraint.size() == 1) { 1255 // GCC Constraint Letters 1256 switch (Constraint[0]) { 1257 default: break; 1258 case 'd': // Data register (equivalent to 'r') 1259 case 'r': // General-purpose register 1260 if (VT.getSizeInBits() == 64) 1261 return std::make_pair(0U, &SystemZ::GR64BitRegClass); 1262 else if (VT.getSizeInBits() == 128) 1263 return std::make_pair(0U, &SystemZ::GR128BitRegClass); 1264 return std::make_pair(0U, &SystemZ::GR32BitRegClass); 1265 1266 case 'a': // Address register 1267 if (VT == MVT::i64) 1268 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass); 1269 else if (VT == MVT::i128) 1270 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass); 1271 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass); 1272 1273 case 'h': // High-part register (an LLVM extension) 1274 return std::make_pair(0U, &SystemZ::GRH32BitRegClass); 1275 1276 case 'f': // Floating-point register 1277 if (!useSoftFloat()) { 1278 if (VT.getSizeInBits() == 64) 1279 return std::make_pair(0U, &SystemZ::FP64BitRegClass); 1280 else if (VT.getSizeInBits() == 128) 1281 return std::make_pair(0U, &SystemZ::FP128BitRegClass); 1282 return std::make_pair(0U, &SystemZ::FP32BitRegClass); 1283 } 1284 break; 1285 1286 case 'v': // Vector register 1287 if (Subtarget.hasVector()) { 1288 if (VT.getSizeInBits() == 32) 1289 return std::make_pair(0U, &SystemZ::VR32BitRegClass); 1290 if (VT.getSizeInBits() == 64) 1291 return std::make_pair(0U, &SystemZ::VR64BitRegClass); 1292 return std::make_pair(0U, &SystemZ::VR128BitRegClass); 1293 } 1294 break; 1295 } 1296 } 1297 if (Constraint.size() > 0 && Constraint[0] == '{') { 1298 1299 // A clobber constraint (e.g. ~{f0}) will have MVT::Other which is illegal 1300 // to check the size on. 1301 auto getVTSizeInBits = [&VT]() { 1302 return VT == MVT::Other ? 0 : VT.getSizeInBits(); 1303 }; 1304 1305 // We need to override the default register parsing for GPRs and FPRs 1306 // because the interpretation depends on VT. The internal names of 1307 // the registers are also different from the external names 1308 // (F0D and F0S instead of F0, etc.). 1309 if (Constraint[1] == 'r') { 1310 if (getVTSizeInBits() == 32) 1311 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass, 1312 SystemZMC::GR32Regs, 16); 1313 if (getVTSizeInBits() == 128) 1314 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass, 1315 SystemZMC::GR128Regs, 16); 1316 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass, 1317 SystemZMC::GR64Regs, 16); 1318 } 1319 if (Constraint[1] == 'f') { 1320 if (useSoftFloat()) 1321 return std::make_pair( 1322 0u, static_cast<const TargetRegisterClass *>(nullptr)); 1323 if (getVTSizeInBits() == 32) 1324 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass, 1325 SystemZMC::FP32Regs, 16); 1326 if (getVTSizeInBits() == 128) 1327 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass, 1328 SystemZMC::FP128Regs, 16); 1329 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass, 1330 SystemZMC::FP64Regs, 16); 1331 } 1332 if (Constraint[1] == 'v') { 1333 if (!Subtarget.hasVector()) 1334 return std::make_pair( 1335 0u, static_cast<const TargetRegisterClass *>(nullptr)); 1336 if (getVTSizeInBits() == 32) 1337 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass, 1338 SystemZMC::VR32Regs, 32); 1339 if (getVTSizeInBits() == 64) 1340 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass, 1341 SystemZMC::VR64Regs, 32); 1342 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass, 1343 SystemZMC::VR128Regs, 32); 1344 } 1345 } 1346 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 1347 } 1348 1349 // FIXME? Maybe this could be a TableGen attribute on some registers and 1350 // this table could be generated automatically from RegInfo. 1351 Register 1352 SystemZTargetLowering::getRegisterByName(const char *RegName, LLT VT, 1353 const MachineFunction &MF) const { 1354 Register Reg = 1355 StringSwitch<Register>(RegName) 1356 .Case("r4", Subtarget.isTargetXPLINK64() ? SystemZ::R4D : 0) 1357 .Case("r15", Subtarget.isTargetELF() ? SystemZ::R15D : 0) 1358 .Default(0); 1359 1360 if (Reg) 1361 return Reg; 1362 report_fatal_error("Invalid register name global variable"); 1363 } 1364 1365 Register SystemZTargetLowering::getExceptionPointerRegister( 1366 const Constant *PersonalityFn) const { 1367 return Subtarget.isTargetXPLINK64() ? SystemZ::R1D : SystemZ::R6D; 1368 } 1369 1370 Register SystemZTargetLowering::getExceptionSelectorRegister( 1371 const Constant *PersonalityFn) const { 1372 return Subtarget.isTargetXPLINK64() ? SystemZ::R2D : SystemZ::R7D; 1373 } 1374 1375 void SystemZTargetLowering::LowerAsmOperandForConstraint( 1376 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops, 1377 SelectionDAG &DAG) const { 1378 // Only support length 1 constraints for now. 1379 if (Constraint.size() == 1) { 1380 switch (Constraint[0]) { 1381 case 'I': // Unsigned 8-bit constant 1382 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 1383 if (isUInt<8>(C->getZExtValue())) 1384 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op), 1385 Op.getValueType())); 1386 return; 1387 1388 case 'J': // Unsigned 12-bit constant 1389 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 1390 if (isUInt<12>(C->getZExtValue())) 1391 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op), 1392 Op.getValueType())); 1393 return; 1394 1395 case 'K': // Signed 16-bit constant 1396 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 1397 if (isInt<16>(C->getSExtValue())) 1398 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), 1399 Op.getValueType())); 1400 return; 1401 1402 case 'L': // Signed 20-bit displacement (on all targets we support) 1403 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 1404 if (isInt<20>(C->getSExtValue())) 1405 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), 1406 Op.getValueType())); 1407 return; 1408 1409 case 'M': // 0x7fffffff 1410 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 1411 if (C->getZExtValue() == 0x7fffffff) 1412 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op), 1413 Op.getValueType())); 1414 return; 1415 } 1416 } 1417 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 1418 } 1419 1420 //===----------------------------------------------------------------------===// 1421 // Calling conventions 1422 //===----------------------------------------------------------------------===// 1423 1424 #include "SystemZGenCallingConv.inc" 1425 1426 const MCPhysReg *SystemZTargetLowering::getScratchRegisters( 1427 CallingConv::ID) const { 1428 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D, 1429 SystemZ::R14D, 0 }; 1430 return ScratchRegs; 1431 } 1432 1433 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType, 1434 Type *ToType) const { 1435 return isTruncateFree(FromType, ToType); 1436 } 1437 1438 bool SystemZTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 1439 return CI->isTailCall(); 1440 } 1441 1442 // Value is a value that has been passed to us in the location described by VA 1443 // (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining 1444 // any loads onto Chain. 1445 static SDValue convertLocVTToValVT(SelectionDAG &DAG, const SDLoc &DL, 1446 CCValAssign &VA, SDValue Chain, 1447 SDValue Value) { 1448 // If the argument has been promoted from a smaller type, insert an 1449 // assertion to capture this. 1450 if (VA.getLocInfo() == CCValAssign::SExt) 1451 Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value, 1452 DAG.getValueType(VA.getValVT())); 1453 else if (VA.getLocInfo() == CCValAssign::ZExt) 1454 Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value, 1455 DAG.getValueType(VA.getValVT())); 1456 1457 if (VA.isExtInLoc()) 1458 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value); 1459 else if (VA.getLocInfo() == CCValAssign::BCvt) { 1460 // If this is a short vector argument loaded from the stack, 1461 // extend from i64 to full vector size and then bitcast. 1462 assert(VA.getLocVT() == MVT::i64); 1463 assert(VA.getValVT().isVector()); 1464 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)}); 1465 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value); 1466 } else 1467 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo"); 1468 return Value; 1469 } 1470 1471 // Value is a value of type VA.getValVT() that we need to copy into 1472 // the location described by VA. Return a copy of Value converted to 1473 // VA.getValVT(). The caller is responsible for handling indirect values. 1474 static SDValue convertValVTToLocVT(SelectionDAG &DAG, const SDLoc &DL, 1475 CCValAssign &VA, SDValue Value) { 1476 switch (VA.getLocInfo()) { 1477 case CCValAssign::SExt: 1478 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value); 1479 case CCValAssign::ZExt: 1480 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value); 1481 case CCValAssign::AExt: 1482 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value); 1483 case CCValAssign::BCvt: { 1484 assert(VA.getLocVT() == MVT::i64 || VA.getLocVT() == MVT::i128); 1485 assert(VA.getValVT().isVector() || VA.getValVT() == MVT::f32 || 1486 VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::f128); 1487 // For an f32 vararg we need to first promote it to an f64 and then 1488 // bitcast it to an i64. 1489 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i64) 1490 Value = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Value); 1491 MVT BitCastToType = VA.getValVT().isVector() && VA.getLocVT() == MVT::i64 1492 ? MVT::v2i64 1493 : VA.getLocVT(); 1494 Value = DAG.getNode(ISD::BITCAST, DL, BitCastToType, Value); 1495 // For ELF, this is a short vector argument to be stored to the stack, 1496 // bitcast to v2i64 and then extract first element. 1497 if (BitCastToType == MVT::v2i64) 1498 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value, 1499 DAG.getConstant(0, DL, MVT::i32)); 1500 return Value; 1501 } 1502 case CCValAssign::Full: 1503 return Value; 1504 default: 1505 llvm_unreachable("Unhandled getLocInfo()"); 1506 } 1507 } 1508 1509 static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In) { 1510 SDLoc DL(In); 1511 SDValue Lo, Hi; 1512 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) { 1513 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, In); 1514 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 1515 DAG.getNode(ISD::SRL, DL, MVT::i128, In, 1516 DAG.getConstant(64, DL, MVT::i32))); 1517 } else { 1518 std::tie(Lo, Hi) = DAG.SplitScalar(In, DL, MVT::i64, MVT::i64); 1519 } 1520 1521 SDNode *Pair = DAG.getMachineNode(SystemZ::PAIR128, DL, 1522 MVT::Untyped, Hi, Lo); 1523 return SDValue(Pair, 0); 1524 } 1525 1526 static SDValue lowerGR128ToI128(SelectionDAG &DAG, SDValue In) { 1527 SDLoc DL(In); 1528 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64, 1529 DL, MVT::i64, In); 1530 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64, 1531 DL, MVT::i64, In); 1532 1533 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) { 1534 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Lo); 1535 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Hi); 1536 Hi = DAG.getNode(ISD::SHL, DL, MVT::i128, Hi, 1537 DAG.getConstant(64, DL, MVT::i32)); 1538 return DAG.getNode(ISD::OR, DL, MVT::i128, Lo, Hi); 1539 } else { 1540 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi); 1541 } 1542 } 1543 1544 bool SystemZTargetLowering::splitValueIntoRegisterParts( 1545 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 1546 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const { 1547 EVT ValueVT = Val.getValueType(); 1548 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) { 1549 // Inline assembly operand. 1550 Parts[0] = lowerI128ToGR128(DAG, DAG.getBitcast(MVT::i128, Val)); 1551 return true; 1552 } 1553 1554 return false; 1555 } 1556 1557 SDValue SystemZTargetLowering::joinRegisterPartsIntoValue( 1558 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 1559 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const { 1560 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) { 1561 // Inline assembly operand. 1562 SDValue Res = lowerGR128ToI128(DAG, Parts[0]); 1563 return DAG.getBitcast(ValueVT, Res); 1564 } 1565 1566 return SDValue(); 1567 } 1568 1569 SDValue SystemZTargetLowering::LowerFormalArguments( 1570 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 1571 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1572 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1573 MachineFunction &MF = DAG.getMachineFunction(); 1574 MachineFrameInfo &MFI = MF.getFrameInfo(); 1575 MachineRegisterInfo &MRI = MF.getRegInfo(); 1576 SystemZMachineFunctionInfo *FuncInfo = 1577 MF.getInfo<SystemZMachineFunctionInfo>(); 1578 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>(); 1579 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 1580 1581 // Assign locations to all of the incoming arguments. 1582 SmallVector<CCValAssign, 16> ArgLocs; 1583 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 1584 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ); 1585 FuncInfo->setSizeOfFnParams(CCInfo.getStackSize()); 1586 1587 unsigned NumFixedGPRs = 0; 1588 unsigned NumFixedFPRs = 0; 1589 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 1590 SDValue ArgValue; 1591 CCValAssign &VA = ArgLocs[I]; 1592 EVT LocVT = VA.getLocVT(); 1593 if (VA.isRegLoc()) { 1594 // Arguments passed in registers 1595 const TargetRegisterClass *RC; 1596 switch (LocVT.getSimpleVT().SimpleTy) { 1597 default: 1598 // Integers smaller than i64 should be promoted to i64. 1599 llvm_unreachable("Unexpected argument type"); 1600 case MVT::i32: 1601 NumFixedGPRs += 1; 1602 RC = &SystemZ::GR32BitRegClass; 1603 break; 1604 case MVT::i64: 1605 NumFixedGPRs += 1; 1606 RC = &SystemZ::GR64BitRegClass; 1607 break; 1608 case MVT::f32: 1609 NumFixedFPRs += 1; 1610 RC = &SystemZ::FP32BitRegClass; 1611 break; 1612 case MVT::f64: 1613 NumFixedFPRs += 1; 1614 RC = &SystemZ::FP64BitRegClass; 1615 break; 1616 case MVT::f128: 1617 NumFixedFPRs += 2; 1618 RC = &SystemZ::FP128BitRegClass; 1619 break; 1620 case MVT::v16i8: 1621 case MVT::v8i16: 1622 case MVT::v4i32: 1623 case MVT::v2i64: 1624 case MVT::v4f32: 1625 case MVT::v2f64: 1626 RC = &SystemZ::VR128BitRegClass; 1627 break; 1628 } 1629 1630 Register VReg = MRI.createVirtualRegister(RC); 1631 MRI.addLiveIn(VA.getLocReg(), VReg); 1632 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 1633 } else { 1634 assert(VA.isMemLoc() && "Argument not register or memory"); 1635 1636 // Create the frame index object for this incoming parameter. 1637 // FIXME: Pre-include call frame size in the offset, should not 1638 // need to manually add it here. 1639 int64_t ArgSPOffset = VA.getLocMemOffset(); 1640 if (Subtarget.isTargetXPLINK64()) { 1641 auto &XPRegs = 1642 Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>(); 1643 ArgSPOffset += XPRegs.getCallFrameSize(); 1644 } 1645 int FI = 1646 MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, ArgSPOffset, true); 1647 1648 // Create the SelectionDAG nodes corresponding to a load 1649 // from this parameter. Unpromoted ints and floats are 1650 // passed as right-justified 8-byte values. 1651 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 1652 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32) 1653 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 1654 DAG.getIntPtrConstant(4, DL)); 1655 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN, 1656 MachinePointerInfo::getFixedStack(MF, FI)); 1657 } 1658 1659 // Convert the value of the argument register into the value that's 1660 // being passed. 1661 if (VA.getLocInfo() == CCValAssign::Indirect) { 1662 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 1663 MachinePointerInfo())); 1664 // If the original argument was split (e.g. i128), we need 1665 // to load all parts of it here (using the same address). 1666 unsigned ArgIndex = Ins[I].OrigArgIndex; 1667 assert (Ins[I].PartOffset == 0); 1668 while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) { 1669 CCValAssign &PartVA = ArgLocs[I + 1]; 1670 unsigned PartOffset = Ins[I + 1].PartOffset; 1671 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, 1672 DAG.getIntPtrConstant(PartOffset, DL)); 1673 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 1674 MachinePointerInfo())); 1675 ++I; 1676 } 1677 } else 1678 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue)); 1679 } 1680 1681 if (IsVarArg && Subtarget.isTargetXPLINK64()) { 1682 // Save the number of non-varargs registers for later use by va_start, etc. 1683 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs); 1684 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs); 1685 1686 auto *Regs = static_cast<SystemZXPLINK64Registers *>( 1687 Subtarget.getSpecialRegisters()); 1688 1689 // Likewise the address (in the form of a frame index) of where the 1690 // first stack vararg would be. The 1-byte size here is arbitrary. 1691 // FIXME: Pre-include call frame size in the offset, should not 1692 // need to manually add it here. 1693 int64_t VarArgOffset = CCInfo.getStackSize() + Regs->getCallFrameSize(); 1694 int FI = MFI.CreateFixedObject(1, VarArgOffset, true); 1695 FuncInfo->setVarArgsFrameIndex(FI); 1696 } 1697 1698 if (IsVarArg && Subtarget.isTargetELF()) { 1699 // Save the number of non-varargs registers for later use by va_start, etc. 1700 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs); 1701 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs); 1702 1703 // Likewise the address (in the form of a frame index) of where the 1704 // first stack vararg would be. The 1-byte size here is arbitrary. 1705 int64_t VarArgsOffset = CCInfo.getStackSize(); 1706 FuncInfo->setVarArgsFrameIndex( 1707 MFI.CreateFixedObject(1, VarArgsOffset, true)); 1708 1709 // ...and a similar frame index for the caller-allocated save area 1710 // that will be used to store the incoming registers. 1711 int64_t RegSaveOffset = 1712 -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16; 1713 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true); 1714 FuncInfo->setRegSaveFrameIndex(RegSaveIndex); 1715 1716 // Store the FPR varargs in the reserved frame slots. (We store the 1717 // GPRs as part of the prologue.) 1718 if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) { 1719 SDValue MemOps[SystemZ::ELFNumArgFPRs]; 1720 for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) { 1721 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]); 1722 int FI = 1723 MFI.CreateFixedObject(8, -SystemZMC::ELFCallFrameSize + Offset, true); 1724 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 1725 Register VReg = MF.addLiveIn(SystemZ::ELFArgFPRs[I], 1726 &SystemZ::FP64BitRegClass); 1727 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64); 1728 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN, 1729 MachinePointerInfo::getFixedStack(MF, FI)); 1730 } 1731 // Join the stores, which are independent of one another. 1732 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 1733 ArrayRef(&MemOps[NumFixedFPRs], 1734 SystemZ::ELFNumArgFPRs - NumFixedFPRs)); 1735 } 1736 } 1737 1738 if (Subtarget.isTargetXPLINK64()) { 1739 // Create virual register for handling incoming "ADA" special register (R5) 1740 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass; 1741 Register ADAvReg = MRI.createVirtualRegister(RC); 1742 auto *Regs = static_cast<SystemZXPLINK64Registers *>( 1743 Subtarget.getSpecialRegisters()); 1744 MRI.addLiveIn(Regs->getADARegister(), ADAvReg); 1745 FuncInfo->setADAVirtualRegister(ADAvReg); 1746 } 1747 return Chain; 1748 } 1749 1750 static bool canUseSiblingCall(const CCState &ArgCCInfo, 1751 SmallVectorImpl<CCValAssign> &ArgLocs, 1752 SmallVectorImpl<ISD::OutputArg> &Outs) { 1753 // Punt if there are any indirect or stack arguments, or if the call 1754 // needs the callee-saved argument register R6, or if the call uses 1755 // the callee-saved register arguments SwiftSelf and SwiftError. 1756 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 1757 CCValAssign &VA = ArgLocs[I]; 1758 if (VA.getLocInfo() == CCValAssign::Indirect) 1759 return false; 1760 if (!VA.isRegLoc()) 1761 return false; 1762 Register Reg = VA.getLocReg(); 1763 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D) 1764 return false; 1765 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError()) 1766 return false; 1767 } 1768 return true; 1769 } 1770 1771 static SDValue getADAEntry(SelectionDAG &DAG, SDValue Val, SDLoc DL, 1772 unsigned Offset, bool LoadAdr = false) { 1773 MachineFunction &MF = DAG.getMachineFunction(); 1774 SystemZMachineFunctionInfo *MFI = MF.getInfo<SystemZMachineFunctionInfo>(); 1775 unsigned ADAvReg = MFI->getADAVirtualRegister(); 1776 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1777 1778 SDValue Reg = DAG.getRegister(ADAvReg, PtrVT); 1779 SDValue Ofs = DAG.getTargetConstant(Offset, DL, PtrVT); 1780 1781 SDValue Result = DAG.getNode(SystemZISD::ADA_ENTRY, DL, PtrVT, Val, Reg, Ofs); 1782 if (!LoadAdr) 1783 Result = DAG.getLoad( 1784 PtrVT, DL, DAG.getEntryNode(), Result, MachinePointerInfo(), Align(8), 1785 MachineMemOperand::MODereferenceable | MachineMemOperand::MOInvariant); 1786 1787 return Result; 1788 } 1789 1790 // ADA access using Global value 1791 // Note: for functions, address of descriptor is returned 1792 static SDValue getADAEntry(SelectionDAG &DAG, const GlobalValue *GV, SDLoc DL, 1793 EVT PtrVT) { 1794 unsigned ADAtype; 1795 bool LoadAddr = false; 1796 const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV); 1797 bool IsFunction = 1798 (isa<Function>(GV)) || (GA && isa<Function>(GA->getAliaseeObject())); 1799 bool IsInternal = (GV->hasInternalLinkage() || GV->hasPrivateLinkage()); 1800 1801 if (IsFunction) { 1802 if (IsInternal) { 1803 ADAtype = SystemZII::MO_ADA_DIRECT_FUNC_DESC; 1804 LoadAddr = true; 1805 } else 1806 ADAtype = SystemZII::MO_ADA_INDIRECT_FUNC_DESC; 1807 } else { 1808 ADAtype = SystemZII::MO_ADA_DATA_SYMBOL_ADDR; 1809 } 1810 SDValue Val = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ADAtype); 1811 1812 return getADAEntry(DAG, Val, DL, 0, LoadAddr); 1813 } 1814 1815 static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA, 1816 SDLoc &DL, SDValue &Chain) { 1817 unsigned ADADelta = 0; // ADA offset in desc. 1818 unsigned EPADelta = 8; // EPA offset in desc. 1819 MachineFunction &MF = DAG.getMachineFunction(); 1820 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1821 1822 // XPLink calling convention. 1823 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1824 bool IsInternal = (G->getGlobal()->hasInternalLinkage() || 1825 G->getGlobal()->hasPrivateLinkage()); 1826 if (IsInternal) { 1827 SystemZMachineFunctionInfo *MFI = 1828 MF.getInfo<SystemZMachineFunctionInfo>(); 1829 unsigned ADAvReg = MFI->getADAVirtualRegister(); 1830 ADA = DAG.getCopyFromReg(Chain, DL, ADAvReg, PtrVT); 1831 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT); 1832 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee); 1833 return true; 1834 } else { 1835 SDValue GA = DAG.getTargetGlobalAddress( 1836 G->getGlobal(), DL, PtrVT, 0, SystemZII::MO_ADA_DIRECT_FUNC_DESC); 1837 ADA = getADAEntry(DAG, GA, DL, ADADelta); 1838 Callee = getADAEntry(DAG, GA, DL, EPADelta); 1839 } 1840 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1841 SDValue ES = DAG.getTargetExternalSymbol( 1842 E->getSymbol(), PtrVT, SystemZII::MO_ADA_DIRECT_FUNC_DESC); 1843 ADA = getADAEntry(DAG, ES, DL, ADADelta); 1844 Callee = getADAEntry(DAG, ES, DL, EPADelta); 1845 } else { 1846 // Function pointer case 1847 ADA = DAG.getNode(ISD::ADD, DL, PtrVT, Callee, 1848 DAG.getConstant(ADADelta, DL, PtrVT)); 1849 ADA = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), ADA, 1850 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 1851 Callee = DAG.getNode(ISD::ADD, DL, PtrVT, Callee, 1852 DAG.getConstant(EPADelta, DL, PtrVT)); 1853 Callee = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Callee, 1854 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 1855 } 1856 return false; 1857 } 1858 1859 SDValue 1860 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI, 1861 SmallVectorImpl<SDValue> &InVals) const { 1862 SelectionDAG &DAG = CLI.DAG; 1863 SDLoc &DL = CLI.DL; 1864 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1865 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1866 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1867 SDValue Chain = CLI.Chain; 1868 SDValue Callee = CLI.Callee; 1869 bool &IsTailCall = CLI.IsTailCall; 1870 CallingConv::ID CallConv = CLI.CallConv; 1871 bool IsVarArg = CLI.IsVarArg; 1872 MachineFunction &MF = DAG.getMachineFunction(); 1873 EVT PtrVT = getPointerTy(MF.getDataLayout()); 1874 LLVMContext &Ctx = *DAG.getContext(); 1875 SystemZCallingConventionRegisters *Regs = Subtarget.getSpecialRegisters(); 1876 1877 // FIXME: z/OS support to be added in later. 1878 if (Subtarget.isTargetXPLINK64()) 1879 IsTailCall = false; 1880 1881 // Analyze the operands of the call, assigning locations to each operand. 1882 SmallVector<CCValAssign, 16> ArgLocs; 1883 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx); 1884 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ); 1885 1886 // We don't support GuaranteedTailCallOpt, only automatically-detected 1887 // sibling calls. 1888 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs)) 1889 IsTailCall = false; 1890 1891 // Get a count of how many bytes are to be pushed on the stack. 1892 unsigned NumBytes = ArgCCInfo.getStackSize(); 1893 1894 // Mark the start of the call. 1895 if (!IsTailCall) 1896 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 1897 1898 // Copy argument values to their designated locations. 1899 SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass; 1900 SmallVector<SDValue, 8> MemOpChains; 1901 SDValue StackPtr; 1902 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 1903 CCValAssign &VA = ArgLocs[I]; 1904 SDValue ArgValue = OutVals[I]; 1905 1906 if (VA.getLocInfo() == CCValAssign::Indirect) { 1907 // Store the argument in a stack slot and pass its address. 1908 unsigned ArgIndex = Outs[I].OrigArgIndex; 1909 EVT SlotVT; 1910 if (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) { 1911 // Allocate the full stack space for a promoted (and split) argument. 1912 Type *OrigArgType = CLI.Args[Outs[I].OrigArgIndex].Ty; 1913 EVT OrigArgVT = getValueType(MF.getDataLayout(), OrigArgType); 1914 MVT PartVT = getRegisterTypeForCallingConv(Ctx, CLI.CallConv, OrigArgVT); 1915 unsigned N = getNumRegistersForCallingConv(Ctx, CLI.CallConv, OrigArgVT); 1916 SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * N); 1917 } else { 1918 SlotVT = Outs[I].ArgVT; 1919 } 1920 SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT); 1921 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 1922 MemOpChains.push_back( 1923 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 1924 MachinePointerInfo::getFixedStack(MF, FI))); 1925 // If the original argument was split (e.g. i128), we need 1926 // to store all parts of it here (and pass just one address). 1927 assert (Outs[I].PartOffset == 0); 1928 while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) { 1929 SDValue PartValue = OutVals[I + 1]; 1930 unsigned PartOffset = Outs[I + 1].PartOffset; 1931 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, 1932 DAG.getIntPtrConstant(PartOffset, DL)); 1933 MemOpChains.push_back( 1934 DAG.getStore(Chain, DL, PartValue, Address, 1935 MachinePointerInfo::getFixedStack(MF, FI))); 1936 assert((PartOffset + PartValue.getValueType().getStoreSize() <= 1937 SlotVT.getStoreSize()) && "Not enough space for argument part!"); 1938 ++I; 1939 } 1940 ArgValue = SpillSlot; 1941 } else 1942 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue); 1943 1944 if (VA.isRegLoc()) { 1945 // In XPLINK64, for the 128-bit vararg case, ArgValue is bitcasted to a 1946 // MVT::i128 type. We decompose the 128-bit type to a pair of its high 1947 // and low values. 1948 if (VA.getLocVT() == MVT::i128) 1949 ArgValue = lowerI128ToGR128(DAG, ArgValue); 1950 // Queue up the argument copies and emit them at the end. 1951 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 1952 } else { 1953 assert(VA.isMemLoc() && "Argument not register or memory"); 1954 1955 // Work out the address of the stack slot. Unpromoted ints and 1956 // floats are passed as right-justified 8-byte values. 1957 if (!StackPtr.getNode()) 1958 StackPtr = DAG.getCopyFromReg(Chain, DL, 1959 Regs->getStackPointerRegister(), PtrVT); 1960 unsigned Offset = Regs->getStackPointerBias() + Regs->getCallFrameSize() + 1961 VA.getLocMemOffset(); 1962 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32) 1963 Offset += 4; 1964 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 1965 DAG.getIntPtrConstant(Offset, DL)); 1966 1967 // Emit the store. 1968 MemOpChains.push_back( 1969 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 1970 1971 // Although long doubles or vectors are passed through the stack when 1972 // they are vararg (non-fixed arguments), if a long double or vector 1973 // occupies the third and fourth slot of the argument list GPR3 should 1974 // still shadow the third slot of the argument list. 1975 if (Subtarget.isTargetXPLINK64() && VA.needsCustom()) { 1976 SDValue ShadowArgValue = 1977 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, ArgValue, 1978 DAG.getIntPtrConstant(1, DL)); 1979 RegsToPass.push_back(std::make_pair(SystemZ::R3D, ShadowArgValue)); 1980 } 1981 } 1982 } 1983 1984 // Join the stores, which are independent of one another. 1985 if (!MemOpChains.empty()) 1986 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 1987 1988 // Accept direct calls by converting symbolic call addresses to the 1989 // associated Target* opcodes. Force %r1 to be used for indirect 1990 // tail calls. 1991 SDValue Glue; 1992 1993 if (Subtarget.isTargetXPLINK64()) { 1994 SDValue ADA; 1995 bool IsBRASL = getzOSCalleeAndADA(DAG, Callee, ADA, DL, Chain); 1996 if (!IsBRASL) { 1997 unsigned CalleeReg = static_cast<SystemZXPLINK64Registers *>(Regs) 1998 ->getAddressOfCalleeRegister(); 1999 Chain = DAG.getCopyToReg(Chain, DL, CalleeReg, Callee, Glue); 2000 Glue = Chain.getValue(1); 2001 Callee = DAG.getRegister(CalleeReg, Callee.getValueType()); 2002 } 2003 RegsToPass.push_back(std::make_pair( 2004 static_cast<SystemZXPLINK64Registers *>(Regs)->getADARegister(), ADA)); 2005 } else { 2006 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2007 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT); 2008 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee); 2009 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2010 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT); 2011 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee); 2012 } else if (IsTailCall) { 2013 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue); 2014 Glue = Chain.getValue(1); 2015 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType()); 2016 } 2017 } 2018 2019 // Build a sequence of copy-to-reg nodes, chained and glued together. 2020 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) { 2021 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first, 2022 RegsToPass[I].second, Glue); 2023 Glue = Chain.getValue(1); 2024 } 2025 2026 // The first call operand is the chain and the second is the target address. 2027 SmallVector<SDValue, 8> Ops; 2028 Ops.push_back(Chain); 2029 Ops.push_back(Callee); 2030 2031 // Add argument registers to the end of the list so that they are 2032 // known live into the call. 2033 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) 2034 Ops.push_back(DAG.getRegister(RegsToPass[I].first, 2035 RegsToPass[I].second.getValueType())); 2036 2037 // Add a register mask operand representing the call-preserved registers. 2038 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 2039 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2040 assert(Mask && "Missing call preserved mask for calling convention"); 2041 Ops.push_back(DAG.getRegisterMask(Mask)); 2042 2043 // Glue the call to the argument copies, if any. 2044 if (Glue.getNode()) 2045 Ops.push_back(Glue); 2046 2047 // Emit the call. 2048 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2049 if (IsTailCall) { 2050 SDValue Ret = DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops); 2051 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge); 2052 return Ret; 2053 } 2054 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops); 2055 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 2056 Glue = Chain.getValue(1); 2057 2058 // Mark the end of the call, which is glued to the call itself. 2059 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL); 2060 Glue = Chain.getValue(1); 2061 2062 // Assign locations to each value returned by this call. 2063 SmallVector<CCValAssign, 16> RetLocs; 2064 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx); 2065 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ); 2066 2067 // Copy all of the result registers out of their specified physreg. 2068 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) { 2069 CCValAssign &VA = RetLocs[I]; 2070 2071 // Copy the value out, gluing the copy to the end of the call sequence. 2072 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), 2073 VA.getLocVT(), Glue); 2074 Chain = RetValue.getValue(1); 2075 Glue = RetValue.getValue(2); 2076 2077 // Convert the value of the return register into the value that's 2078 // being returned. 2079 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue)); 2080 } 2081 2082 return Chain; 2083 } 2084 2085 // Generate a call taking the given operands as arguments and returning a 2086 // result of type RetVT. 2087 std::pair<SDValue, SDValue> SystemZTargetLowering::makeExternalCall( 2088 SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT, 2089 ArrayRef<SDValue> Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL, 2090 bool DoesNotReturn, bool IsReturnValueUsed) const { 2091 TargetLowering::ArgListTy Args; 2092 Args.reserve(Ops.size()); 2093 2094 TargetLowering::ArgListEntry Entry; 2095 for (SDValue Op : Ops) { 2096 Entry.Node = Op; 2097 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 2098 Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), IsSigned); 2099 Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), IsSigned); 2100 Args.push_back(Entry); 2101 } 2102 2103 SDValue Callee = 2104 DAG.getExternalSymbol(CalleeName, getPointerTy(DAG.getDataLayout())); 2105 2106 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2107 TargetLowering::CallLoweringInfo CLI(DAG); 2108 bool SignExtend = shouldSignExtendTypeInLibCall(RetVT, IsSigned); 2109 CLI.setDebugLoc(DL) 2110 .setChain(Chain) 2111 .setCallee(CallConv, RetTy, Callee, std::move(Args)) 2112 .setNoReturn(DoesNotReturn) 2113 .setDiscardResult(!IsReturnValueUsed) 2114 .setSExtResult(SignExtend) 2115 .setZExtResult(!SignExtend); 2116 return LowerCallTo(CLI); 2117 } 2118 2119 bool SystemZTargetLowering:: 2120 CanLowerReturn(CallingConv::ID CallConv, 2121 MachineFunction &MF, bool isVarArg, 2122 const SmallVectorImpl<ISD::OutputArg> &Outs, 2123 LLVMContext &Context) const { 2124 // Special case that we cannot easily detect in RetCC_SystemZ since 2125 // i128 may not be a legal type. 2126 for (auto &Out : Outs) 2127 if (Out.ArgVT == MVT::i128) 2128 return false; 2129 2130 SmallVector<CCValAssign, 16> RetLocs; 2131 CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context); 2132 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ); 2133 } 2134 2135 SDValue 2136 SystemZTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2137 bool IsVarArg, 2138 const SmallVectorImpl<ISD::OutputArg> &Outs, 2139 const SmallVectorImpl<SDValue> &OutVals, 2140 const SDLoc &DL, SelectionDAG &DAG) const { 2141 MachineFunction &MF = DAG.getMachineFunction(); 2142 2143 // Assign locations to each returned value. 2144 SmallVector<CCValAssign, 16> RetLocs; 2145 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext()); 2146 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ); 2147 2148 // Quick exit for void returns 2149 if (RetLocs.empty()) 2150 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, Chain); 2151 2152 if (CallConv == CallingConv::GHC) 2153 report_fatal_error("GHC functions return void only"); 2154 2155 // Copy the result values into the output registers. 2156 SDValue Glue; 2157 SmallVector<SDValue, 4> RetOps; 2158 RetOps.push_back(Chain); 2159 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) { 2160 CCValAssign &VA = RetLocs[I]; 2161 SDValue RetValue = OutVals[I]; 2162 2163 // Make the return register live on exit. 2164 assert(VA.isRegLoc() && "Can only return in registers!"); 2165 2166 // Promote the value as required. 2167 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue); 2168 2169 // Chain and glue the copies together. 2170 Register Reg = VA.getLocReg(); 2171 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue); 2172 Glue = Chain.getValue(1); 2173 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT())); 2174 } 2175 2176 // Update chain and glue. 2177 RetOps[0] = Chain; 2178 if (Glue.getNode()) 2179 RetOps.push_back(Glue); 2180 2181 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, RetOps); 2182 } 2183 2184 // Return true if Op is an intrinsic node with chain that returns the CC value 2185 // as its only (other) argument. Provide the associated SystemZISD opcode and 2186 // the mask of valid CC values if so. 2187 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode, 2188 unsigned &CCValid) { 2189 unsigned Id = Op.getConstantOperandVal(1); 2190 switch (Id) { 2191 case Intrinsic::s390_tbegin: 2192 Opcode = SystemZISD::TBEGIN; 2193 CCValid = SystemZ::CCMASK_TBEGIN; 2194 return true; 2195 2196 case Intrinsic::s390_tbegin_nofloat: 2197 Opcode = SystemZISD::TBEGIN_NOFLOAT; 2198 CCValid = SystemZ::CCMASK_TBEGIN; 2199 return true; 2200 2201 case Intrinsic::s390_tend: 2202 Opcode = SystemZISD::TEND; 2203 CCValid = SystemZ::CCMASK_TEND; 2204 return true; 2205 2206 default: 2207 return false; 2208 } 2209 } 2210 2211 // Return true if Op is an intrinsic node without chain that returns the 2212 // CC value as its final argument. Provide the associated SystemZISD 2213 // opcode and the mask of valid CC values if so. 2214 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) { 2215 unsigned Id = Op.getConstantOperandVal(0); 2216 switch (Id) { 2217 case Intrinsic::s390_vpkshs: 2218 case Intrinsic::s390_vpksfs: 2219 case Intrinsic::s390_vpksgs: 2220 Opcode = SystemZISD::PACKS_CC; 2221 CCValid = SystemZ::CCMASK_VCMP; 2222 return true; 2223 2224 case Intrinsic::s390_vpklshs: 2225 case Intrinsic::s390_vpklsfs: 2226 case Intrinsic::s390_vpklsgs: 2227 Opcode = SystemZISD::PACKLS_CC; 2228 CCValid = SystemZ::CCMASK_VCMP; 2229 return true; 2230 2231 case Intrinsic::s390_vceqbs: 2232 case Intrinsic::s390_vceqhs: 2233 case Intrinsic::s390_vceqfs: 2234 case Intrinsic::s390_vceqgs: 2235 Opcode = SystemZISD::VICMPES; 2236 CCValid = SystemZ::CCMASK_VCMP; 2237 return true; 2238 2239 case Intrinsic::s390_vchbs: 2240 case Intrinsic::s390_vchhs: 2241 case Intrinsic::s390_vchfs: 2242 case Intrinsic::s390_vchgs: 2243 Opcode = SystemZISD::VICMPHS; 2244 CCValid = SystemZ::CCMASK_VCMP; 2245 return true; 2246 2247 case Intrinsic::s390_vchlbs: 2248 case Intrinsic::s390_vchlhs: 2249 case Intrinsic::s390_vchlfs: 2250 case Intrinsic::s390_vchlgs: 2251 Opcode = SystemZISD::VICMPHLS; 2252 CCValid = SystemZ::CCMASK_VCMP; 2253 return true; 2254 2255 case Intrinsic::s390_vtm: 2256 Opcode = SystemZISD::VTM; 2257 CCValid = SystemZ::CCMASK_VCMP; 2258 return true; 2259 2260 case Intrinsic::s390_vfaebs: 2261 case Intrinsic::s390_vfaehs: 2262 case Intrinsic::s390_vfaefs: 2263 Opcode = SystemZISD::VFAE_CC; 2264 CCValid = SystemZ::CCMASK_ANY; 2265 return true; 2266 2267 case Intrinsic::s390_vfaezbs: 2268 case Intrinsic::s390_vfaezhs: 2269 case Intrinsic::s390_vfaezfs: 2270 Opcode = SystemZISD::VFAEZ_CC; 2271 CCValid = SystemZ::CCMASK_ANY; 2272 return true; 2273 2274 case Intrinsic::s390_vfeebs: 2275 case Intrinsic::s390_vfeehs: 2276 case Intrinsic::s390_vfeefs: 2277 Opcode = SystemZISD::VFEE_CC; 2278 CCValid = SystemZ::CCMASK_ANY; 2279 return true; 2280 2281 case Intrinsic::s390_vfeezbs: 2282 case Intrinsic::s390_vfeezhs: 2283 case Intrinsic::s390_vfeezfs: 2284 Opcode = SystemZISD::VFEEZ_CC; 2285 CCValid = SystemZ::CCMASK_ANY; 2286 return true; 2287 2288 case Intrinsic::s390_vfenebs: 2289 case Intrinsic::s390_vfenehs: 2290 case Intrinsic::s390_vfenefs: 2291 Opcode = SystemZISD::VFENE_CC; 2292 CCValid = SystemZ::CCMASK_ANY; 2293 return true; 2294 2295 case Intrinsic::s390_vfenezbs: 2296 case Intrinsic::s390_vfenezhs: 2297 case Intrinsic::s390_vfenezfs: 2298 Opcode = SystemZISD::VFENEZ_CC; 2299 CCValid = SystemZ::CCMASK_ANY; 2300 return true; 2301 2302 case Intrinsic::s390_vistrbs: 2303 case Intrinsic::s390_vistrhs: 2304 case Intrinsic::s390_vistrfs: 2305 Opcode = SystemZISD::VISTR_CC; 2306 CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3; 2307 return true; 2308 2309 case Intrinsic::s390_vstrcbs: 2310 case Intrinsic::s390_vstrchs: 2311 case Intrinsic::s390_vstrcfs: 2312 Opcode = SystemZISD::VSTRC_CC; 2313 CCValid = SystemZ::CCMASK_ANY; 2314 return true; 2315 2316 case Intrinsic::s390_vstrczbs: 2317 case Intrinsic::s390_vstrczhs: 2318 case Intrinsic::s390_vstrczfs: 2319 Opcode = SystemZISD::VSTRCZ_CC; 2320 CCValid = SystemZ::CCMASK_ANY; 2321 return true; 2322 2323 case Intrinsic::s390_vstrsb: 2324 case Intrinsic::s390_vstrsh: 2325 case Intrinsic::s390_vstrsf: 2326 Opcode = SystemZISD::VSTRS_CC; 2327 CCValid = SystemZ::CCMASK_ANY; 2328 return true; 2329 2330 case Intrinsic::s390_vstrszb: 2331 case Intrinsic::s390_vstrszh: 2332 case Intrinsic::s390_vstrszf: 2333 Opcode = SystemZISD::VSTRSZ_CC; 2334 CCValid = SystemZ::CCMASK_ANY; 2335 return true; 2336 2337 case Intrinsic::s390_vfcedbs: 2338 case Intrinsic::s390_vfcesbs: 2339 Opcode = SystemZISD::VFCMPES; 2340 CCValid = SystemZ::CCMASK_VCMP; 2341 return true; 2342 2343 case Intrinsic::s390_vfchdbs: 2344 case Intrinsic::s390_vfchsbs: 2345 Opcode = SystemZISD::VFCMPHS; 2346 CCValid = SystemZ::CCMASK_VCMP; 2347 return true; 2348 2349 case Intrinsic::s390_vfchedbs: 2350 case Intrinsic::s390_vfchesbs: 2351 Opcode = SystemZISD::VFCMPHES; 2352 CCValid = SystemZ::CCMASK_VCMP; 2353 return true; 2354 2355 case Intrinsic::s390_vftcidb: 2356 case Intrinsic::s390_vftcisb: 2357 Opcode = SystemZISD::VFTCI; 2358 CCValid = SystemZ::CCMASK_VCMP; 2359 return true; 2360 2361 case Intrinsic::s390_tdc: 2362 Opcode = SystemZISD::TDC; 2363 CCValid = SystemZ::CCMASK_TDC; 2364 return true; 2365 2366 default: 2367 return false; 2368 } 2369 } 2370 2371 // Emit an intrinsic with chain and an explicit CC register result. 2372 static SDNode *emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op, 2373 unsigned Opcode) { 2374 // Copy all operands except the intrinsic ID. 2375 unsigned NumOps = Op.getNumOperands(); 2376 SmallVector<SDValue, 6> Ops; 2377 Ops.reserve(NumOps - 1); 2378 Ops.push_back(Op.getOperand(0)); 2379 for (unsigned I = 2; I < NumOps; ++I) 2380 Ops.push_back(Op.getOperand(I)); 2381 2382 assert(Op->getNumValues() == 2 && "Expected only CC result and chain"); 2383 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other); 2384 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops); 2385 SDValue OldChain = SDValue(Op.getNode(), 1); 2386 SDValue NewChain = SDValue(Intr.getNode(), 1); 2387 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain); 2388 return Intr.getNode(); 2389 } 2390 2391 // Emit an intrinsic with an explicit CC register result. 2392 static SDNode *emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op, 2393 unsigned Opcode) { 2394 // Copy all operands except the intrinsic ID. 2395 unsigned NumOps = Op.getNumOperands(); 2396 SmallVector<SDValue, 6> Ops; 2397 Ops.reserve(NumOps - 1); 2398 for (unsigned I = 1; I < NumOps; ++I) 2399 Ops.push_back(Op.getOperand(I)); 2400 2401 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), Op->getVTList(), Ops); 2402 return Intr.getNode(); 2403 } 2404 2405 // CC is a comparison that will be implemented using an integer or 2406 // floating-point comparison. Return the condition code mask for 2407 // a branch on true. In the integer case, CCMASK_CMP_UO is set for 2408 // unsigned comparisons and clear for signed ones. In the floating-point 2409 // case, CCMASK_CMP_UO has its normal mask meaning (unordered). 2410 static unsigned CCMaskForCondCode(ISD::CondCode CC) { 2411 #define CONV(X) \ 2412 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \ 2413 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \ 2414 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X 2415 2416 switch (CC) { 2417 default: 2418 llvm_unreachable("Invalid integer condition!"); 2419 2420 CONV(EQ); 2421 CONV(NE); 2422 CONV(GT); 2423 CONV(GE); 2424 CONV(LT); 2425 CONV(LE); 2426 2427 case ISD::SETO: return SystemZ::CCMASK_CMP_O; 2428 case ISD::SETUO: return SystemZ::CCMASK_CMP_UO; 2429 } 2430 #undef CONV 2431 } 2432 2433 // If C can be converted to a comparison against zero, adjust the operands 2434 // as necessary. 2435 static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) { 2436 if (C.ICmpType == SystemZICMP::UnsignedOnly) 2437 return; 2438 2439 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode()); 2440 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64) 2441 return; 2442 2443 int64_t Value = ConstOp1->getSExtValue(); 2444 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) || 2445 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) || 2446 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) || 2447 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) { 2448 C.CCMask ^= SystemZ::CCMASK_CMP_EQ; 2449 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType()); 2450 } 2451 } 2452 2453 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI, 2454 // adjust the operands as necessary. 2455 static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL, 2456 Comparison &C) { 2457 // For us to make any changes, it must a comparison between a single-use 2458 // load and a constant. 2459 if (!C.Op0.hasOneUse() || 2460 C.Op0.getOpcode() != ISD::LOAD || 2461 C.Op1.getOpcode() != ISD::Constant) 2462 return; 2463 2464 // We must have an 8- or 16-bit load. 2465 auto *Load = cast<LoadSDNode>(C.Op0); 2466 unsigned NumBits = Load->getMemoryVT().getSizeInBits(); 2467 if ((NumBits != 8 && NumBits != 16) || 2468 NumBits != Load->getMemoryVT().getStoreSizeInBits()) 2469 return; 2470 2471 // The load must be an extending one and the constant must be within the 2472 // range of the unextended value. 2473 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1); 2474 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64) 2475 return; 2476 uint64_t Value = ConstOp1->getZExtValue(); 2477 uint64_t Mask = (1 << NumBits) - 1; 2478 if (Load->getExtensionType() == ISD::SEXTLOAD) { 2479 // Make sure that ConstOp1 is in range of C.Op0. 2480 int64_t SignedValue = ConstOp1->getSExtValue(); 2481 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask) 2482 return; 2483 if (C.ICmpType != SystemZICMP::SignedOnly) { 2484 // Unsigned comparison between two sign-extended values is equivalent 2485 // to unsigned comparison between two zero-extended values. 2486 Value &= Mask; 2487 } else if (NumBits == 8) { 2488 // Try to treat the comparison as unsigned, so that we can use CLI. 2489 // Adjust CCMask and Value as necessary. 2490 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT) 2491 // Test whether the high bit of the byte is set. 2492 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT; 2493 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE) 2494 // Test whether the high bit of the byte is clear. 2495 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT; 2496 else 2497 // No instruction exists for this combination. 2498 return; 2499 C.ICmpType = SystemZICMP::UnsignedOnly; 2500 } 2501 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) { 2502 if (Value > Mask) 2503 return; 2504 // If the constant is in range, we can use any comparison. 2505 C.ICmpType = SystemZICMP::Any; 2506 } else 2507 return; 2508 2509 // Make sure that the first operand is an i32 of the right extension type. 2510 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ? 2511 ISD::SEXTLOAD : 2512 ISD::ZEXTLOAD); 2513 if (C.Op0.getValueType() != MVT::i32 || 2514 Load->getExtensionType() != ExtType) { 2515 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(), 2516 Load->getBasePtr(), Load->getPointerInfo(), 2517 Load->getMemoryVT(), Load->getAlign(), 2518 Load->getMemOperand()->getFlags()); 2519 // Update the chain uses. 2520 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1)); 2521 } 2522 2523 // Make sure that the second operand is an i32 with the right value. 2524 if (C.Op1.getValueType() != MVT::i32 || 2525 Value != ConstOp1->getZExtValue()) 2526 C.Op1 = DAG.getConstant(Value, DL, MVT::i32); 2527 } 2528 2529 // Return true if Op is either an unextended load, or a load suitable 2530 // for integer register-memory comparisons of type ICmpType. 2531 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) { 2532 auto *Load = dyn_cast<LoadSDNode>(Op.getNode()); 2533 if (Load) { 2534 // There are no instructions to compare a register with a memory byte. 2535 if (Load->getMemoryVT() == MVT::i8) 2536 return false; 2537 // Otherwise decide on extension type. 2538 switch (Load->getExtensionType()) { 2539 case ISD::NON_EXTLOAD: 2540 return true; 2541 case ISD::SEXTLOAD: 2542 return ICmpType != SystemZICMP::UnsignedOnly; 2543 case ISD::ZEXTLOAD: 2544 return ICmpType != SystemZICMP::SignedOnly; 2545 default: 2546 break; 2547 } 2548 } 2549 return false; 2550 } 2551 2552 // Return true if it is better to swap the operands of C. 2553 static bool shouldSwapCmpOperands(const Comparison &C) { 2554 // Leave i128 and f128 comparisons alone, since they have no memory forms. 2555 if (C.Op0.getValueType() == MVT::i128) 2556 return false; 2557 if (C.Op0.getValueType() == MVT::f128) 2558 return false; 2559 2560 // Always keep a floating-point constant second, since comparisons with 2561 // zero can use LOAD TEST and comparisons with other constants make a 2562 // natural memory operand. 2563 if (isa<ConstantFPSDNode>(C.Op1)) 2564 return false; 2565 2566 // Never swap comparisons with zero since there are many ways to optimize 2567 // those later. 2568 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1); 2569 if (ConstOp1 && ConstOp1->getZExtValue() == 0) 2570 return false; 2571 2572 // Also keep natural memory operands second if the loaded value is 2573 // only used here. Several comparisons have memory forms. 2574 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse()) 2575 return false; 2576 2577 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't. 2578 // In that case we generally prefer the memory to be second. 2579 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) { 2580 // The only exceptions are when the second operand is a constant and 2581 // we can use things like CHHSI. 2582 if (!ConstOp1) 2583 return true; 2584 // The unsigned memory-immediate instructions can handle 16-bit 2585 // unsigned integers. 2586 if (C.ICmpType != SystemZICMP::SignedOnly && 2587 isUInt<16>(ConstOp1->getZExtValue())) 2588 return false; 2589 // The signed memory-immediate instructions can handle 16-bit 2590 // signed integers. 2591 if (C.ICmpType != SystemZICMP::UnsignedOnly && 2592 isInt<16>(ConstOp1->getSExtValue())) 2593 return false; 2594 return true; 2595 } 2596 2597 // Try to promote the use of CGFR and CLGFR. 2598 unsigned Opcode0 = C.Op0.getOpcode(); 2599 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND) 2600 return true; 2601 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND) 2602 return true; 2603 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::AND && 2604 C.Op0.getOperand(1).getOpcode() == ISD::Constant && 2605 C.Op0.getConstantOperandVal(1) == 0xffffffff) 2606 return true; 2607 2608 return false; 2609 } 2610 2611 // Check whether C tests for equality between X and Y and whether X - Y 2612 // or Y - X is also computed. In that case it's better to compare the 2613 // result of the subtraction against zero. 2614 static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL, 2615 Comparison &C) { 2616 if (C.CCMask == SystemZ::CCMASK_CMP_EQ || 2617 C.CCMask == SystemZ::CCMASK_CMP_NE) { 2618 for (SDNode *N : C.Op0->uses()) { 2619 if (N->getOpcode() == ISD::SUB && 2620 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) || 2621 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) { 2622 // Disable the nsw and nuw flags: the backend needs to handle 2623 // overflow as well during comparison elimination. 2624 SDNodeFlags Flags = N->getFlags(); 2625 Flags.setNoSignedWrap(false); 2626 Flags.setNoUnsignedWrap(false); 2627 N->setFlags(Flags); 2628 C.Op0 = SDValue(N, 0); 2629 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0)); 2630 return; 2631 } 2632 } 2633 } 2634 } 2635 2636 // Check whether C compares a floating-point value with zero and if that 2637 // floating-point value is also negated. In this case we can use the 2638 // negation to set CC, so avoiding separate LOAD AND TEST and 2639 // LOAD (NEGATIVE/COMPLEMENT) instructions. 2640 static void adjustForFNeg(Comparison &C) { 2641 // This optimization is invalid for strict comparisons, since FNEG 2642 // does not raise any exceptions. 2643 if (C.Chain) 2644 return; 2645 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1); 2646 if (C1 && C1->isZero()) { 2647 for (SDNode *N : C.Op0->uses()) { 2648 if (N->getOpcode() == ISD::FNEG) { 2649 C.Op0 = SDValue(N, 0); 2650 C.CCMask = SystemZ::reverseCCMask(C.CCMask); 2651 return; 2652 } 2653 } 2654 } 2655 } 2656 2657 // Check whether C compares (shl X, 32) with 0 and whether X is 2658 // also sign-extended. In that case it is better to test the result 2659 // of the sign extension using LTGFR. 2660 // 2661 // This case is important because InstCombine transforms a comparison 2662 // with (sext (trunc X)) into a comparison with (shl X, 32). 2663 static void adjustForLTGFR(Comparison &C) { 2664 // Check for a comparison between (shl X, 32) and 0. 2665 if (C.Op0.getOpcode() == ISD::SHL && C.Op0.getValueType() == MVT::i64 && 2666 C.Op1.getOpcode() == ISD::Constant && C.Op1->getAsZExtVal() == 0) { 2667 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1)); 2668 if (C1 && C1->getZExtValue() == 32) { 2669 SDValue ShlOp0 = C.Op0.getOperand(0); 2670 // See whether X has any SIGN_EXTEND_INREG uses. 2671 for (SDNode *N : ShlOp0->uses()) { 2672 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG && 2673 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) { 2674 C.Op0 = SDValue(N, 0); 2675 return; 2676 } 2677 } 2678 } 2679 } 2680 } 2681 2682 // If C compares the truncation of an extending load, try to compare 2683 // the untruncated value instead. This exposes more opportunities to 2684 // reuse CC. 2685 static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL, 2686 Comparison &C) { 2687 if (C.Op0.getOpcode() == ISD::TRUNCATE && 2688 C.Op0.getOperand(0).getOpcode() == ISD::LOAD && 2689 C.Op1.getOpcode() == ISD::Constant && 2690 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 && 2691 C.Op1->getAsZExtVal() == 0) { 2692 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0)); 2693 if (L->getMemoryVT().getStoreSizeInBits().getFixedValue() <= 2694 C.Op0.getValueSizeInBits().getFixedValue()) { 2695 unsigned Type = L->getExtensionType(); 2696 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) || 2697 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) { 2698 C.Op0 = C.Op0.getOperand(0); 2699 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType()); 2700 } 2701 } 2702 } 2703 } 2704 2705 // Return true if shift operation N has an in-range constant shift value. 2706 // Store it in ShiftVal if so. 2707 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) { 2708 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2709 if (!Shift) 2710 return false; 2711 2712 uint64_t Amount = Shift->getZExtValue(); 2713 if (Amount >= N.getValueSizeInBits()) 2714 return false; 2715 2716 ShiftVal = Amount; 2717 return true; 2718 } 2719 2720 // Check whether an AND with Mask is suitable for a TEST UNDER MASK 2721 // instruction and whether the CC value is descriptive enough to handle 2722 // a comparison of type Opcode between the AND result and CmpVal. 2723 // CCMask says which comparison result is being tested and BitSize is 2724 // the number of bits in the operands. If TEST UNDER MASK can be used, 2725 // return the corresponding CC mask, otherwise return 0. 2726 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask, 2727 uint64_t Mask, uint64_t CmpVal, 2728 unsigned ICmpType) { 2729 assert(Mask != 0 && "ANDs with zero should have been removed by now"); 2730 2731 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL. 2732 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) && 2733 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask)) 2734 return 0; 2735 2736 // Work out the masks for the lowest and highest bits. 2737 uint64_t High = llvm::bit_floor(Mask); 2738 uint64_t Low = uint64_t(1) << llvm::countr_zero(Mask); 2739 2740 // Signed ordered comparisons are effectively unsigned if the sign 2741 // bit is dropped. 2742 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly); 2743 2744 // Check for equality comparisons with 0, or the equivalent. 2745 if (CmpVal == 0) { 2746 if (CCMask == SystemZ::CCMASK_CMP_EQ) 2747 return SystemZ::CCMASK_TM_ALL_0; 2748 if (CCMask == SystemZ::CCMASK_CMP_NE) 2749 return SystemZ::CCMASK_TM_SOME_1; 2750 } 2751 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) { 2752 if (CCMask == SystemZ::CCMASK_CMP_LT) 2753 return SystemZ::CCMASK_TM_ALL_0; 2754 if (CCMask == SystemZ::CCMASK_CMP_GE) 2755 return SystemZ::CCMASK_TM_SOME_1; 2756 } 2757 if (EffectivelyUnsigned && CmpVal < Low) { 2758 if (CCMask == SystemZ::CCMASK_CMP_LE) 2759 return SystemZ::CCMASK_TM_ALL_0; 2760 if (CCMask == SystemZ::CCMASK_CMP_GT) 2761 return SystemZ::CCMASK_TM_SOME_1; 2762 } 2763 2764 // Check for equality comparisons with the mask, or the equivalent. 2765 if (CmpVal == Mask) { 2766 if (CCMask == SystemZ::CCMASK_CMP_EQ) 2767 return SystemZ::CCMASK_TM_ALL_1; 2768 if (CCMask == SystemZ::CCMASK_CMP_NE) 2769 return SystemZ::CCMASK_TM_SOME_0; 2770 } 2771 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) { 2772 if (CCMask == SystemZ::CCMASK_CMP_GT) 2773 return SystemZ::CCMASK_TM_ALL_1; 2774 if (CCMask == SystemZ::CCMASK_CMP_LE) 2775 return SystemZ::CCMASK_TM_SOME_0; 2776 } 2777 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) { 2778 if (CCMask == SystemZ::CCMASK_CMP_GE) 2779 return SystemZ::CCMASK_TM_ALL_1; 2780 if (CCMask == SystemZ::CCMASK_CMP_LT) 2781 return SystemZ::CCMASK_TM_SOME_0; 2782 } 2783 2784 // Check for ordered comparisons with the top bit. 2785 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) { 2786 if (CCMask == SystemZ::CCMASK_CMP_LE) 2787 return SystemZ::CCMASK_TM_MSB_0; 2788 if (CCMask == SystemZ::CCMASK_CMP_GT) 2789 return SystemZ::CCMASK_TM_MSB_1; 2790 } 2791 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) { 2792 if (CCMask == SystemZ::CCMASK_CMP_LT) 2793 return SystemZ::CCMASK_TM_MSB_0; 2794 if (CCMask == SystemZ::CCMASK_CMP_GE) 2795 return SystemZ::CCMASK_TM_MSB_1; 2796 } 2797 2798 // If there are just two bits, we can do equality checks for Low and High 2799 // as well. 2800 if (Mask == Low + High) { 2801 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low) 2802 return SystemZ::CCMASK_TM_MIXED_MSB_0; 2803 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low) 2804 return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY; 2805 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High) 2806 return SystemZ::CCMASK_TM_MIXED_MSB_1; 2807 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High) 2808 return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY; 2809 } 2810 2811 // Looks like we've exhausted our options. 2812 return 0; 2813 } 2814 2815 // See whether C can be implemented as a TEST UNDER MASK instruction. 2816 // Update the arguments with the TM version if so. 2817 static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL, 2818 Comparison &C) { 2819 // Use VECTOR TEST UNDER MASK for i128 operations. 2820 if (C.Op0.getValueType() == MVT::i128) { 2821 // We can use VTM for EQ/NE comparisons of x & y against 0. 2822 if (C.Op0.getOpcode() == ISD::AND && 2823 (C.CCMask == SystemZ::CCMASK_CMP_EQ || 2824 C.CCMask == SystemZ::CCMASK_CMP_NE)) { 2825 auto *Mask = dyn_cast<ConstantSDNode>(C.Op1); 2826 if (Mask && Mask->getAPIntValue() == 0) { 2827 C.Opcode = SystemZISD::VTM; 2828 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(1)); 2829 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(0)); 2830 C.CCValid = SystemZ::CCMASK_VCMP; 2831 if (C.CCMask == SystemZ::CCMASK_CMP_EQ) 2832 C.CCMask = SystemZ::CCMASK_VCMP_ALL; 2833 else 2834 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid; 2835 } 2836 } 2837 return; 2838 } 2839 2840 // Check that we have a comparison with a constant. 2841 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1); 2842 if (!ConstOp1) 2843 return; 2844 uint64_t CmpVal = ConstOp1->getZExtValue(); 2845 2846 // Check whether the nonconstant input is an AND with a constant mask. 2847 Comparison NewC(C); 2848 uint64_t MaskVal; 2849 ConstantSDNode *Mask = nullptr; 2850 if (C.Op0.getOpcode() == ISD::AND) { 2851 NewC.Op0 = C.Op0.getOperand(0); 2852 NewC.Op1 = C.Op0.getOperand(1); 2853 Mask = dyn_cast<ConstantSDNode>(NewC.Op1); 2854 if (!Mask) 2855 return; 2856 MaskVal = Mask->getZExtValue(); 2857 } else { 2858 // There is no instruction to compare with a 64-bit immediate 2859 // so use TMHH instead if possible. We need an unsigned ordered 2860 // comparison with an i64 immediate. 2861 if (NewC.Op0.getValueType() != MVT::i64 || 2862 NewC.CCMask == SystemZ::CCMASK_CMP_EQ || 2863 NewC.CCMask == SystemZ::CCMASK_CMP_NE || 2864 NewC.ICmpType == SystemZICMP::SignedOnly) 2865 return; 2866 // Convert LE and GT comparisons into LT and GE. 2867 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE || 2868 NewC.CCMask == SystemZ::CCMASK_CMP_GT) { 2869 if (CmpVal == uint64_t(-1)) 2870 return; 2871 CmpVal += 1; 2872 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ; 2873 } 2874 // If the low N bits of Op1 are zero than the low N bits of Op0 can 2875 // be masked off without changing the result. 2876 MaskVal = -(CmpVal & -CmpVal); 2877 NewC.ICmpType = SystemZICMP::UnsignedOnly; 2878 } 2879 if (!MaskVal) 2880 return; 2881 2882 // Check whether the combination of mask, comparison value and comparison 2883 // type are suitable. 2884 unsigned BitSize = NewC.Op0.getValueSizeInBits(); 2885 unsigned NewCCMask, ShiftVal; 2886 if (NewC.ICmpType != SystemZICMP::SignedOnly && 2887 NewC.Op0.getOpcode() == ISD::SHL && 2888 isSimpleShift(NewC.Op0, ShiftVal) && 2889 (MaskVal >> ShiftVal != 0) && 2890 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal && 2891 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, 2892 MaskVal >> ShiftVal, 2893 CmpVal >> ShiftVal, 2894 SystemZICMP::Any))) { 2895 NewC.Op0 = NewC.Op0.getOperand(0); 2896 MaskVal >>= ShiftVal; 2897 } else if (NewC.ICmpType != SystemZICMP::SignedOnly && 2898 NewC.Op0.getOpcode() == ISD::SRL && 2899 isSimpleShift(NewC.Op0, ShiftVal) && 2900 (MaskVal << ShiftVal != 0) && 2901 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal && 2902 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, 2903 MaskVal << ShiftVal, 2904 CmpVal << ShiftVal, 2905 SystemZICMP::UnsignedOnly))) { 2906 NewC.Op0 = NewC.Op0.getOperand(0); 2907 MaskVal <<= ShiftVal; 2908 } else { 2909 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal, 2910 NewC.ICmpType); 2911 if (!NewCCMask) 2912 return; 2913 } 2914 2915 // Go ahead and make the change. 2916 C.Opcode = SystemZISD::TM; 2917 C.Op0 = NewC.Op0; 2918 if (Mask && Mask->getZExtValue() == MaskVal) 2919 C.Op1 = SDValue(Mask, 0); 2920 else 2921 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType()); 2922 C.CCValid = SystemZ::CCMASK_TM; 2923 C.CCMask = NewCCMask; 2924 } 2925 2926 // Implement i128 comparison in vector registers. 2927 static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL, 2928 Comparison &C) { 2929 if (C.Opcode != SystemZISD::ICMP) 2930 return; 2931 if (C.Op0.getValueType() != MVT::i128) 2932 return; 2933 2934 // (In-)Equality comparisons can be implemented via VCEQGS. 2935 if (C.CCMask == SystemZ::CCMASK_CMP_EQ || 2936 C.CCMask == SystemZ::CCMASK_CMP_NE) { 2937 C.Opcode = SystemZISD::VICMPES; 2938 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op0); 2939 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op1); 2940 C.CCValid = SystemZ::CCMASK_VCMP; 2941 if (C.CCMask == SystemZ::CCMASK_CMP_EQ) 2942 C.CCMask = SystemZ::CCMASK_VCMP_ALL; 2943 else 2944 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid; 2945 return; 2946 } 2947 2948 // Normalize other comparisons to GT. 2949 bool Swap = false, Invert = false; 2950 switch (C.CCMask) { 2951 case SystemZ::CCMASK_CMP_GT: break; 2952 case SystemZ::CCMASK_CMP_LT: Swap = true; break; 2953 case SystemZ::CCMASK_CMP_LE: Invert = true; break; 2954 case SystemZ::CCMASK_CMP_GE: Swap = Invert = true; break; 2955 default: llvm_unreachable("Invalid integer condition!"); 2956 } 2957 if (Swap) 2958 std::swap(C.Op0, C.Op1); 2959 2960 if (C.ICmpType == SystemZICMP::UnsignedOnly) 2961 C.Opcode = SystemZISD::UCMP128HI; 2962 else 2963 C.Opcode = SystemZISD::SCMP128HI; 2964 C.CCValid = SystemZ::CCMASK_ANY; 2965 C.CCMask = SystemZ::CCMASK_1; 2966 2967 if (Invert) 2968 C.CCMask ^= C.CCValid; 2969 } 2970 2971 // See whether the comparison argument contains a redundant AND 2972 // and remove it if so. This sometimes happens due to the generic 2973 // BRCOND expansion. 2974 static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL, 2975 Comparison &C) { 2976 if (C.Op0.getOpcode() != ISD::AND) 2977 return; 2978 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1)); 2979 if (!Mask || Mask->getValueSizeInBits(0) > 64) 2980 return; 2981 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0)); 2982 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue()) 2983 return; 2984 2985 C.Op0 = C.Op0.getOperand(0); 2986 } 2987 2988 // Return a Comparison that tests the condition-code result of intrinsic 2989 // node Call against constant integer CC using comparison code Cond. 2990 // Opcode is the opcode of the SystemZISD operation for the intrinsic 2991 // and CCValid is the set of possible condition-code results. 2992 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode, 2993 SDValue Call, unsigned CCValid, uint64_t CC, 2994 ISD::CondCode Cond) { 2995 Comparison C(Call, SDValue(), SDValue()); 2996 C.Opcode = Opcode; 2997 C.CCValid = CCValid; 2998 if (Cond == ISD::SETEQ) 2999 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3. 3000 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0; 3001 else if (Cond == ISD::SETNE) 3002 // ...and the inverse of that. 3003 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1; 3004 else if (Cond == ISD::SETLT || Cond == ISD::SETULT) 3005 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3, 3006 // always true for CC>3. 3007 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1; 3008 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE) 3009 // ...and the inverse of that. 3010 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0; 3011 else if (Cond == ISD::SETLE || Cond == ISD::SETULE) 3012 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true), 3013 // always true for CC>3. 3014 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1; 3015 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT) 3016 // ...and the inverse of that. 3017 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0; 3018 else 3019 llvm_unreachable("Unexpected integer comparison type"); 3020 C.CCMask &= CCValid; 3021 return C; 3022 } 3023 3024 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1. 3025 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1, 3026 ISD::CondCode Cond, const SDLoc &DL, 3027 SDValue Chain = SDValue(), 3028 bool IsSignaling = false) { 3029 if (CmpOp1.getOpcode() == ISD::Constant) { 3030 assert(!Chain); 3031 unsigned Opcode, CCValid; 3032 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN && 3033 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) && 3034 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid)) 3035 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, 3036 CmpOp1->getAsZExtVal(), Cond); 3037 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 3038 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 && 3039 isIntrinsicWithCC(CmpOp0, Opcode, CCValid)) 3040 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, 3041 CmpOp1->getAsZExtVal(), Cond); 3042 } 3043 Comparison C(CmpOp0, CmpOp1, Chain); 3044 C.CCMask = CCMaskForCondCode(Cond); 3045 if (C.Op0.getValueType().isFloatingPoint()) { 3046 C.CCValid = SystemZ::CCMASK_FCMP; 3047 if (!C.Chain) 3048 C.Opcode = SystemZISD::FCMP; 3049 else if (!IsSignaling) 3050 C.Opcode = SystemZISD::STRICT_FCMP; 3051 else 3052 C.Opcode = SystemZISD::STRICT_FCMPS; 3053 adjustForFNeg(C); 3054 } else { 3055 assert(!C.Chain); 3056 C.CCValid = SystemZ::CCMASK_ICMP; 3057 C.Opcode = SystemZISD::ICMP; 3058 // Choose the type of comparison. Equality and inequality tests can 3059 // use either signed or unsigned comparisons. The choice also doesn't 3060 // matter if both sign bits are known to be clear. In those cases we 3061 // want to give the main isel code the freedom to choose whichever 3062 // form fits best. 3063 if (C.CCMask == SystemZ::CCMASK_CMP_EQ || 3064 C.CCMask == SystemZ::CCMASK_CMP_NE || 3065 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1))) 3066 C.ICmpType = SystemZICMP::Any; 3067 else if (C.CCMask & SystemZ::CCMASK_CMP_UO) 3068 C.ICmpType = SystemZICMP::UnsignedOnly; 3069 else 3070 C.ICmpType = SystemZICMP::SignedOnly; 3071 C.CCMask &= ~SystemZ::CCMASK_CMP_UO; 3072 adjustForRedundantAnd(DAG, DL, C); 3073 adjustZeroCmp(DAG, DL, C); 3074 adjustSubwordCmp(DAG, DL, C); 3075 adjustForSubtraction(DAG, DL, C); 3076 adjustForLTGFR(C); 3077 adjustICmpTruncate(DAG, DL, C); 3078 } 3079 3080 if (shouldSwapCmpOperands(C)) { 3081 std::swap(C.Op0, C.Op1); 3082 C.CCMask = SystemZ::reverseCCMask(C.CCMask); 3083 } 3084 3085 adjustForTestUnderMask(DAG, DL, C); 3086 adjustICmp128(DAG, DL, C); 3087 return C; 3088 } 3089 3090 // Emit the comparison instruction described by C. 3091 static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) { 3092 if (!C.Op1.getNode()) { 3093 SDNode *Node; 3094 switch (C.Op0.getOpcode()) { 3095 case ISD::INTRINSIC_W_CHAIN: 3096 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode); 3097 return SDValue(Node, 0); 3098 case ISD::INTRINSIC_WO_CHAIN: 3099 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode); 3100 return SDValue(Node, Node->getNumValues() - 1); 3101 default: 3102 llvm_unreachable("Invalid comparison operands"); 3103 } 3104 } 3105 if (C.Opcode == SystemZISD::ICMP) 3106 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1, 3107 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32)); 3108 if (C.Opcode == SystemZISD::TM) { 3109 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) != 3110 bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1)); 3111 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1, 3112 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32)); 3113 } 3114 if (C.Opcode == SystemZISD::VICMPES) { 3115 SDVTList VTs = DAG.getVTList(C.Op0.getValueType(), MVT::i32); 3116 SDValue Val = DAG.getNode(C.Opcode, DL, VTs, C.Op0, C.Op1); 3117 return SDValue(Val.getNode(), 1); 3118 } 3119 if (C.Chain) { 3120 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other); 3121 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1); 3122 } 3123 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1); 3124 } 3125 3126 // Implement a 32-bit *MUL_LOHI operation by extending both operands to 3127 // 64 bits. Extend is the extension type to use. Store the high part 3128 // in Hi and the low part in Lo. 3129 static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend, 3130 SDValue Op0, SDValue Op1, SDValue &Hi, 3131 SDValue &Lo) { 3132 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0); 3133 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1); 3134 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1); 3135 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 3136 DAG.getConstant(32, DL, MVT::i64)); 3137 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi); 3138 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul); 3139 } 3140 3141 // Lower a binary operation that produces two VT results, one in each 3142 // half of a GR128 pair. Op0 and Op1 are the VT operands to the operation, 3143 // and Opcode performs the GR128 operation. Store the even register result 3144 // in Even and the odd register result in Odd. 3145 static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT, 3146 unsigned Opcode, SDValue Op0, SDValue Op1, 3147 SDValue &Even, SDValue &Odd) { 3148 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1); 3149 bool Is32Bit = is32Bit(VT); 3150 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result); 3151 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result); 3152 } 3153 3154 // Return an i32 value that is 1 if the CC value produced by CCReg is 3155 // in the mask CCMask and 0 otherwise. CC is known to have a value 3156 // in CCValid, so other values can be ignored. 3157 static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg, 3158 unsigned CCValid, unsigned CCMask) { 3159 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32), 3160 DAG.getConstant(0, DL, MVT::i32), 3161 DAG.getTargetConstant(CCValid, DL, MVT::i32), 3162 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg}; 3163 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops); 3164 } 3165 3166 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot 3167 // be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP 3168 // for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet) 3169 // floating-point comparisons, and CmpMode::SignalingFP for strict signaling 3170 // floating-point comparisons. 3171 enum class CmpMode { Int, FP, StrictFP, SignalingFP }; 3172 static unsigned getVectorComparison(ISD::CondCode CC, CmpMode Mode) { 3173 switch (CC) { 3174 case ISD::SETOEQ: 3175 case ISD::SETEQ: 3176 switch (Mode) { 3177 case CmpMode::Int: return SystemZISD::VICMPE; 3178 case CmpMode::FP: return SystemZISD::VFCMPE; 3179 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE; 3180 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES; 3181 } 3182 llvm_unreachable("Bad mode"); 3183 3184 case ISD::SETOGE: 3185 case ISD::SETGE: 3186 switch (Mode) { 3187 case CmpMode::Int: return 0; 3188 case CmpMode::FP: return SystemZISD::VFCMPHE; 3189 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE; 3190 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES; 3191 } 3192 llvm_unreachable("Bad mode"); 3193 3194 case ISD::SETOGT: 3195 case ISD::SETGT: 3196 switch (Mode) { 3197 case CmpMode::Int: return SystemZISD::VICMPH; 3198 case CmpMode::FP: return SystemZISD::VFCMPH; 3199 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH; 3200 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS; 3201 } 3202 llvm_unreachable("Bad mode"); 3203 3204 case ISD::SETUGT: 3205 switch (Mode) { 3206 case CmpMode::Int: return SystemZISD::VICMPHL; 3207 case CmpMode::FP: return 0; 3208 case CmpMode::StrictFP: return 0; 3209 case CmpMode::SignalingFP: return 0; 3210 } 3211 llvm_unreachable("Bad mode"); 3212 3213 default: 3214 return 0; 3215 } 3216 } 3217 3218 // Return the SystemZISD vector comparison operation for CC or its inverse, 3219 // or 0 if neither can be done directly. Indicate in Invert whether the 3220 // result is for the inverse of CC. Mode is as above. 3221 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, CmpMode Mode, 3222 bool &Invert) { 3223 if (unsigned Opcode = getVectorComparison(CC, Mode)) { 3224 Invert = false; 3225 return Opcode; 3226 } 3227 3228 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32); 3229 if (unsigned Opcode = getVectorComparison(CC, Mode)) { 3230 Invert = true; 3231 return Opcode; 3232 } 3233 3234 return 0; 3235 } 3236 3237 // Return a v2f64 that contains the extended form of elements Start and Start+1 3238 // of v4f32 value Op. If Chain is nonnull, return the strict form. 3239 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL, 3240 SDValue Op, SDValue Chain) { 3241 int Mask[] = { Start, -1, Start + 1, -1 }; 3242 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask); 3243 if (Chain) { 3244 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other); 3245 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op); 3246 } 3247 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op); 3248 } 3249 3250 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode, 3251 // producing a result of type VT. If Chain is nonnull, return the strict form. 3252 SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode, 3253 const SDLoc &DL, EVT VT, 3254 SDValue CmpOp0, 3255 SDValue CmpOp1, 3256 SDValue Chain) const { 3257 // There is no hardware support for v4f32 (unless we have the vector 3258 // enhancements facility 1), so extend the vector into two v2f64s 3259 // and compare those. 3260 if (CmpOp0.getValueType() == MVT::v4f32 && 3261 !Subtarget.hasVectorEnhancements1()) { 3262 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain); 3263 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain); 3264 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain); 3265 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain); 3266 if (Chain) { 3267 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other); 3268 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1); 3269 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1); 3270 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes); 3271 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1), 3272 H1.getValue(1), L1.getValue(1), 3273 HRes.getValue(1), LRes.getValue(1) }; 3274 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 3275 SDValue Ops[2] = { Res, NewChain }; 3276 return DAG.getMergeValues(Ops, DL); 3277 } 3278 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1); 3279 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1); 3280 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes); 3281 } 3282 if (Chain) { 3283 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 3284 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1); 3285 } 3286 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1); 3287 } 3288 3289 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing 3290 // an integer mask of type VT. If Chain is nonnull, we have a strict 3291 // floating-point comparison. If in addition IsSignaling is true, we have 3292 // a strict signaling floating-point comparison. 3293 SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG, 3294 const SDLoc &DL, EVT VT, 3295 ISD::CondCode CC, 3296 SDValue CmpOp0, 3297 SDValue CmpOp1, 3298 SDValue Chain, 3299 bool IsSignaling) const { 3300 bool IsFP = CmpOp0.getValueType().isFloatingPoint(); 3301 assert (!Chain || IsFP); 3302 assert (!IsSignaling || Chain); 3303 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP : 3304 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int; 3305 bool Invert = false; 3306 SDValue Cmp; 3307 switch (CC) { 3308 // Handle tests for order using (or (ogt y x) (oge x y)). 3309 case ISD::SETUO: 3310 Invert = true; 3311 [[fallthrough]]; 3312 case ISD::SETO: { 3313 assert(IsFP && "Unexpected integer comparison"); 3314 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode), 3315 DL, VT, CmpOp1, CmpOp0, Chain); 3316 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode), 3317 DL, VT, CmpOp0, CmpOp1, Chain); 3318 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE); 3319 if (Chain) 3320 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 3321 LT.getValue(1), GE.getValue(1)); 3322 break; 3323 } 3324 3325 // Handle <> tests using (or (ogt y x) (ogt x y)). 3326 case ISD::SETUEQ: 3327 Invert = true; 3328 [[fallthrough]]; 3329 case ISD::SETONE: { 3330 assert(IsFP && "Unexpected integer comparison"); 3331 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode), 3332 DL, VT, CmpOp1, CmpOp0, Chain); 3333 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode), 3334 DL, VT, CmpOp0, CmpOp1, Chain); 3335 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT); 3336 if (Chain) 3337 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 3338 LT.getValue(1), GT.getValue(1)); 3339 break; 3340 } 3341 3342 // Otherwise a single comparison is enough. It doesn't really 3343 // matter whether we try the inversion or the swap first, since 3344 // there are no cases where both work. 3345 default: 3346 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert)) 3347 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain); 3348 else { 3349 CC = ISD::getSetCCSwappedOperands(CC); 3350 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert)) 3351 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain); 3352 else 3353 llvm_unreachable("Unhandled comparison"); 3354 } 3355 if (Chain) 3356 Chain = Cmp.getValue(1); 3357 break; 3358 } 3359 if (Invert) { 3360 SDValue Mask = 3361 DAG.getSplatBuildVector(VT, DL, DAG.getConstant(-1, DL, MVT::i64)); 3362 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask); 3363 } 3364 if (Chain && Chain.getNode() != Cmp.getNode()) { 3365 SDValue Ops[2] = { Cmp, Chain }; 3366 Cmp = DAG.getMergeValues(Ops, DL); 3367 } 3368 return Cmp; 3369 } 3370 3371 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op, 3372 SelectionDAG &DAG) const { 3373 SDValue CmpOp0 = Op.getOperand(0); 3374 SDValue CmpOp1 = Op.getOperand(1); 3375 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3376 SDLoc DL(Op); 3377 EVT VT = Op.getValueType(); 3378 if (VT.isVector()) 3379 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1); 3380 3381 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL)); 3382 SDValue CCReg = emitCmp(DAG, DL, C); 3383 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask); 3384 } 3385 3386 SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op, 3387 SelectionDAG &DAG, 3388 bool IsSignaling) const { 3389 SDValue Chain = Op.getOperand(0); 3390 SDValue CmpOp0 = Op.getOperand(1); 3391 SDValue CmpOp1 = Op.getOperand(2); 3392 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get(); 3393 SDLoc DL(Op); 3394 EVT VT = Op.getNode()->getValueType(0); 3395 if (VT.isVector()) { 3396 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1, 3397 Chain, IsSignaling); 3398 return Res.getValue(Op.getResNo()); 3399 } 3400 3401 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling)); 3402 SDValue CCReg = emitCmp(DAG, DL, C); 3403 CCReg->setFlags(Op->getFlags()); 3404 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask); 3405 SDValue Ops[2] = { Result, CCReg.getValue(1) }; 3406 return DAG.getMergeValues(Ops, DL); 3407 } 3408 3409 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3410 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3411 SDValue CmpOp0 = Op.getOperand(2); 3412 SDValue CmpOp1 = Op.getOperand(3); 3413 SDValue Dest = Op.getOperand(4); 3414 SDLoc DL(Op); 3415 3416 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL)); 3417 SDValue CCReg = emitCmp(DAG, DL, C); 3418 return DAG.getNode( 3419 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0), 3420 DAG.getTargetConstant(C.CCValid, DL, MVT::i32), 3421 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg); 3422 } 3423 3424 // Return true if Pos is CmpOp and Neg is the negative of CmpOp, 3425 // allowing Pos and Neg to be wider than CmpOp. 3426 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) { 3427 return (Neg.getOpcode() == ISD::SUB && 3428 Neg.getOperand(0).getOpcode() == ISD::Constant && 3429 Neg.getConstantOperandVal(0) == 0 && Neg.getOperand(1) == Pos && 3430 (Pos == CmpOp || (Pos.getOpcode() == ISD::SIGN_EXTEND && 3431 Pos.getOperand(0) == CmpOp))); 3432 } 3433 3434 // Return the absolute or negative absolute of Op; IsNegative decides which. 3435 static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op, 3436 bool IsNegative) { 3437 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op); 3438 if (IsNegative) 3439 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(), 3440 DAG.getConstant(0, DL, Op.getValueType()), Op); 3441 return Op; 3442 } 3443 3444 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op, 3445 SelectionDAG &DAG) const { 3446 SDValue CmpOp0 = Op.getOperand(0); 3447 SDValue CmpOp1 = Op.getOperand(1); 3448 SDValue TrueOp = Op.getOperand(2); 3449 SDValue FalseOp = Op.getOperand(3); 3450 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3451 SDLoc DL(Op); 3452 3453 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL)); 3454 3455 // Check for absolute and negative-absolute selections, including those 3456 // where the comparison value is sign-extended (for LPGFR and LNGFR). 3457 // This check supplements the one in DAGCombiner. 3458 if (C.Opcode == SystemZISD::ICMP && C.CCMask != SystemZ::CCMASK_CMP_EQ && 3459 C.CCMask != SystemZ::CCMASK_CMP_NE && 3460 C.Op1.getOpcode() == ISD::Constant && 3461 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 && 3462 C.Op1->getAsZExtVal() == 0) { 3463 if (isAbsolute(C.Op0, TrueOp, FalseOp)) 3464 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT); 3465 if (isAbsolute(C.Op0, FalseOp, TrueOp)) 3466 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT); 3467 } 3468 3469 SDValue CCReg = emitCmp(DAG, DL, C); 3470 SDValue Ops[] = {TrueOp, FalseOp, 3471 DAG.getTargetConstant(C.CCValid, DL, MVT::i32), 3472 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg}; 3473 3474 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops); 3475 } 3476 3477 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node, 3478 SelectionDAG &DAG) const { 3479 SDLoc DL(Node); 3480 const GlobalValue *GV = Node->getGlobal(); 3481 int64_t Offset = Node->getOffset(); 3482 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3483 CodeModel::Model CM = DAG.getTarget().getCodeModel(); 3484 3485 SDValue Result; 3486 if (Subtarget.isPC32DBLSymbol(GV, CM)) { 3487 if (isInt<32>(Offset)) { 3488 // Assign anchors at 1<<12 byte boundaries. 3489 uint64_t Anchor = Offset & ~uint64_t(0xfff); 3490 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor); 3491 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 3492 3493 // The offset can be folded into the address if it is aligned to a 3494 // halfword. 3495 Offset -= Anchor; 3496 if (Offset != 0 && (Offset & 1) == 0) { 3497 SDValue Full = 3498 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset); 3499 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result); 3500 Offset = 0; 3501 } 3502 } else { 3503 // Conservatively load a constant offset greater than 32 bits into a 3504 // register below. 3505 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT); 3506 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 3507 } 3508 } else if (Subtarget.isTargetELF()) { 3509 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT); 3510 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 3511 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3512 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3513 } else if (Subtarget.isTargetzOS()) { 3514 Result = getADAEntry(DAG, GV, DL, PtrVT); 3515 } else 3516 llvm_unreachable("Unexpected Subtarget"); 3517 3518 // If there was a non-zero offset that we didn't fold, create an explicit 3519 // addition for it. 3520 if (Offset != 0) 3521 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result, 3522 DAG.getConstant(Offset, DL, PtrVT)); 3523 3524 return Result; 3525 } 3526 3527 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node, 3528 SelectionDAG &DAG, 3529 unsigned Opcode, 3530 SDValue GOTOffset) const { 3531 SDLoc DL(Node); 3532 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3533 SDValue Chain = DAG.getEntryNode(); 3534 SDValue Glue; 3535 3536 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3537 CallingConv::GHC) 3538 report_fatal_error("In GHC calling convention TLS is not supported"); 3539 3540 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12. 3541 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT); 3542 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue); 3543 Glue = Chain.getValue(1); 3544 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue); 3545 Glue = Chain.getValue(1); 3546 3547 // The first call operand is the chain and the second is the TLS symbol. 3548 SmallVector<SDValue, 8> Ops; 3549 Ops.push_back(Chain); 3550 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL, 3551 Node->getValueType(0), 3552 0, 0)); 3553 3554 // Add argument registers to the end of the list so that they are 3555 // known live into the call. 3556 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT)); 3557 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT)); 3558 3559 // Add a register mask operand representing the call-preserved registers. 3560 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 3561 const uint32_t *Mask = 3562 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 3563 assert(Mask && "Missing call preserved mask for calling convention"); 3564 Ops.push_back(DAG.getRegisterMask(Mask)); 3565 3566 // Glue the call to the argument copies. 3567 Ops.push_back(Glue); 3568 3569 // Emit the call. 3570 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3571 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops); 3572 Glue = Chain.getValue(1); 3573 3574 // Copy the return value from %r2. 3575 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue); 3576 } 3577 3578 SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL, 3579 SelectionDAG &DAG) const { 3580 SDValue Chain = DAG.getEntryNode(); 3581 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3582 3583 // The high part of the thread pointer is in access register 0. 3584 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32); 3585 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi); 3586 3587 // The low part of the thread pointer is in access register 1. 3588 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32); 3589 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo); 3590 3591 // Merge them into a single 64-bit address. 3592 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi, 3593 DAG.getConstant(32, DL, PtrVT)); 3594 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo); 3595 } 3596 3597 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node, 3598 SelectionDAG &DAG) const { 3599 if (DAG.getTarget().useEmulatedTLS()) 3600 return LowerToTLSEmulatedModel(Node, DAG); 3601 SDLoc DL(Node); 3602 const GlobalValue *GV = Node->getGlobal(); 3603 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3604 TLSModel::Model model = DAG.getTarget().getTLSModel(GV); 3605 3606 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3607 CallingConv::GHC) 3608 report_fatal_error("In GHC calling convention TLS is not supported"); 3609 3610 SDValue TP = lowerThreadPointer(DL, DAG); 3611 3612 // Get the offset of GA from the thread pointer, based on the TLS model. 3613 SDValue Offset; 3614 switch (model) { 3615 case TLSModel::GeneralDynamic: { 3616 // Load the GOT offset of the tls_index (module ID / per-symbol offset). 3617 SystemZConstantPoolValue *CPV = 3618 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD); 3619 3620 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8)); 3621 Offset = DAG.getLoad( 3622 PtrVT, DL, DAG.getEntryNode(), Offset, 3623 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3624 3625 // Call __tls_get_offset to retrieve the offset. 3626 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset); 3627 break; 3628 } 3629 3630 case TLSModel::LocalDynamic: { 3631 // Load the GOT offset of the module ID. 3632 SystemZConstantPoolValue *CPV = 3633 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM); 3634 3635 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8)); 3636 Offset = DAG.getLoad( 3637 PtrVT, DL, DAG.getEntryNode(), Offset, 3638 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3639 3640 // Call __tls_get_offset to retrieve the module base offset. 3641 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset); 3642 3643 // Note: The SystemZLDCleanupPass will remove redundant computations 3644 // of the module base offset. Count total number of local-dynamic 3645 // accesses to trigger execution of that pass. 3646 SystemZMachineFunctionInfo* MFI = 3647 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>(); 3648 MFI->incNumLocalDynamicTLSAccesses(); 3649 3650 // Add the per-symbol offset. 3651 CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF); 3652 3653 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8)); 3654 DTPOffset = DAG.getLoad( 3655 PtrVT, DL, DAG.getEntryNode(), DTPOffset, 3656 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3657 3658 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset); 3659 break; 3660 } 3661 3662 case TLSModel::InitialExec: { 3663 // Load the offset from the GOT. 3664 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 3665 SystemZII::MO_INDNTPOFF); 3666 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset); 3667 Offset = 3668 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset, 3669 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3670 break; 3671 } 3672 3673 case TLSModel::LocalExec: { 3674 // Force the offset into the constant pool and load it from there. 3675 SystemZConstantPoolValue *CPV = 3676 SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF); 3677 3678 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8)); 3679 Offset = DAG.getLoad( 3680 PtrVT, DL, DAG.getEntryNode(), Offset, 3681 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3682 break; 3683 } 3684 } 3685 3686 // Add the base and offset together. 3687 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset); 3688 } 3689 3690 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node, 3691 SelectionDAG &DAG) const { 3692 SDLoc DL(Node); 3693 const BlockAddress *BA = Node->getBlockAddress(); 3694 int64_t Offset = Node->getOffset(); 3695 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3696 3697 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset); 3698 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 3699 return Result; 3700 } 3701 3702 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT, 3703 SelectionDAG &DAG) const { 3704 SDLoc DL(JT); 3705 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3706 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3707 3708 // Use LARL to load the address of the table. 3709 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 3710 } 3711 3712 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP, 3713 SelectionDAG &DAG) const { 3714 SDLoc DL(CP); 3715 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3716 3717 SDValue Result; 3718 if (CP->isMachineConstantPoolEntry()) 3719 Result = 3720 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign()); 3721 else 3722 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(), 3723 CP->getOffset()); 3724 3725 // Use LARL to load the address of the constant pool entry. 3726 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 3727 } 3728 3729 SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op, 3730 SelectionDAG &DAG) const { 3731 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>(); 3732 MachineFunction &MF = DAG.getMachineFunction(); 3733 MachineFrameInfo &MFI = MF.getFrameInfo(); 3734 MFI.setFrameAddressIsTaken(true); 3735 3736 SDLoc DL(Op); 3737 unsigned Depth = Op.getConstantOperandVal(0); 3738 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3739 3740 // By definition, the frame address is the address of the back chain. (In 3741 // the case of packed stack without backchain, return the address where the 3742 // backchain would have been stored. This will either be an unused space or 3743 // contain a saved register). 3744 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF); 3745 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT); 3746 3747 if (Depth > 0) { 3748 // FIXME The frontend should detect this case. 3749 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain()) 3750 report_fatal_error("Unsupported stack frame traversal count"); 3751 3752 SDValue Offset = DAG.getConstant(TFL->getBackchainOffset(MF), DL, PtrVT); 3753 while (Depth--) { 3754 BackChain = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), BackChain, 3755 MachinePointerInfo()); 3756 BackChain = DAG.getNode(ISD::ADD, DL, PtrVT, BackChain, Offset); 3757 } 3758 } 3759 3760 return BackChain; 3761 } 3762 3763 SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op, 3764 SelectionDAG &DAG) const { 3765 MachineFunction &MF = DAG.getMachineFunction(); 3766 MachineFrameInfo &MFI = MF.getFrameInfo(); 3767 MFI.setReturnAddressIsTaken(true); 3768 3769 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3770 return SDValue(); 3771 3772 SDLoc DL(Op); 3773 unsigned Depth = Op.getConstantOperandVal(0); 3774 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3775 3776 if (Depth > 0) { 3777 // FIXME The frontend should detect this case. 3778 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain()) 3779 report_fatal_error("Unsupported stack frame traversal count"); 3780 3781 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3782 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>(); 3783 int Offset = (TFL->usePackedStack(MF) ? -2 : 14) * 3784 getTargetMachine().getPointerSize(0); 3785 SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, FrameAddr, 3786 DAG.getConstant(Offset, DL, PtrVT)); 3787 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, 3788 MachinePointerInfo()); 3789 } 3790 3791 // Return R14D, which has the return address. Mark it an implicit live-in. 3792 Register LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass); 3793 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT); 3794 } 3795 3796 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op, 3797 SelectionDAG &DAG) const { 3798 SDLoc DL(Op); 3799 SDValue In = Op.getOperand(0); 3800 EVT InVT = In.getValueType(); 3801 EVT ResVT = Op.getValueType(); 3802 3803 // Convert loads directly. This is normally done by DAGCombiner, 3804 // but we need this case for bitcasts that are created during lowering 3805 // and which are then lowered themselves. 3806 if (auto *LoadN = dyn_cast<LoadSDNode>(In)) 3807 if (ISD::isNormalLoad(LoadN)) { 3808 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(), 3809 LoadN->getBasePtr(), LoadN->getMemOperand()); 3810 // Update the chain uses. 3811 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1)); 3812 return NewLoad; 3813 } 3814 3815 if (InVT == MVT::i32 && ResVT == MVT::f32) { 3816 SDValue In64; 3817 if (Subtarget.hasHighWord()) { 3818 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, 3819 MVT::i64); 3820 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL, 3821 MVT::i64, SDValue(U64, 0), In); 3822 } else { 3823 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In); 3824 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64, 3825 DAG.getConstant(32, DL, MVT::i64)); 3826 } 3827 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64); 3828 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, 3829 DL, MVT::f32, Out64); 3830 } 3831 if (InVT == MVT::f32 && ResVT == MVT::i32) { 3832 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64); 3833 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL, 3834 MVT::f64, SDValue(U64, 0), In); 3835 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64); 3836 if (Subtarget.hasHighWord()) 3837 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL, 3838 MVT::i32, Out64); 3839 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64, 3840 DAG.getConstant(32, DL, MVT::i64)); 3841 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift); 3842 } 3843 llvm_unreachable("Unexpected bitcast combination"); 3844 } 3845 3846 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op, 3847 SelectionDAG &DAG) const { 3848 3849 if (Subtarget.isTargetXPLINK64()) 3850 return lowerVASTART_XPLINK(Op, DAG); 3851 else 3852 return lowerVASTART_ELF(Op, DAG); 3853 } 3854 3855 SDValue SystemZTargetLowering::lowerVASTART_XPLINK(SDValue Op, 3856 SelectionDAG &DAG) const { 3857 MachineFunction &MF = DAG.getMachineFunction(); 3858 SystemZMachineFunctionInfo *FuncInfo = 3859 MF.getInfo<SystemZMachineFunctionInfo>(); 3860 3861 SDLoc DL(Op); 3862 3863 // vastart just stores the address of the VarArgsFrameIndex slot into the 3864 // memory location argument. 3865 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3866 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3867 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3868 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 3869 MachinePointerInfo(SV)); 3870 } 3871 3872 SDValue SystemZTargetLowering::lowerVASTART_ELF(SDValue Op, 3873 SelectionDAG &DAG) const { 3874 MachineFunction &MF = DAG.getMachineFunction(); 3875 SystemZMachineFunctionInfo *FuncInfo = 3876 MF.getInfo<SystemZMachineFunctionInfo>(); 3877 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3878 3879 SDValue Chain = Op.getOperand(0); 3880 SDValue Addr = Op.getOperand(1); 3881 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3882 SDLoc DL(Op); 3883 3884 // The initial values of each field. 3885 const unsigned NumFields = 4; 3886 SDValue Fields[NumFields] = { 3887 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT), 3888 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT), 3889 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT), 3890 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT) 3891 }; 3892 3893 // Store each field into its respective slot. 3894 SDValue MemOps[NumFields]; 3895 unsigned Offset = 0; 3896 for (unsigned I = 0; I < NumFields; ++I) { 3897 SDValue FieldAddr = Addr; 3898 if (Offset != 0) 3899 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr, 3900 DAG.getIntPtrConstant(Offset, DL)); 3901 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr, 3902 MachinePointerInfo(SV, Offset)); 3903 Offset += 8; 3904 } 3905 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 3906 } 3907 3908 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op, 3909 SelectionDAG &DAG) const { 3910 SDValue Chain = Op.getOperand(0); 3911 SDValue DstPtr = Op.getOperand(1); 3912 SDValue SrcPtr = Op.getOperand(2); 3913 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 3914 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 3915 SDLoc DL(Op); 3916 3917 uint32_t Sz = 3918 Subtarget.isTargetXPLINK64() ? getTargetMachine().getPointerSize(0) : 32; 3919 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(Sz, DL), 3920 Align(8), /*isVolatile*/ false, /*AlwaysInline*/ false, 3921 /*isTailCall*/ false, MachinePointerInfo(DstSV), 3922 MachinePointerInfo(SrcSV)); 3923 } 3924 3925 SDValue 3926 SystemZTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op, 3927 SelectionDAG &DAG) const { 3928 if (Subtarget.isTargetXPLINK64()) 3929 return lowerDYNAMIC_STACKALLOC_XPLINK(Op, DAG); 3930 else 3931 return lowerDYNAMIC_STACKALLOC_ELF(Op, DAG); 3932 } 3933 3934 SDValue 3935 SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_XPLINK(SDValue Op, 3936 SelectionDAG &DAG) const { 3937 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 3938 MachineFunction &MF = DAG.getMachineFunction(); 3939 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack"); 3940 SDValue Chain = Op.getOperand(0); 3941 SDValue Size = Op.getOperand(1); 3942 SDValue Align = Op.getOperand(2); 3943 SDLoc DL(Op); 3944 3945 // If user has set the no alignment function attribute, ignore 3946 // alloca alignments. 3947 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0); 3948 3949 uint64_t StackAlign = TFI->getStackAlignment(); 3950 uint64_t RequiredAlign = std::max(AlignVal, StackAlign); 3951 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign; 3952 3953 SDValue NeededSpace = Size; 3954 3955 // Add extra space for alignment if needed. 3956 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3957 if (ExtraAlignSpace) 3958 NeededSpace = DAG.getNode(ISD::ADD, DL, PtrVT, NeededSpace, 3959 DAG.getConstant(ExtraAlignSpace, DL, PtrVT)); 3960 3961 bool IsSigned = false; 3962 bool DoesNotReturn = false; 3963 bool IsReturnValueUsed = false; 3964 EVT VT = Op.getValueType(); 3965 SDValue AllocaCall = 3966 makeExternalCall(Chain, DAG, "@@ALCAXP", VT, ArrayRef(NeededSpace), 3967 CallingConv::C, IsSigned, DL, DoesNotReturn, 3968 IsReturnValueUsed) 3969 .first; 3970 3971 // Perform a CopyFromReg from %GPR4 (stack pointer register). Chain and Glue 3972 // to end of call in order to ensure it isn't broken up from the call 3973 // sequence. 3974 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>(); 3975 Register SPReg = Regs.getStackPointerRegister(); 3976 Chain = AllocaCall.getValue(1); 3977 SDValue Glue = AllocaCall.getValue(2); 3978 SDValue NewSPRegNode = DAG.getCopyFromReg(Chain, DL, SPReg, PtrVT, Glue); 3979 Chain = NewSPRegNode.getValue(1); 3980 3981 MVT PtrMVT = getPointerMemTy(MF.getDataLayout()); 3982 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, PtrMVT); 3983 SDValue Result = DAG.getNode(ISD::ADD, DL, PtrMVT, NewSPRegNode, ArgAdjust); 3984 3985 // Dynamically realign if needed. 3986 if (ExtraAlignSpace) { 3987 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result, 3988 DAG.getConstant(ExtraAlignSpace, DL, PtrVT)); 3989 Result = DAG.getNode(ISD::AND, DL, PtrVT, Result, 3990 DAG.getConstant(~(RequiredAlign - 1), DL, PtrVT)); 3991 } 3992 3993 SDValue Ops[2] = {Result, Chain}; 3994 return DAG.getMergeValues(Ops, DL); 3995 } 3996 3997 SDValue 3998 SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_ELF(SDValue Op, 3999 SelectionDAG &DAG) const { 4000 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 4001 MachineFunction &MF = DAG.getMachineFunction(); 4002 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack"); 4003 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain(); 4004 4005 SDValue Chain = Op.getOperand(0); 4006 SDValue Size = Op.getOperand(1); 4007 SDValue Align = Op.getOperand(2); 4008 SDLoc DL(Op); 4009 4010 // If user has set the no alignment function attribute, ignore 4011 // alloca alignments. 4012 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0); 4013 4014 uint64_t StackAlign = TFI->getStackAlignment(); 4015 uint64_t RequiredAlign = std::max(AlignVal, StackAlign); 4016 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign; 4017 4018 Register SPReg = getStackPointerRegisterToSaveRestore(); 4019 SDValue NeededSpace = Size; 4020 4021 // Get a reference to the stack pointer. 4022 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64); 4023 4024 // If we need a backchain, save it now. 4025 SDValue Backchain; 4026 if (StoreBackchain) 4027 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG), 4028 MachinePointerInfo()); 4029 4030 // Add extra space for alignment if needed. 4031 if (ExtraAlignSpace) 4032 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace, 4033 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64)); 4034 4035 // Get the new stack pointer value. 4036 SDValue NewSP; 4037 if (hasInlineStackProbe(MF)) { 4038 NewSP = DAG.getNode(SystemZISD::PROBED_ALLOCA, DL, 4039 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace); 4040 Chain = NewSP.getValue(1); 4041 } 4042 else { 4043 NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace); 4044 // Copy the new stack pointer back. 4045 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP); 4046 } 4047 4048 // The allocated data lives above the 160 bytes allocated for the standard 4049 // frame, plus any outgoing stack arguments. We don't know how much that 4050 // amounts to yet, so emit a special ADJDYNALLOC placeholder. 4051 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64); 4052 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust); 4053 4054 // Dynamically realign if needed. 4055 if (RequiredAlign > StackAlign) { 4056 Result = 4057 DAG.getNode(ISD::ADD, DL, MVT::i64, Result, 4058 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64)); 4059 Result = 4060 DAG.getNode(ISD::AND, DL, MVT::i64, Result, 4061 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64)); 4062 } 4063 4064 if (StoreBackchain) 4065 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG), 4066 MachinePointerInfo()); 4067 4068 SDValue Ops[2] = { Result, Chain }; 4069 return DAG.getMergeValues(Ops, DL); 4070 } 4071 4072 SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET( 4073 SDValue Op, SelectionDAG &DAG) const { 4074 SDLoc DL(Op); 4075 4076 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64); 4077 } 4078 4079 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op, 4080 SelectionDAG &DAG) const { 4081 EVT VT = Op.getValueType(); 4082 SDLoc DL(Op); 4083 SDValue Ops[2]; 4084 if (is32Bit(VT)) 4085 // Just do a normal 64-bit multiplication and extract the results. 4086 // We define this so that it can be used for constant division. 4087 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0), 4088 Op.getOperand(1), Ops[1], Ops[0]); 4089 else if (Subtarget.hasMiscellaneousExtensions2()) 4090 // SystemZISD::SMUL_LOHI returns the low result in the odd register and 4091 // the high result in the even register. ISD::SMUL_LOHI is defined to 4092 // return the low half first, so the results are in reverse order. 4093 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI, 4094 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]); 4095 else { 4096 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI: 4097 // 4098 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64) 4099 // 4100 // but using the fact that the upper halves are either all zeros 4101 // or all ones: 4102 // 4103 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64) 4104 // 4105 // and grouping the right terms together since they are quicker than the 4106 // multiplication: 4107 // 4108 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64) 4109 SDValue C63 = DAG.getConstant(63, DL, MVT::i64); 4110 SDValue LL = Op.getOperand(0); 4111 SDValue RL = Op.getOperand(1); 4112 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63); 4113 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63); 4114 // SystemZISD::UMUL_LOHI returns the low result in the odd register and 4115 // the high result in the even register. ISD::SMUL_LOHI is defined to 4116 // return the low half first, so the results are in reverse order. 4117 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI, 4118 LL, RL, Ops[1], Ops[0]); 4119 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH); 4120 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL); 4121 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL); 4122 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum); 4123 } 4124 return DAG.getMergeValues(Ops, DL); 4125 } 4126 4127 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op, 4128 SelectionDAG &DAG) const { 4129 EVT VT = Op.getValueType(); 4130 SDLoc DL(Op); 4131 SDValue Ops[2]; 4132 if (is32Bit(VT)) 4133 // Just do a normal 64-bit multiplication and extract the results. 4134 // We define this so that it can be used for constant division. 4135 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0), 4136 Op.getOperand(1), Ops[1], Ops[0]); 4137 else 4138 // SystemZISD::UMUL_LOHI returns the low result in the odd register and 4139 // the high result in the even register. ISD::UMUL_LOHI is defined to 4140 // return the low half first, so the results are in reverse order. 4141 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI, 4142 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]); 4143 return DAG.getMergeValues(Ops, DL); 4144 } 4145 4146 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op, 4147 SelectionDAG &DAG) const { 4148 SDValue Op0 = Op.getOperand(0); 4149 SDValue Op1 = Op.getOperand(1); 4150 EVT VT = Op.getValueType(); 4151 SDLoc DL(Op); 4152 4153 // We use DSGF for 32-bit division. This means the first operand must 4154 // always be 64-bit, and the second operand should be 32-bit whenever 4155 // that is possible, to improve performance. 4156 if (is32Bit(VT)) 4157 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0); 4158 else if (DAG.ComputeNumSignBits(Op1) > 32) 4159 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1); 4160 4161 // DSG(F) returns the remainder in the even register and the 4162 // quotient in the odd register. 4163 SDValue Ops[2]; 4164 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]); 4165 return DAG.getMergeValues(Ops, DL); 4166 } 4167 4168 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op, 4169 SelectionDAG &DAG) const { 4170 EVT VT = Op.getValueType(); 4171 SDLoc DL(Op); 4172 4173 // DL(G) returns the remainder in the even register and the 4174 // quotient in the odd register. 4175 SDValue Ops[2]; 4176 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM, 4177 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]); 4178 return DAG.getMergeValues(Ops, DL); 4179 } 4180 4181 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const { 4182 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation"); 4183 4184 // Get the known-zero masks for each operand. 4185 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)}; 4186 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]), 4187 DAG.computeKnownBits(Ops[1])}; 4188 4189 // See if the upper 32 bits of one operand and the lower 32 bits of the 4190 // other are known zero. They are the low and high operands respectively. 4191 uint64_t Masks[] = { Known[0].Zero.getZExtValue(), 4192 Known[1].Zero.getZExtValue() }; 4193 unsigned High, Low; 4194 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff) 4195 High = 1, Low = 0; 4196 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff) 4197 High = 0, Low = 1; 4198 else 4199 return Op; 4200 4201 SDValue LowOp = Ops[Low]; 4202 SDValue HighOp = Ops[High]; 4203 4204 // If the high part is a constant, we're better off using IILH. 4205 if (HighOp.getOpcode() == ISD::Constant) 4206 return Op; 4207 4208 // If the low part is a constant that is outside the range of LHI, 4209 // then we're better off using IILF. 4210 if (LowOp.getOpcode() == ISD::Constant) { 4211 int64_t Value = int32_t(LowOp->getAsZExtVal()); 4212 if (!isInt<16>(Value)) 4213 return Op; 4214 } 4215 4216 // Check whether the high part is an AND that doesn't change the 4217 // high 32 bits and just masks out low bits. We can skip it if so. 4218 if (HighOp.getOpcode() == ISD::AND && 4219 HighOp.getOperand(1).getOpcode() == ISD::Constant) { 4220 SDValue HighOp0 = HighOp.getOperand(0); 4221 uint64_t Mask = HighOp.getConstantOperandVal(1); 4222 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff)))) 4223 HighOp = HighOp0; 4224 } 4225 4226 // Take advantage of the fact that all GR32 operations only change the 4227 // low 32 bits by truncating Low to an i32 and inserting it directly 4228 // using a subreg. The interesting cases are those where the truncation 4229 // can be folded. 4230 SDLoc DL(Op); 4231 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp); 4232 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL, 4233 MVT::i64, HighOp, Low32); 4234 } 4235 4236 // Lower SADDO/SSUBO/UADDO/USUBO nodes. 4237 SDValue SystemZTargetLowering::lowerXALUO(SDValue Op, 4238 SelectionDAG &DAG) const { 4239 SDNode *N = Op.getNode(); 4240 SDValue LHS = N->getOperand(0); 4241 SDValue RHS = N->getOperand(1); 4242 SDLoc DL(N); 4243 4244 if (N->getValueType(0) == MVT::i128) { 4245 unsigned BaseOp = 0; 4246 unsigned FlagOp = 0; 4247 switch (Op.getOpcode()) { 4248 default: llvm_unreachable("Unknown instruction!"); 4249 case ISD::UADDO: 4250 BaseOp = ISD::ADD; 4251 FlagOp = SystemZISD::VACC; 4252 break; 4253 case ISD::USUBO: 4254 BaseOp = ISD::SUB; 4255 FlagOp = SystemZISD::VSCBI; 4256 break; 4257 } 4258 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS); 4259 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS); 4260 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag, 4261 DAG.getValueType(MVT::i1)); 4262 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1)); 4263 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag); 4264 } 4265 4266 unsigned BaseOp = 0; 4267 unsigned CCValid = 0; 4268 unsigned CCMask = 0; 4269 4270 switch (Op.getOpcode()) { 4271 default: llvm_unreachable("Unknown instruction!"); 4272 case ISD::SADDO: 4273 BaseOp = SystemZISD::SADDO; 4274 CCValid = SystemZ::CCMASK_ARITH; 4275 CCMask = SystemZ::CCMASK_ARITH_OVERFLOW; 4276 break; 4277 case ISD::SSUBO: 4278 BaseOp = SystemZISD::SSUBO; 4279 CCValid = SystemZ::CCMASK_ARITH; 4280 CCMask = SystemZ::CCMASK_ARITH_OVERFLOW; 4281 break; 4282 case ISD::UADDO: 4283 BaseOp = SystemZISD::UADDO; 4284 CCValid = SystemZ::CCMASK_LOGICAL; 4285 CCMask = SystemZ::CCMASK_LOGICAL_CARRY; 4286 break; 4287 case ISD::USUBO: 4288 BaseOp = SystemZISD::USUBO; 4289 CCValid = SystemZ::CCMASK_LOGICAL; 4290 CCMask = SystemZ::CCMASK_LOGICAL_BORROW; 4291 break; 4292 } 4293 4294 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 4295 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 4296 4297 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask); 4298 if (N->getValueType(1) == MVT::i1) 4299 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC); 4300 4301 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC); 4302 } 4303 4304 static bool isAddCarryChain(SDValue Carry) { 4305 while (Carry.getOpcode() == ISD::UADDO_CARRY) 4306 Carry = Carry.getOperand(2); 4307 return Carry.getOpcode() == ISD::UADDO; 4308 } 4309 4310 static bool isSubBorrowChain(SDValue Carry) { 4311 while (Carry.getOpcode() == ISD::USUBO_CARRY) 4312 Carry = Carry.getOperand(2); 4313 return Carry.getOpcode() == ISD::USUBO; 4314 } 4315 4316 // Lower UADDO_CARRY/USUBO_CARRY nodes. 4317 SDValue SystemZTargetLowering::lowerUADDSUBO_CARRY(SDValue Op, 4318 SelectionDAG &DAG) const { 4319 4320 SDNode *N = Op.getNode(); 4321 MVT VT = N->getSimpleValueType(0); 4322 4323 // Let legalize expand this if it isn't a legal type yet. 4324 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 4325 return SDValue(); 4326 4327 SDValue LHS = N->getOperand(0); 4328 SDValue RHS = N->getOperand(1); 4329 SDValue Carry = Op.getOperand(2); 4330 SDLoc DL(N); 4331 4332 if (VT == MVT::i128) { 4333 unsigned BaseOp = 0; 4334 unsigned FlagOp = 0; 4335 switch (Op.getOpcode()) { 4336 default: llvm_unreachable("Unknown instruction!"); 4337 case ISD::UADDO_CARRY: 4338 BaseOp = SystemZISD::VAC; 4339 FlagOp = SystemZISD::VACCC; 4340 break; 4341 case ISD::USUBO_CARRY: 4342 BaseOp = SystemZISD::VSBI; 4343 FlagOp = SystemZISD::VSBCBI; 4344 break; 4345 } 4346 Carry = DAG.getZExtOrTrunc(Carry, DL, MVT::i128); 4347 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS, Carry); 4348 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS, Carry); 4349 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag, 4350 DAG.getValueType(MVT::i1)); 4351 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1)); 4352 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag); 4353 } 4354 4355 unsigned BaseOp = 0; 4356 unsigned CCValid = 0; 4357 unsigned CCMask = 0; 4358 4359 switch (Op.getOpcode()) { 4360 default: llvm_unreachable("Unknown instruction!"); 4361 case ISD::UADDO_CARRY: 4362 if (!isAddCarryChain(Carry)) 4363 return SDValue(); 4364 4365 BaseOp = SystemZISD::ADDCARRY; 4366 CCValid = SystemZ::CCMASK_LOGICAL; 4367 CCMask = SystemZ::CCMASK_LOGICAL_CARRY; 4368 break; 4369 case ISD::USUBO_CARRY: 4370 if (!isSubBorrowChain(Carry)) 4371 return SDValue(); 4372 4373 BaseOp = SystemZISD::SUBCARRY; 4374 CCValid = SystemZ::CCMASK_LOGICAL; 4375 CCMask = SystemZ::CCMASK_LOGICAL_BORROW; 4376 break; 4377 } 4378 4379 // Set the condition code from the carry flag. 4380 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry, 4381 DAG.getConstant(CCValid, DL, MVT::i32), 4382 DAG.getConstant(CCMask, DL, MVT::i32)); 4383 4384 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4385 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry); 4386 4387 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask); 4388 if (N->getValueType(1) == MVT::i1) 4389 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC); 4390 4391 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC); 4392 } 4393 4394 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op, 4395 SelectionDAG &DAG) const { 4396 EVT VT = Op.getValueType(); 4397 SDLoc DL(Op); 4398 Op = Op.getOperand(0); 4399 4400 if (VT.getScalarSizeInBits() == 128) { 4401 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op); 4402 Op = DAG.getNode(ISD::CTPOP, DL, MVT::v2i64, Op); 4403 SDValue Tmp = DAG.getSplatBuildVector(MVT::v2i64, DL, 4404 DAG.getConstant(0, DL, MVT::i64)); 4405 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp); 4406 return Op; 4407 } 4408 4409 // Handle vector types via VPOPCT. 4410 if (VT.isVector()) { 4411 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op); 4412 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op); 4413 switch (VT.getScalarSizeInBits()) { 4414 case 8: 4415 break; 4416 case 16: { 4417 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op); 4418 SDValue Shift = DAG.getConstant(8, DL, MVT::i32); 4419 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift); 4420 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp); 4421 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift); 4422 break; 4423 } 4424 case 32: { 4425 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL, 4426 DAG.getConstant(0, DL, MVT::i32)); 4427 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp); 4428 break; 4429 } 4430 case 64: { 4431 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL, 4432 DAG.getConstant(0, DL, MVT::i32)); 4433 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp); 4434 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp); 4435 break; 4436 } 4437 default: 4438 llvm_unreachable("Unexpected type"); 4439 } 4440 return Op; 4441 } 4442 4443 // Get the known-zero mask for the operand. 4444 KnownBits Known = DAG.computeKnownBits(Op); 4445 unsigned NumSignificantBits = Known.getMaxValue().getActiveBits(); 4446 if (NumSignificantBits == 0) 4447 return DAG.getConstant(0, DL, VT); 4448 4449 // Skip known-zero high parts of the operand. 4450 int64_t OrigBitSize = VT.getSizeInBits(); 4451 int64_t BitSize = llvm::bit_ceil(NumSignificantBits); 4452 BitSize = std::min(BitSize, OrigBitSize); 4453 4454 // The POPCNT instruction counts the number of bits in each byte. 4455 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op); 4456 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op); 4457 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 4458 4459 // Add up per-byte counts in a binary tree. All bits of Op at 4460 // position larger than BitSize remain zero throughout. 4461 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) { 4462 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT)); 4463 if (BitSize != OrigBitSize) 4464 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp, 4465 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT)); 4466 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp); 4467 } 4468 4469 // Extract overall result from high byte. 4470 if (BitSize > 8) 4471 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4472 DAG.getConstant(BitSize - 8, DL, VT)); 4473 4474 return Op; 4475 } 4476 4477 SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op, 4478 SelectionDAG &DAG) const { 4479 SDLoc DL(Op); 4480 AtomicOrdering FenceOrdering = 4481 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1)); 4482 SyncScope::ID FenceSSID = 4483 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2)); 4484 4485 // The only fence that needs an instruction is a sequentially-consistent 4486 // cross-thread fence. 4487 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent && 4488 FenceSSID == SyncScope::System) { 4489 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other, 4490 Op.getOperand(0)), 4491 0); 4492 } 4493 4494 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 4495 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0)); 4496 } 4497 4498 // Op is an atomic load. Lower it into a normal volatile load. 4499 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op, 4500 SelectionDAG &DAG) const { 4501 auto *Node = cast<AtomicSDNode>(Op.getNode()); 4502 if (Node->getMemoryVT() == MVT::i128) { 4503 // Use same code to handle both legal and non-legal i128 types. 4504 SmallVector<SDValue, 2> Results; 4505 LowerOperationWrapper(Node, Results, DAG); 4506 return DAG.getMergeValues(Results, SDLoc(Op)); 4507 } 4508 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(), 4509 Node->getChain(), Node->getBasePtr(), 4510 Node->getMemoryVT(), Node->getMemOperand()); 4511 } 4512 4513 // Op is an atomic store. Lower it into a normal volatile store. 4514 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op, 4515 SelectionDAG &DAG) const { 4516 auto *Node = cast<AtomicSDNode>(Op.getNode()); 4517 if (Node->getMemoryVT() == MVT::i128) { 4518 // Use same code to handle both legal and non-legal i128 types. 4519 SmallVector<SDValue, 1> Results; 4520 LowerOperationWrapper(Node, Results, DAG); 4521 return DAG.getMergeValues(Results, SDLoc(Op)); 4522 } 4523 SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(), 4524 Node->getBasePtr(), Node->getMemoryVT(), 4525 Node->getMemOperand()); 4526 // We have to enforce sequential consistency by performing a 4527 // serialization operation after the store. 4528 if (Node->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent) 4529 Chain = SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), 4530 MVT::Other, Chain), 0); 4531 return Chain; 4532 } 4533 4534 // Prepare for a Compare And Swap for a subword operation. This needs to be 4535 // done in memory with 4 bytes at natural alignment. 4536 static void getCSAddressAndShifts(SDValue Addr, SelectionDAG &DAG, SDLoc DL, 4537 SDValue &AlignedAddr, SDValue &BitShift, 4538 SDValue &NegBitShift) { 4539 EVT PtrVT = Addr.getValueType(); 4540 EVT WideVT = MVT::i32; 4541 4542 // Get the address of the containing word. 4543 AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr, 4544 DAG.getConstant(-4, DL, PtrVT)); 4545 4546 // Get the number of bits that the word must be rotated left in order 4547 // to bring the field to the top bits of a GR32. 4548 BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr, 4549 DAG.getConstant(3, DL, PtrVT)); 4550 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift); 4551 4552 // Get the complementing shift amount, for rotating a field in the top 4553 // bits back to its proper position. 4554 NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT, 4555 DAG.getConstant(0, DL, WideVT), BitShift); 4556 4557 } 4558 4559 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first 4560 // two into the fullword ATOMIC_LOADW_* operation given by Opcode. 4561 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op, 4562 SelectionDAG &DAG, 4563 unsigned Opcode) const { 4564 auto *Node = cast<AtomicSDNode>(Op.getNode()); 4565 4566 // 32-bit operations need no special handling. 4567 EVT NarrowVT = Node->getMemoryVT(); 4568 EVT WideVT = MVT::i32; 4569 if (NarrowVT == WideVT) 4570 return Op; 4571 4572 int64_t BitSize = NarrowVT.getSizeInBits(); 4573 SDValue ChainIn = Node->getChain(); 4574 SDValue Addr = Node->getBasePtr(); 4575 SDValue Src2 = Node->getVal(); 4576 MachineMemOperand *MMO = Node->getMemOperand(); 4577 SDLoc DL(Node); 4578 4579 // Convert atomic subtracts of constants into additions. 4580 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB) 4581 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) { 4582 Opcode = SystemZISD::ATOMIC_LOADW_ADD; 4583 Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType()); 4584 } 4585 4586 SDValue AlignedAddr, BitShift, NegBitShift; 4587 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift); 4588 4589 // Extend the source operand to 32 bits and prepare it for the inner loop. 4590 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other 4591 // operations require the source to be shifted in advance. (This shift 4592 // can be folded if the source is constant.) For AND and NAND, the lower 4593 // bits must be set, while for other opcodes they should be left clear. 4594 if (Opcode != SystemZISD::ATOMIC_SWAPW) 4595 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2, 4596 DAG.getConstant(32 - BitSize, DL, WideVT)); 4597 if (Opcode == SystemZISD::ATOMIC_LOADW_AND || 4598 Opcode == SystemZISD::ATOMIC_LOADW_NAND) 4599 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2, 4600 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT)); 4601 4602 // Construct the ATOMIC_LOADW_* node. 4603 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other); 4604 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift, 4605 DAG.getConstant(BitSize, DL, WideVT) }; 4606 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops, 4607 NarrowVT, MMO); 4608 4609 // Rotate the result of the final CS so that the field is in the lower 4610 // bits of a GR32, then truncate it. 4611 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift, 4612 DAG.getConstant(BitSize, DL, WideVT)); 4613 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift); 4614 4615 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) }; 4616 return DAG.getMergeValues(RetOps, DL); 4617 } 4618 4619 // Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations into 4620 // ATOMIC_LOADW_SUBs and convert 32- and 64-bit operations into additions. 4621 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op, 4622 SelectionDAG &DAG) const { 4623 auto *Node = cast<AtomicSDNode>(Op.getNode()); 4624 EVT MemVT = Node->getMemoryVT(); 4625 if (MemVT == MVT::i32 || MemVT == MVT::i64) { 4626 // A full-width operation: negate and use LAA(G). 4627 assert(Op.getValueType() == MemVT && "Mismatched VTs"); 4628 assert(Subtarget.hasInterlockedAccess1() && 4629 "Should have been expanded by AtomicExpand pass."); 4630 SDValue Src2 = Node->getVal(); 4631 SDLoc DL(Src2); 4632 SDValue NegSrc2 = 4633 DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT), Src2); 4634 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT, 4635 Node->getChain(), Node->getBasePtr(), NegSrc2, 4636 Node->getMemOperand()); 4637 } 4638 4639 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB); 4640 } 4641 4642 // Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node. 4643 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op, 4644 SelectionDAG &DAG) const { 4645 auto *Node = cast<AtomicSDNode>(Op.getNode()); 4646 SDValue ChainIn = Node->getOperand(0); 4647 SDValue Addr = Node->getOperand(1); 4648 SDValue CmpVal = Node->getOperand(2); 4649 SDValue SwapVal = Node->getOperand(3); 4650 MachineMemOperand *MMO = Node->getMemOperand(); 4651 SDLoc DL(Node); 4652 4653 if (Node->getMemoryVT() == MVT::i128) { 4654 // Use same code to handle both legal and non-legal i128 types. 4655 SmallVector<SDValue, 3> Results; 4656 LowerOperationWrapper(Node, Results, DAG); 4657 return DAG.getMergeValues(Results, DL); 4658 } 4659 4660 // We have native support for 32-bit and 64-bit compare and swap, but we 4661 // still need to expand extracting the "success" result from the CC. 4662 EVT NarrowVT = Node->getMemoryVT(); 4663 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32; 4664 if (NarrowVT == WideVT) { 4665 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other); 4666 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal }; 4667 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP, 4668 DL, Tys, Ops, NarrowVT, MMO); 4669 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1), 4670 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ); 4671 4672 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0)); 4673 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success); 4674 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2)); 4675 return SDValue(); 4676 } 4677 4678 // Convert 8-bit and 16-bit compare and swap to a loop, implemented 4679 // via a fullword ATOMIC_CMP_SWAPW operation. 4680 int64_t BitSize = NarrowVT.getSizeInBits(); 4681 4682 SDValue AlignedAddr, BitShift, NegBitShift; 4683 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift); 4684 4685 // Construct the ATOMIC_CMP_SWAPW node. 4686 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other); 4687 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift, 4688 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) }; 4689 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL, 4690 VTList, Ops, NarrowVT, MMO); 4691 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1), 4692 SystemZ::CCMASK_ICMP, SystemZ::CCMASK_CMP_EQ); 4693 4694 // emitAtomicCmpSwapW() will zero extend the result (original value). 4695 SDValue OrigVal = DAG.getNode(ISD::AssertZext, DL, WideVT, AtomicOp.getValue(0), 4696 DAG.getValueType(NarrowVT)); 4697 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), OrigVal); 4698 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success); 4699 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2)); 4700 return SDValue(); 4701 } 4702 4703 MachineMemOperand::Flags 4704 SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const { 4705 // Because of how we convert atomic_load and atomic_store to normal loads and 4706 // stores in the DAG, we need to ensure that the MMOs are marked volatile 4707 // since DAGCombine hasn't been updated to account for atomic, but non 4708 // volatile loads. (See D57601) 4709 if (auto *SI = dyn_cast<StoreInst>(&I)) 4710 if (SI->isAtomic()) 4711 return MachineMemOperand::MOVolatile; 4712 if (auto *LI = dyn_cast<LoadInst>(&I)) 4713 if (LI->isAtomic()) 4714 return MachineMemOperand::MOVolatile; 4715 if (auto *AI = dyn_cast<AtomicRMWInst>(&I)) 4716 if (AI->isAtomic()) 4717 return MachineMemOperand::MOVolatile; 4718 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I)) 4719 if (AI->isAtomic()) 4720 return MachineMemOperand::MOVolatile; 4721 return MachineMemOperand::MONone; 4722 } 4723 4724 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op, 4725 SelectionDAG &DAG) const { 4726 MachineFunction &MF = DAG.getMachineFunction(); 4727 auto *Regs = Subtarget.getSpecialRegisters(); 4728 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 4729 report_fatal_error("Variable-sized stack allocations are not supported " 4730 "in GHC calling convention"); 4731 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op), 4732 Regs->getStackPointerRegister(), Op.getValueType()); 4733 } 4734 4735 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op, 4736 SelectionDAG &DAG) const { 4737 MachineFunction &MF = DAG.getMachineFunction(); 4738 auto *Regs = Subtarget.getSpecialRegisters(); 4739 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain(); 4740 4741 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 4742 report_fatal_error("Variable-sized stack allocations are not supported " 4743 "in GHC calling convention"); 4744 4745 SDValue Chain = Op.getOperand(0); 4746 SDValue NewSP = Op.getOperand(1); 4747 SDValue Backchain; 4748 SDLoc DL(Op); 4749 4750 if (StoreBackchain) { 4751 SDValue OldSP = DAG.getCopyFromReg( 4752 Chain, DL, Regs->getStackPointerRegister(), MVT::i64); 4753 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG), 4754 MachinePointerInfo()); 4755 } 4756 4757 Chain = DAG.getCopyToReg(Chain, DL, Regs->getStackPointerRegister(), NewSP); 4758 4759 if (StoreBackchain) 4760 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG), 4761 MachinePointerInfo()); 4762 4763 return Chain; 4764 } 4765 4766 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op, 4767 SelectionDAG &DAG) const { 4768 bool IsData = Op.getConstantOperandVal(4); 4769 if (!IsData) 4770 // Just preserve the chain. 4771 return Op.getOperand(0); 4772 4773 SDLoc DL(Op); 4774 bool IsWrite = Op.getConstantOperandVal(2); 4775 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ; 4776 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode()); 4777 SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32), 4778 Op.getOperand(1)}; 4779 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL, 4780 Node->getVTList(), Ops, 4781 Node->getMemoryVT(), Node->getMemOperand()); 4782 } 4783 4784 // Convert condition code in CCReg to an i32 value. 4785 static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg) { 4786 SDLoc DL(CCReg); 4787 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg); 4788 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM, 4789 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32)); 4790 } 4791 4792 SDValue 4793 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op, 4794 SelectionDAG &DAG) const { 4795 unsigned Opcode, CCValid; 4796 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) { 4797 assert(Op->getNumValues() == 2 && "Expected only CC result and chain"); 4798 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode); 4799 SDValue CC = getCCResult(DAG, SDValue(Node, 0)); 4800 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC); 4801 return SDValue(); 4802 } 4803 4804 return SDValue(); 4805 } 4806 4807 SDValue 4808 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op, 4809 SelectionDAG &DAG) const { 4810 unsigned Opcode, CCValid; 4811 if (isIntrinsicWithCC(Op, Opcode, CCValid)) { 4812 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode); 4813 if (Op->getNumValues() == 1) 4814 return getCCResult(DAG, SDValue(Node, 0)); 4815 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result"); 4816 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(), 4817 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1))); 4818 } 4819 4820 unsigned Id = Op.getConstantOperandVal(0); 4821 switch (Id) { 4822 case Intrinsic::thread_pointer: 4823 return lowerThreadPointer(SDLoc(Op), DAG); 4824 4825 case Intrinsic::s390_vpdi: 4826 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(), 4827 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4828 4829 case Intrinsic::s390_vperm: 4830 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(), 4831 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4832 4833 case Intrinsic::s390_vuphb: 4834 case Intrinsic::s390_vuphh: 4835 case Intrinsic::s390_vuphf: 4836 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(), 4837 Op.getOperand(1)); 4838 4839 case Intrinsic::s390_vuplhb: 4840 case Intrinsic::s390_vuplhh: 4841 case Intrinsic::s390_vuplhf: 4842 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(), 4843 Op.getOperand(1)); 4844 4845 case Intrinsic::s390_vuplb: 4846 case Intrinsic::s390_vuplhw: 4847 case Intrinsic::s390_vuplf: 4848 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(), 4849 Op.getOperand(1)); 4850 4851 case Intrinsic::s390_vupllb: 4852 case Intrinsic::s390_vupllh: 4853 case Intrinsic::s390_vupllf: 4854 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(), 4855 Op.getOperand(1)); 4856 4857 case Intrinsic::s390_vsumb: 4858 case Intrinsic::s390_vsumh: 4859 case Intrinsic::s390_vsumgh: 4860 case Intrinsic::s390_vsumgf: 4861 case Intrinsic::s390_vsumqf: 4862 case Intrinsic::s390_vsumqg: 4863 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(), 4864 Op.getOperand(1), Op.getOperand(2)); 4865 4866 case Intrinsic::s390_vaq: 4867 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), 4868 Op.getOperand(1), Op.getOperand(2)); 4869 case Intrinsic::s390_vaccb: 4870 case Intrinsic::s390_vacch: 4871 case Intrinsic::s390_vaccf: 4872 case Intrinsic::s390_vaccg: 4873 case Intrinsic::s390_vaccq: 4874 return DAG.getNode(SystemZISD::VACC, SDLoc(Op), Op.getValueType(), 4875 Op.getOperand(1), Op.getOperand(2)); 4876 case Intrinsic::s390_vacq: 4877 return DAG.getNode(SystemZISD::VAC, SDLoc(Op), Op.getValueType(), 4878 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4879 case Intrinsic::s390_vacccq: 4880 return DAG.getNode(SystemZISD::VACCC, SDLoc(Op), Op.getValueType(), 4881 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4882 4883 case Intrinsic::s390_vsq: 4884 return DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), 4885 Op.getOperand(1), Op.getOperand(2)); 4886 case Intrinsic::s390_vscbib: 4887 case Intrinsic::s390_vscbih: 4888 case Intrinsic::s390_vscbif: 4889 case Intrinsic::s390_vscbig: 4890 case Intrinsic::s390_vscbiq: 4891 return DAG.getNode(SystemZISD::VSCBI, SDLoc(Op), Op.getValueType(), 4892 Op.getOperand(1), Op.getOperand(2)); 4893 case Intrinsic::s390_vsbiq: 4894 return DAG.getNode(SystemZISD::VSBI, SDLoc(Op), Op.getValueType(), 4895 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4896 case Intrinsic::s390_vsbcbiq: 4897 return DAG.getNode(SystemZISD::VSBCBI, SDLoc(Op), Op.getValueType(), 4898 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4899 } 4900 4901 return SDValue(); 4902 } 4903 4904 namespace { 4905 // Says that SystemZISD operation Opcode can be used to perform the equivalent 4906 // of a VPERM with permute vector Bytes. If Opcode takes three operands, 4907 // Operand is the constant third operand, otherwise it is the number of 4908 // bytes in each element of the result. 4909 struct Permute { 4910 unsigned Opcode; 4911 unsigned Operand; 4912 unsigned char Bytes[SystemZ::VectorBytes]; 4913 }; 4914 } 4915 4916 static const Permute PermuteForms[] = { 4917 // VMRHG 4918 { SystemZISD::MERGE_HIGH, 8, 4919 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } }, 4920 // VMRHF 4921 { SystemZISD::MERGE_HIGH, 4, 4922 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } }, 4923 // VMRHH 4924 { SystemZISD::MERGE_HIGH, 2, 4925 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } }, 4926 // VMRHB 4927 { SystemZISD::MERGE_HIGH, 1, 4928 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } }, 4929 // VMRLG 4930 { SystemZISD::MERGE_LOW, 8, 4931 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } }, 4932 // VMRLF 4933 { SystemZISD::MERGE_LOW, 4, 4934 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } }, 4935 // VMRLH 4936 { SystemZISD::MERGE_LOW, 2, 4937 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } }, 4938 // VMRLB 4939 { SystemZISD::MERGE_LOW, 1, 4940 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } }, 4941 // VPKG 4942 { SystemZISD::PACK, 4, 4943 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } }, 4944 // VPKF 4945 { SystemZISD::PACK, 2, 4946 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } }, 4947 // VPKH 4948 { SystemZISD::PACK, 1, 4949 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } }, 4950 // VPDI V1, V2, 4 (low half of V1, high half of V2) 4951 { SystemZISD::PERMUTE_DWORDS, 4, 4952 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } }, 4953 // VPDI V1, V2, 1 (high half of V1, low half of V2) 4954 { SystemZISD::PERMUTE_DWORDS, 1, 4955 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } } 4956 }; 4957 4958 // Called after matching a vector shuffle against a particular pattern. 4959 // Both the original shuffle and the pattern have two vector operands. 4960 // OpNos[0] is the operand of the original shuffle that should be used for 4961 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything. 4962 // OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and 4963 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used 4964 // for operands 0 and 1 of the pattern. 4965 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) { 4966 if (OpNos[0] < 0) { 4967 if (OpNos[1] < 0) 4968 return false; 4969 OpNo0 = OpNo1 = OpNos[1]; 4970 } else if (OpNos[1] < 0) { 4971 OpNo0 = OpNo1 = OpNos[0]; 4972 } else { 4973 OpNo0 = OpNos[0]; 4974 OpNo1 = OpNos[1]; 4975 } 4976 return true; 4977 } 4978 4979 // Bytes is a VPERM-like permute vector, except that -1 is used for 4980 // undefined bytes. Return true if the VPERM can be implemented using P. 4981 // When returning true set OpNo0 to the VPERM operand that should be 4982 // used for operand 0 of P and likewise OpNo1 for operand 1 of P. 4983 // 4984 // For example, if swapping the VPERM operands allows P to match, OpNo0 4985 // will be 1 and OpNo1 will be 0. If instead Bytes only refers to one 4986 // operand, but rewriting it to use two duplicated operands allows it to 4987 // match P, then OpNo0 and OpNo1 will be the same. 4988 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P, 4989 unsigned &OpNo0, unsigned &OpNo1) { 4990 int OpNos[] = { -1, -1 }; 4991 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) { 4992 int Elt = Bytes[I]; 4993 if (Elt >= 0) { 4994 // Make sure that the two permute vectors use the same suboperand 4995 // byte number. Only the operand numbers (the high bits) are 4996 // allowed to differ. 4997 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1)) 4998 return false; 4999 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes; 5000 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes; 5001 // Make sure that the operand mappings are consistent with previous 5002 // elements. 5003 if (OpNos[ModelOpNo] == 1 - RealOpNo) 5004 return false; 5005 OpNos[ModelOpNo] = RealOpNo; 5006 } 5007 } 5008 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1); 5009 } 5010 5011 // As above, but search for a matching permute. 5012 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes, 5013 unsigned &OpNo0, unsigned &OpNo1) { 5014 for (auto &P : PermuteForms) 5015 if (matchPermute(Bytes, P, OpNo0, OpNo1)) 5016 return &P; 5017 return nullptr; 5018 } 5019 5020 // Bytes is a VPERM-like permute vector, except that -1 is used for 5021 // undefined bytes. This permute is an operand of an outer permute. 5022 // See whether redistributing the -1 bytes gives a shuffle that can be 5023 // implemented using P. If so, set Transform to a VPERM-like permute vector 5024 // that, when applied to the result of P, gives the original permute in Bytes. 5025 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes, 5026 const Permute &P, 5027 SmallVectorImpl<int> &Transform) { 5028 unsigned To = 0; 5029 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) { 5030 int Elt = Bytes[From]; 5031 if (Elt < 0) 5032 // Byte number From of the result is undefined. 5033 Transform[From] = -1; 5034 else { 5035 while (P.Bytes[To] != Elt) { 5036 To += 1; 5037 if (To == SystemZ::VectorBytes) 5038 return false; 5039 } 5040 Transform[From] = To; 5041 } 5042 } 5043 return true; 5044 } 5045 5046 // As above, but search for a matching permute. 5047 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes, 5048 SmallVectorImpl<int> &Transform) { 5049 for (auto &P : PermuteForms) 5050 if (matchDoublePermute(Bytes, P, Transform)) 5051 return &P; 5052 return nullptr; 5053 } 5054 5055 // Convert the mask of the given shuffle op into a byte-level mask, 5056 // as if it had type vNi8. 5057 static bool getVPermMask(SDValue ShuffleOp, 5058 SmallVectorImpl<int> &Bytes) { 5059 EVT VT = ShuffleOp.getValueType(); 5060 unsigned NumElements = VT.getVectorNumElements(); 5061 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize(); 5062 5063 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) { 5064 Bytes.resize(NumElements * BytesPerElement, -1); 5065 for (unsigned I = 0; I < NumElements; ++I) { 5066 int Index = VSN->getMaskElt(I); 5067 if (Index >= 0) 5068 for (unsigned J = 0; J < BytesPerElement; ++J) 5069 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J; 5070 } 5071 return true; 5072 } 5073 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() && 5074 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) { 5075 unsigned Index = ShuffleOp.getConstantOperandVal(1); 5076 Bytes.resize(NumElements * BytesPerElement, -1); 5077 for (unsigned I = 0; I < NumElements; ++I) 5078 for (unsigned J = 0; J < BytesPerElement; ++J) 5079 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J; 5080 return true; 5081 } 5082 return false; 5083 } 5084 5085 // Bytes is a VPERM-like permute vector, except that -1 is used for 5086 // undefined bytes. See whether bytes [Start, Start + BytesPerElement) of 5087 // the result come from a contiguous sequence of bytes from one input. 5088 // Set Base to the selector for the first byte if so. 5089 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start, 5090 unsigned BytesPerElement, int &Base) { 5091 Base = -1; 5092 for (unsigned I = 0; I < BytesPerElement; ++I) { 5093 if (Bytes[Start + I] >= 0) { 5094 unsigned Elem = Bytes[Start + I]; 5095 if (Base < 0) { 5096 Base = Elem - I; 5097 // Make sure the bytes would come from one input operand. 5098 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size()) 5099 return false; 5100 } else if (unsigned(Base) != Elem - I) 5101 return false; 5102 } 5103 } 5104 return true; 5105 } 5106 5107 // Bytes is a VPERM-like permute vector, except that -1 is used for 5108 // undefined bytes. Return true if it can be performed using VSLDB. 5109 // When returning true, set StartIndex to the shift amount and OpNo0 5110 // and OpNo1 to the VPERM operands that should be used as the first 5111 // and second shift operand respectively. 5112 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes, 5113 unsigned &StartIndex, unsigned &OpNo0, 5114 unsigned &OpNo1) { 5115 int OpNos[] = { -1, -1 }; 5116 int Shift = -1; 5117 for (unsigned I = 0; I < 16; ++I) { 5118 int Index = Bytes[I]; 5119 if (Index >= 0) { 5120 int ExpectedShift = (Index - I) % SystemZ::VectorBytes; 5121 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes; 5122 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes; 5123 if (Shift < 0) 5124 Shift = ExpectedShift; 5125 else if (Shift != ExpectedShift) 5126 return false; 5127 // Make sure that the operand mappings are consistent with previous 5128 // elements. 5129 if (OpNos[ModelOpNo] == 1 - RealOpNo) 5130 return false; 5131 OpNos[ModelOpNo] = RealOpNo; 5132 } 5133 } 5134 StartIndex = Shift; 5135 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1); 5136 } 5137 5138 // Create a node that performs P on operands Op0 and Op1, casting the 5139 // operands to the appropriate type. The type of the result is determined by P. 5140 static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL, 5141 const Permute &P, SDValue Op0, SDValue Op1) { 5142 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input 5143 // elements of a PACK are twice as wide as the outputs. 5144 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 : 5145 P.Opcode == SystemZISD::PACK ? P.Operand * 2 : 5146 P.Operand); 5147 // Cast both operands to the appropriate type. 5148 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8), 5149 SystemZ::VectorBytes / InBytes); 5150 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0); 5151 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1); 5152 SDValue Op; 5153 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) { 5154 SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32); 5155 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2); 5156 } else if (P.Opcode == SystemZISD::PACK) { 5157 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8), 5158 SystemZ::VectorBytes / P.Operand); 5159 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1); 5160 } else { 5161 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1); 5162 } 5163 return Op; 5164 } 5165 5166 static bool isZeroVector(SDValue N) { 5167 if (N->getOpcode() == ISD::BITCAST) 5168 N = N->getOperand(0); 5169 if (N->getOpcode() == ISD::SPLAT_VECTOR) 5170 if (auto *Op = dyn_cast<ConstantSDNode>(N->getOperand(0))) 5171 return Op->getZExtValue() == 0; 5172 return ISD::isBuildVectorAllZeros(N.getNode()); 5173 } 5174 5175 // Return the index of the zero/undef vector, or UINT32_MAX if not found. 5176 static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num) { 5177 for (unsigned I = 0; I < Num ; I++) 5178 if (isZeroVector(Ops[I])) 5179 return I; 5180 return UINT32_MAX; 5181 } 5182 5183 // Bytes is a VPERM-like permute vector, except that -1 is used for 5184 // undefined bytes. Implement it on operands Ops[0] and Ops[1] using 5185 // VSLDB or VPERM. 5186 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL, 5187 SDValue *Ops, 5188 const SmallVectorImpl<int> &Bytes) { 5189 for (unsigned I = 0; I < 2; ++I) 5190 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]); 5191 5192 // First see whether VSLDB can be used. 5193 unsigned StartIndex, OpNo0, OpNo1; 5194 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1)) 5195 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0], 5196 Ops[OpNo1], 5197 DAG.getTargetConstant(StartIndex, DL, MVT::i32)); 5198 5199 // Fall back on VPERM. Construct an SDNode for the permute vector. Try to 5200 // eliminate a zero vector by reusing any zero index in the permute vector. 5201 unsigned ZeroVecIdx = findZeroVectorIdx(&Ops[0], 2); 5202 if (ZeroVecIdx != UINT32_MAX) { 5203 bool MaskFirst = true; 5204 int ZeroIdx = -1; 5205 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) { 5206 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes; 5207 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes; 5208 if (OpNo == ZeroVecIdx && I == 0) { 5209 // If the first byte is zero, use mask as first operand. 5210 ZeroIdx = 0; 5211 break; 5212 } 5213 if (OpNo != ZeroVecIdx && Byte == 0) { 5214 // If mask contains a zero, use it by placing that vector first. 5215 ZeroIdx = I + SystemZ::VectorBytes; 5216 MaskFirst = false; 5217 break; 5218 } 5219 } 5220 if (ZeroIdx != -1) { 5221 SDValue IndexNodes[SystemZ::VectorBytes]; 5222 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) { 5223 if (Bytes[I] >= 0) { 5224 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes; 5225 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes; 5226 if (OpNo == ZeroVecIdx) 5227 IndexNodes[I] = DAG.getConstant(ZeroIdx, DL, MVT::i32); 5228 else { 5229 unsigned BIdx = MaskFirst ? Byte + SystemZ::VectorBytes : Byte; 5230 IndexNodes[I] = DAG.getConstant(BIdx, DL, MVT::i32); 5231 } 5232 } else 5233 IndexNodes[I] = DAG.getUNDEF(MVT::i32); 5234 } 5235 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes); 5236 SDValue Src = ZeroVecIdx == 0 ? Ops[1] : Ops[0]; 5237 if (MaskFirst) 5238 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Mask, Src, 5239 Mask); 5240 else 5241 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Src, Mask, 5242 Mask); 5243 } 5244 } 5245 5246 SDValue IndexNodes[SystemZ::VectorBytes]; 5247 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) 5248 if (Bytes[I] >= 0) 5249 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32); 5250 else 5251 IndexNodes[I] = DAG.getUNDEF(MVT::i32); 5252 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes); 5253 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], 5254 (!Ops[1].isUndef() ? Ops[1] : Ops[0]), Op2); 5255 } 5256 5257 namespace { 5258 // Describes a general N-operand vector shuffle. 5259 struct GeneralShuffle { 5260 GeneralShuffle(EVT vt) : VT(vt), UnpackFromEltSize(UINT_MAX) {} 5261 void addUndef(); 5262 bool add(SDValue, unsigned); 5263 SDValue getNode(SelectionDAG &, const SDLoc &); 5264 void tryPrepareForUnpack(); 5265 bool unpackWasPrepared() { return UnpackFromEltSize <= 4; } 5266 SDValue insertUnpackIfPrepared(SelectionDAG &DAG, const SDLoc &DL, SDValue Op); 5267 5268 // The operands of the shuffle. 5269 SmallVector<SDValue, SystemZ::VectorBytes> Ops; 5270 5271 // Index I is -1 if byte I of the result is undefined. Otherwise the 5272 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand 5273 // Bytes[I] / SystemZ::VectorBytes. 5274 SmallVector<int, SystemZ::VectorBytes> Bytes; 5275 5276 // The type of the shuffle result. 5277 EVT VT; 5278 5279 // Holds a value of 1, 2 or 4 if a final unpack has been prepared for. 5280 unsigned UnpackFromEltSize; 5281 }; 5282 } 5283 5284 // Add an extra undefined element to the shuffle. 5285 void GeneralShuffle::addUndef() { 5286 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize(); 5287 for (unsigned I = 0; I < BytesPerElement; ++I) 5288 Bytes.push_back(-1); 5289 } 5290 5291 // Add an extra element to the shuffle, taking it from element Elem of Op. 5292 // A null Op indicates a vector input whose value will be calculated later; 5293 // there is at most one such input per shuffle and it always has the same 5294 // type as the result. Aborts and returns false if the source vector elements 5295 // of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per 5296 // LLVM they become implicitly extended, but this is rare and not optimized. 5297 bool GeneralShuffle::add(SDValue Op, unsigned Elem) { 5298 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize(); 5299 5300 // The source vector can have wider elements than the result, 5301 // either through an explicit TRUNCATE or because of type legalization. 5302 // We want the least significant part. 5303 EVT FromVT = Op.getNode() ? Op.getValueType() : VT; 5304 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize(); 5305 5306 // Return false if the source elements are smaller than their destination 5307 // elements. 5308 if (FromBytesPerElement < BytesPerElement) 5309 return false; 5310 5311 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes + 5312 (FromBytesPerElement - BytesPerElement)); 5313 5314 // Look through things like shuffles and bitcasts. 5315 while (Op.getNode()) { 5316 if (Op.getOpcode() == ISD::BITCAST) 5317 Op = Op.getOperand(0); 5318 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) { 5319 // See whether the bytes we need come from a contiguous part of one 5320 // operand. 5321 SmallVector<int, SystemZ::VectorBytes> OpBytes; 5322 if (!getVPermMask(Op, OpBytes)) 5323 break; 5324 int NewByte; 5325 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte)) 5326 break; 5327 if (NewByte < 0) { 5328 addUndef(); 5329 return true; 5330 } 5331 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes); 5332 Byte = unsigned(NewByte) % SystemZ::VectorBytes; 5333 } else if (Op.isUndef()) { 5334 addUndef(); 5335 return true; 5336 } else 5337 break; 5338 } 5339 5340 // Make sure that the source of the extraction is in Ops. 5341 unsigned OpNo = 0; 5342 for (; OpNo < Ops.size(); ++OpNo) 5343 if (Ops[OpNo] == Op) 5344 break; 5345 if (OpNo == Ops.size()) 5346 Ops.push_back(Op); 5347 5348 // Add the element to Bytes. 5349 unsigned Base = OpNo * SystemZ::VectorBytes + Byte; 5350 for (unsigned I = 0; I < BytesPerElement; ++I) 5351 Bytes.push_back(Base + I); 5352 5353 return true; 5354 } 5355 5356 // Return SDNodes for the completed shuffle. 5357 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) { 5358 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector"); 5359 5360 if (Ops.size() == 0) 5361 return DAG.getUNDEF(VT); 5362 5363 // Use a single unpack if possible as the last operation. 5364 tryPrepareForUnpack(); 5365 5366 // Make sure that there are at least two shuffle operands. 5367 if (Ops.size() == 1) 5368 Ops.push_back(DAG.getUNDEF(MVT::v16i8)); 5369 5370 // Create a tree of shuffles, deferring root node until after the loop. 5371 // Try to redistribute the undefined elements of non-root nodes so that 5372 // the non-root shuffles match something like a pack or merge, then adjust 5373 // the parent node's permute vector to compensate for the new order. 5374 // Among other things, this copes with vectors like <2 x i16> that were 5375 // padded with undefined elements during type legalization. 5376 // 5377 // In the best case this redistribution will lead to the whole tree 5378 // using packs and merges. It should rarely be a loss in other cases. 5379 unsigned Stride = 1; 5380 for (; Stride * 2 < Ops.size(); Stride *= 2) { 5381 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) { 5382 SDValue SubOps[] = { Ops[I], Ops[I + Stride] }; 5383 5384 // Create a mask for just these two operands. 5385 SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes); 5386 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) { 5387 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes; 5388 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes; 5389 if (OpNo == I) 5390 NewBytes[J] = Byte; 5391 else if (OpNo == I + Stride) 5392 NewBytes[J] = SystemZ::VectorBytes + Byte; 5393 else 5394 NewBytes[J] = -1; 5395 } 5396 // See if it would be better to reorganize NewMask to avoid using VPERM. 5397 SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes); 5398 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) { 5399 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]); 5400 // Applying NewBytesMap to Ops[I] gets back to NewBytes. 5401 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) { 5402 if (NewBytes[J] >= 0) { 5403 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes && 5404 "Invalid double permute"); 5405 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J]; 5406 } else 5407 assert(NewBytesMap[J] < 0 && "Invalid double permute"); 5408 } 5409 } else { 5410 // Just use NewBytes on the operands. 5411 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes); 5412 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) 5413 if (NewBytes[J] >= 0) 5414 Bytes[J] = I * SystemZ::VectorBytes + J; 5415 } 5416 } 5417 } 5418 5419 // Now we just have 2 inputs. Put the second operand in Ops[1]. 5420 if (Stride > 1) { 5421 Ops[1] = Ops[Stride]; 5422 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) 5423 if (Bytes[I] >= int(SystemZ::VectorBytes)) 5424 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes; 5425 } 5426 5427 // Look for an instruction that can do the permute without resorting 5428 // to VPERM. 5429 unsigned OpNo0, OpNo1; 5430 SDValue Op; 5431 if (unpackWasPrepared() && Ops[1].isUndef()) 5432 Op = Ops[0]; 5433 else if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1)) 5434 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]); 5435 else 5436 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes); 5437 5438 Op = insertUnpackIfPrepared(DAG, DL, Op); 5439 5440 return DAG.getNode(ISD::BITCAST, DL, VT, Op); 5441 } 5442 5443 #ifndef NDEBUG 5444 static void dumpBytes(const SmallVectorImpl<int> &Bytes, std::string Msg) { 5445 dbgs() << Msg.c_str() << " { "; 5446 for (unsigned i = 0; i < Bytes.size(); i++) 5447 dbgs() << Bytes[i] << " "; 5448 dbgs() << "}\n"; 5449 } 5450 #endif 5451 5452 // If the Bytes vector matches an unpack operation, prepare to do the unpack 5453 // after all else by removing the zero vector and the effect of the unpack on 5454 // Bytes. 5455 void GeneralShuffle::tryPrepareForUnpack() { 5456 uint32_t ZeroVecOpNo = findZeroVectorIdx(&Ops[0], Ops.size()); 5457 if (ZeroVecOpNo == UINT32_MAX || Ops.size() == 1) 5458 return; 5459 5460 // Only do this if removing the zero vector reduces the depth, otherwise 5461 // the critical path will increase with the final unpack. 5462 if (Ops.size() > 2 && 5463 Log2_32_Ceil(Ops.size()) == Log2_32_Ceil(Ops.size() - 1)) 5464 return; 5465 5466 // Find an unpack that would allow removing the zero vector from Ops. 5467 UnpackFromEltSize = 1; 5468 for (; UnpackFromEltSize <= 4; UnpackFromEltSize *= 2) { 5469 bool MatchUnpack = true; 5470 SmallVector<int, SystemZ::VectorBytes> SrcBytes; 5471 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes; Elt++) { 5472 unsigned ToEltSize = UnpackFromEltSize * 2; 5473 bool IsZextByte = (Elt % ToEltSize) < UnpackFromEltSize; 5474 if (!IsZextByte) 5475 SrcBytes.push_back(Bytes[Elt]); 5476 if (Bytes[Elt] != -1) { 5477 unsigned OpNo = unsigned(Bytes[Elt]) / SystemZ::VectorBytes; 5478 if (IsZextByte != (OpNo == ZeroVecOpNo)) { 5479 MatchUnpack = false; 5480 break; 5481 } 5482 } 5483 } 5484 if (MatchUnpack) { 5485 if (Ops.size() == 2) { 5486 // Don't use unpack if a single source operand needs rearrangement. 5487 for (unsigned i = 0; i < SystemZ::VectorBytes / 2; i++) 5488 if (SrcBytes[i] != -1 && SrcBytes[i] % 16 != int(i)) { 5489 UnpackFromEltSize = UINT_MAX; 5490 return; 5491 } 5492 } 5493 break; 5494 } 5495 } 5496 if (UnpackFromEltSize > 4) 5497 return; 5498 5499 LLVM_DEBUG(dbgs() << "Preparing for final unpack of element size " 5500 << UnpackFromEltSize << ". Zero vector is Op#" << ZeroVecOpNo 5501 << ".\n"; 5502 dumpBytes(Bytes, "Original Bytes vector:");); 5503 5504 // Apply the unpack in reverse to the Bytes array. 5505 unsigned B = 0; 5506 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes;) { 5507 Elt += UnpackFromEltSize; 5508 for (unsigned i = 0; i < UnpackFromEltSize; i++, Elt++, B++) 5509 Bytes[B] = Bytes[Elt]; 5510 } 5511 while (B < SystemZ::VectorBytes) 5512 Bytes[B++] = -1; 5513 5514 // Remove the zero vector from Ops 5515 Ops.erase(&Ops[ZeroVecOpNo]); 5516 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) 5517 if (Bytes[I] >= 0) { 5518 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes; 5519 if (OpNo > ZeroVecOpNo) 5520 Bytes[I] -= SystemZ::VectorBytes; 5521 } 5522 5523 LLVM_DEBUG(dumpBytes(Bytes, "Resulting Bytes vector, zero vector removed:"); 5524 dbgs() << "\n";); 5525 } 5526 5527 SDValue GeneralShuffle::insertUnpackIfPrepared(SelectionDAG &DAG, 5528 const SDLoc &DL, 5529 SDValue Op) { 5530 if (!unpackWasPrepared()) 5531 return Op; 5532 unsigned InBits = UnpackFromEltSize * 8; 5533 EVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBits), 5534 SystemZ::VectorBits / InBits); 5535 SDValue PackedOp = DAG.getNode(ISD::BITCAST, DL, InVT, Op); 5536 unsigned OutBits = InBits * 2; 5537 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(OutBits), 5538 SystemZ::VectorBits / OutBits); 5539 return DAG.getNode(SystemZISD::UNPACKL_HIGH, DL, OutVT, PackedOp); 5540 } 5541 5542 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion. 5543 static bool isScalarToVector(SDValue Op) { 5544 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I) 5545 if (!Op.getOperand(I).isUndef()) 5546 return false; 5547 return true; 5548 } 5549 5550 // Return a vector of type VT that contains Value in the first element. 5551 // The other elements don't matter. 5552 static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT, 5553 SDValue Value) { 5554 // If we have a constant, replicate it to all elements and let the 5555 // BUILD_VECTOR lowering take care of it. 5556 if (Value.getOpcode() == ISD::Constant || 5557 Value.getOpcode() == ISD::ConstantFP) { 5558 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value); 5559 return DAG.getBuildVector(VT, DL, Ops); 5560 } 5561 if (Value.isUndef()) 5562 return DAG.getUNDEF(VT); 5563 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value); 5564 } 5565 5566 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in 5567 // element 1. Used for cases in which replication is cheap. 5568 static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT, 5569 SDValue Op0, SDValue Op1) { 5570 if (Op0.isUndef()) { 5571 if (Op1.isUndef()) 5572 return DAG.getUNDEF(VT); 5573 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1); 5574 } 5575 if (Op1.isUndef()) 5576 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0); 5577 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT, 5578 buildScalarToVector(DAG, DL, VT, Op0), 5579 buildScalarToVector(DAG, DL, VT, Op1)); 5580 } 5581 5582 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64 5583 // vector for them. 5584 static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0, 5585 SDValue Op1) { 5586 if (Op0.isUndef() && Op1.isUndef()) 5587 return DAG.getUNDEF(MVT::v2i64); 5588 // If one of the two inputs is undefined then replicate the other one, 5589 // in order to avoid using another register unnecessarily. 5590 if (Op0.isUndef()) 5591 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1); 5592 else if (Op1.isUndef()) 5593 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 5594 else { 5595 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 5596 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1); 5597 } 5598 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1); 5599 } 5600 5601 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually 5602 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for 5603 // the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR 5604 // would benefit from this representation and return it if so. 5605 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG, 5606 BuildVectorSDNode *BVN) { 5607 EVT VT = BVN->getValueType(0); 5608 unsigned NumElements = VT.getVectorNumElements(); 5609 5610 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation 5611 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still 5612 // need a BUILD_VECTOR, add an additional placeholder operand for that 5613 // BUILD_VECTOR and store its operands in ResidueOps. 5614 GeneralShuffle GS(VT); 5615 SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps; 5616 bool FoundOne = false; 5617 for (unsigned I = 0; I < NumElements; ++I) { 5618 SDValue Op = BVN->getOperand(I); 5619 if (Op.getOpcode() == ISD::TRUNCATE) 5620 Op = Op.getOperand(0); 5621 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5622 Op.getOperand(1).getOpcode() == ISD::Constant) { 5623 unsigned Elem = Op.getConstantOperandVal(1); 5624 if (!GS.add(Op.getOperand(0), Elem)) 5625 return SDValue(); 5626 FoundOne = true; 5627 } else if (Op.isUndef()) { 5628 GS.addUndef(); 5629 } else { 5630 if (!GS.add(SDValue(), ResidueOps.size())) 5631 return SDValue(); 5632 ResidueOps.push_back(BVN->getOperand(I)); 5633 } 5634 } 5635 5636 // Nothing to do if there are no EXTRACT_VECTOR_ELTs. 5637 if (!FoundOne) 5638 return SDValue(); 5639 5640 // Create the BUILD_VECTOR for the remaining elements, if any. 5641 if (!ResidueOps.empty()) { 5642 while (ResidueOps.size() < NumElements) 5643 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType())); 5644 for (auto &Op : GS.Ops) { 5645 if (!Op.getNode()) { 5646 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps); 5647 break; 5648 } 5649 } 5650 } 5651 return GS.getNode(DAG, SDLoc(BVN)); 5652 } 5653 5654 bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const { 5655 if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed()) 5656 return true; 5657 if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV) 5658 return true; 5659 return false; 5660 } 5661 5662 // Combine GPR scalar values Elems into a vector of type VT. 5663 SDValue 5664 SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT, 5665 SmallVectorImpl<SDValue> &Elems) const { 5666 // See whether there is a single replicated value. 5667 SDValue Single; 5668 unsigned int NumElements = Elems.size(); 5669 unsigned int Count = 0; 5670 for (auto Elem : Elems) { 5671 if (!Elem.isUndef()) { 5672 if (!Single.getNode()) 5673 Single = Elem; 5674 else if (Elem != Single) { 5675 Single = SDValue(); 5676 break; 5677 } 5678 Count += 1; 5679 } 5680 } 5681 // There are three cases here: 5682 // 5683 // - if the only defined element is a loaded one, the best sequence 5684 // is a replicating load. 5685 // 5686 // - otherwise, if the only defined element is an i64 value, we will 5687 // end up with the same VLVGP sequence regardless of whether we short-cut 5688 // for replication or fall through to the later code. 5689 // 5690 // - otherwise, if the only defined element is an i32 or smaller value, 5691 // we would need 2 instructions to replicate it: VLVGP followed by VREPx. 5692 // This is only a win if the single defined element is used more than once. 5693 // In other cases we're better off using a single VLVGx. 5694 if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single))) 5695 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single); 5696 5697 // If all elements are loads, use VLREP/VLEs (below). 5698 bool AllLoads = true; 5699 for (auto Elem : Elems) 5700 if (!isVectorElementLoad(Elem)) { 5701 AllLoads = false; 5702 break; 5703 } 5704 5705 // The best way of building a v2i64 from two i64s is to use VLVGP. 5706 if (VT == MVT::v2i64 && !AllLoads) 5707 return joinDwords(DAG, DL, Elems[0], Elems[1]); 5708 5709 // Use a 64-bit merge high to combine two doubles. 5710 if (VT == MVT::v2f64 && !AllLoads) 5711 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]); 5712 5713 // Build v4f32 values directly from the FPRs: 5714 // 5715 // <Axxx> <Bxxx> <Cxxxx> <Dxxx> 5716 // V V VMRHF 5717 // <ABxx> <CDxx> 5718 // V VMRHG 5719 // <ABCD> 5720 if (VT == MVT::v4f32 && !AllLoads) { 5721 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]); 5722 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]); 5723 // Avoid unnecessary undefs by reusing the other operand. 5724 if (Op01.isUndef()) 5725 Op01 = Op23; 5726 else if (Op23.isUndef()) 5727 Op23 = Op01; 5728 // Merging identical replications is a no-op. 5729 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23) 5730 return Op01; 5731 Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01); 5732 Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23); 5733 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH, 5734 DL, MVT::v2i64, Op01, Op23); 5735 return DAG.getNode(ISD::BITCAST, DL, VT, Op); 5736 } 5737 5738 // Collect the constant terms. 5739 SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue()); 5740 SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false); 5741 5742 unsigned NumConstants = 0; 5743 for (unsigned I = 0; I < NumElements; ++I) { 5744 SDValue Elem = Elems[I]; 5745 if (Elem.getOpcode() == ISD::Constant || 5746 Elem.getOpcode() == ISD::ConstantFP) { 5747 NumConstants += 1; 5748 Constants[I] = Elem; 5749 Done[I] = true; 5750 } 5751 } 5752 // If there was at least one constant, fill in the other elements of 5753 // Constants with undefs to get a full vector constant and use that 5754 // as the starting point. 5755 SDValue Result; 5756 SDValue ReplicatedVal; 5757 if (NumConstants > 0) { 5758 for (unsigned I = 0; I < NumElements; ++I) 5759 if (!Constants[I].getNode()) 5760 Constants[I] = DAG.getUNDEF(Elems[I].getValueType()); 5761 Result = DAG.getBuildVector(VT, DL, Constants); 5762 } else { 5763 // Otherwise try to use VLREP or VLVGP to start the sequence in order to 5764 // avoid a false dependency on any previous contents of the vector 5765 // register. 5766 5767 // Use a VLREP if at least one element is a load. Make sure to replicate 5768 // the load with the most elements having its value. 5769 std::map<const SDNode*, unsigned> UseCounts; 5770 SDNode *LoadMaxUses = nullptr; 5771 for (unsigned I = 0; I < NumElements; ++I) 5772 if (isVectorElementLoad(Elems[I])) { 5773 SDNode *Ld = Elems[I].getNode(); 5774 UseCounts[Ld]++; 5775 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < UseCounts[Ld]) 5776 LoadMaxUses = Ld; 5777 } 5778 if (LoadMaxUses != nullptr) { 5779 ReplicatedVal = SDValue(LoadMaxUses, 0); 5780 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal); 5781 } else { 5782 // Try to use VLVGP. 5783 unsigned I1 = NumElements / 2 - 1; 5784 unsigned I2 = NumElements - 1; 5785 bool Def1 = !Elems[I1].isUndef(); 5786 bool Def2 = !Elems[I2].isUndef(); 5787 if (Def1 || Def2) { 5788 SDValue Elem1 = Elems[Def1 ? I1 : I2]; 5789 SDValue Elem2 = Elems[Def2 ? I2 : I1]; 5790 Result = DAG.getNode(ISD::BITCAST, DL, VT, 5791 joinDwords(DAG, DL, Elem1, Elem2)); 5792 Done[I1] = true; 5793 Done[I2] = true; 5794 } else 5795 Result = DAG.getUNDEF(VT); 5796 } 5797 } 5798 5799 // Use VLVGx to insert the other elements. 5800 for (unsigned I = 0; I < NumElements; ++I) 5801 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal) 5802 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I], 5803 DAG.getConstant(I, DL, MVT::i32)); 5804 return Result; 5805 } 5806 5807 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op, 5808 SelectionDAG &DAG) const { 5809 auto *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5810 SDLoc DL(Op); 5811 EVT VT = Op.getValueType(); 5812 5813 if (BVN->isConstant()) { 5814 if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget)) 5815 return Op; 5816 5817 // Fall back to loading it from memory. 5818 return SDValue(); 5819 } 5820 5821 // See if we should use shuffles to construct the vector from other vectors. 5822 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN)) 5823 return Res; 5824 5825 // Detect SCALAR_TO_VECTOR conversions. 5826 if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op)) 5827 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0)); 5828 5829 // Otherwise use buildVector to build the vector up from GPRs. 5830 unsigned NumElements = Op.getNumOperands(); 5831 SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements); 5832 for (unsigned I = 0; I < NumElements; ++I) 5833 Ops[I] = Op.getOperand(I); 5834 return buildVector(DAG, DL, VT, Ops); 5835 } 5836 5837 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5838 SelectionDAG &DAG) const { 5839 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode()); 5840 SDLoc DL(Op); 5841 EVT VT = Op.getValueType(); 5842 unsigned NumElements = VT.getVectorNumElements(); 5843 5844 if (VSN->isSplat()) { 5845 SDValue Op0 = Op.getOperand(0); 5846 unsigned Index = VSN->getSplatIndex(); 5847 assert(Index < VT.getVectorNumElements() && 5848 "Splat index should be defined and in first operand"); 5849 // See whether the value we're splatting is directly available as a scalar. 5850 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) || 5851 Op0.getOpcode() == ISD::BUILD_VECTOR) 5852 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index)); 5853 // Otherwise keep it as a vector-to-vector operation. 5854 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0), 5855 DAG.getTargetConstant(Index, DL, MVT::i32)); 5856 } 5857 5858 GeneralShuffle GS(VT); 5859 for (unsigned I = 0; I < NumElements; ++I) { 5860 int Elt = VSN->getMaskElt(I); 5861 if (Elt < 0) 5862 GS.addUndef(); 5863 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements), 5864 unsigned(Elt) % NumElements)) 5865 return SDValue(); 5866 } 5867 return GS.getNode(DAG, SDLoc(VSN)); 5868 } 5869 5870 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op, 5871 SelectionDAG &DAG) const { 5872 SDLoc DL(Op); 5873 // Just insert the scalar into element 0 of an undefined vector. 5874 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, 5875 Op.getValueType(), DAG.getUNDEF(Op.getValueType()), 5876 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32)); 5877 } 5878 5879 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5880 SelectionDAG &DAG) const { 5881 // Handle insertions of floating-point values. 5882 SDLoc DL(Op); 5883 SDValue Op0 = Op.getOperand(0); 5884 SDValue Op1 = Op.getOperand(1); 5885 SDValue Op2 = Op.getOperand(2); 5886 EVT VT = Op.getValueType(); 5887 5888 // Insertions into constant indices of a v2f64 can be done using VPDI. 5889 // However, if the inserted value is a bitcast or a constant then it's 5890 // better to use GPRs, as below. 5891 if (VT == MVT::v2f64 && 5892 Op1.getOpcode() != ISD::BITCAST && 5893 Op1.getOpcode() != ISD::ConstantFP && 5894 Op2.getOpcode() == ISD::Constant) { 5895 uint64_t Index = Op2->getAsZExtVal(); 5896 unsigned Mask = VT.getVectorNumElements() - 1; 5897 if (Index <= Mask) 5898 return Op; 5899 } 5900 5901 // Otherwise bitcast to the equivalent integer form and insert via a GPR. 5902 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits()); 5903 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements()); 5904 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT, 5905 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), 5906 DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2); 5907 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 5908 } 5909 5910 SDValue 5911 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5912 SelectionDAG &DAG) const { 5913 // Handle extractions of floating-point values. 5914 SDLoc DL(Op); 5915 SDValue Op0 = Op.getOperand(0); 5916 SDValue Op1 = Op.getOperand(1); 5917 EVT VT = Op.getValueType(); 5918 EVT VecVT = Op0.getValueType(); 5919 5920 // Extractions of constant indices can be done directly. 5921 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) { 5922 uint64_t Index = CIndexN->getZExtValue(); 5923 unsigned Mask = VecVT.getVectorNumElements() - 1; 5924 if (Index <= Mask) 5925 return Op; 5926 } 5927 5928 // Otherwise bitcast to the equivalent integer form and extract via a GPR. 5929 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits()); 5930 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements()); 5931 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT, 5932 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1); 5933 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 5934 } 5935 5936 SDValue SystemZTargetLowering:: 5937 lowerSIGN_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const { 5938 SDValue PackedOp = Op.getOperand(0); 5939 EVT OutVT = Op.getValueType(); 5940 EVT InVT = PackedOp.getValueType(); 5941 unsigned ToBits = OutVT.getScalarSizeInBits(); 5942 unsigned FromBits = InVT.getScalarSizeInBits(); 5943 do { 5944 FromBits *= 2; 5945 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits), 5946 SystemZ::VectorBits / FromBits); 5947 PackedOp = 5948 DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(PackedOp), OutVT, PackedOp); 5949 } while (FromBits != ToBits); 5950 return PackedOp; 5951 } 5952 5953 // Lower a ZERO_EXTEND_VECTOR_INREG to a vector shuffle with a zero vector. 5954 SDValue SystemZTargetLowering:: 5955 lowerZERO_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const { 5956 SDValue PackedOp = Op.getOperand(0); 5957 SDLoc DL(Op); 5958 EVT OutVT = Op.getValueType(); 5959 EVT InVT = PackedOp.getValueType(); 5960 unsigned InNumElts = InVT.getVectorNumElements(); 5961 unsigned OutNumElts = OutVT.getVectorNumElements(); 5962 unsigned NumInPerOut = InNumElts / OutNumElts; 5963 5964 SDValue ZeroVec = 5965 DAG.getSplatVector(InVT, DL, DAG.getConstant(0, DL, InVT.getScalarType())); 5966 5967 SmallVector<int, 16> Mask(InNumElts); 5968 unsigned ZeroVecElt = InNumElts; 5969 for (unsigned PackedElt = 0; PackedElt < OutNumElts; PackedElt++) { 5970 unsigned MaskElt = PackedElt * NumInPerOut; 5971 unsigned End = MaskElt + NumInPerOut - 1; 5972 for (; MaskElt < End; MaskElt++) 5973 Mask[MaskElt] = ZeroVecElt++; 5974 Mask[MaskElt] = PackedElt; 5975 } 5976 SDValue Shuf = DAG.getVectorShuffle(InVT, DL, PackedOp, ZeroVec, Mask); 5977 return DAG.getNode(ISD::BITCAST, DL, OutVT, Shuf); 5978 } 5979 5980 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG, 5981 unsigned ByScalar) const { 5982 // Look for cases where a vector shift can use the *_BY_SCALAR form. 5983 SDValue Op0 = Op.getOperand(0); 5984 SDValue Op1 = Op.getOperand(1); 5985 SDLoc DL(Op); 5986 EVT VT = Op.getValueType(); 5987 unsigned ElemBitSize = VT.getScalarSizeInBits(); 5988 5989 // See whether the shift vector is a splat represented as BUILD_VECTOR. 5990 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) { 5991 APInt SplatBits, SplatUndef; 5992 unsigned SplatBitSize; 5993 bool HasAnyUndefs; 5994 // Check for constant splats. Use ElemBitSize as the minimum element 5995 // width and reject splats that need wider elements. 5996 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 5997 ElemBitSize, true) && 5998 SplatBitSize == ElemBitSize) { 5999 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff, 6000 DL, MVT::i32); 6001 return DAG.getNode(ByScalar, DL, VT, Op0, Shift); 6002 } 6003 // Check for variable splats. 6004 BitVector UndefElements; 6005 SDValue Splat = BVN->getSplatValue(&UndefElements); 6006 if (Splat) { 6007 // Since i32 is the smallest legal type, we either need a no-op 6008 // or a truncation. 6009 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat); 6010 return DAG.getNode(ByScalar, DL, VT, Op0, Shift); 6011 } 6012 } 6013 6014 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR, 6015 // and the shift amount is directly available in a GPR. 6016 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) { 6017 if (VSN->isSplat()) { 6018 SDValue VSNOp0 = VSN->getOperand(0); 6019 unsigned Index = VSN->getSplatIndex(); 6020 assert(Index < VT.getVectorNumElements() && 6021 "Splat index should be defined and in first operand"); 6022 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) || 6023 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) { 6024 // Since i32 is the smallest legal type, we either need a no-op 6025 // or a truncation. 6026 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, 6027 VSNOp0.getOperand(Index)); 6028 return DAG.getNode(ByScalar, DL, VT, Op0, Shift); 6029 } 6030 } 6031 } 6032 6033 // Otherwise just treat the current form as legal. 6034 return Op; 6035 } 6036 6037 SDValue SystemZTargetLowering::lowerIS_FPCLASS(SDValue Op, 6038 SelectionDAG &DAG) const { 6039 SDLoc DL(Op); 6040 MVT ResultVT = Op.getSimpleValueType(); 6041 SDValue Arg = Op.getOperand(0); 6042 auto CNode = cast<ConstantSDNode>(Op.getOperand(1)); 6043 unsigned Check = CNode->getZExtValue(); 6044 6045 unsigned TDCMask = 0; 6046 if (Check & fcSNan) 6047 TDCMask |= SystemZ::TDCMASK_SNAN_PLUS | SystemZ::TDCMASK_SNAN_MINUS; 6048 if (Check & fcQNan) 6049 TDCMask |= SystemZ::TDCMASK_QNAN_PLUS | SystemZ::TDCMASK_QNAN_MINUS; 6050 if (Check & fcPosInf) 6051 TDCMask |= SystemZ::TDCMASK_INFINITY_PLUS; 6052 if (Check & fcNegInf) 6053 TDCMask |= SystemZ::TDCMASK_INFINITY_MINUS; 6054 if (Check & fcPosNormal) 6055 TDCMask |= SystemZ::TDCMASK_NORMAL_PLUS; 6056 if (Check & fcNegNormal) 6057 TDCMask |= SystemZ::TDCMASK_NORMAL_MINUS; 6058 if (Check & fcPosSubnormal) 6059 TDCMask |= SystemZ::TDCMASK_SUBNORMAL_PLUS; 6060 if (Check & fcNegSubnormal) 6061 TDCMask |= SystemZ::TDCMASK_SUBNORMAL_MINUS; 6062 if (Check & fcPosZero) 6063 TDCMask |= SystemZ::TDCMASK_ZERO_PLUS; 6064 if (Check & fcNegZero) 6065 TDCMask |= SystemZ::TDCMASK_ZERO_MINUS; 6066 SDValue TDCMaskV = DAG.getConstant(TDCMask, DL, MVT::i64); 6067 6068 SDValue Intr = DAG.getNode(SystemZISD::TDC, DL, ResultVT, Arg, TDCMaskV); 6069 return getCCResult(DAG, Intr); 6070 } 6071 6072 SDValue SystemZTargetLowering::LowerOperation(SDValue Op, 6073 SelectionDAG &DAG) const { 6074 switch (Op.getOpcode()) { 6075 case ISD::FRAMEADDR: 6076 return lowerFRAMEADDR(Op, DAG); 6077 case ISD::RETURNADDR: 6078 return lowerRETURNADDR(Op, DAG); 6079 case ISD::BR_CC: 6080 return lowerBR_CC(Op, DAG); 6081 case ISD::SELECT_CC: 6082 return lowerSELECT_CC(Op, DAG); 6083 case ISD::SETCC: 6084 return lowerSETCC(Op, DAG); 6085 case ISD::STRICT_FSETCC: 6086 return lowerSTRICT_FSETCC(Op, DAG, false); 6087 case ISD::STRICT_FSETCCS: 6088 return lowerSTRICT_FSETCC(Op, DAG, true); 6089 case ISD::GlobalAddress: 6090 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG); 6091 case ISD::GlobalTLSAddress: 6092 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG); 6093 case ISD::BlockAddress: 6094 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG); 6095 case ISD::JumpTable: 6096 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG); 6097 case ISD::ConstantPool: 6098 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG); 6099 case ISD::BITCAST: 6100 return lowerBITCAST(Op, DAG); 6101 case ISD::VASTART: 6102 return lowerVASTART(Op, DAG); 6103 case ISD::VACOPY: 6104 return lowerVACOPY(Op, DAG); 6105 case ISD::DYNAMIC_STACKALLOC: 6106 return lowerDYNAMIC_STACKALLOC(Op, DAG); 6107 case ISD::GET_DYNAMIC_AREA_OFFSET: 6108 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 6109 case ISD::SMUL_LOHI: 6110 return lowerSMUL_LOHI(Op, DAG); 6111 case ISD::UMUL_LOHI: 6112 return lowerUMUL_LOHI(Op, DAG); 6113 case ISD::SDIVREM: 6114 return lowerSDIVREM(Op, DAG); 6115 case ISD::UDIVREM: 6116 return lowerUDIVREM(Op, DAG); 6117 case ISD::SADDO: 6118 case ISD::SSUBO: 6119 case ISD::UADDO: 6120 case ISD::USUBO: 6121 return lowerXALUO(Op, DAG); 6122 case ISD::UADDO_CARRY: 6123 case ISD::USUBO_CARRY: 6124 return lowerUADDSUBO_CARRY(Op, DAG); 6125 case ISD::OR: 6126 return lowerOR(Op, DAG); 6127 case ISD::CTPOP: 6128 return lowerCTPOP(Op, DAG); 6129 case ISD::ATOMIC_FENCE: 6130 return lowerATOMIC_FENCE(Op, DAG); 6131 case ISD::ATOMIC_SWAP: 6132 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW); 6133 case ISD::ATOMIC_STORE: 6134 return lowerATOMIC_STORE(Op, DAG); 6135 case ISD::ATOMIC_LOAD: 6136 return lowerATOMIC_LOAD(Op, DAG); 6137 case ISD::ATOMIC_LOAD_ADD: 6138 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD); 6139 case ISD::ATOMIC_LOAD_SUB: 6140 return lowerATOMIC_LOAD_SUB(Op, DAG); 6141 case ISD::ATOMIC_LOAD_AND: 6142 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND); 6143 case ISD::ATOMIC_LOAD_OR: 6144 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR); 6145 case ISD::ATOMIC_LOAD_XOR: 6146 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR); 6147 case ISD::ATOMIC_LOAD_NAND: 6148 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND); 6149 case ISD::ATOMIC_LOAD_MIN: 6150 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN); 6151 case ISD::ATOMIC_LOAD_MAX: 6152 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX); 6153 case ISD::ATOMIC_LOAD_UMIN: 6154 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN); 6155 case ISD::ATOMIC_LOAD_UMAX: 6156 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX); 6157 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 6158 return lowerATOMIC_CMP_SWAP(Op, DAG); 6159 case ISD::STACKSAVE: 6160 return lowerSTACKSAVE(Op, DAG); 6161 case ISD::STACKRESTORE: 6162 return lowerSTACKRESTORE(Op, DAG); 6163 case ISD::PREFETCH: 6164 return lowerPREFETCH(Op, DAG); 6165 case ISD::INTRINSIC_W_CHAIN: 6166 return lowerINTRINSIC_W_CHAIN(Op, DAG); 6167 case ISD::INTRINSIC_WO_CHAIN: 6168 return lowerINTRINSIC_WO_CHAIN(Op, DAG); 6169 case ISD::BUILD_VECTOR: 6170 return lowerBUILD_VECTOR(Op, DAG); 6171 case ISD::VECTOR_SHUFFLE: 6172 return lowerVECTOR_SHUFFLE(Op, DAG); 6173 case ISD::SCALAR_TO_VECTOR: 6174 return lowerSCALAR_TO_VECTOR(Op, DAG); 6175 case ISD::INSERT_VECTOR_ELT: 6176 return lowerINSERT_VECTOR_ELT(Op, DAG); 6177 case ISD::EXTRACT_VECTOR_ELT: 6178 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 6179 case ISD::SIGN_EXTEND_VECTOR_INREG: 6180 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG); 6181 case ISD::ZERO_EXTEND_VECTOR_INREG: 6182 return lowerZERO_EXTEND_VECTOR_INREG(Op, DAG); 6183 case ISD::SHL: 6184 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR); 6185 case ISD::SRL: 6186 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR); 6187 case ISD::SRA: 6188 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR); 6189 case ISD::ROTL: 6190 return lowerShift(Op, DAG, SystemZISD::VROTL_BY_SCALAR); 6191 case ISD::IS_FPCLASS: 6192 return lowerIS_FPCLASS(Op, DAG); 6193 case ISD::GET_ROUNDING: 6194 return lowerGET_ROUNDING(Op, DAG); 6195 default: 6196 llvm_unreachable("Unexpected node to lower"); 6197 } 6198 } 6199 6200 // Lower operations with invalid operand or result types (currently used 6201 // only for 128-bit integer types). 6202 void 6203 SystemZTargetLowering::LowerOperationWrapper(SDNode *N, 6204 SmallVectorImpl<SDValue> &Results, 6205 SelectionDAG &DAG) const { 6206 switch (N->getOpcode()) { 6207 case ISD::ATOMIC_LOAD: { 6208 SDLoc DL(N); 6209 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::Other); 6210 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) }; 6211 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 6212 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128, 6213 DL, Tys, Ops, MVT::i128, MMO); 6214 Results.push_back(lowerGR128ToI128(DAG, Res)); 6215 Results.push_back(Res.getValue(1)); 6216 break; 6217 } 6218 case ISD::ATOMIC_STORE: { 6219 SDLoc DL(N); 6220 SDVTList Tys = DAG.getVTList(MVT::Other); 6221 SDValue Ops[] = {N->getOperand(0), lowerI128ToGR128(DAG, N->getOperand(1)), 6222 N->getOperand(2)}; 6223 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 6224 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128, 6225 DL, Tys, Ops, MVT::i128, MMO); 6226 // We have to enforce sequential consistency by performing a 6227 // serialization operation after the store. 6228 if (cast<AtomicSDNode>(N)->getSuccessOrdering() == 6229 AtomicOrdering::SequentiallyConsistent) 6230 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, 6231 MVT::Other, Res), 0); 6232 Results.push_back(Res); 6233 break; 6234 } 6235 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: { 6236 SDLoc DL(N); 6237 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other); 6238 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), 6239 lowerI128ToGR128(DAG, N->getOperand(2)), 6240 lowerI128ToGR128(DAG, N->getOperand(3)) }; 6241 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 6242 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128, 6243 DL, Tys, Ops, MVT::i128, MMO); 6244 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1), 6245 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ); 6246 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1)); 6247 Results.push_back(lowerGR128ToI128(DAG, Res)); 6248 Results.push_back(Success); 6249 Results.push_back(Res.getValue(2)); 6250 break; 6251 } 6252 case ISD::BITCAST: { 6253 SDValue Src = N->getOperand(0); 6254 if (N->getValueType(0) == MVT::i128 && Src.getValueType() == MVT::f128 && 6255 !useSoftFloat()) { 6256 SDLoc DL(N); 6257 SDValue Lo, Hi; 6258 if (getRepRegClassFor(MVT::f128) == &SystemZ::VR128BitRegClass) { 6259 SDValue VecBC = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Src); 6260 Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, VecBC, 6261 DAG.getConstant(1, DL, MVT::i32)); 6262 Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, VecBC, 6263 DAG.getConstant(0, DL, MVT::i32)); 6264 } else { 6265 assert(getRepRegClassFor(MVT::f128) == &SystemZ::FP128BitRegClass && 6266 "Unrecognized register class for f128."); 6267 SDValue LoFP = DAG.getTargetExtractSubreg(SystemZ::subreg_l64, 6268 DL, MVT::f64, Src); 6269 SDValue HiFP = DAG.getTargetExtractSubreg(SystemZ::subreg_h64, 6270 DL, MVT::f64, Src); 6271 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::i64, LoFP); 6272 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::i64, HiFP); 6273 } 6274 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi)); 6275 } 6276 break; 6277 } 6278 default: 6279 llvm_unreachable("Unexpected node to lower"); 6280 } 6281 } 6282 6283 void 6284 SystemZTargetLowering::ReplaceNodeResults(SDNode *N, 6285 SmallVectorImpl<SDValue> &Results, 6286 SelectionDAG &DAG) const { 6287 return LowerOperationWrapper(N, Results, DAG); 6288 } 6289 6290 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const { 6291 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME 6292 switch ((SystemZISD::NodeType)Opcode) { 6293 case SystemZISD::FIRST_NUMBER: break; 6294 OPCODE(RET_GLUE); 6295 OPCODE(CALL); 6296 OPCODE(SIBCALL); 6297 OPCODE(TLS_GDCALL); 6298 OPCODE(TLS_LDCALL); 6299 OPCODE(PCREL_WRAPPER); 6300 OPCODE(PCREL_OFFSET); 6301 OPCODE(ICMP); 6302 OPCODE(FCMP); 6303 OPCODE(STRICT_FCMP); 6304 OPCODE(STRICT_FCMPS); 6305 OPCODE(TM); 6306 OPCODE(BR_CCMASK); 6307 OPCODE(SELECT_CCMASK); 6308 OPCODE(ADJDYNALLOC); 6309 OPCODE(PROBED_ALLOCA); 6310 OPCODE(POPCNT); 6311 OPCODE(SMUL_LOHI); 6312 OPCODE(UMUL_LOHI); 6313 OPCODE(SDIVREM); 6314 OPCODE(UDIVREM); 6315 OPCODE(SADDO); 6316 OPCODE(SSUBO); 6317 OPCODE(UADDO); 6318 OPCODE(USUBO); 6319 OPCODE(ADDCARRY); 6320 OPCODE(SUBCARRY); 6321 OPCODE(GET_CCMASK); 6322 OPCODE(MVC); 6323 OPCODE(NC); 6324 OPCODE(OC); 6325 OPCODE(XC); 6326 OPCODE(CLC); 6327 OPCODE(MEMSET_MVC); 6328 OPCODE(STPCPY); 6329 OPCODE(STRCMP); 6330 OPCODE(SEARCH_STRING); 6331 OPCODE(IPM); 6332 OPCODE(TBEGIN); 6333 OPCODE(TBEGIN_NOFLOAT); 6334 OPCODE(TEND); 6335 OPCODE(BYTE_MASK); 6336 OPCODE(ROTATE_MASK); 6337 OPCODE(REPLICATE); 6338 OPCODE(JOIN_DWORDS); 6339 OPCODE(SPLAT); 6340 OPCODE(MERGE_HIGH); 6341 OPCODE(MERGE_LOW); 6342 OPCODE(SHL_DOUBLE); 6343 OPCODE(PERMUTE_DWORDS); 6344 OPCODE(PERMUTE); 6345 OPCODE(PACK); 6346 OPCODE(PACKS_CC); 6347 OPCODE(PACKLS_CC); 6348 OPCODE(UNPACK_HIGH); 6349 OPCODE(UNPACKL_HIGH); 6350 OPCODE(UNPACK_LOW); 6351 OPCODE(UNPACKL_LOW); 6352 OPCODE(VSHL_BY_SCALAR); 6353 OPCODE(VSRL_BY_SCALAR); 6354 OPCODE(VSRA_BY_SCALAR); 6355 OPCODE(VROTL_BY_SCALAR); 6356 OPCODE(VSUM); 6357 OPCODE(VACC); 6358 OPCODE(VSCBI); 6359 OPCODE(VAC); 6360 OPCODE(VSBI); 6361 OPCODE(VACCC); 6362 OPCODE(VSBCBI); 6363 OPCODE(VICMPE); 6364 OPCODE(VICMPH); 6365 OPCODE(VICMPHL); 6366 OPCODE(VICMPES); 6367 OPCODE(VICMPHS); 6368 OPCODE(VICMPHLS); 6369 OPCODE(VFCMPE); 6370 OPCODE(STRICT_VFCMPE); 6371 OPCODE(STRICT_VFCMPES); 6372 OPCODE(VFCMPH); 6373 OPCODE(STRICT_VFCMPH); 6374 OPCODE(STRICT_VFCMPHS); 6375 OPCODE(VFCMPHE); 6376 OPCODE(STRICT_VFCMPHE); 6377 OPCODE(STRICT_VFCMPHES); 6378 OPCODE(VFCMPES); 6379 OPCODE(VFCMPHS); 6380 OPCODE(VFCMPHES); 6381 OPCODE(VFTCI); 6382 OPCODE(VEXTEND); 6383 OPCODE(STRICT_VEXTEND); 6384 OPCODE(VROUND); 6385 OPCODE(STRICT_VROUND); 6386 OPCODE(VTM); 6387 OPCODE(SCMP128HI); 6388 OPCODE(UCMP128HI); 6389 OPCODE(VFAE_CC); 6390 OPCODE(VFAEZ_CC); 6391 OPCODE(VFEE_CC); 6392 OPCODE(VFEEZ_CC); 6393 OPCODE(VFENE_CC); 6394 OPCODE(VFENEZ_CC); 6395 OPCODE(VISTR_CC); 6396 OPCODE(VSTRC_CC); 6397 OPCODE(VSTRCZ_CC); 6398 OPCODE(VSTRS_CC); 6399 OPCODE(VSTRSZ_CC); 6400 OPCODE(TDC); 6401 OPCODE(ATOMIC_SWAPW); 6402 OPCODE(ATOMIC_LOADW_ADD); 6403 OPCODE(ATOMIC_LOADW_SUB); 6404 OPCODE(ATOMIC_LOADW_AND); 6405 OPCODE(ATOMIC_LOADW_OR); 6406 OPCODE(ATOMIC_LOADW_XOR); 6407 OPCODE(ATOMIC_LOADW_NAND); 6408 OPCODE(ATOMIC_LOADW_MIN); 6409 OPCODE(ATOMIC_LOADW_MAX); 6410 OPCODE(ATOMIC_LOADW_UMIN); 6411 OPCODE(ATOMIC_LOADW_UMAX); 6412 OPCODE(ATOMIC_CMP_SWAPW); 6413 OPCODE(ATOMIC_CMP_SWAP); 6414 OPCODE(ATOMIC_LOAD_128); 6415 OPCODE(ATOMIC_STORE_128); 6416 OPCODE(ATOMIC_CMP_SWAP_128); 6417 OPCODE(LRV); 6418 OPCODE(STRV); 6419 OPCODE(VLER); 6420 OPCODE(VSTER); 6421 OPCODE(PREFETCH); 6422 OPCODE(ADA_ENTRY); 6423 } 6424 return nullptr; 6425 #undef OPCODE 6426 } 6427 6428 // Return true if VT is a vector whose elements are a whole number of bytes 6429 // in width. Also check for presence of vector support. 6430 bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const { 6431 if (!Subtarget.hasVector()) 6432 return false; 6433 6434 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple(); 6435 } 6436 6437 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT 6438 // producing a result of type ResVT. Op is a possibly bitcast version 6439 // of the input vector and Index is the index (based on type VecVT) that 6440 // should be extracted. Return the new extraction if a simplification 6441 // was possible or if Force is true. 6442 SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT, 6443 EVT VecVT, SDValue Op, 6444 unsigned Index, 6445 DAGCombinerInfo &DCI, 6446 bool Force) const { 6447 SelectionDAG &DAG = DCI.DAG; 6448 6449 // The number of bytes being extracted. 6450 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize(); 6451 6452 for (;;) { 6453 unsigned Opcode = Op.getOpcode(); 6454 if (Opcode == ISD::BITCAST) 6455 // Look through bitcasts. 6456 Op = Op.getOperand(0); 6457 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) && 6458 canTreatAsByteVector(Op.getValueType())) { 6459 // Get a VPERM-like permute mask and see whether the bytes covered 6460 // by the extracted element are a contiguous sequence from one 6461 // source operand. 6462 SmallVector<int, SystemZ::VectorBytes> Bytes; 6463 if (!getVPermMask(Op, Bytes)) 6464 break; 6465 int First; 6466 if (!getShuffleInput(Bytes, Index * BytesPerElement, 6467 BytesPerElement, First)) 6468 break; 6469 if (First < 0) 6470 return DAG.getUNDEF(ResVT); 6471 // Make sure the contiguous sequence starts at a multiple of the 6472 // original element size. 6473 unsigned Byte = unsigned(First) % Bytes.size(); 6474 if (Byte % BytesPerElement != 0) 6475 break; 6476 // We can get the extracted value directly from an input. 6477 Index = Byte / BytesPerElement; 6478 Op = Op.getOperand(unsigned(First) / Bytes.size()); 6479 Force = true; 6480 } else if (Opcode == ISD::BUILD_VECTOR && 6481 canTreatAsByteVector(Op.getValueType())) { 6482 // We can only optimize this case if the BUILD_VECTOR elements are 6483 // at least as wide as the extracted value. 6484 EVT OpVT = Op.getValueType(); 6485 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize(); 6486 if (OpBytesPerElement < BytesPerElement) 6487 break; 6488 // Make sure that the least-significant bit of the extracted value 6489 // is the least significant bit of an input. 6490 unsigned End = (Index + 1) * BytesPerElement; 6491 if (End % OpBytesPerElement != 0) 6492 break; 6493 // We're extracting the low part of one operand of the BUILD_VECTOR. 6494 Op = Op.getOperand(End / OpBytesPerElement - 1); 6495 if (!Op.getValueType().isInteger()) { 6496 EVT VT = MVT::getIntegerVT(Op.getValueSizeInBits()); 6497 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op); 6498 DCI.AddToWorklist(Op.getNode()); 6499 } 6500 EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits()); 6501 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 6502 if (VT != ResVT) { 6503 DCI.AddToWorklist(Op.getNode()); 6504 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op); 6505 } 6506 return Op; 6507 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 6508 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG || 6509 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) && 6510 canTreatAsByteVector(Op.getValueType()) && 6511 canTreatAsByteVector(Op.getOperand(0).getValueType())) { 6512 // Make sure that only the unextended bits are significant. 6513 EVT ExtVT = Op.getValueType(); 6514 EVT OpVT = Op.getOperand(0).getValueType(); 6515 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize(); 6516 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize(); 6517 unsigned Byte = Index * BytesPerElement; 6518 unsigned SubByte = Byte % ExtBytesPerElement; 6519 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement; 6520 if (SubByte < MinSubByte || 6521 SubByte + BytesPerElement > ExtBytesPerElement) 6522 break; 6523 // Get the byte offset of the unextended element 6524 Byte = Byte / ExtBytesPerElement * OpBytesPerElement; 6525 // ...then add the byte offset relative to that element. 6526 Byte += SubByte - MinSubByte; 6527 if (Byte % BytesPerElement != 0) 6528 break; 6529 Op = Op.getOperand(0); 6530 Index = Byte / BytesPerElement; 6531 Force = true; 6532 } else 6533 break; 6534 } 6535 if (Force) { 6536 if (Op.getValueType() != VecVT) { 6537 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op); 6538 DCI.AddToWorklist(Op.getNode()); 6539 } 6540 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op, 6541 DAG.getConstant(Index, DL, MVT::i32)); 6542 } 6543 return SDValue(); 6544 } 6545 6546 // Optimize vector operations in scalar value Op on the basis that Op 6547 // is truncated to TruncVT. 6548 SDValue SystemZTargetLowering::combineTruncateExtract( 6549 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const { 6550 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into 6551 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements 6552 // of type TruncVT. 6553 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6554 TruncVT.getSizeInBits() % 8 == 0) { 6555 SDValue Vec = Op.getOperand(0); 6556 EVT VecVT = Vec.getValueType(); 6557 if (canTreatAsByteVector(VecVT)) { 6558 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 6559 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize(); 6560 unsigned TruncBytes = TruncVT.getStoreSize(); 6561 if (BytesPerElement % TruncBytes == 0) { 6562 // Calculate the value of Y' in the above description. We are 6563 // splitting the original elements into Scale equal-sized pieces 6564 // and for truncation purposes want the last (least-significant) 6565 // of these pieces for IndexN. This is easiest to do by calculating 6566 // the start index of the following element and then subtracting 1. 6567 unsigned Scale = BytesPerElement / TruncBytes; 6568 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1; 6569 6570 // Defer the creation of the bitcast from X to combineExtract, 6571 // which might be able to optimize the extraction. 6572 VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8), 6573 VecVT.getStoreSize() / TruncBytes); 6574 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT); 6575 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true); 6576 } 6577 } 6578 } 6579 } 6580 return SDValue(); 6581 } 6582 6583 SDValue SystemZTargetLowering::combineZERO_EXTEND( 6584 SDNode *N, DAGCombinerInfo &DCI) const { 6585 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2') 6586 SelectionDAG &DAG = DCI.DAG; 6587 SDValue N0 = N->getOperand(0); 6588 EVT VT = N->getValueType(0); 6589 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) { 6590 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 6591 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6592 if (TrueOp && FalseOp) { 6593 SDLoc DL(N0); 6594 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT), 6595 DAG.getConstant(FalseOp->getZExtValue(), DL, VT), 6596 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) }; 6597 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops); 6598 // If N0 has multiple uses, change other uses as well. 6599 if (!N0.hasOneUse()) { 6600 SDValue TruncSelect = 6601 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect); 6602 DCI.CombineTo(N0.getNode(), TruncSelect); 6603 } 6604 return NewSelect; 6605 } 6606 } 6607 return SDValue(); 6608 } 6609 6610 SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG( 6611 SDNode *N, DAGCombinerInfo &DCI) const { 6612 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1) 6613 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1) 6614 // into (select_cc LHS, RHS, -1, 0, COND) 6615 SelectionDAG &DAG = DCI.DAG; 6616 SDValue N0 = N->getOperand(0); 6617 EVT VT = N->getValueType(0); 6618 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6619 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND) 6620 N0 = N0.getOperand(0); 6621 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) { 6622 SDLoc DL(N0); 6623 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1), 6624 DAG.getConstant(-1, DL, VT), DAG.getConstant(0, DL, VT), 6625 N0.getOperand(2) }; 6626 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 6627 } 6628 return SDValue(); 6629 } 6630 6631 SDValue SystemZTargetLowering::combineSIGN_EXTEND( 6632 SDNode *N, DAGCombinerInfo &DCI) const { 6633 // Convert (sext (ashr (shl X, C1), C2)) to 6634 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as 6635 // cheap as narrower ones. 6636 SelectionDAG &DAG = DCI.DAG; 6637 SDValue N0 = N->getOperand(0); 6638 EVT VT = N->getValueType(0); 6639 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) { 6640 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6641 SDValue Inner = N0.getOperand(0); 6642 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) { 6643 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) { 6644 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits()); 6645 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra; 6646 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra; 6647 EVT ShiftVT = N0.getOperand(1).getValueType(); 6648 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT, 6649 Inner.getOperand(0)); 6650 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext, 6651 DAG.getConstant(NewShlAmt, SDLoc(Inner), 6652 ShiftVT)); 6653 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, 6654 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT)); 6655 } 6656 } 6657 } 6658 return SDValue(); 6659 } 6660 6661 SDValue SystemZTargetLowering::combineMERGE( 6662 SDNode *N, DAGCombinerInfo &DCI) const { 6663 SelectionDAG &DAG = DCI.DAG; 6664 unsigned Opcode = N->getOpcode(); 6665 SDValue Op0 = N->getOperand(0); 6666 SDValue Op1 = N->getOperand(1); 6667 if (Op0.getOpcode() == ISD::BITCAST) 6668 Op0 = Op0.getOperand(0); 6669 if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6670 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF 6671 // for v4f32. 6672 if (Op1 == N->getOperand(0)) 6673 return Op1; 6674 // (z_merge_? 0, X) -> (z_unpackl_? 0, X). 6675 EVT VT = Op1.getValueType(); 6676 unsigned ElemBytes = VT.getVectorElementType().getStoreSize(); 6677 if (ElemBytes <= 4) { 6678 Opcode = (Opcode == SystemZISD::MERGE_HIGH ? 6679 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW); 6680 EVT InVT = VT.changeVectorElementTypeToInteger(); 6681 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16), 6682 SystemZ::VectorBytes / ElemBytes / 2); 6683 if (VT != InVT) { 6684 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1); 6685 DCI.AddToWorklist(Op1.getNode()); 6686 } 6687 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1); 6688 DCI.AddToWorklist(Op.getNode()); 6689 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 6690 } 6691 } 6692 return SDValue(); 6693 } 6694 6695 SDValue SystemZTargetLowering::combineLOAD( 6696 SDNode *N, DAGCombinerInfo &DCI) const { 6697 SelectionDAG &DAG = DCI.DAG; 6698 EVT LdVT = N->getValueType(0); 6699 SDLoc DL(N); 6700 6701 // Replace an i128 load that is used solely to move its value into GPRs 6702 // by separate loads of both halves. 6703 if (LdVT == MVT::i128) { 6704 LoadSDNode *LD = cast<LoadSDNode>(N); 6705 if (!LD->isSimple() || !ISD::isNormalLoad(LD)) 6706 return SDValue(); 6707 6708 // Scan through all users. 6709 SmallVector<std::pair<SDNode *, int>, 2> Users; 6710 int UsedElements = 0; 6711 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 6712 UI != UIEnd; ++UI) { 6713 // Skip the uses of the chain. 6714 if (UI.getUse().getResNo() != 0) 6715 continue; 6716 6717 // Verify every user is a TRUNCATE to i64 of the low or high half ... 6718 SDNode *User = *UI; 6719 int Index = 1; 6720 if (User->getOpcode() == ISD::SRL && 6721 User->getOperand(1).getOpcode() == ISD::Constant && 6722 User->getConstantOperandVal(1) == 64 && User->hasOneUse()) { 6723 User = *User->use_begin(); 6724 Index = 0; 6725 } 6726 if (User->getOpcode() != ISD::TRUNCATE || 6727 User->getValueType(0) != MVT::i64) 6728 return SDValue(); 6729 6730 // ... and no half is extracted twice. 6731 if (UsedElements & (1 << Index)) 6732 return SDValue(); 6733 6734 UsedElements |= 1 << Index; 6735 Users.push_back(std::make_pair(User, Index)); 6736 } 6737 6738 // Rewrite each extraction as an independent load. 6739 SmallVector<SDValue, 2> ArgChains; 6740 for (auto UserAndIndex : Users) { 6741 SDNode *User = UserAndIndex.first; 6742 unsigned Offset = User->getValueType(0).getStoreSize() * UserAndIndex.second; 6743 SDValue Ptr = 6744 DAG.getMemBasePlusOffset(LD->getBasePtr(), TypeSize::getFixed(Offset), DL); 6745 SDValue EltLoad = 6746 DAG.getLoad(User->getValueType(0), DL, LD->getChain(), Ptr, 6747 LD->getPointerInfo().getWithOffset(Offset), 6748 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 6749 LD->getAAInfo()); 6750 6751 DCI.CombineTo(User, EltLoad, true); 6752 ArgChains.push_back(EltLoad.getValue(1)); 6753 } 6754 6755 // Collect all chains via TokenFactor. 6756 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 6757 ArgChains); 6758 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 6759 DCI.AddToWorklist(Chain.getNode()); 6760 return SDValue(N, 0); 6761 } 6762 6763 if (LdVT.isVector() || LdVT.isInteger()) 6764 return SDValue(); 6765 // Transform a scalar load that is REPLICATEd as well as having other 6766 // use(s) to the form where the other use(s) use the first element of the 6767 // REPLICATE instead of the load. Otherwise instruction selection will not 6768 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating 6769 // point loads. 6770 6771 SDValue Replicate; 6772 SmallVector<SDNode*, 8> OtherUses; 6773 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6774 UI != UE; ++UI) { 6775 if (UI->getOpcode() == SystemZISD::REPLICATE) { 6776 if (Replicate) 6777 return SDValue(); // Should never happen 6778 Replicate = SDValue(*UI, 0); 6779 } 6780 else if (UI.getUse().getResNo() == 0) 6781 OtherUses.push_back(*UI); 6782 } 6783 if (!Replicate || OtherUses.empty()) 6784 return SDValue(); 6785 6786 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT, 6787 Replicate, DAG.getConstant(0, DL, MVT::i32)); 6788 // Update uses of the loaded Value while preserving old chains. 6789 for (SDNode *U : OtherUses) { 6790 SmallVector<SDValue, 8> Ops; 6791 for (SDValue Op : U->ops()) 6792 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op); 6793 DAG.UpdateNodeOperands(U, Ops); 6794 } 6795 return SDValue(N, 0); 6796 } 6797 6798 bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const { 6799 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) 6800 return true; 6801 if (Subtarget.hasVectorEnhancements2()) 6802 if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64 || VT == MVT::i128) 6803 return true; 6804 return false; 6805 } 6806 6807 static bool isVectorElementSwap(ArrayRef<int> M, EVT VT) { 6808 if (!VT.isVector() || !VT.isSimple() || 6809 VT.getSizeInBits() != 128 || 6810 VT.getScalarSizeInBits() % 8 != 0) 6811 return false; 6812 6813 unsigned NumElts = VT.getVectorNumElements(); 6814 for (unsigned i = 0; i < NumElts; ++i) { 6815 if (M[i] < 0) continue; // ignore UNDEF indices 6816 if ((unsigned) M[i] != NumElts - 1 - i) 6817 return false; 6818 } 6819 6820 return true; 6821 } 6822 6823 static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG) { 6824 for (auto *U : StoredVal->uses()) { 6825 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(U)) { 6826 EVT CurrMemVT = ST->getMemoryVT().getScalarType(); 6827 if (CurrMemVT.isRound() && CurrMemVT.getStoreSize() <= 16) 6828 continue; 6829 } else if (isa<BuildVectorSDNode>(U)) { 6830 SDValue BuildVector = SDValue(U, 0); 6831 if (DAG.isSplatValue(BuildVector, true/*AllowUndefs*/) && 6832 isOnlyUsedByStores(BuildVector, DAG)) 6833 continue; 6834 } 6835 return false; 6836 } 6837 return true; 6838 } 6839 6840 static bool isMovedFromParts(SDValue Val, SDValue &LoPart, SDValue &HiPart) { 6841 if (Val.getOpcode() != ISD::OR || !Val.getNode()->hasOneUse()) 6842 return false; 6843 6844 SDValue Op0 = Val.getOperand(0); 6845 SDValue Op1 = Val.getOperand(1); 6846 6847 if (Op0.getOpcode() == ISD::SHL) 6848 std::swap(Op0, Op1); 6849 if (Op1.getOpcode() != ISD::SHL || !Op1.getNode()->hasOneUse() || 6850 Op1.getOperand(1).getOpcode() != ISD::Constant || 6851 Op1.getConstantOperandVal(1) != 64) 6852 return false; 6853 Op1 = Op1.getOperand(0); 6854 6855 if (Op0.getOpcode() != ISD::ZERO_EXTEND || !Op0.getNode()->hasOneUse() || 6856 Op0.getOperand(0).getValueType() != MVT::i64) 6857 return false; 6858 if (Op1.getOpcode() != ISD::ANY_EXTEND || !Op1.getNode()->hasOneUse() || 6859 Op1.getOperand(0).getValueType() != MVT::i64) 6860 return false; 6861 6862 LoPart = Op0.getOperand(0); 6863 HiPart = Op1.getOperand(0); 6864 return true; 6865 } 6866 6867 SDValue SystemZTargetLowering::combineSTORE( 6868 SDNode *N, DAGCombinerInfo &DCI) const { 6869 SelectionDAG &DAG = DCI.DAG; 6870 auto *SN = cast<StoreSDNode>(N); 6871 auto &Op1 = N->getOperand(1); 6872 EVT MemVT = SN->getMemoryVT(); 6873 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better 6874 // for the extraction to be done on a vMiN value, so that we can use VSTE. 6875 // If X has wider elements then convert it to: 6876 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z). 6877 if (MemVT.isInteger() && SN->isTruncatingStore()) { 6878 if (SDValue Value = 6879 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) { 6880 DCI.AddToWorklist(Value.getNode()); 6881 6882 // Rewrite the store with the new form of stored value. 6883 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value, 6884 SN->getBasePtr(), SN->getMemoryVT(), 6885 SN->getMemOperand()); 6886 } 6887 } 6888 // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR 6889 if (!SN->isTruncatingStore() && 6890 Op1.getOpcode() == ISD::BSWAP && 6891 Op1.getNode()->hasOneUse() && 6892 canLoadStoreByteSwapped(Op1.getValueType())) { 6893 6894 SDValue BSwapOp = Op1.getOperand(0); 6895 6896 if (BSwapOp.getValueType() == MVT::i16) 6897 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp); 6898 6899 SDValue Ops[] = { 6900 N->getOperand(0), BSwapOp, N->getOperand(2) 6901 }; 6902 6903 return 6904 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other), 6905 Ops, MemVT, SN->getMemOperand()); 6906 } 6907 // Combine STORE (element-swap) into VSTER 6908 if (!SN->isTruncatingStore() && 6909 Op1.getOpcode() == ISD::VECTOR_SHUFFLE && 6910 Op1.getNode()->hasOneUse() && 6911 Subtarget.hasVectorEnhancements2()) { 6912 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode()); 6913 ArrayRef<int> ShuffleMask = SVN->getMask(); 6914 if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) { 6915 SDValue Ops[] = { 6916 N->getOperand(0), Op1.getOperand(0), N->getOperand(2) 6917 }; 6918 6919 return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N), 6920 DAG.getVTList(MVT::Other), 6921 Ops, MemVT, SN->getMemOperand()); 6922 } 6923 } 6924 6925 // Transform a store of an i128 moved from GPRs into two separate stores. 6926 if (MemVT == MVT::i128 && SN->isSimple() && ISD::isNormalStore(SN)) { 6927 SDValue LoPart, HiPart; 6928 if (isMovedFromParts(Op1, LoPart, HiPart)) { 6929 SDLoc DL(SN); 6930 SDValue Chain0 = 6931 DAG.getStore(SN->getChain(), DL, HiPart, SN->getBasePtr(), 6932 SN->getPointerInfo(), SN->getOriginalAlign(), 6933 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 6934 SDValue Chain1 = 6935 DAG.getStore(SN->getChain(), DL, LoPart, 6936 DAG.getObjectPtrOffset(DL, SN->getBasePtr(), 6937 TypeSize::getFixed(8)), 6938 SN->getPointerInfo().getWithOffset(8), 6939 SN->getOriginalAlign(), 6940 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 6941 6942 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chain0, Chain1); 6943 } 6944 } 6945 6946 // Replicate a reg or immediate with VREP instead of scalar multiply or 6947 // immediate load. It seems best to do this during the first DAGCombine as 6948 // it is straight-forward to handle the zero-extend node in the initial 6949 // DAG, and also not worry about the keeping the new MemVT legal (e.g. when 6950 // extracting an i16 element from a v16i8 vector). 6951 if (Subtarget.hasVector() && DCI.Level == BeforeLegalizeTypes && 6952 isOnlyUsedByStores(Op1, DAG)) { 6953 SDValue Word = SDValue(); 6954 EVT WordVT; 6955 6956 // Find a replicated immediate and return it if found in Word and its 6957 // type in WordVT. 6958 auto FindReplicatedImm = [&](ConstantSDNode *C, unsigned TotBytes) { 6959 // Some constants are better handled with a scalar store. 6960 if (C->getAPIntValue().getBitWidth() > 64 || C->isAllOnes() || 6961 isInt<16>(C->getSExtValue()) || MemVT.getStoreSize() <= 2) 6962 return; 6963 SystemZVectorConstantInfo VCI(APInt(TotBytes * 8, C->getZExtValue())); 6964 if (VCI.isVectorConstantLegal(Subtarget) && 6965 VCI.Opcode == SystemZISD::REPLICATE) { 6966 Word = DAG.getConstant(VCI.OpVals[0], SDLoc(SN), MVT::i32); 6967 WordVT = VCI.VecVT.getScalarType(); 6968 } 6969 }; 6970 6971 // Find a replicated register and return it if found in Word and its type 6972 // in WordVT. 6973 auto FindReplicatedReg = [&](SDValue MulOp) { 6974 EVT MulVT = MulOp.getValueType(); 6975 if (MulOp->getOpcode() == ISD::MUL && 6976 (MulVT == MVT::i16 || MulVT == MVT::i32 || MulVT == MVT::i64)) { 6977 // Find a zero extended value and its type. 6978 SDValue LHS = MulOp->getOperand(0); 6979 if (LHS->getOpcode() == ISD::ZERO_EXTEND) 6980 WordVT = LHS->getOperand(0).getValueType(); 6981 else if (LHS->getOpcode() == ISD::AssertZext) 6982 WordVT = cast<VTSDNode>(LHS->getOperand(1))->getVT(); 6983 else 6984 return; 6985 // Find a replicating constant, e.g. 0x00010001. 6986 if (auto *C = dyn_cast<ConstantSDNode>(MulOp->getOperand(1))) { 6987 SystemZVectorConstantInfo VCI( 6988 APInt(MulVT.getSizeInBits(), C->getZExtValue())); 6989 if (VCI.isVectorConstantLegal(Subtarget) && 6990 VCI.Opcode == SystemZISD::REPLICATE && VCI.OpVals[0] == 1 && 6991 WordVT == VCI.VecVT.getScalarType()) 6992 Word = DAG.getZExtOrTrunc(LHS->getOperand(0), SDLoc(SN), WordVT); 6993 } 6994 } 6995 }; 6996 6997 if (isa<BuildVectorSDNode>(Op1) && 6998 DAG.isSplatValue(Op1, true/*AllowUndefs*/)) { 6999 SDValue SplatVal = Op1->getOperand(0); 7000 if (auto *C = dyn_cast<ConstantSDNode>(SplatVal)) 7001 FindReplicatedImm(C, SplatVal.getValueType().getStoreSize()); 7002 else 7003 FindReplicatedReg(SplatVal); 7004 } else { 7005 if (auto *C = dyn_cast<ConstantSDNode>(Op1)) 7006 FindReplicatedImm(C, MemVT.getStoreSize()); 7007 else 7008 FindReplicatedReg(Op1); 7009 } 7010 7011 if (Word != SDValue()) { 7012 assert(MemVT.getSizeInBits() % WordVT.getSizeInBits() == 0 && 7013 "Bad type handling"); 7014 unsigned NumElts = MemVT.getSizeInBits() / WordVT.getSizeInBits(); 7015 EVT SplatVT = EVT::getVectorVT(*DAG.getContext(), WordVT, NumElts); 7016 SDValue SplatVal = DAG.getSplatVector(SplatVT, SDLoc(SN), Word); 7017 return DAG.getStore(SN->getChain(), SDLoc(SN), SplatVal, 7018 SN->getBasePtr(), SN->getMemOperand()); 7019 } 7020 } 7021 7022 return SDValue(); 7023 } 7024 7025 SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE( 7026 SDNode *N, DAGCombinerInfo &DCI) const { 7027 SelectionDAG &DAG = DCI.DAG; 7028 // Combine element-swap (LOAD) into VLER 7029 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 7030 N->getOperand(0).hasOneUse() && 7031 Subtarget.hasVectorEnhancements2()) { 7032 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 7033 ArrayRef<int> ShuffleMask = SVN->getMask(); 7034 if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) { 7035 SDValue Load = N->getOperand(0); 7036 LoadSDNode *LD = cast<LoadSDNode>(Load); 7037 7038 // Create the element-swapping load. 7039 SDValue Ops[] = { 7040 LD->getChain(), // Chain 7041 LD->getBasePtr() // Ptr 7042 }; 7043 SDValue ESLoad = 7044 DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N), 7045 DAG.getVTList(LD->getValueType(0), MVT::Other), 7046 Ops, LD->getMemoryVT(), LD->getMemOperand()); 7047 7048 // First, combine the VECTOR_SHUFFLE away. This makes the value produced 7049 // by the load dead. 7050 DCI.CombineTo(N, ESLoad); 7051 7052 // Next, combine the load away, we give it a bogus result value but a real 7053 // chain result. The result value is dead because the shuffle is dead. 7054 DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1)); 7055 7056 // Return N so it doesn't get rechecked! 7057 return SDValue(N, 0); 7058 } 7059 } 7060 7061 return SDValue(); 7062 } 7063 7064 SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT( 7065 SDNode *N, DAGCombinerInfo &DCI) const { 7066 SelectionDAG &DAG = DCI.DAG; 7067 7068 if (!Subtarget.hasVector()) 7069 return SDValue(); 7070 7071 // Look through bitcasts that retain the number of vector elements. 7072 SDValue Op = N->getOperand(0); 7073 if (Op.getOpcode() == ISD::BITCAST && 7074 Op.getValueType().isVector() && 7075 Op.getOperand(0).getValueType().isVector() && 7076 Op.getValueType().getVectorNumElements() == 7077 Op.getOperand(0).getValueType().getVectorNumElements()) 7078 Op = Op.getOperand(0); 7079 7080 // Pull BSWAP out of a vector extraction. 7081 if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) { 7082 EVT VecVT = Op.getValueType(); 7083 EVT EltVT = VecVT.getVectorElementType(); 7084 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT, 7085 Op.getOperand(0), N->getOperand(1)); 7086 DCI.AddToWorklist(Op.getNode()); 7087 Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op); 7088 if (EltVT != N->getValueType(0)) { 7089 DCI.AddToWorklist(Op.getNode()); 7090 Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op); 7091 } 7092 return Op; 7093 } 7094 7095 // Try to simplify a vector extraction. 7096 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 7097 SDValue Op0 = N->getOperand(0); 7098 EVT VecVT = Op0.getValueType(); 7099 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0, 7100 IndexN->getZExtValue(), DCI, false); 7101 } 7102 return SDValue(); 7103 } 7104 7105 SDValue SystemZTargetLowering::combineJOIN_DWORDS( 7106 SDNode *N, DAGCombinerInfo &DCI) const { 7107 SelectionDAG &DAG = DCI.DAG; 7108 // (join_dwords X, X) == (replicate X) 7109 if (N->getOperand(0) == N->getOperand(1)) 7110 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0), 7111 N->getOperand(0)); 7112 return SDValue(); 7113 } 7114 7115 static SDValue MergeInputChains(SDNode *N1, SDNode *N2) { 7116 SDValue Chain1 = N1->getOperand(0); 7117 SDValue Chain2 = N2->getOperand(0); 7118 7119 // Trivial case: both nodes take the same chain. 7120 if (Chain1 == Chain2) 7121 return Chain1; 7122 7123 // FIXME - we could handle more complex cases via TokenFactor, 7124 // assuming we can verify that this would not create a cycle. 7125 return SDValue(); 7126 } 7127 7128 SDValue SystemZTargetLowering::combineFP_ROUND( 7129 SDNode *N, DAGCombinerInfo &DCI) const { 7130 7131 if (!Subtarget.hasVector()) 7132 return SDValue(); 7133 7134 // (fpround (extract_vector_elt X 0)) 7135 // (fpround (extract_vector_elt X 1)) -> 7136 // (extract_vector_elt (VROUND X) 0) 7137 // (extract_vector_elt (VROUND X) 2) 7138 // 7139 // This is a special case since the target doesn't really support v2f32s. 7140 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0; 7141 SelectionDAG &DAG = DCI.DAG; 7142 SDValue Op0 = N->getOperand(OpNo); 7143 if (N->getValueType(0) == MVT::f32 && Op0.hasOneUse() && 7144 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7145 Op0.getOperand(0).getValueType() == MVT::v2f64 && 7146 Op0.getOperand(1).getOpcode() == ISD::Constant && 7147 Op0.getConstantOperandVal(1) == 0) { 7148 SDValue Vec = Op0.getOperand(0); 7149 for (auto *U : Vec->uses()) { 7150 if (U != Op0.getNode() && U->hasOneUse() && 7151 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7152 U->getOperand(0) == Vec && 7153 U->getOperand(1).getOpcode() == ISD::Constant && 7154 U->getConstantOperandVal(1) == 1) { 7155 SDValue OtherRound = SDValue(*U->use_begin(), 0); 7156 if (OtherRound.getOpcode() == N->getOpcode() && 7157 OtherRound.getOperand(OpNo) == SDValue(U, 0) && 7158 OtherRound.getValueType() == MVT::f32) { 7159 SDValue VRound, Chain; 7160 if (N->isStrictFPOpcode()) { 7161 Chain = MergeInputChains(N, OtherRound.getNode()); 7162 if (!Chain) 7163 continue; 7164 VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N), 7165 {MVT::v4f32, MVT::Other}, {Chain, Vec}); 7166 Chain = VRound.getValue(1); 7167 } else 7168 VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N), 7169 MVT::v4f32, Vec); 7170 DCI.AddToWorklist(VRound.getNode()); 7171 SDValue Extract1 = 7172 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32, 7173 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32)); 7174 DCI.AddToWorklist(Extract1.getNode()); 7175 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1); 7176 if (Chain) 7177 DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain); 7178 SDValue Extract0 = 7179 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32, 7180 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32)); 7181 if (Chain) 7182 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0), 7183 N->getVTList(), Extract0, Chain); 7184 return Extract0; 7185 } 7186 } 7187 } 7188 } 7189 return SDValue(); 7190 } 7191 7192 SDValue SystemZTargetLowering::combineFP_EXTEND( 7193 SDNode *N, DAGCombinerInfo &DCI) const { 7194 7195 if (!Subtarget.hasVector()) 7196 return SDValue(); 7197 7198 // (fpextend (extract_vector_elt X 0)) 7199 // (fpextend (extract_vector_elt X 2)) -> 7200 // (extract_vector_elt (VEXTEND X) 0) 7201 // (extract_vector_elt (VEXTEND X) 1) 7202 // 7203 // This is a special case since the target doesn't really support v2f32s. 7204 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0; 7205 SelectionDAG &DAG = DCI.DAG; 7206 SDValue Op0 = N->getOperand(OpNo); 7207 if (N->getValueType(0) == MVT::f64 && Op0.hasOneUse() && 7208 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7209 Op0.getOperand(0).getValueType() == MVT::v4f32 && 7210 Op0.getOperand(1).getOpcode() == ISD::Constant && 7211 Op0.getConstantOperandVal(1) == 0) { 7212 SDValue Vec = Op0.getOperand(0); 7213 for (auto *U : Vec->uses()) { 7214 if (U != Op0.getNode() && U->hasOneUse() && 7215 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7216 U->getOperand(0) == Vec && 7217 U->getOperand(1).getOpcode() == ISD::Constant && 7218 U->getConstantOperandVal(1) == 2) { 7219 SDValue OtherExtend = SDValue(*U->use_begin(), 0); 7220 if (OtherExtend.getOpcode() == N->getOpcode() && 7221 OtherExtend.getOperand(OpNo) == SDValue(U, 0) && 7222 OtherExtend.getValueType() == MVT::f64) { 7223 SDValue VExtend, Chain; 7224 if (N->isStrictFPOpcode()) { 7225 Chain = MergeInputChains(N, OtherExtend.getNode()); 7226 if (!Chain) 7227 continue; 7228 VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N), 7229 {MVT::v2f64, MVT::Other}, {Chain, Vec}); 7230 Chain = VExtend.getValue(1); 7231 } else 7232 VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N), 7233 MVT::v2f64, Vec); 7234 DCI.AddToWorklist(VExtend.getNode()); 7235 SDValue Extract1 = 7236 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64, 7237 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32)); 7238 DCI.AddToWorklist(Extract1.getNode()); 7239 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1); 7240 if (Chain) 7241 DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain); 7242 SDValue Extract0 = 7243 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64, 7244 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32)); 7245 if (Chain) 7246 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0), 7247 N->getVTList(), Extract0, Chain); 7248 return Extract0; 7249 } 7250 } 7251 } 7252 } 7253 return SDValue(); 7254 } 7255 7256 SDValue SystemZTargetLowering::combineINT_TO_FP( 7257 SDNode *N, DAGCombinerInfo &DCI) const { 7258 if (DCI.Level != BeforeLegalizeTypes) 7259 return SDValue(); 7260 SelectionDAG &DAG = DCI.DAG; 7261 LLVMContext &Ctx = *DAG.getContext(); 7262 unsigned Opcode = N->getOpcode(); 7263 EVT OutVT = N->getValueType(0); 7264 Type *OutLLVMTy = OutVT.getTypeForEVT(Ctx); 7265 SDValue Op = N->getOperand(0); 7266 unsigned OutScalarBits = OutLLVMTy->getScalarSizeInBits(); 7267 unsigned InScalarBits = Op->getValueType(0).getScalarSizeInBits(); 7268 7269 // Insert an extension before type-legalization to avoid scalarization, e.g.: 7270 // v2f64 = uint_to_fp v2i16 7271 // => 7272 // v2f64 = uint_to_fp (v2i64 zero_extend v2i16) 7273 if (OutLLVMTy->isVectorTy() && OutScalarBits > InScalarBits && 7274 OutScalarBits <= 64) { 7275 unsigned NumElts = cast<FixedVectorType>(OutLLVMTy)->getNumElements(); 7276 EVT ExtVT = EVT::getVectorVT( 7277 Ctx, EVT::getIntegerVT(Ctx, OutLLVMTy->getScalarSizeInBits()), NumElts); 7278 unsigned ExtOpcode = 7279 (Opcode == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND); 7280 SDValue ExtOp = DAG.getNode(ExtOpcode, SDLoc(N), ExtVT, Op); 7281 return DAG.getNode(Opcode, SDLoc(N), OutVT, ExtOp); 7282 } 7283 return SDValue(); 7284 } 7285 7286 SDValue SystemZTargetLowering::combineBSWAP( 7287 SDNode *N, DAGCombinerInfo &DCI) const { 7288 SelectionDAG &DAG = DCI.DAG; 7289 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR 7290 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 7291 N->getOperand(0).hasOneUse() && 7292 canLoadStoreByteSwapped(N->getValueType(0))) { 7293 SDValue Load = N->getOperand(0); 7294 LoadSDNode *LD = cast<LoadSDNode>(Load); 7295 7296 // Create the byte-swapping load. 7297 SDValue Ops[] = { 7298 LD->getChain(), // Chain 7299 LD->getBasePtr() // Ptr 7300 }; 7301 EVT LoadVT = N->getValueType(0); 7302 if (LoadVT == MVT::i16) 7303 LoadVT = MVT::i32; 7304 SDValue BSLoad = 7305 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N), 7306 DAG.getVTList(LoadVT, MVT::Other), 7307 Ops, LD->getMemoryVT(), LD->getMemOperand()); 7308 7309 // If this is an i16 load, insert the truncate. 7310 SDValue ResVal = BSLoad; 7311 if (N->getValueType(0) == MVT::i16) 7312 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad); 7313 7314 // First, combine the bswap away. This makes the value produced by the 7315 // load dead. 7316 DCI.CombineTo(N, ResVal); 7317 7318 // Next, combine the load away, we give it a bogus result value but a real 7319 // chain result. The result value is dead because the bswap is dead. 7320 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 7321 7322 // Return N so it doesn't get rechecked! 7323 return SDValue(N, 0); 7324 } 7325 7326 // Look through bitcasts that retain the number of vector elements. 7327 SDValue Op = N->getOperand(0); 7328 if (Op.getOpcode() == ISD::BITCAST && 7329 Op.getValueType().isVector() && 7330 Op.getOperand(0).getValueType().isVector() && 7331 Op.getValueType().getVectorNumElements() == 7332 Op.getOperand(0).getValueType().getVectorNumElements()) 7333 Op = Op.getOperand(0); 7334 7335 // Push BSWAP into a vector insertion if at least one side then simplifies. 7336 if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) { 7337 SDValue Vec = Op.getOperand(0); 7338 SDValue Elt = Op.getOperand(1); 7339 SDValue Idx = Op.getOperand(2); 7340 7341 if (DAG.isConstantIntBuildVectorOrConstantInt(Vec) || 7342 Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() || 7343 DAG.isConstantIntBuildVectorOrConstantInt(Elt) || 7344 Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() || 7345 (canLoadStoreByteSwapped(N->getValueType(0)) && 7346 ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) { 7347 EVT VecVT = N->getValueType(0); 7348 EVT EltVT = N->getValueType(0).getVectorElementType(); 7349 if (VecVT != Vec.getValueType()) { 7350 Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec); 7351 DCI.AddToWorklist(Vec.getNode()); 7352 } 7353 if (EltVT != Elt.getValueType()) { 7354 Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt); 7355 DCI.AddToWorklist(Elt.getNode()); 7356 } 7357 Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec); 7358 DCI.AddToWorklist(Vec.getNode()); 7359 Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt); 7360 DCI.AddToWorklist(Elt.getNode()); 7361 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT, 7362 Vec, Elt, Idx); 7363 } 7364 } 7365 7366 // Push BSWAP into a vector shuffle if at least one side then simplifies. 7367 ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op); 7368 if (SV && Op.hasOneUse()) { 7369 SDValue Op0 = Op.getOperand(0); 7370 SDValue Op1 = Op.getOperand(1); 7371 7372 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 7373 Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() || 7374 DAG.isConstantIntBuildVectorOrConstantInt(Op1) || 7375 Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) { 7376 EVT VecVT = N->getValueType(0); 7377 if (VecVT != Op0.getValueType()) { 7378 Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0); 7379 DCI.AddToWorklist(Op0.getNode()); 7380 } 7381 if (VecVT != Op1.getValueType()) { 7382 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1); 7383 DCI.AddToWorklist(Op1.getNode()); 7384 } 7385 Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0); 7386 DCI.AddToWorklist(Op0.getNode()); 7387 Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1); 7388 DCI.AddToWorklist(Op1.getNode()); 7389 return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask()); 7390 } 7391 } 7392 7393 return SDValue(); 7394 } 7395 7396 static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask) { 7397 // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code 7398 // set by the CCReg instruction using the CCValid / CCMask masks, 7399 // If the CCReg instruction is itself a ICMP testing the condition 7400 // code set by some other instruction, see whether we can directly 7401 // use that condition code. 7402 7403 // Verify that we have an ICMP against some constant. 7404 if (CCValid != SystemZ::CCMASK_ICMP) 7405 return false; 7406 auto *ICmp = CCReg.getNode(); 7407 if (ICmp->getOpcode() != SystemZISD::ICMP) 7408 return false; 7409 auto *CompareLHS = ICmp->getOperand(0).getNode(); 7410 auto *CompareRHS = dyn_cast<ConstantSDNode>(ICmp->getOperand(1)); 7411 if (!CompareRHS) 7412 return false; 7413 7414 // Optimize the case where CompareLHS is a SELECT_CCMASK. 7415 if (CompareLHS->getOpcode() == SystemZISD::SELECT_CCMASK) { 7416 // Verify that we have an appropriate mask for a EQ or NE comparison. 7417 bool Invert = false; 7418 if (CCMask == SystemZ::CCMASK_CMP_NE) 7419 Invert = !Invert; 7420 else if (CCMask != SystemZ::CCMASK_CMP_EQ) 7421 return false; 7422 7423 // Verify that the ICMP compares against one of select values. 7424 auto *TrueVal = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(0)); 7425 if (!TrueVal) 7426 return false; 7427 auto *FalseVal = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(1)); 7428 if (!FalseVal) 7429 return false; 7430 if (CompareRHS->getZExtValue() == FalseVal->getZExtValue()) 7431 Invert = !Invert; 7432 else if (CompareRHS->getZExtValue() != TrueVal->getZExtValue()) 7433 return false; 7434 7435 // Compute the effective CC mask for the new branch or select. 7436 auto *NewCCValid = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(2)); 7437 auto *NewCCMask = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(3)); 7438 if (!NewCCValid || !NewCCMask) 7439 return false; 7440 CCValid = NewCCValid->getZExtValue(); 7441 CCMask = NewCCMask->getZExtValue(); 7442 if (Invert) 7443 CCMask ^= CCValid; 7444 7445 // Return the updated CCReg link. 7446 CCReg = CompareLHS->getOperand(4); 7447 return true; 7448 } 7449 7450 // Optimize the case where CompareRHS is (SRA (SHL (IPM))). 7451 if (CompareLHS->getOpcode() == ISD::SRA) { 7452 auto *SRACount = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(1)); 7453 if (!SRACount || SRACount->getZExtValue() != 30) 7454 return false; 7455 auto *SHL = CompareLHS->getOperand(0).getNode(); 7456 if (SHL->getOpcode() != ISD::SHL) 7457 return false; 7458 auto *SHLCount = dyn_cast<ConstantSDNode>(SHL->getOperand(1)); 7459 if (!SHLCount || SHLCount->getZExtValue() != 30 - SystemZ::IPM_CC) 7460 return false; 7461 auto *IPM = SHL->getOperand(0).getNode(); 7462 if (IPM->getOpcode() != SystemZISD::IPM) 7463 return false; 7464 7465 // Avoid introducing CC spills (because SRA would clobber CC). 7466 if (!CompareLHS->hasOneUse()) 7467 return false; 7468 // Verify that the ICMP compares against zero. 7469 if (CompareRHS->getZExtValue() != 0) 7470 return false; 7471 7472 // Compute the effective CC mask for the new branch or select. 7473 CCMask = SystemZ::reverseCCMask(CCMask); 7474 7475 // Return the updated CCReg link. 7476 CCReg = IPM->getOperand(0); 7477 return true; 7478 } 7479 7480 return false; 7481 } 7482 7483 SDValue SystemZTargetLowering::combineBR_CCMASK( 7484 SDNode *N, DAGCombinerInfo &DCI) const { 7485 SelectionDAG &DAG = DCI.DAG; 7486 7487 // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK. 7488 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7489 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2)); 7490 if (!CCValid || !CCMask) 7491 return SDValue(); 7492 7493 int CCValidVal = CCValid->getZExtValue(); 7494 int CCMaskVal = CCMask->getZExtValue(); 7495 SDValue Chain = N->getOperand(0); 7496 SDValue CCReg = N->getOperand(4); 7497 7498 if (combineCCMask(CCReg, CCValidVal, CCMaskVal)) 7499 return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0), 7500 Chain, 7501 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32), 7502 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32), 7503 N->getOperand(3), CCReg); 7504 return SDValue(); 7505 } 7506 7507 SDValue SystemZTargetLowering::combineSELECT_CCMASK( 7508 SDNode *N, DAGCombinerInfo &DCI) const { 7509 SelectionDAG &DAG = DCI.DAG; 7510 7511 // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK. 7512 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2)); 7513 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3)); 7514 if (!CCValid || !CCMask) 7515 return SDValue(); 7516 7517 int CCValidVal = CCValid->getZExtValue(); 7518 int CCMaskVal = CCMask->getZExtValue(); 7519 SDValue CCReg = N->getOperand(4); 7520 7521 if (combineCCMask(CCReg, CCValidVal, CCMaskVal)) 7522 return DAG.getNode(SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0), 7523 N->getOperand(0), N->getOperand(1), 7524 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32), 7525 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32), 7526 CCReg); 7527 return SDValue(); 7528 } 7529 7530 7531 SDValue SystemZTargetLowering::combineGET_CCMASK( 7532 SDNode *N, DAGCombinerInfo &DCI) const { 7533 7534 // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible 7535 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7536 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2)); 7537 if (!CCValid || !CCMask) 7538 return SDValue(); 7539 int CCValidVal = CCValid->getZExtValue(); 7540 int CCMaskVal = CCMask->getZExtValue(); 7541 7542 SDValue Select = N->getOperand(0); 7543 if (Select->getOpcode() == ISD::TRUNCATE) 7544 Select = Select->getOperand(0); 7545 if (Select->getOpcode() != SystemZISD::SELECT_CCMASK) 7546 return SDValue(); 7547 7548 auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2)); 7549 auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3)); 7550 if (!SelectCCValid || !SelectCCMask) 7551 return SDValue(); 7552 int SelectCCValidVal = SelectCCValid->getZExtValue(); 7553 int SelectCCMaskVal = SelectCCMask->getZExtValue(); 7554 7555 auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0)); 7556 auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1)); 7557 if (!TrueVal || !FalseVal) 7558 return SDValue(); 7559 if (TrueVal->getZExtValue() == 1 && FalseVal->getZExtValue() == 0) 7560 ; 7561 else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() == 1) 7562 SelectCCMaskVal ^= SelectCCValidVal; 7563 else 7564 return SDValue(); 7565 7566 if (SelectCCValidVal & ~CCValidVal) 7567 return SDValue(); 7568 if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal)) 7569 return SDValue(); 7570 7571 return Select->getOperand(4); 7572 } 7573 7574 SDValue SystemZTargetLowering::combineIntDIVREM( 7575 SDNode *N, DAGCombinerInfo &DCI) const { 7576 SelectionDAG &DAG = DCI.DAG; 7577 EVT VT = N->getValueType(0); 7578 // In the case where the divisor is a vector of constants a cheaper 7579 // sequence of instructions can replace the divide. BuildSDIV is called to 7580 // do this during DAG combining, but it only succeeds when it can build a 7581 // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and 7582 // since it is not Legal but Custom it can only happen before 7583 // legalization. Therefore we must scalarize this early before Combine 7584 // 1. For widened vectors, this is already the result of type legalization. 7585 if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) && 7586 DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1))) 7587 return DAG.UnrollVectorOp(N); 7588 return SDValue(); 7589 } 7590 7591 SDValue SystemZTargetLowering::combineINTRINSIC( 7592 SDNode *N, DAGCombinerInfo &DCI) const { 7593 SelectionDAG &DAG = DCI.DAG; 7594 7595 unsigned Id = N->getConstantOperandVal(1); 7596 switch (Id) { 7597 // VECTOR LOAD (RIGHTMOST) WITH LENGTH with a length operand of 15 7598 // or larger is simply a vector load. 7599 case Intrinsic::s390_vll: 7600 case Intrinsic::s390_vlrl: 7601 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2))) 7602 if (C->getZExtValue() >= 15) 7603 return DAG.getLoad(N->getValueType(0), SDLoc(N), N->getOperand(0), 7604 N->getOperand(3), MachinePointerInfo()); 7605 break; 7606 // Likewise for VECTOR STORE (RIGHTMOST) WITH LENGTH. 7607 case Intrinsic::s390_vstl: 7608 case Intrinsic::s390_vstrl: 7609 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(3))) 7610 if (C->getZExtValue() >= 15) 7611 return DAG.getStore(N->getOperand(0), SDLoc(N), N->getOperand(2), 7612 N->getOperand(4), MachinePointerInfo()); 7613 break; 7614 } 7615 7616 return SDValue(); 7617 } 7618 7619 SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const { 7620 if (N->getOpcode() == SystemZISD::PCREL_WRAPPER) 7621 return N->getOperand(0); 7622 return N; 7623 } 7624 7625 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N, 7626 DAGCombinerInfo &DCI) const { 7627 switch(N->getOpcode()) { 7628 default: break; 7629 case ISD::ZERO_EXTEND: return combineZERO_EXTEND(N, DCI); 7630 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI); 7631 case ISD::SIGN_EXTEND_INREG: return combineSIGN_EXTEND_INREG(N, DCI); 7632 case SystemZISD::MERGE_HIGH: 7633 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI); 7634 case ISD::LOAD: return combineLOAD(N, DCI); 7635 case ISD::STORE: return combineSTORE(N, DCI); 7636 case ISD::VECTOR_SHUFFLE: return combineVECTOR_SHUFFLE(N, DCI); 7637 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI); 7638 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI); 7639 case ISD::STRICT_FP_ROUND: 7640 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI); 7641 case ISD::STRICT_FP_EXTEND: 7642 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DCI); 7643 case ISD::SINT_TO_FP: 7644 case ISD::UINT_TO_FP: return combineINT_TO_FP(N, DCI); 7645 case ISD::BSWAP: return combineBSWAP(N, DCI); 7646 case SystemZISD::BR_CCMASK: return combineBR_CCMASK(N, DCI); 7647 case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI); 7648 case SystemZISD::GET_CCMASK: return combineGET_CCMASK(N, DCI); 7649 case ISD::SDIV: 7650 case ISD::UDIV: 7651 case ISD::SREM: 7652 case ISD::UREM: return combineIntDIVREM(N, DCI); 7653 case ISD::INTRINSIC_W_CHAIN: 7654 case ISD::INTRINSIC_VOID: return combineINTRINSIC(N, DCI); 7655 } 7656 7657 return SDValue(); 7658 } 7659 7660 // Return the demanded elements for the OpNo source operand of Op. DemandedElts 7661 // are for Op. 7662 static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts, 7663 unsigned OpNo) { 7664 EVT VT = Op.getValueType(); 7665 unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1); 7666 APInt SrcDemE; 7667 unsigned Opcode = Op.getOpcode(); 7668 if (Opcode == ISD::INTRINSIC_WO_CHAIN) { 7669 unsigned Id = Op.getConstantOperandVal(0); 7670 switch (Id) { 7671 case Intrinsic::s390_vpksh: // PACKS 7672 case Intrinsic::s390_vpksf: 7673 case Intrinsic::s390_vpksg: 7674 case Intrinsic::s390_vpkshs: // PACKS_CC 7675 case Intrinsic::s390_vpksfs: 7676 case Intrinsic::s390_vpksgs: 7677 case Intrinsic::s390_vpklsh: // PACKLS 7678 case Intrinsic::s390_vpklsf: 7679 case Intrinsic::s390_vpklsg: 7680 case Intrinsic::s390_vpklshs: // PACKLS_CC 7681 case Intrinsic::s390_vpklsfs: 7682 case Intrinsic::s390_vpklsgs: 7683 // VECTOR PACK truncates the elements of two source vectors into one. 7684 SrcDemE = DemandedElts; 7685 if (OpNo == 2) 7686 SrcDemE.lshrInPlace(NumElts / 2); 7687 SrcDemE = SrcDemE.trunc(NumElts / 2); 7688 break; 7689 // VECTOR UNPACK extends half the elements of the source vector. 7690 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH 7691 case Intrinsic::s390_vuphh: 7692 case Intrinsic::s390_vuphf: 7693 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH 7694 case Intrinsic::s390_vuplhh: 7695 case Intrinsic::s390_vuplhf: 7696 SrcDemE = APInt(NumElts * 2, 0); 7697 SrcDemE.insertBits(DemandedElts, 0); 7698 break; 7699 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW 7700 case Intrinsic::s390_vuplhw: 7701 case Intrinsic::s390_vuplf: 7702 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW 7703 case Intrinsic::s390_vupllh: 7704 case Intrinsic::s390_vupllf: 7705 SrcDemE = APInt(NumElts * 2, 0); 7706 SrcDemE.insertBits(DemandedElts, NumElts); 7707 break; 7708 case Intrinsic::s390_vpdi: { 7709 // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source. 7710 SrcDemE = APInt(NumElts, 0); 7711 if (!DemandedElts[OpNo - 1]) 7712 break; 7713 unsigned Mask = Op.getConstantOperandVal(3); 7714 unsigned MaskBit = ((OpNo - 1) ? 1 : 4); 7715 // Demand input element 0 or 1, given by the mask bit value. 7716 SrcDemE.setBit((Mask & MaskBit)? 1 : 0); 7717 break; 7718 } 7719 case Intrinsic::s390_vsldb: { 7720 // VECTOR SHIFT LEFT DOUBLE BY BYTE 7721 assert(VT == MVT::v16i8 && "Unexpected type."); 7722 unsigned FirstIdx = Op.getConstantOperandVal(3); 7723 assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand."); 7724 unsigned NumSrc0Els = 16 - FirstIdx; 7725 SrcDemE = APInt(NumElts, 0); 7726 if (OpNo == 1) { 7727 APInt DemEls = DemandedElts.trunc(NumSrc0Els); 7728 SrcDemE.insertBits(DemEls, FirstIdx); 7729 } else { 7730 APInt DemEls = DemandedElts.lshr(NumSrc0Els); 7731 SrcDemE.insertBits(DemEls, 0); 7732 } 7733 break; 7734 } 7735 case Intrinsic::s390_vperm: 7736 SrcDemE = APInt(NumElts, 1); 7737 break; 7738 default: 7739 llvm_unreachable("Unhandled intrinsic."); 7740 break; 7741 } 7742 } else { 7743 switch (Opcode) { 7744 case SystemZISD::JOIN_DWORDS: 7745 // Scalar operand. 7746 SrcDemE = APInt(1, 1); 7747 break; 7748 case SystemZISD::SELECT_CCMASK: 7749 SrcDemE = DemandedElts; 7750 break; 7751 default: 7752 llvm_unreachable("Unhandled opcode."); 7753 break; 7754 } 7755 } 7756 return SrcDemE; 7757 } 7758 7759 static void computeKnownBitsBinOp(const SDValue Op, KnownBits &Known, 7760 const APInt &DemandedElts, 7761 const SelectionDAG &DAG, unsigned Depth, 7762 unsigned OpNo) { 7763 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo); 7764 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1); 7765 KnownBits LHSKnown = 7766 DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1); 7767 KnownBits RHSKnown = 7768 DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1); 7769 Known = LHSKnown.intersectWith(RHSKnown); 7770 } 7771 7772 void 7773 SystemZTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7774 KnownBits &Known, 7775 const APInt &DemandedElts, 7776 const SelectionDAG &DAG, 7777 unsigned Depth) const { 7778 Known.resetAll(); 7779 7780 // Intrinsic CC result is returned in the two low bits. 7781 unsigned tmp0, tmp1; // not used 7782 if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, tmp0, tmp1)) { 7783 Known.Zero.setBitsFrom(2); 7784 return; 7785 } 7786 EVT VT = Op.getValueType(); 7787 if (Op.getResNo() != 0 || VT == MVT::Untyped) 7788 return; 7789 assert (Known.getBitWidth() == VT.getScalarSizeInBits() && 7790 "KnownBits does not match VT in bitwidth"); 7791 assert ((!VT.isVector() || 7792 (DemandedElts.getBitWidth() == VT.getVectorNumElements())) && 7793 "DemandedElts does not match VT number of elements"); 7794 unsigned BitWidth = Known.getBitWidth(); 7795 unsigned Opcode = Op.getOpcode(); 7796 if (Opcode == ISD::INTRINSIC_WO_CHAIN) { 7797 bool IsLogical = false; 7798 unsigned Id = Op.getConstantOperandVal(0); 7799 switch (Id) { 7800 case Intrinsic::s390_vpksh: // PACKS 7801 case Intrinsic::s390_vpksf: 7802 case Intrinsic::s390_vpksg: 7803 case Intrinsic::s390_vpkshs: // PACKS_CC 7804 case Intrinsic::s390_vpksfs: 7805 case Intrinsic::s390_vpksgs: 7806 case Intrinsic::s390_vpklsh: // PACKLS 7807 case Intrinsic::s390_vpklsf: 7808 case Intrinsic::s390_vpklsg: 7809 case Intrinsic::s390_vpklshs: // PACKLS_CC 7810 case Intrinsic::s390_vpklsfs: 7811 case Intrinsic::s390_vpklsgs: 7812 case Intrinsic::s390_vpdi: 7813 case Intrinsic::s390_vsldb: 7814 case Intrinsic::s390_vperm: 7815 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1); 7816 break; 7817 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH 7818 case Intrinsic::s390_vuplhh: 7819 case Intrinsic::s390_vuplhf: 7820 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW 7821 case Intrinsic::s390_vupllh: 7822 case Intrinsic::s390_vupllf: 7823 IsLogical = true; 7824 [[fallthrough]]; 7825 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH 7826 case Intrinsic::s390_vuphh: 7827 case Intrinsic::s390_vuphf: 7828 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW 7829 case Intrinsic::s390_vuplhw: 7830 case Intrinsic::s390_vuplf: { 7831 SDValue SrcOp = Op.getOperand(1); 7832 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0); 7833 Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1); 7834 if (IsLogical) { 7835 Known = Known.zext(BitWidth); 7836 } else 7837 Known = Known.sext(BitWidth); 7838 break; 7839 } 7840 default: 7841 break; 7842 } 7843 } else { 7844 switch (Opcode) { 7845 case SystemZISD::JOIN_DWORDS: 7846 case SystemZISD::SELECT_CCMASK: 7847 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0); 7848 break; 7849 case SystemZISD::REPLICATE: { 7850 SDValue SrcOp = Op.getOperand(0); 7851 Known = DAG.computeKnownBits(SrcOp, Depth + 1); 7852 if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp)) 7853 Known = Known.sext(BitWidth); // VREPI sign extends the immedate. 7854 break; 7855 } 7856 default: 7857 break; 7858 } 7859 } 7860 7861 // Known has the width of the source operand(s). Adjust if needed to match 7862 // the passed bitwidth. 7863 if (Known.getBitWidth() != BitWidth) 7864 Known = Known.anyextOrTrunc(BitWidth); 7865 } 7866 7867 static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts, 7868 const SelectionDAG &DAG, unsigned Depth, 7869 unsigned OpNo) { 7870 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo); 7871 unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1); 7872 if (LHS == 1) return 1; // Early out. 7873 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1); 7874 unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1); 7875 if (RHS == 1) return 1; // Early out. 7876 unsigned Common = std::min(LHS, RHS); 7877 unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits(); 7878 EVT VT = Op.getValueType(); 7879 unsigned VTBits = VT.getScalarSizeInBits(); 7880 if (SrcBitWidth > VTBits) { // PACK 7881 unsigned SrcExtraBits = SrcBitWidth - VTBits; 7882 if (Common > SrcExtraBits) 7883 return (Common - SrcExtraBits); 7884 return 1; 7885 } 7886 assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth."); 7887 return Common; 7888 } 7889 7890 unsigned 7891 SystemZTargetLowering::ComputeNumSignBitsForTargetNode( 7892 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7893 unsigned Depth) const { 7894 if (Op.getResNo() != 0) 7895 return 1; 7896 unsigned Opcode = Op.getOpcode(); 7897 if (Opcode == ISD::INTRINSIC_WO_CHAIN) { 7898 unsigned Id = Op.getConstantOperandVal(0); 7899 switch (Id) { 7900 case Intrinsic::s390_vpksh: // PACKS 7901 case Intrinsic::s390_vpksf: 7902 case Intrinsic::s390_vpksg: 7903 case Intrinsic::s390_vpkshs: // PACKS_CC 7904 case Intrinsic::s390_vpksfs: 7905 case Intrinsic::s390_vpksgs: 7906 case Intrinsic::s390_vpklsh: // PACKLS 7907 case Intrinsic::s390_vpklsf: 7908 case Intrinsic::s390_vpklsg: 7909 case Intrinsic::s390_vpklshs: // PACKLS_CC 7910 case Intrinsic::s390_vpklsfs: 7911 case Intrinsic::s390_vpklsgs: 7912 case Intrinsic::s390_vpdi: 7913 case Intrinsic::s390_vsldb: 7914 case Intrinsic::s390_vperm: 7915 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1); 7916 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH 7917 case Intrinsic::s390_vuphh: 7918 case Intrinsic::s390_vuphf: 7919 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW 7920 case Intrinsic::s390_vuplhw: 7921 case Intrinsic::s390_vuplf: { 7922 SDValue PackedOp = Op.getOperand(1); 7923 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1); 7924 unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1); 7925 EVT VT = Op.getValueType(); 7926 unsigned VTBits = VT.getScalarSizeInBits(); 7927 Tmp += VTBits - PackedOp.getScalarValueSizeInBits(); 7928 return Tmp; 7929 } 7930 default: 7931 break; 7932 } 7933 } else { 7934 switch (Opcode) { 7935 case SystemZISD::SELECT_CCMASK: 7936 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0); 7937 default: 7938 break; 7939 } 7940 } 7941 7942 return 1; 7943 } 7944 7945 bool SystemZTargetLowering:: 7946 isGuaranteedNotToBeUndefOrPoisonForTargetNode(SDValue Op, 7947 const APInt &DemandedElts, const SelectionDAG &DAG, 7948 bool PoisonOnly, unsigned Depth) const { 7949 switch (Op->getOpcode()) { 7950 case SystemZISD::PCREL_WRAPPER: 7951 case SystemZISD::PCREL_OFFSET: 7952 return true; 7953 } 7954 return false; 7955 } 7956 7957 unsigned 7958 SystemZTargetLowering::getStackProbeSize(const MachineFunction &MF) const { 7959 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 7960 unsigned StackAlign = TFI->getStackAlignment(); 7961 assert(StackAlign >=1 && isPowerOf2_32(StackAlign) && 7962 "Unexpected stack alignment"); 7963 // The default stack probe size is 4096 if the function has no 7964 // stack-probe-size attribute. 7965 unsigned StackProbeSize = 7966 MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size", 4096); 7967 // Round down to the stack alignment. 7968 StackProbeSize &= ~(StackAlign - 1); 7969 return StackProbeSize ? StackProbeSize : StackAlign; 7970 } 7971 7972 //===----------------------------------------------------------------------===// 7973 // Custom insertion 7974 //===----------------------------------------------------------------------===// 7975 7976 // Force base value Base into a register before MI. Return the register. 7977 static Register forceReg(MachineInstr &MI, MachineOperand &Base, 7978 const SystemZInstrInfo *TII) { 7979 MachineBasicBlock *MBB = MI.getParent(); 7980 MachineFunction &MF = *MBB->getParent(); 7981 MachineRegisterInfo &MRI = MF.getRegInfo(); 7982 7983 if (Base.isReg()) { 7984 // Copy Base into a new virtual register to help register coalescing in 7985 // cases with multiple uses. 7986 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass); 7987 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::COPY), Reg) 7988 .add(Base); 7989 return Reg; 7990 } 7991 7992 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass); 7993 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg) 7994 .add(Base) 7995 .addImm(0) 7996 .addReg(0); 7997 return Reg; 7998 } 7999 8000 // The CC operand of MI might be missing a kill marker because there 8001 // were multiple uses of CC, and ISel didn't know which to mark. 8002 // Figure out whether MI should have had a kill marker. 8003 static bool checkCCKill(MachineInstr &MI, MachineBasicBlock *MBB) { 8004 // Scan forward through BB for a use/def of CC. 8005 MachineBasicBlock::iterator miI(std::next(MachineBasicBlock::iterator(MI))); 8006 for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) { 8007 const MachineInstr& mi = *miI; 8008 if (mi.readsRegister(SystemZ::CC)) 8009 return false; 8010 if (mi.definesRegister(SystemZ::CC)) 8011 break; // Should have kill-flag - update below. 8012 } 8013 8014 // If we hit the end of the block, check whether CC is live into a 8015 // successor. 8016 if (miI == MBB->end()) { 8017 for (const MachineBasicBlock *Succ : MBB->successors()) 8018 if (Succ->isLiveIn(SystemZ::CC)) 8019 return false; 8020 } 8021 8022 return true; 8023 } 8024 8025 // Return true if it is OK for this Select pseudo-opcode to be cascaded 8026 // together with other Select pseudo-opcodes into a single basic-block with 8027 // a conditional jump around it. 8028 static bool isSelectPseudo(MachineInstr &MI) { 8029 switch (MI.getOpcode()) { 8030 case SystemZ::Select32: 8031 case SystemZ::Select64: 8032 case SystemZ::Select128: 8033 case SystemZ::SelectF32: 8034 case SystemZ::SelectF64: 8035 case SystemZ::SelectF128: 8036 case SystemZ::SelectVR32: 8037 case SystemZ::SelectVR64: 8038 case SystemZ::SelectVR128: 8039 return true; 8040 8041 default: 8042 return false; 8043 } 8044 } 8045 8046 // Helper function, which inserts PHI functions into SinkMBB: 8047 // %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ], 8048 // where %FalseValue(i) and %TrueValue(i) are taken from Selects. 8049 static void createPHIsForSelects(SmallVector<MachineInstr*, 8> &Selects, 8050 MachineBasicBlock *TrueMBB, 8051 MachineBasicBlock *FalseMBB, 8052 MachineBasicBlock *SinkMBB) { 8053 MachineFunction *MF = TrueMBB->getParent(); 8054 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 8055 8056 MachineInstr *FirstMI = Selects.front(); 8057 unsigned CCValid = FirstMI->getOperand(3).getImm(); 8058 unsigned CCMask = FirstMI->getOperand(4).getImm(); 8059 8060 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin(); 8061 8062 // As we are creating the PHIs, we have to be careful if there is more than 8063 // one. Later Selects may reference the results of earlier Selects, but later 8064 // PHIs have to reference the individual true/false inputs from earlier PHIs. 8065 // That also means that PHI construction must work forward from earlier to 8066 // later, and that the code must maintain a mapping from earlier PHI's 8067 // destination registers, and the registers that went into the PHI. 8068 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable; 8069 8070 for (auto *MI : Selects) { 8071 Register DestReg = MI->getOperand(0).getReg(); 8072 Register TrueReg = MI->getOperand(1).getReg(); 8073 Register FalseReg = MI->getOperand(2).getReg(); 8074 8075 // If this Select we are generating is the opposite condition from 8076 // the jump we generated, then we have to swap the operands for the 8077 // PHI that is going to be generated. 8078 if (MI->getOperand(4).getImm() == (CCValid ^ CCMask)) 8079 std::swap(TrueReg, FalseReg); 8080 8081 if (RegRewriteTable.contains(TrueReg)) 8082 TrueReg = RegRewriteTable[TrueReg].first; 8083 8084 if (RegRewriteTable.contains(FalseReg)) 8085 FalseReg = RegRewriteTable[FalseReg].second; 8086 8087 DebugLoc DL = MI->getDebugLoc(); 8088 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg) 8089 .addReg(TrueReg).addMBB(TrueMBB) 8090 .addReg(FalseReg).addMBB(FalseMBB); 8091 8092 // Add this PHI to the rewrite table. 8093 RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg); 8094 } 8095 8096 MF->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 8097 } 8098 8099 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI. 8100 MachineBasicBlock * 8101 SystemZTargetLowering::emitSelect(MachineInstr &MI, 8102 MachineBasicBlock *MBB) const { 8103 assert(isSelectPseudo(MI) && "Bad call to emitSelect()"); 8104 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 8105 8106 unsigned CCValid = MI.getOperand(3).getImm(); 8107 unsigned CCMask = MI.getOperand(4).getImm(); 8108 8109 // If we have a sequence of Select* pseudo instructions using the 8110 // same condition code value, we want to expand all of them into 8111 // a single pair of basic blocks using the same condition. 8112 SmallVector<MachineInstr*, 8> Selects; 8113 SmallVector<MachineInstr*, 8> DbgValues; 8114 Selects.push_back(&MI); 8115 unsigned Count = 0; 8116 for (MachineInstr &NextMI : llvm::make_range( 8117 std::next(MachineBasicBlock::iterator(MI)), MBB->end())) { 8118 if (isSelectPseudo(NextMI)) { 8119 assert(NextMI.getOperand(3).getImm() == CCValid && 8120 "Bad CCValid operands since CC was not redefined."); 8121 if (NextMI.getOperand(4).getImm() == CCMask || 8122 NextMI.getOperand(4).getImm() == (CCValid ^ CCMask)) { 8123 Selects.push_back(&NextMI); 8124 continue; 8125 } 8126 break; 8127 } 8128 if (NextMI.definesRegister(SystemZ::CC) || NextMI.usesCustomInsertionHook()) 8129 break; 8130 bool User = false; 8131 for (auto *SelMI : Selects) 8132 if (NextMI.readsVirtualRegister(SelMI->getOperand(0).getReg())) { 8133 User = true; 8134 break; 8135 } 8136 if (NextMI.isDebugInstr()) { 8137 if (User) { 8138 assert(NextMI.isDebugValue() && "Unhandled debug opcode."); 8139 DbgValues.push_back(&NextMI); 8140 } 8141 } else if (User || ++Count > 20) 8142 break; 8143 } 8144 8145 MachineInstr *LastMI = Selects.back(); 8146 bool CCKilled = 8147 (LastMI->killsRegister(SystemZ::CC) || checkCCKill(*LastMI, MBB)); 8148 MachineBasicBlock *StartMBB = MBB; 8149 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(LastMI, MBB); 8150 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB); 8151 8152 // Unless CC was killed in the last Select instruction, mark it as 8153 // live-in to both FalseMBB and JoinMBB. 8154 if (!CCKilled) { 8155 FalseMBB->addLiveIn(SystemZ::CC); 8156 JoinMBB->addLiveIn(SystemZ::CC); 8157 } 8158 8159 // StartMBB: 8160 // BRC CCMask, JoinMBB 8161 // # fallthrough to FalseMBB 8162 MBB = StartMBB; 8163 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC)) 8164 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB); 8165 MBB->addSuccessor(JoinMBB); 8166 MBB->addSuccessor(FalseMBB); 8167 8168 // FalseMBB: 8169 // # fallthrough to JoinMBB 8170 MBB = FalseMBB; 8171 MBB->addSuccessor(JoinMBB); 8172 8173 // JoinMBB: 8174 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ] 8175 // ... 8176 MBB = JoinMBB; 8177 createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB); 8178 for (auto *SelMI : Selects) 8179 SelMI->eraseFromParent(); 8180 8181 MachineBasicBlock::iterator InsertPos = MBB->getFirstNonPHI(); 8182 for (auto *DbgMI : DbgValues) 8183 MBB->splice(InsertPos, StartMBB, DbgMI); 8184 8185 return JoinMBB; 8186 } 8187 8188 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI. 8189 // StoreOpcode is the store to use and Invert says whether the store should 8190 // happen when the condition is false rather than true. If a STORE ON 8191 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0. 8192 MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI, 8193 MachineBasicBlock *MBB, 8194 unsigned StoreOpcode, 8195 unsigned STOCOpcode, 8196 bool Invert) const { 8197 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 8198 8199 Register SrcReg = MI.getOperand(0).getReg(); 8200 MachineOperand Base = MI.getOperand(1); 8201 int64_t Disp = MI.getOperand(2).getImm(); 8202 Register IndexReg = MI.getOperand(3).getReg(); 8203 unsigned CCValid = MI.getOperand(4).getImm(); 8204 unsigned CCMask = MI.getOperand(5).getImm(); 8205 DebugLoc DL = MI.getDebugLoc(); 8206 8207 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp); 8208 8209 // ISel pattern matching also adds a load memory operand of the same 8210 // address, so take special care to find the storing memory operand. 8211 MachineMemOperand *MMO = nullptr; 8212 for (auto *I : MI.memoperands()) 8213 if (I->isStore()) { 8214 MMO = I; 8215 break; 8216 } 8217 8218 // Use STOCOpcode if possible. We could use different store patterns in 8219 // order to avoid matching the index register, but the performance trade-offs 8220 // might be more complicated in that case. 8221 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) { 8222 if (Invert) 8223 CCMask ^= CCValid; 8224 8225 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode)) 8226 .addReg(SrcReg) 8227 .add(Base) 8228 .addImm(Disp) 8229 .addImm(CCValid) 8230 .addImm(CCMask) 8231 .addMemOperand(MMO); 8232 8233 MI.eraseFromParent(); 8234 return MBB; 8235 } 8236 8237 // Get the condition needed to branch around the store. 8238 if (!Invert) 8239 CCMask ^= CCValid; 8240 8241 MachineBasicBlock *StartMBB = MBB; 8242 MachineBasicBlock *JoinMBB = SystemZ::splitBlockBefore(MI, MBB); 8243 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB); 8244 8245 // Unless CC was killed in the CondStore instruction, mark it as 8246 // live-in to both FalseMBB and JoinMBB. 8247 if (!MI.killsRegister(SystemZ::CC) && !checkCCKill(MI, JoinMBB)) { 8248 FalseMBB->addLiveIn(SystemZ::CC); 8249 JoinMBB->addLiveIn(SystemZ::CC); 8250 } 8251 8252 // StartMBB: 8253 // BRC CCMask, JoinMBB 8254 // # fallthrough to FalseMBB 8255 MBB = StartMBB; 8256 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8257 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB); 8258 MBB->addSuccessor(JoinMBB); 8259 MBB->addSuccessor(FalseMBB); 8260 8261 // FalseMBB: 8262 // store %SrcReg, %Disp(%Index,%Base) 8263 // # fallthrough to JoinMBB 8264 MBB = FalseMBB; 8265 BuildMI(MBB, DL, TII->get(StoreOpcode)) 8266 .addReg(SrcReg) 8267 .add(Base) 8268 .addImm(Disp) 8269 .addReg(IndexReg) 8270 .addMemOperand(MMO); 8271 MBB->addSuccessor(JoinMBB); 8272 8273 MI.eraseFromParent(); 8274 return JoinMBB; 8275 } 8276 8277 // Implement EmitInstrWithCustomInserter for pseudo [SU]Cmp128Hi instruction MI. 8278 MachineBasicBlock * 8279 SystemZTargetLowering::emitICmp128Hi(MachineInstr &MI, 8280 MachineBasicBlock *MBB, 8281 bool Unsigned) const { 8282 MachineFunction &MF = *MBB->getParent(); 8283 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 8284 MachineRegisterInfo &MRI = MF.getRegInfo(); 8285 8286 // Synthetic instruction to compare 128-bit values. 8287 // Sets CC 1 if Op0 > Op1, sets a different CC otherwise. 8288 Register Op0 = MI.getOperand(0).getReg(); 8289 Register Op1 = MI.getOperand(1).getReg(); 8290 8291 MachineBasicBlock *StartMBB = MBB; 8292 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(MI, MBB); 8293 MachineBasicBlock *HiEqMBB = SystemZ::emitBlockAfter(StartMBB); 8294 8295 // StartMBB: 8296 // 8297 // Use VECTOR ELEMENT COMPARE [LOGICAL] to compare the high parts. 8298 // Swap the inputs to get: 8299 // CC 1 if high(Op0) > high(Op1) 8300 // CC 2 if high(Op0) < high(Op1) 8301 // CC 0 if high(Op0) == high(Op1) 8302 // 8303 // If CC != 0, we'd done, so jump over the next instruction. 8304 // 8305 // VEC[L]G Op1, Op0 8306 // JNE JoinMBB 8307 // # fallthrough to HiEqMBB 8308 MBB = StartMBB; 8309 int HiOpcode = Unsigned? SystemZ::VECLG : SystemZ::VECG; 8310 BuildMI(MBB, MI.getDebugLoc(), TII->get(HiOpcode)) 8311 .addReg(Op1).addReg(Op0); 8312 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC)) 8313 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE).addMBB(JoinMBB); 8314 MBB->addSuccessor(JoinMBB); 8315 MBB->addSuccessor(HiEqMBB); 8316 8317 // HiEqMBB: 8318 // 8319 // Otherwise, use VECTOR COMPARE HIGH LOGICAL. 8320 // Since we already know the high parts are equal, the CC 8321 // result will only depend on the low parts: 8322 // CC 1 if low(Op0) > low(Op1) 8323 // CC 3 if low(Op0) <= low(Op1) 8324 // 8325 // VCHLGS Tmp, Op0, Op1 8326 // # fallthrough to JoinMBB 8327 MBB = HiEqMBB; 8328 Register Temp = MRI.createVirtualRegister(&SystemZ::VR128BitRegClass); 8329 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::VCHLGS), Temp) 8330 .addReg(Op0).addReg(Op1); 8331 MBB->addSuccessor(JoinMBB); 8332 8333 // Mark CC as live-in to JoinMBB. 8334 JoinMBB->addLiveIn(SystemZ::CC); 8335 8336 MI.eraseFromParent(); 8337 return JoinMBB; 8338 } 8339 8340 // Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_LOADW_* or 8341 // ATOMIC_SWAPW instruction MI. BinOpcode is the instruction that performs 8342 // the binary operation elided by "*", or 0 for ATOMIC_SWAPW. Invert says 8343 // whether the field should be inverted after performing BinOpcode (e.g. for 8344 // NAND). 8345 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary( 8346 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode, 8347 bool Invert) const { 8348 MachineFunction &MF = *MBB->getParent(); 8349 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 8350 MachineRegisterInfo &MRI = MF.getRegInfo(); 8351 8352 // Extract the operands. Base can be a register or a frame index. 8353 // Src2 can be a register or immediate. 8354 Register Dest = MI.getOperand(0).getReg(); 8355 MachineOperand Base = earlyUseOperand(MI.getOperand(1)); 8356 int64_t Disp = MI.getOperand(2).getImm(); 8357 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3)); 8358 Register BitShift = MI.getOperand(4).getReg(); 8359 Register NegBitShift = MI.getOperand(5).getReg(); 8360 unsigned BitSize = MI.getOperand(6).getImm(); 8361 DebugLoc DL = MI.getDebugLoc(); 8362 8363 // Get the right opcodes for the displacement. 8364 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp); 8365 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp); 8366 assert(LOpcode && CSOpcode && "Displacement out of range"); 8367 8368 // Create virtual registers for temporary results. 8369 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8370 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8371 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8372 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8373 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8374 8375 // Insert a basic block for the main loop. 8376 MachineBasicBlock *StartMBB = MBB; 8377 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB); 8378 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB); 8379 8380 // StartMBB: 8381 // ... 8382 // %OrigVal = L Disp(%Base) 8383 // # fall through to LoopMBB 8384 MBB = StartMBB; 8385 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0); 8386 MBB->addSuccessor(LoopMBB); 8387 8388 // LoopMBB: 8389 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ] 8390 // %RotatedOldVal = RLL %OldVal, 0(%BitShift) 8391 // %RotatedNewVal = OP %RotatedOldVal, %Src2 8392 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift) 8393 // %Dest = CS %OldVal, %NewVal, Disp(%Base) 8394 // JNE LoopMBB 8395 // # fall through to DoneMBB 8396 MBB = LoopMBB; 8397 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal) 8398 .addReg(OrigVal).addMBB(StartMBB) 8399 .addReg(Dest).addMBB(LoopMBB); 8400 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal) 8401 .addReg(OldVal).addReg(BitShift).addImm(0); 8402 if (Invert) { 8403 // Perform the operation normally and then invert every bit of the field. 8404 Register Tmp = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8405 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp).addReg(RotatedOldVal).add(Src2); 8406 // XILF with the upper BitSize bits set. 8407 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal) 8408 .addReg(Tmp).addImm(-1U << (32 - BitSize)); 8409 } else if (BinOpcode) 8410 // A simply binary operation. 8411 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal) 8412 .addReg(RotatedOldVal) 8413 .add(Src2); 8414 else 8415 // Use RISBG to rotate Src2 into position and use it to replace the 8416 // field in RotatedOldVal. 8417 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal) 8418 .addReg(RotatedOldVal).addReg(Src2.getReg()) 8419 .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize); 8420 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal) 8421 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0); 8422 BuildMI(MBB, DL, TII->get(CSOpcode), Dest) 8423 .addReg(OldVal) 8424 .addReg(NewVal) 8425 .add(Base) 8426 .addImm(Disp); 8427 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8428 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB); 8429 MBB->addSuccessor(LoopMBB); 8430 MBB->addSuccessor(DoneMBB); 8431 8432 MI.eraseFromParent(); 8433 return DoneMBB; 8434 } 8435 8436 // Implement EmitInstrWithCustomInserter for subword pseudo 8437 // ATOMIC_LOADW_{,U}{MIN,MAX} instruction MI. CompareOpcode is the 8438 // instruction that should be used to compare the current field with the 8439 // minimum or maximum value. KeepOldMask is the BRC condition-code mask 8440 // for when the current field should be kept. 8441 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax( 8442 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode, 8443 unsigned KeepOldMask) const { 8444 MachineFunction &MF = *MBB->getParent(); 8445 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 8446 MachineRegisterInfo &MRI = MF.getRegInfo(); 8447 8448 // Extract the operands. Base can be a register or a frame index. 8449 Register Dest = MI.getOperand(0).getReg(); 8450 MachineOperand Base = earlyUseOperand(MI.getOperand(1)); 8451 int64_t Disp = MI.getOperand(2).getImm(); 8452 Register Src2 = MI.getOperand(3).getReg(); 8453 Register BitShift = MI.getOperand(4).getReg(); 8454 Register NegBitShift = MI.getOperand(5).getReg(); 8455 unsigned BitSize = MI.getOperand(6).getImm(); 8456 DebugLoc DL = MI.getDebugLoc(); 8457 8458 // Get the right opcodes for the displacement. 8459 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp); 8460 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp); 8461 assert(LOpcode && CSOpcode && "Displacement out of range"); 8462 8463 // Create virtual registers for temporary results. 8464 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8465 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8466 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8467 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8468 Register RotatedAltVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8469 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass); 8470 8471 // Insert 3 basic blocks for the loop. 8472 MachineBasicBlock *StartMBB = MBB; 8473 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB); 8474 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB); 8475 MachineBasicBlock *UseAltMBB = SystemZ::emitBlockAfter(LoopMBB); 8476 MachineBasicBlock *UpdateMBB = SystemZ::emitBlockAfter(UseAltMBB); 8477 8478 // StartMBB: 8479 // ... 8480 // %OrigVal = L Disp(%Base) 8481 // # fall through to LoopMBB 8482 MBB = StartMBB; 8483 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0); 8484 MBB->addSuccessor(LoopMBB); 8485 8486 // LoopMBB: 8487 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ] 8488 // %RotatedOldVal = RLL %OldVal, 0(%BitShift) 8489 // CompareOpcode %RotatedOldVal, %Src2 8490 // BRC KeepOldMask, UpdateMBB 8491 MBB = LoopMBB; 8492 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal) 8493 .addReg(OrigVal).addMBB(StartMBB) 8494 .addReg(Dest).addMBB(UpdateMBB); 8495 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal) 8496 .addReg(OldVal).addReg(BitShift).addImm(0); 8497 BuildMI(MBB, DL, TII->get(CompareOpcode)) 8498 .addReg(RotatedOldVal).addReg(Src2); 8499 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8500 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB); 8501 MBB->addSuccessor(UpdateMBB); 8502 MBB->addSuccessor(UseAltMBB); 8503 8504 // UseAltMBB: 8505 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0 8506 // # fall through to UpdateMBB 8507 MBB = UseAltMBB; 8508 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal) 8509 .addReg(RotatedOldVal).addReg(Src2) 8510 .addImm(32).addImm(31 + BitSize).addImm(0); 8511 MBB->addSuccessor(UpdateMBB); 8512 8513 // UpdateMBB: 8514 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ], 8515 // [ %RotatedAltVal, UseAltMBB ] 8516 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift) 8517 // %Dest = CS %OldVal, %NewVal, Disp(%Base) 8518 // JNE LoopMBB 8519 // # fall through to DoneMBB 8520 MBB = UpdateMBB; 8521 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal) 8522 .addReg(RotatedOldVal).addMBB(LoopMBB) 8523 .addReg(RotatedAltVal).addMBB(UseAltMBB); 8524 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal) 8525 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0); 8526 BuildMI(MBB, DL, TII->get(CSOpcode), Dest) 8527 .addReg(OldVal) 8528 .addReg(NewVal) 8529 .add(Base) 8530 .addImm(Disp); 8531 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8532 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB); 8533 MBB->addSuccessor(LoopMBB); 8534 MBB->addSuccessor(DoneMBB); 8535 8536 MI.eraseFromParent(); 8537 return DoneMBB; 8538 } 8539 8540 // Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_CMP_SWAPW 8541 // instruction MI. 8542 MachineBasicBlock * 8543 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI, 8544 MachineBasicBlock *MBB) const { 8545 MachineFunction &MF = *MBB->getParent(); 8546 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 8547 MachineRegisterInfo &MRI = MF.getRegInfo(); 8548 8549 // Extract the operands. Base can be a register or a frame index. 8550 Register Dest = MI.getOperand(0).getReg(); 8551 MachineOperand Base = earlyUseOperand(MI.getOperand(1)); 8552 int64_t Disp = MI.getOperand(2).getImm(); 8553 Register CmpVal = MI.getOperand(3).getReg(); 8554 Register OrigSwapVal = MI.getOperand(4).getReg(); 8555 Register BitShift = MI.getOperand(5).getReg(); 8556 Register NegBitShift = MI.getOperand(6).getReg(); 8557 int64_t BitSize = MI.getOperand(7).getImm(); 8558 DebugLoc DL = MI.getDebugLoc(); 8559 8560 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass; 8561 8562 // Get the right opcodes for the displacement and zero-extension. 8563 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp); 8564 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp); 8565 unsigned ZExtOpcode = BitSize == 8 ? SystemZ::LLCR : SystemZ::LLHR; 8566 assert(LOpcode && CSOpcode && "Displacement out of range"); 8567 8568 // Create virtual registers for temporary results. 8569 Register OrigOldVal = MRI.createVirtualRegister(RC); 8570 Register OldVal = MRI.createVirtualRegister(RC); 8571 Register SwapVal = MRI.createVirtualRegister(RC); 8572 Register StoreVal = MRI.createVirtualRegister(RC); 8573 Register OldValRot = MRI.createVirtualRegister(RC); 8574 Register RetryOldVal = MRI.createVirtualRegister(RC); 8575 Register RetrySwapVal = MRI.createVirtualRegister(RC); 8576 8577 // Insert 2 basic blocks for the loop. 8578 MachineBasicBlock *StartMBB = MBB; 8579 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB); 8580 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB); 8581 MachineBasicBlock *SetMBB = SystemZ::emitBlockAfter(LoopMBB); 8582 8583 // StartMBB: 8584 // ... 8585 // %OrigOldVal = L Disp(%Base) 8586 // # fall through to LoopMBB 8587 MBB = StartMBB; 8588 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal) 8589 .add(Base) 8590 .addImm(Disp) 8591 .addReg(0); 8592 MBB->addSuccessor(LoopMBB); 8593 8594 // LoopMBB: 8595 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ] 8596 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ] 8597 // %OldValRot = RLL %OldVal, BitSize(%BitShift) 8598 // ^^ The low BitSize bits contain the field 8599 // of interest. 8600 // %RetrySwapVal = RISBG32 %SwapVal, %OldValRot, 32, 63-BitSize, 0 8601 // ^^ Replace the upper 32-BitSize bits of the 8602 // swap value with those that we loaded and rotated. 8603 // %Dest = LL[CH] %OldValRot 8604 // CR %Dest, %CmpVal 8605 // JNE DoneMBB 8606 // # Fall through to SetMBB 8607 MBB = LoopMBB; 8608 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal) 8609 .addReg(OrigOldVal).addMBB(StartMBB) 8610 .addReg(RetryOldVal).addMBB(SetMBB); 8611 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal) 8612 .addReg(OrigSwapVal).addMBB(StartMBB) 8613 .addReg(RetrySwapVal).addMBB(SetMBB); 8614 BuildMI(MBB, DL, TII->get(SystemZ::RLL), OldValRot) 8615 .addReg(OldVal).addReg(BitShift).addImm(BitSize); 8616 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal) 8617 .addReg(SwapVal).addReg(OldValRot).addImm(32).addImm(63 - BitSize).addImm(0); 8618 BuildMI(MBB, DL, TII->get(ZExtOpcode), Dest) 8619 .addReg(OldValRot); 8620 BuildMI(MBB, DL, TII->get(SystemZ::CR)) 8621 .addReg(Dest).addReg(CmpVal); 8622 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8623 .addImm(SystemZ::CCMASK_ICMP) 8624 .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB); 8625 MBB->addSuccessor(DoneMBB); 8626 MBB->addSuccessor(SetMBB); 8627 8628 // SetMBB: 8629 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift) 8630 // ^^ Rotate the new field to its proper position. 8631 // %RetryOldVal = CS %OldVal, %StoreVal, Disp(%Base) 8632 // JNE LoopMBB 8633 // # fall through to ExitMBB 8634 MBB = SetMBB; 8635 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal) 8636 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize); 8637 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal) 8638 .addReg(OldVal) 8639 .addReg(StoreVal) 8640 .add(Base) 8641 .addImm(Disp); 8642 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8643 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB); 8644 MBB->addSuccessor(LoopMBB); 8645 MBB->addSuccessor(DoneMBB); 8646 8647 // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in 8648 // to the block after the loop. At this point, CC may have been defined 8649 // either by the CR in LoopMBB or by the CS in SetMBB. 8650 if (!MI.registerDefIsDead(SystemZ::CC)) 8651 DoneMBB->addLiveIn(SystemZ::CC); 8652 8653 MI.eraseFromParent(); 8654 return DoneMBB; 8655 } 8656 8657 // Emit a move from two GR64s to a GR128. 8658 MachineBasicBlock * 8659 SystemZTargetLowering::emitPair128(MachineInstr &MI, 8660 MachineBasicBlock *MBB) const { 8661 MachineFunction &MF = *MBB->getParent(); 8662 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 8663 MachineRegisterInfo &MRI = MF.getRegInfo(); 8664 DebugLoc DL = MI.getDebugLoc(); 8665 8666 Register Dest = MI.getOperand(0).getReg(); 8667 Register Hi = MI.getOperand(1).getReg(); 8668 Register Lo = MI.getOperand(2).getReg(); 8669 Register Tmp1 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass); 8670 Register Tmp2 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass); 8671 8672 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Tmp1); 8673 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Tmp2) 8674 .addReg(Tmp1).addReg(Hi).addImm(SystemZ::subreg_h64); 8675 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest) 8676 .addReg(Tmp2).addReg(Lo).addImm(SystemZ::subreg_l64); 8677 8678 MI.eraseFromParent(); 8679 return MBB; 8680 } 8681 8682 // Emit an extension from a GR64 to a GR128. ClearEven is true 8683 // if the high register of the GR128 value must be cleared or false if 8684 // it's "don't care". 8685 MachineBasicBlock *SystemZTargetLowering::emitExt128(MachineInstr &MI, 8686 MachineBasicBlock *MBB, 8687 bool ClearEven) const { 8688 MachineFunction &MF = *MBB->getParent(); 8689 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 8690 MachineRegisterInfo &MRI = MF.getRegInfo(); 8691 DebugLoc DL = MI.getDebugLoc(); 8692 8693 Register Dest = MI.getOperand(0).getReg(); 8694 Register Src = MI.getOperand(1).getReg(); 8695 Register In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass); 8696 8697 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128); 8698 if (ClearEven) { 8699 Register NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass); 8700 Register Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass); 8701 8702 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64) 8703 .addImm(0); 8704 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128) 8705 .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64); 8706 In128 = NewIn128; 8707 } 8708 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest) 8709 .addReg(In128).addReg(Src).addImm(SystemZ::subreg_l64); 8710 8711 MI.eraseFromParent(); 8712 return MBB; 8713 } 8714 8715 MachineBasicBlock * 8716 SystemZTargetLowering::emitMemMemWrapper(MachineInstr &MI, 8717 MachineBasicBlock *MBB, 8718 unsigned Opcode, bool IsMemset) const { 8719 MachineFunction &MF = *MBB->getParent(); 8720 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 8721 MachineRegisterInfo &MRI = MF.getRegInfo(); 8722 DebugLoc DL = MI.getDebugLoc(); 8723 8724 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0)); 8725 uint64_t DestDisp = MI.getOperand(1).getImm(); 8726 MachineOperand SrcBase = MachineOperand::CreateReg(0U, false); 8727 uint64_t SrcDisp; 8728 8729 // Fold the displacement Disp if it is out of range. 8730 auto foldDisplIfNeeded = [&](MachineOperand &Base, uint64_t &Disp) -> void { 8731 if (!isUInt<12>(Disp)) { 8732 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass); 8733 unsigned Opcode = TII->getOpcodeForOffset(SystemZ::LA, Disp); 8734 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(Opcode), Reg) 8735 .add(Base).addImm(Disp).addReg(0); 8736 Base = MachineOperand::CreateReg(Reg, false); 8737 Disp = 0; 8738 } 8739 }; 8740 8741 if (!IsMemset) { 8742 SrcBase = earlyUseOperand(MI.getOperand(2)); 8743 SrcDisp = MI.getOperand(3).getImm(); 8744 } else { 8745 SrcBase = DestBase; 8746 SrcDisp = DestDisp++; 8747 foldDisplIfNeeded(DestBase, DestDisp); 8748 } 8749 8750 MachineOperand &LengthMO = MI.getOperand(IsMemset ? 2 : 4); 8751 bool IsImmForm = LengthMO.isImm(); 8752 bool IsRegForm = !IsImmForm; 8753 8754 // Build and insert one Opcode of Length, with special treatment for memset. 8755 auto insertMemMemOp = [&](MachineBasicBlock *InsMBB, 8756 MachineBasicBlock::iterator InsPos, 8757 MachineOperand DBase, uint64_t DDisp, 8758 MachineOperand SBase, uint64_t SDisp, 8759 unsigned Length) -> void { 8760 assert(Length > 0 && Length <= 256 && "Building memory op with bad length."); 8761 if (IsMemset) { 8762 MachineOperand ByteMO = earlyUseOperand(MI.getOperand(3)); 8763 if (ByteMO.isImm()) 8764 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::MVI)) 8765 .add(SBase).addImm(SDisp).add(ByteMO); 8766 else 8767 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::STC)) 8768 .add(ByteMO).add(SBase).addImm(SDisp).addReg(0); 8769 if (--Length == 0) 8770 return; 8771 } 8772 BuildMI(*MBB, InsPos, DL, TII->get(Opcode)) 8773 .add(DBase).addImm(DDisp).addImm(Length) 8774 .add(SBase).addImm(SDisp) 8775 .setMemRefs(MI.memoperands()); 8776 }; 8777 8778 bool NeedsLoop = false; 8779 uint64_t ImmLength = 0; 8780 Register LenAdjReg = SystemZ::NoRegister; 8781 if (IsImmForm) { 8782 ImmLength = LengthMO.getImm(); 8783 ImmLength += IsMemset ? 2 : 1; // Add back the subtracted adjustment. 8784 if (ImmLength == 0) { 8785 MI.eraseFromParent(); 8786 return MBB; 8787 } 8788 if (Opcode == SystemZ::CLC) { 8789 if (ImmLength > 3 * 256) 8790 // A two-CLC sequence is a clear win over a loop, not least because 8791 // it needs only one branch. A three-CLC sequence needs the same 8792 // number of branches as a loop (i.e. 2), but is shorter. That 8793 // brings us to lengths greater than 768 bytes. It seems relatively 8794 // likely that a difference will be found within the first 768 bytes, 8795 // so we just optimize for the smallest number of branch 8796 // instructions, in order to avoid polluting the prediction buffer 8797 // too much. 8798 NeedsLoop = true; 8799 } else if (ImmLength > 6 * 256) 8800 // The heuristic we use is to prefer loops for anything that would 8801 // require 7 or more MVCs. With these kinds of sizes there isn't much 8802 // to choose between straight-line code and looping code, since the 8803 // time will be dominated by the MVCs themselves. 8804 NeedsLoop = true; 8805 } else { 8806 NeedsLoop = true; 8807 LenAdjReg = LengthMO.getReg(); 8808 } 8809 8810 // When generating more than one CLC, all but the last will need to 8811 // branch to the end when a difference is found. 8812 MachineBasicBlock *EndMBB = 8813 (Opcode == SystemZ::CLC && (ImmLength > 256 || NeedsLoop) 8814 ? SystemZ::splitBlockAfter(MI, MBB) 8815 : nullptr); 8816 8817 if (NeedsLoop) { 8818 Register StartCountReg = 8819 MRI.createVirtualRegister(&SystemZ::GR64BitRegClass); 8820 if (IsImmForm) { 8821 TII->loadImmediate(*MBB, MI, StartCountReg, ImmLength / 256); 8822 ImmLength &= 255; 8823 } else { 8824 BuildMI(*MBB, MI, DL, TII->get(SystemZ::SRLG), StartCountReg) 8825 .addReg(LenAdjReg) 8826 .addReg(0) 8827 .addImm(8); 8828 } 8829 8830 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase); 8831 auto loadZeroAddress = [&]() -> MachineOperand { 8832 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass); 8833 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LGHI), Reg).addImm(0); 8834 return MachineOperand::CreateReg(Reg, false); 8835 }; 8836 if (DestBase.isReg() && DestBase.getReg() == SystemZ::NoRegister) 8837 DestBase = loadZeroAddress(); 8838 if (SrcBase.isReg() && SrcBase.getReg() == SystemZ::NoRegister) 8839 SrcBase = HaveSingleBase ? DestBase : loadZeroAddress(); 8840 8841 MachineBasicBlock *StartMBB = nullptr; 8842 MachineBasicBlock *LoopMBB = nullptr; 8843 MachineBasicBlock *NextMBB = nullptr; 8844 MachineBasicBlock *DoneMBB = nullptr; 8845 MachineBasicBlock *AllDoneMBB = nullptr; 8846 8847 Register StartSrcReg = forceReg(MI, SrcBase, TII); 8848 Register StartDestReg = 8849 (HaveSingleBase ? StartSrcReg : forceReg(MI, DestBase, TII)); 8850 8851 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass; 8852 Register ThisSrcReg = MRI.createVirtualRegister(RC); 8853 Register ThisDestReg = 8854 (HaveSingleBase ? ThisSrcReg : MRI.createVirtualRegister(RC)); 8855 Register NextSrcReg = MRI.createVirtualRegister(RC); 8856 Register NextDestReg = 8857 (HaveSingleBase ? NextSrcReg : MRI.createVirtualRegister(RC)); 8858 RC = &SystemZ::GR64BitRegClass; 8859 Register ThisCountReg = MRI.createVirtualRegister(RC); 8860 Register NextCountReg = MRI.createVirtualRegister(RC); 8861 8862 if (IsRegForm) { 8863 AllDoneMBB = SystemZ::splitBlockBefore(MI, MBB); 8864 StartMBB = SystemZ::emitBlockAfter(MBB); 8865 LoopMBB = SystemZ::emitBlockAfter(StartMBB); 8866 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB); 8867 DoneMBB = SystemZ::emitBlockAfter(NextMBB); 8868 8869 // MBB: 8870 // # Jump to AllDoneMBB if LenAdjReg means 0, or fall thru to StartMBB. 8871 BuildMI(MBB, DL, TII->get(SystemZ::CGHI)) 8872 .addReg(LenAdjReg).addImm(IsMemset ? -2 : -1); 8873 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8874 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_EQ) 8875 .addMBB(AllDoneMBB); 8876 MBB->addSuccessor(AllDoneMBB); 8877 if (!IsMemset) 8878 MBB->addSuccessor(StartMBB); 8879 else { 8880 // MemsetOneCheckMBB: 8881 // # Jump to MemsetOneMBB for a memset of length 1, or 8882 // # fall thru to StartMBB. 8883 MachineBasicBlock *MemsetOneCheckMBB = SystemZ::emitBlockAfter(MBB); 8884 MachineBasicBlock *MemsetOneMBB = SystemZ::emitBlockAfter(&*MF.rbegin()); 8885 MBB->addSuccessor(MemsetOneCheckMBB); 8886 MBB = MemsetOneCheckMBB; 8887 BuildMI(MBB, DL, TII->get(SystemZ::CGHI)) 8888 .addReg(LenAdjReg).addImm(-1); 8889 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8890 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_EQ) 8891 .addMBB(MemsetOneMBB); 8892 MBB->addSuccessor(MemsetOneMBB, {10, 100}); 8893 MBB->addSuccessor(StartMBB, {90, 100}); 8894 8895 // MemsetOneMBB: 8896 // # Jump back to AllDoneMBB after a single MVI or STC. 8897 MBB = MemsetOneMBB; 8898 insertMemMemOp(MBB, MBB->end(), 8899 MachineOperand::CreateReg(StartDestReg, false), DestDisp, 8900 MachineOperand::CreateReg(StartSrcReg, false), SrcDisp, 8901 1); 8902 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(AllDoneMBB); 8903 MBB->addSuccessor(AllDoneMBB); 8904 } 8905 8906 // StartMBB: 8907 // # Jump to DoneMBB if %StartCountReg is zero, or fall through to LoopMBB. 8908 MBB = StartMBB; 8909 BuildMI(MBB, DL, TII->get(SystemZ::CGHI)) 8910 .addReg(StartCountReg).addImm(0); 8911 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8912 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_EQ) 8913 .addMBB(DoneMBB); 8914 MBB->addSuccessor(DoneMBB); 8915 MBB->addSuccessor(LoopMBB); 8916 } 8917 else { 8918 StartMBB = MBB; 8919 DoneMBB = SystemZ::splitBlockBefore(MI, MBB); 8920 LoopMBB = SystemZ::emitBlockAfter(StartMBB); 8921 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB); 8922 8923 // StartMBB: 8924 // # fall through to LoopMBB 8925 MBB->addSuccessor(LoopMBB); 8926 8927 DestBase = MachineOperand::CreateReg(NextDestReg, false); 8928 SrcBase = MachineOperand::CreateReg(NextSrcReg, false); 8929 if (EndMBB && !ImmLength) 8930 // If the loop handled the whole CLC range, DoneMBB will be empty with 8931 // CC live-through into EndMBB, so add it as live-in. 8932 DoneMBB->addLiveIn(SystemZ::CC); 8933 } 8934 8935 // LoopMBB: 8936 // %ThisDestReg = phi [ %StartDestReg, StartMBB ], 8937 // [ %NextDestReg, NextMBB ] 8938 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ], 8939 // [ %NextSrcReg, NextMBB ] 8940 // %ThisCountReg = phi [ %StartCountReg, StartMBB ], 8941 // [ %NextCountReg, NextMBB ] 8942 // ( PFD 2, 768+DestDisp(%ThisDestReg) ) 8943 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg) 8944 // ( JLH EndMBB ) 8945 // 8946 // The prefetch is used only for MVC. The JLH is used only for CLC. 8947 MBB = LoopMBB; 8948 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg) 8949 .addReg(StartDestReg).addMBB(StartMBB) 8950 .addReg(NextDestReg).addMBB(NextMBB); 8951 if (!HaveSingleBase) 8952 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg) 8953 .addReg(StartSrcReg).addMBB(StartMBB) 8954 .addReg(NextSrcReg).addMBB(NextMBB); 8955 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg) 8956 .addReg(StartCountReg).addMBB(StartMBB) 8957 .addReg(NextCountReg).addMBB(NextMBB); 8958 if (Opcode == SystemZ::MVC) 8959 BuildMI(MBB, DL, TII->get(SystemZ::PFD)) 8960 .addImm(SystemZ::PFD_WRITE) 8961 .addReg(ThisDestReg).addImm(DestDisp - IsMemset + 768).addReg(0); 8962 insertMemMemOp(MBB, MBB->end(), 8963 MachineOperand::CreateReg(ThisDestReg, false), DestDisp, 8964 MachineOperand::CreateReg(ThisSrcReg, false), SrcDisp, 256); 8965 if (EndMBB) { 8966 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8967 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE) 8968 .addMBB(EndMBB); 8969 MBB->addSuccessor(EndMBB); 8970 MBB->addSuccessor(NextMBB); 8971 } 8972 8973 // NextMBB: 8974 // %NextDestReg = LA 256(%ThisDestReg) 8975 // %NextSrcReg = LA 256(%ThisSrcReg) 8976 // %NextCountReg = AGHI %ThisCountReg, -1 8977 // CGHI %NextCountReg, 0 8978 // JLH LoopMBB 8979 // # fall through to DoneMBB 8980 // 8981 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes. 8982 MBB = NextMBB; 8983 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg) 8984 .addReg(ThisDestReg).addImm(256).addReg(0); 8985 if (!HaveSingleBase) 8986 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg) 8987 .addReg(ThisSrcReg).addImm(256).addReg(0); 8988 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg) 8989 .addReg(ThisCountReg).addImm(-1); 8990 BuildMI(MBB, DL, TII->get(SystemZ::CGHI)) 8991 .addReg(NextCountReg).addImm(0); 8992 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 8993 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE) 8994 .addMBB(LoopMBB); 8995 MBB->addSuccessor(LoopMBB); 8996 MBB->addSuccessor(DoneMBB); 8997 8998 MBB = DoneMBB; 8999 if (IsRegForm) { 9000 // DoneMBB: 9001 // # Make PHIs for RemDestReg/RemSrcReg as the loop may or may not run. 9002 // # Use EXecute Relative Long for the remainder of the bytes. The target 9003 // instruction of the EXRL will have a length field of 1 since 0 is an 9004 // illegal value. The number of bytes processed becomes (%LenAdjReg & 9005 // 0xff) + 1. 9006 // # Fall through to AllDoneMBB. 9007 Register RemSrcReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass); 9008 Register RemDestReg = HaveSingleBase ? RemSrcReg 9009 : MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass); 9010 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemDestReg) 9011 .addReg(StartDestReg).addMBB(StartMBB) 9012 .addReg(NextDestReg).addMBB(NextMBB); 9013 if (!HaveSingleBase) 9014 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemSrcReg) 9015 .addReg(StartSrcReg).addMBB(StartMBB) 9016 .addReg(NextSrcReg).addMBB(NextMBB); 9017 if (IsMemset) 9018 insertMemMemOp(MBB, MBB->end(), 9019 MachineOperand::CreateReg(RemDestReg, false), DestDisp, 9020 MachineOperand::CreateReg(RemSrcReg, false), SrcDisp, 1); 9021 MachineInstrBuilder EXRL_MIB = 9022 BuildMI(MBB, DL, TII->get(SystemZ::EXRL_Pseudo)) 9023 .addImm(Opcode) 9024 .addReg(LenAdjReg) 9025 .addReg(RemDestReg).addImm(DestDisp) 9026 .addReg(RemSrcReg).addImm(SrcDisp); 9027 MBB->addSuccessor(AllDoneMBB); 9028 MBB = AllDoneMBB; 9029 if (Opcode != SystemZ::MVC) { 9030 EXRL_MIB.addReg(SystemZ::CC, RegState::ImplicitDefine); 9031 if (EndMBB) 9032 MBB->addLiveIn(SystemZ::CC); 9033 } 9034 } 9035 MF.getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9036 } 9037 9038 // Handle any remaining bytes with straight-line code. 9039 while (ImmLength > 0) { 9040 uint64_t ThisLength = std::min(ImmLength, uint64_t(256)); 9041 // The previous iteration might have created out-of-range displacements. 9042 // Apply them using LA/LAY if so. 9043 foldDisplIfNeeded(DestBase, DestDisp); 9044 foldDisplIfNeeded(SrcBase, SrcDisp); 9045 insertMemMemOp(MBB, MI, DestBase, DestDisp, SrcBase, SrcDisp, ThisLength); 9046 DestDisp += ThisLength; 9047 SrcDisp += ThisLength; 9048 ImmLength -= ThisLength; 9049 // If there's another CLC to go, branch to the end if a difference 9050 // was found. 9051 if (EndMBB && ImmLength > 0) { 9052 MachineBasicBlock *NextMBB = SystemZ::splitBlockBefore(MI, MBB); 9053 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 9054 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE) 9055 .addMBB(EndMBB); 9056 MBB->addSuccessor(EndMBB); 9057 MBB->addSuccessor(NextMBB); 9058 MBB = NextMBB; 9059 } 9060 } 9061 if (EndMBB) { 9062 MBB->addSuccessor(EndMBB); 9063 MBB = EndMBB; 9064 MBB->addLiveIn(SystemZ::CC); 9065 } 9066 9067 MI.eraseFromParent(); 9068 return MBB; 9069 } 9070 9071 // Decompose string pseudo-instruction MI into a loop that continually performs 9072 // Opcode until CC != 3. 9073 MachineBasicBlock *SystemZTargetLowering::emitStringWrapper( 9074 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const { 9075 MachineFunction &MF = *MBB->getParent(); 9076 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 9077 MachineRegisterInfo &MRI = MF.getRegInfo(); 9078 DebugLoc DL = MI.getDebugLoc(); 9079 9080 uint64_t End1Reg = MI.getOperand(0).getReg(); 9081 uint64_t Start1Reg = MI.getOperand(1).getReg(); 9082 uint64_t Start2Reg = MI.getOperand(2).getReg(); 9083 uint64_t CharReg = MI.getOperand(3).getReg(); 9084 9085 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass; 9086 uint64_t This1Reg = MRI.createVirtualRegister(RC); 9087 uint64_t This2Reg = MRI.createVirtualRegister(RC); 9088 uint64_t End2Reg = MRI.createVirtualRegister(RC); 9089 9090 MachineBasicBlock *StartMBB = MBB; 9091 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB); 9092 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB); 9093 9094 // StartMBB: 9095 // # fall through to LoopMBB 9096 MBB->addSuccessor(LoopMBB); 9097 9098 // LoopMBB: 9099 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ] 9100 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ] 9101 // R0L = %CharReg 9102 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L 9103 // JO LoopMBB 9104 // # fall through to DoneMBB 9105 // 9106 // The load of R0L can be hoisted by post-RA LICM. 9107 MBB = LoopMBB; 9108 9109 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg) 9110 .addReg(Start1Reg).addMBB(StartMBB) 9111 .addReg(End1Reg).addMBB(LoopMBB); 9112 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg) 9113 .addReg(Start2Reg).addMBB(StartMBB) 9114 .addReg(End2Reg).addMBB(LoopMBB); 9115 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg); 9116 BuildMI(MBB, DL, TII->get(Opcode)) 9117 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define) 9118 .addReg(This1Reg).addReg(This2Reg); 9119 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 9120 .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB); 9121 MBB->addSuccessor(LoopMBB); 9122 MBB->addSuccessor(DoneMBB); 9123 9124 DoneMBB->addLiveIn(SystemZ::CC); 9125 9126 MI.eraseFromParent(); 9127 return DoneMBB; 9128 } 9129 9130 // Update TBEGIN instruction with final opcode and register clobbers. 9131 MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin( 9132 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode, 9133 bool NoFloat) const { 9134 MachineFunction &MF = *MBB->getParent(); 9135 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 9136 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 9137 9138 // Update opcode. 9139 MI.setDesc(TII->get(Opcode)); 9140 9141 // We cannot handle a TBEGIN that clobbers the stack or frame pointer. 9142 // Make sure to add the corresponding GRSM bits if they are missing. 9143 uint64_t Control = MI.getOperand(2).getImm(); 9144 static const unsigned GPRControlBit[16] = { 9145 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000, 9146 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100 9147 }; 9148 Control |= GPRControlBit[15]; 9149 if (TFI->hasFP(MF)) 9150 Control |= GPRControlBit[11]; 9151 MI.getOperand(2).setImm(Control); 9152 9153 // Add GPR clobbers. 9154 for (int I = 0; I < 16; I++) { 9155 if ((Control & GPRControlBit[I]) == 0) { 9156 unsigned Reg = SystemZMC::GR64Regs[I]; 9157 MI.addOperand(MachineOperand::CreateReg(Reg, true, true)); 9158 } 9159 } 9160 9161 // Add FPR/VR clobbers. 9162 if (!NoFloat && (Control & 4) != 0) { 9163 if (Subtarget.hasVector()) { 9164 for (unsigned Reg : SystemZMC::VR128Regs) { 9165 MI.addOperand(MachineOperand::CreateReg(Reg, true, true)); 9166 } 9167 } else { 9168 for (unsigned Reg : SystemZMC::FP64Regs) { 9169 MI.addOperand(MachineOperand::CreateReg(Reg, true, true)); 9170 } 9171 } 9172 } 9173 9174 return MBB; 9175 } 9176 9177 MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0( 9178 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const { 9179 MachineFunction &MF = *MBB->getParent(); 9180 MachineRegisterInfo *MRI = &MF.getRegInfo(); 9181 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 9182 DebugLoc DL = MI.getDebugLoc(); 9183 9184 Register SrcReg = MI.getOperand(0).getReg(); 9185 9186 // Create new virtual register of the same class as source. 9187 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg); 9188 Register DstReg = MRI->createVirtualRegister(RC); 9189 9190 // Replace pseudo with a normal load-and-test that models the def as 9191 // well. 9192 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg) 9193 .addReg(SrcReg) 9194 .setMIFlags(MI.getFlags()); 9195 MI.eraseFromParent(); 9196 9197 return MBB; 9198 } 9199 9200 MachineBasicBlock *SystemZTargetLowering::emitProbedAlloca( 9201 MachineInstr &MI, MachineBasicBlock *MBB) const { 9202 MachineFunction &MF = *MBB->getParent(); 9203 MachineRegisterInfo *MRI = &MF.getRegInfo(); 9204 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 9205 DebugLoc DL = MI.getDebugLoc(); 9206 const unsigned ProbeSize = getStackProbeSize(MF); 9207 Register DstReg = MI.getOperand(0).getReg(); 9208 Register SizeReg = MI.getOperand(2).getReg(); 9209 9210 MachineBasicBlock *StartMBB = MBB; 9211 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB); 9212 MachineBasicBlock *LoopTestMBB = SystemZ::emitBlockAfter(StartMBB); 9213 MachineBasicBlock *LoopBodyMBB = SystemZ::emitBlockAfter(LoopTestMBB); 9214 MachineBasicBlock *TailTestMBB = SystemZ::emitBlockAfter(LoopBodyMBB); 9215 MachineBasicBlock *TailMBB = SystemZ::emitBlockAfter(TailTestMBB); 9216 9217 MachineMemOperand *VolLdMMO = MF.getMachineMemOperand(MachinePointerInfo(), 9218 MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad, 8, Align(1)); 9219 9220 Register PHIReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass); 9221 Register IncReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass); 9222 9223 // LoopTestMBB 9224 // BRC TailTestMBB 9225 // # fallthrough to LoopBodyMBB 9226 StartMBB->addSuccessor(LoopTestMBB); 9227 MBB = LoopTestMBB; 9228 BuildMI(MBB, DL, TII->get(SystemZ::PHI), PHIReg) 9229 .addReg(SizeReg) 9230 .addMBB(StartMBB) 9231 .addReg(IncReg) 9232 .addMBB(LoopBodyMBB); 9233 BuildMI(MBB, DL, TII->get(SystemZ::CLGFI)) 9234 .addReg(PHIReg) 9235 .addImm(ProbeSize); 9236 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 9237 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_LT) 9238 .addMBB(TailTestMBB); 9239 MBB->addSuccessor(LoopBodyMBB); 9240 MBB->addSuccessor(TailTestMBB); 9241 9242 // LoopBodyMBB: Allocate and probe by means of a volatile compare. 9243 // J LoopTestMBB 9244 MBB = LoopBodyMBB; 9245 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), IncReg) 9246 .addReg(PHIReg) 9247 .addImm(ProbeSize); 9248 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), SystemZ::R15D) 9249 .addReg(SystemZ::R15D) 9250 .addImm(ProbeSize); 9251 BuildMI(MBB, DL, TII->get(SystemZ::CG)).addReg(SystemZ::R15D) 9252 .addReg(SystemZ::R15D).addImm(ProbeSize - 8).addReg(0) 9253 .setMemRefs(VolLdMMO); 9254 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(LoopTestMBB); 9255 MBB->addSuccessor(LoopTestMBB); 9256 9257 // TailTestMBB 9258 // BRC DoneMBB 9259 // # fallthrough to TailMBB 9260 MBB = TailTestMBB; 9261 BuildMI(MBB, DL, TII->get(SystemZ::CGHI)) 9262 .addReg(PHIReg) 9263 .addImm(0); 9264 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 9265 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_EQ) 9266 .addMBB(DoneMBB); 9267 MBB->addSuccessor(TailMBB); 9268 MBB->addSuccessor(DoneMBB); 9269 9270 // TailMBB 9271 // # fallthrough to DoneMBB 9272 MBB = TailMBB; 9273 BuildMI(MBB, DL, TII->get(SystemZ::SLGR), SystemZ::R15D) 9274 .addReg(SystemZ::R15D) 9275 .addReg(PHIReg); 9276 BuildMI(MBB, DL, TII->get(SystemZ::CG)).addReg(SystemZ::R15D) 9277 .addReg(SystemZ::R15D).addImm(-8).addReg(PHIReg) 9278 .setMemRefs(VolLdMMO); 9279 MBB->addSuccessor(DoneMBB); 9280 9281 // DoneMBB 9282 MBB = DoneMBB; 9283 BuildMI(*MBB, MBB->begin(), DL, TII->get(TargetOpcode::COPY), DstReg) 9284 .addReg(SystemZ::R15D); 9285 9286 MI.eraseFromParent(); 9287 return DoneMBB; 9288 } 9289 9290 SDValue SystemZTargetLowering:: 9291 getBackchainAddress(SDValue SP, SelectionDAG &DAG) const { 9292 MachineFunction &MF = DAG.getMachineFunction(); 9293 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>(); 9294 SDLoc DL(SP); 9295 return DAG.getNode(ISD::ADD, DL, MVT::i64, SP, 9296 DAG.getIntPtrConstant(TFL->getBackchainOffset(MF), DL)); 9297 } 9298 9299 MachineBasicBlock *SystemZTargetLowering::EmitInstrWithCustomInserter( 9300 MachineInstr &MI, MachineBasicBlock *MBB) const { 9301 switch (MI.getOpcode()) { 9302 case SystemZ::Select32: 9303 case SystemZ::Select64: 9304 case SystemZ::Select128: 9305 case SystemZ::SelectF32: 9306 case SystemZ::SelectF64: 9307 case SystemZ::SelectF128: 9308 case SystemZ::SelectVR32: 9309 case SystemZ::SelectVR64: 9310 case SystemZ::SelectVR128: 9311 return emitSelect(MI, MBB); 9312 9313 case SystemZ::CondStore8Mux: 9314 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false); 9315 case SystemZ::CondStore8MuxInv: 9316 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true); 9317 case SystemZ::CondStore16Mux: 9318 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false); 9319 case SystemZ::CondStore16MuxInv: 9320 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true); 9321 case SystemZ::CondStore32Mux: 9322 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false); 9323 case SystemZ::CondStore32MuxInv: 9324 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true); 9325 case SystemZ::CondStore8: 9326 return emitCondStore(MI, MBB, SystemZ::STC, 0, false); 9327 case SystemZ::CondStore8Inv: 9328 return emitCondStore(MI, MBB, SystemZ::STC, 0, true); 9329 case SystemZ::CondStore16: 9330 return emitCondStore(MI, MBB, SystemZ::STH, 0, false); 9331 case SystemZ::CondStore16Inv: 9332 return emitCondStore(MI, MBB, SystemZ::STH, 0, true); 9333 case SystemZ::CondStore32: 9334 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false); 9335 case SystemZ::CondStore32Inv: 9336 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true); 9337 case SystemZ::CondStore64: 9338 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false); 9339 case SystemZ::CondStore64Inv: 9340 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true); 9341 case SystemZ::CondStoreF32: 9342 return emitCondStore(MI, MBB, SystemZ::STE, 0, false); 9343 case SystemZ::CondStoreF32Inv: 9344 return emitCondStore(MI, MBB, SystemZ::STE, 0, true); 9345 case SystemZ::CondStoreF64: 9346 return emitCondStore(MI, MBB, SystemZ::STD, 0, false); 9347 case SystemZ::CondStoreF64Inv: 9348 return emitCondStore(MI, MBB, SystemZ::STD, 0, true); 9349 9350 case SystemZ::SCmp128Hi: 9351 return emitICmp128Hi(MI, MBB, false); 9352 case SystemZ::UCmp128Hi: 9353 return emitICmp128Hi(MI, MBB, true); 9354 9355 case SystemZ::PAIR128: 9356 return emitPair128(MI, MBB); 9357 case SystemZ::AEXT128: 9358 return emitExt128(MI, MBB, false); 9359 case SystemZ::ZEXT128: 9360 return emitExt128(MI, MBB, true); 9361 9362 case SystemZ::ATOMIC_SWAPW: 9363 return emitAtomicLoadBinary(MI, MBB, 0); 9364 9365 case SystemZ::ATOMIC_LOADW_AR: 9366 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR); 9367 case SystemZ::ATOMIC_LOADW_AFI: 9368 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI); 9369 9370 case SystemZ::ATOMIC_LOADW_SR: 9371 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR); 9372 9373 case SystemZ::ATOMIC_LOADW_NR: 9374 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR); 9375 case SystemZ::ATOMIC_LOADW_NILH: 9376 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH); 9377 9378 case SystemZ::ATOMIC_LOADW_OR: 9379 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR); 9380 case SystemZ::ATOMIC_LOADW_OILH: 9381 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH); 9382 9383 case SystemZ::ATOMIC_LOADW_XR: 9384 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR); 9385 case SystemZ::ATOMIC_LOADW_XILF: 9386 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF); 9387 9388 case SystemZ::ATOMIC_LOADW_NRi: 9389 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, true); 9390 case SystemZ::ATOMIC_LOADW_NILHi: 9391 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, true); 9392 9393 case SystemZ::ATOMIC_LOADW_MIN: 9394 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_LE); 9395 case SystemZ::ATOMIC_LOADW_MAX: 9396 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_GE); 9397 case SystemZ::ATOMIC_LOADW_UMIN: 9398 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_LE); 9399 case SystemZ::ATOMIC_LOADW_UMAX: 9400 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_GE); 9401 9402 case SystemZ::ATOMIC_CMP_SWAPW: 9403 return emitAtomicCmpSwapW(MI, MBB); 9404 case SystemZ::MVCImm: 9405 case SystemZ::MVCReg: 9406 return emitMemMemWrapper(MI, MBB, SystemZ::MVC); 9407 case SystemZ::NCImm: 9408 return emitMemMemWrapper(MI, MBB, SystemZ::NC); 9409 case SystemZ::OCImm: 9410 return emitMemMemWrapper(MI, MBB, SystemZ::OC); 9411 case SystemZ::XCImm: 9412 case SystemZ::XCReg: 9413 return emitMemMemWrapper(MI, MBB, SystemZ::XC); 9414 case SystemZ::CLCImm: 9415 case SystemZ::CLCReg: 9416 return emitMemMemWrapper(MI, MBB, SystemZ::CLC); 9417 case SystemZ::MemsetImmImm: 9418 case SystemZ::MemsetImmReg: 9419 case SystemZ::MemsetRegImm: 9420 case SystemZ::MemsetRegReg: 9421 return emitMemMemWrapper(MI, MBB, SystemZ::MVC, true/*IsMemset*/); 9422 case SystemZ::CLSTLoop: 9423 return emitStringWrapper(MI, MBB, SystemZ::CLST); 9424 case SystemZ::MVSTLoop: 9425 return emitStringWrapper(MI, MBB, SystemZ::MVST); 9426 case SystemZ::SRSTLoop: 9427 return emitStringWrapper(MI, MBB, SystemZ::SRST); 9428 case SystemZ::TBEGIN: 9429 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false); 9430 case SystemZ::TBEGIN_nofloat: 9431 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true); 9432 case SystemZ::TBEGINC: 9433 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true); 9434 case SystemZ::LTEBRCompare_VecPseudo: 9435 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR); 9436 case SystemZ::LTDBRCompare_VecPseudo: 9437 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR); 9438 case SystemZ::LTXBRCompare_VecPseudo: 9439 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR); 9440 9441 case SystemZ::PROBED_ALLOCA: 9442 return emitProbedAlloca(MI, MBB); 9443 9444 case TargetOpcode::STACKMAP: 9445 case TargetOpcode::PATCHPOINT: 9446 return emitPatchPoint(MI, MBB); 9447 9448 default: 9449 llvm_unreachable("Unexpected instr type to insert"); 9450 } 9451 } 9452 9453 // This is only used by the isel schedulers, and is needed only to prevent 9454 // compiler from crashing when list-ilp is used. 9455 const TargetRegisterClass * 9456 SystemZTargetLowering::getRepRegClassFor(MVT VT) const { 9457 if (VT == MVT::Untyped) 9458 return &SystemZ::ADDR128BitRegClass; 9459 return TargetLowering::getRepRegClassFor(VT); 9460 } 9461 9462 SDValue SystemZTargetLowering::lowerGET_ROUNDING(SDValue Op, 9463 SelectionDAG &DAG) const { 9464 SDLoc dl(Op); 9465 /* 9466 The rounding method is in FPC Byte 3 bits 6-7, and has the following 9467 settings: 9468 00 Round to nearest 9469 01 Round to 0 9470 10 Round to +inf 9471 11 Round to -inf 9472 9473 FLT_ROUNDS, on the other hand, expects the following: 9474 -1 Undefined 9475 0 Round to 0 9476 1 Round to nearest 9477 2 Round to +inf 9478 3 Round to -inf 9479 */ 9480 9481 // Save FPC to register. 9482 SDValue Chain = Op.getOperand(0); 9483 SDValue EFPC( 9484 DAG.getMachineNode(SystemZ::EFPC, dl, {MVT::i32, MVT::Other}, Chain), 0); 9485 Chain = EFPC.getValue(1); 9486 9487 // Transform as necessary 9488 SDValue CWD1 = DAG.getNode(ISD::AND, dl, MVT::i32, EFPC, 9489 DAG.getConstant(3, dl, MVT::i32)); 9490 // RetVal = (CWD1 ^ (CWD1 >> 1)) ^ 1 9491 SDValue CWD2 = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, 9492 DAG.getNode(ISD::SRL, dl, MVT::i32, CWD1, 9493 DAG.getConstant(1, dl, MVT::i32))); 9494 9495 SDValue RetVal = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD2, 9496 DAG.getConstant(1, dl, MVT::i32)); 9497 RetVal = DAG.getZExtOrTrunc(RetVal, dl, Op.getValueType()); 9498 9499 return DAG.getMergeValues({RetVal, Chain}, dl); 9500 } 9501