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/Intrinsics.h" 23 #include "llvm/IR/IntrinsicInst.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Support/KnownBits.h" 26 #include <cctype> 27 28 using namespace llvm; 29 30 #define DEBUG_TYPE "systemz-lower" 31 32 namespace { 33 // Represents information about a comparison. 34 struct Comparison { 35 Comparison(SDValue Op0In, SDValue Op1In) 36 : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {} 37 38 // The operands to the comparison. 39 SDValue Op0, Op1; 40 41 // The opcode that should be used to compare Op0 and Op1. 42 unsigned Opcode; 43 44 // A SystemZICMP value. Only used for integer comparisons. 45 unsigned ICmpType; 46 47 // The mask of CC values that Opcode can produce. 48 unsigned CCValid; 49 50 // The mask of CC values for which the original condition is true. 51 unsigned CCMask; 52 }; 53 } // end anonymous namespace 54 55 // Classify VT as either 32 or 64 bit. 56 static bool is32Bit(EVT VT) { 57 switch (VT.getSimpleVT().SimpleTy) { 58 case MVT::i32: 59 return true; 60 case MVT::i64: 61 return false; 62 default: 63 llvm_unreachable("Unsupported type"); 64 } 65 } 66 67 // Return a version of MachineOperand that can be safely used before the 68 // final use. 69 static MachineOperand earlyUseOperand(MachineOperand Op) { 70 if (Op.isReg()) 71 Op.setIsKill(false); 72 return Op; 73 } 74 75 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &TM, 76 const SystemZSubtarget &STI) 77 : TargetLowering(TM), Subtarget(STI) { 78 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize(0)); 79 80 // Set up the register classes. 81 if (Subtarget.hasHighWord()) 82 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass); 83 else 84 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass); 85 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass); 86 if (Subtarget.hasVector()) { 87 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass); 88 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass); 89 } else { 90 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass); 91 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass); 92 } 93 if (Subtarget.hasVectorEnhancements1()) 94 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass); 95 else 96 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass); 97 98 if (Subtarget.hasVector()) { 99 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass); 100 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass); 101 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass); 102 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass); 103 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass); 104 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass); 105 } 106 107 // Compute derived properties from the register classes 108 computeRegisterProperties(Subtarget.getRegisterInfo()); 109 110 // Set up special registers. 111 setStackPointerRegisterToSaveRestore(SystemZ::R15D); 112 113 // TODO: It may be better to default to latency-oriented scheduling, however 114 // LLVM's current latency-oriented scheduler can't handle physreg definitions 115 // such as SystemZ has with CC, so set this to the register-pressure 116 // scheduler, because it can. 117 setSchedulingPreference(Sched::RegPressure); 118 119 setBooleanContents(ZeroOrOneBooleanContent); 120 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 121 122 // Instructions are strings of 2-byte aligned 2-byte values. 123 setMinFunctionAlignment(2); 124 // For performance reasons we prefer 16-byte alignment. 125 setPrefFunctionAlignment(4); 126 127 // Handle operations that are handled in a similar way for all types. 128 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE; 129 I <= MVT::LAST_FP_VALUETYPE; 130 ++I) { 131 MVT VT = MVT::SimpleValueType(I); 132 if (isTypeLegal(VT)) { 133 // Lower SET_CC into an IPM-based sequence. 134 setOperationAction(ISD::SETCC, VT, Custom); 135 136 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE). 137 setOperationAction(ISD::SELECT, VT, Expand); 138 139 // Lower SELECT_CC and BR_CC into separate comparisons and branches. 140 setOperationAction(ISD::SELECT_CC, VT, Custom); 141 setOperationAction(ISD::BR_CC, VT, Custom); 142 } 143 } 144 145 // Expand jump table branches as address arithmetic followed by an 146 // indirect jump. 147 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 148 149 // Expand BRCOND into a BR_CC (see above). 150 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 151 152 // Handle integer types. 153 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE; 154 I <= MVT::LAST_INTEGER_VALUETYPE; 155 ++I) { 156 MVT VT = MVT::SimpleValueType(I); 157 if (isTypeLegal(VT)) { 158 // Expand individual DIV and REMs into DIVREMs. 159 setOperationAction(ISD::SDIV, VT, Expand); 160 setOperationAction(ISD::UDIV, VT, Expand); 161 setOperationAction(ISD::SREM, VT, Expand); 162 setOperationAction(ISD::UREM, VT, Expand); 163 setOperationAction(ISD::SDIVREM, VT, Custom); 164 setOperationAction(ISD::UDIVREM, VT, Custom); 165 166 // Support addition/subtraction with overflow. 167 setOperationAction(ISD::SADDO, VT, Custom); 168 setOperationAction(ISD::SSUBO, VT, Custom); 169 170 // Support addition/subtraction with carry. 171 setOperationAction(ISD::UADDO, VT, Custom); 172 setOperationAction(ISD::USUBO, VT, Custom); 173 174 // Support carry in as value rather than glue. 175 setOperationAction(ISD::ADDCARRY, VT, Custom); 176 setOperationAction(ISD::SUBCARRY, VT, Custom); 177 178 // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and 179 // stores, putting a serialization instruction after the stores. 180 setOperationAction(ISD::ATOMIC_LOAD, VT, Custom); 181 setOperationAction(ISD::ATOMIC_STORE, VT, Custom); 182 183 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are 184 // available, or if the operand is constant. 185 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 186 187 // Use POPCNT on z196 and above. 188 if (Subtarget.hasPopulationCount()) 189 setOperationAction(ISD::CTPOP, VT, Custom); 190 else 191 setOperationAction(ISD::CTPOP, VT, Expand); 192 193 // No special instructions for these. 194 setOperationAction(ISD::CTTZ, VT, Expand); 195 setOperationAction(ISD::ROTR, VT, Expand); 196 197 // Use *MUL_LOHI where possible instead of MULH*. 198 setOperationAction(ISD::MULHS, VT, Expand); 199 setOperationAction(ISD::MULHU, VT, Expand); 200 setOperationAction(ISD::SMUL_LOHI, VT, Custom); 201 setOperationAction(ISD::UMUL_LOHI, VT, Custom); 202 203 // Only z196 and above have native support for conversions to unsigned. 204 // On z10, promoting to i64 doesn't generate an inexact condition for 205 // values that are outside the i32 range but in the i64 range, so use 206 // the default expansion. 207 if (!Subtarget.hasFPExtension()) 208 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 209 } 210 } 211 212 // Type legalization will convert 8- and 16-bit atomic operations into 213 // forms that operate on i32s (but still keeping the original memory VT). 214 // Lower them into full i32 operations. 215 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Custom); 216 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Custom); 217 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); 218 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); 219 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Custom); 220 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Custom); 221 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom); 222 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Custom); 223 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Custom); 224 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom); 225 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom); 226 227 // Even though i128 is not a legal type, we still need to custom lower 228 // the atomic operations in order to exploit SystemZ instructions. 229 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom); 230 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom); 231 232 // We can use the CC result of compare-and-swap to implement 233 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS. 234 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Custom); 235 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Custom); 236 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom); 237 238 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 239 240 // Traps are legal, as we will convert them to "j .+2". 241 setOperationAction(ISD::TRAP, MVT::Other, Legal); 242 243 // z10 has instructions for signed but not unsigned FP conversion. 244 // Handle unsigned 32-bit types as signed 64-bit types. 245 if (!Subtarget.hasFPExtension()) { 246 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote); 247 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 248 } 249 250 // We have native support for a 64-bit CTLZ, via FLOGR. 251 setOperationAction(ISD::CTLZ, MVT::i32, Promote); 252 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Promote); 253 setOperationAction(ISD::CTLZ, MVT::i64, Legal); 254 255 // Give LowerOperation the chance to replace 64-bit ORs with subregs. 256 setOperationAction(ISD::OR, MVT::i64, Custom); 257 258 // FIXME: Can we support these natively? 259 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 260 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 261 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 262 263 // We have native instructions for i8, i16 and i32 extensions, but not i1. 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 265 for (MVT VT : MVT::integer_valuetypes()) { 266 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 267 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 268 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote); 269 } 270 271 // Handle the various types of symbolic address. 272 setOperationAction(ISD::ConstantPool, PtrVT, Custom); 273 setOperationAction(ISD::GlobalAddress, PtrVT, Custom); 274 setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom); 275 setOperationAction(ISD::BlockAddress, PtrVT, Custom); 276 setOperationAction(ISD::JumpTable, PtrVT, Custom); 277 278 // We need to handle dynamic allocations specially because of the 279 // 160-byte area at the bottom of the stack. 280 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom); 281 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, PtrVT, Custom); 282 283 // Use custom expanders so that we can force the function to use 284 // a frame pointer. 285 setOperationAction(ISD::STACKSAVE, MVT::Other, Custom); 286 setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom); 287 288 // Handle prefetches with PFD or PFDRL. 289 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 290 291 for (MVT VT : MVT::vector_valuetypes()) { 292 // Assume by default that all vector operations need to be expanded. 293 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode) 294 if (getOperationAction(Opcode, VT) == Legal) 295 setOperationAction(Opcode, VT, Expand); 296 297 // Likewise all truncating stores and extending loads. 298 for (MVT InnerVT : MVT::vector_valuetypes()) { 299 setTruncStoreAction(VT, InnerVT, Expand); 300 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 301 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 302 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 303 } 304 305 if (isTypeLegal(VT)) { 306 // These operations are legal for anything that can be stored in a 307 // vector register, even if there is no native support for the format 308 // as such. In particular, we can do these for v4f32 even though there 309 // are no specific instructions for that format. 310 setOperationAction(ISD::LOAD, VT, Legal); 311 setOperationAction(ISD::STORE, VT, Legal); 312 setOperationAction(ISD::VSELECT, VT, Legal); 313 setOperationAction(ISD::BITCAST, VT, Legal); 314 setOperationAction(ISD::UNDEF, VT, Legal); 315 316 // Likewise, except that we need to replace the nodes with something 317 // more specific. 318 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 319 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 320 } 321 } 322 323 // Handle integer vector types. 324 for (MVT VT : MVT::integer_vector_valuetypes()) { 325 if (isTypeLegal(VT)) { 326 // These operations have direct equivalents. 327 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal); 328 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal); 329 setOperationAction(ISD::ADD, VT, Legal); 330 setOperationAction(ISD::SUB, VT, Legal); 331 if (VT != MVT::v2i64) 332 setOperationAction(ISD::MUL, VT, Legal); 333 setOperationAction(ISD::AND, VT, Legal); 334 setOperationAction(ISD::OR, VT, Legal); 335 setOperationAction(ISD::XOR, VT, Legal); 336 if (Subtarget.hasVectorEnhancements1()) 337 setOperationAction(ISD::CTPOP, VT, Legal); 338 else 339 setOperationAction(ISD::CTPOP, VT, Custom); 340 setOperationAction(ISD::CTTZ, VT, Legal); 341 setOperationAction(ISD::CTLZ, VT, Legal); 342 343 // Convert a GPR scalar to a vector by inserting it into element 0. 344 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom); 345 346 // Use a series of unpacks for extensions. 347 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom); 348 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom); 349 350 // Detect shifts by a scalar amount and convert them into 351 // V*_BY_SCALAR. 352 setOperationAction(ISD::SHL, VT, Custom); 353 setOperationAction(ISD::SRA, VT, Custom); 354 setOperationAction(ISD::SRL, VT, Custom); 355 356 // At present ROTL isn't matched by DAGCombiner. ROTR should be 357 // converted into ROTL. 358 setOperationAction(ISD::ROTL, VT, Expand); 359 setOperationAction(ISD::ROTR, VT, Expand); 360 361 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands 362 // and inverting the result as necessary. 363 setOperationAction(ISD::SETCC, VT, Custom); 364 } 365 } 366 367 if (Subtarget.hasVector()) { 368 // There should be no need to check for float types other than v2f64 369 // since <2 x f32> isn't a legal type. 370 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 371 setOperationAction(ISD::FP_TO_SINT, MVT::v2f64, Legal); 372 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 373 setOperationAction(ISD::FP_TO_UINT, MVT::v2f64, Legal); 374 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 375 setOperationAction(ISD::SINT_TO_FP, MVT::v2f64, Legal); 376 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 377 setOperationAction(ISD::UINT_TO_FP, MVT::v2f64, Legal); 378 } 379 380 // Handle floating-point types. 381 for (unsigned I = MVT::FIRST_FP_VALUETYPE; 382 I <= MVT::LAST_FP_VALUETYPE; 383 ++I) { 384 MVT VT = MVT::SimpleValueType(I); 385 if (isTypeLegal(VT)) { 386 // We can use FI for FRINT. 387 setOperationAction(ISD::FRINT, VT, Legal); 388 389 // We can use the extended form of FI for other rounding operations. 390 if (Subtarget.hasFPExtension()) { 391 setOperationAction(ISD::FNEARBYINT, VT, Legal); 392 setOperationAction(ISD::FFLOOR, VT, Legal); 393 setOperationAction(ISD::FCEIL, VT, Legal); 394 setOperationAction(ISD::FTRUNC, VT, Legal); 395 setOperationAction(ISD::FROUND, VT, Legal); 396 } 397 398 // No special instructions for these. 399 setOperationAction(ISD::FSIN, VT, Expand); 400 setOperationAction(ISD::FCOS, VT, Expand); 401 setOperationAction(ISD::FSINCOS, VT, Expand); 402 setOperationAction(ISD::FREM, VT, Expand); 403 setOperationAction(ISD::FPOW, VT, Expand); 404 } 405 } 406 407 // Handle floating-point vector types. 408 if (Subtarget.hasVector()) { 409 // Scalar-to-vector conversion is just a subreg. 410 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 411 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 412 413 // Some insertions and extractions can be done directly but others 414 // need to go via integers. 415 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 416 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 417 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 418 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 419 420 // These operations have direct equivalents. 421 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 422 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 423 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 424 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 425 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 426 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 427 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 428 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 429 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 430 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 431 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 432 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 433 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 434 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 435 } 436 437 // The vector enhancements facility 1 has instructions for these. 438 if (Subtarget.hasVectorEnhancements1()) { 439 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 440 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 441 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 442 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 443 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 444 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 445 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 446 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 447 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 448 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 449 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 450 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 451 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 452 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 453 454 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 455 setOperationAction(ISD::FMAXIMUM, MVT::f64, Legal); 456 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 457 setOperationAction(ISD::FMINIMUM, MVT::f64, Legal); 458 459 setOperationAction(ISD::FMAXNUM, MVT::v2f64, Legal); 460 setOperationAction(ISD::FMAXIMUM, MVT::v2f64, Legal); 461 setOperationAction(ISD::FMINNUM, MVT::v2f64, Legal); 462 setOperationAction(ISD::FMINIMUM, MVT::v2f64, Legal); 463 464 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 465 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 466 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 467 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 468 469 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 470 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 471 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 472 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 473 474 setOperationAction(ISD::FMAXNUM, MVT::f128, Legal); 475 setOperationAction(ISD::FMAXIMUM, MVT::f128, Legal); 476 setOperationAction(ISD::FMINNUM, MVT::f128, Legal); 477 setOperationAction(ISD::FMINIMUM, MVT::f128, Legal); 478 } 479 480 // We have fused multiply-addition for f32 and f64 but not f128. 481 setOperationAction(ISD::FMA, MVT::f32, Legal); 482 setOperationAction(ISD::FMA, MVT::f64, Legal); 483 if (Subtarget.hasVectorEnhancements1()) 484 setOperationAction(ISD::FMA, MVT::f128, Legal); 485 else 486 setOperationAction(ISD::FMA, MVT::f128, Expand); 487 488 // We don't have a copysign instruction on vector registers. 489 if (Subtarget.hasVectorEnhancements1()) 490 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 491 492 // Needed so that we don't try to implement f128 constant loads using 493 // a load-and-extend of a f80 constant (in cases where the constant 494 // would fit in an f80). 495 for (MVT VT : MVT::fp_valuetypes()) 496 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 497 498 // We don't have extending load instruction on vector registers. 499 if (Subtarget.hasVectorEnhancements1()) { 500 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand); 501 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand); 502 } 503 504 // Floating-point truncation and stores need to be done separately. 505 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 506 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 507 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 508 509 // We have 64-bit FPR<->GPR moves, but need special handling for 510 // 32-bit forms. 511 if (!Subtarget.hasVector()) { 512 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 513 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 514 } 515 516 // VASTART and VACOPY need to deal with the SystemZ-specific varargs 517 // structure, but VAEND is a no-op. 518 setOperationAction(ISD::VASTART, MVT::Other, Custom); 519 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 520 setOperationAction(ISD::VAEND, MVT::Other, Expand); 521 522 // Codes for which we want to perform some z-specific combinations. 523 setTargetDAGCombine(ISD::ZERO_EXTEND); 524 setTargetDAGCombine(ISD::SIGN_EXTEND); 525 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 526 setTargetDAGCombine(ISD::LOAD); 527 setTargetDAGCombine(ISD::STORE); 528 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 529 setTargetDAGCombine(ISD::FP_ROUND); 530 setTargetDAGCombine(ISD::FP_EXTEND); 531 setTargetDAGCombine(ISD::BSWAP); 532 setTargetDAGCombine(ISD::SDIV); 533 setTargetDAGCombine(ISD::UDIV); 534 setTargetDAGCombine(ISD::SREM); 535 setTargetDAGCombine(ISD::UREM); 536 537 // Handle intrinsics. 538 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 539 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 540 541 // We want to use MVC in preference to even a single load/store pair. 542 MaxStoresPerMemcpy = 0; 543 MaxStoresPerMemcpyOptSize = 0; 544 545 // The main memset sequence is a byte store followed by an MVC. 546 // Two STC or MV..I stores win over that, but the kind of fused stores 547 // generated by target-independent code don't when the byte value is 548 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better 549 // than "STC;MVC". Handle the choice in target-specific code instead. 550 MaxStoresPerMemset = 0; 551 MaxStoresPerMemsetOptSize = 0; 552 } 553 554 EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL, 555 LLVMContext &, EVT VT) const { 556 if (!VT.isVector()) 557 return MVT::i32; 558 return VT.changeVectorElementTypeToInteger(); 559 } 560 561 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 562 VT = VT.getScalarType(); 563 564 if (!VT.isSimple()) 565 return false; 566 567 switch (VT.getSimpleVT().SimpleTy) { 568 case MVT::f32: 569 case MVT::f64: 570 return true; 571 case MVT::f128: 572 return Subtarget.hasVectorEnhancements1(); 573 default: 574 break; 575 } 576 577 return false; 578 } 579 580 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 581 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR. 582 return Imm.isZero() || Imm.isNegZero(); 583 } 584 585 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 586 // We can use CGFI or CLGFI. 587 return isInt<32>(Imm) || isUInt<32>(Imm); 588 } 589 590 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const { 591 // We can use ALGFI or SLGFI. 592 return isUInt<32>(Imm) || isUInt<32>(-Imm); 593 } 594 595 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 596 unsigned, 597 unsigned, 598 bool *Fast) const { 599 // Unaligned accesses should never be slower than the expanded version. 600 // We check specifically for aligned accesses in the few cases where 601 // they are required. 602 if (Fast) 603 *Fast = true; 604 return true; 605 } 606 607 // Information about the addressing mode for a memory access. 608 struct AddressingMode { 609 // True if a long displacement is supported. 610 bool LongDisplacement; 611 612 // True if use of index register is supported. 613 bool IndexReg; 614 615 AddressingMode(bool LongDispl, bool IdxReg) : 616 LongDisplacement(LongDispl), IndexReg(IdxReg) {} 617 }; 618 619 // Return the desired addressing mode for a Load which has only one use (in 620 // the same block) which is a Store. 621 static AddressingMode getLoadStoreAddrMode(bool HasVector, 622 Type *Ty) { 623 // With vector support a Load->Store combination may be combined to either 624 // an MVC or vector operations and it seems to work best to allow the 625 // vector addressing mode. 626 if (HasVector) 627 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/); 628 629 // Otherwise only the MVC case is special. 630 bool MVC = Ty->isIntegerTy(8); 631 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/); 632 } 633 634 // Return the addressing mode which seems most desirable given an LLVM 635 // Instruction pointer. 636 static AddressingMode 637 supportedAddressingMode(Instruction *I, bool HasVector) { 638 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 639 switch (II->getIntrinsicID()) { 640 default: break; 641 case Intrinsic::memset: 642 case Intrinsic::memmove: 643 case Intrinsic::memcpy: 644 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/); 645 } 646 } 647 648 if (isa<LoadInst>(I) && I->hasOneUse()) { 649 auto *SingleUser = dyn_cast<Instruction>(*I->user_begin()); 650 if (SingleUser->getParent() == I->getParent()) { 651 if (isa<ICmpInst>(SingleUser)) { 652 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1))) 653 if (C->getBitWidth() <= 64 && 654 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue()))) 655 // Comparison of memory with 16 bit signed / unsigned immediate 656 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/); 657 } else if (isa<StoreInst>(SingleUser)) 658 // Load->Store 659 return getLoadStoreAddrMode(HasVector, I->getType()); 660 } 661 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) { 662 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand())) 663 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent()) 664 // Load->Store 665 return getLoadStoreAddrMode(HasVector, LoadI->getType()); 666 } 667 668 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) { 669 670 // * Use LDE instead of LE/LEY for z13 to avoid partial register 671 // dependencies (LDE only supports small offsets). 672 // * Utilize the vector registers to hold floating point 673 // values (vector load / store instructions only support small 674 // offsets). 675 676 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() : 677 I->getOperand(0)->getType()); 678 bool IsFPAccess = MemAccessTy->isFloatingPointTy(); 679 bool IsVectorAccess = MemAccessTy->isVectorTy(); 680 681 // A store of an extracted vector element will be combined into a VSTE type 682 // instruction. 683 if (!IsVectorAccess && isa<StoreInst>(I)) { 684 Value *DataOp = I->getOperand(0); 685 if (isa<ExtractElementInst>(DataOp)) 686 IsVectorAccess = true; 687 } 688 689 // A load which gets inserted into a vector element will be combined into a 690 // VLE type instruction. 691 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) { 692 User *LoadUser = *I->user_begin(); 693 if (isa<InsertElementInst>(LoadUser)) 694 IsVectorAccess = true; 695 } 696 697 if (IsFPAccess || IsVectorAccess) 698 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/); 699 } 700 701 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/); 702 } 703 704 bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL, 705 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const { 706 // Punt on globals for now, although they can be used in limited 707 // RELATIVE LONG cases. 708 if (AM.BaseGV) 709 return false; 710 711 // Require a 20-bit signed offset. 712 if (!isInt<20>(AM.BaseOffs)) 713 return false; 714 715 AddressingMode SupportedAM(true, true); 716 if (I != nullptr) 717 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector()); 718 719 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs)) 720 return false; 721 722 if (!SupportedAM.IndexReg) 723 // No indexing allowed. 724 return AM.Scale == 0; 725 else 726 // Indexing is OK but no scale factor can be applied. 727 return AM.Scale == 0 || AM.Scale == 1; 728 } 729 730 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const { 731 if (!FromType->isIntegerTy() || !ToType->isIntegerTy()) 732 return false; 733 unsigned FromBits = FromType->getPrimitiveSizeInBits(); 734 unsigned ToBits = ToType->getPrimitiveSizeInBits(); 735 return FromBits > ToBits; 736 } 737 738 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const { 739 if (!FromVT.isInteger() || !ToVT.isInteger()) 740 return false; 741 unsigned FromBits = FromVT.getSizeInBits(); 742 unsigned ToBits = ToVT.getSizeInBits(); 743 return FromBits > ToBits; 744 } 745 746 //===----------------------------------------------------------------------===// 747 // Inline asm support 748 //===----------------------------------------------------------------------===// 749 750 TargetLowering::ConstraintType 751 SystemZTargetLowering::getConstraintType(StringRef Constraint) const { 752 if (Constraint.size() == 1) { 753 switch (Constraint[0]) { 754 case 'a': // Address register 755 case 'd': // Data register (equivalent to 'r') 756 case 'f': // Floating-point register 757 case 'h': // High-part register 758 case 'r': // General-purpose register 759 case 'v': // Vector register 760 return C_RegisterClass; 761 762 case 'Q': // Memory with base and unsigned 12-bit displacement 763 case 'R': // Likewise, plus an index 764 case 'S': // Memory with base and signed 20-bit displacement 765 case 'T': // Likewise, plus an index 766 case 'm': // Equivalent to 'T'. 767 return C_Memory; 768 769 case 'I': // Unsigned 8-bit constant 770 case 'J': // Unsigned 12-bit constant 771 case 'K': // Signed 16-bit constant 772 case 'L': // Signed 20-bit displacement (on all targets we support) 773 case 'M': // 0x7fffffff 774 return C_Other; 775 776 default: 777 break; 778 } 779 } 780 return TargetLowering::getConstraintType(Constraint); 781 } 782 783 TargetLowering::ConstraintWeight SystemZTargetLowering:: 784 getSingleConstraintMatchWeight(AsmOperandInfo &info, 785 const char *constraint) const { 786 ConstraintWeight weight = CW_Invalid; 787 Value *CallOperandVal = info.CallOperandVal; 788 // If we don't have a value, we can't do a match, 789 // but allow it at the lowest weight. 790 if (!CallOperandVal) 791 return CW_Default; 792 Type *type = CallOperandVal->getType(); 793 // Look at the constraint type. 794 switch (*constraint) { 795 default: 796 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 797 break; 798 799 case 'a': // Address register 800 case 'd': // Data register (equivalent to 'r') 801 case 'h': // High-part register 802 case 'r': // General-purpose register 803 if (CallOperandVal->getType()->isIntegerTy()) 804 weight = CW_Register; 805 break; 806 807 case 'f': // Floating-point register 808 if (type->isFloatingPointTy()) 809 weight = CW_Register; 810 break; 811 812 case 'v': // Vector register 813 if ((type->isVectorTy() || type->isFloatingPointTy()) && 814 Subtarget.hasVector()) 815 weight = CW_Register; 816 break; 817 818 case 'I': // Unsigned 8-bit constant 819 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) 820 if (isUInt<8>(C->getZExtValue())) 821 weight = CW_Constant; 822 break; 823 824 case 'J': // Unsigned 12-bit constant 825 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) 826 if (isUInt<12>(C->getZExtValue())) 827 weight = CW_Constant; 828 break; 829 830 case 'K': // Signed 16-bit constant 831 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) 832 if (isInt<16>(C->getSExtValue())) 833 weight = CW_Constant; 834 break; 835 836 case 'L': // Signed 20-bit displacement (on all targets we support) 837 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) 838 if (isInt<20>(C->getSExtValue())) 839 weight = CW_Constant; 840 break; 841 842 case 'M': // 0x7fffffff 843 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) 844 if (C->getZExtValue() == 0x7fffffff) 845 weight = CW_Constant; 846 break; 847 } 848 return weight; 849 } 850 851 // Parse a "{tNNN}" register constraint for which the register type "t" 852 // has already been verified. MC is the class associated with "t" and 853 // Map maps 0-based register numbers to LLVM register numbers. 854 static std::pair<unsigned, const TargetRegisterClass *> 855 parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC, 856 const unsigned *Map, unsigned Size) { 857 assert(*(Constraint.end()-1) == '}' && "Missing '}'"); 858 if (isdigit(Constraint[2])) { 859 unsigned Index; 860 bool Failed = 861 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index); 862 if (!Failed && Index < Size && Map[Index]) 863 return std::make_pair(Map[Index], RC); 864 } 865 return std::make_pair(0U, nullptr); 866 } 867 868 std::pair<unsigned, const TargetRegisterClass *> 869 SystemZTargetLowering::getRegForInlineAsmConstraint( 870 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 871 if (Constraint.size() == 1) { 872 // GCC Constraint Letters 873 switch (Constraint[0]) { 874 default: break; 875 case 'd': // Data register (equivalent to 'r') 876 case 'r': // General-purpose register 877 if (VT == MVT::i64) 878 return std::make_pair(0U, &SystemZ::GR64BitRegClass); 879 else if (VT == MVT::i128) 880 return std::make_pair(0U, &SystemZ::GR128BitRegClass); 881 return std::make_pair(0U, &SystemZ::GR32BitRegClass); 882 883 case 'a': // Address register 884 if (VT == MVT::i64) 885 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass); 886 else if (VT == MVT::i128) 887 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass); 888 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass); 889 890 case 'h': // High-part register (an LLVM extension) 891 return std::make_pair(0U, &SystemZ::GRH32BitRegClass); 892 893 case 'f': // Floating-point register 894 if (VT == MVT::f64) 895 return std::make_pair(0U, &SystemZ::FP64BitRegClass); 896 else if (VT == MVT::f128) 897 return std::make_pair(0U, &SystemZ::FP128BitRegClass); 898 return std::make_pair(0U, &SystemZ::FP32BitRegClass); 899 900 case 'v': // Vector register 901 if (Subtarget.hasVector()) { 902 if (VT == MVT::f32) 903 return std::make_pair(0U, &SystemZ::VR32BitRegClass); 904 if (VT == MVT::f64) 905 return std::make_pair(0U, &SystemZ::VR64BitRegClass); 906 return std::make_pair(0U, &SystemZ::VR128BitRegClass); 907 } 908 break; 909 } 910 } 911 if (Constraint.size() > 0 && Constraint[0] == '{') { 912 // We need to override the default register parsing for GPRs and FPRs 913 // because the interpretation depends on VT. The internal names of 914 // the registers are also different from the external names 915 // (F0D and F0S instead of F0, etc.). 916 if (Constraint[1] == 'r') { 917 if (VT == MVT::i32) 918 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass, 919 SystemZMC::GR32Regs, 16); 920 if (VT == MVT::i128) 921 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass, 922 SystemZMC::GR128Regs, 16); 923 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass, 924 SystemZMC::GR64Regs, 16); 925 } 926 if (Constraint[1] == 'f') { 927 if (VT == MVT::f32) 928 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass, 929 SystemZMC::FP32Regs, 16); 930 if (VT == MVT::f128) 931 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass, 932 SystemZMC::FP128Regs, 16); 933 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass, 934 SystemZMC::FP64Regs, 16); 935 } 936 if (Constraint[1] == 'v') { 937 if (VT == MVT::f32) 938 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass, 939 SystemZMC::VR32Regs, 32); 940 if (VT == MVT::f64) 941 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass, 942 SystemZMC::VR64Regs, 32); 943 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass, 944 SystemZMC::VR128Regs, 32); 945 } 946 } 947 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 948 } 949 950 void SystemZTargetLowering:: 951 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint, 952 std::vector<SDValue> &Ops, 953 SelectionDAG &DAG) const { 954 // Only support length 1 constraints for now. 955 if (Constraint.length() == 1) { 956 switch (Constraint[0]) { 957 case 'I': // Unsigned 8-bit constant 958 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 959 if (isUInt<8>(C->getZExtValue())) 960 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op), 961 Op.getValueType())); 962 return; 963 964 case 'J': // Unsigned 12-bit constant 965 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 966 if (isUInt<12>(C->getZExtValue())) 967 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op), 968 Op.getValueType())); 969 return; 970 971 case 'K': // Signed 16-bit constant 972 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 973 if (isInt<16>(C->getSExtValue())) 974 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), 975 Op.getValueType())); 976 return; 977 978 case 'L': // Signed 20-bit displacement (on all targets we support) 979 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 980 if (isInt<20>(C->getSExtValue())) 981 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), 982 Op.getValueType())); 983 return; 984 985 case 'M': // 0x7fffffff 986 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 987 if (C->getZExtValue() == 0x7fffffff) 988 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op), 989 Op.getValueType())); 990 return; 991 } 992 } 993 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 994 } 995 996 //===----------------------------------------------------------------------===// 997 // Calling conventions 998 //===----------------------------------------------------------------------===// 999 1000 #include "SystemZGenCallingConv.inc" 1001 1002 const MCPhysReg *SystemZTargetLowering::getScratchRegisters( 1003 CallingConv::ID) const { 1004 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D, 1005 SystemZ::R14D, 0 }; 1006 return ScratchRegs; 1007 } 1008 1009 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType, 1010 Type *ToType) const { 1011 return isTruncateFree(FromType, ToType); 1012 } 1013 1014 bool SystemZTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 1015 return CI->isTailCall(); 1016 } 1017 1018 // We do not yet support 128-bit single-element vector types. If the user 1019 // attempts to use such types as function argument or return type, prefer 1020 // to error out instead of emitting code violating the ABI. 1021 static void VerifyVectorType(MVT VT, EVT ArgVT) { 1022 if (ArgVT.isVector() && !VT.isVector()) 1023 report_fatal_error("Unsupported vector argument or return type"); 1024 } 1025 1026 static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) { 1027 for (unsigned i = 0; i < Ins.size(); ++i) 1028 VerifyVectorType(Ins[i].VT, Ins[i].ArgVT); 1029 } 1030 1031 static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) { 1032 for (unsigned i = 0; i < Outs.size(); ++i) 1033 VerifyVectorType(Outs[i].VT, Outs[i].ArgVT); 1034 } 1035 1036 // Value is a value that has been passed to us in the location described by VA 1037 // (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining 1038 // any loads onto Chain. 1039 static SDValue convertLocVTToValVT(SelectionDAG &DAG, const SDLoc &DL, 1040 CCValAssign &VA, SDValue Chain, 1041 SDValue Value) { 1042 // If the argument has been promoted from a smaller type, insert an 1043 // assertion to capture this. 1044 if (VA.getLocInfo() == CCValAssign::SExt) 1045 Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value, 1046 DAG.getValueType(VA.getValVT())); 1047 else if (VA.getLocInfo() == CCValAssign::ZExt) 1048 Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value, 1049 DAG.getValueType(VA.getValVT())); 1050 1051 if (VA.isExtInLoc()) 1052 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value); 1053 else if (VA.getLocInfo() == CCValAssign::BCvt) { 1054 // If this is a short vector argument loaded from the stack, 1055 // extend from i64 to full vector size and then bitcast. 1056 assert(VA.getLocVT() == MVT::i64); 1057 assert(VA.getValVT().isVector()); 1058 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)}); 1059 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value); 1060 } else 1061 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo"); 1062 return Value; 1063 } 1064 1065 // Value is a value of type VA.getValVT() that we need to copy into 1066 // the location described by VA. Return a copy of Value converted to 1067 // VA.getValVT(). The caller is responsible for handling indirect values. 1068 static SDValue convertValVTToLocVT(SelectionDAG &DAG, const SDLoc &DL, 1069 CCValAssign &VA, SDValue Value) { 1070 switch (VA.getLocInfo()) { 1071 case CCValAssign::SExt: 1072 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value); 1073 case CCValAssign::ZExt: 1074 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value); 1075 case CCValAssign::AExt: 1076 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value); 1077 case CCValAssign::BCvt: 1078 // If this is a short vector argument to be stored to the stack, 1079 // bitcast to v2i64 and then extract first element. 1080 assert(VA.getLocVT() == MVT::i64); 1081 assert(VA.getValVT().isVector()); 1082 Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value); 1083 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value, 1084 DAG.getConstant(0, DL, MVT::i32)); 1085 case CCValAssign::Full: 1086 return Value; 1087 default: 1088 llvm_unreachable("Unhandled getLocInfo()"); 1089 } 1090 } 1091 1092 SDValue SystemZTargetLowering::LowerFormalArguments( 1093 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 1094 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1095 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1096 MachineFunction &MF = DAG.getMachineFunction(); 1097 MachineFrameInfo &MFI = MF.getFrameInfo(); 1098 MachineRegisterInfo &MRI = MF.getRegInfo(); 1099 SystemZMachineFunctionInfo *FuncInfo = 1100 MF.getInfo<SystemZMachineFunctionInfo>(); 1101 auto *TFL = 1102 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering()); 1103 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 1104 1105 // Detect unsupported vector argument types. 1106 if (Subtarget.hasVector()) 1107 VerifyVectorTypes(Ins); 1108 1109 // Assign locations to all of the incoming arguments. 1110 SmallVector<CCValAssign, 16> ArgLocs; 1111 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 1112 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ); 1113 1114 unsigned NumFixedGPRs = 0; 1115 unsigned NumFixedFPRs = 0; 1116 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 1117 SDValue ArgValue; 1118 CCValAssign &VA = ArgLocs[I]; 1119 EVT LocVT = VA.getLocVT(); 1120 if (VA.isRegLoc()) { 1121 // Arguments passed in registers 1122 const TargetRegisterClass *RC; 1123 switch (LocVT.getSimpleVT().SimpleTy) { 1124 default: 1125 // Integers smaller than i64 should be promoted to i64. 1126 llvm_unreachable("Unexpected argument type"); 1127 case MVT::i32: 1128 NumFixedGPRs += 1; 1129 RC = &SystemZ::GR32BitRegClass; 1130 break; 1131 case MVT::i64: 1132 NumFixedGPRs += 1; 1133 RC = &SystemZ::GR64BitRegClass; 1134 break; 1135 case MVT::f32: 1136 NumFixedFPRs += 1; 1137 RC = &SystemZ::FP32BitRegClass; 1138 break; 1139 case MVT::f64: 1140 NumFixedFPRs += 1; 1141 RC = &SystemZ::FP64BitRegClass; 1142 break; 1143 case MVT::v16i8: 1144 case MVT::v8i16: 1145 case MVT::v4i32: 1146 case MVT::v2i64: 1147 case MVT::v4f32: 1148 case MVT::v2f64: 1149 RC = &SystemZ::VR128BitRegClass; 1150 break; 1151 } 1152 1153 unsigned VReg = MRI.createVirtualRegister(RC); 1154 MRI.addLiveIn(VA.getLocReg(), VReg); 1155 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 1156 } else { 1157 assert(VA.isMemLoc() && "Argument not register or memory"); 1158 1159 // Create the frame index object for this incoming parameter. 1160 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, 1161 VA.getLocMemOffset(), true); 1162 1163 // Create the SelectionDAG nodes corresponding to a load 1164 // from this parameter. Unpromoted ints and floats are 1165 // passed as right-justified 8-byte values. 1166 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 1167 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32) 1168 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 1169 DAG.getIntPtrConstant(4, DL)); 1170 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN, 1171 MachinePointerInfo::getFixedStack(MF, FI)); 1172 } 1173 1174 // Convert the value of the argument register into the value that's 1175 // being passed. 1176 if (VA.getLocInfo() == CCValAssign::Indirect) { 1177 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 1178 MachinePointerInfo())); 1179 // If the original argument was split (e.g. i128), we need 1180 // to load all parts of it here (using the same address). 1181 unsigned ArgIndex = Ins[I].OrigArgIndex; 1182 assert (Ins[I].PartOffset == 0); 1183 while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) { 1184 CCValAssign &PartVA = ArgLocs[I + 1]; 1185 unsigned PartOffset = Ins[I + 1].PartOffset; 1186 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, 1187 DAG.getIntPtrConstant(PartOffset, DL)); 1188 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 1189 MachinePointerInfo())); 1190 ++I; 1191 } 1192 } else 1193 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue)); 1194 } 1195 1196 if (IsVarArg) { 1197 // Save the number of non-varargs registers for later use by va_start, etc. 1198 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs); 1199 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs); 1200 1201 // Likewise the address (in the form of a frame index) of where the 1202 // first stack vararg would be. The 1-byte size here is arbitrary. 1203 int64_t StackSize = CCInfo.getNextStackOffset(); 1204 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true)); 1205 1206 // ...and a similar frame index for the caller-allocated save area 1207 // that will be used to store the incoming registers. 1208 int64_t RegSaveOffset = TFL->getOffsetOfLocalArea(); 1209 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true); 1210 FuncInfo->setRegSaveFrameIndex(RegSaveIndex); 1211 1212 // Store the FPR varargs in the reserved frame slots. (We store the 1213 // GPRs as part of the prologue.) 1214 if (NumFixedFPRs < SystemZ::NumArgFPRs) { 1215 SDValue MemOps[SystemZ::NumArgFPRs]; 1216 for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) { 1217 unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]); 1218 int FI = MFI.CreateFixedObject(8, RegSaveOffset + Offset, true); 1219 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 1220 unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I], 1221 &SystemZ::FP64BitRegClass); 1222 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64); 1223 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN, 1224 MachinePointerInfo::getFixedStack(MF, FI)); 1225 } 1226 // Join the stores, which are independent of one another. 1227 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 1228 makeArrayRef(&MemOps[NumFixedFPRs], 1229 SystemZ::NumArgFPRs-NumFixedFPRs)); 1230 } 1231 } 1232 1233 return Chain; 1234 } 1235 1236 static bool canUseSiblingCall(const CCState &ArgCCInfo, 1237 SmallVectorImpl<CCValAssign> &ArgLocs, 1238 SmallVectorImpl<ISD::OutputArg> &Outs) { 1239 // Punt if there are any indirect or stack arguments, or if the call 1240 // needs the callee-saved argument register R6, or if the call uses 1241 // the callee-saved register arguments SwiftSelf and SwiftError. 1242 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 1243 CCValAssign &VA = ArgLocs[I]; 1244 if (VA.getLocInfo() == CCValAssign::Indirect) 1245 return false; 1246 if (!VA.isRegLoc()) 1247 return false; 1248 unsigned Reg = VA.getLocReg(); 1249 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D) 1250 return false; 1251 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError()) 1252 return false; 1253 } 1254 return true; 1255 } 1256 1257 SDValue 1258 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI, 1259 SmallVectorImpl<SDValue> &InVals) const { 1260 SelectionDAG &DAG = CLI.DAG; 1261 SDLoc &DL = CLI.DL; 1262 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1263 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1264 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1265 SDValue Chain = CLI.Chain; 1266 SDValue Callee = CLI.Callee; 1267 bool &IsTailCall = CLI.IsTailCall; 1268 CallingConv::ID CallConv = CLI.CallConv; 1269 bool IsVarArg = CLI.IsVarArg; 1270 MachineFunction &MF = DAG.getMachineFunction(); 1271 EVT PtrVT = getPointerTy(MF.getDataLayout()); 1272 1273 // Detect unsupported vector argument and return types. 1274 if (Subtarget.hasVector()) { 1275 VerifyVectorTypes(Outs); 1276 VerifyVectorTypes(Ins); 1277 } 1278 1279 // Analyze the operands of the call, assigning locations to each operand. 1280 SmallVector<CCValAssign, 16> ArgLocs; 1281 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 1282 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ); 1283 1284 // We don't support GuaranteedTailCallOpt, only automatically-detected 1285 // sibling calls. 1286 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs)) 1287 IsTailCall = false; 1288 1289 // Get a count of how many bytes are to be pushed on the stack. 1290 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 1291 1292 // Mark the start of the call. 1293 if (!IsTailCall) 1294 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 1295 1296 // Copy argument values to their designated locations. 1297 SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass; 1298 SmallVector<SDValue, 8> MemOpChains; 1299 SDValue StackPtr; 1300 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 1301 CCValAssign &VA = ArgLocs[I]; 1302 SDValue ArgValue = OutVals[I]; 1303 1304 if (VA.getLocInfo() == CCValAssign::Indirect) { 1305 // Store the argument in a stack slot and pass its address. 1306 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[I].ArgVT); 1307 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 1308 MemOpChains.push_back( 1309 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 1310 MachinePointerInfo::getFixedStack(MF, FI))); 1311 // If the original argument was split (e.g. i128), we need 1312 // to store all parts of it here (and pass just one address). 1313 unsigned ArgIndex = Outs[I].OrigArgIndex; 1314 assert (Outs[I].PartOffset == 0); 1315 while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) { 1316 SDValue PartValue = OutVals[I + 1]; 1317 unsigned PartOffset = Outs[I + 1].PartOffset; 1318 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, 1319 DAG.getIntPtrConstant(PartOffset, DL)); 1320 MemOpChains.push_back( 1321 DAG.getStore(Chain, DL, PartValue, Address, 1322 MachinePointerInfo::getFixedStack(MF, FI))); 1323 ++I; 1324 } 1325 ArgValue = SpillSlot; 1326 } else 1327 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue); 1328 1329 if (VA.isRegLoc()) 1330 // Queue up the argument copies and emit them at the end. 1331 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 1332 else { 1333 assert(VA.isMemLoc() && "Argument not register or memory"); 1334 1335 // Work out the address of the stack slot. Unpromoted ints and 1336 // floats are passed as right-justified 8-byte values. 1337 if (!StackPtr.getNode()) 1338 StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT); 1339 unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset(); 1340 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32) 1341 Offset += 4; 1342 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 1343 DAG.getIntPtrConstant(Offset, DL)); 1344 1345 // Emit the store. 1346 MemOpChains.push_back( 1347 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 1348 } 1349 } 1350 1351 // Join the stores, which are independent of one another. 1352 if (!MemOpChains.empty()) 1353 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 1354 1355 // Accept direct calls by converting symbolic call addresses to the 1356 // associated Target* opcodes. Force %r1 to be used for indirect 1357 // tail calls. 1358 SDValue Glue; 1359 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1360 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT); 1361 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee); 1362 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1363 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT); 1364 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee); 1365 } else if (IsTailCall) { 1366 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue); 1367 Glue = Chain.getValue(1); 1368 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType()); 1369 } 1370 1371 // Build a sequence of copy-to-reg nodes, chained and glued together. 1372 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) { 1373 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first, 1374 RegsToPass[I].second, Glue); 1375 Glue = Chain.getValue(1); 1376 } 1377 1378 // The first call operand is the chain and the second is the target address. 1379 SmallVector<SDValue, 8> Ops; 1380 Ops.push_back(Chain); 1381 Ops.push_back(Callee); 1382 1383 // Add argument registers to the end of the list so that they are 1384 // known live into the call. 1385 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) 1386 Ops.push_back(DAG.getRegister(RegsToPass[I].first, 1387 RegsToPass[I].second.getValueType())); 1388 1389 // Add a register mask operand representing the call-preserved registers. 1390 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 1391 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 1392 assert(Mask && "Missing call preserved mask for calling convention"); 1393 Ops.push_back(DAG.getRegisterMask(Mask)); 1394 1395 // Glue the call to the argument copies, if any. 1396 if (Glue.getNode()) 1397 Ops.push_back(Glue); 1398 1399 // Emit the call. 1400 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1401 if (IsTailCall) 1402 return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops); 1403 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops); 1404 Glue = Chain.getValue(1); 1405 1406 // Mark the end of the call, which is glued to the call itself. 1407 Chain = DAG.getCALLSEQ_END(Chain, 1408 DAG.getConstant(NumBytes, DL, PtrVT, true), 1409 DAG.getConstant(0, DL, PtrVT, true), 1410 Glue, DL); 1411 Glue = Chain.getValue(1); 1412 1413 // Assign locations to each value returned by this call. 1414 SmallVector<CCValAssign, 16> RetLocs; 1415 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext()); 1416 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ); 1417 1418 // Copy all of the result registers out of their specified physreg. 1419 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) { 1420 CCValAssign &VA = RetLocs[I]; 1421 1422 // Copy the value out, gluing the copy to the end of the call sequence. 1423 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), 1424 VA.getLocVT(), Glue); 1425 Chain = RetValue.getValue(1); 1426 Glue = RetValue.getValue(2); 1427 1428 // Convert the value of the return register into the value that's 1429 // being returned. 1430 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue)); 1431 } 1432 1433 return Chain; 1434 } 1435 1436 bool SystemZTargetLowering:: 1437 CanLowerReturn(CallingConv::ID CallConv, 1438 MachineFunction &MF, bool isVarArg, 1439 const SmallVectorImpl<ISD::OutputArg> &Outs, 1440 LLVMContext &Context) const { 1441 // Detect unsupported vector return types. 1442 if (Subtarget.hasVector()) 1443 VerifyVectorTypes(Outs); 1444 1445 // Special case that we cannot easily detect in RetCC_SystemZ since 1446 // i128 is not a legal type. 1447 for (auto &Out : Outs) 1448 if (Out.ArgVT == MVT::i128) 1449 return false; 1450 1451 SmallVector<CCValAssign, 16> RetLocs; 1452 CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context); 1453 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ); 1454 } 1455 1456 SDValue 1457 SystemZTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1458 bool IsVarArg, 1459 const SmallVectorImpl<ISD::OutputArg> &Outs, 1460 const SmallVectorImpl<SDValue> &OutVals, 1461 const SDLoc &DL, SelectionDAG &DAG) const { 1462 MachineFunction &MF = DAG.getMachineFunction(); 1463 1464 // Detect unsupported vector return types. 1465 if (Subtarget.hasVector()) 1466 VerifyVectorTypes(Outs); 1467 1468 // Assign locations to each returned value. 1469 SmallVector<CCValAssign, 16> RetLocs; 1470 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext()); 1471 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ); 1472 1473 // Quick exit for void returns 1474 if (RetLocs.empty()) 1475 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain); 1476 1477 // Copy the result values into the output registers. 1478 SDValue Glue; 1479 SmallVector<SDValue, 4> RetOps; 1480 RetOps.push_back(Chain); 1481 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) { 1482 CCValAssign &VA = RetLocs[I]; 1483 SDValue RetValue = OutVals[I]; 1484 1485 // Make the return register live on exit. 1486 assert(VA.isRegLoc() && "Can only return in registers!"); 1487 1488 // Promote the value as required. 1489 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue); 1490 1491 // Chain and glue the copies together. 1492 unsigned Reg = VA.getLocReg(); 1493 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue); 1494 Glue = Chain.getValue(1); 1495 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT())); 1496 } 1497 1498 // Update chain and glue. 1499 RetOps[0] = Chain; 1500 if (Glue.getNode()) 1501 RetOps.push_back(Glue); 1502 1503 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps); 1504 } 1505 1506 // Return true if Op is an intrinsic node with chain that returns the CC value 1507 // as its only (other) argument. Provide the associated SystemZISD opcode and 1508 // the mask of valid CC values if so. 1509 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode, 1510 unsigned &CCValid) { 1511 unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 1512 switch (Id) { 1513 case Intrinsic::s390_tbegin: 1514 Opcode = SystemZISD::TBEGIN; 1515 CCValid = SystemZ::CCMASK_TBEGIN; 1516 return true; 1517 1518 case Intrinsic::s390_tbegin_nofloat: 1519 Opcode = SystemZISD::TBEGIN_NOFLOAT; 1520 CCValid = SystemZ::CCMASK_TBEGIN; 1521 return true; 1522 1523 case Intrinsic::s390_tend: 1524 Opcode = SystemZISD::TEND; 1525 CCValid = SystemZ::CCMASK_TEND; 1526 return true; 1527 1528 default: 1529 return false; 1530 } 1531 } 1532 1533 // Return true if Op is an intrinsic node without chain that returns the 1534 // CC value as its final argument. Provide the associated SystemZISD 1535 // opcode and the mask of valid CC values if so. 1536 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) { 1537 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1538 switch (Id) { 1539 case Intrinsic::s390_vpkshs: 1540 case Intrinsic::s390_vpksfs: 1541 case Intrinsic::s390_vpksgs: 1542 Opcode = SystemZISD::PACKS_CC; 1543 CCValid = SystemZ::CCMASK_VCMP; 1544 return true; 1545 1546 case Intrinsic::s390_vpklshs: 1547 case Intrinsic::s390_vpklsfs: 1548 case Intrinsic::s390_vpklsgs: 1549 Opcode = SystemZISD::PACKLS_CC; 1550 CCValid = SystemZ::CCMASK_VCMP; 1551 return true; 1552 1553 case Intrinsic::s390_vceqbs: 1554 case Intrinsic::s390_vceqhs: 1555 case Intrinsic::s390_vceqfs: 1556 case Intrinsic::s390_vceqgs: 1557 Opcode = SystemZISD::VICMPES; 1558 CCValid = SystemZ::CCMASK_VCMP; 1559 return true; 1560 1561 case Intrinsic::s390_vchbs: 1562 case Intrinsic::s390_vchhs: 1563 case Intrinsic::s390_vchfs: 1564 case Intrinsic::s390_vchgs: 1565 Opcode = SystemZISD::VICMPHS; 1566 CCValid = SystemZ::CCMASK_VCMP; 1567 return true; 1568 1569 case Intrinsic::s390_vchlbs: 1570 case Intrinsic::s390_vchlhs: 1571 case Intrinsic::s390_vchlfs: 1572 case Intrinsic::s390_vchlgs: 1573 Opcode = SystemZISD::VICMPHLS; 1574 CCValid = SystemZ::CCMASK_VCMP; 1575 return true; 1576 1577 case Intrinsic::s390_vtm: 1578 Opcode = SystemZISD::VTM; 1579 CCValid = SystemZ::CCMASK_VCMP; 1580 return true; 1581 1582 case Intrinsic::s390_vfaebs: 1583 case Intrinsic::s390_vfaehs: 1584 case Intrinsic::s390_vfaefs: 1585 Opcode = SystemZISD::VFAE_CC; 1586 CCValid = SystemZ::CCMASK_ANY; 1587 return true; 1588 1589 case Intrinsic::s390_vfaezbs: 1590 case Intrinsic::s390_vfaezhs: 1591 case Intrinsic::s390_vfaezfs: 1592 Opcode = SystemZISD::VFAEZ_CC; 1593 CCValid = SystemZ::CCMASK_ANY; 1594 return true; 1595 1596 case Intrinsic::s390_vfeebs: 1597 case Intrinsic::s390_vfeehs: 1598 case Intrinsic::s390_vfeefs: 1599 Opcode = SystemZISD::VFEE_CC; 1600 CCValid = SystemZ::CCMASK_ANY; 1601 return true; 1602 1603 case Intrinsic::s390_vfeezbs: 1604 case Intrinsic::s390_vfeezhs: 1605 case Intrinsic::s390_vfeezfs: 1606 Opcode = SystemZISD::VFEEZ_CC; 1607 CCValid = SystemZ::CCMASK_ANY; 1608 return true; 1609 1610 case Intrinsic::s390_vfenebs: 1611 case Intrinsic::s390_vfenehs: 1612 case Intrinsic::s390_vfenefs: 1613 Opcode = SystemZISD::VFENE_CC; 1614 CCValid = SystemZ::CCMASK_ANY; 1615 return true; 1616 1617 case Intrinsic::s390_vfenezbs: 1618 case Intrinsic::s390_vfenezhs: 1619 case Intrinsic::s390_vfenezfs: 1620 Opcode = SystemZISD::VFENEZ_CC; 1621 CCValid = SystemZ::CCMASK_ANY; 1622 return true; 1623 1624 case Intrinsic::s390_vistrbs: 1625 case Intrinsic::s390_vistrhs: 1626 case Intrinsic::s390_vistrfs: 1627 Opcode = SystemZISD::VISTR_CC; 1628 CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3; 1629 return true; 1630 1631 case Intrinsic::s390_vstrcbs: 1632 case Intrinsic::s390_vstrchs: 1633 case Intrinsic::s390_vstrcfs: 1634 Opcode = SystemZISD::VSTRC_CC; 1635 CCValid = SystemZ::CCMASK_ANY; 1636 return true; 1637 1638 case Intrinsic::s390_vstrczbs: 1639 case Intrinsic::s390_vstrczhs: 1640 case Intrinsic::s390_vstrczfs: 1641 Opcode = SystemZISD::VSTRCZ_CC; 1642 CCValid = SystemZ::CCMASK_ANY; 1643 return true; 1644 1645 case Intrinsic::s390_vfcedbs: 1646 case Intrinsic::s390_vfcesbs: 1647 Opcode = SystemZISD::VFCMPES; 1648 CCValid = SystemZ::CCMASK_VCMP; 1649 return true; 1650 1651 case Intrinsic::s390_vfchdbs: 1652 case Intrinsic::s390_vfchsbs: 1653 Opcode = SystemZISD::VFCMPHS; 1654 CCValid = SystemZ::CCMASK_VCMP; 1655 return true; 1656 1657 case Intrinsic::s390_vfchedbs: 1658 case Intrinsic::s390_vfchesbs: 1659 Opcode = SystemZISD::VFCMPHES; 1660 CCValid = SystemZ::CCMASK_VCMP; 1661 return true; 1662 1663 case Intrinsic::s390_vftcidb: 1664 case Intrinsic::s390_vftcisb: 1665 Opcode = SystemZISD::VFTCI; 1666 CCValid = SystemZ::CCMASK_VCMP; 1667 return true; 1668 1669 case Intrinsic::s390_tdc: 1670 Opcode = SystemZISD::TDC; 1671 CCValid = SystemZ::CCMASK_TDC; 1672 return true; 1673 1674 default: 1675 return false; 1676 } 1677 } 1678 1679 // Emit an intrinsic with chain and an explicit CC register result. 1680 static SDNode *emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op, 1681 unsigned Opcode) { 1682 // Copy all operands except the intrinsic ID. 1683 unsigned NumOps = Op.getNumOperands(); 1684 SmallVector<SDValue, 6> Ops; 1685 Ops.reserve(NumOps - 1); 1686 Ops.push_back(Op.getOperand(0)); 1687 for (unsigned I = 2; I < NumOps; ++I) 1688 Ops.push_back(Op.getOperand(I)); 1689 1690 assert(Op->getNumValues() == 2 && "Expected only CC result and chain"); 1691 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other); 1692 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops); 1693 SDValue OldChain = SDValue(Op.getNode(), 1); 1694 SDValue NewChain = SDValue(Intr.getNode(), 1); 1695 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain); 1696 return Intr.getNode(); 1697 } 1698 1699 // Emit an intrinsic with an explicit CC register result. 1700 static SDNode *emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op, 1701 unsigned Opcode) { 1702 // Copy all operands except the intrinsic ID. 1703 unsigned NumOps = Op.getNumOperands(); 1704 SmallVector<SDValue, 6> Ops; 1705 Ops.reserve(NumOps - 1); 1706 for (unsigned I = 1; I < NumOps; ++I) 1707 Ops.push_back(Op.getOperand(I)); 1708 1709 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), Op->getVTList(), Ops); 1710 return Intr.getNode(); 1711 } 1712 1713 // CC is a comparison that will be implemented using an integer or 1714 // floating-point comparison. Return the condition code mask for 1715 // a branch on true. In the integer case, CCMASK_CMP_UO is set for 1716 // unsigned comparisons and clear for signed ones. In the floating-point 1717 // case, CCMASK_CMP_UO has its normal mask meaning (unordered). 1718 static unsigned CCMaskForCondCode(ISD::CondCode CC) { 1719 #define CONV(X) \ 1720 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \ 1721 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \ 1722 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X 1723 1724 switch (CC) { 1725 default: 1726 llvm_unreachable("Invalid integer condition!"); 1727 1728 CONV(EQ); 1729 CONV(NE); 1730 CONV(GT); 1731 CONV(GE); 1732 CONV(LT); 1733 CONV(LE); 1734 1735 case ISD::SETO: return SystemZ::CCMASK_CMP_O; 1736 case ISD::SETUO: return SystemZ::CCMASK_CMP_UO; 1737 } 1738 #undef CONV 1739 } 1740 1741 // If C can be converted to a comparison against zero, adjust the operands 1742 // as necessary. 1743 static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) { 1744 if (C.ICmpType == SystemZICMP::UnsignedOnly) 1745 return; 1746 1747 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode()); 1748 if (!ConstOp1) 1749 return; 1750 1751 int64_t Value = ConstOp1->getSExtValue(); 1752 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) || 1753 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) || 1754 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) || 1755 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) { 1756 C.CCMask ^= SystemZ::CCMASK_CMP_EQ; 1757 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType()); 1758 } 1759 } 1760 1761 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI, 1762 // adjust the operands as necessary. 1763 static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL, 1764 Comparison &C) { 1765 // For us to make any changes, it must a comparison between a single-use 1766 // load and a constant. 1767 if (!C.Op0.hasOneUse() || 1768 C.Op0.getOpcode() != ISD::LOAD || 1769 C.Op1.getOpcode() != ISD::Constant) 1770 return; 1771 1772 // We must have an 8- or 16-bit load. 1773 auto *Load = cast<LoadSDNode>(C.Op0); 1774 unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits(); 1775 if (NumBits != 8 && NumBits != 16) 1776 return; 1777 1778 // The load must be an extending one and the constant must be within the 1779 // range of the unextended value. 1780 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1); 1781 uint64_t Value = ConstOp1->getZExtValue(); 1782 uint64_t Mask = (1 << NumBits) - 1; 1783 if (Load->getExtensionType() == ISD::SEXTLOAD) { 1784 // Make sure that ConstOp1 is in range of C.Op0. 1785 int64_t SignedValue = ConstOp1->getSExtValue(); 1786 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask) 1787 return; 1788 if (C.ICmpType != SystemZICMP::SignedOnly) { 1789 // Unsigned comparison between two sign-extended values is equivalent 1790 // to unsigned comparison between two zero-extended values. 1791 Value &= Mask; 1792 } else if (NumBits == 8) { 1793 // Try to treat the comparison as unsigned, so that we can use CLI. 1794 // Adjust CCMask and Value as necessary. 1795 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT) 1796 // Test whether the high bit of the byte is set. 1797 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT; 1798 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE) 1799 // Test whether the high bit of the byte is clear. 1800 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT; 1801 else 1802 // No instruction exists for this combination. 1803 return; 1804 C.ICmpType = SystemZICMP::UnsignedOnly; 1805 } 1806 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) { 1807 if (Value > Mask) 1808 return; 1809 // If the constant is in range, we can use any comparison. 1810 C.ICmpType = SystemZICMP::Any; 1811 } else 1812 return; 1813 1814 // Make sure that the first operand is an i32 of the right extension type. 1815 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ? 1816 ISD::SEXTLOAD : 1817 ISD::ZEXTLOAD); 1818 if (C.Op0.getValueType() != MVT::i32 || 1819 Load->getExtensionType() != ExtType) { 1820 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(), 1821 Load->getBasePtr(), Load->getPointerInfo(), 1822 Load->getMemoryVT(), Load->getAlignment(), 1823 Load->getMemOperand()->getFlags()); 1824 // Update the chain uses. 1825 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1)); 1826 } 1827 1828 // Make sure that the second operand is an i32 with the right value. 1829 if (C.Op1.getValueType() != MVT::i32 || 1830 Value != ConstOp1->getZExtValue()) 1831 C.Op1 = DAG.getConstant(Value, DL, MVT::i32); 1832 } 1833 1834 // Return true if Op is either an unextended load, or a load suitable 1835 // for integer register-memory comparisons of type ICmpType. 1836 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) { 1837 auto *Load = dyn_cast<LoadSDNode>(Op.getNode()); 1838 if (Load) { 1839 // There are no instructions to compare a register with a memory byte. 1840 if (Load->getMemoryVT() == MVT::i8) 1841 return false; 1842 // Otherwise decide on extension type. 1843 switch (Load->getExtensionType()) { 1844 case ISD::NON_EXTLOAD: 1845 return true; 1846 case ISD::SEXTLOAD: 1847 return ICmpType != SystemZICMP::UnsignedOnly; 1848 case ISD::ZEXTLOAD: 1849 return ICmpType != SystemZICMP::SignedOnly; 1850 default: 1851 break; 1852 } 1853 } 1854 return false; 1855 } 1856 1857 // Return true if it is better to swap the operands of C. 1858 static bool shouldSwapCmpOperands(const Comparison &C) { 1859 // Leave f128 comparisons alone, since they have no memory forms. 1860 if (C.Op0.getValueType() == MVT::f128) 1861 return false; 1862 1863 // Always keep a floating-point constant second, since comparisons with 1864 // zero can use LOAD TEST and comparisons with other constants make a 1865 // natural memory operand. 1866 if (isa<ConstantFPSDNode>(C.Op1)) 1867 return false; 1868 1869 // Never swap comparisons with zero since there are many ways to optimize 1870 // those later. 1871 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1); 1872 if (ConstOp1 && ConstOp1->getZExtValue() == 0) 1873 return false; 1874 1875 // Also keep natural memory operands second if the loaded value is 1876 // only used here. Several comparisons have memory forms. 1877 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse()) 1878 return false; 1879 1880 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't. 1881 // In that case we generally prefer the memory to be second. 1882 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) { 1883 // The only exceptions are when the second operand is a constant and 1884 // we can use things like CHHSI. 1885 if (!ConstOp1) 1886 return true; 1887 // The unsigned memory-immediate instructions can handle 16-bit 1888 // unsigned integers. 1889 if (C.ICmpType != SystemZICMP::SignedOnly && 1890 isUInt<16>(ConstOp1->getZExtValue())) 1891 return false; 1892 // The signed memory-immediate instructions can handle 16-bit 1893 // signed integers. 1894 if (C.ICmpType != SystemZICMP::UnsignedOnly && 1895 isInt<16>(ConstOp1->getSExtValue())) 1896 return false; 1897 return true; 1898 } 1899 1900 // Try to promote the use of CGFR and CLGFR. 1901 unsigned Opcode0 = C.Op0.getOpcode(); 1902 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND) 1903 return true; 1904 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND) 1905 return true; 1906 if (C.ICmpType != SystemZICMP::SignedOnly && 1907 Opcode0 == ISD::AND && 1908 C.Op0.getOperand(1).getOpcode() == ISD::Constant && 1909 cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff) 1910 return true; 1911 1912 return false; 1913 } 1914 1915 // Return a version of comparison CC mask CCMask in which the LT and GT 1916 // actions are swapped. 1917 static unsigned reverseCCMask(unsigned CCMask) { 1918 return ((CCMask & SystemZ::CCMASK_CMP_EQ) | 1919 (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) | 1920 (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) | 1921 (CCMask & SystemZ::CCMASK_CMP_UO)); 1922 } 1923 1924 // Check whether C tests for equality between X and Y and whether X - Y 1925 // or Y - X is also computed. In that case it's better to compare the 1926 // result of the subtraction against zero. 1927 static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL, 1928 Comparison &C) { 1929 if (C.CCMask == SystemZ::CCMASK_CMP_EQ || 1930 C.CCMask == SystemZ::CCMASK_CMP_NE) { 1931 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) { 1932 SDNode *N = *I; 1933 if (N->getOpcode() == ISD::SUB && 1934 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) || 1935 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) { 1936 C.Op0 = SDValue(N, 0); 1937 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0)); 1938 return; 1939 } 1940 } 1941 } 1942 } 1943 1944 // Check whether C compares a floating-point value with zero and if that 1945 // floating-point value is also negated. In this case we can use the 1946 // negation to set CC, so avoiding separate LOAD AND TEST and 1947 // LOAD (NEGATIVE/COMPLEMENT) instructions. 1948 static void adjustForFNeg(Comparison &C) { 1949 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1); 1950 if (C1 && C1->isZero()) { 1951 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) { 1952 SDNode *N = *I; 1953 if (N->getOpcode() == ISD::FNEG) { 1954 C.Op0 = SDValue(N, 0); 1955 C.CCMask = reverseCCMask(C.CCMask); 1956 return; 1957 } 1958 } 1959 } 1960 } 1961 1962 // Check whether C compares (shl X, 32) with 0 and whether X is 1963 // also sign-extended. In that case it is better to test the result 1964 // of the sign extension using LTGFR. 1965 // 1966 // This case is important because InstCombine transforms a comparison 1967 // with (sext (trunc X)) into a comparison with (shl X, 32). 1968 static void adjustForLTGFR(Comparison &C) { 1969 // Check for a comparison between (shl X, 32) and 0. 1970 if (C.Op0.getOpcode() == ISD::SHL && 1971 C.Op0.getValueType() == MVT::i64 && 1972 C.Op1.getOpcode() == ISD::Constant && 1973 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) { 1974 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1)); 1975 if (C1 && C1->getZExtValue() == 32) { 1976 SDValue ShlOp0 = C.Op0.getOperand(0); 1977 // See whether X has any SIGN_EXTEND_INREG uses. 1978 for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) { 1979 SDNode *N = *I; 1980 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG && 1981 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) { 1982 C.Op0 = SDValue(N, 0); 1983 return; 1984 } 1985 } 1986 } 1987 } 1988 } 1989 1990 // If C compares the truncation of an extending load, try to compare 1991 // the untruncated value instead. This exposes more opportunities to 1992 // reuse CC. 1993 static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL, 1994 Comparison &C) { 1995 if (C.Op0.getOpcode() == ISD::TRUNCATE && 1996 C.Op0.getOperand(0).getOpcode() == ISD::LOAD && 1997 C.Op1.getOpcode() == ISD::Constant && 1998 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) { 1999 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0)); 2000 if (L->getMemoryVT().getStoreSizeInBits() <= C.Op0.getValueSizeInBits()) { 2001 unsigned Type = L->getExtensionType(); 2002 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) || 2003 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) { 2004 C.Op0 = C.Op0.getOperand(0); 2005 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType()); 2006 } 2007 } 2008 } 2009 } 2010 2011 // Return true if shift operation N has an in-range constant shift value. 2012 // Store it in ShiftVal if so. 2013 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) { 2014 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2015 if (!Shift) 2016 return false; 2017 2018 uint64_t Amount = Shift->getZExtValue(); 2019 if (Amount >= N.getValueSizeInBits()) 2020 return false; 2021 2022 ShiftVal = Amount; 2023 return true; 2024 } 2025 2026 // Check whether an AND with Mask is suitable for a TEST UNDER MASK 2027 // instruction and whether the CC value is descriptive enough to handle 2028 // a comparison of type Opcode between the AND result and CmpVal. 2029 // CCMask says which comparison result is being tested and BitSize is 2030 // the number of bits in the operands. If TEST UNDER MASK can be used, 2031 // return the corresponding CC mask, otherwise return 0. 2032 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask, 2033 uint64_t Mask, uint64_t CmpVal, 2034 unsigned ICmpType) { 2035 assert(Mask != 0 && "ANDs with zero should have been removed by now"); 2036 2037 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL. 2038 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) && 2039 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask)) 2040 return 0; 2041 2042 // Work out the masks for the lowest and highest bits. 2043 unsigned HighShift = 63 - countLeadingZeros(Mask); 2044 uint64_t High = uint64_t(1) << HighShift; 2045 uint64_t Low = uint64_t(1) << countTrailingZeros(Mask); 2046 2047 // Signed ordered comparisons are effectively unsigned if the sign 2048 // bit is dropped. 2049 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly); 2050 2051 // Check for equality comparisons with 0, or the equivalent. 2052 if (CmpVal == 0) { 2053 if (CCMask == SystemZ::CCMASK_CMP_EQ) 2054 return SystemZ::CCMASK_TM_ALL_0; 2055 if (CCMask == SystemZ::CCMASK_CMP_NE) 2056 return SystemZ::CCMASK_TM_SOME_1; 2057 } 2058 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) { 2059 if (CCMask == SystemZ::CCMASK_CMP_LT) 2060 return SystemZ::CCMASK_TM_ALL_0; 2061 if (CCMask == SystemZ::CCMASK_CMP_GE) 2062 return SystemZ::CCMASK_TM_SOME_1; 2063 } 2064 if (EffectivelyUnsigned && CmpVal < Low) { 2065 if (CCMask == SystemZ::CCMASK_CMP_LE) 2066 return SystemZ::CCMASK_TM_ALL_0; 2067 if (CCMask == SystemZ::CCMASK_CMP_GT) 2068 return SystemZ::CCMASK_TM_SOME_1; 2069 } 2070 2071 // Check for equality comparisons with the mask, or the equivalent. 2072 if (CmpVal == Mask) { 2073 if (CCMask == SystemZ::CCMASK_CMP_EQ) 2074 return SystemZ::CCMASK_TM_ALL_1; 2075 if (CCMask == SystemZ::CCMASK_CMP_NE) 2076 return SystemZ::CCMASK_TM_SOME_0; 2077 } 2078 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) { 2079 if (CCMask == SystemZ::CCMASK_CMP_GT) 2080 return SystemZ::CCMASK_TM_ALL_1; 2081 if (CCMask == SystemZ::CCMASK_CMP_LE) 2082 return SystemZ::CCMASK_TM_SOME_0; 2083 } 2084 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) { 2085 if (CCMask == SystemZ::CCMASK_CMP_GE) 2086 return SystemZ::CCMASK_TM_ALL_1; 2087 if (CCMask == SystemZ::CCMASK_CMP_LT) 2088 return SystemZ::CCMASK_TM_SOME_0; 2089 } 2090 2091 // Check for ordered comparisons with the top bit. 2092 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) { 2093 if (CCMask == SystemZ::CCMASK_CMP_LE) 2094 return SystemZ::CCMASK_TM_MSB_0; 2095 if (CCMask == SystemZ::CCMASK_CMP_GT) 2096 return SystemZ::CCMASK_TM_MSB_1; 2097 } 2098 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) { 2099 if (CCMask == SystemZ::CCMASK_CMP_LT) 2100 return SystemZ::CCMASK_TM_MSB_0; 2101 if (CCMask == SystemZ::CCMASK_CMP_GE) 2102 return SystemZ::CCMASK_TM_MSB_1; 2103 } 2104 2105 // If there are just two bits, we can do equality checks for Low and High 2106 // as well. 2107 if (Mask == Low + High) { 2108 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low) 2109 return SystemZ::CCMASK_TM_MIXED_MSB_0; 2110 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low) 2111 return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY; 2112 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High) 2113 return SystemZ::CCMASK_TM_MIXED_MSB_1; 2114 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High) 2115 return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY; 2116 } 2117 2118 // Looks like we've exhausted our options. 2119 return 0; 2120 } 2121 2122 // See whether C can be implemented as a TEST UNDER MASK instruction. 2123 // Update the arguments with the TM version if so. 2124 static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL, 2125 Comparison &C) { 2126 // Check that we have a comparison with a constant. 2127 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1); 2128 if (!ConstOp1) 2129 return; 2130 uint64_t CmpVal = ConstOp1->getZExtValue(); 2131 2132 // Check whether the nonconstant input is an AND with a constant mask. 2133 Comparison NewC(C); 2134 uint64_t MaskVal; 2135 ConstantSDNode *Mask = nullptr; 2136 if (C.Op0.getOpcode() == ISD::AND) { 2137 NewC.Op0 = C.Op0.getOperand(0); 2138 NewC.Op1 = C.Op0.getOperand(1); 2139 Mask = dyn_cast<ConstantSDNode>(NewC.Op1); 2140 if (!Mask) 2141 return; 2142 MaskVal = Mask->getZExtValue(); 2143 } else { 2144 // There is no instruction to compare with a 64-bit immediate 2145 // so use TMHH instead if possible. We need an unsigned ordered 2146 // comparison with an i64 immediate. 2147 if (NewC.Op0.getValueType() != MVT::i64 || 2148 NewC.CCMask == SystemZ::CCMASK_CMP_EQ || 2149 NewC.CCMask == SystemZ::CCMASK_CMP_NE || 2150 NewC.ICmpType == SystemZICMP::SignedOnly) 2151 return; 2152 // Convert LE and GT comparisons into LT and GE. 2153 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE || 2154 NewC.CCMask == SystemZ::CCMASK_CMP_GT) { 2155 if (CmpVal == uint64_t(-1)) 2156 return; 2157 CmpVal += 1; 2158 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ; 2159 } 2160 // If the low N bits of Op1 are zero than the low N bits of Op0 can 2161 // be masked off without changing the result. 2162 MaskVal = -(CmpVal & -CmpVal); 2163 NewC.ICmpType = SystemZICMP::UnsignedOnly; 2164 } 2165 if (!MaskVal) 2166 return; 2167 2168 // Check whether the combination of mask, comparison value and comparison 2169 // type are suitable. 2170 unsigned BitSize = NewC.Op0.getValueSizeInBits(); 2171 unsigned NewCCMask, ShiftVal; 2172 if (NewC.ICmpType != SystemZICMP::SignedOnly && 2173 NewC.Op0.getOpcode() == ISD::SHL && 2174 isSimpleShift(NewC.Op0, ShiftVal) && 2175 (MaskVal >> ShiftVal != 0) && 2176 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal && 2177 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, 2178 MaskVal >> ShiftVal, 2179 CmpVal >> ShiftVal, 2180 SystemZICMP::Any))) { 2181 NewC.Op0 = NewC.Op0.getOperand(0); 2182 MaskVal >>= ShiftVal; 2183 } else if (NewC.ICmpType != SystemZICMP::SignedOnly && 2184 NewC.Op0.getOpcode() == ISD::SRL && 2185 isSimpleShift(NewC.Op0, ShiftVal) && 2186 (MaskVal << ShiftVal != 0) && 2187 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal && 2188 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, 2189 MaskVal << ShiftVal, 2190 CmpVal << ShiftVal, 2191 SystemZICMP::UnsignedOnly))) { 2192 NewC.Op0 = NewC.Op0.getOperand(0); 2193 MaskVal <<= ShiftVal; 2194 } else { 2195 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal, 2196 NewC.ICmpType); 2197 if (!NewCCMask) 2198 return; 2199 } 2200 2201 // Go ahead and make the change. 2202 C.Opcode = SystemZISD::TM; 2203 C.Op0 = NewC.Op0; 2204 if (Mask && Mask->getZExtValue() == MaskVal) 2205 C.Op1 = SDValue(Mask, 0); 2206 else 2207 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType()); 2208 C.CCValid = SystemZ::CCMASK_TM; 2209 C.CCMask = NewCCMask; 2210 } 2211 2212 // See whether the comparison argument contains a redundant AND 2213 // and remove it if so. This sometimes happens due to the generic 2214 // BRCOND expansion. 2215 static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL, 2216 Comparison &C) { 2217 if (C.Op0.getOpcode() != ISD::AND) 2218 return; 2219 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1)); 2220 if (!Mask) 2221 return; 2222 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0)); 2223 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue()) 2224 return; 2225 2226 C.Op0 = C.Op0.getOperand(0); 2227 } 2228 2229 // Return a Comparison that tests the condition-code result of intrinsic 2230 // node Call against constant integer CC using comparison code Cond. 2231 // Opcode is the opcode of the SystemZISD operation for the intrinsic 2232 // and CCValid is the set of possible condition-code results. 2233 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode, 2234 SDValue Call, unsigned CCValid, uint64_t CC, 2235 ISD::CondCode Cond) { 2236 Comparison C(Call, SDValue()); 2237 C.Opcode = Opcode; 2238 C.CCValid = CCValid; 2239 if (Cond == ISD::SETEQ) 2240 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3. 2241 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0; 2242 else if (Cond == ISD::SETNE) 2243 // ...and the inverse of that. 2244 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1; 2245 else if (Cond == ISD::SETLT || Cond == ISD::SETULT) 2246 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3, 2247 // always true for CC>3. 2248 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1; 2249 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE) 2250 // ...and the inverse of that. 2251 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0; 2252 else if (Cond == ISD::SETLE || Cond == ISD::SETULE) 2253 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true), 2254 // always true for CC>3. 2255 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1; 2256 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT) 2257 // ...and the inverse of that. 2258 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0; 2259 else 2260 llvm_unreachable("Unexpected integer comparison type"); 2261 C.CCMask &= CCValid; 2262 return C; 2263 } 2264 2265 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1. 2266 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1, 2267 ISD::CondCode Cond, const SDLoc &DL) { 2268 if (CmpOp1.getOpcode() == ISD::Constant) { 2269 uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue(); 2270 unsigned Opcode, CCValid; 2271 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN && 2272 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) && 2273 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid)) 2274 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond); 2275 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 2276 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 && 2277 isIntrinsicWithCC(CmpOp0, Opcode, CCValid)) 2278 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond); 2279 } 2280 Comparison C(CmpOp0, CmpOp1); 2281 C.CCMask = CCMaskForCondCode(Cond); 2282 if (C.Op0.getValueType().isFloatingPoint()) { 2283 C.CCValid = SystemZ::CCMASK_FCMP; 2284 C.Opcode = SystemZISD::FCMP; 2285 adjustForFNeg(C); 2286 } else { 2287 C.CCValid = SystemZ::CCMASK_ICMP; 2288 C.Opcode = SystemZISD::ICMP; 2289 // Choose the type of comparison. Equality and inequality tests can 2290 // use either signed or unsigned comparisons. The choice also doesn't 2291 // matter if both sign bits are known to be clear. In those cases we 2292 // want to give the main isel code the freedom to choose whichever 2293 // form fits best. 2294 if (C.CCMask == SystemZ::CCMASK_CMP_EQ || 2295 C.CCMask == SystemZ::CCMASK_CMP_NE || 2296 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1))) 2297 C.ICmpType = SystemZICMP::Any; 2298 else if (C.CCMask & SystemZ::CCMASK_CMP_UO) 2299 C.ICmpType = SystemZICMP::UnsignedOnly; 2300 else 2301 C.ICmpType = SystemZICMP::SignedOnly; 2302 C.CCMask &= ~SystemZ::CCMASK_CMP_UO; 2303 adjustForRedundantAnd(DAG, DL, C); 2304 adjustZeroCmp(DAG, DL, C); 2305 adjustSubwordCmp(DAG, DL, C); 2306 adjustForSubtraction(DAG, DL, C); 2307 adjustForLTGFR(C); 2308 adjustICmpTruncate(DAG, DL, C); 2309 } 2310 2311 if (shouldSwapCmpOperands(C)) { 2312 std::swap(C.Op0, C.Op1); 2313 C.CCMask = reverseCCMask(C.CCMask); 2314 } 2315 2316 adjustForTestUnderMask(DAG, DL, C); 2317 return C; 2318 } 2319 2320 // Emit the comparison instruction described by C. 2321 static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) { 2322 if (!C.Op1.getNode()) { 2323 SDNode *Node; 2324 switch (C.Op0.getOpcode()) { 2325 case ISD::INTRINSIC_W_CHAIN: 2326 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode); 2327 return SDValue(Node, 0); 2328 case ISD::INTRINSIC_WO_CHAIN: 2329 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode); 2330 return SDValue(Node, Node->getNumValues() - 1); 2331 default: 2332 llvm_unreachable("Invalid comparison operands"); 2333 } 2334 } 2335 if (C.Opcode == SystemZISD::ICMP) 2336 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1, 2337 DAG.getConstant(C.ICmpType, DL, MVT::i32)); 2338 if (C.Opcode == SystemZISD::TM) { 2339 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) != 2340 bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1)); 2341 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1, 2342 DAG.getConstant(RegisterOnly, DL, MVT::i32)); 2343 } 2344 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1); 2345 } 2346 2347 // Implement a 32-bit *MUL_LOHI operation by extending both operands to 2348 // 64 bits. Extend is the extension type to use. Store the high part 2349 // in Hi and the low part in Lo. 2350 static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend, 2351 SDValue Op0, SDValue Op1, SDValue &Hi, 2352 SDValue &Lo) { 2353 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0); 2354 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1); 2355 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1); 2356 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 2357 DAG.getConstant(32, DL, MVT::i64)); 2358 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi); 2359 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul); 2360 } 2361 2362 // Lower a binary operation that produces two VT results, one in each 2363 // half of a GR128 pair. Op0 and Op1 are the VT operands to the operation, 2364 // and Opcode performs the GR128 operation. Store the even register result 2365 // in Even and the odd register result in Odd. 2366 static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT, 2367 unsigned Opcode, SDValue Op0, SDValue Op1, 2368 SDValue &Even, SDValue &Odd) { 2369 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1); 2370 bool Is32Bit = is32Bit(VT); 2371 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result); 2372 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result); 2373 } 2374 2375 // Return an i32 value that is 1 if the CC value produced by CCReg is 2376 // in the mask CCMask and 0 otherwise. CC is known to have a value 2377 // in CCValid, so other values can be ignored. 2378 static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg, 2379 unsigned CCValid, unsigned CCMask) { 2380 SDValue Ops[] = { DAG.getConstant(1, DL, MVT::i32), 2381 DAG.getConstant(0, DL, MVT::i32), 2382 DAG.getConstant(CCValid, DL, MVT::i32), 2383 DAG.getConstant(CCMask, DL, MVT::i32), CCReg }; 2384 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops); 2385 } 2386 2387 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot 2388 // be done directly. IsFP is true if CC is for a floating-point rather than 2389 // integer comparison. 2390 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) { 2391 switch (CC) { 2392 case ISD::SETOEQ: 2393 case ISD::SETEQ: 2394 return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE; 2395 2396 case ISD::SETOGE: 2397 case ISD::SETGE: 2398 return IsFP ? SystemZISD::VFCMPHE : static_cast<SystemZISD::NodeType>(0); 2399 2400 case ISD::SETOGT: 2401 case ISD::SETGT: 2402 return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH; 2403 2404 case ISD::SETUGT: 2405 return IsFP ? static_cast<SystemZISD::NodeType>(0) : SystemZISD::VICMPHL; 2406 2407 default: 2408 return 0; 2409 } 2410 } 2411 2412 // Return the SystemZISD vector comparison operation for CC or its inverse, 2413 // or 0 if neither can be done directly. Indicate in Invert whether the 2414 // result is for the inverse of CC. IsFP is true if CC is for a 2415 // floating-point rather than integer comparison. 2416 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP, 2417 bool &Invert) { 2418 if (unsigned Opcode = getVectorComparison(CC, IsFP)) { 2419 Invert = false; 2420 return Opcode; 2421 } 2422 2423 CC = ISD::getSetCCInverse(CC, !IsFP); 2424 if (unsigned Opcode = getVectorComparison(CC, IsFP)) { 2425 Invert = true; 2426 return Opcode; 2427 } 2428 2429 return 0; 2430 } 2431 2432 // Return a v2f64 that contains the extended form of elements Start and Start+1 2433 // of v4f32 value Op. 2434 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL, 2435 SDValue Op) { 2436 int Mask[] = { Start, -1, Start + 1, -1 }; 2437 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask); 2438 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op); 2439 } 2440 2441 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode, 2442 // producing a result of type VT. 2443 SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode, 2444 const SDLoc &DL, EVT VT, 2445 SDValue CmpOp0, 2446 SDValue CmpOp1) const { 2447 // There is no hardware support for v4f32 (unless we have the vector 2448 // enhancements facility 1), so extend the vector into two v2f64s 2449 // and compare those. 2450 if (CmpOp0.getValueType() == MVT::v4f32 && 2451 !Subtarget.hasVectorEnhancements1()) { 2452 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0); 2453 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0); 2454 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1); 2455 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1); 2456 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1); 2457 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1); 2458 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes); 2459 } 2460 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1); 2461 } 2462 2463 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing 2464 // an integer mask of type VT. 2465 SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG, 2466 const SDLoc &DL, EVT VT, 2467 ISD::CondCode CC, 2468 SDValue CmpOp0, 2469 SDValue CmpOp1) const { 2470 bool IsFP = CmpOp0.getValueType().isFloatingPoint(); 2471 bool Invert = false; 2472 SDValue Cmp; 2473 switch (CC) { 2474 // Handle tests for order using (or (ogt y x) (oge x y)). 2475 case ISD::SETUO: 2476 Invert = true; 2477 LLVM_FALLTHROUGH; 2478 case ISD::SETO: { 2479 assert(IsFP && "Unexpected integer comparison"); 2480 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0); 2481 SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1); 2482 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE); 2483 break; 2484 } 2485 2486 // Handle <> tests using (or (ogt y x) (ogt x y)). 2487 case ISD::SETUEQ: 2488 Invert = true; 2489 LLVM_FALLTHROUGH; 2490 case ISD::SETONE: { 2491 assert(IsFP && "Unexpected integer comparison"); 2492 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0); 2493 SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1); 2494 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT); 2495 break; 2496 } 2497 2498 // Otherwise a single comparison is enough. It doesn't really 2499 // matter whether we try the inversion or the swap first, since 2500 // there are no cases where both work. 2501 default: 2502 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert)) 2503 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1); 2504 else { 2505 CC = ISD::getSetCCSwappedOperands(CC); 2506 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert)) 2507 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0); 2508 else 2509 llvm_unreachable("Unhandled comparison"); 2510 } 2511 break; 2512 } 2513 if (Invert) { 2514 SDValue Mask = 2515 DAG.getSplatBuildVector(VT, DL, DAG.getConstant(-1, DL, MVT::i64)); 2516 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask); 2517 } 2518 return Cmp; 2519 } 2520 2521 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op, 2522 SelectionDAG &DAG) const { 2523 SDValue CmpOp0 = Op.getOperand(0); 2524 SDValue CmpOp1 = Op.getOperand(1); 2525 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2526 SDLoc DL(Op); 2527 EVT VT = Op.getValueType(); 2528 if (VT.isVector()) 2529 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1); 2530 2531 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL)); 2532 SDValue CCReg = emitCmp(DAG, DL, C); 2533 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask); 2534 } 2535 2536 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 2537 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 2538 SDValue CmpOp0 = Op.getOperand(2); 2539 SDValue CmpOp1 = Op.getOperand(3); 2540 SDValue Dest = Op.getOperand(4); 2541 SDLoc DL(Op); 2542 2543 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL)); 2544 SDValue CCReg = emitCmp(DAG, DL, C); 2545 return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(), 2546 Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32), 2547 DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, CCReg); 2548 } 2549 2550 // Return true if Pos is CmpOp and Neg is the negative of CmpOp, 2551 // allowing Pos and Neg to be wider than CmpOp. 2552 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) { 2553 return (Neg.getOpcode() == ISD::SUB && 2554 Neg.getOperand(0).getOpcode() == ISD::Constant && 2555 cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 && 2556 Neg.getOperand(1) == Pos && 2557 (Pos == CmpOp || 2558 (Pos.getOpcode() == ISD::SIGN_EXTEND && 2559 Pos.getOperand(0) == CmpOp))); 2560 } 2561 2562 // Return the absolute or negative absolute of Op; IsNegative decides which. 2563 static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op, 2564 bool IsNegative) { 2565 Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op); 2566 if (IsNegative) 2567 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(), 2568 DAG.getConstant(0, DL, Op.getValueType()), Op); 2569 return Op; 2570 } 2571 2572 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op, 2573 SelectionDAG &DAG) const { 2574 SDValue CmpOp0 = Op.getOperand(0); 2575 SDValue CmpOp1 = Op.getOperand(1); 2576 SDValue TrueOp = Op.getOperand(2); 2577 SDValue FalseOp = Op.getOperand(3); 2578 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 2579 SDLoc DL(Op); 2580 2581 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL)); 2582 2583 // Check for absolute and negative-absolute selections, including those 2584 // where the comparison value is sign-extended (for LPGFR and LNGFR). 2585 // This check supplements the one in DAGCombiner. 2586 if (C.Opcode == SystemZISD::ICMP && 2587 C.CCMask != SystemZ::CCMASK_CMP_EQ && 2588 C.CCMask != SystemZ::CCMASK_CMP_NE && 2589 C.Op1.getOpcode() == ISD::Constant && 2590 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) { 2591 if (isAbsolute(C.Op0, TrueOp, FalseOp)) 2592 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT); 2593 if (isAbsolute(C.Op0, FalseOp, TrueOp)) 2594 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT); 2595 } 2596 2597 SDValue CCReg = emitCmp(DAG, DL, C); 2598 SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32), 2599 DAG.getConstant(C.CCMask, DL, MVT::i32), CCReg}; 2600 2601 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops); 2602 } 2603 2604 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node, 2605 SelectionDAG &DAG) const { 2606 SDLoc DL(Node); 2607 const GlobalValue *GV = Node->getGlobal(); 2608 int64_t Offset = Node->getOffset(); 2609 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2610 CodeModel::Model CM = DAG.getTarget().getCodeModel(); 2611 2612 SDValue Result; 2613 if (Subtarget.isPC32DBLSymbol(GV, CM)) { 2614 // Assign anchors at 1<<12 byte boundaries. 2615 uint64_t Anchor = Offset & ~uint64_t(0xfff); 2616 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor); 2617 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 2618 2619 // The offset can be folded into the address if it is aligned to a halfword. 2620 Offset -= Anchor; 2621 if (Offset != 0 && (Offset & 1) == 0) { 2622 SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset); 2623 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result); 2624 Offset = 0; 2625 } 2626 } else { 2627 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT); 2628 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 2629 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2630 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2631 } 2632 2633 // If there was a non-zero offset that we didn't fold, create an explicit 2634 // addition for it. 2635 if (Offset != 0) 2636 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result, 2637 DAG.getConstant(Offset, DL, PtrVT)); 2638 2639 return Result; 2640 } 2641 2642 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node, 2643 SelectionDAG &DAG, 2644 unsigned Opcode, 2645 SDValue GOTOffset) const { 2646 SDLoc DL(Node); 2647 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2648 SDValue Chain = DAG.getEntryNode(); 2649 SDValue Glue; 2650 2651 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12. 2652 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT); 2653 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue); 2654 Glue = Chain.getValue(1); 2655 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue); 2656 Glue = Chain.getValue(1); 2657 2658 // The first call operand is the chain and the second is the TLS symbol. 2659 SmallVector<SDValue, 8> Ops; 2660 Ops.push_back(Chain); 2661 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL, 2662 Node->getValueType(0), 2663 0, 0)); 2664 2665 // Add argument registers to the end of the list so that they are 2666 // known live into the call. 2667 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT)); 2668 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT)); 2669 2670 // Add a register mask operand representing the call-preserved registers. 2671 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 2672 const uint32_t *Mask = 2673 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 2674 assert(Mask && "Missing call preserved mask for calling convention"); 2675 Ops.push_back(DAG.getRegisterMask(Mask)); 2676 2677 // Glue the call to the argument copies. 2678 Ops.push_back(Glue); 2679 2680 // Emit the call. 2681 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2682 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops); 2683 Glue = Chain.getValue(1); 2684 2685 // Copy the return value from %r2. 2686 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue); 2687 } 2688 2689 SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL, 2690 SelectionDAG &DAG) const { 2691 SDValue Chain = DAG.getEntryNode(); 2692 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2693 2694 // The high part of the thread pointer is in access register 0. 2695 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32); 2696 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi); 2697 2698 // The low part of the thread pointer is in access register 1. 2699 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32); 2700 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo); 2701 2702 // Merge them into a single 64-bit address. 2703 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi, 2704 DAG.getConstant(32, DL, PtrVT)); 2705 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo); 2706 } 2707 2708 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node, 2709 SelectionDAG &DAG) const { 2710 if (DAG.getTarget().useEmulatedTLS()) 2711 return LowerToTLSEmulatedModel(Node, DAG); 2712 SDLoc DL(Node); 2713 const GlobalValue *GV = Node->getGlobal(); 2714 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2715 TLSModel::Model model = DAG.getTarget().getTLSModel(GV); 2716 2717 SDValue TP = lowerThreadPointer(DL, DAG); 2718 2719 // Get the offset of GA from the thread pointer, based on the TLS model. 2720 SDValue Offset; 2721 switch (model) { 2722 case TLSModel::GeneralDynamic: { 2723 // Load the GOT offset of the tls_index (module ID / per-symbol offset). 2724 SystemZConstantPoolValue *CPV = 2725 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD); 2726 2727 Offset = DAG.getConstantPool(CPV, PtrVT, 8); 2728 Offset = DAG.getLoad( 2729 PtrVT, DL, DAG.getEntryNode(), Offset, 2730 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2731 2732 // Call __tls_get_offset to retrieve the offset. 2733 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset); 2734 break; 2735 } 2736 2737 case TLSModel::LocalDynamic: { 2738 // Load the GOT offset of the module ID. 2739 SystemZConstantPoolValue *CPV = 2740 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM); 2741 2742 Offset = DAG.getConstantPool(CPV, PtrVT, 8); 2743 Offset = DAG.getLoad( 2744 PtrVT, DL, DAG.getEntryNode(), Offset, 2745 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2746 2747 // Call __tls_get_offset to retrieve the module base offset. 2748 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset); 2749 2750 // Note: The SystemZLDCleanupPass will remove redundant computations 2751 // of the module base offset. Count total number of local-dynamic 2752 // accesses to trigger execution of that pass. 2753 SystemZMachineFunctionInfo* MFI = 2754 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>(); 2755 MFI->incNumLocalDynamicTLSAccesses(); 2756 2757 // Add the per-symbol offset. 2758 CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF); 2759 2760 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8); 2761 DTPOffset = DAG.getLoad( 2762 PtrVT, DL, DAG.getEntryNode(), DTPOffset, 2763 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2764 2765 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset); 2766 break; 2767 } 2768 2769 case TLSModel::InitialExec: { 2770 // Load the offset from the GOT. 2771 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2772 SystemZII::MO_INDNTPOFF); 2773 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset); 2774 Offset = 2775 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset, 2776 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2777 break; 2778 } 2779 2780 case TLSModel::LocalExec: { 2781 // Force the offset into the constant pool and load it from there. 2782 SystemZConstantPoolValue *CPV = 2783 SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF); 2784 2785 Offset = DAG.getConstantPool(CPV, PtrVT, 8); 2786 Offset = DAG.getLoad( 2787 PtrVT, DL, DAG.getEntryNode(), Offset, 2788 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2789 break; 2790 } 2791 } 2792 2793 // Add the base and offset together. 2794 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset); 2795 } 2796 2797 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node, 2798 SelectionDAG &DAG) const { 2799 SDLoc DL(Node); 2800 const BlockAddress *BA = Node->getBlockAddress(); 2801 int64_t Offset = Node->getOffset(); 2802 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2803 2804 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset); 2805 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 2806 return Result; 2807 } 2808 2809 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT, 2810 SelectionDAG &DAG) const { 2811 SDLoc DL(JT); 2812 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2813 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2814 2815 // Use LARL to load the address of the table. 2816 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 2817 } 2818 2819 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP, 2820 SelectionDAG &DAG) const { 2821 SDLoc DL(CP); 2822 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2823 2824 SDValue Result; 2825 if (CP->isMachineConstantPoolEntry()) 2826 Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2827 CP->getAlignment()); 2828 else 2829 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2830 CP->getAlignment(), CP->getOffset()); 2831 2832 // Use LARL to load the address of the constant pool entry. 2833 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result); 2834 } 2835 2836 SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op, 2837 SelectionDAG &DAG) const { 2838 MachineFunction &MF = DAG.getMachineFunction(); 2839 MachineFrameInfo &MFI = MF.getFrameInfo(); 2840 MFI.setFrameAddressIsTaken(true); 2841 2842 SDLoc DL(Op); 2843 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2844 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2845 2846 // If the back chain frame index has not been allocated yet, do so. 2847 SystemZMachineFunctionInfo *FI = MF.getInfo<SystemZMachineFunctionInfo>(); 2848 int BackChainIdx = FI->getFramePointerSaveIndex(); 2849 if (!BackChainIdx) { 2850 // By definition, the frame address is the address of the back chain. 2851 BackChainIdx = MFI.CreateFixedObject(8, -SystemZMC::CallFrameSize, false); 2852 FI->setFramePointerSaveIndex(BackChainIdx); 2853 } 2854 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT); 2855 2856 // FIXME The frontend should detect this case. 2857 if (Depth > 0) { 2858 report_fatal_error("Unsupported stack frame traversal count"); 2859 } 2860 2861 return BackChain; 2862 } 2863 2864 SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op, 2865 SelectionDAG &DAG) const { 2866 MachineFunction &MF = DAG.getMachineFunction(); 2867 MachineFrameInfo &MFI = MF.getFrameInfo(); 2868 MFI.setReturnAddressIsTaken(true); 2869 2870 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 2871 return SDValue(); 2872 2873 SDLoc DL(Op); 2874 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2875 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2876 2877 // FIXME The frontend should detect this case. 2878 if (Depth > 0) { 2879 report_fatal_error("Unsupported stack frame traversal count"); 2880 } 2881 2882 // Return R14D, which has the return address. Mark it an implicit live-in. 2883 unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass); 2884 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT); 2885 } 2886 2887 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op, 2888 SelectionDAG &DAG) const { 2889 SDLoc DL(Op); 2890 SDValue In = Op.getOperand(0); 2891 EVT InVT = In.getValueType(); 2892 EVT ResVT = Op.getValueType(); 2893 2894 // Convert loads directly. This is normally done by DAGCombiner, 2895 // but we need this case for bitcasts that are created during lowering 2896 // and which are then lowered themselves. 2897 if (auto *LoadN = dyn_cast<LoadSDNode>(In)) 2898 if (ISD::isNormalLoad(LoadN)) { 2899 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(), 2900 LoadN->getBasePtr(), LoadN->getMemOperand()); 2901 // Update the chain uses. 2902 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1)); 2903 return NewLoad; 2904 } 2905 2906 if (InVT == MVT::i32 && ResVT == MVT::f32) { 2907 SDValue In64; 2908 if (Subtarget.hasHighWord()) { 2909 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, 2910 MVT::i64); 2911 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL, 2912 MVT::i64, SDValue(U64, 0), In); 2913 } else { 2914 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In); 2915 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64, 2916 DAG.getConstant(32, DL, MVT::i64)); 2917 } 2918 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64); 2919 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, 2920 DL, MVT::f32, Out64); 2921 } 2922 if (InVT == MVT::f32 && ResVT == MVT::i32) { 2923 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64); 2924 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL, 2925 MVT::f64, SDValue(U64, 0), In); 2926 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64); 2927 if (Subtarget.hasHighWord()) 2928 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL, 2929 MVT::i32, Out64); 2930 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64, 2931 DAG.getConstant(32, DL, MVT::i64)); 2932 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift); 2933 } 2934 llvm_unreachable("Unexpected bitcast combination"); 2935 } 2936 2937 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op, 2938 SelectionDAG &DAG) const { 2939 MachineFunction &MF = DAG.getMachineFunction(); 2940 SystemZMachineFunctionInfo *FuncInfo = 2941 MF.getInfo<SystemZMachineFunctionInfo>(); 2942 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2943 2944 SDValue Chain = Op.getOperand(0); 2945 SDValue Addr = Op.getOperand(1); 2946 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2947 SDLoc DL(Op); 2948 2949 // The initial values of each field. 2950 const unsigned NumFields = 4; 2951 SDValue Fields[NumFields] = { 2952 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT), 2953 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT), 2954 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT), 2955 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT) 2956 }; 2957 2958 // Store each field into its respective slot. 2959 SDValue MemOps[NumFields]; 2960 unsigned Offset = 0; 2961 for (unsigned I = 0; I < NumFields; ++I) { 2962 SDValue FieldAddr = Addr; 2963 if (Offset != 0) 2964 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr, 2965 DAG.getIntPtrConstant(Offset, DL)); 2966 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr, 2967 MachinePointerInfo(SV, Offset)); 2968 Offset += 8; 2969 } 2970 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 2971 } 2972 2973 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op, 2974 SelectionDAG &DAG) const { 2975 SDValue Chain = Op.getOperand(0); 2976 SDValue DstPtr = Op.getOperand(1); 2977 SDValue SrcPtr = Op.getOperand(2); 2978 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 2979 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 2980 SDLoc DL(Op); 2981 2982 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL), 2983 /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false, 2984 /*isTailCall*/false, 2985 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 2986 } 2987 2988 SDValue SystemZTargetLowering:: 2989 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 2990 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 2991 MachineFunction &MF = DAG.getMachineFunction(); 2992 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack"); 2993 bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain"); 2994 2995 SDValue Chain = Op.getOperand(0); 2996 SDValue Size = Op.getOperand(1); 2997 SDValue Align = Op.getOperand(2); 2998 SDLoc DL(Op); 2999 3000 // If user has set the no alignment function attribute, ignore 3001 // alloca alignments. 3002 uint64_t AlignVal = (RealignOpt ? 3003 dyn_cast<ConstantSDNode>(Align)->getZExtValue() : 0); 3004 3005 uint64_t StackAlign = TFI->getStackAlignment(); 3006 uint64_t RequiredAlign = std::max(AlignVal, StackAlign); 3007 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign; 3008 3009 unsigned SPReg = getStackPointerRegisterToSaveRestore(); 3010 SDValue NeededSpace = Size; 3011 3012 // Get a reference to the stack pointer. 3013 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64); 3014 3015 // If we need a backchain, save it now. 3016 SDValue Backchain; 3017 if (StoreBackchain) 3018 Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo()); 3019 3020 // Add extra space for alignment if needed. 3021 if (ExtraAlignSpace) 3022 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace, 3023 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64)); 3024 3025 // Get the new stack pointer value. 3026 SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace); 3027 3028 // Copy the new stack pointer back. 3029 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP); 3030 3031 // The allocated data lives above the 160 bytes allocated for the standard 3032 // frame, plus any outgoing stack arguments. We don't know how much that 3033 // amounts to yet, so emit a special ADJDYNALLOC placeholder. 3034 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64); 3035 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust); 3036 3037 // Dynamically realign if needed. 3038 if (RequiredAlign > StackAlign) { 3039 Result = 3040 DAG.getNode(ISD::ADD, DL, MVT::i64, Result, 3041 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64)); 3042 Result = 3043 DAG.getNode(ISD::AND, DL, MVT::i64, Result, 3044 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64)); 3045 } 3046 3047 if (StoreBackchain) 3048 Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo()); 3049 3050 SDValue Ops[2] = { Result, Chain }; 3051 return DAG.getMergeValues(Ops, DL); 3052 } 3053 3054 SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET( 3055 SDValue Op, SelectionDAG &DAG) const { 3056 SDLoc DL(Op); 3057 3058 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64); 3059 } 3060 3061 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op, 3062 SelectionDAG &DAG) const { 3063 EVT VT = Op.getValueType(); 3064 SDLoc DL(Op); 3065 SDValue Ops[2]; 3066 if (is32Bit(VT)) 3067 // Just do a normal 64-bit multiplication and extract the results. 3068 // We define this so that it can be used for constant division. 3069 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0), 3070 Op.getOperand(1), Ops[1], Ops[0]); 3071 else if (Subtarget.hasMiscellaneousExtensions2()) 3072 // SystemZISD::SMUL_LOHI returns the low result in the odd register and 3073 // the high result in the even register. ISD::SMUL_LOHI is defined to 3074 // return the low half first, so the results are in reverse order. 3075 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI, 3076 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]); 3077 else { 3078 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI: 3079 // 3080 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64) 3081 // 3082 // but using the fact that the upper halves are either all zeros 3083 // or all ones: 3084 // 3085 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64) 3086 // 3087 // and grouping the right terms together since they are quicker than the 3088 // multiplication: 3089 // 3090 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64) 3091 SDValue C63 = DAG.getConstant(63, DL, MVT::i64); 3092 SDValue LL = Op.getOperand(0); 3093 SDValue RL = Op.getOperand(1); 3094 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63); 3095 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63); 3096 // SystemZISD::UMUL_LOHI returns the low result in the odd register and 3097 // the high result in the even register. ISD::SMUL_LOHI is defined to 3098 // return the low half first, so the results are in reverse order. 3099 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI, 3100 LL, RL, Ops[1], Ops[0]); 3101 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH); 3102 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL); 3103 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL); 3104 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum); 3105 } 3106 return DAG.getMergeValues(Ops, DL); 3107 } 3108 3109 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op, 3110 SelectionDAG &DAG) const { 3111 EVT VT = Op.getValueType(); 3112 SDLoc DL(Op); 3113 SDValue Ops[2]; 3114 if (is32Bit(VT)) 3115 // Just do a normal 64-bit multiplication and extract the results. 3116 // We define this so that it can be used for constant division. 3117 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0), 3118 Op.getOperand(1), Ops[1], Ops[0]); 3119 else 3120 // SystemZISD::UMUL_LOHI returns the low result in the odd register and 3121 // the high result in the even register. ISD::UMUL_LOHI is defined to 3122 // return the low half first, so the results are in reverse order. 3123 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI, 3124 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]); 3125 return DAG.getMergeValues(Ops, DL); 3126 } 3127 3128 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op, 3129 SelectionDAG &DAG) const { 3130 SDValue Op0 = Op.getOperand(0); 3131 SDValue Op1 = Op.getOperand(1); 3132 EVT VT = Op.getValueType(); 3133 SDLoc DL(Op); 3134 3135 // We use DSGF for 32-bit division. This means the first operand must 3136 // always be 64-bit, and the second operand should be 32-bit whenever 3137 // that is possible, to improve performance. 3138 if (is32Bit(VT)) 3139 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0); 3140 else if (DAG.ComputeNumSignBits(Op1) > 32) 3141 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1); 3142 3143 // DSG(F) returns the remainder in the even register and the 3144 // quotient in the odd register. 3145 SDValue Ops[2]; 3146 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]); 3147 return DAG.getMergeValues(Ops, DL); 3148 } 3149 3150 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op, 3151 SelectionDAG &DAG) const { 3152 EVT VT = Op.getValueType(); 3153 SDLoc DL(Op); 3154 3155 // DL(G) returns the remainder in the even register and the 3156 // quotient in the odd register. 3157 SDValue Ops[2]; 3158 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM, 3159 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]); 3160 return DAG.getMergeValues(Ops, DL); 3161 } 3162 3163 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const { 3164 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation"); 3165 3166 // Get the known-zero masks for each operand. 3167 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)}; 3168 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]), 3169 DAG.computeKnownBits(Ops[1])}; 3170 3171 // See if the upper 32 bits of one operand and the lower 32 bits of the 3172 // other are known zero. They are the low and high operands respectively. 3173 uint64_t Masks[] = { Known[0].Zero.getZExtValue(), 3174 Known[1].Zero.getZExtValue() }; 3175 unsigned High, Low; 3176 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff) 3177 High = 1, Low = 0; 3178 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff) 3179 High = 0, Low = 1; 3180 else 3181 return Op; 3182 3183 SDValue LowOp = Ops[Low]; 3184 SDValue HighOp = Ops[High]; 3185 3186 // If the high part is a constant, we're better off using IILH. 3187 if (HighOp.getOpcode() == ISD::Constant) 3188 return Op; 3189 3190 // If the low part is a constant that is outside the range of LHI, 3191 // then we're better off using IILF. 3192 if (LowOp.getOpcode() == ISD::Constant) { 3193 int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue()); 3194 if (!isInt<16>(Value)) 3195 return Op; 3196 } 3197 3198 // Check whether the high part is an AND that doesn't change the 3199 // high 32 bits and just masks out low bits. We can skip it if so. 3200 if (HighOp.getOpcode() == ISD::AND && 3201 HighOp.getOperand(1).getOpcode() == ISD::Constant) { 3202 SDValue HighOp0 = HighOp.getOperand(0); 3203 uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue(); 3204 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff)))) 3205 HighOp = HighOp0; 3206 } 3207 3208 // Take advantage of the fact that all GR32 operations only change the 3209 // low 32 bits by truncating Low to an i32 and inserting it directly 3210 // using a subreg. The interesting cases are those where the truncation 3211 // can be folded. 3212 SDLoc DL(Op); 3213 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp); 3214 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL, 3215 MVT::i64, HighOp, Low32); 3216 } 3217 3218 // Lower SADDO/SSUBO/UADDO/USUBO nodes. 3219 SDValue SystemZTargetLowering::lowerXALUO(SDValue Op, 3220 SelectionDAG &DAG) const { 3221 SDNode *N = Op.getNode(); 3222 SDValue LHS = N->getOperand(0); 3223 SDValue RHS = N->getOperand(1); 3224 SDLoc DL(N); 3225 unsigned BaseOp = 0; 3226 unsigned CCValid = 0; 3227 unsigned CCMask = 0; 3228 3229 switch (Op.getOpcode()) { 3230 default: llvm_unreachable("Unknown instruction!"); 3231 case ISD::SADDO: 3232 BaseOp = SystemZISD::SADDO; 3233 CCValid = SystemZ::CCMASK_ARITH; 3234 CCMask = SystemZ::CCMASK_ARITH_OVERFLOW; 3235 break; 3236 case ISD::SSUBO: 3237 BaseOp = SystemZISD::SSUBO; 3238 CCValid = SystemZ::CCMASK_ARITH; 3239 CCMask = SystemZ::CCMASK_ARITH_OVERFLOW; 3240 break; 3241 case ISD::UADDO: 3242 BaseOp = SystemZISD::UADDO; 3243 CCValid = SystemZ::CCMASK_LOGICAL; 3244 CCMask = SystemZ::CCMASK_LOGICAL_CARRY; 3245 break; 3246 case ISD::USUBO: 3247 BaseOp = SystemZISD::USUBO; 3248 CCValid = SystemZ::CCMASK_LOGICAL; 3249 CCMask = SystemZ::CCMASK_LOGICAL_BORROW; 3250 break; 3251 } 3252 3253 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 3254 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 3255 3256 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask); 3257 if (N->getValueType(1) == MVT::i1) 3258 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC); 3259 3260 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC); 3261 } 3262 3263 // Lower ADDCARRY/SUBCARRY nodes. 3264 SDValue SystemZTargetLowering::lowerADDSUBCARRY(SDValue Op, 3265 SelectionDAG &DAG) const { 3266 3267 SDNode *N = Op.getNode(); 3268 MVT VT = N->getSimpleValueType(0); 3269 3270 // Let legalize expand this if it isn't a legal type yet. 3271 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 3272 return SDValue(); 3273 3274 SDValue LHS = N->getOperand(0); 3275 SDValue RHS = N->getOperand(1); 3276 SDValue Carry = Op.getOperand(2); 3277 SDLoc DL(N); 3278 unsigned BaseOp = 0; 3279 unsigned CCValid = 0; 3280 unsigned CCMask = 0; 3281 3282 switch (Op.getOpcode()) { 3283 default: llvm_unreachable("Unknown instruction!"); 3284 case ISD::ADDCARRY: 3285 BaseOp = SystemZISD::ADDCARRY; 3286 CCValid = SystemZ::CCMASK_LOGICAL; 3287 CCMask = SystemZ::CCMASK_LOGICAL_CARRY; 3288 break; 3289 case ISD::SUBCARRY: 3290 BaseOp = SystemZISD::SUBCARRY; 3291 CCValid = SystemZ::CCMASK_LOGICAL; 3292 CCMask = SystemZ::CCMASK_LOGICAL_BORROW; 3293 break; 3294 } 3295 3296 // Set the condition code from the carry flag. 3297 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry, 3298 DAG.getConstant(CCValid, DL, MVT::i32), 3299 DAG.getConstant(CCMask, DL, MVT::i32)); 3300 3301 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 3302 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry); 3303 3304 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask); 3305 if (N->getValueType(1) == MVT::i1) 3306 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC); 3307 3308 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC); 3309 } 3310 3311 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op, 3312 SelectionDAG &DAG) const { 3313 EVT VT = Op.getValueType(); 3314 SDLoc DL(Op); 3315 Op = Op.getOperand(0); 3316 3317 // Handle vector types via VPOPCT. 3318 if (VT.isVector()) { 3319 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op); 3320 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op); 3321 switch (VT.getScalarSizeInBits()) { 3322 case 8: 3323 break; 3324 case 16: { 3325 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op); 3326 SDValue Shift = DAG.getConstant(8, DL, MVT::i32); 3327 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift); 3328 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp); 3329 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift); 3330 break; 3331 } 3332 case 32: { 3333 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL, 3334 DAG.getConstant(0, DL, MVT::i32)); 3335 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp); 3336 break; 3337 } 3338 case 64: { 3339 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL, 3340 DAG.getConstant(0, DL, MVT::i32)); 3341 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp); 3342 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp); 3343 break; 3344 } 3345 default: 3346 llvm_unreachable("Unexpected type"); 3347 } 3348 return Op; 3349 } 3350 3351 // Get the known-zero mask for the operand. 3352 KnownBits Known = DAG.computeKnownBits(Op); 3353 unsigned NumSignificantBits = (~Known.Zero).getActiveBits(); 3354 if (NumSignificantBits == 0) 3355 return DAG.getConstant(0, DL, VT); 3356 3357 // Skip known-zero high parts of the operand. 3358 int64_t OrigBitSize = VT.getSizeInBits(); 3359 int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits); 3360 BitSize = std::min(BitSize, OrigBitSize); 3361 3362 // The POPCNT instruction counts the number of bits in each byte. 3363 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op); 3364 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op); 3365 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 3366 3367 // Add up per-byte counts in a binary tree. All bits of Op at 3368 // position larger than BitSize remain zero throughout. 3369 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) { 3370 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT)); 3371 if (BitSize != OrigBitSize) 3372 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp, 3373 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT)); 3374 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp); 3375 } 3376 3377 // Extract overall result from high byte. 3378 if (BitSize > 8) 3379 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 3380 DAG.getConstant(BitSize - 8, DL, VT)); 3381 3382 return Op; 3383 } 3384 3385 SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op, 3386 SelectionDAG &DAG) const { 3387 SDLoc DL(Op); 3388 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>( 3389 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()); 3390 SyncScope::ID FenceSSID = static_cast<SyncScope::ID>( 3391 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 3392 3393 // The only fence that needs an instruction is a sequentially-consistent 3394 // cross-thread fence. 3395 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent && 3396 FenceSSID == SyncScope::System) { 3397 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other, 3398 Op.getOperand(0)), 3399 0); 3400 } 3401 3402 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 3403 return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0)); 3404 } 3405 3406 // Op is an atomic load. Lower it into a normal volatile load. 3407 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op, 3408 SelectionDAG &DAG) const { 3409 auto *Node = cast<AtomicSDNode>(Op.getNode()); 3410 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(), 3411 Node->getChain(), Node->getBasePtr(), 3412 Node->getMemoryVT(), Node->getMemOperand()); 3413 } 3414 3415 // Op is an atomic store. Lower it into a normal volatile store. 3416 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op, 3417 SelectionDAG &DAG) const { 3418 auto *Node = cast<AtomicSDNode>(Op.getNode()); 3419 SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(), 3420 Node->getBasePtr(), Node->getMemoryVT(), 3421 Node->getMemOperand()); 3422 // We have to enforce sequential consistency by performing a 3423 // serialization operation after the store. 3424 if (Node->getOrdering() == AtomicOrdering::SequentiallyConsistent) 3425 Chain = SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), 3426 MVT::Other, Chain), 0); 3427 return Chain; 3428 } 3429 3430 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first 3431 // two into the fullword ATOMIC_LOADW_* operation given by Opcode. 3432 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op, 3433 SelectionDAG &DAG, 3434 unsigned Opcode) const { 3435 auto *Node = cast<AtomicSDNode>(Op.getNode()); 3436 3437 // 32-bit operations need no code outside the main loop. 3438 EVT NarrowVT = Node->getMemoryVT(); 3439 EVT WideVT = MVT::i32; 3440 if (NarrowVT == WideVT) 3441 return Op; 3442 3443 int64_t BitSize = NarrowVT.getSizeInBits(); 3444 SDValue ChainIn = Node->getChain(); 3445 SDValue Addr = Node->getBasePtr(); 3446 SDValue Src2 = Node->getVal(); 3447 MachineMemOperand *MMO = Node->getMemOperand(); 3448 SDLoc DL(Node); 3449 EVT PtrVT = Addr.getValueType(); 3450 3451 // Convert atomic subtracts of constants into additions. 3452 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB) 3453 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) { 3454 Opcode = SystemZISD::ATOMIC_LOADW_ADD; 3455 Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType()); 3456 } 3457 3458 // Get the address of the containing word. 3459 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr, 3460 DAG.getConstant(-4, DL, PtrVT)); 3461 3462 // Get the number of bits that the word must be rotated left in order 3463 // to bring the field to the top bits of a GR32. 3464 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr, 3465 DAG.getConstant(3, DL, PtrVT)); 3466 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift); 3467 3468 // Get the complementing shift amount, for rotating a field in the top 3469 // bits back to its proper position. 3470 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT, 3471 DAG.getConstant(0, DL, WideVT), BitShift); 3472 3473 // Extend the source operand to 32 bits and prepare it for the inner loop. 3474 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other 3475 // operations require the source to be shifted in advance. (This shift 3476 // can be folded if the source is constant.) For AND and NAND, the lower 3477 // bits must be set, while for other opcodes they should be left clear. 3478 if (Opcode != SystemZISD::ATOMIC_SWAPW) 3479 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2, 3480 DAG.getConstant(32 - BitSize, DL, WideVT)); 3481 if (Opcode == SystemZISD::ATOMIC_LOADW_AND || 3482 Opcode == SystemZISD::ATOMIC_LOADW_NAND) 3483 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2, 3484 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT)); 3485 3486 // Construct the ATOMIC_LOADW_* node. 3487 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other); 3488 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift, 3489 DAG.getConstant(BitSize, DL, WideVT) }; 3490 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops, 3491 NarrowVT, MMO); 3492 3493 // Rotate the result of the final CS so that the field is in the lower 3494 // bits of a GR32, then truncate it. 3495 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift, 3496 DAG.getConstant(BitSize, DL, WideVT)); 3497 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift); 3498 3499 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) }; 3500 return DAG.getMergeValues(RetOps, DL); 3501 } 3502 3503 // Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations 3504 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit 3505 // operations into additions. 3506 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op, 3507 SelectionDAG &DAG) const { 3508 auto *Node = cast<AtomicSDNode>(Op.getNode()); 3509 EVT MemVT = Node->getMemoryVT(); 3510 if (MemVT == MVT::i32 || MemVT == MVT::i64) { 3511 // A full-width operation. 3512 assert(Op.getValueType() == MemVT && "Mismatched VTs"); 3513 SDValue Src2 = Node->getVal(); 3514 SDValue NegSrc2; 3515 SDLoc DL(Src2); 3516 3517 if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) { 3518 // Use an addition if the operand is constant and either LAA(G) is 3519 // available or the negative value is in the range of A(G)FHI. 3520 int64_t Value = (-Op2->getAPIntValue()).getSExtValue(); 3521 if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1()) 3522 NegSrc2 = DAG.getConstant(Value, DL, MemVT); 3523 } else if (Subtarget.hasInterlockedAccess1()) 3524 // Use LAA(G) if available. 3525 NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT), 3526 Src2); 3527 3528 if (NegSrc2.getNode()) 3529 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT, 3530 Node->getChain(), Node->getBasePtr(), NegSrc2, 3531 Node->getMemOperand()); 3532 3533 // Use the node as-is. 3534 return Op; 3535 } 3536 3537 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB); 3538 } 3539 3540 // Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node. 3541 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op, 3542 SelectionDAG &DAG) const { 3543 auto *Node = cast<AtomicSDNode>(Op.getNode()); 3544 SDValue ChainIn = Node->getOperand(0); 3545 SDValue Addr = Node->getOperand(1); 3546 SDValue CmpVal = Node->getOperand(2); 3547 SDValue SwapVal = Node->getOperand(3); 3548 MachineMemOperand *MMO = Node->getMemOperand(); 3549 SDLoc DL(Node); 3550 3551 // We have native support for 32-bit and 64-bit compare and swap, but we 3552 // still need to expand extracting the "success" result from the CC. 3553 EVT NarrowVT = Node->getMemoryVT(); 3554 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32; 3555 if (NarrowVT == WideVT) { 3556 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other); 3557 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal }; 3558 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP, 3559 DL, Tys, Ops, NarrowVT, MMO); 3560 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1), 3561 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ); 3562 3563 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0)); 3564 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success); 3565 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2)); 3566 return SDValue(); 3567 } 3568 3569 // Convert 8-bit and 16-bit compare and swap to a loop, implemented 3570 // via a fullword ATOMIC_CMP_SWAPW operation. 3571 int64_t BitSize = NarrowVT.getSizeInBits(); 3572 EVT PtrVT = Addr.getValueType(); 3573 3574 // Get the address of the containing word. 3575 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr, 3576 DAG.getConstant(-4, DL, PtrVT)); 3577 3578 // Get the number of bits that the word must be rotated left in order 3579 // to bring the field to the top bits of a GR32. 3580 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr, 3581 DAG.getConstant(3, DL, PtrVT)); 3582 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift); 3583 3584 // Get the complementing shift amount, for rotating a field in the top 3585 // bits back to its proper position. 3586 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT, 3587 DAG.getConstant(0, DL, WideVT), BitShift); 3588 3589 // Construct the ATOMIC_CMP_SWAPW node. 3590 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other); 3591 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift, 3592 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) }; 3593 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL, 3594 VTList, Ops, NarrowVT, MMO); 3595 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1), 3596 SystemZ::CCMASK_ICMP, SystemZ::CCMASK_CMP_EQ); 3597 3598 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0)); 3599 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success); 3600 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2)); 3601 return SDValue(); 3602 } 3603 3604 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op, 3605 SelectionDAG &DAG) const { 3606 MachineFunction &MF = DAG.getMachineFunction(); 3607 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true); 3608 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op), 3609 SystemZ::R15D, Op.getValueType()); 3610 } 3611 3612 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op, 3613 SelectionDAG &DAG) const { 3614 MachineFunction &MF = DAG.getMachineFunction(); 3615 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true); 3616 bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain"); 3617 3618 SDValue Chain = Op.getOperand(0); 3619 SDValue NewSP = Op.getOperand(1); 3620 SDValue Backchain; 3621 SDLoc DL(Op); 3622 3623 if (StoreBackchain) { 3624 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, MVT::i64); 3625 Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo()); 3626 } 3627 3628 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R15D, NewSP); 3629 3630 if (StoreBackchain) 3631 Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo()); 3632 3633 return Chain; 3634 } 3635 3636 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op, 3637 SelectionDAG &DAG) const { 3638 bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3639 if (!IsData) 3640 // Just preserve the chain. 3641 return Op.getOperand(0); 3642 3643 SDLoc DL(Op); 3644 bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 3645 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ; 3646 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode()); 3647 SDValue Ops[] = { 3648 Op.getOperand(0), 3649 DAG.getConstant(Code, DL, MVT::i32), 3650 Op.getOperand(1) 3651 }; 3652 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL, 3653 Node->getVTList(), Ops, 3654 Node->getMemoryVT(), Node->getMemOperand()); 3655 } 3656 3657 // Convert condition code in CCReg to an i32 value. 3658 static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg) { 3659 SDLoc DL(CCReg); 3660 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg); 3661 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM, 3662 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32)); 3663 } 3664 3665 SDValue 3666 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op, 3667 SelectionDAG &DAG) const { 3668 unsigned Opcode, CCValid; 3669 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) { 3670 assert(Op->getNumValues() == 2 && "Expected only CC result and chain"); 3671 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode); 3672 SDValue CC = getCCResult(DAG, SDValue(Node, 0)); 3673 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC); 3674 return SDValue(); 3675 } 3676 3677 return SDValue(); 3678 } 3679 3680 SDValue 3681 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op, 3682 SelectionDAG &DAG) const { 3683 unsigned Opcode, CCValid; 3684 if (isIntrinsicWithCC(Op, Opcode, CCValid)) { 3685 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode); 3686 if (Op->getNumValues() == 1) 3687 return getCCResult(DAG, SDValue(Node, 0)); 3688 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result"); 3689 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(), 3690 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1))); 3691 } 3692 3693 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3694 switch (Id) { 3695 case Intrinsic::thread_pointer: 3696 return lowerThreadPointer(SDLoc(Op), DAG); 3697 3698 case Intrinsic::s390_vpdi: 3699 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(), 3700 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3701 3702 case Intrinsic::s390_vperm: 3703 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(), 3704 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3705 3706 case Intrinsic::s390_vuphb: 3707 case Intrinsic::s390_vuphh: 3708 case Intrinsic::s390_vuphf: 3709 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(), 3710 Op.getOperand(1)); 3711 3712 case Intrinsic::s390_vuplhb: 3713 case Intrinsic::s390_vuplhh: 3714 case Intrinsic::s390_vuplhf: 3715 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(), 3716 Op.getOperand(1)); 3717 3718 case Intrinsic::s390_vuplb: 3719 case Intrinsic::s390_vuplhw: 3720 case Intrinsic::s390_vuplf: 3721 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(), 3722 Op.getOperand(1)); 3723 3724 case Intrinsic::s390_vupllb: 3725 case Intrinsic::s390_vupllh: 3726 case Intrinsic::s390_vupllf: 3727 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(), 3728 Op.getOperand(1)); 3729 3730 case Intrinsic::s390_vsumb: 3731 case Intrinsic::s390_vsumh: 3732 case Intrinsic::s390_vsumgh: 3733 case Intrinsic::s390_vsumgf: 3734 case Intrinsic::s390_vsumqf: 3735 case Intrinsic::s390_vsumqg: 3736 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(), 3737 Op.getOperand(1), Op.getOperand(2)); 3738 } 3739 3740 return SDValue(); 3741 } 3742 3743 namespace { 3744 // Says that SystemZISD operation Opcode can be used to perform the equivalent 3745 // of a VPERM with permute vector Bytes. If Opcode takes three operands, 3746 // Operand is the constant third operand, otherwise it is the number of 3747 // bytes in each element of the result. 3748 struct Permute { 3749 unsigned Opcode; 3750 unsigned Operand; 3751 unsigned char Bytes[SystemZ::VectorBytes]; 3752 }; 3753 } 3754 3755 static const Permute PermuteForms[] = { 3756 // VMRHG 3757 { SystemZISD::MERGE_HIGH, 8, 3758 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } }, 3759 // VMRHF 3760 { SystemZISD::MERGE_HIGH, 4, 3761 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } }, 3762 // VMRHH 3763 { SystemZISD::MERGE_HIGH, 2, 3764 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } }, 3765 // VMRHB 3766 { SystemZISD::MERGE_HIGH, 1, 3767 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } }, 3768 // VMRLG 3769 { SystemZISD::MERGE_LOW, 8, 3770 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } }, 3771 // VMRLF 3772 { SystemZISD::MERGE_LOW, 4, 3773 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } }, 3774 // VMRLH 3775 { SystemZISD::MERGE_LOW, 2, 3776 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } }, 3777 // VMRLB 3778 { SystemZISD::MERGE_LOW, 1, 3779 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } }, 3780 // VPKG 3781 { SystemZISD::PACK, 4, 3782 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } }, 3783 // VPKF 3784 { SystemZISD::PACK, 2, 3785 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } }, 3786 // VPKH 3787 { SystemZISD::PACK, 1, 3788 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } }, 3789 // VPDI V1, V2, 4 (low half of V1, high half of V2) 3790 { SystemZISD::PERMUTE_DWORDS, 4, 3791 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } }, 3792 // VPDI V1, V2, 1 (high half of V1, low half of V2) 3793 { SystemZISD::PERMUTE_DWORDS, 1, 3794 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } } 3795 }; 3796 3797 // Called after matching a vector shuffle against a particular pattern. 3798 // Both the original shuffle and the pattern have two vector operands. 3799 // OpNos[0] is the operand of the original shuffle that should be used for 3800 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything. 3801 // OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and 3802 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used 3803 // for operands 0 and 1 of the pattern. 3804 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) { 3805 if (OpNos[0] < 0) { 3806 if (OpNos[1] < 0) 3807 return false; 3808 OpNo0 = OpNo1 = OpNos[1]; 3809 } else if (OpNos[1] < 0) { 3810 OpNo0 = OpNo1 = OpNos[0]; 3811 } else { 3812 OpNo0 = OpNos[0]; 3813 OpNo1 = OpNos[1]; 3814 } 3815 return true; 3816 } 3817 3818 // Bytes is a VPERM-like permute vector, except that -1 is used for 3819 // undefined bytes. Return true if the VPERM can be implemented using P. 3820 // When returning true set OpNo0 to the VPERM operand that should be 3821 // used for operand 0 of P and likewise OpNo1 for operand 1 of P. 3822 // 3823 // For example, if swapping the VPERM operands allows P to match, OpNo0 3824 // will be 1 and OpNo1 will be 0. If instead Bytes only refers to one 3825 // operand, but rewriting it to use two duplicated operands allows it to 3826 // match P, then OpNo0 and OpNo1 will be the same. 3827 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P, 3828 unsigned &OpNo0, unsigned &OpNo1) { 3829 int OpNos[] = { -1, -1 }; 3830 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) { 3831 int Elt = Bytes[I]; 3832 if (Elt >= 0) { 3833 // Make sure that the two permute vectors use the same suboperand 3834 // byte number. Only the operand numbers (the high bits) are 3835 // allowed to differ. 3836 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1)) 3837 return false; 3838 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes; 3839 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes; 3840 // Make sure that the operand mappings are consistent with previous 3841 // elements. 3842 if (OpNos[ModelOpNo] == 1 - RealOpNo) 3843 return false; 3844 OpNos[ModelOpNo] = RealOpNo; 3845 } 3846 } 3847 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1); 3848 } 3849 3850 // As above, but search for a matching permute. 3851 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes, 3852 unsigned &OpNo0, unsigned &OpNo1) { 3853 for (auto &P : PermuteForms) 3854 if (matchPermute(Bytes, P, OpNo0, OpNo1)) 3855 return &P; 3856 return nullptr; 3857 } 3858 3859 // Bytes is a VPERM-like permute vector, except that -1 is used for 3860 // undefined bytes. This permute is an operand of an outer permute. 3861 // See whether redistributing the -1 bytes gives a shuffle that can be 3862 // implemented using P. If so, set Transform to a VPERM-like permute vector 3863 // that, when applied to the result of P, gives the original permute in Bytes. 3864 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes, 3865 const Permute &P, 3866 SmallVectorImpl<int> &Transform) { 3867 unsigned To = 0; 3868 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) { 3869 int Elt = Bytes[From]; 3870 if (Elt < 0) 3871 // Byte number From of the result is undefined. 3872 Transform[From] = -1; 3873 else { 3874 while (P.Bytes[To] != Elt) { 3875 To += 1; 3876 if (To == SystemZ::VectorBytes) 3877 return false; 3878 } 3879 Transform[From] = To; 3880 } 3881 } 3882 return true; 3883 } 3884 3885 // As above, but search for a matching permute. 3886 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes, 3887 SmallVectorImpl<int> &Transform) { 3888 for (auto &P : PermuteForms) 3889 if (matchDoublePermute(Bytes, P, Transform)) 3890 return &P; 3891 return nullptr; 3892 } 3893 3894 // Convert the mask of the given shuffle op into a byte-level mask, 3895 // as if it had type vNi8. 3896 static bool getVPermMask(SDValue ShuffleOp, 3897 SmallVectorImpl<int> &Bytes) { 3898 EVT VT = ShuffleOp.getValueType(); 3899 unsigned NumElements = VT.getVectorNumElements(); 3900 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize(); 3901 3902 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) { 3903 Bytes.resize(NumElements * BytesPerElement, -1); 3904 for (unsigned I = 0; I < NumElements; ++I) { 3905 int Index = VSN->getMaskElt(I); 3906 if (Index >= 0) 3907 for (unsigned J = 0; J < BytesPerElement; ++J) 3908 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J; 3909 } 3910 return true; 3911 } 3912 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() && 3913 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) { 3914 unsigned Index = ShuffleOp.getConstantOperandVal(1); 3915 Bytes.resize(NumElements * BytesPerElement, -1); 3916 for (unsigned I = 0; I < NumElements; ++I) 3917 for (unsigned J = 0; J < BytesPerElement; ++J) 3918 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J; 3919 return true; 3920 } 3921 return false; 3922 } 3923 3924 // Bytes is a VPERM-like permute vector, except that -1 is used for 3925 // undefined bytes. See whether bytes [Start, Start + BytesPerElement) of 3926 // the result come from a contiguous sequence of bytes from one input. 3927 // Set Base to the selector for the first byte if so. 3928 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start, 3929 unsigned BytesPerElement, int &Base) { 3930 Base = -1; 3931 for (unsigned I = 0; I < BytesPerElement; ++I) { 3932 if (Bytes[Start + I] >= 0) { 3933 unsigned Elem = Bytes[Start + I]; 3934 if (Base < 0) { 3935 Base = Elem - I; 3936 // Make sure the bytes would come from one input operand. 3937 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size()) 3938 return false; 3939 } else if (unsigned(Base) != Elem - I) 3940 return false; 3941 } 3942 } 3943 return true; 3944 } 3945 3946 // Bytes is a VPERM-like permute vector, except that -1 is used for 3947 // undefined bytes. Return true if it can be performed using VSLDI. 3948 // When returning true, set StartIndex to the shift amount and OpNo0 3949 // and OpNo1 to the VPERM operands that should be used as the first 3950 // and second shift operand respectively. 3951 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes, 3952 unsigned &StartIndex, unsigned &OpNo0, 3953 unsigned &OpNo1) { 3954 int OpNos[] = { -1, -1 }; 3955 int Shift = -1; 3956 for (unsigned I = 0; I < 16; ++I) { 3957 int Index = Bytes[I]; 3958 if (Index >= 0) { 3959 int ExpectedShift = (Index - I) % SystemZ::VectorBytes; 3960 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes; 3961 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes; 3962 if (Shift < 0) 3963 Shift = ExpectedShift; 3964 else if (Shift != ExpectedShift) 3965 return false; 3966 // Make sure that the operand mappings are consistent with previous 3967 // elements. 3968 if (OpNos[ModelOpNo] == 1 - RealOpNo) 3969 return false; 3970 OpNos[ModelOpNo] = RealOpNo; 3971 } 3972 } 3973 StartIndex = Shift; 3974 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1); 3975 } 3976 3977 // Create a node that performs P on operands Op0 and Op1, casting the 3978 // operands to the appropriate type. The type of the result is determined by P. 3979 static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL, 3980 const Permute &P, SDValue Op0, SDValue Op1) { 3981 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input 3982 // elements of a PACK are twice as wide as the outputs. 3983 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 : 3984 P.Opcode == SystemZISD::PACK ? P.Operand * 2 : 3985 P.Operand); 3986 // Cast both operands to the appropriate type. 3987 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8), 3988 SystemZ::VectorBytes / InBytes); 3989 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0); 3990 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1); 3991 SDValue Op; 3992 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) { 3993 SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32); 3994 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2); 3995 } else if (P.Opcode == SystemZISD::PACK) { 3996 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8), 3997 SystemZ::VectorBytes / P.Operand); 3998 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1); 3999 } else { 4000 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1); 4001 } 4002 return Op; 4003 } 4004 4005 // Bytes is a VPERM-like permute vector, except that -1 is used for 4006 // undefined bytes. Implement it on operands Ops[0] and Ops[1] using 4007 // VSLDI or VPERM. 4008 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL, 4009 SDValue *Ops, 4010 const SmallVectorImpl<int> &Bytes) { 4011 for (unsigned I = 0; I < 2; ++I) 4012 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]); 4013 4014 // First see whether VSLDI can be used. 4015 unsigned StartIndex, OpNo0, OpNo1; 4016 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1)) 4017 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0], 4018 Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32)); 4019 4020 // Fall back on VPERM. Construct an SDNode for the permute vector. 4021 SDValue IndexNodes[SystemZ::VectorBytes]; 4022 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) 4023 if (Bytes[I] >= 0) 4024 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32); 4025 else 4026 IndexNodes[I] = DAG.getUNDEF(MVT::i32); 4027 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes); 4028 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2); 4029 } 4030 4031 namespace { 4032 // Describes a general N-operand vector shuffle. 4033 struct GeneralShuffle { 4034 GeneralShuffle(EVT vt) : VT(vt) {} 4035 void addUndef(); 4036 bool add(SDValue, unsigned); 4037 SDValue getNode(SelectionDAG &, const SDLoc &); 4038 4039 // The operands of the shuffle. 4040 SmallVector<SDValue, SystemZ::VectorBytes> Ops; 4041 4042 // Index I is -1 if byte I of the result is undefined. Otherwise the 4043 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand 4044 // Bytes[I] / SystemZ::VectorBytes. 4045 SmallVector<int, SystemZ::VectorBytes> Bytes; 4046 4047 // The type of the shuffle result. 4048 EVT VT; 4049 }; 4050 } 4051 4052 // Add an extra undefined element to the shuffle. 4053 void GeneralShuffle::addUndef() { 4054 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize(); 4055 for (unsigned I = 0; I < BytesPerElement; ++I) 4056 Bytes.push_back(-1); 4057 } 4058 4059 // Add an extra element to the shuffle, taking it from element Elem of Op. 4060 // A null Op indicates a vector input whose value will be calculated later; 4061 // there is at most one such input per shuffle and it always has the same 4062 // type as the result. Aborts and returns false if the source vector elements 4063 // of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per 4064 // LLVM they become implicitly extended, but this is rare and not optimized. 4065 bool GeneralShuffle::add(SDValue Op, unsigned Elem) { 4066 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize(); 4067 4068 // The source vector can have wider elements than the result, 4069 // either through an explicit TRUNCATE or because of type legalization. 4070 // We want the least significant part. 4071 EVT FromVT = Op.getNode() ? Op.getValueType() : VT; 4072 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize(); 4073 4074 // Return false if the source elements are smaller than their destination 4075 // elements. 4076 if (FromBytesPerElement < BytesPerElement) 4077 return false; 4078 4079 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes + 4080 (FromBytesPerElement - BytesPerElement)); 4081 4082 // Look through things like shuffles and bitcasts. 4083 while (Op.getNode()) { 4084 if (Op.getOpcode() == ISD::BITCAST) 4085 Op = Op.getOperand(0); 4086 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) { 4087 // See whether the bytes we need come from a contiguous part of one 4088 // operand. 4089 SmallVector<int, SystemZ::VectorBytes> OpBytes; 4090 if (!getVPermMask(Op, OpBytes)) 4091 break; 4092 int NewByte; 4093 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte)) 4094 break; 4095 if (NewByte < 0) { 4096 addUndef(); 4097 return true; 4098 } 4099 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes); 4100 Byte = unsigned(NewByte) % SystemZ::VectorBytes; 4101 } else if (Op.isUndef()) { 4102 addUndef(); 4103 return true; 4104 } else 4105 break; 4106 } 4107 4108 // Make sure that the source of the extraction is in Ops. 4109 unsigned OpNo = 0; 4110 for (; OpNo < Ops.size(); ++OpNo) 4111 if (Ops[OpNo] == Op) 4112 break; 4113 if (OpNo == Ops.size()) 4114 Ops.push_back(Op); 4115 4116 // Add the element to Bytes. 4117 unsigned Base = OpNo * SystemZ::VectorBytes + Byte; 4118 for (unsigned I = 0; I < BytesPerElement; ++I) 4119 Bytes.push_back(Base + I); 4120 4121 return true; 4122 } 4123 4124 // Return SDNodes for the completed shuffle. 4125 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) { 4126 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector"); 4127 4128 if (Ops.size() == 0) 4129 return DAG.getUNDEF(VT); 4130 4131 // Make sure that there are at least two shuffle operands. 4132 if (Ops.size() == 1) 4133 Ops.push_back(DAG.getUNDEF(MVT::v16i8)); 4134 4135 // Create a tree of shuffles, deferring root node until after the loop. 4136 // Try to redistribute the undefined elements of non-root nodes so that 4137 // the non-root shuffles match something like a pack or merge, then adjust 4138 // the parent node's permute vector to compensate for the new order. 4139 // Among other things, this copes with vectors like <2 x i16> that were 4140 // padded with undefined elements during type legalization. 4141 // 4142 // In the best case this redistribution will lead to the whole tree 4143 // using packs and merges. It should rarely be a loss in other cases. 4144 unsigned Stride = 1; 4145 for (; Stride * 2 < Ops.size(); Stride *= 2) { 4146 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) { 4147 SDValue SubOps[] = { Ops[I], Ops[I + Stride] }; 4148 4149 // Create a mask for just these two operands. 4150 SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes); 4151 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) { 4152 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes; 4153 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes; 4154 if (OpNo == I) 4155 NewBytes[J] = Byte; 4156 else if (OpNo == I + Stride) 4157 NewBytes[J] = SystemZ::VectorBytes + Byte; 4158 else 4159 NewBytes[J] = -1; 4160 } 4161 // See if it would be better to reorganize NewMask to avoid using VPERM. 4162 SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes); 4163 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) { 4164 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]); 4165 // Applying NewBytesMap to Ops[I] gets back to NewBytes. 4166 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) { 4167 if (NewBytes[J] >= 0) { 4168 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes && 4169 "Invalid double permute"); 4170 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J]; 4171 } else 4172 assert(NewBytesMap[J] < 0 && "Invalid double permute"); 4173 } 4174 } else { 4175 // Just use NewBytes on the operands. 4176 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes); 4177 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) 4178 if (NewBytes[J] >= 0) 4179 Bytes[J] = I * SystemZ::VectorBytes + J; 4180 } 4181 } 4182 } 4183 4184 // Now we just have 2 inputs. Put the second operand in Ops[1]. 4185 if (Stride > 1) { 4186 Ops[1] = Ops[Stride]; 4187 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) 4188 if (Bytes[I] >= int(SystemZ::VectorBytes)) 4189 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes; 4190 } 4191 4192 // Look for an instruction that can do the permute without resorting 4193 // to VPERM. 4194 unsigned OpNo0, OpNo1; 4195 SDValue Op; 4196 if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1)) 4197 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]); 4198 else 4199 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes); 4200 return DAG.getNode(ISD::BITCAST, DL, VT, Op); 4201 } 4202 4203 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion. 4204 static bool isScalarToVector(SDValue Op) { 4205 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I) 4206 if (!Op.getOperand(I).isUndef()) 4207 return false; 4208 return true; 4209 } 4210 4211 // Return a vector of type VT that contains Value in the first element. 4212 // The other elements don't matter. 4213 static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT, 4214 SDValue Value) { 4215 // If we have a constant, replicate it to all elements and let the 4216 // BUILD_VECTOR lowering take care of it. 4217 if (Value.getOpcode() == ISD::Constant || 4218 Value.getOpcode() == ISD::ConstantFP) { 4219 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value); 4220 return DAG.getBuildVector(VT, DL, Ops); 4221 } 4222 if (Value.isUndef()) 4223 return DAG.getUNDEF(VT); 4224 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value); 4225 } 4226 4227 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in 4228 // element 1. Used for cases in which replication is cheap. 4229 static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT, 4230 SDValue Op0, SDValue Op1) { 4231 if (Op0.isUndef()) { 4232 if (Op1.isUndef()) 4233 return DAG.getUNDEF(VT); 4234 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1); 4235 } 4236 if (Op1.isUndef()) 4237 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0); 4238 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT, 4239 buildScalarToVector(DAG, DL, VT, Op0), 4240 buildScalarToVector(DAG, DL, VT, Op1)); 4241 } 4242 4243 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64 4244 // vector for them. 4245 static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0, 4246 SDValue Op1) { 4247 if (Op0.isUndef() && Op1.isUndef()) 4248 return DAG.getUNDEF(MVT::v2i64); 4249 // If one of the two inputs is undefined then replicate the other one, 4250 // in order to avoid using another register unnecessarily. 4251 if (Op0.isUndef()) 4252 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1); 4253 else if (Op1.isUndef()) 4254 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 4255 else { 4256 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 4257 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1); 4258 } 4259 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1); 4260 } 4261 4262 // Try to represent constant BUILD_VECTOR node BVN using a BYTE MASK style 4263 // mask. Store the mask value in Mask on success. 4264 bool SystemZTargetLowering:: 4265 tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) { 4266 EVT ElemVT = BVN->getValueType(0).getVectorElementType(); 4267 unsigned BytesPerElement = ElemVT.getStoreSize(); 4268 for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) { 4269 SDValue Op = BVN->getOperand(I); 4270 if (!Op.isUndef()) { 4271 uint64_t Value; 4272 if (Op.getOpcode() == ISD::Constant) 4273 Value = cast<ConstantSDNode>(Op)->getZExtValue(); 4274 else if (Op.getOpcode() == ISD::ConstantFP) 4275 Value = (cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt() 4276 .getZExtValue()); 4277 else 4278 return false; 4279 for (unsigned J = 0; J < BytesPerElement; ++J) { 4280 uint64_t Byte = (Value >> (J * 8)) & 0xff; 4281 if (Byte == 0xff) 4282 Mask |= 1ULL << ((E - I - 1) * BytesPerElement + J); 4283 else if (Byte != 0) 4284 return false; 4285 } 4286 } 4287 } 4288 return true; 4289 } 4290 4291 // Try to load a vector constant in which BitsPerElement-bit value Value 4292 // is replicated to fill the vector. VT is the type of the resulting 4293 // constant, which may have elements of a different size from BitsPerElement. 4294 // Return the SDValue of the constant on success, otherwise return 4295 // an empty value. 4296 static SDValue tryBuildVectorReplicate(SelectionDAG &DAG, 4297 const SystemZInstrInfo *TII, 4298 const SDLoc &DL, EVT VT, uint64_t Value, 4299 unsigned BitsPerElement) { 4300 // Signed 16-bit values can be replicated using VREPI. 4301 // Mark the constants as opaque or DAGCombiner will convert back to 4302 // BUILD_VECTOR. 4303 int64_t SignedValue = SignExtend64(Value, BitsPerElement); 4304 if (isInt<16>(SignedValue)) { 4305 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement), 4306 SystemZ::VectorBits / BitsPerElement); 4307 SDValue Op = DAG.getNode( 4308 SystemZISD::REPLICATE, DL, VecVT, 4309 DAG.getConstant(SignedValue, DL, MVT::i32, false, true /*isOpaque*/)); 4310 return DAG.getNode(ISD::BITCAST, DL, VT, Op); 4311 } 4312 // See whether rotating the constant left some N places gives a value that 4313 // is one less than a power of 2 (i.e. all zeros followed by all ones). 4314 // If so we can use VGM. 4315 unsigned Start, End; 4316 if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) { 4317 // isRxSBGMask returns the bit numbers for a full 64-bit value, 4318 // with 0 denoting 1 << 63 and 63 denoting 1. Convert them to 4319 // bit numbers for an BitsPerElement value, so that 0 denotes 4320 // 1 << (BitsPerElement-1). 4321 Start -= 64 - BitsPerElement; 4322 End -= 64 - BitsPerElement; 4323 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement), 4324 SystemZ::VectorBits / BitsPerElement); 4325 SDValue Op = DAG.getNode( 4326 SystemZISD::ROTATE_MASK, DL, VecVT, 4327 DAG.getConstant(Start, DL, MVT::i32, false, true /*isOpaque*/), 4328 DAG.getConstant(End, DL, MVT::i32, false, true /*isOpaque*/)); 4329 return DAG.getNode(ISD::BITCAST, DL, VT, Op); 4330 } 4331 return SDValue(); 4332 } 4333 4334 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually 4335 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for 4336 // the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR 4337 // would benefit from this representation and return it if so. 4338 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG, 4339 BuildVectorSDNode *BVN) { 4340 EVT VT = BVN->getValueType(0); 4341 unsigned NumElements = VT.getVectorNumElements(); 4342 4343 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation 4344 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still 4345 // need a BUILD_VECTOR, add an additional placeholder operand for that 4346 // BUILD_VECTOR and store its operands in ResidueOps. 4347 GeneralShuffle GS(VT); 4348 SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps; 4349 bool FoundOne = false; 4350 for (unsigned I = 0; I < NumElements; ++I) { 4351 SDValue Op = BVN->getOperand(I); 4352 if (Op.getOpcode() == ISD::TRUNCATE) 4353 Op = Op.getOperand(0); 4354 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 4355 Op.getOperand(1).getOpcode() == ISD::Constant) { 4356 unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4357 if (!GS.add(Op.getOperand(0), Elem)) 4358 return SDValue(); 4359 FoundOne = true; 4360 } else if (Op.isUndef()) { 4361 GS.addUndef(); 4362 } else { 4363 if (!GS.add(SDValue(), ResidueOps.size())) 4364 return SDValue(); 4365 ResidueOps.push_back(BVN->getOperand(I)); 4366 } 4367 } 4368 4369 // Nothing to do if there are no EXTRACT_VECTOR_ELTs. 4370 if (!FoundOne) 4371 return SDValue(); 4372 4373 // Create the BUILD_VECTOR for the remaining elements, if any. 4374 if (!ResidueOps.empty()) { 4375 while (ResidueOps.size() < NumElements) 4376 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType())); 4377 for (auto &Op : GS.Ops) { 4378 if (!Op.getNode()) { 4379 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps); 4380 break; 4381 } 4382 } 4383 } 4384 return GS.getNode(DAG, SDLoc(BVN)); 4385 } 4386 4387 // Combine GPR scalar values Elems into a vector of type VT. 4388 static SDValue buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT, 4389 SmallVectorImpl<SDValue> &Elems) { 4390 // See whether there is a single replicated value. 4391 SDValue Single; 4392 unsigned int NumElements = Elems.size(); 4393 unsigned int Count = 0; 4394 for (auto Elem : Elems) { 4395 if (!Elem.isUndef()) { 4396 if (!Single.getNode()) 4397 Single = Elem; 4398 else if (Elem != Single) { 4399 Single = SDValue(); 4400 break; 4401 } 4402 Count += 1; 4403 } 4404 } 4405 // There are three cases here: 4406 // 4407 // - if the only defined element is a loaded one, the best sequence 4408 // is a replicating load. 4409 // 4410 // - otherwise, if the only defined element is an i64 value, we will 4411 // end up with the same VLVGP sequence regardless of whether we short-cut 4412 // for replication or fall through to the later code. 4413 // 4414 // - otherwise, if the only defined element is an i32 or smaller value, 4415 // we would need 2 instructions to replicate it: VLVGP followed by VREPx. 4416 // This is only a win if the single defined element is used more than once. 4417 // In other cases we're better off using a single VLVGx. 4418 if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD)) 4419 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single); 4420 4421 // If all elements are loads, use VLREP/VLEs (below). 4422 bool AllLoads = true; 4423 for (auto Elem : Elems) 4424 if (Elem.getOpcode() != ISD::LOAD || cast<LoadSDNode>(Elem)->isIndexed()) { 4425 AllLoads = false; 4426 break; 4427 } 4428 4429 // The best way of building a v2i64 from two i64s is to use VLVGP. 4430 if (VT == MVT::v2i64 && !AllLoads) 4431 return joinDwords(DAG, DL, Elems[0], Elems[1]); 4432 4433 // Use a 64-bit merge high to combine two doubles. 4434 if (VT == MVT::v2f64 && !AllLoads) 4435 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]); 4436 4437 // Build v4f32 values directly from the FPRs: 4438 // 4439 // <Axxx> <Bxxx> <Cxxxx> <Dxxx> 4440 // V V VMRHF 4441 // <ABxx> <CDxx> 4442 // V VMRHG 4443 // <ABCD> 4444 if (VT == MVT::v4f32 && !AllLoads) { 4445 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]); 4446 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]); 4447 // Avoid unnecessary undefs by reusing the other operand. 4448 if (Op01.isUndef()) 4449 Op01 = Op23; 4450 else if (Op23.isUndef()) 4451 Op23 = Op01; 4452 // Merging identical replications is a no-op. 4453 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23) 4454 return Op01; 4455 Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01); 4456 Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23); 4457 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH, 4458 DL, MVT::v2i64, Op01, Op23); 4459 return DAG.getNode(ISD::BITCAST, DL, VT, Op); 4460 } 4461 4462 // Collect the constant terms. 4463 SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue()); 4464 SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false); 4465 4466 unsigned NumConstants = 0; 4467 for (unsigned I = 0; I < NumElements; ++I) { 4468 SDValue Elem = Elems[I]; 4469 if (Elem.getOpcode() == ISD::Constant || 4470 Elem.getOpcode() == ISD::ConstantFP) { 4471 NumConstants += 1; 4472 Constants[I] = Elem; 4473 Done[I] = true; 4474 } 4475 } 4476 // If there was at least one constant, fill in the other elements of 4477 // Constants with undefs to get a full vector constant and use that 4478 // as the starting point. 4479 SDValue Result; 4480 SDValue ReplicatedVal; 4481 if (NumConstants > 0) { 4482 for (unsigned I = 0; I < NumElements; ++I) 4483 if (!Constants[I].getNode()) 4484 Constants[I] = DAG.getUNDEF(Elems[I].getValueType()); 4485 Result = DAG.getBuildVector(VT, DL, Constants); 4486 } else { 4487 // Otherwise try to use VLREP or VLVGP to start the sequence in order to 4488 // avoid a false dependency on any previous contents of the vector 4489 // register. 4490 4491 // Use a VLREP if at least one element is a load. Make sure to replicate 4492 // the load with the most elements having its value. 4493 std::map<const SDNode*, unsigned> UseCounts; 4494 SDNode *LoadMaxUses = nullptr; 4495 for (unsigned I = 0; I < NumElements; ++I) 4496 if (Elems[I].getOpcode() == ISD::LOAD && 4497 cast<LoadSDNode>(Elems[I])->isUnindexed()) { 4498 SDNode *Ld = Elems[I].getNode(); 4499 UseCounts[Ld]++; 4500 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < UseCounts[Ld]) 4501 LoadMaxUses = Ld; 4502 } 4503 if (LoadMaxUses != nullptr) { 4504 ReplicatedVal = SDValue(LoadMaxUses, 0); 4505 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal); 4506 } else { 4507 // Try to use VLVGP. 4508 unsigned I1 = NumElements / 2 - 1; 4509 unsigned I2 = NumElements - 1; 4510 bool Def1 = !Elems[I1].isUndef(); 4511 bool Def2 = !Elems[I2].isUndef(); 4512 if (Def1 || Def2) { 4513 SDValue Elem1 = Elems[Def1 ? I1 : I2]; 4514 SDValue Elem2 = Elems[Def2 ? I2 : I1]; 4515 Result = DAG.getNode(ISD::BITCAST, DL, VT, 4516 joinDwords(DAG, DL, Elem1, Elem2)); 4517 Done[I1] = true; 4518 Done[I2] = true; 4519 } else 4520 Result = DAG.getUNDEF(VT); 4521 } 4522 } 4523 4524 // Use VLVGx to insert the other elements. 4525 for (unsigned I = 0; I < NumElements; ++I) 4526 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal) 4527 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I], 4528 DAG.getConstant(I, DL, MVT::i32)); 4529 return Result; 4530 } 4531 4532 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op, 4533 SelectionDAG &DAG) const { 4534 const SystemZInstrInfo *TII = 4535 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 4536 auto *BVN = cast<BuildVectorSDNode>(Op.getNode()); 4537 SDLoc DL(Op); 4538 EVT VT = Op.getValueType(); 4539 4540 if (BVN->isConstant()) { 4541 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally- 4542 // preferred way of creating all-zero and all-one vectors so give it 4543 // priority over other methods below. 4544 uint64_t Mask; 4545 if (ISD::isBuildVectorAllZeros(Op.getNode()) || 4546 ISD::isBuildVectorAllOnes(Op.getNode()) || 4547 (VT.isInteger() && tryBuildVectorByteMask(BVN, Mask))) 4548 return Op; 4549 4550 // Try using some form of replication. 4551 APInt SplatBits, SplatUndef; 4552 unsigned SplatBitSize; 4553 bool HasAnyUndefs; 4554 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 4555 8, true) && 4556 SplatBitSize <= 64) { 4557 // First try assuming that any undefined bits above the highest set bit 4558 // and below the lowest set bit are 1s. This increases the likelihood of 4559 // being able to use a sign-extended element value in VECTOR REPLICATE 4560 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK. 4561 uint64_t SplatBitsZ = SplatBits.getZExtValue(); 4562 uint64_t SplatUndefZ = SplatUndef.getZExtValue(); 4563 uint64_t Lower = (SplatUndefZ 4564 & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1)); 4565 uint64_t Upper = (SplatUndefZ 4566 & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1)); 4567 uint64_t Value = SplatBitsZ | Upper | Lower; 4568 SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, 4569 SplatBitSize); 4570 if (Op.getNode()) 4571 return Op; 4572 4573 // Now try assuming that any undefined bits between the first and 4574 // last defined set bits are set. This increases the chances of 4575 // using a non-wraparound mask. 4576 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower; 4577 Value = SplatBitsZ | Middle; 4578 Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize); 4579 if (Op.getNode()) 4580 return Op; 4581 } 4582 4583 // Fall back to loading it from memory. 4584 return SDValue(); 4585 } 4586 4587 // See if we should use shuffles to construct the vector from other vectors. 4588 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN)) 4589 return Res; 4590 4591 // Detect SCALAR_TO_VECTOR conversions. 4592 if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op)) 4593 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0)); 4594 4595 // Otherwise use buildVector to build the vector up from GPRs. 4596 unsigned NumElements = Op.getNumOperands(); 4597 SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements); 4598 for (unsigned I = 0; I < NumElements; ++I) 4599 Ops[I] = Op.getOperand(I); 4600 return buildVector(DAG, DL, VT, Ops); 4601 } 4602 4603 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4604 SelectionDAG &DAG) const { 4605 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode()); 4606 SDLoc DL(Op); 4607 EVT VT = Op.getValueType(); 4608 unsigned NumElements = VT.getVectorNumElements(); 4609 4610 if (VSN->isSplat()) { 4611 SDValue Op0 = Op.getOperand(0); 4612 unsigned Index = VSN->getSplatIndex(); 4613 assert(Index < VT.getVectorNumElements() && 4614 "Splat index should be defined and in first operand"); 4615 // See whether the value we're splatting is directly available as a scalar. 4616 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) || 4617 Op0.getOpcode() == ISD::BUILD_VECTOR) 4618 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index)); 4619 // Otherwise keep it as a vector-to-vector operation. 4620 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0), 4621 DAG.getConstant(Index, DL, MVT::i32)); 4622 } 4623 4624 GeneralShuffle GS(VT); 4625 for (unsigned I = 0; I < NumElements; ++I) { 4626 int Elt = VSN->getMaskElt(I); 4627 if (Elt < 0) 4628 GS.addUndef(); 4629 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements), 4630 unsigned(Elt) % NumElements)) 4631 return SDValue(); 4632 } 4633 return GS.getNode(DAG, SDLoc(VSN)); 4634 } 4635 4636 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op, 4637 SelectionDAG &DAG) const { 4638 SDLoc DL(Op); 4639 // Just insert the scalar into element 0 of an undefined vector. 4640 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, 4641 Op.getValueType(), DAG.getUNDEF(Op.getValueType()), 4642 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32)); 4643 } 4644 4645 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4646 SelectionDAG &DAG) const { 4647 // Handle insertions of floating-point values. 4648 SDLoc DL(Op); 4649 SDValue Op0 = Op.getOperand(0); 4650 SDValue Op1 = Op.getOperand(1); 4651 SDValue Op2 = Op.getOperand(2); 4652 EVT VT = Op.getValueType(); 4653 4654 // Insertions into constant indices of a v2f64 can be done using VPDI. 4655 // However, if the inserted value is a bitcast or a constant then it's 4656 // better to use GPRs, as below. 4657 if (VT == MVT::v2f64 && 4658 Op1.getOpcode() != ISD::BITCAST && 4659 Op1.getOpcode() != ISD::ConstantFP && 4660 Op2.getOpcode() == ISD::Constant) { 4661 uint64_t Index = cast<ConstantSDNode>(Op2)->getZExtValue(); 4662 unsigned Mask = VT.getVectorNumElements() - 1; 4663 if (Index <= Mask) 4664 return Op; 4665 } 4666 4667 // Otherwise bitcast to the equivalent integer form and insert via a GPR. 4668 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits()); 4669 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements()); 4670 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT, 4671 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), 4672 DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2); 4673 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 4674 } 4675 4676 SDValue 4677 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4678 SelectionDAG &DAG) const { 4679 // Handle extractions of floating-point values. 4680 SDLoc DL(Op); 4681 SDValue Op0 = Op.getOperand(0); 4682 SDValue Op1 = Op.getOperand(1); 4683 EVT VT = Op.getValueType(); 4684 EVT VecVT = Op0.getValueType(); 4685 4686 // Extractions of constant indices can be done directly. 4687 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) { 4688 uint64_t Index = CIndexN->getZExtValue(); 4689 unsigned Mask = VecVT.getVectorNumElements() - 1; 4690 if (Index <= Mask) 4691 return Op; 4692 } 4693 4694 // Otherwise bitcast to the equivalent integer form and extract via a GPR. 4695 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits()); 4696 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements()); 4697 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT, 4698 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1); 4699 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 4700 } 4701 4702 SDValue 4703 SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG, 4704 unsigned UnpackHigh) const { 4705 SDValue PackedOp = Op.getOperand(0); 4706 EVT OutVT = Op.getValueType(); 4707 EVT InVT = PackedOp.getValueType(); 4708 unsigned ToBits = OutVT.getScalarSizeInBits(); 4709 unsigned FromBits = InVT.getScalarSizeInBits(); 4710 do { 4711 FromBits *= 2; 4712 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits), 4713 SystemZ::VectorBits / FromBits); 4714 PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp); 4715 } while (FromBits != ToBits); 4716 return PackedOp; 4717 } 4718 4719 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG, 4720 unsigned ByScalar) const { 4721 // Look for cases where a vector shift can use the *_BY_SCALAR form. 4722 SDValue Op0 = Op.getOperand(0); 4723 SDValue Op1 = Op.getOperand(1); 4724 SDLoc DL(Op); 4725 EVT VT = Op.getValueType(); 4726 unsigned ElemBitSize = VT.getScalarSizeInBits(); 4727 4728 // See whether the shift vector is a splat represented as BUILD_VECTOR. 4729 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) { 4730 APInt SplatBits, SplatUndef; 4731 unsigned SplatBitSize; 4732 bool HasAnyUndefs; 4733 // Check for constant splats. Use ElemBitSize as the minimum element 4734 // width and reject splats that need wider elements. 4735 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 4736 ElemBitSize, true) && 4737 SplatBitSize == ElemBitSize) { 4738 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff, 4739 DL, MVT::i32); 4740 return DAG.getNode(ByScalar, DL, VT, Op0, Shift); 4741 } 4742 // Check for variable splats. 4743 BitVector UndefElements; 4744 SDValue Splat = BVN->getSplatValue(&UndefElements); 4745 if (Splat) { 4746 // Since i32 is the smallest legal type, we either need a no-op 4747 // or a truncation. 4748 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat); 4749 return DAG.getNode(ByScalar, DL, VT, Op0, Shift); 4750 } 4751 } 4752 4753 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR, 4754 // and the shift amount is directly available in a GPR. 4755 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) { 4756 if (VSN->isSplat()) { 4757 SDValue VSNOp0 = VSN->getOperand(0); 4758 unsigned Index = VSN->getSplatIndex(); 4759 assert(Index < VT.getVectorNumElements() && 4760 "Splat index should be defined and in first operand"); 4761 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) || 4762 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) { 4763 // Since i32 is the smallest legal type, we either need a no-op 4764 // or a truncation. 4765 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, 4766 VSNOp0.getOperand(Index)); 4767 return DAG.getNode(ByScalar, DL, VT, Op0, Shift); 4768 } 4769 } 4770 } 4771 4772 // Otherwise just treat the current form as legal. 4773 return Op; 4774 } 4775 4776 SDValue SystemZTargetLowering::LowerOperation(SDValue Op, 4777 SelectionDAG &DAG) const { 4778 switch (Op.getOpcode()) { 4779 case ISD::FRAMEADDR: 4780 return lowerFRAMEADDR(Op, DAG); 4781 case ISD::RETURNADDR: 4782 return lowerRETURNADDR(Op, DAG); 4783 case ISD::BR_CC: 4784 return lowerBR_CC(Op, DAG); 4785 case ISD::SELECT_CC: 4786 return lowerSELECT_CC(Op, DAG); 4787 case ISD::SETCC: 4788 return lowerSETCC(Op, DAG); 4789 case ISD::GlobalAddress: 4790 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG); 4791 case ISD::GlobalTLSAddress: 4792 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG); 4793 case ISD::BlockAddress: 4794 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG); 4795 case ISD::JumpTable: 4796 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG); 4797 case ISD::ConstantPool: 4798 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG); 4799 case ISD::BITCAST: 4800 return lowerBITCAST(Op, DAG); 4801 case ISD::VASTART: 4802 return lowerVASTART(Op, DAG); 4803 case ISD::VACOPY: 4804 return lowerVACOPY(Op, DAG); 4805 case ISD::DYNAMIC_STACKALLOC: 4806 return lowerDYNAMIC_STACKALLOC(Op, DAG); 4807 case ISD::GET_DYNAMIC_AREA_OFFSET: 4808 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 4809 case ISD::SMUL_LOHI: 4810 return lowerSMUL_LOHI(Op, DAG); 4811 case ISD::UMUL_LOHI: 4812 return lowerUMUL_LOHI(Op, DAG); 4813 case ISD::SDIVREM: 4814 return lowerSDIVREM(Op, DAG); 4815 case ISD::UDIVREM: 4816 return lowerUDIVREM(Op, DAG); 4817 case ISD::SADDO: 4818 case ISD::SSUBO: 4819 case ISD::UADDO: 4820 case ISD::USUBO: 4821 return lowerXALUO(Op, DAG); 4822 case ISD::ADDCARRY: 4823 case ISD::SUBCARRY: 4824 return lowerADDSUBCARRY(Op, DAG); 4825 case ISD::OR: 4826 return lowerOR(Op, DAG); 4827 case ISD::CTPOP: 4828 return lowerCTPOP(Op, DAG); 4829 case ISD::ATOMIC_FENCE: 4830 return lowerATOMIC_FENCE(Op, DAG); 4831 case ISD::ATOMIC_SWAP: 4832 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW); 4833 case ISD::ATOMIC_STORE: 4834 return lowerATOMIC_STORE(Op, DAG); 4835 case ISD::ATOMIC_LOAD: 4836 return lowerATOMIC_LOAD(Op, DAG); 4837 case ISD::ATOMIC_LOAD_ADD: 4838 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD); 4839 case ISD::ATOMIC_LOAD_SUB: 4840 return lowerATOMIC_LOAD_SUB(Op, DAG); 4841 case ISD::ATOMIC_LOAD_AND: 4842 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND); 4843 case ISD::ATOMIC_LOAD_OR: 4844 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR); 4845 case ISD::ATOMIC_LOAD_XOR: 4846 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR); 4847 case ISD::ATOMIC_LOAD_NAND: 4848 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND); 4849 case ISD::ATOMIC_LOAD_MIN: 4850 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN); 4851 case ISD::ATOMIC_LOAD_MAX: 4852 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX); 4853 case ISD::ATOMIC_LOAD_UMIN: 4854 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN); 4855 case ISD::ATOMIC_LOAD_UMAX: 4856 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX); 4857 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4858 return lowerATOMIC_CMP_SWAP(Op, DAG); 4859 case ISD::STACKSAVE: 4860 return lowerSTACKSAVE(Op, DAG); 4861 case ISD::STACKRESTORE: 4862 return lowerSTACKRESTORE(Op, DAG); 4863 case ISD::PREFETCH: 4864 return lowerPREFETCH(Op, DAG); 4865 case ISD::INTRINSIC_W_CHAIN: 4866 return lowerINTRINSIC_W_CHAIN(Op, DAG); 4867 case ISD::INTRINSIC_WO_CHAIN: 4868 return lowerINTRINSIC_WO_CHAIN(Op, DAG); 4869 case ISD::BUILD_VECTOR: 4870 return lowerBUILD_VECTOR(Op, DAG); 4871 case ISD::VECTOR_SHUFFLE: 4872 return lowerVECTOR_SHUFFLE(Op, DAG); 4873 case ISD::SCALAR_TO_VECTOR: 4874 return lowerSCALAR_TO_VECTOR(Op, DAG); 4875 case ISD::INSERT_VECTOR_ELT: 4876 return lowerINSERT_VECTOR_ELT(Op, DAG); 4877 case ISD::EXTRACT_VECTOR_ELT: 4878 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4879 case ISD::SIGN_EXTEND_VECTOR_INREG: 4880 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACK_HIGH); 4881 case ISD::ZERO_EXTEND_VECTOR_INREG: 4882 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACKL_HIGH); 4883 case ISD::SHL: 4884 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR); 4885 case ISD::SRL: 4886 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR); 4887 case ISD::SRA: 4888 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR); 4889 default: 4890 llvm_unreachable("Unexpected node to lower"); 4891 } 4892 } 4893 4894 // Lower operations with invalid operand or result types (currently used 4895 // only for 128-bit integer types). 4896 4897 static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In) { 4898 SDLoc DL(In); 4899 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, In, 4900 DAG.getIntPtrConstant(0, DL)); 4901 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, In, 4902 DAG.getIntPtrConstant(1, DL)); 4903 SDNode *Pair = DAG.getMachineNode(SystemZ::PAIR128, DL, 4904 MVT::Untyped, Hi, Lo); 4905 return SDValue(Pair, 0); 4906 } 4907 4908 static SDValue lowerGR128ToI128(SelectionDAG &DAG, SDValue In) { 4909 SDLoc DL(In); 4910 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64, 4911 DL, MVT::i64, In); 4912 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64, 4913 DL, MVT::i64, In); 4914 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi); 4915 } 4916 4917 void 4918 SystemZTargetLowering::LowerOperationWrapper(SDNode *N, 4919 SmallVectorImpl<SDValue> &Results, 4920 SelectionDAG &DAG) const { 4921 switch (N->getOpcode()) { 4922 case ISD::ATOMIC_LOAD: { 4923 SDLoc DL(N); 4924 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::Other); 4925 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) }; 4926 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 4927 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128, 4928 DL, Tys, Ops, MVT::i128, MMO); 4929 Results.push_back(lowerGR128ToI128(DAG, Res)); 4930 Results.push_back(Res.getValue(1)); 4931 break; 4932 } 4933 case ISD::ATOMIC_STORE: { 4934 SDLoc DL(N); 4935 SDVTList Tys = DAG.getVTList(MVT::Other); 4936 SDValue Ops[] = { N->getOperand(0), 4937 lowerI128ToGR128(DAG, N->getOperand(2)), 4938 N->getOperand(1) }; 4939 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 4940 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128, 4941 DL, Tys, Ops, MVT::i128, MMO); 4942 // We have to enforce sequential consistency by performing a 4943 // serialization operation after the store. 4944 if (cast<AtomicSDNode>(N)->getOrdering() == 4945 AtomicOrdering::SequentiallyConsistent) 4946 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, 4947 MVT::Other, Res), 0); 4948 Results.push_back(Res); 4949 break; 4950 } 4951 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: { 4952 SDLoc DL(N); 4953 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other); 4954 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), 4955 lowerI128ToGR128(DAG, N->getOperand(2)), 4956 lowerI128ToGR128(DAG, N->getOperand(3)) }; 4957 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 4958 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128, 4959 DL, Tys, Ops, MVT::i128, MMO); 4960 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1), 4961 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ); 4962 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1)); 4963 Results.push_back(lowerGR128ToI128(DAG, Res)); 4964 Results.push_back(Success); 4965 Results.push_back(Res.getValue(2)); 4966 break; 4967 } 4968 default: 4969 llvm_unreachable("Unexpected node to lower"); 4970 } 4971 } 4972 4973 void 4974 SystemZTargetLowering::ReplaceNodeResults(SDNode *N, 4975 SmallVectorImpl<SDValue> &Results, 4976 SelectionDAG &DAG) const { 4977 return LowerOperationWrapper(N, Results, DAG); 4978 } 4979 4980 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const { 4981 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME 4982 switch ((SystemZISD::NodeType)Opcode) { 4983 case SystemZISD::FIRST_NUMBER: break; 4984 OPCODE(RET_FLAG); 4985 OPCODE(CALL); 4986 OPCODE(SIBCALL); 4987 OPCODE(TLS_GDCALL); 4988 OPCODE(TLS_LDCALL); 4989 OPCODE(PCREL_WRAPPER); 4990 OPCODE(PCREL_OFFSET); 4991 OPCODE(IABS); 4992 OPCODE(ICMP); 4993 OPCODE(FCMP); 4994 OPCODE(TM); 4995 OPCODE(BR_CCMASK); 4996 OPCODE(SELECT_CCMASK); 4997 OPCODE(ADJDYNALLOC); 4998 OPCODE(POPCNT); 4999 OPCODE(SMUL_LOHI); 5000 OPCODE(UMUL_LOHI); 5001 OPCODE(SDIVREM); 5002 OPCODE(UDIVREM); 5003 OPCODE(SADDO); 5004 OPCODE(SSUBO); 5005 OPCODE(UADDO); 5006 OPCODE(USUBO); 5007 OPCODE(ADDCARRY); 5008 OPCODE(SUBCARRY); 5009 OPCODE(GET_CCMASK); 5010 OPCODE(MVC); 5011 OPCODE(MVC_LOOP); 5012 OPCODE(NC); 5013 OPCODE(NC_LOOP); 5014 OPCODE(OC); 5015 OPCODE(OC_LOOP); 5016 OPCODE(XC); 5017 OPCODE(XC_LOOP); 5018 OPCODE(CLC); 5019 OPCODE(CLC_LOOP); 5020 OPCODE(STPCPY); 5021 OPCODE(STRCMP); 5022 OPCODE(SEARCH_STRING); 5023 OPCODE(IPM); 5024 OPCODE(MEMBARRIER); 5025 OPCODE(TBEGIN); 5026 OPCODE(TBEGIN_NOFLOAT); 5027 OPCODE(TEND); 5028 OPCODE(ROTATE_MASK); 5029 OPCODE(REPLICATE); 5030 OPCODE(JOIN_DWORDS); 5031 OPCODE(SPLAT); 5032 OPCODE(MERGE_HIGH); 5033 OPCODE(MERGE_LOW); 5034 OPCODE(SHL_DOUBLE); 5035 OPCODE(PERMUTE_DWORDS); 5036 OPCODE(PERMUTE); 5037 OPCODE(PACK); 5038 OPCODE(PACKS_CC); 5039 OPCODE(PACKLS_CC); 5040 OPCODE(UNPACK_HIGH); 5041 OPCODE(UNPACKL_HIGH); 5042 OPCODE(UNPACK_LOW); 5043 OPCODE(UNPACKL_LOW); 5044 OPCODE(VSHL_BY_SCALAR); 5045 OPCODE(VSRL_BY_SCALAR); 5046 OPCODE(VSRA_BY_SCALAR); 5047 OPCODE(VSUM); 5048 OPCODE(VICMPE); 5049 OPCODE(VICMPH); 5050 OPCODE(VICMPHL); 5051 OPCODE(VICMPES); 5052 OPCODE(VICMPHS); 5053 OPCODE(VICMPHLS); 5054 OPCODE(VFCMPE); 5055 OPCODE(VFCMPH); 5056 OPCODE(VFCMPHE); 5057 OPCODE(VFCMPES); 5058 OPCODE(VFCMPHS); 5059 OPCODE(VFCMPHES); 5060 OPCODE(VFTCI); 5061 OPCODE(VEXTEND); 5062 OPCODE(VROUND); 5063 OPCODE(VTM); 5064 OPCODE(VFAE_CC); 5065 OPCODE(VFAEZ_CC); 5066 OPCODE(VFEE_CC); 5067 OPCODE(VFEEZ_CC); 5068 OPCODE(VFENE_CC); 5069 OPCODE(VFENEZ_CC); 5070 OPCODE(VISTR_CC); 5071 OPCODE(VSTRC_CC); 5072 OPCODE(VSTRCZ_CC); 5073 OPCODE(TDC); 5074 OPCODE(ATOMIC_SWAPW); 5075 OPCODE(ATOMIC_LOADW_ADD); 5076 OPCODE(ATOMIC_LOADW_SUB); 5077 OPCODE(ATOMIC_LOADW_AND); 5078 OPCODE(ATOMIC_LOADW_OR); 5079 OPCODE(ATOMIC_LOADW_XOR); 5080 OPCODE(ATOMIC_LOADW_NAND); 5081 OPCODE(ATOMIC_LOADW_MIN); 5082 OPCODE(ATOMIC_LOADW_MAX); 5083 OPCODE(ATOMIC_LOADW_UMIN); 5084 OPCODE(ATOMIC_LOADW_UMAX); 5085 OPCODE(ATOMIC_CMP_SWAPW); 5086 OPCODE(ATOMIC_CMP_SWAP); 5087 OPCODE(ATOMIC_LOAD_128); 5088 OPCODE(ATOMIC_STORE_128); 5089 OPCODE(ATOMIC_CMP_SWAP_128); 5090 OPCODE(LRV); 5091 OPCODE(STRV); 5092 OPCODE(PREFETCH); 5093 } 5094 return nullptr; 5095 #undef OPCODE 5096 } 5097 5098 // Return true if VT is a vector whose elements are a whole number of bytes 5099 // in width. Also check for presence of vector support. 5100 bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const { 5101 if (!Subtarget.hasVector()) 5102 return false; 5103 5104 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple(); 5105 } 5106 5107 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT 5108 // producing a result of type ResVT. Op is a possibly bitcast version 5109 // of the input vector and Index is the index (based on type VecVT) that 5110 // should be extracted. Return the new extraction if a simplification 5111 // was possible or if Force is true. 5112 SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT, 5113 EVT VecVT, SDValue Op, 5114 unsigned Index, 5115 DAGCombinerInfo &DCI, 5116 bool Force) const { 5117 SelectionDAG &DAG = DCI.DAG; 5118 5119 // The number of bytes being extracted. 5120 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize(); 5121 5122 for (;;) { 5123 unsigned Opcode = Op.getOpcode(); 5124 if (Opcode == ISD::BITCAST) 5125 // Look through bitcasts. 5126 Op = Op.getOperand(0); 5127 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) && 5128 canTreatAsByteVector(Op.getValueType())) { 5129 // Get a VPERM-like permute mask and see whether the bytes covered 5130 // by the extracted element are a contiguous sequence from one 5131 // source operand. 5132 SmallVector<int, SystemZ::VectorBytes> Bytes; 5133 if (!getVPermMask(Op, Bytes)) 5134 break; 5135 int First; 5136 if (!getShuffleInput(Bytes, Index * BytesPerElement, 5137 BytesPerElement, First)) 5138 break; 5139 if (First < 0) 5140 return DAG.getUNDEF(ResVT); 5141 // Make sure the contiguous sequence starts at a multiple of the 5142 // original element size. 5143 unsigned Byte = unsigned(First) % Bytes.size(); 5144 if (Byte % BytesPerElement != 0) 5145 break; 5146 // We can get the extracted value directly from an input. 5147 Index = Byte / BytesPerElement; 5148 Op = Op.getOperand(unsigned(First) / Bytes.size()); 5149 Force = true; 5150 } else if (Opcode == ISD::BUILD_VECTOR && 5151 canTreatAsByteVector(Op.getValueType())) { 5152 // We can only optimize this case if the BUILD_VECTOR elements are 5153 // at least as wide as the extracted value. 5154 EVT OpVT = Op.getValueType(); 5155 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize(); 5156 if (OpBytesPerElement < BytesPerElement) 5157 break; 5158 // Make sure that the least-significant bit of the extracted value 5159 // is the least significant bit of an input. 5160 unsigned End = (Index + 1) * BytesPerElement; 5161 if (End % OpBytesPerElement != 0) 5162 break; 5163 // We're extracting the low part of one operand of the BUILD_VECTOR. 5164 Op = Op.getOperand(End / OpBytesPerElement - 1); 5165 if (!Op.getValueType().isInteger()) { 5166 EVT VT = MVT::getIntegerVT(Op.getValueSizeInBits()); 5167 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op); 5168 DCI.AddToWorklist(Op.getNode()); 5169 } 5170 EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits()); 5171 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 5172 if (VT != ResVT) { 5173 DCI.AddToWorklist(Op.getNode()); 5174 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op); 5175 } 5176 return Op; 5177 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 5178 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG || 5179 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) && 5180 canTreatAsByteVector(Op.getValueType()) && 5181 canTreatAsByteVector(Op.getOperand(0).getValueType())) { 5182 // Make sure that only the unextended bits are significant. 5183 EVT ExtVT = Op.getValueType(); 5184 EVT OpVT = Op.getOperand(0).getValueType(); 5185 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize(); 5186 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize(); 5187 unsigned Byte = Index * BytesPerElement; 5188 unsigned SubByte = Byte % ExtBytesPerElement; 5189 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement; 5190 if (SubByte < MinSubByte || 5191 SubByte + BytesPerElement > ExtBytesPerElement) 5192 break; 5193 // Get the byte offset of the unextended element 5194 Byte = Byte / ExtBytesPerElement * OpBytesPerElement; 5195 // ...then add the byte offset relative to that element. 5196 Byte += SubByte - MinSubByte; 5197 if (Byte % BytesPerElement != 0) 5198 break; 5199 Op = Op.getOperand(0); 5200 Index = Byte / BytesPerElement; 5201 Force = true; 5202 } else 5203 break; 5204 } 5205 if (Force) { 5206 if (Op.getValueType() != VecVT) { 5207 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op); 5208 DCI.AddToWorklist(Op.getNode()); 5209 } 5210 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op, 5211 DAG.getConstant(Index, DL, MVT::i32)); 5212 } 5213 return SDValue(); 5214 } 5215 5216 // Optimize vector operations in scalar value Op on the basis that Op 5217 // is truncated to TruncVT. 5218 SDValue SystemZTargetLowering::combineTruncateExtract( 5219 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const { 5220 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into 5221 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements 5222 // of type TruncVT. 5223 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5224 TruncVT.getSizeInBits() % 8 == 0) { 5225 SDValue Vec = Op.getOperand(0); 5226 EVT VecVT = Vec.getValueType(); 5227 if (canTreatAsByteVector(VecVT)) { 5228 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 5229 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize(); 5230 unsigned TruncBytes = TruncVT.getStoreSize(); 5231 if (BytesPerElement % TruncBytes == 0) { 5232 // Calculate the value of Y' in the above description. We are 5233 // splitting the original elements into Scale equal-sized pieces 5234 // and for truncation purposes want the last (least-significant) 5235 // of these pieces for IndexN. This is easiest to do by calculating 5236 // the start index of the following element and then subtracting 1. 5237 unsigned Scale = BytesPerElement / TruncBytes; 5238 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1; 5239 5240 // Defer the creation of the bitcast from X to combineExtract, 5241 // which might be able to optimize the extraction. 5242 VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8), 5243 VecVT.getStoreSize() / TruncBytes); 5244 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT); 5245 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true); 5246 } 5247 } 5248 } 5249 } 5250 return SDValue(); 5251 } 5252 5253 SDValue SystemZTargetLowering::combineZERO_EXTEND( 5254 SDNode *N, DAGCombinerInfo &DCI) const { 5255 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2') 5256 SelectionDAG &DAG = DCI.DAG; 5257 SDValue N0 = N->getOperand(0); 5258 EVT VT = N->getValueType(0); 5259 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) { 5260 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 5261 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5262 if (TrueOp && FalseOp) { 5263 SDLoc DL(N0); 5264 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT), 5265 DAG.getConstant(FalseOp->getZExtValue(), DL, VT), 5266 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) }; 5267 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops); 5268 // If N0 has multiple uses, change other uses as well. 5269 if (!N0.hasOneUse()) { 5270 SDValue TruncSelect = 5271 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect); 5272 DCI.CombineTo(N0.getNode(), TruncSelect); 5273 } 5274 return NewSelect; 5275 } 5276 } 5277 return SDValue(); 5278 } 5279 5280 SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG( 5281 SDNode *N, DAGCombinerInfo &DCI) const { 5282 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1) 5283 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1) 5284 // into (select_cc LHS, RHS, -1, 0, COND) 5285 SelectionDAG &DAG = DCI.DAG; 5286 SDValue N0 = N->getOperand(0); 5287 EVT VT = N->getValueType(0); 5288 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 5289 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND) 5290 N0 = N0.getOperand(0); 5291 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) { 5292 SDLoc DL(N0); 5293 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1), 5294 DAG.getConstant(-1, DL, VT), DAG.getConstant(0, DL, VT), 5295 N0.getOperand(2) }; 5296 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 5297 } 5298 return SDValue(); 5299 } 5300 5301 SDValue SystemZTargetLowering::combineSIGN_EXTEND( 5302 SDNode *N, DAGCombinerInfo &DCI) const { 5303 // Convert (sext (ashr (shl X, C1), C2)) to 5304 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as 5305 // cheap as narrower ones. 5306 SelectionDAG &DAG = DCI.DAG; 5307 SDValue N0 = N->getOperand(0); 5308 EVT VT = N->getValueType(0); 5309 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) { 5310 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5311 SDValue Inner = N0.getOperand(0); 5312 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) { 5313 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) { 5314 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits()); 5315 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra; 5316 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra; 5317 EVT ShiftVT = N0.getOperand(1).getValueType(); 5318 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT, 5319 Inner.getOperand(0)); 5320 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext, 5321 DAG.getConstant(NewShlAmt, SDLoc(Inner), 5322 ShiftVT)); 5323 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, 5324 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT)); 5325 } 5326 } 5327 } 5328 return SDValue(); 5329 } 5330 5331 SDValue SystemZTargetLowering::combineMERGE( 5332 SDNode *N, DAGCombinerInfo &DCI) const { 5333 SelectionDAG &DAG = DCI.DAG; 5334 unsigned Opcode = N->getOpcode(); 5335 SDValue Op0 = N->getOperand(0); 5336 SDValue Op1 = N->getOperand(1); 5337 if (Op0.getOpcode() == ISD::BITCAST) 5338 Op0 = Op0.getOperand(0); 5339 if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5340 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF 5341 // for v4f32. 5342 if (Op1 == N->getOperand(0)) 5343 return Op1; 5344 // (z_merge_? 0, X) -> (z_unpackl_? 0, X). 5345 EVT VT = Op1.getValueType(); 5346 unsigned ElemBytes = VT.getVectorElementType().getStoreSize(); 5347 if (ElemBytes <= 4) { 5348 Opcode = (Opcode == SystemZISD::MERGE_HIGH ? 5349 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW); 5350 EVT InVT = VT.changeVectorElementTypeToInteger(); 5351 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16), 5352 SystemZ::VectorBytes / ElemBytes / 2); 5353 if (VT != InVT) { 5354 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1); 5355 DCI.AddToWorklist(Op1.getNode()); 5356 } 5357 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1); 5358 DCI.AddToWorklist(Op.getNode()); 5359 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 5360 } 5361 } 5362 return SDValue(); 5363 } 5364 5365 SDValue SystemZTargetLowering::combineLOAD( 5366 SDNode *N, DAGCombinerInfo &DCI) const { 5367 SelectionDAG &DAG = DCI.DAG; 5368 EVT LdVT = N->getValueType(0); 5369 if (LdVT.isVector() || LdVT.isInteger()) 5370 return SDValue(); 5371 // Transform a scalar load that is REPLICATEd as well as having other 5372 // use(s) to the form where the other use(s) use the first element of the 5373 // REPLICATE instead of the load. Otherwise instruction selection will not 5374 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating 5375 // point loads. 5376 5377 SDValue Replicate; 5378 SmallVector<SDNode*, 8> OtherUses; 5379 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5380 UI != UE; ++UI) { 5381 if (UI->getOpcode() == SystemZISD::REPLICATE) { 5382 if (Replicate) 5383 return SDValue(); // Should never happen 5384 Replicate = SDValue(*UI, 0); 5385 } 5386 else if (UI.getUse().getResNo() == 0) 5387 OtherUses.push_back(*UI); 5388 } 5389 if (!Replicate || OtherUses.empty()) 5390 return SDValue(); 5391 5392 SDLoc DL(N); 5393 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT, 5394 Replicate, DAG.getConstant(0, DL, MVT::i32)); 5395 // Update uses of the loaded Value while preserving old chains. 5396 for (SDNode *U : OtherUses) { 5397 SmallVector<SDValue, 8> Ops; 5398 for (SDValue Op : U->ops()) 5399 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op); 5400 DAG.UpdateNodeOperands(U, Ops); 5401 } 5402 return SDValue(N, 0); 5403 } 5404 5405 SDValue SystemZTargetLowering::combineSTORE( 5406 SDNode *N, DAGCombinerInfo &DCI) const { 5407 SelectionDAG &DAG = DCI.DAG; 5408 auto *SN = cast<StoreSDNode>(N); 5409 auto &Op1 = N->getOperand(1); 5410 EVT MemVT = SN->getMemoryVT(); 5411 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better 5412 // for the extraction to be done on a vMiN value, so that we can use VSTE. 5413 // If X has wider elements then convert it to: 5414 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z). 5415 if (MemVT.isInteger() && SN->isTruncatingStore()) { 5416 if (SDValue Value = 5417 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) { 5418 DCI.AddToWorklist(Value.getNode()); 5419 5420 // Rewrite the store with the new form of stored value. 5421 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value, 5422 SN->getBasePtr(), SN->getMemoryVT(), 5423 SN->getMemOperand()); 5424 } 5425 } 5426 // Combine STORE (BSWAP) into STRVH/STRV/STRVG 5427 if (!SN->isTruncatingStore() && 5428 Op1.getOpcode() == ISD::BSWAP && 5429 Op1.getNode()->hasOneUse() && 5430 (Op1.getValueType() == MVT::i16 || 5431 Op1.getValueType() == MVT::i32 || 5432 Op1.getValueType() == MVT::i64)) { 5433 5434 SDValue BSwapOp = Op1.getOperand(0); 5435 5436 if (BSwapOp.getValueType() == MVT::i16) 5437 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp); 5438 5439 SDValue Ops[] = { 5440 N->getOperand(0), BSwapOp, N->getOperand(2) 5441 }; 5442 5443 return 5444 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other), 5445 Ops, MemVT, SN->getMemOperand()); 5446 } 5447 return SDValue(); 5448 } 5449 5450 SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT( 5451 SDNode *N, DAGCombinerInfo &DCI) const { 5452 5453 if (!Subtarget.hasVector()) 5454 return SDValue(); 5455 5456 // Try to simplify a vector extraction. 5457 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 5458 SDValue Op0 = N->getOperand(0); 5459 EVT VecVT = Op0.getValueType(); 5460 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0, 5461 IndexN->getZExtValue(), DCI, false); 5462 } 5463 return SDValue(); 5464 } 5465 5466 SDValue SystemZTargetLowering::combineJOIN_DWORDS( 5467 SDNode *N, DAGCombinerInfo &DCI) const { 5468 SelectionDAG &DAG = DCI.DAG; 5469 // (join_dwords X, X) == (replicate X) 5470 if (N->getOperand(0) == N->getOperand(1)) 5471 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0), 5472 N->getOperand(0)); 5473 return SDValue(); 5474 } 5475 5476 SDValue SystemZTargetLowering::combineFP_ROUND( 5477 SDNode *N, DAGCombinerInfo &DCI) const { 5478 // (fpround (extract_vector_elt X 0)) 5479 // (fpround (extract_vector_elt X 1)) -> 5480 // (extract_vector_elt (VROUND X) 0) 5481 // (extract_vector_elt (VROUND X) 2) 5482 // 5483 // This is a special case since the target doesn't really support v2f32s. 5484 SelectionDAG &DAG = DCI.DAG; 5485 SDValue Op0 = N->getOperand(0); 5486 if (N->getValueType(0) == MVT::f32 && 5487 Op0.hasOneUse() && 5488 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5489 Op0.getOperand(0).getValueType() == MVT::v2f64 && 5490 Op0.getOperand(1).getOpcode() == ISD::Constant && 5491 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) { 5492 SDValue Vec = Op0.getOperand(0); 5493 for (auto *U : Vec->uses()) { 5494 if (U != Op0.getNode() && 5495 U->hasOneUse() && 5496 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5497 U->getOperand(0) == Vec && 5498 U->getOperand(1).getOpcode() == ISD::Constant && 5499 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) { 5500 SDValue OtherRound = SDValue(*U->use_begin(), 0); 5501 if (OtherRound.getOpcode() == ISD::FP_ROUND && 5502 OtherRound.getOperand(0) == SDValue(U, 0) && 5503 OtherRound.getValueType() == MVT::f32) { 5504 SDValue VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N), 5505 MVT::v4f32, Vec); 5506 DCI.AddToWorklist(VRound.getNode()); 5507 SDValue Extract1 = 5508 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32, 5509 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32)); 5510 DCI.AddToWorklist(Extract1.getNode()); 5511 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1); 5512 SDValue Extract0 = 5513 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32, 5514 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32)); 5515 return Extract0; 5516 } 5517 } 5518 } 5519 } 5520 return SDValue(); 5521 } 5522 5523 SDValue SystemZTargetLowering::combineFP_EXTEND( 5524 SDNode *N, DAGCombinerInfo &DCI) const { 5525 // (fpextend (extract_vector_elt X 0)) 5526 // (fpextend (extract_vector_elt X 2)) -> 5527 // (extract_vector_elt (VEXTEND X) 0) 5528 // (extract_vector_elt (VEXTEND X) 1) 5529 // 5530 // This is a special case since the target doesn't really support v2f32s. 5531 SelectionDAG &DAG = DCI.DAG; 5532 SDValue Op0 = N->getOperand(0); 5533 if (N->getValueType(0) == MVT::f64 && 5534 Op0.hasOneUse() && 5535 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5536 Op0.getOperand(0).getValueType() == MVT::v4f32 && 5537 Op0.getOperand(1).getOpcode() == ISD::Constant && 5538 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) { 5539 SDValue Vec = Op0.getOperand(0); 5540 for (auto *U : Vec->uses()) { 5541 if (U != Op0.getNode() && 5542 U->hasOneUse() && 5543 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5544 U->getOperand(0) == Vec && 5545 U->getOperand(1).getOpcode() == ISD::Constant && 5546 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 2) { 5547 SDValue OtherExtend = SDValue(*U->use_begin(), 0); 5548 if (OtherExtend.getOpcode() == ISD::FP_EXTEND && 5549 OtherExtend.getOperand(0) == SDValue(U, 0) && 5550 OtherExtend.getValueType() == MVT::f64) { 5551 SDValue VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N), 5552 MVT::v2f64, Vec); 5553 DCI.AddToWorklist(VExtend.getNode()); 5554 SDValue Extract1 = 5555 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64, 5556 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32)); 5557 DCI.AddToWorklist(Extract1.getNode()); 5558 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1); 5559 SDValue Extract0 = 5560 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64, 5561 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32)); 5562 return Extract0; 5563 } 5564 } 5565 } 5566 } 5567 return SDValue(); 5568 } 5569 5570 SDValue SystemZTargetLowering::combineBSWAP( 5571 SDNode *N, DAGCombinerInfo &DCI) const { 5572 SelectionDAG &DAG = DCI.DAG; 5573 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG 5574 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 5575 N->getOperand(0).hasOneUse() && 5576 (N->getValueType(0) == MVT::i16 || N->getValueType(0) == MVT::i32 || 5577 N->getValueType(0) == MVT::i64)) { 5578 SDValue Load = N->getOperand(0); 5579 LoadSDNode *LD = cast<LoadSDNode>(Load); 5580 5581 // Create the byte-swapping load. 5582 SDValue Ops[] = { 5583 LD->getChain(), // Chain 5584 LD->getBasePtr() // Ptr 5585 }; 5586 EVT LoadVT = N->getValueType(0); 5587 if (LoadVT == MVT::i16) 5588 LoadVT = MVT::i32; 5589 SDValue BSLoad = 5590 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N), 5591 DAG.getVTList(LoadVT, MVT::Other), 5592 Ops, LD->getMemoryVT(), LD->getMemOperand()); 5593 5594 // If this is an i16 load, insert the truncate. 5595 SDValue ResVal = BSLoad; 5596 if (N->getValueType(0) == MVT::i16) 5597 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad); 5598 5599 // First, combine the bswap away. This makes the value produced by the 5600 // load dead. 5601 DCI.CombineTo(N, ResVal); 5602 5603 // Next, combine the load away, we give it a bogus result value but a real 5604 // chain result. The result value is dead because the bswap is dead. 5605 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 5606 5607 // Return N so it doesn't get rechecked! 5608 return SDValue(N, 0); 5609 } 5610 return SDValue(); 5611 } 5612 5613 static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask) { 5614 // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code 5615 // set by the CCReg instruction using the CCValid / CCMask masks, 5616 // If the CCReg instruction is itself a ICMP testing the condition 5617 // code set by some other instruction, see whether we can directly 5618 // use that condition code. 5619 5620 // Verify that we have an ICMP against some constant. 5621 if (CCValid != SystemZ::CCMASK_ICMP) 5622 return false; 5623 auto *ICmp = CCReg.getNode(); 5624 if (ICmp->getOpcode() != SystemZISD::ICMP) 5625 return false; 5626 auto *CompareLHS = ICmp->getOperand(0).getNode(); 5627 auto *CompareRHS = dyn_cast<ConstantSDNode>(ICmp->getOperand(1)); 5628 if (!CompareRHS) 5629 return false; 5630 5631 // Optimize the case where CompareLHS is a SELECT_CCMASK. 5632 if (CompareLHS->getOpcode() == SystemZISD::SELECT_CCMASK) { 5633 // Verify that we have an appropriate mask for a EQ or NE comparison. 5634 bool Invert = false; 5635 if (CCMask == SystemZ::CCMASK_CMP_NE) 5636 Invert = !Invert; 5637 else if (CCMask != SystemZ::CCMASK_CMP_EQ) 5638 return false; 5639 5640 // Verify that the ICMP compares against one of select values. 5641 auto *TrueVal = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(0)); 5642 if (!TrueVal) 5643 return false; 5644 auto *FalseVal = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(1)); 5645 if (!FalseVal) 5646 return false; 5647 if (CompareRHS->getZExtValue() == FalseVal->getZExtValue()) 5648 Invert = !Invert; 5649 else if (CompareRHS->getZExtValue() != TrueVal->getZExtValue()) 5650 return false; 5651 5652 // Compute the effective CC mask for the new branch or select. 5653 auto *NewCCValid = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(2)); 5654 auto *NewCCMask = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(3)); 5655 if (!NewCCValid || !NewCCMask) 5656 return false; 5657 CCValid = NewCCValid->getZExtValue(); 5658 CCMask = NewCCMask->getZExtValue(); 5659 if (Invert) 5660 CCMask ^= CCValid; 5661 5662 // Return the updated CCReg link. 5663 CCReg = CompareLHS->getOperand(4); 5664 return true; 5665 } 5666 5667 // Optimize the case where CompareRHS is (SRA (SHL (IPM))). 5668 if (CompareLHS->getOpcode() == ISD::SRA) { 5669 auto *SRACount = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(1)); 5670 if (!SRACount || SRACount->getZExtValue() != 30) 5671 return false; 5672 auto *SHL = CompareLHS->getOperand(0).getNode(); 5673 if (SHL->getOpcode() != ISD::SHL) 5674 return false; 5675 auto *SHLCount = dyn_cast<ConstantSDNode>(SHL->getOperand(1)); 5676 if (!SHLCount || SHLCount->getZExtValue() != 30 - SystemZ::IPM_CC) 5677 return false; 5678 auto *IPM = SHL->getOperand(0).getNode(); 5679 if (IPM->getOpcode() != SystemZISD::IPM) 5680 return false; 5681 5682 // Avoid introducing CC spills (because SRA would clobber CC). 5683 if (!CompareLHS->hasOneUse()) 5684 return false; 5685 // Verify that the ICMP compares against zero. 5686 if (CompareRHS->getZExtValue() != 0) 5687 return false; 5688 5689 // Compute the effective CC mask for the new branch or select. 5690 switch (CCMask) { 5691 case SystemZ::CCMASK_CMP_EQ: break; 5692 case SystemZ::CCMASK_CMP_NE: break; 5693 case SystemZ::CCMASK_CMP_LT: CCMask = SystemZ::CCMASK_CMP_GT; break; 5694 case SystemZ::CCMASK_CMP_GT: CCMask = SystemZ::CCMASK_CMP_LT; break; 5695 case SystemZ::CCMASK_CMP_LE: CCMask = SystemZ::CCMASK_CMP_GE; break; 5696 case SystemZ::CCMASK_CMP_GE: CCMask = SystemZ::CCMASK_CMP_LE; break; 5697 default: return false; 5698 } 5699 5700 // Return the updated CCReg link. 5701 CCReg = IPM->getOperand(0); 5702 return true; 5703 } 5704 5705 return false; 5706 } 5707 5708 SDValue SystemZTargetLowering::combineBR_CCMASK( 5709 SDNode *N, DAGCombinerInfo &DCI) const { 5710 SelectionDAG &DAG = DCI.DAG; 5711 5712 // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK. 5713 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1)); 5714 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2)); 5715 if (!CCValid || !CCMask) 5716 return SDValue(); 5717 5718 int CCValidVal = CCValid->getZExtValue(); 5719 int CCMaskVal = CCMask->getZExtValue(); 5720 SDValue Chain = N->getOperand(0); 5721 SDValue CCReg = N->getOperand(4); 5722 5723 if (combineCCMask(CCReg, CCValidVal, CCMaskVal)) 5724 return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0), 5725 Chain, 5726 DAG.getConstant(CCValidVal, SDLoc(N), MVT::i32), 5727 DAG.getConstant(CCMaskVal, SDLoc(N), MVT::i32), 5728 N->getOperand(3), CCReg); 5729 return SDValue(); 5730 } 5731 5732 SDValue SystemZTargetLowering::combineSELECT_CCMASK( 5733 SDNode *N, DAGCombinerInfo &DCI) const { 5734 SelectionDAG &DAG = DCI.DAG; 5735 5736 // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK. 5737 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2)); 5738 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3)); 5739 if (!CCValid || !CCMask) 5740 return SDValue(); 5741 5742 int CCValidVal = CCValid->getZExtValue(); 5743 int CCMaskVal = CCMask->getZExtValue(); 5744 SDValue CCReg = N->getOperand(4); 5745 5746 if (combineCCMask(CCReg, CCValidVal, CCMaskVal)) 5747 return DAG.getNode(SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0), 5748 N->getOperand(0), 5749 N->getOperand(1), 5750 DAG.getConstant(CCValidVal, SDLoc(N), MVT::i32), 5751 DAG.getConstant(CCMaskVal, SDLoc(N), MVT::i32), 5752 CCReg); 5753 return SDValue(); 5754 } 5755 5756 5757 SDValue SystemZTargetLowering::combineGET_CCMASK( 5758 SDNode *N, DAGCombinerInfo &DCI) const { 5759 5760 // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible 5761 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1)); 5762 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2)); 5763 if (!CCValid || !CCMask) 5764 return SDValue(); 5765 int CCValidVal = CCValid->getZExtValue(); 5766 int CCMaskVal = CCMask->getZExtValue(); 5767 5768 SDValue Select = N->getOperand(0); 5769 if (Select->getOpcode() != SystemZISD::SELECT_CCMASK) 5770 return SDValue(); 5771 5772 auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2)); 5773 auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3)); 5774 if (!SelectCCValid || !SelectCCMask) 5775 return SDValue(); 5776 int SelectCCValidVal = SelectCCValid->getZExtValue(); 5777 int SelectCCMaskVal = SelectCCMask->getZExtValue(); 5778 5779 auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0)); 5780 auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1)); 5781 if (!TrueVal || !FalseVal) 5782 return SDValue(); 5783 if (TrueVal->getZExtValue() != 0 && FalseVal->getZExtValue() == 0) 5784 ; 5785 else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() != 0) 5786 SelectCCMaskVal ^= SelectCCValidVal; 5787 else 5788 return SDValue(); 5789 5790 if (SelectCCValidVal & ~CCValidVal) 5791 return SDValue(); 5792 if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal)) 5793 return SDValue(); 5794 5795 return Select->getOperand(4); 5796 } 5797 5798 SDValue SystemZTargetLowering::combineIntDIVREM( 5799 SDNode *N, DAGCombinerInfo &DCI) const { 5800 SelectionDAG &DAG = DCI.DAG; 5801 EVT VT = N->getValueType(0); 5802 // In the case where the divisor is a vector of constants a cheaper 5803 // sequence of instructions can replace the divide. BuildSDIV is called to 5804 // do this during DAG combining, but it only succeeds when it can build a 5805 // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and 5806 // since it is not Legal but Custom it can only happen before 5807 // legalization. Therefore we must scalarize this early before Combine 5808 // 1. For widened vectors, this is already the result of type legalization. 5809 if (VT.isVector() && isTypeLegal(VT) && 5810 DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1))) 5811 return DAG.UnrollVectorOp(N); 5812 return SDValue(); 5813 } 5814 5815 SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const { 5816 if (N->getOpcode() == SystemZISD::PCREL_WRAPPER) 5817 return N->getOperand(0); 5818 return N; 5819 } 5820 5821 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N, 5822 DAGCombinerInfo &DCI) const { 5823 switch(N->getOpcode()) { 5824 default: break; 5825 case ISD::ZERO_EXTEND: return combineZERO_EXTEND(N, DCI); 5826 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI); 5827 case ISD::SIGN_EXTEND_INREG: return combineSIGN_EXTEND_INREG(N, DCI); 5828 case SystemZISD::MERGE_HIGH: 5829 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI); 5830 case ISD::LOAD: return combineLOAD(N, DCI); 5831 case ISD::STORE: return combineSTORE(N, DCI); 5832 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI); 5833 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI); 5834 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI); 5835 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DCI); 5836 case ISD::BSWAP: return combineBSWAP(N, DCI); 5837 case SystemZISD::BR_CCMASK: return combineBR_CCMASK(N, DCI); 5838 case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI); 5839 case SystemZISD::GET_CCMASK: return combineGET_CCMASK(N, DCI); 5840 case ISD::SDIV: 5841 case ISD::UDIV: 5842 case ISD::SREM: 5843 case ISD::UREM: return combineIntDIVREM(N, DCI); 5844 } 5845 5846 return SDValue(); 5847 } 5848 5849 // Return the demanded elements for the OpNo source operand of Op. DemandedElts 5850 // are for Op. 5851 static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts, 5852 unsigned OpNo) { 5853 EVT VT = Op.getValueType(); 5854 unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1); 5855 APInt SrcDemE; 5856 unsigned Opcode = Op.getOpcode(); 5857 if (Opcode == ISD::INTRINSIC_WO_CHAIN) { 5858 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5859 switch (Id) { 5860 case Intrinsic::s390_vpksh: // PACKS 5861 case Intrinsic::s390_vpksf: 5862 case Intrinsic::s390_vpksg: 5863 case Intrinsic::s390_vpkshs: // PACKS_CC 5864 case Intrinsic::s390_vpksfs: 5865 case Intrinsic::s390_vpksgs: 5866 case Intrinsic::s390_vpklsh: // PACKLS 5867 case Intrinsic::s390_vpklsf: 5868 case Intrinsic::s390_vpklsg: 5869 case Intrinsic::s390_vpklshs: // PACKLS_CC 5870 case Intrinsic::s390_vpklsfs: 5871 case Intrinsic::s390_vpklsgs: 5872 // VECTOR PACK truncates the elements of two source vectors into one. 5873 SrcDemE = DemandedElts; 5874 if (OpNo == 2) 5875 SrcDemE.lshrInPlace(NumElts / 2); 5876 SrcDemE = SrcDemE.trunc(NumElts / 2); 5877 break; 5878 // VECTOR UNPACK extends half the elements of the source vector. 5879 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH 5880 case Intrinsic::s390_vuphh: 5881 case Intrinsic::s390_vuphf: 5882 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH 5883 case Intrinsic::s390_vuplhh: 5884 case Intrinsic::s390_vuplhf: 5885 SrcDemE = APInt(NumElts * 2, 0); 5886 SrcDemE.insertBits(DemandedElts, 0); 5887 break; 5888 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW 5889 case Intrinsic::s390_vuplhw: 5890 case Intrinsic::s390_vuplf: 5891 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW 5892 case Intrinsic::s390_vupllh: 5893 case Intrinsic::s390_vupllf: 5894 SrcDemE = APInt(NumElts * 2, 0); 5895 SrcDemE.insertBits(DemandedElts, NumElts); 5896 break; 5897 case Intrinsic::s390_vpdi: { 5898 // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source. 5899 SrcDemE = APInt(NumElts, 0); 5900 if (!DemandedElts[OpNo - 1]) 5901 break; 5902 unsigned Mask = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 5903 unsigned MaskBit = ((OpNo - 1) ? 1 : 4); 5904 // Demand input element 0 or 1, given by the mask bit value. 5905 SrcDemE.setBit((Mask & MaskBit)? 1 : 0); 5906 break; 5907 } 5908 case Intrinsic::s390_vsldb: { 5909 // VECTOR SHIFT LEFT DOUBLE BY BYTE 5910 assert(VT == MVT::v16i8 && "Unexpected type."); 5911 unsigned FirstIdx = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 5912 assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand."); 5913 unsigned NumSrc0Els = 16 - FirstIdx; 5914 SrcDemE = APInt(NumElts, 0); 5915 if (OpNo == 1) { 5916 APInt DemEls = DemandedElts.trunc(NumSrc0Els); 5917 SrcDemE.insertBits(DemEls, FirstIdx); 5918 } else { 5919 APInt DemEls = DemandedElts.lshr(NumSrc0Els); 5920 SrcDemE.insertBits(DemEls, 0); 5921 } 5922 break; 5923 } 5924 case Intrinsic::s390_vperm: 5925 SrcDemE = APInt(NumElts, 1); 5926 break; 5927 default: 5928 llvm_unreachable("Unhandled intrinsic."); 5929 break; 5930 } 5931 } else { 5932 switch (Opcode) { 5933 case SystemZISD::JOIN_DWORDS: 5934 // Scalar operand. 5935 SrcDemE = APInt(1, 1); 5936 break; 5937 case SystemZISD::SELECT_CCMASK: 5938 SrcDemE = DemandedElts; 5939 break; 5940 default: 5941 llvm_unreachable("Unhandled opcode."); 5942 break; 5943 } 5944 } 5945 return SrcDemE; 5946 } 5947 5948 static void computeKnownBitsBinOp(const SDValue Op, KnownBits &Known, 5949 const APInt &DemandedElts, 5950 const SelectionDAG &DAG, unsigned Depth, 5951 unsigned OpNo) { 5952 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo); 5953 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1); 5954 KnownBits LHSKnown = 5955 DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1); 5956 KnownBits RHSKnown = 5957 DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1); 5958 Known.Zero = LHSKnown.Zero & RHSKnown.Zero; 5959 Known.One = LHSKnown.One & RHSKnown.One; 5960 } 5961 5962 void 5963 SystemZTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 5964 KnownBits &Known, 5965 const APInt &DemandedElts, 5966 const SelectionDAG &DAG, 5967 unsigned Depth) const { 5968 Known.resetAll(); 5969 5970 // Intrinsic CC result is returned in the two low bits. 5971 unsigned tmp0, tmp1; // not used 5972 if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, tmp0, tmp1)) { 5973 Known.Zero.setBitsFrom(2); 5974 return; 5975 } 5976 EVT VT = Op.getValueType(); 5977 if (Op.getResNo() != 0 || VT == MVT::Untyped) 5978 return; 5979 assert (Known.getBitWidth() == VT.getScalarSizeInBits() && 5980 "KnownBits does not match VT in bitwidth"); 5981 assert ((!VT.isVector() || 5982 (DemandedElts.getBitWidth() == VT.getVectorNumElements())) && 5983 "DemandedElts does not match VT number of elements"); 5984 unsigned BitWidth = Known.getBitWidth(); 5985 unsigned Opcode = Op.getOpcode(); 5986 if (Opcode == ISD::INTRINSIC_WO_CHAIN) { 5987 bool IsLogical = false; 5988 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5989 switch (Id) { 5990 case Intrinsic::s390_vpksh: // PACKS 5991 case Intrinsic::s390_vpksf: 5992 case Intrinsic::s390_vpksg: 5993 case Intrinsic::s390_vpkshs: // PACKS_CC 5994 case Intrinsic::s390_vpksfs: 5995 case Intrinsic::s390_vpksgs: 5996 case Intrinsic::s390_vpklsh: // PACKLS 5997 case Intrinsic::s390_vpklsf: 5998 case Intrinsic::s390_vpklsg: 5999 case Intrinsic::s390_vpklshs: // PACKLS_CC 6000 case Intrinsic::s390_vpklsfs: 6001 case Intrinsic::s390_vpklsgs: 6002 case Intrinsic::s390_vpdi: 6003 case Intrinsic::s390_vsldb: 6004 case Intrinsic::s390_vperm: 6005 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1); 6006 break; 6007 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH 6008 case Intrinsic::s390_vuplhh: 6009 case Intrinsic::s390_vuplhf: 6010 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW 6011 case Intrinsic::s390_vupllh: 6012 case Intrinsic::s390_vupllf: 6013 IsLogical = true; 6014 LLVM_FALLTHROUGH; 6015 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH 6016 case Intrinsic::s390_vuphh: 6017 case Intrinsic::s390_vuphf: 6018 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW 6019 case Intrinsic::s390_vuplhw: 6020 case Intrinsic::s390_vuplf: { 6021 SDValue SrcOp = Op.getOperand(1); 6022 unsigned SrcBitWidth = SrcOp.getScalarValueSizeInBits(); 6023 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0); 6024 Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1); 6025 if (IsLogical) { 6026 Known = Known.zext(BitWidth); 6027 Known.Zero.setBitsFrom(SrcBitWidth); 6028 } else 6029 Known = Known.sext(BitWidth); 6030 break; 6031 } 6032 default: 6033 break; 6034 } 6035 } else { 6036 switch (Opcode) { 6037 case SystemZISD::JOIN_DWORDS: 6038 case SystemZISD::SELECT_CCMASK: 6039 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0); 6040 break; 6041 case SystemZISD::REPLICATE: { 6042 SDValue SrcOp = Op.getOperand(0); 6043 Known = DAG.computeKnownBits(SrcOp, Depth + 1); 6044 if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp)) 6045 Known = Known.sext(BitWidth); // VREPI sign extends the immedate. 6046 break; 6047 } 6048 default: 6049 break; 6050 } 6051 } 6052 6053 // Known has the width of the source operand(s). Adjust if needed to match 6054 // the passed bitwidth. 6055 if (Known.getBitWidth() != BitWidth) 6056 Known = Known.zextOrTrunc(BitWidth); 6057 } 6058 6059 static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts, 6060 const SelectionDAG &DAG, unsigned Depth, 6061 unsigned OpNo) { 6062 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo); 6063 unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1); 6064 if (LHS == 1) return 1; // Early out. 6065 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1); 6066 unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1); 6067 if (RHS == 1) return 1; // Early out. 6068 unsigned Common = std::min(LHS, RHS); 6069 unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits(); 6070 EVT VT = Op.getValueType(); 6071 unsigned VTBits = VT.getScalarSizeInBits(); 6072 if (SrcBitWidth > VTBits) { // PACK 6073 unsigned SrcExtraBits = SrcBitWidth - VTBits; 6074 if (Common > SrcExtraBits) 6075 return (Common - SrcExtraBits); 6076 return 1; 6077 } 6078 assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth."); 6079 return Common; 6080 } 6081 6082 unsigned 6083 SystemZTargetLowering::ComputeNumSignBitsForTargetNode( 6084 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 6085 unsigned Depth) const { 6086 if (Op.getResNo() != 0) 6087 return 1; 6088 unsigned Opcode = Op.getOpcode(); 6089 if (Opcode == ISD::INTRINSIC_WO_CHAIN) { 6090 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6091 switch (Id) { 6092 case Intrinsic::s390_vpksh: // PACKS 6093 case Intrinsic::s390_vpksf: 6094 case Intrinsic::s390_vpksg: 6095 case Intrinsic::s390_vpkshs: // PACKS_CC 6096 case Intrinsic::s390_vpksfs: 6097 case Intrinsic::s390_vpksgs: 6098 case Intrinsic::s390_vpklsh: // PACKLS 6099 case Intrinsic::s390_vpklsf: 6100 case Intrinsic::s390_vpklsg: 6101 case Intrinsic::s390_vpklshs: // PACKLS_CC 6102 case Intrinsic::s390_vpklsfs: 6103 case Intrinsic::s390_vpklsgs: 6104 case Intrinsic::s390_vpdi: 6105 case Intrinsic::s390_vsldb: 6106 case Intrinsic::s390_vperm: 6107 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1); 6108 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH 6109 case Intrinsic::s390_vuphh: 6110 case Intrinsic::s390_vuphf: 6111 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW 6112 case Intrinsic::s390_vuplhw: 6113 case Intrinsic::s390_vuplf: { 6114 SDValue PackedOp = Op.getOperand(1); 6115 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1); 6116 unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1); 6117 EVT VT = Op.getValueType(); 6118 unsigned VTBits = VT.getScalarSizeInBits(); 6119 Tmp += VTBits - PackedOp.getScalarValueSizeInBits(); 6120 return Tmp; 6121 } 6122 default: 6123 break; 6124 } 6125 } else { 6126 switch (Opcode) { 6127 case SystemZISD::SELECT_CCMASK: 6128 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0); 6129 default: 6130 break; 6131 } 6132 } 6133 6134 return 1; 6135 } 6136 6137 //===----------------------------------------------------------------------===// 6138 // Custom insertion 6139 //===----------------------------------------------------------------------===// 6140 6141 // Create a new basic block after MBB. 6142 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) { 6143 MachineFunction &MF = *MBB->getParent(); 6144 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock()); 6145 MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB); 6146 return NewMBB; 6147 } 6148 6149 // Split MBB after MI and return the new block (the one that contains 6150 // instructions after MI). 6151 static MachineBasicBlock *splitBlockAfter(MachineBasicBlock::iterator MI, 6152 MachineBasicBlock *MBB) { 6153 MachineBasicBlock *NewMBB = emitBlockAfter(MBB); 6154 NewMBB->splice(NewMBB->begin(), MBB, 6155 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 6156 NewMBB->transferSuccessorsAndUpdatePHIs(MBB); 6157 return NewMBB; 6158 } 6159 6160 // Split MBB before MI and return the new block (the one that contains MI). 6161 static MachineBasicBlock *splitBlockBefore(MachineBasicBlock::iterator MI, 6162 MachineBasicBlock *MBB) { 6163 MachineBasicBlock *NewMBB = emitBlockAfter(MBB); 6164 NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end()); 6165 NewMBB->transferSuccessorsAndUpdatePHIs(MBB); 6166 return NewMBB; 6167 } 6168 6169 // Force base value Base into a register before MI. Return the register. 6170 static unsigned forceReg(MachineInstr &MI, MachineOperand &Base, 6171 const SystemZInstrInfo *TII) { 6172 if (Base.isReg()) 6173 return Base.getReg(); 6174 6175 MachineBasicBlock *MBB = MI.getParent(); 6176 MachineFunction &MF = *MBB->getParent(); 6177 MachineRegisterInfo &MRI = MF.getRegInfo(); 6178 6179 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass); 6180 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg) 6181 .add(Base) 6182 .addImm(0) 6183 .addReg(0); 6184 return Reg; 6185 } 6186 6187 // The CC operand of MI might be missing a kill marker because there 6188 // were multiple uses of CC, and ISel didn't know which to mark. 6189 // Figure out whether MI should have had a kill marker. 6190 static bool checkCCKill(MachineInstr &MI, MachineBasicBlock *MBB) { 6191 // Scan forward through BB for a use/def of CC. 6192 MachineBasicBlock::iterator miI(std::next(MachineBasicBlock::iterator(MI))); 6193 for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) { 6194 const MachineInstr& mi = *miI; 6195 if (mi.readsRegister(SystemZ::CC)) 6196 return false; 6197 if (mi.definesRegister(SystemZ::CC)) 6198 break; // Should have kill-flag - update below. 6199 } 6200 6201 // If we hit the end of the block, check whether CC is live into a 6202 // successor. 6203 if (miI == MBB->end()) { 6204 for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) 6205 if ((*SI)->isLiveIn(SystemZ::CC)) 6206 return false; 6207 } 6208 6209 return true; 6210 } 6211 6212 // Return true if it is OK for this Select pseudo-opcode to be cascaded 6213 // together with other Select pseudo-opcodes into a single basic-block with 6214 // a conditional jump around it. 6215 static bool isSelectPseudo(MachineInstr &MI) { 6216 switch (MI.getOpcode()) { 6217 case SystemZ::Select32: 6218 case SystemZ::Select64: 6219 case SystemZ::SelectF32: 6220 case SystemZ::SelectF64: 6221 case SystemZ::SelectF128: 6222 case SystemZ::SelectVR32: 6223 case SystemZ::SelectVR64: 6224 case SystemZ::SelectVR128: 6225 return true; 6226 6227 default: 6228 return false; 6229 } 6230 } 6231 6232 // Helper function, which inserts PHI functions into SinkMBB: 6233 // %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ], 6234 // where %FalseValue(i) and %TrueValue(i) are taken from the consequent Selects 6235 // in [MIItBegin, MIItEnd) range. 6236 static void createPHIsForSelects(MachineBasicBlock::iterator MIItBegin, 6237 MachineBasicBlock::iterator MIItEnd, 6238 MachineBasicBlock *TrueMBB, 6239 MachineBasicBlock *FalseMBB, 6240 MachineBasicBlock *SinkMBB) { 6241 MachineFunction *MF = TrueMBB->getParent(); 6242 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 6243 6244 unsigned CCValid = MIItBegin->getOperand(3).getImm(); 6245 unsigned CCMask = MIItBegin->getOperand(4).getImm(); 6246 DebugLoc DL = MIItBegin->getDebugLoc(); 6247 6248 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin(); 6249 6250 // As we are creating the PHIs, we have to be careful if there is more than 6251 // one. Later Selects may reference the results of earlier Selects, but later 6252 // PHIs have to reference the individual true/false inputs from earlier PHIs. 6253 // That also means that PHI construction must work forward from earlier to 6254 // later, and that the code must maintain a mapping from earlier PHI's 6255 // destination registers, and the registers that went into the PHI. 6256 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable; 6257 6258 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; 6259 MIIt = skipDebugInstructionsForward(++MIIt, MIItEnd)) { 6260 unsigned DestReg = MIIt->getOperand(0).getReg(); 6261 unsigned TrueReg = MIIt->getOperand(1).getReg(); 6262 unsigned FalseReg = MIIt->getOperand(2).getReg(); 6263 6264 // If this Select we are generating is the opposite condition from 6265 // the jump we generated, then we have to swap the operands for the 6266 // PHI that is going to be generated. 6267 if (MIIt->getOperand(4).getImm() == (CCValid ^ CCMask)) 6268 std::swap(TrueReg, FalseReg); 6269 6270 if (RegRewriteTable.find(TrueReg) != RegRewriteTable.end()) 6271 TrueReg = RegRewriteTable[TrueReg].first; 6272 6273 if (RegRewriteTable.find(FalseReg) != RegRewriteTable.end()) 6274 FalseReg = RegRewriteTable[FalseReg].second; 6275 6276 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg) 6277 .addReg(TrueReg).addMBB(TrueMBB) 6278 .addReg(FalseReg).addMBB(FalseMBB); 6279 6280 // Add this PHI to the rewrite table. 6281 RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg); 6282 } 6283 6284 MF->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 6285 } 6286 6287 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI. 6288 MachineBasicBlock * 6289 SystemZTargetLowering::emitSelect(MachineInstr &MI, 6290 MachineBasicBlock *MBB) const { 6291 const SystemZInstrInfo *TII = 6292 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 6293 6294 unsigned CCValid = MI.getOperand(3).getImm(); 6295 unsigned CCMask = MI.getOperand(4).getImm(); 6296 DebugLoc DL = MI.getDebugLoc(); 6297 6298 // If we have a sequence of Select* pseudo instructions using the 6299 // same condition code value, we want to expand all of them into 6300 // a single pair of basic blocks using the same condition. 6301 MachineInstr *LastMI = &MI; 6302 MachineBasicBlock::iterator NextMIIt = skipDebugInstructionsForward( 6303 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 6304 6305 if (isSelectPseudo(MI)) 6306 while (NextMIIt != MBB->end() && isSelectPseudo(*NextMIIt) && 6307 NextMIIt->getOperand(3).getImm() == CCValid && 6308 (NextMIIt->getOperand(4).getImm() == CCMask || 6309 NextMIIt->getOperand(4).getImm() == (CCValid ^ CCMask))) { 6310 LastMI = &*NextMIIt; 6311 NextMIIt = skipDebugInstructionsForward(++NextMIIt, MBB->end()); 6312 } 6313 6314 MachineBasicBlock *StartMBB = MBB; 6315 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB); 6316 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB); 6317 6318 // Unless CC was killed in the last Select instruction, mark it as 6319 // live-in to both FalseMBB and JoinMBB. 6320 if (!LastMI->killsRegister(SystemZ::CC) && !checkCCKill(*LastMI, JoinMBB)) { 6321 FalseMBB->addLiveIn(SystemZ::CC); 6322 JoinMBB->addLiveIn(SystemZ::CC); 6323 } 6324 6325 // StartMBB: 6326 // BRC CCMask, JoinMBB 6327 // # fallthrough to FalseMBB 6328 MBB = StartMBB; 6329 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 6330 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB); 6331 MBB->addSuccessor(JoinMBB); 6332 MBB->addSuccessor(FalseMBB); 6333 6334 // FalseMBB: 6335 // # fallthrough to JoinMBB 6336 MBB = FalseMBB; 6337 MBB->addSuccessor(JoinMBB); 6338 6339 // JoinMBB: 6340 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ] 6341 // ... 6342 MBB = JoinMBB; 6343 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI); 6344 MachineBasicBlock::iterator MIItEnd = skipDebugInstructionsForward( 6345 std::next(MachineBasicBlock::iterator(LastMI)), MBB->end()); 6346 createPHIsForSelects(MIItBegin, MIItEnd, StartMBB, FalseMBB, MBB); 6347 6348 StartMBB->erase(MIItBegin, MIItEnd); 6349 return JoinMBB; 6350 } 6351 6352 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI. 6353 // StoreOpcode is the store to use and Invert says whether the store should 6354 // happen when the condition is false rather than true. If a STORE ON 6355 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0. 6356 MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI, 6357 MachineBasicBlock *MBB, 6358 unsigned StoreOpcode, 6359 unsigned STOCOpcode, 6360 bool Invert) const { 6361 const SystemZInstrInfo *TII = 6362 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 6363 6364 unsigned SrcReg = MI.getOperand(0).getReg(); 6365 MachineOperand Base = MI.getOperand(1); 6366 int64_t Disp = MI.getOperand(2).getImm(); 6367 unsigned IndexReg = MI.getOperand(3).getReg(); 6368 unsigned CCValid = MI.getOperand(4).getImm(); 6369 unsigned CCMask = MI.getOperand(5).getImm(); 6370 DebugLoc DL = MI.getDebugLoc(); 6371 6372 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp); 6373 6374 // Use STOCOpcode if possible. We could use different store patterns in 6375 // order to avoid matching the index register, but the performance trade-offs 6376 // might be more complicated in that case. 6377 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) { 6378 if (Invert) 6379 CCMask ^= CCValid; 6380 6381 // ISel pattern matching also adds a load memory operand of the same 6382 // address, so take special care to find the storing memory operand. 6383 MachineMemOperand *MMO = nullptr; 6384 for (auto *I : MI.memoperands()) 6385 if (I->isStore()) { 6386 MMO = I; 6387 break; 6388 } 6389 6390 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode)) 6391 .addReg(SrcReg) 6392 .add(Base) 6393 .addImm(Disp) 6394 .addImm(CCValid) 6395 .addImm(CCMask) 6396 .addMemOperand(MMO); 6397 6398 MI.eraseFromParent(); 6399 return MBB; 6400 } 6401 6402 // Get the condition needed to branch around the store. 6403 if (!Invert) 6404 CCMask ^= CCValid; 6405 6406 MachineBasicBlock *StartMBB = MBB; 6407 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB); 6408 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB); 6409 6410 // Unless CC was killed in the CondStore instruction, mark it as 6411 // live-in to both FalseMBB and JoinMBB. 6412 if (!MI.killsRegister(SystemZ::CC) && !checkCCKill(MI, JoinMBB)) { 6413 FalseMBB->addLiveIn(SystemZ::CC); 6414 JoinMBB->addLiveIn(SystemZ::CC); 6415 } 6416 6417 // StartMBB: 6418 // BRC CCMask, JoinMBB 6419 // # fallthrough to FalseMBB 6420 MBB = StartMBB; 6421 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 6422 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB); 6423 MBB->addSuccessor(JoinMBB); 6424 MBB->addSuccessor(FalseMBB); 6425 6426 // FalseMBB: 6427 // store %SrcReg, %Disp(%Index,%Base) 6428 // # fallthrough to JoinMBB 6429 MBB = FalseMBB; 6430 BuildMI(MBB, DL, TII->get(StoreOpcode)) 6431 .addReg(SrcReg) 6432 .add(Base) 6433 .addImm(Disp) 6434 .addReg(IndexReg); 6435 MBB->addSuccessor(JoinMBB); 6436 6437 MI.eraseFromParent(); 6438 return JoinMBB; 6439 } 6440 6441 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_* 6442 // or ATOMIC_SWAP{,W} instruction MI. BinOpcode is the instruction that 6443 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}. 6444 // BitSize is the width of the field in bits, or 0 if this is a partword 6445 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize 6446 // is one of the operands. Invert says whether the field should be 6447 // inverted after performing BinOpcode (e.g. for NAND). 6448 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary( 6449 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode, 6450 unsigned BitSize, bool Invert) const { 6451 MachineFunction &MF = *MBB->getParent(); 6452 const SystemZInstrInfo *TII = 6453 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 6454 MachineRegisterInfo &MRI = MF.getRegInfo(); 6455 bool IsSubWord = (BitSize < 32); 6456 6457 // Extract the operands. Base can be a register or a frame index. 6458 // Src2 can be a register or immediate. 6459 unsigned Dest = MI.getOperand(0).getReg(); 6460 MachineOperand Base = earlyUseOperand(MI.getOperand(1)); 6461 int64_t Disp = MI.getOperand(2).getImm(); 6462 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3)); 6463 unsigned BitShift = (IsSubWord ? MI.getOperand(4).getReg() : 0); 6464 unsigned NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : 0); 6465 DebugLoc DL = MI.getDebugLoc(); 6466 if (IsSubWord) 6467 BitSize = MI.getOperand(6).getImm(); 6468 6469 // Subword operations use 32-bit registers. 6470 const TargetRegisterClass *RC = (BitSize <= 32 ? 6471 &SystemZ::GR32BitRegClass : 6472 &SystemZ::GR64BitRegClass); 6473 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG; 6474 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG; 6475 6476 // Get the right opcodes for the displacement. 6477 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp); 6478 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp); 6479 assert(LOpcode && CSOpcode && "Displacement out of range"); 6480 6481 // Create virtual registers for temporary results. 6482 unsigned OrigVal = MRI.createVirtualRegister(RC); 6483 unsigned OldVal = MRI.createVirtualRegister(RC); 6484 unsigned NewVal = (BinOpcode || IsSubWord ? 6485 MRI.createVirtualRegister(RC) : Src2.getReg()); 6486 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal); 6487 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal); 6488 6489 // Insert a basic block for the main loop. 6490 MachineBasicBlock *StartMBB = MBB; 6491 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB); 6492 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB); 6493 6494 // StartMBB: 6495 // ... 6496 // %OrigVal = L Disp(%Base) 6497 // # fall through to LoopMMB 6498 MBB = StartMBB; 6499 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0); 6500 MBB->addSuccessor(LoopMBB); 6501 6502 // LoopMBB: 6503 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ] 6504 // %RotatedOldVal = RLL %OldVal, 0(%BitShift) 6505 // %RotatedNewVal = OP %RotatedOldVal, %Src2 6506 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift) 6507 // %Dest = CS %OldVal, %NewVal, Disp(%Base) 6508 // JNE LoopMBB 6509 // # fall through to DoneMMB 6510 MBB = LoopMBB; 6511 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal) 6512 .addReg(OrigVal).addMBB(StartMBB) 6513 .addReg(Dest).addMBB(LoopMBB); 6514 if (IsSubWord) 6515 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal) 6516 .addReg(OldVal).addReg(BitShift).addImm(0); 6517 if (Invert) { 6518 // Perform the operation normally and then invert every bit of the field. 6519 unsigned Tmp = MRI.createVirtualRegister(RC); 6520 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp).addReg(RotatedOldVal).add(Src2); 6521 if (BitSize <= 32) 6522 // XILF with the upper BitSize bits set. 6523 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal) 6524 .addReg(Tmp).addImm(-1U << (32 - BitSize)); 6525 else { 6526 // Use LCGR and add -1 to the result, which is more compact than 6527 // an XILF, XILH pair. 6528 unsigned Tmp2 = MRI.createVirtualRegister(RC); 6529 BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp); 6530 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal) 6531 .addReg(Tmp2).addImm(-1); 6532 } 6533 } else if (BinOpcode) 6534 // A simply binary operation. 6535 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal) 6536 .addReg(RotatedOldVal) 6537 .add(Src2); 6538 else if (IsSubWord) 6539 // Use RISBG to rotate Src2 into position and use it to replace the 6540 // field in RotatedOldVal. 6541 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal) 6542 .addReg(RotatedOldVal).addReg(Src2.getReg()) 6543 .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize); 6544 if (IsSubWord) 6545 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal) 6546 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0); 6547 BuildMI(MBB, DL, TII->get(CSOpcode), Dest) 6548 .addReg(OldVal) 6549 .addReg(NewVal) 6550 .add(Base) 6551 .addImm(Disp); 6552 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 6553 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB); 6554 MBB->addSuccessor(LoopMBB); 6555 MBB->addSuccessor(DoneMBB); 6556 6557 MI.eraseFromParent(); 6558 return DoneMBB; 6559 } 6560 6561 // Implement EmitInstrWithCustomInserter for pseudo 6562 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI. CompareOpcode is the 6563 // instruction that should be used to compare the current field with the 6564 // minimum or maximum value. KeepOldMask is the BRC condition-code mask 6565 // for when the current field should be kept. BitSize is the width of 6566 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction. 6567 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax( 6568 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode, 6569 unsigned KeepOldMask, unsigned BitSize) const { 6570 MachineFunction &MF = *MBB->getParent(); 6571 const SystemZInstrInfo *TII = 6572 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 6573 MachineRegisterInfo &MRI = MF.getRegInfo(); 6574 bool IsSubWord = (BitSize < 32); 6575 6576 // Extract the operands. Base can be a register or a frame index. 6577 unsigned Dest = MI.getOperand(0).getReg(); 6578 MachineOperand Base = earlyUseOperand(MI.getOperand(1)); 6579 int64_t Disp = MI.getOperand(2).getImm(); 6580 unsigned Src2 = MI.getOperand(3).getReg(); 6581 unsigned BitShift = (IsSubWord ? MI.getOperand(4).getReg() : 0); 6582 unsigned NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : 0); 6583 DebugLoc DL = MI.getDebugLoc(); 6584 if (IsSubWord) 6585 BitSize = MI.getOperand(6).getImm(); 6586 6587 // Subword operations use 32-bit registers. 6588 const TargetRegisterClass *RC = (BitSize <= 32 ? 6589 &SystemZ::GR32BitRegClass : 6590 &SystemZ::GR64BitRegClass); 6591 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG; 6592 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG; 6593 6594 // Get the right opcodes for the displacement. 6595 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp); 6596 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp); 6597 assert(LOpcode && CSOpcode && "Displacement out of range"); 6598 6599 // Create virtual registers for temporary results. 6600 unsigned OrigVal = MRI.createVirtualRegister(RC); 6601 unsigned OldVal = MRI.createVirtualRegister(RC); 6602 unsigned NewVal = MRI.createVirtualRegister(RC); 6603 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal); 6604 unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2); 6605 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal); 6606 6607 // Insert 3 basic blocks for the loop. 6608 MachineBasicBlock *StartMBB = MBB; 6609 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB); 6610 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB); 6611 MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB); 6612 MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB); 6613 6614 // StartMBB: 6615 // ... 6616 // %OrigVal = L Disp(%Base) 6617 // # fall through to LoopMMB 6618 MBB = StartMBB; 6619 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0); 6620 MBB->addSuccessor(LoopMBB); 6621 6622 // LoopMBB: 6623 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ] 6624 // %RotatedOldVal = RLL %OldVal, 0(%BitShift) 6625 // CompareOpcode %RotatedOldVal, %Src2 6626 // BRC KeepOldMask, UpdateMBB 6627 MBB = LoopMBB; 6628 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal) 6629 .addReg(OrigVal).addMBB(StartMBB) 6630 .addReg(Dest).addMBB(UpdateMBB); 6631 if (IsSubWord) 6632 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal) 6633 .addReg(OldVal).addReg(BitShift).addImm(0); 6634 BuildMI(MBB, DL, TII->get(CompareOpcode)) 6635 .addReg(RotatedOldVal).addReg(Src2); 6636 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 6637 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB); 6638 MBB->addSuccessor(UpdateMBB); 6639 MBB->addSuccessor(UseAltMBB); 6640 6641 // UseAltMBB: 6642 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0 6643 // # fall through to UpdateMMB 6644 MBB = UseAltMBB; 6645 if (IsSubWord) 6646 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal) 6647 .addReg(RotatedOldVal).addReg(Src2) 6648 .addImm(32).addImm(31 + BitSize).addImm(0); 6649 MBB->addSuccessor(UpdateMBB); 6650 6651 // UpdateMBB: 6652 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ], 6653 // [ %RotatedAltVal, UseAltMBB ] 6654 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift) 6655 // %Dest = CS %OldVal, %NewVal, Disp(%Base) 6656 // JNE LoopMBB 6657 // # fall through to DoneMMB 6658 MBB = UpdateMBB; 6659 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal) 6660 .addReg(RotatedOldVal).addMBB(LoopMBB) 6661 .addReg(RotatedAltVal).addMBB(UseAltMBB); 6662 if (IsSubWord) 6663 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal) 6664 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0); 6665 BuildMI(MBB, DL, TII->get(CSOpcode), Dest) 6666 .addReg(OldVal) 6667 .addReg(NewVal) 6668 .add(Base) 6669 .addImm(Disp); 6670 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 6671 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB); 6672 MBB->addSuccessor(LoopMBB); 6673 MBB->addSuccessor(DoneMBB); 6674 6675 MI.eraseFromParent(); 6676 return DoneMBB; 6677 } 6678 6679 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW 6680 // instruction MI. 6681 MachineBasicBlock * 6682 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI, 6683 MachineBasicBlock *MBB) const { 6684 6685 MachineFunction &MF = *MBB->getParent(); 6686 const SystemZInstrInfo *TII = 6687 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 6688 MachineRegisterInfo &MRI = MF.getRegInfo(); 6689 6690 // Extract the operands. Base can be a register or a frame index. 6691 unsigned Dest = MI.getOperand(0).getReg(); 6692 MachineOperand Base = earlyUseOperand(MI.getOperand(1)); 6693 int64_t Disp = MI.getOperand(2).getImm(); 6694 unsigned OrigCmpVal = MI.getOperand(3).getReg(); 6695 unsigned OrigSwapVal = MI.getOperand(4).getReg(); 6696 unsigned BitShift = MI.getOperand(5).getReg(); 6697 unsigned NegBitShift = MI.getOperand(6).getReg(); 6698 int64_t BitSize = MI.getOperand(7).getImm(); 6699 DebugLoc DL = MI.getDebugLoc(); 6700 6701 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass; 6702 6703 // Get the right opcodes for the displacement. 6704 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp); 6705 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp); 6706 assert(LOpcode && CSOpcode && "Displacement out of range"); 6707 6708 // Create virtual registers for temporary results. 6709 unsigned OrigOldVal = MRI.createVirtualRegister(RC); 6710 unsigned OldVal = MRI.createVirtualRegister(RC); 6711 unsigned CmpVal = MRI.createVirtualRegister(RC); 6712 unsigned SwapVal = MRI.createVirtualRegister(RC); 6713 unsigned StoreVal = MRI.createVirtualRegister(RC); 6714 unsigned RetryOldVal = MRI.createVirtualRegister(RC); 6715 unsigned RetryCmpVal = MRI.createVirtualRegister(RC); 6716 unsigned RetrySwapVal = MRI.createVirtualRegister(RC); 6717 6718 // Insert 2 basic blocks for the loop. 6719 MachineBasicBlock *StartMBB = MBB; 6720 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB); 6721 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB); 6722 MachineBasicBlock *SetMBB = emitBlockAfter(LoopMBB); 6723 6724 // StartMBB: 6725 // ... 6726 // %OrigOldVal = L Disp(%Base) 6727 // # fall through to LoopMMB 6728 MBB = StartMBB; 6729 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal) 6730 .add(Base) 6731 .addImm(Disp) 6732 .addReg(0); 6733 MBB->addSuccessor(LoopMBB); 6734 6735 // LoopMBB: 6736 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ] 6737 // %CmpVal = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ] 6738 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ] 6739 // %Dest = RLL %OldVal, BitSize(%BitShift) 6740 // ^^ The low BitSize bits contain the field 6741 // of interest. 6742 // %RetryCmpVal = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0 6743 // ^^ Replace the upper 32-BitSize bits of the 6744 // comparison value with those that we loaded, 6745 // so that we can use a full word comparison. 6746 // CR %Dest, %RetryCmpVal 6747 // JNE DoneMBB 6748 // # Fall through to SetMBB 6749 MBB = LoopMBB; 6750 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal) 6751 .addReg(OrigOldVal).addMBB(StartMBB) 6752 .addReg(RetryOldVal).addMBB(SetMBB); 6753 BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal) 6754 .addReg(OrigCmpVal).addMBB(StartMBB) 6755 .addReg(RetryCmpVal).addMBB(SetMBB); 6756 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal) 6757 .addReg(OrigSwapVal).addMBB(StartMBB) 6758 .addReg(RetrySwapVal).addMBB(SetMBB); 6759 BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest) 6760 .addReg(OldVal).addReg(BitShift).addImm(BitSize); 6761 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal) 6762 .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0); 6763 BuildMI(MBB, DL, TII->get(SystemZ::CR)) 6764 .addReg(Dest).addReg(RetryCmpVal); 6765 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 6766 .addImm(SystemZ::CCMASK_ICMP) 6767 .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB); 6768 MBB->addSuccessor(DoneMBB); 6769 MBB->addSuccessor(SetMBB); 6770 6771 // SetMBB: 6772 // %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0 6773 // ^^ Replace the upper 32-BitSize bits of the new 6774 // value with those that we loaded. 6775 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift) 6776 // ^^ Rotate the new field to its proper position. 6777 // %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base) 6778 // JNE LoopMBB 6779 // # fall through to ExitMMB 6780 MBB = SetMBB; 6781 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal) 6782 .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0); 6783 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal) 6784 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize); 6785 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal) 6786 .addReg(OldVal) 6787 .addReg(StoreVal) 6788 .add(Base) 6789 .addImm(Disp); 6790 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 6791 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB); 6792 MBB->addSuccessor(LoopMBB); 6793 MBB->addSuccessor(DoneMBB); 6794 6795 // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in 6796 // to the block after the loop. At this point, CC may have been defined 6797 // either by the CR in LoopMBB or by the CS in SetMBB. 6798 if (!MI.registerDefIsDead(SystemZ::CC)) 6799 DoneMBB->addLiveIn(SystemZ::CC); 6800 6801 MI.eraseFromParent(); 6802 return DoneMBB; 6803 } 6804 6805 // Emit a move from two GR64s to a GR128. 6806 MachineBasicBlock * 6807 SystemZTargetLowering::emitPair128(MachineInstr &MI, 6808 MachineBasicBlock *MBB) const { 6809 MachineFunction &MF = *MBB->getParent(); 6810 const SystemZInstrInfo *TII = 6811 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 6812 MachineRegisterInfo &MRI = MF.getRegInfo(); 6813 DebugLoc DL = MI.getDebugLoc(); 6814 6815 unsigned Dest = MI.getOperand(0).getReg(); 6816 unsigned Hi = MI.getOperand(1).getReg(); 6817 unsigned Lo = MI.getOperand(2).getReg(); 6818 unsigned Tmp1 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass); 6819 unsigned Tmp2 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass); 6820 6821 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Tmp1); 6822 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Tmp2) 6823 .addReg(Tmp1).addReg(Hi).addImm(SystemZ::subreg_h64); 6824 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest) 6825 .addReg(Tmp2).addReg(Lo).addImm(SystemZ::subreg_l64); 6826 6827 MI.eraseFromParent(); 6828 return MBB; 6829 } 6830 6831 // Emit an extension from a GR64 to a GR128. ClearEven is true 6832 // if the high register of the GR128 value must be cleared or false if 6833 // it's "don't care". 6834 MachineBasicBlock *SystemZTargetLowering::emitExt128(MachineInstr &MI, 6835 MachineBasicBlock *MBB, 6836 bool ClearEven) const { 6837 MachineFunction &MF = *MBB->getParent(); 6838 const SystemZInstrInfo *TII = 6839 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 6840 MachineRegisterInfo &MRI = MF.getRegInfo(); 6841 DebugLoc DL = MI.getDebugLoc(); 6842 6843 unsigned Dest = MI.getOperand(0).getReg(); 6844 unsigned Src = MI.getOperand(1).getReg(); 6845 unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass); 6846 6847 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128); 6848 if (ClearEven) { 6849 unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass); 6850 unsigned Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass); 6851 6852 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64) 6853 .addImm(0); 6854 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128) 6855 .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64); 6856 In128 = NewIn128; 6857 } 6858 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest) 6859 .addReg(In128).addReg(Src).addImm(SystemZ::subreg_l64); 6860 6861 MI.eraseFromParent(); 6862 return MBB; 6863 } 6864 6865 MachineBasicBlock *SystemZTargetLowering::emitMemMemWrapper( 6866 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const { 6867 MachineFunction &MF = *MBB->getParent(); 6868 const SystemZInstrInfo *TII = 6869 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 6870 MachineRegisterInfo &MRI = MF.getRegInfo(); 6871 DebugLoc DL = MI.getDebugLoc(); 6872 6873 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0)); 6874 uint64_t DestDisp = MI.getOperand(1).getImm(); 6875 MachineOperand SrcBase = earlyUseOperand(MI.getOperand(2)); 6876 uint64_t SrcDisp = MI.getOperand(3).getImm(); 6877 uint64_t Length = MI.getOperand(4).getImm(); 6878 6879 // When generating more than one CLC, all but the last will need to 6880 // branch to the end when a difference is found. 6881 MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ? 6882 splitBlockAfter(MI, MBB) : nullptr); 6883 6884 // Check for the loop form, in which operand 5 is the trip count. 6885 if (MI.getNumExplicitOperands() > 5) { 6886 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase); 6887 6888 uint64_t StartCountReg = MI.getOperand(5).getReg(); 6889 uint64_t StartSrcReg = forceReg(MI, SrcBase, TII); 6890 uint64_t StartDestReg = (HaveSingleBase ? StartSrcReg : 6891 forceReg(MI, DestBase, TII)); 6892 6893 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass; 6894 uint64_t ThisSrcReg = MRI.createVirtualRegister(RC); 6895 uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg : 6896 MRI.createVirtualRegister(RC)); 6897 uint64_t NextSrcReg = MRI.createVirtualRegister(RC); 6898 uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg : 6899 MRI.createVirtualRegister(RC)); 6900 6901 RC = &SystemZ::GR64BitRegClass; 6902 uint64_t ThisCountReg = MRI.createVirtualRegister(RC); 6903 uint64_t NextCountReg = MRI.createVirtualRegister(RC); 6904 6905 MachineBasicBlock *StartMBB = MBB; 6906 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB); 6907 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB); 6908 MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB); 6909 6910 // StartMBB: 6911 // # fall through to LoopMMB 6912 MBB->addSuccessor(LoopMBB); 6913 6914 // LoopMBB: 6915 // %ThisDestReg = phi [ %StartDestReg, StartMBB ], 6916 // [ %NextDestReg, NextMBB ] 6917 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ], 6918 // [ %NextSrcReg, NextMBB ] 6919 // %ThisCountReg = phi [ %StartCountReg, StartMBB ], 6920 // [ %NextCountReg, NextMBB ] 6921 // ( PFD 2, 768+DestDisp(%ThisDestReg) ) 6922 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg) 6923 // ( JLH EndMBB ) 6924 // 6925 // The prefetch is used only for MVC. The JLH is used only for CLC. 6926 MBB = LoopMBB; 6927 6928 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg) 6929 .addReg(StartDestReg).addMBB(StartMBB) 6930 .addReg(NextDestReg).addMBB(NextMBB); 6931 if (!HaveSingleBase) 6932 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg) 6933 .addReg(StartSrcReg).addMBB(StartMBB) 6934 .addReg(NextSrcReg).addMBB(NextMBB); 6935 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg) 6936 .addReg(StartCountReg).addMBB(StartMBB) 6937 .addReg(NextCountReg).addMBB(NextMBB); 6938 if (Opcode == SystemZ::MVC) 6939 BuildMI(MBB, DL, TII->get(SystemZ::PFD)) 6940 .addImm(SystemZ::PFD_WRITE) 6941 .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0); 6942 BuildMI(MBB, DL, TII->get(Opcode)) 6943 .addReg(ThisDestReg).addImm(DestDisp).addImm(256) 6944 .addReg(ThisSrcReg).addImm(SrcDisp); 6945 if (EndMBB) { 6946 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 6947 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE) 6948 .addMBB(EndMBB); 6949 MBB->addSuccessor(EndMBB); 6950 MBB->addSuccessor(NextMBB); 6951 } 6952 6953 // NextMBB: 6954 // %NextDestReg = LA 256(%ThisDestReg) 6955 // %NextSrcReg = LA 256(%ThisSrcReg) 6956 // %NextCountReg = AGHI %ThisCountReg, -1 6957 // CGHI %NextCountReg, 0 6958 // JLH LoopMBB 6959 // # fall through to DoneMMB 6960 // 6961 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes. 6962 MBB = NextMBB; 6963 6964 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg) 6965 .addReg(ThisDestReg).addImm(256).addReg(0); 6966 if (!HaveSingleBase) 6967 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg) 6968 .addReg(ThisSrcReg).addImm(256).addReg(0); 6969 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg) 6970 .addReg(ThisCountReg).addImm(-1); 6971 BuildMI(MBB, DL, TII->get(SystemZ::CGHI)) 6972 .addReg(NextCountReg).addImm(0); 6973 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 6974 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE) 6975 .addMBB(LoopMBB); 6976 MBB->addSuccessor(LoopMBB); 6977 MBB->addSuccessor(DoneMBB); 6978 6979 DestBase = MachineOperand::CreateReg(NextDestReg, false); 6980 SrcBase = MachineOperand::CreateReg(NextSrcReg, false); 6981 Length &= 255; 6982 if (EndMBB && !Length) 6983 // If the loop handled the whole CLC range, DoneMBB will be empty with 6984 // CC live-through into EndMBB, so add it as live-in. 6985 DoneMBB->addLiveIn(SystemZ::CC); 6986 MBB = DoneMBB; 6987 } 6988 // Handle any remaining bytes with straight-line code. 6989 while (Length > 0) { 6990 uint64_t ThisLength = std::min(Length, uint64_t(256)); 6991 // The previous iteration might have created out-of-range displacements. 6992 // Apply them using LAY if so. 6993 if (!isUInt<12>(DestDisp)) { 6994 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass); 6995 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg) 6996 .add(DestBase) 6997 .addImm(DestDisp) 6998 .addReg(0); 6999 DestBase = MachineOperand::CreateReg(Reg, false); 7000 DestDisp = 0; 7001 } 7002 if (!isUInt<12>(SrcDisp)) { 7003 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass); 7004 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg) 7005 .add(SrcBase) 7006 .addImm(SrcDisp) 7007 .addReg(0); 7008 SrcBase = MachineOperand::CreateReg(Reg, false); 7009 SrcDisp = 0; 7010 } 7011 BuildMI(*MBB, MI, DL, TII->get(Opcode)) 7012 .add(DestBase) 7013 .addImm(DestDisp) 7014 .addImm(ThisLength) 7015 .add(SrcBase) 7016 .addImm(SrcDisp) 7017 .setMemRefs(MI.memoperands()); 7018 DestDisp += ThisLength; 7019 SrcDisp += ThisLength; 7020 Length -= ThisLength; 7021 // If there's another CLC to go, branch to the end if a difference 7022 // was found. 7023 if (EndMBB && Length > 0) { 7024 MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB); 7025 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 7026 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE) 7027 .addMBB(EndMBB); 7028 MBB->addSuccessor(EndMBB); 7029 MBB->addSuccessor(NextMBB); 7030 MBB = NextMBB; 7031 } 7032 } 7033 if (EndMBB) { 7034 MBB->addSuccessor(EndMBB); 7035 MBB = EndMBB; 7036 MBB->addLiveIn(SystemZ::CC); 7037 } 7038 7039 MI.eraseFromParent(); 7040 return MBB; 7041 } 7042 7043 // Decompose string pseudo-instruction MI into a loop that continually performs 7044 // Opcode until CC != 3. 7045 MachineBasicBlock *SystemZTargetLowering::emitStringWrapper( 7046 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const { 7047 MachineFunction &MF = *MBB->getParent(); 7048 const SystemZInstrInfo *TII = 7049 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 7050 MachineRegisterInfo &MRI = MF.getRegInfo(); 7051 DebugLoc DL = MI.getDebugLoc(); 7052 7053 uint64_t End1Reg = MI.getOperand(0).getReg(); 7054 uint64_t Start1Reg = MI.getOperand(1).getReg(); 7055 uint64_t Start2Reg = MI.getOperand(2).getReg(); 7056 uint64_t CharReg = MI.getOperand(3).getReg(); 7057 7058 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass; 7059 uint64_t This1Reg = MRI.createVirtualRegister(RC); 7060 uint64_t This2Reg = MRI.createVirtualRegister(RC); 7061 uint64_t End2Reg = MRI.createVirtualRegister(RC); 7062 7063 MachineBasicBlock *StartMBB = MBB; 7064 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB); 7065 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB); 7066 7067 // StartMBB: 7068 // # fall through to LoopMMB 7069 MBB->addSuccessor(LoopMBB); 7070 7071 // LoopMBB: 7072 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ] 7073 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ] 7074 // R0L = %CharReg 7075 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L 7076 // JO LoopMBB 7077 // # fall through to DoneMMB 7078 // 7079 // The load of R0L can be hoisted by post-RA LICM. 7080 MBB = LoopMBB; 7081 7082 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg) 7083 .addReg(Start1Reg).addMBB(StartMBB) 7084 .addReg(End1Reg).addMBB(LoopMBB); 7085 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg) 7086 .addReg(Start2Reg).addMBB(StartMBB) 7087 .addReg(End2Reg).addMBB(LoopMBB); 7088 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg); 7089 BuildMI(MBB, DL, TII->get(Opcode)) 7090 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define) 7091 .addReg(This1Reg).addReg(This2Reg); 7092 BuildMI(MBB, DL, TII->get(SystemZ::BRC)) 7093 .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB); 7094 MBB->addSuccessor(LoopMBB); 7095 MBB->addSuccessor(DoneMBB); 7096 7097 DoneMBB->addLiveIn(SystemZ::CC); 7098 7099 MI.eraseFromParent(); 7100 return DoneMBB; 7101 } 7102 7103 // Update TBEGIN instruction with final opcode and register clobbers. 7104 MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin( 7105 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode, 7106 bool NoFloat) const { 7107 MachineFunction &MF = *MBB->getParent(); 7108 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 7109 const SystemZInstrInfo *TII = Subtarget.getInstrInfo(); 7110 7111 // Update opcode. 7112 MI.setDesc(TII->get(Opcode)); 7113 7114 // We cannot handle a TBEGIN that clobbers the stack or frame pointer. 7115 // Make sure to add the corresponding GRSM bits if they are missing. 7116 uint64_t Control = MI.getOperand(2).getImm(); 7117 static const unsigned GPRControlBit[16] = { 7118 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000, 7119 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100 7120 }; 7121 Control |= GPRControlBit[15]; 7122 if (TFI->hasFP(MF)) 7123 Control |= GPRControlBit[11]; 7124 MI.getOperand(2).setImm(Control); 7125 7126 // Add GPR clobbers. 7127 for (int I = 0; I < 16; I++) { 7128 if ((Control & GPRControlBit[I]) == 0) { 7129 unsigned Reg = SystemZMC::GR64Regs[I]; 7130 MI.addOperand(MachineOperand::CreateReg(Reg, true, true)); 7131 } 7132 } 7133 7134 // Add FPR/VR clobbers. 7135 if (!NoFloat && (Control & 4) != 0) { 7136 if (Subtarget.hasVector()) { 7137 for (int I = 0; I < 32; I++) { 7138 unsigned Reg = SystemZMC::VR128Regs[I]; 7139 MI.addOperand(MachineOperand::CreateReg(Reg, true, true)); 7140 } 7141 } else { 7142 for (int I = 0; I < 16; I++) { 7143 unsigned Reg = SystemZMC::FP64Regs[I]; 7144 MI.addOperand(MachineOperand::CreateReg(Reg, true, true)); 7145 } 7146 } 7147 } 7148 7149 return MBB; 7150 } 7151 7152 MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0( 7153 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const { 7154 MachineFunction &MF = *MBB->getParent(); 7155 MachineRegisterInfo *MRI = &MF.getRegInfo(); 7156 const SystemZInstrInfo *TII = 7157 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo()); 7158 DebugLoc DL = MI.getDebugLoc(); 7159 7160 unsigned SrcReg = MI.getOperand(0).getReg(); 7161 7162 // Create new virtual register of the same class as source. 7163 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg); 7164 unsigned DstReg = MRI->createVirtualRegister(RC); 7165 7166 // Replace pseudo with a normal load-and-test that models the def as 7167 // well. 7168 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg) 7169 .addReg(SrcReg); 7170 MI.eraseFromParent(); 7171 7172 return MBB; 7173 } 7174 7175 MachineBasicBlock *SystemZTargetLowering::EmitInstrWithCustomInserter( 7176 MachineInstr &MI, MachineBasicBlock *MBB) const { 7177 switch (MI.getOpcode()) { 7178 case SystemZ::Select32: 7179 case SystemZ::Select64: 7180 case SystemZ::SelectF32: 7181 case SystemZ::SelectF64: 7182 case SystemZ::SelectF128: 7183 case SystemZ::SelectVR32: 7184 case SystemZ::SelectVR64: 7185 case SystemZ::SelectVR128: 7186 return emitSelect(MI, MBB); 7187 7188 case SystemZ::CondStore8Mux: 7189 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false); 7190 case SystemZ::CondStore8MuxInv: 7191 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true); 7192 case SystemZ::CondStore16Mux: 7193 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false); 7194 case SystemZ::CondStore16MuxInv: 7195 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true); 7196 case SystemZ::CondStore32Mux: 7197 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false); 7198 case SystemZ::CondStore32MuxInv: 7199 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true); 7200 case SystemZ::CondStore8: 7201 return emitCondStore(MI, MBB, SystemZ::STC, 0, false); 7202 case SystemZ::CondStore8Inv: 7203 return emitCondStore(MI, MBB, SystemZ::STC, 0, true); 7204 case SystemZ::CondStore16: 7205 return emitCondStore(MI, MBB, SystemZ::STH, 0, false); 7206 case SystemZ::CondStore16Inv: 7207 return emitCondStore(MI, MBB, SystemZ::STH, 0, true); 7208 case SystemZ::CondStore32: 7209 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false); 7210 case SystemZ::CondStore32Inv: 7211 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true); 7212 case SystemZ::CondStore64: 7213 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false); 7214 case SystemZ::CondStore64Inv: 7215 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true); 7216 case SystemZ::CondStoreF32: 7217 return emitCondStore(MI, MBB, SystemZ::STE, 0, false); 7218 case SystemZ::CondStoreF32Inv: 7219 return emitCondStore(MI, MBB, SystemZ::STE, 0, true); 7220 case SystemZ::CondStoreF64: 7221 return emitCondStore(MI, MBB, SystemZ::STD, 0, false); 7222 case SystemZ::CondStoreF64Inv: 7223 return emitCondStore(MI, MBB, SystemZ::STD, 0, true); 7224 7225 case SystemZ::PAIR128: 7226 return emitPair128(MI, MBB); 7227 case SystemZ::AEXT128: 7228 return emitExt128(MI, MBB, false); 7229 case SystemZ::ZEXT128: 7230 return emitExt128(MI, MBB, true); 7231 7232 case SystemZ::ATOMIC_SWAPW: 7233 return emitAtomicLoadBinary(MI, MBB, 0, 0); 7234 case SystemZ::ATOMIC_SWAP_32: 7235 return emitAtomicLoadBinary(MI, MBB, 0, 32); 7236 case SystemZ::ATOMIC_SWAP_64: 7237 return emitAtomicLoadBinary(MI, MBB, 0, 64); 7238 7239 case SystemZ::ATOMIC_LOADW_AR: 7240 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0); 7241 case SystemZ::ATOMIC_LOADW_AFI: 7242 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0); 7243 case SystemZ::ATOMIC_LOAD_AR: 7244 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32); 7245 case SystemZ::ATOMIC_LOAD_AHI: 7246 return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32); 7247 case SystemZ::ATOMIC_LOAD_AFI: 7248 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32); 7249 case SystemZ::ATOMIC_LOAD_AGR: 7250 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64); 7251 case SystemZ::ATOMIC_LOAD_AGHI: 7252 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64); 7253 case SystemZ::ATOMIC_LOAD_AGFI: 7254 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64); 7255 7256 case SystemZ::ATOMIC_LOADW_SR: 7257 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0); 7258 case SystemZ::ATOMIC_LOAD_SR: 7259 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32); 7260 case SystemZ::ATOMIC_LOAD_SGR: 7261 return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64); 7262 7263 case SystemZ::ATOMIC_LOADW_NR: 7264 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0); 7265 case SystemZ::ATOMIC_LOADW_NILH: 7266 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0); 7267 case SystemZ::ATOMIC_LOAD_NR: 7268 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32); 7269 case SystemZ::ATOMIC_LOAD_NILL: 7270 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32); 7271 case SystemZ::ATOMIC_LOAD_NILH: 7272 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32); 7273 case SystemZ::ATOMIC_LOAD_NILF: 7274 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32); 7275 case SystemZ::ATOMIC_LOAD_NGR: 7276 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64); 7277 case SystemZ::ATOMIC_LOAD_NILL64: 7278 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64); 7279 case SystemZ::ATOMIC_LOAD_NILH64: 7280 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64); 7281 case SystemZ::ATOMIC_LOAD_NIHL64: 7282 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64); 7283 case SystemZ::ATOMIC_LOAD_NIHH64: 7284 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64); 7285 case SystemZ::ATOMIC_LOAD_NILF64: 7286 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64); 7287 case SystemZ::ATOMIC_LOAD_NIHF64: 7288 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64); 7289 7290 case SystemZ::ATOMIC_LOADW_OR: 7291 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0); 7292 case SystemZ::ATOMIC_LOADW_OILH: 7293 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0); 7294 case SystemZ::ATOMIC_LOAD_OR: 7295 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32); 7296 case SystemZ::ATOMIC_LOAD_OILL: 7297 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32); 7298 case SystemZ::ATOMIC_LOAD_OILH: 7299 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32); 7300 case SystemZ::ATOMIC_LOAD_OILF: 7301 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32); 7302 case SystemZ::ATOMIC_LOAD_OGR: 7303 return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64); 7304 case SystemZ::ATOMIC_LOAD_OILL64: 7305 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64); 7306 case SystemZ::ATOMIC_LOAD_OILH64: 7307 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64); 7308 case SystemZ::ATOMIC_LOAD_OIHL64: 7309 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64); 7310 case SystemZ::ATOMIC_LOAD_OIHH64: 7311 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64); 7312 case SystemZ::ATOMIC_LOAD_OILF64: 7313 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64); 7314 case SystemZ::ATOMIC_LOAD_OIHF64: 7315 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64); 7316 7317 case SystemZ::ATOMIC_LOADW_XR: 7318 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0); 7319 case SystemZ::ATOMIC_LOADW_XILF: 7320 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0); 7321 case SystemZ::ATOMIC_LOAD_XR: 7322 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32); 7323 case SystemZ::ATOMIC_LOAD_XILF: 7324 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32); 7325 case SystemZ::ATOMIC_LOAD_XGR: 7326 return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64); 7327 case SystemZ::ATOMIC_LOAD_XILF64: 7328 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64); 7329 case SystemZ::ATOMIC_LOAD_XIHF64: 7330 return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64); 7331 7332 case SystemZ::ATOMIC_LOADW_NRi: 7333 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true); 7334 case SystemZ::ATOMIC_LOADW_NILHi: 7335 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true); 7336 case SystemZ::ATOMIC_LOAD_NRi: 7337 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true); 7338 case SystemZ::ATOMIC_LOAD_NILLi: 7339 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true); 7340 case SystemZ::ATOMIC_LOAD_NILHi: 7341 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true); 7342 case SystemZ::ATOMIC_LOAD_NILFi: 7343 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true); 7344 case SystemZ::ATOMIC_LOAD_NGRi: 7345 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true); 7346 case SystemZ::ATOMIC_LOAD_NILL64i: 7347 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true); 7348 case SystemZ::ATOMIC_LOAD_NILH64i: 7349 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true); 7350 case SystemZ::ATOMIC_LOAD_NIHL64i: 7351 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true); 7352 case SystemZ::ATOMIC_LOAD_NIHH64i: 7353 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true); 7354 case SystemZ::ATOMIC_LOAD_NILF64i: 7355 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true); 7356 case SystemZ::ATOMIC_LOAD_NIHF64i: 7357 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true); 7358 7359 case SystemZ::ATOMIC_LOADW_MIN: 7360 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, 7361 SystemZ::CCMASK_CMP_LE, 0); 7362 case SystemZ::ATOMIC_LOAD_MIN_32: 7363 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, 7364 SystemZ::CCMASK_CMP_LE, 32); 7365 case SystemZ::ATOMIC_LOAD_MIN_64: 7366 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR, 7367 SystemZ::CCMASK_CMP_LE, 64); 7368 7369 case SystemZ::ATOMIC_LOADW_MAX: 7370 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, 7371 SystemZ::CCMASK_CMP_GE, 0); 7372 case SystemZ::ATOMIC_LOAD_MAX_32: 7373 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, 7374 SystemZ::CCMASK_CMP_GE, 32); 7375 case SystemZ::ATOMIC_LOAD_MAX_64: 7376 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR, 7377 SystemZ::CCMASK_CMP_GE, 64); 7378 7379 case SystemZ::ATOMIC_LOADW_UMIN: 7380 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, 7381 SystemZ::CCMASK_CMP_LE, 0); 7382 case SystemZ::ATOMIC_LOAD_UMIN_32: 7383 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, 7384 SystemZ::CCMASK_CMP_LE, 32); 7385 case SystemZ::ATOMIC_LOAD_UMIN_64: 7386 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR, 7387 SystemZ::CCMASK_CMP_LE, 64); 7388 7389 case SystemZ::ATOMIC_LOADW_UMAX: 7390 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, 7391 SystemZ::CCMASK_CMP_GE, 0); 7392 case SystemZ::ATOMIC_LOAD_UMAX_32: 7393 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, 7394 SystemZ::CCMASK_CMP_GE, 32); 7395 case SystemZ::ATOMIC_LOAD_UMAX_64: 7396 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR, 7397 SystemZ::CCMASK_CMP_GE, 64); 7398 7399 case SystemZ::ATOMIC_CMP_SWAPW: 7400 return emitAtomicCmpSwapW(MI, MBB); 7401 case SystemZ::MVCSequence: 7402 case SystemZ::MVCLoop: 7403 return emitMemMemWrapper(MI, MBB, SystemZ::MVC); 7404 case SystemZ::NCSequence: 7405 case SystemZ::NCLoop: 7406 return emitMemMemWrapper(MI, MBB, SystemZ::NC); 7407 case SystemZ::OCSequence: 7408 case SystemZ::OCLoop: 7409 return emitMemMemWrapper(MI, MBB, SystemZ::OC); 7410 case SystemZ::XCSequence: 7411 case SystemZ::XCLoop: 7412 return emitMemMemWrapper(MI, MBB, SystemZ::XC); 7413 case SystemZ::CLCSequence: 7414 case SystemZ::CLCLoop: 7415 return emitMemMemWrapper(MI, MBB, SystemZ::CLC); 7416 case SystemZ::CLSTLoop: 7417 return emitStringWrapper(MI, MBB, SystemZ::CLST); 7418 case SystemZ::MVSTLoop: 7419 return emitStringWrapper(MI, MBB, SystemZ::MVST); 7420 case SystemZ::SRSTLoop: 7421 return emitStringWrapper(MI, MBB, SystemZ::SRST); 7422 case SystemZ::TBEGIN: 7423 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false); 7424 case SystemZ::TBEGIN_nofloat: 7425 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true); 7426 case SystemZ::TBEGINC: 7427 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true); 7428 case SystemZ::LTEBRCompare_VecPseudo: 7429 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR); 7430 case SystemZ::LTDBRCompare_VecPseudo: 7431 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR); 7432 case SystemZ::LTXBRCompare_VecPseudo: 7433 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR); 7434 7435 case TargetOpcode::STACKMAP: 7436 case TargetOpcode::PATCHPOINT: 7437 return emitPatchPoint(MI, MBB); 7438 7439 default: 7440 llvm_unreachable("Unexpected instr type to insert"); 7441 } 7442 } 7443 7444 // This is only used by the isel schedulers, and is needed only to prevent 7445 // compiler from crashing when list-ilp is used. 7446 const TargetRegisterClass * 7447 SystemZTargetLowering::getRepRegClassFor(MVT VT) const { 7448 if (VT == MVT::Untyped) 7449 return &SystemZ::ADDR128BitRegClass; 7450 return TargetLowering::getRepRegClassFor(VT); 7451 } 7452