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