1 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SystemZTargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "SystemZISelLowering.h"
15 #include "SystemZCallingConv.h"
16 #include "SystemZConstantPoolValue.h"
17 #include "SystemZMachineFunctionInfo.h"
18 #include "SystemZTargetMachine.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
23 #include "llvm/IR/Intrinsics.h"
28 #define DEBUG_TYPE "systemz-lower"
31 // Represents a sequence for extracting a 0/1 value from an IPM result:
32 // (((X ^ XORValue) + AddValue) >> Bit)
33 struct IPMConversion {
34 IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
35 : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
42 // Represents information about a comparison.
44 Comparison(SDValue Op0In, SDValue Op1In)
45 : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
47 // The operands to the comparison.
50 // The opcode that should be used to compare Op0 and Op1.
53 // A SystemZICMP value. Only used for integer comparisons.
56 // The mask of CC values that Opcode can produce.
59 // The mask of CC values for which the original condition is true.
62 } // end anonymous namespace
64 // Classify VT as either 32 or 64 bit.
65 static bool is32Bit(EVT VT) {
66 switch (VT.getSimpleVT().SimpleTy) {
72 llvm_unreachable("Unsupported type");
76 // Return a version of MachineOperand that can be safely used before the
78 static MachineOperand earlyUseOperand(MachineOperand Op) {
84 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &tm,
85 const SystemZSubtarget &STI)
86 : TargetLowering(tm), Subtarget(STI) {
87 MVT PtrVT = getPointerTy();
89 // Set up the register classes.
90 if (Subtarget.hasHighWord())
91 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
93 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
94 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
95 if (Subtarget.hasVector()) {
96 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
97 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
99 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
100 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
102 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
104 if (Subtarget.hasVector()) {
105 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
106 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
107 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
108 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
109 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
110 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
113 // Compute derived properties from the register classes
114 computeRegisterProperties(Subtarget.getRegisterInfo());
116 // Set up special registers.
117 setExceptionPointerRegister(SystemZ::R6D);
118 setExceptionSelectorRegister(SystemZ::R7D);
119 setStackPointerRegisterToSaveRestore(SystemZ::R15D);
121 // TODO: It may be better to default to latency-oriented scheduling, however
122 // LLVM's current latency-oriented scheduler can't handle physreg definitions
123 // such as SystemZ has with CC, so set this to the register-pressure
124 // scheduler, because it can.
125 setSchedulingPreference(Sched::RegPressure);
127 setBooleanContents(ZeroOrOneBooleanContent);
128 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
130 // Instructions are strings of 2-byte aligned 2-byte values.
131 setMinFunctionAlignment(2);
133 // Handle operations that are handled in a similar way for all types.
134 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
135 I <= MVT::LAST_FP_VALUETYPE;
137 MVT VT = MVT::SimpleValueType(I);
138 if (isTypeLegal(VT)) {
139 // Lower SET_CC into an IPM-based sequence.
140 setOperationAction(ISD::SETCC, VT, Custom);
142 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
143 setOperationAction(ISD::SELECT, VT, Expand);
145 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
146 setOperationAction(ISD::SELECT_CC, VT, Custom);
147 setOperationAction(ISD::BR_CC, VT, Custom);
151 // Expand jump table branches as address arithmetic followed by an
153 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
155 // Expand BRCOND into a BR_CC (see above).
156 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
158 // Handle integer types.
159 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
160 I <= MVT::LAST_INTEGER_VALUETYPE;
162 MVT VT = MVT::SimpleValueType(I);
163 if (isTypeLegal(VT)) {
164 // Expand individual DIV and REMs into DIVREMs.
165 setOperationAction(ISD::SDIV, VT, Expand);
166 setOperationAction(ISD::UDIV, VT, Expand);
167 setOperationAction(ISD::SREM, VT, Expand);
168 setOperationAction(ISD::UREM, VT, Expand);
169 setOperationAction(ISD::SDIVREM, VT, Custom);
170 setOperationAction(ISD::UDIVREM, VT, Custom);
172 // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
173 // stores, putting a serialization instruction after the stores.
174 setOperationAction(ISD::ATOMIC_LOAD, VT, Custom);
175 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
177 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
178 // available, or if the operand is constant.
179 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
181 // Use POPCNT on z196 and above.
182 if (Subtarget.hasPopulationCount())
183 setOperationAction(ISD::CTPOP, VT, Custom);
185 setOperationAction(ISD::CTPOP, VT, Expand);
187 // No special instructions for these.
188 setOperationAction(ISD::CTTZ, VT, Expand);
189 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
190 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
191 setOperationAction(ISD::ROTR, VT, Expand);
193 // Use *MUL_LOHI where possible instead of MULH*.
194 setOperationAction(ISD::MULHS, VT, Expand);
195 setOperationAction(ISD::MULHU, VT, Expand);
196 setOperationAction(ISD::SMUL_LOHI, VT, Custom);
197 setOperationAction(ISD::UMUL_LOHI, VT, Custom);
199 // Only z196 and above have native support for conversions to unsigned.
200 if (!Subtarget.hasFPExtension())
201 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
205 // Type legalization will convert 8- and 16-bit atomic operations into
206 // forms that operate on i32s (but still keeping the original memory VT).
207 // Lower them into full i32 operations.
208 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Custom);
209 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Custom);
210 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
211 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
212 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Custom);
213 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Custom);
214 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
215 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Custom);
216 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Custom);
217 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
218 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
219 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
221 // z10 has instructions for signed but not unsigned FP conversion.
222 // Handle unsigned 32-bit types as signed 64-bit types.
223 if (!Subtarget.hasFPExtension()) {
224 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
225 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
228 // We have native support for a 64-bit CTLZ, via FLOGR.
229 setOperationAction(ISD::CTLZ, MVT::i32, Promote);
230 setOperationAction(ISD::CTLZ, MVT::i64, Legal);
232 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
233 setOperationAction(ISD::OR, MVT::i64, Custom);
235 // FIXME: Can we support these natively?
236 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
237 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
238 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
240 // We have native instructions for i8, i16 and i32 extensions, but not i1.
241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
242 for (MVT VT : MVT::integer_valuetypes()) {
243 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
244 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
245 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
248 // Handle the various types of symbolic address.
249 setOperationAction(ISD::ConstantPool, PtrVT, Custom);
250 setOperationAction(ISD::GlobalAddress, PtrVT, Custom);
251 setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
252 setOperationAction(ISD::BlockAddress, PtrVT, Custom);
253 setOperationAction(ISD::JumpTable, PtrVT, Custom);
255 // We need to handle dynamic allocations specially because of the
256 // 160-byte area at the bottom of the stack.
257 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
259 // Use custom expanders so that we can force the function to use
261 setOperationAction(ISD::STACKSAVE, MVT::Other, Custom);
262 setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
264 // Handle prefetches with PFD or PFDRL.
265 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
267 for (MVT VT : MVT::vector_valuetypes()) {
268 // Assume by default that all vector operations need to be expanded.
269 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
270 if (getOperationAction(Opcode, VT) == Legal)
271 setOperationAction(Opcode, VT, Expand);
273 // Likewise all truncating stores and extending loads.
274 for (MVT InnerVT : MVT::vector_valuetypes()) {
275 setTruncStoreAction(VT, InnerVT, Expand);
276 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
277 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
278 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
281 if (isTypeLegal(VT)) {
282 // These operations are legal for anything that can be stored in a
283 // vector register, even if there is no native support for the format
284 // as such. In particular, we can do these for v4f32 even though there
285 // are no specific instructions for that format.
286 setOperationAction(ISD::LOAD, VT, Legal);
287 setOperationAction(ISD::STORE, VT, Legal);
288 setOperationAction(ISD::VSELECT, VT, Legal);
289 setOperationAction(ISD::BITCAST, VT, Legal);
290 setOperationAction(ISD::UNDEF, VT, Legal);
292 // Likewise, except that we need to replace the nodes with something
294 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
295 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
299 // Handle integer vector types.
300 for (MVT VT : MVT::integer_vector_valuetypes()) {
301 if (isTypeLegal(VT)) {
302 // These operations have direct equivalents.
303 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
304 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
305 setOperationAction(ISD::ADD, VT, Legal);
306 setOperationAction(ISD::SUB, VT, Legal);
307 if (VT != MVT::v2i64)
308 setOperationAction(ISD::MUL, VT, Legal);
309 setOperationAction(ISD::AND, VT, Legal);
310 setOperationAction(ISD::OR, VT, Legal);
311 setOperationAction(ISD::XOR, VT, Legal);
312 setOperationAction(ISD::CTPOP, VT, Custom);
313 setOperationAction(ISD::CTTZ, VT, Legal);
314 setOperationAction(ISD::CTLZ, VT, Legal);
315 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
316 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
318 // Convert a GPR scalar to a vector by inserting it into element 0.
319 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
321 // Use a series of unpacks for extensions.
322 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
323 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
325 // Detect shifts by a scalar amount and convert them into
327 setOperationAction(ISD::SHL, VT, Custom);
328 setOperationAction(ISD::SRA, VT, Custom);
329 setOperationAction(ISD::SRL, VT, Custom);
331 // At present ROTL isn't matched by DAGCombiner. ROTR should be
332 // converted into ROTL.
333 setOperationAction(ISD::ROTL, VT, Expand);
334 setOperationAction(ISD::ROTR, VT, Expand);
336 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
337 // and inverting the result as necessary.
338 setOperationAction(ISD::SETCC, VT, Custom);
342 if (Subtarget.hasVector()) {
343 // There should be no need to check for float types other than v2f64
344 // since <2 x f32> isn't a legal type.
345 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
346 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
347 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
348 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
351 // Handle floating-point types.
352 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
353 I <= MVT::LAST_FP_VALUETYPE;
355 MVT VT = MVT::SimpleValueType(I);
356 if (isTypeLegal(VT)) {
357 // We can use FI for FRINT.
358 setOperationAction(ISD::FRINT, VT, Legal);
360 // We can use the extended form of FI for other rounding operations.
361 if (Subtarget.hasFPExtension()) {
362 setOperationAction(ISD::FNEARBYINT, VT, Legal);
363 setOperationAction(ISD::FFLOOR, VT, Legal);
364 setOperationAction(ISD::FCEIL, VT, Legal);
365 setOperationAction(ISD::FTRUNC, VT, Legal);
366 setOperationAction(ISD::FROUND, VT, Legal);
369 // No special instructions for these.
370 setOperationAction(ISD::FSIN, VT, Expand);
371 setOperationAction(ISD::FCOS, VT, Expand);
372 setOperationAction(ISD::FREM, VT, Expand);
376 // Handle floating-point vector types.
377 if (Subtarget.hasVector()) {
378 // Scalar-to-vector conversion is just a subreg.
379 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
380 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
382 // Some insertions and extractions can be done directly but others
383 // need to go via integers.
384 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
385 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
386 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
387 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
389 // These operations have direct equivalents.
390 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
391 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
392 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
393 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
394 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
395 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
396 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
397 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
398 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
399 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
400 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
401 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
402 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
403 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
406 // We have fused multiply-addition for f32 and f64 but not f128.
407 setOperationAction(ISD::FMA, MVT::f32, Legal);
408 setOperationAction(ISD::FMA, MVT::f64, Legal);
409 setOperationAction(ISD::FMA, MVT::f128, Expand);
411 // Needed so that we don't try to implement f128 constant loads using
412 // a load-and-extend of a f80 constant (in cases where the constant
413 // would fit in an f80).
414 for (MVT VT : MVT::fp_valuetypes())
415 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
417 // Floating-point truncation and stores need to be done separately.
418 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
419 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
420 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
422 // We have 64-bit FPR<->GPR moves, but need special handling for
424 if (!Subtarget.hasVector()) {
425 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
426 setOperationAction(ISD::BITCAST, MVT::f32, Custom);
429 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
430 // structure, but VAEND is a no-op.
431 setOperationAction(ISD::VASTART, MVT::Other, Custom);
432 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
433 setOperationAction(ISD::VAEND, MVT::Other, Expand);
435 // Codes for which we want to perform some z-specific combinations.
436 setTargetDAGCombine(ISD::SIGN_EXTEND);
437 setTargetDAGCombine(ISD::STORE);
438 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
439 setTargetDAGCombine(ISD::FP_ROUND);
441 // Handle intrinsics.
442 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
444 // We want to use MVC in preference to even a single load/store pair.
445 MaxStoresPerMemcpy = 0;
446 MaxStoresPerMemcpyOptSize = 0;
448 // The main memset sequence is a byte store followed by an MVC.
449 // Two STC or MV..I stores win over that, but the kind of fused stores
450 // generated by target-independent code don't when the byte value is
451 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
452 // than "STC;MVC". Handle the choice in target-specific code instead.
453 MaxStoresPerMemset = 0;
454 MaxStoresPerMemsetOptSize = 0;
457 EVT SystemZTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
460 return VT.changeVectorElementTypeToInteger();
463 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
464 VT = VT.getScalarType();
469 switch (VT.getSimpleVT().SimpleTy) {
482 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
483 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
484 return Imm.isZero() || Imm.isNegZero();
487 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
488 // We can use CGFI or CLGFI.
489 return isInt<32>(Imm) || isUInt<32>(Imm);
492 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
493 // We can use ALGFI or SLGFI.
494 return isUInt<32>(Imm) || isUInt<32>(-Imm);
497 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
501 // Unaligned accesses should never be slower than the expanded version.
502 // We check specifically for aligned accesses in the few cases where
503 // they are required.
509 bool SystemZTargetLowering::isLegalAddressingMode(const AddrMode &AM,
511 // Punt on globals for now, although they can be used in limited
512 // RELATIVE LONG cases.
516 // Require a 20-bit signed offset.
517 if (!isInt<20>(AM.BaseOffs))
520 // Indexing is OK but no scale factor can be applied.
521 return AM.Scale == 0 || AM.Scale == 1;
524 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
525 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
527 unsigned FromBits = FromType->getPrimitiveSizeInBits();
528 unsigned ToBits = ToType->getPrimitiveSizeInBits();
529 return FromBits > ToBits;
532 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
533 if (!FromVT.isInteger() || !ToVT.isInteger())
535 unsigned FromBits = FromVT.getSizeInBits();
536 unsigned ToBits = ToVT.getSizeInBits();
537 return FromBits > ToBits;
540 //===----------------------------------------------------------------------===//
541 // Inline asm support
542 //===----------------------------------------------------------------------===//
544 TargetLowering::ConstraintType
545 SystemZTargetLowering::getConstraintType(const std::string &Constraint) const {
546 if (Constraint.size() == 1) {
547 switch (Constraint[0]) {
548 case 'a': // Address register
549 case 'd': // Data register (equivalent to 'r')
550 case 'f': // Floating-point register
551 case 'h': // High-part register
552 case 'r': // General-purpose register
553 return C_RegisterClass;
555 case 'Q': // Memory with base and unsigned 12-bit displacement
556 case 'R': // Likewise, plus an index
557 case 'S': // Memory with base and signed 20-bit displacement
558 case 'T': // Likewise, plus an index
559 case 'm': // Equivalent to 'T'.
562 case 'I': // Unsigned 8-bit constant
563 case 'J': // Unsigned 12-bit constant
564 case 'K': // Signed 16-bit constant
565 case 'L': // Signed 20-bit displacement (on all targets we support)
566 case 'M': // 0x7fffffff
573 return TargetLowering::getConstraintType(Constraint);
576 TargetLowering::ConstraintWeight SystemZTargetLowering::
577 getSingleConstraintMatchWeight(AsmOperandInfo &info,
578 const char *constraint) const {
579 ConstraintWeight weight = CW_Invalid;
580 Value *CallOperandVal = info.CallOperandVal;
581 // If we don't have a value, we can't do a match,
582 // but allow it at the lowest weight.
585 Type *type = CallOperandVal->getType();
586 // Look at the constraint type.
587 switch (*constraint) {
589 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
592 case 'a': // Address register
593 case 'd': // Data register (equivalent to 'r')
594 case 'h': // High-part register
595 case 'r': // General-purpose register
596 if (CallOperandVal->getType()->isIntegerTy())
597 weight = CW_Register;
600 case 'f': // Floating-point register
601 if (type->isFloatingPointTy())
602 weight = CW_Register;
605 case 'I': // Unsigned 8-bit constant
606 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
607 if (isUInt<8>(C->getZExtValue()))
608 weight = CW_Constant;
611 case 'J': // Unsigned 12-bit constant
612 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
613 if (isUInt<12>(C->getZExtValue()))
614 weight = CW_Constant;
617 case 'K': // Signed 16-bit constant
618 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
619 if (isInt<16>(C->getSExtValue()))
620 weight = CW_Constant;
623 case 'L': // Signed 20-bit displacement (on all targets we support)
624 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
625 if (isInt<20>(C->getSExtValue()))
626 weight = CW_Constant;
629 case 'M': // 0x7fffffff
630 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
631 if (C->getZExtValue() == 0x7fffffff)
632 weight = CW_Constant;
638 // Parse a "{tNNN}" register constraint for which the register type "t"
639 // has already been verified. MC is the class associated with "t" and
640 // Map maps 0-based register numbers to LLVM register numbers.
641 static std::pair<unsigned, const TargetRegisterClass *>
642 parseRegisterNumber(const std::string &Constraint,
643 const TargetRegisterClass *RC, const unsigned *Map) {
644 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
645 if (isdigit(Constraint[2])) {
646 std::string Suffix(Constraint.data() + 2, Constraint.size() - 2);
647 unsigned Index = atoi(Suffix.c_str());
648 if (Index < 16 && Map[Index])
649 return std::make_pair(Map[Index], RC);
651 return std::make_pair(0U, nullptr);
654 std::pair<unsigned, const TargetRegisterClass *>
655 SystemZTargetLowering::getRegForInlineAsmConstraint(
656 const TargetRegisterInfo *TRI, const std::string &Constraint,
658 if (Constraint.size() == 1) {
659 // GCC Constraint Letters
660 switch (Constraint[0]) {
662 case 'd': // Data register (equivalent to 'r')
663 case 'r': // General-purpose register
665 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
666 else if (VT == MVT::i128)
667 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
668 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
670 case 'a': // Address register
672 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
673 else if (VT == MVT::i128)
674 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
675 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
677 case 'h': // High-part register (an LLVM extension)
678 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
680 case 'f': // Floating-point register
682 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
683 else if (VT == MVT::f128)
684 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
685 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
688 if (Constraint[0] == '{') {
689 // We need to override the default register parsing for GPRs and FPRs
690 // because the interpretation depends on VT. The internal names of
691 // the registers are also different from the external names
692 // (F0D and F0S instead of F0, etc.).
693 if (Constraint[1] == 'r') {
695 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
696 SystemZMC::GR32Regs);
698 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
699 SystemZMC::GR128Regs);
700 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
701 SystemZMC::GR64Regs);
703 if (Constraint[1] == 'f') {
705 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
706 SystemZMC::FP32Regs);
708 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
709 SystemZMC::FP128Regs);
710 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
711 SystemZMC::FP64Regs);
714 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
717 void SystemZTargetLowering::
718 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
719 std::vector<SDValue> &Ops,
720 SelectionDAG &DAG) const {
721 // Only support length 1 constraints for now.
722 if (Constraint.length() == 1) {
723 switch (Constraint[0]) {
724 case 'I': // Unsigned 8-bit constant
725 if (auto *C = dyn_cast<ConstantSDNode>(Op))
726 if (isUInt<8>(C->getZExtValue()))
727 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
731 case 'J': // Unsigned 12-bit constant
732 if (auto *C = dyn_cast<ConstantSDNode>(Op))
733 if (isUInt<12>(C->getZExtValue()))
734 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
738 case 'K': // Signed 16-bit constant
739 if (auto *C = dyn_cast<ConstantSDNode>(Op))
740 if (isInt<16>(C->getSExtValue()))
741 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
745 case 'L': // Signed 20-bit displacement (on all targets we support)
746 if (auto *C = dyn_cast<ConstantSDNode>(Op))
747 if (isInt<20>(C->getSExtValue()))
748 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
752 case 'M': // 0x7fffffff
753 if (auto *C = dyn_cast<ConstantSDNode>(Op))
754 if (C->getZExtValue() == 0x7fffffff)
755 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
760 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
763 //===----------------------------------------------------------------------===//
764 // Calling conventions
765 //===----------------------------------------------------------------------===//
767 #include "SystemZGenCallingConv.inc"
769 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
770 Type *ToType) const {
771 return isTruncateFree(FromType, ToType);
774 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
775 if (!CI->isTailCall())
780 // Value is a value that has been passed to us in the location described by VA
781 // (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
782 // any loads onto Chain.
783 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
784 CCValAssign &VA, SDValue Chain,
786 // If the argument has been promoted from a smaller type, insert an
787 // assertion to capture this.
788 if (VA.getLocInfo() == CCValAssign::SExt)
789 Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
790 DAG.getValueType(VA.getValVT()));
791 else if (VA.getLocInfo() == CCValAssign::ZExt)
792 Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
793 DAG.getValueType(VA.getValVT()));
796 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
797 else if (VA.getLocInfo() == CCValAssign::Indirect)
798 Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
799 MachinePointerInfo(), false, false, false, 0);
800 else if (VA.getLocInfo() == CCValAssign::BCvt) {
801 // If this is a short vector argument loaded from the stack,
802 // extend from i64 to full vector size and then bitcast.
803 assert(VA.getLocVT() == MVT::i64);
804 assert(VA.getValVT().isVector());
805 Value = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i64,
806 Value, DAG.getUNDEF(MVT::i64));
807 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
809 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
813 // Value is a value of type VA.getValVT() that we need to copy into
814 // the location described by VA. Return a copy of Value converted to
815 // VA.getValVT(). The caller is responsible for handling indirect values.
816 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
817 CCValAssign &VA, SDValue Value) {
818 switch (VA.getLocInfo()) {
819 case CCValAssign::SExt:
820 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
821 case CCValAssign::ZExt:
822 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
823 case CCValAssign::AExt:
824 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
825 case CCValAssign::BCvt:
826 // If this is a short vector argument to be stored to the stack,
827 // bitcast to v2i64 and then extract first element.
828 assert(VA.getLocVT() == MVT::i64);
829 assert(VA.getValVT().isVector());
830 Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
831 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
832 DAG.getConstant(0, DL, MVT::i32));
833 case CCValAssign::Full:
836 llvm_unreachable("Unhandled getLocInfo()");
840 SDValue SystemZTargetLowering::
841 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
842 const SmallVectorImpl<ISD::InputArg> &Ins,
843 SDLoc DL, SelectionDAG &DAG,
844 SmallVectorImpl<SDValue> &InVals) const {
845 MachineFunction &MF = DAG.getMachineFunction();
846 MachineFrameInfo *MFI = MF.getFrameInfo();
847 MachineRegisterInfo &MRI = MF.getRegInfo();
848 SystemZMachineFunctionInfo *FuncInfo =
849 MF.getInfo<SystemZMachineFunctionInfo>();
851 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
853 // Assign locations to all of the incoming arguments.
854 SmallVector<CCValAssign, 16> ArgLocs;
855 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
856 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
858 unsigned NumFixedGPRs = 0;
859 unsigned NumFixedFPRs = 0;
860 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
862 CCValAssign &VA = ArgLocs[I];
863 EVT LocVT = VA.getLocVT();
865 // Arguments passed in registers
866 const TargetRegisterClass *RC;
867 switch (LocVT.getSimpleVT().SimpleTy) {
869 // Integers smaller than i64 should be promoted to i64.
870 llvm_unreachable("Unexpected argument type");
873 RC = &SystemZ::GR32BitRegClass;
877 RC = &SystemZ::GR64BitRegClass;
881 RC = &SystemZ::FP32BitRegClass;
885 RC = &SystemZ::FP64BitRegClass;
893 RC = &SystemZ::VR128BitRegClass;
897 unsigned VReg = MRI.createVirtualRegister(RC);
898 MRI.addLiveIn(VA.getLocReg(), VReg);
899 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
901 assert(VA.isMemLoc() && "Argument not register or memory");
903 // Create the frame index object for this incoming parameter.
904 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
905 VA.getLocMemOffset(), true);
907 // Create the SelectionDAG nodes corresponding to a load
908 // from this parameter. Unpromoted ints and floats are
909 // passed as right-justified 8-byte values.
910 EVT PtrVT = getPointerTy();
911 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
912 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
913 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
914 DAG.getIntPtrConstant(4, DL));
915 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
916 MachinePointerInfo::getFixedStack(FI),
917 false, false, false, 0);
920 // Convert the value of the argument register into the value that's
922 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
926 // Save the number of non-varargs registers for later use by va_start, etc.
927 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
928 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
930 // Likewise the address (in the form of a frame index) of where the
931 // first stack vararg would be. The 1-byte size here is arbitrary.
932 int64_t StackSize = CCInfo.getNextStackOffset();
933 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
935 // ...and a similar frame index for the caller-allocated save area
936 // that will be used to store the incoming registers.
937 int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
938 unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
939 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
941 // Store the FPR varargs in the reserved frame slots. (We store the
942 // GPRs as part of the prologue.)
943 if (NumFixedFPRs < SystemZ::NumArgFPRs) {
944 SDValue MemOps[SystemZ::NumArgFPRs];
945 for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
946 unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
947 int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
948 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
949 unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
950 &SystemZ::FP64BitRegClass);
951 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
952 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
953 MachinePointerInfo::getFixedStack(FI),
957 // Join the stores, which are independent of one another.
958 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
959 makeArrayRef(&MemOps[NumFixedFPRs],
960 SystemZ::NumArgFPRs-NumFixedFPRs));
967 static bool canUseSiblingCall(const CCState &ArgCCInfo,
968 SmallVectorImpl<CCValAssign> &ArgLocs) {
969 // Punt if there are any indirect or stack arguments, or if the call
970 // needs the call-saved argument register R6.
971 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
972 CCValAssign &VA = ArgLocs[I];
973 if (VA.getLocInfo() == CCValAssign::Indirect)
977 unsigned Reg = VA.getLocReg();
978 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
985 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
986 SmallVectorImpl<SDValue> &InVals) const {
987 SelectionDAG &DAG = CLI.DAG;
989 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
990 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
991 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
992 SDValue Chain = CLI.Chain;
993 SDValue Callee = CLI.Callee;
994 bool &IsTailCall = CLI.IsTailCall;
995 CallingConv::ID CallConv = CLI.CallConv;
996 bool IsVarArg = CLI.IsVarArg;
997 MachineFunction &MF = DAG.getMachineFunction();
998 EVT PtrVT = getPointerTy();
1000 // Analyze the operands of the call, assigning locations to each operand.
1001 SmallVector<CCValAssign, 16> ArgLocs;
1002 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1003 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1005 // We don't support GuaranteedTailCallOpt, only automatically-detected
1007 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs))
1010 // Get a count of how many bytes are to be pushed on the stack.
1011 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1013 // Mark the start of the call.
1015 Chain = DAG.getCALLSEQ_START(Chain,
1016 DAG.getConstant(NumBytes, DL, PtrVT, true),
1019 // Copy argument values to their designated locations.
1020 SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1021 SmallVector<SDValue, 8> MemOpChains;
1023 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1024 CCValAssign &VA = ArgLocs[I];
1025 SDValue ArgValue = OutVals[I];
1027 if (VA.getLocInfo() == CCValAssign::Indirect) {
1028 // Store the argument in a stack slot and pass its address.
1029 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1030 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1031 MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1032 MachinePointerInfo::getFixedStack(FI),
1034 ArgValue = SpillSlot;
1036 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1039 // Queue up the argument copies and emit them at the end.
1040 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1042 assert(VA.isMemLoc() && "Argument not register or memory");
1044 // Work out the address of the stack slot. Unpromoted ints and
1045 // floats are passed as right-justified 8-byte values.
1046 if (!StackPtr.getNode())
1047 StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1048 unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1049 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1051 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1052 DAG.getIntPtrConstant(Offset, DL));
1055 MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
1056 MachinePointerInfo(),
1061 // Join the stores, which are independent of one another.
1062 if (!MemOpChains.empty())
1063 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1065 // Accept direct calls by converting symbolic call addresses to the
1066 // associated Target* opcodes. Force %r1 to be used for indirect
1069 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1070 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1071 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1072 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1073 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1074 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1075 } else if (IsTailCall) {
1076 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1077 Glue = Chain.getValue(1);
1078 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1081 // Build a sequence of copy-to-reg nodes, chained and glued together.
1082 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1083 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1084 RegsToPass[I].second, Glue);
1085 Glue = Chain.getValue(1);
1088 // The first call operand is the chain and the second is the target address.
1089 SmallVector<SDValue, 8> Ops;
1090 Ops.push_back(Chain);
1091 Ops.push_back(Callee);
1093 // Add argument registers to the end of the list so that they are
1094 // known live into the call.
1095 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1096 Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1097 RegsToPass[I].second.getValueType()));
1099 // Add a register mask operand representing the call-preserved registers.
1100 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1101 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1102 assert(Mask && "Missing call preserved mask for calling convention");
1103 Ops.push_back(DAG.getRegisterMask(Mask));
1105 // Glue the call to the argument copies, if any.
1107 Ops.push_back(Glue);
1110 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1112 return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1113 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1114 Glue = Chain.getValue(1);
1116 // Mark the end of the call, which is glued to the call itself.
1117 Chain = DAG.getCALLSEQ_END(Chain,
1118 DAG.getConstant(NumBytes, DL, PtrVT, true),
1119 DAG.getConstant(0, DL, PtrVT, true),
1121 Glue = Chain.getValue(1);
1123 // Assign locations to each value returned by this call.
1124 SmallVector<CCValAssign, 16> RetLocs;
1125 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1126 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1128 // Copy all of the result registers out of their specified physreg.
1129 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1130 CCValAssign &VA = RetLocs[I];
1132 // Copy the value out, gluing the copy to the end of the call sequence.
1133 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1134 VA.getLocVT(), Glue);
1135 Chain = RetValue.getValue(1);
1136 Glue = RetValue.getValue(2);
1138 // Convert the value of the return register into the value that's
1140 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1147 SystemZTargetLowering::LowerReturn(SDValue Chain,
1148 CallingConv::ID CallConv, bool IsVarArg,
1149 const SmallVectorImpl<ISD::OutputArg> &Outs,
1150 const SmallVectorImpl<SDValue> &OutVals,
1151 SDLoc DL, SelectionDAG &DAG) const {
1152 MachineFunction &MF = DAG.getMachineFunction();
1154 // Assign locations to each returned value.
1155 SmallVector<CCValAssign, 16> RetLocs;
1156 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1157 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1159 // Quick exit for void returns
1160 if (RetLocs.empty())
1161 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1163 // Copy the result values into the output registers.
1165 SmallVector<SDValue, 4> RetOps;
1166 RetOps.push_back(Chain);
1167 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1168 CCValAssign &VA = RetLocs[I];
1169 SDValue RetValue = OutVals[I];
1171 // Make the return register live on exit.
1172 assert(VA.isRegLoc() && "Can only return in registers!");
1174 // Promote the value as required.
1175 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1177 // Chain and glue the copies together.
1178 unsigned Reg = VA.getLocReg();
1179 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1180 Glue = Chain.getValue(1);
1181 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1184 // Update chain and glue.
1187 RetOps.push_back(Glue);
1189 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1192 SDValue SystemZTargetLowering::
1193 prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL, SelectionDAG &DAG) const {
1194 return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
1197 // Return true if Op is an intrinsic node with chain that returns the CC value
1198 // as its only (other) argument. Provide the associated SystemZISD opcode and
1199 // the mask of valid CC values if so.
1200 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1201 unsigned &CCValid) {
1202 unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1204 case Intrinsic::s390_tbegin:
1205 Opcode = SystemZISD::TBEGIN;
1206 CCValid = SystemZ::CCMASK_TBEGIN;
1209 case Intrinsic::s390_tbegin_nofloat:
1210 Opcode = SystemZISD::TBEGIN_NOFLOAT;
1211 CCValid = SystemZ::CCMASK_TBEGIN;
1214 case Intrinsic::s390_tend:
1215 Opcode = SystemZISD::TEND;
1216 CCValid = SystemZ::CCMASK_TEND;
1224 // Emit an intrinsic with chain with a glued value instead of its CC result.
1225 static SDValue emitIntrinsicWithChainAndGlue(SelectionDAG &DAG, SDValue Op,
1227 // Copy all operands except the intrinsic ID.
1228 unsigned NumOps = Op.getNumOperands();
1229 SmallVector<SDValue, 6> Ops;
1230 Ops.reserve(NumOps - 1);
1231 Ops.push_back(Op.getOperand(0));
1232 for (unsigned I = 2; I < NumOps; ++I)
1233 Ops.push_back(Op.getOperand(I));
1235 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1236 SDVTList RawVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1237 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1238 SDValue OldChain = SDValue(Op.getNode(), 1);
1239 SDValue NewChain = SDValue(Intr.getNode(), 0);
1240 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1244 // CC is a comparison that will be implemented using an integer or
1245 // floating-point comparison. Return the condition code mask for
1246 // a branch on true. In the integer case, CCMASK_CMP_UO is set for
1247 // unsigned comparisons and clear for signed ones. In the floating-point
1248 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1249 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1251 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1252 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1253 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1257 llvm_unreachable("Invalid integer condition!");
1266 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
1267 case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1272 // Return a sequence for getting a 1 from an IPM result when CC has a
1273 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1274 // The handling of CC values outside CCValid doesn't matter.
1275 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1276 // Deal with cases where the result can be taken directly from a bit
1277 // of the IPM result.
1278 if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1279 return IPMConversion(0, 0, SystemZ::IPM_CC);
1280 if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1281 return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1283 // Deal with cases where we can add a value to force the sign bit
1284 // to contain the right value. Putting the bit in 31 means we can
1285 // use SRL rather than RISBG(L), and also makes it easier to get a
1286 // 0/-1 value, so it has priority over the other tests below.
1288 // These sequences rely on the fact that the upper two bits of the
1289 // IPM result are zero.
1290 uint64_t TopBit = uint64_t(1) << 31;
1291 if (CCMask == (CCValid & SystemZ::CCMASK_0))
1292 return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1293 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1294 return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1295 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1297 | SystemZ::CCMASK_2)))
1298 return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1299 if (CCMask == (CCValid & SystemZ::CCMASK_3))
1300 return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1301 if (CCMask == (CCValid & (SystemZ::CCMASK_1
1303 | SystemZ::CCMASK_3)))
1304 return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1306 // Next try inverting the value and testing a bit. 0/1 could be
1307 // handled this way too, but we dealt with that case above.
1308 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1309 return IPMConversion(-1, 0, SystemZ::IPM_CC);
1311 // Handle cases where adding a value forces a non-sign bit to contain
1313 if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1314 return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1315 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1316 return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1318 // The remaining cases are 1, 2, 0/1/3 and 0/2/3. All these are
1319 // can be done by inverting the low CC bit and applying one of the
1320 // sign-based extractions above.
1321 if (CCMask == (CCValid & SystemZ::CCMASK_1))
1322 return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1323 if (CCMask == (CCValid & SystemZ::CCMASK_2))
1324 return IPMConversion(1 << SystemZ::IPM_CC,
1325 TopBit - (3 << SystemZ::IPM_CC), 31);
1326 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1328 | SystemZ::CCMASK_3)))
1329 return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1330 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1332 | SystemZ::CCMASK_3)))
1333 return IPMConversion(1 << SystemZ::IPM_CC,
1334 TopBit - (1 << SystemZ::IPM_CC), 31);
1336 llvm_unreachable("Unexpected CC combination");
1339 // If C can be converted to a comparison against zero, adjust the operands
1341 static void adjustZeroCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1342 if (C.ICmpType == SystemZICMP::UnsignedOnly)
1345 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1349 int64_t Value = ConstOp1->getSExtValue();
1350 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1351 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1352 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1353 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1354 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1355 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1359 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1360 // adjust the operands as necessary.
1361 static void adjustSubwordCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1362 // For us to make any changes, it must a comparison between a single-use
1363 // load and a constant.
1364 if (!C.Op0.hasOneUse() ||
1365 C.Op0.getOpcode() != ISD::LOAD ||
1366 C.Op1.getOpcode() != ISD::Constant)
1369 // We must have an 8- or 16-bit load.
1370 auto *Load = cast<LoadSDNode>(C.Op0);
1371 unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1372 if (NumBits != 8 && NumBits != 16)
1375 // The load must be an extending one and the constant must be within the
1376 // range of the unextended value.
1377 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1378 uint64_t Value = ConstOp1->getZExtValue();
1379 uint64_t Mask = (1 << NumBits) - 1;
1380 if (Load->getExtensionType() == ISD::SEXTLOAD) {
1381 // Make sure that ConstOp1 is in range of C.Op0.
1382 int64_t SignedValue = ConstOp1->getSExtValue();
1383 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1385 if (C.ICmpType != SystemZICMP::SignedOnly) {
1386 // Unsigned comparison between two sign-extended values is equivalent
1387 // to unsigned comparison between two zero-extended values.
1389 } else if (NumBits == 8) {
1390 // Try to treat the comparison as unsigned, so that we can use CLI.
1391 // Adjust CCMask and Value as necessary.
1392 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1393 // Test whether the high bit of the byte is set.
1394 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1395 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1396 // Test whether the high bit of the byte is clear.
1397 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1399 // No instruction exists for this combination.
1401 C.ICmpType = SystemZICMP::UnsignedOnly;
1403 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1406 assert(C.ICmpType == SystemZICMP::Any &&
1407 "Signedness shouldn't matter here.");
1411 // Make sure that the first operand is an i32 of the right extension type.
1412 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1415 if (C.Op0.getValueType() != MVT::i32 ||
1416 Load->getExtensionType() != ExtType)
1417 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
1418 Load->getChain(), Load->getBasePtr(),
1419 Load->getPointerInfo(), Load->getMemoryVT(),
1420 Load->isVolatile(), Load->isNonTemporal(),
1421 Load->isInvariant(), Load->getAlignment());
1423 // Make sure that the second operand is an i32 with the right value.
1424 if (C.Op1.getValueType() != MVT::i32 ||
1425 Value != ConstOp1->getZExtValue())
1426 C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
1429 // Return true if Op is either an unextended load, or a load suitable
1430 // for integer register-memory comparisons of type ICmpType.
1431 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1432 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1434 // There are no instructions to compare a register with a memory byte.
1435 if (Load->getMemoryVT() == MVT::i8)
1437 // Otherwise decide on extension type.
1438 switch (Load->getExtensionType()) {
1439 case ISD::NON_EXTLOAD:
1442 return ICmpType != SystemZICMP::UnsignedOnly;
1444 return ICmpType != SystemZICMP::SignedOnly;
1452 // Return true if it is better to swap the operands of C.
1453 static bool shouldSwapCmpOperands(const Comparison &C) {
1454 // Leave f128 comparisons alone, since they have no memory forms.
1455 if (C.Op0.getValueType() == MVT::f128)
1458 // Always keep a floating-point constant second, since comparisons with
1459 // zero can use LOAD TEST and comparisons with other constants make a
1460 // natural memory operand.
1461 if (isa<ConstantFPSDNode>(C.Op1))
1464 // Never swap comparisons with zero since there are many ways to optimize
1466 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1467 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1470 // Also keep natural memory operands second if the loaded value is
1471 // only used here. Several comparisons have memory forms.
1472 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1475 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1476 // In that case we generally prefer the memory to be second.
1477 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1478 // The only exceptions are when the second operand is a constant and
1479 // we can use things like CHHSI.
1482 // The unsigned memory-immediate instructions can handle 16-bit
1483 // unsigned integers.
1484 if (C.ICmpType != SystemZICMP::SignedOnly &&
1485 isUInt<16>(ConstOp1->getZExtValue()))
1487 // The signed memory-immediate instructions can handle 16-bit
1489 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1490 isInt<16>(ConstOp1->getSExtValue()))
1495 // Try to promote the use of CGFR and CLGFR.
1496 unsigned Opcode0 = C.Op0.getOpcode();
1497 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1499 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1501 if (C.ICmpType != SystemZICMP::SignedOnly &&
1502 Opcode0 == ISD::AND &&
1503 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1504 cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1510 // Return a version of comparison CC mask CCMask in which the LT and GT
1511 // actions are swapped.
1512 static unsigned reverseCCMask(unsigned CCMask) {
1513 return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1514 (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1515 (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1516 (CCMask & SystemZ::CCMASK_CMP_UO));
1519 // Check whether C tests for equality between X and Y and whether X - Y
1520 // or Y - X is also computed. In that case it's better to compare the
1521 // result of the subtraction against zero.
1522 static void adjustForSubtraction(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1523 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1524 C.CCMask == SystemZ::CCMASK_CMP_NE) {
1525 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1527 if (N->getOpcode() == ISD::SUB &&
1528 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1529 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1530 C.Op0 = SDValue(N, 0);
1531 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
1538 // Check whether C compares a floating-point value with zero and if that
1539 // floating-point value is also negated. In this case we can use the
1540 // negation to set CC, so avoiding separate LOAD AND TEST and
1541 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1542 static void adjustForFNeg(Comparison &C) {
1543 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1544 if (C1 && C1->isZero()) {
1545 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1547 if (N->getOpcode() == ISD::FNEG) {
1548 C.Op0 = SDValue(N, 0);
1549 C.CCMask = reverseCCMask(C.CCMask);
1556 // Check whether C compares (shl X, 32) with 0 and whether X is
1557 // also sign-extended. In that case it is better to test the result
1558 // of the sign extension using LTGFR.
1560 // This case is important because InstCombine transforms a comparison
1561 // with (sext (trunc X)) into a comparison with (shl X, 32).
1562 static void adjustForLTGFR(Comparison &C) {
1563 // Check for a comparison between (shl X, 32) and 0.
1564 if (C.Op0.getOpcode() == ISD::SHL &&
1565 C.Op0.getValueType() == MVT::i64 &&
1566 C.Op1.getOpcode() == ISD::Constant &&
1567 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1568 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
1569 if (C1 && C1->getZExtValue() == 32) {
1570 SDValue ShlOp0 = C.Op0.getOperand(0);
1571 // See whether X has any SIGN_EXTEND_INREG uses.
1572 for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
1574 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1575 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1576 C.Op0 = SDValue(N, 0);
1584 // If C compares the truncation of an extending load, try to compare
1585 // the untruncated value instead. This exposes more opportunities to
1587 static void adjustICmpTruncate(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1588 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
1589 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
1590 C.Op1.getOpcode() == ISD::Constant &&
1591 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1592 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
1593 if (L->getMemoryVT().getStoreSizeInBits()
1594 <= C.Op0.getValueType().getSizeInBits()) {
1595 unsigned Type = L->getExtensionType();
1596 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
1597 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
1598 C.Op0 = C.Op0.getOperand(0);
1599 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
1605 // Return true if shift operation N has an in-range constant shift value.
1606 // Store it in ShiftVal if so.
1607 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1608 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1612 uint64_t Amount = Shift->getZExtValue();
1613 if (Amount >= N.getValueType().getSizeInBits())
1620 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1621 // instruction and whether the CC value is descriptive enough to handle
1622 // a comparison of type Opcode between the AND result and CmpVal.
1623 // CCMask says which comparison result is being tested and BitSize is
1624 // the number of bits in the operands. If TEST UNDER MASK can be used,
1625 // return the corresponding CC mask, otherwise return 0.
1626 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1627 uint64_t Mask, uint64_t CmpVal,
1628 unsigned ICmpType) {
1629 assert(Mask != 0 && "ANDs with zero should have been removed by now");
1631 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1632 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1633 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1636 // Work out the masks for the lowest and highest bits.
1637 unsigned HighShift = 63 - countLeadingZeros(Mask);
1638 uint64_t High = uint64_t(1) << HighShift;
1639 uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1641 // Signed ordered comparisons are effectively unsigned if the sign
1643 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1645 // Check for equality comparisons with 0, or the equivalent.
1647 if (CCMask == SystemZ::CCMASK_CMP_EQ)
1648 return SystemZ::CCMASK_TM_ALL_0;
1649 if (CCMask == SystemZ::CCMASK_CMP_NE)
1650 return SystemZ::CCMASK_TM_SOME_1;
1652 if (EffectivelyUnsigned && CmpVal <= Low) {
1653 if (CCMask == SystemZ::CCMASK_CMP_LT)
1654 return SystemZ::CCMASK_TM_ALL_0;
1655 if (CCMask == SystemZ::CCMASK_CMP_GE)
1656 return SystemZ::CCMASK_TM_SOME_1;
1658 if (EffectivelyUnsigned && CmpVal < Low) {
1659 if (CCMask == SystemZ::CCMASK_CMP_LE)
1660 return SystemZ::CCMASK_TM_ALL_0;
1661 if (CCMask == SystemZ::CCMASK_CMP_GT)
1662 return SystemZ::CCMASK_TM_SOME_1;
1665 // Check for equality comparisons with the mask, or the equivalent.
1666 if (CmpVal == Mask) {
1667 if (CCMask == SystemZ::CCMASK_CMP_EQ)
1668 return SystemZ::CCMASK_TM_ALL_1;
1669 if (CCMask == SystemZ::CCMASK_CMP_NE)
1670 return SystemZ::CCMASK_TM_SOME_0;
1672 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1673 if (CCMask == SystemZ::CCMASK_CMP_GT)
1674 return SystemZ::CCMASK_TM_ALL_1;
1675 if (CCMask == SystemZ::CCMASK_CMP_LE)
1676 return SystemZ::CCMASK_TM_SOME_0;
1678 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1679 if (CCMask == SystemZ::CCMASK_CMP_GE)
1680 return SystemZ::CCMASK_TM_ALL_1;
1681 if (CCMask == SystemZ::CCMASK_CMP_LT)
1682 return SystemZ::CCMASK_TM_SOME_0;
1685 // Check for ordered comparisons with the top bit.
1686 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1687 if (CCMask == SystemZ::CCMASK_CMP_LE)
1688 return SystemZ::CCMASK_TM_MSB_0;
1689 if (CCMask == SystemZ::CCMASK_CMP_GT)
1690 return SystemZ::CCMASK_TM_MSB_1;
1692 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1693 if (CCMask == SystemZ::CCMASK_CMP_LT)
1694 return SystemZ::CCMASK_TM_MSB_0;
1695 if (CCMask == SystemZ::CCMASK_CMP_GE)
1696 return SystemZ::CCMASK_TM_MSB_1;
1699 // If there are just two bits, we can do equality checks for Low and High
1701 if (Mask == Low + High) {
1702 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1703 return SystemZ::CCMASK_TM_MIXED_MSB_0;
1704 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1705 return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1706 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1707 return SystemZ::CCMASK_TM_MIXED_MSB_1;
1708 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1709 return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
1712 // Looks like we've exhausted our options.
1716 // See whether C can be implemented as a TEST UNDER MASK instruction.
1717 // Update the arguments with the TM version if so.
1718 static void adjustForTestUnderMask(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1719 // Check that we have a comparison with a constant.
1720 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1723 uint64_t CmpVal = ConstOp1->getZExtValue();
1725 // Check whether the nonconstant input is an AND with a constant mask.
1728 ConstantSDNode *Mask = nullptr;
1729 if (C.Op0.getOpcode() == ISD::AND) {
1730 NewC.Op0 = C.Op0.getOperand(0);
1731 NewC.Op1 = C.Op0.getOperand(1);
1732 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
1735 MaskVal = Mask->getZExtValue();
1737 // There is no instruction to compare with a 64-bit immediate
1738 // so use TMHH instead if possible. We need an unsigned ordered
1739 // comparison with an i64 immediate.
1740 if (NewC.Op0.getValueType() != MVT::i64 ||
1741 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
1742 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
1743 NewC.ICmpType == SystemZICMP::SignedOnly)
1745 // Convert LE and GT comparisons into LT and GE.
1746 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
1747 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
1748 if (CmpVal == uint64_t(-1))
1751 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1753 // If the low N bits of Op1 are zero than the low N bits of Op0 can
1754 // be masked off without changing the result.
1755 MaskVal = -(CmpVal & -CmpVal);
1756 NewC.ICmpType = SystemZICMP::UnsignedOnly;
1761 // Check whether the combination of mask, comparison value and comparison
1762 // type are suitable.
1763 unsigned BitSize = NewC.Op0.getValueType().getSizeInBits();
1764 unsigned NewCCMask, ShiftVal;
1765 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
1766 NewC.Op0.getOpcode() == ISD::SHL &&
1767 isSimpleShift(NewC.Op0, ShiftVal) &&
1768 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
1769 MaskVal >> ShiftVal,
1771 SystemZICMP::Any))) {
1772 NewC.Op0 = NewC.Op0.getOperand(0);
1773 MaskVal >>= ShiftVal;
1774 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
1775 NewC.Op0.getOpcode() == ISD::SRL &&
1776 isSimpleShift(NewC.Op0, ShiftVal) &&
1777 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
1778 MaskVal << ShiftVal,
1780 SystemZICMP::UnsignedOnly))) {
1781 NewC.Op0 = NewC.Op0.getOperand(0);
1782 MaskVal <<= ShiftVal;
1784 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
1790 // Go ahead and make the change.
1791 C.Opcode = SystemZISD::TM;
1793 if (Mask && Mask->getZExtValue() == MaskVal)
1794 C.Op1 = SDValue(Mask, 0);
1796 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
1797 C.CCValid = SystemZ::CCMASK_TM;
1798 C.CCMask = NewCCMask;
1801 // Return a Comparison that tests the condition-code result of intrinsic
1802 // node Call against constant integer CC using comparison code Cond.
1803 // Opcode is the opcode of the SystemZISD operation for the intrinsic
1804 // and CCValid is the set of possible condition-code results.
1805 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
1806 SDValue Call, unsigned CCValid, uint64_t CC,
1807 ISD::CondCode Cond) {
1808 Comparison C(Call, SDValue());
1810 C.CCValid = CCValid;
1811 if (Cond == ISD::SETEQ)
1812 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
1813 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
1814 else if (Cond == ISD::SETNE)
1815 // ...and the inverse of that.
1816 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
1817 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
1818 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
1819 // always true for CC>3.
1820 C.CCMask = CC < 4 ? -1 << (4 - CC) : -1;
1821 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
1822 // ...and the inverse of that.
1823 C.CCMask = CC < 4 ? ~(-1 << (4 - CC)) : 0;
1824 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
1825 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
1826 // always true for CC>3.
1827 C.CCMask = CC < 4 ? -1 << (3 - CC) : -1;
1828 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
1829 // ...and the inverse of that.
1830 C.CCMask = CC < 4 ? ~(-1 << (3 - CC)) : 0;
1832 llvm_unreachable("Unexpected integer comparison type");
1833 C.CCMask &= CCValid;
1837 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
1838 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
1839 ISD::CondCode Cond, SDLoc DL) {
1840 if (CmpOp1.getOpcode() == ISD::Constant) {
1841 uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
1842 unsigned Opcode, CCValid;
1843 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
1844 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
1845 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
1846 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
1848 Comparison C(CmpOp0, CmpOp1);
1849 C.CCMask = CCMaskForCondCode(Cond);
1850 if (C.Op0.getValueType().isFloatingPoint()) {
1851 C.CCValid = SystemZ::CCMASK_FCMP;
1852 C.Opcode = SystemZISD::FCMP;
1855 C.CCValid = SystemZ::CCMASK_ICMP;
1856 C.Opcode = SystemZISD::ICMP;
1857 // Choose the type of comparison. Equality and inequality tests can
1858 // use either signed or unsigned comparisons. The choice also doesn't
1859 // matter if both sign bits are known to be clear. In those cases we
1860 // want to give the main isel code the freedom to choose whichever
1862 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1863 C.CCMask == SystemZ::CCMASK_CMP_NE ||
1864 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
1865 C.ICmpType = SystemZICMP::Any;
1866 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
1867 C.ICmpType = SystemZICMP::UnsignedOnly;
1869 C.ICmpType = SystemZICMP::SignedOnly;
1870 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
1871 adjustZeroCmp(DAG, DL, C);
1872 adjustSubwordCmp(DAG, DL, C);
1873 adjustForSubtraction(DAG, DL, C);
1875 adjustICmpTruncate(DAG, DL, C);
1878 if (shouldSwapCmpOperands(C)) {
1879 std::swap(C.Op0, C.Op1);
1880 C.CCMask = reverseCCMask(C.CCMask);
1883 adjustForTestUnderMask(DAG, DL, C);
1887 // Emit the comparison instruction described by C.
1888 static SDValue emitCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1889 if (!C.Op1.getNode()) {
1891 switch (C.Op0.getOpcode()) {
1892 case ISD::INTRINSIC_W_CHAIN:
1893 Op = emitIntrinsicWithChainAndGlue(DAG, C.Op0, C.Opcode);
1896 llvm_unreachable("Invalid comparison operands");
1898 return SDValue(Op.getNode(), Op->getNumValues() - 1);
1900 if (C.Opcode == SystemZISD::ICMP)
1901 return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
1902 DAG.getConstant(C.ICmpType, DL, MVT::i32));
1903 if (C.Opcode == SystemZISD::TM) {
1904 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
1905 bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
1906 return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
1907 DAG.getConstant(RegisterOnly, DL, MVT::i32));
1909 return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
1912 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
1913 // 64 bits. Extend is the extension type to use. Store the high part
1914 // in Hi and the low part in Lo.
1915 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
1916 unsigned Extend, SDValue Op0, SDValue Op1,
1917 SDValue &Hi, SDValue &Lo) {
1918 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
1919 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
1920 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
1921 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1922 DAG.getConstant(32, DL, MVT::i64));
1923 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
1924 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
1927 // Lower a binary operation that produces two VT results, one in each
1928 // half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
1929 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
1930 // on the extended Op0 and (unextended) Op1. Store the even register result
1931 // in Even and the odd register result in Odd.
1932 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
1933 unsigned Extend, unsigned Opcode,
1934 SDValue Op0, SDValue Op1,
1935 SDValue &Even, SDValue &Odd) {
1936 SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
1937 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
1938 SDValue(In128, 0), Op1);
1939 bool Is32Bit = is32Bit(VT);
1940 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
1941 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
1944 // Return an i32 value that is 1 if the CC value produced by Glue is
1945 // in the mask CCMask and 0 otherwise. CC is known to have a value
1946 // in CCValid, so other values can be ignored.
1947 static SDValue emitSETCC(SelectionDAG &DAG, SDLoc DL, SDValue Glue,
1948 unsigned CCValid, unsigned CCMask) {
1949 IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
1950 SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
1952 if (Conversion.XORValue)
1953 Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
1954 DAG.getConstant(Conversion.XORValue, DL, MVT::i32));
1956 if (Conversion.AddValue)
1957 Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
1958 DAG.getConstant(Conversion.AddValue, DL, MVT::i32));
1960 // The SHR/AND sequence should get optimized to an RISBG.
1961 Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
1962 DAG.getConstant(Conversion.Bit, DL, MVT::i32));
1963 if (Conversion.Bit != 31)
1964 Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
1965 DAG.getConstant(1, DL, MVT::i32));
1969 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
1970 // be done directly. IsFP is true if CC is for a floating-point rather than
1971 // integer comparison.
1972 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) {
1976 return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE;
1980 return IsFP ? SystemZISD::VFCMPHE : 0;
1984 return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH;
1987 return IsFP ? 0 : SystemZISD::VICMPHL;
1994 // Return the SystemZISD vector comparison operation for CC or its inverse,
1995 // or 0 if neither can be done directly. Indicate in Invert whether the
1996 // result is for the inverse of CC. IsFP is true if CC is for a
1997 // floating-point rather than integer comparison.
1998 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP,
2000 if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2005 CC = ISD::getSetCCInverse(CC, !IsFP);
2006 if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2014 // Return a v2f64 that contains the extended form of elements Start and Start+1
2015 // of v4f32 value Op.
2016 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, SDLoc DL,
2018 int Mask[] = { Start, -1, Start + 1, -1 };
2019 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2020 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2023 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2024 // producing a result of type VT.
2025 static SDValue getVectorCmp(SelectionDAG &DAG, unsigned Opcode, SDLoc DL,
2026 EVT VT, SDValue CmpOp0, SDValue CmpOp1) {
2027 // There is no hardware support for v4f32, so extend the vector into
2028 // two v2f64s and compare those.
2029 if (CmpOp0.getValueType() == MVT::v4f32) {
2030 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0);
2031 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0);
2032 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1);
2033 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1);
2034 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2035 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2036 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2038 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2041 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2042 // an integer mask of type VT.
2043 static SDValue lowerVectorSETCC(SelectionDAG &DAG, SDLoc DL, EVT VT,
2044 ISD::CondCode CC, SDValue CmpOp0,
2046 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2047 bool Invert = false;
2050 // Handle tests for order using (or (ogt y x) (oge x y)).
2054 assert(IsFP && "Unexpected integer comparison");
2055 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2056 SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1);
2057 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2061 // Handle <> tests using (or (ogt y x) (ogt x y)).
2065 assert(IsFP && "Unexpected integer comparison");
2066 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2067 SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1);
2068 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2072 // Otherwise a single comparison is enough. It doesn't really
2073 // matter whether we try the inversion or the swap first, since
2074 // there are no cases where both work.
2076 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2077 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1);
2079 CC = ISD::getSetCCSwappedOperands(CC);
2080 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2081 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0);
2083 llvm_unreachable("Unhandled comparison");
2088 SDValue Mask = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2089 DAG.getConstant(65535, DL, MVT::i32));
2090 Mask = DAG.getNode(ISD::BITCAST, DL, VT, Mask);
2091 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2096 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2097 SelectionDAG &DAG) const {
2098 SDValue CmpOp0 = Op.getOperand(0);
2099 SDValue CmpOp1 = Op.getOperand(1);
2100 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2102 EVT VT = Op.getValueType();
2104 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2106 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2107 SDValue Glue = emitCmp(DAG, DL, C);
2108 return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2111 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2112 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2113 SDValue CmpOp0 = Op.getOperand(2);
2114 SDValue CmpOp1 = Op.getOperand(3);
2115 SDValue Dest = Op.getOperand(4);
2118 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2119 SDValue Glue = emitCmp(DAG, DL, C);
2120 return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
2121 Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32),
2122 DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, Glue);
2125 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2126 // allowing Pos and Neg to be wider than CmpOp.
2127 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2128 return (Neg.getOpcode() == ISD::SUB &&
2129 Neg.getOperand(0).getOpcode() == ISD::Constant &&
2130 cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2131 Neg.getOperand(1) == Pos &&
2133 (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2134 Pos.getOperand(0) == CmpOp)));
2137 // Return the absolute or negative absolute of Op; IsNegative decides which.
2138 static SDValue getAbsolute(SelectionDAG &DAG, SDLoc DL, SDValue Op,
2140 Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2142 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2143 DAG.getConstant(0, DL, Op.getValueType()), Op);
2147 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2148 SelectionDAG &DAG) const {
2149 SDValue CmpOp0 = Op.getOperand(0);
2150 SDValue CmpOp1 = Op.getOperand(1);
2151 SDValue TrueOp = Op.getOperand(2);
2152 SDValue FalseOp = Op.getOperand(3);
2153 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2156 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2158 // Check for absolute and negative-absolute selections, including those
2159 // where the comparison value is sign-extended (for LPGFR and LNGFR).
2160 // This check supplements the one in DAGCombiner.
2161 if (C.Opcode == SystemZISD::ICMP &&
2162 C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2163 C.CCMask != SystemZ::CCMASK_CMP_NE &&
2164 C.Op1.getOpcode() == ISD::Constant &&
2165 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2166 if (isAbsolute(C.Op0, TrueOp, FalseOp))
2167 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2168 if (isAbsolute(C.Op0, FalseOp, TrueOp))
2169 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2172 SDValue Glue = emitCmp(DAG, DL, C);
2174 // Special case for handling -1/0 results. The shifts we use here
2175 // should get optimized with the IPM conversion sequence.
2176 auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
2177 auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
2178 if (TrueC && FalseC) {
2179 int64_t TrueVal = TrueC->getSExtValue();
2180 int64_t FalseVal = FalseC->getSExtValue();
2181 if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
2182 // Invert the condition if we want -1 on false.
2184 C.CCMask ^= C.CCValid;
2185 SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2186 EVT VT = Op.getValueType();
2187 // Extend the result to VT. Upper bits are ignored.
2189 Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
2190 // Sign-extend from the low bit.
2191 SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32);
2192 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
2193 return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
2197 SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32),
2198 DAG.getConstant(C.CCMask, DL, MVT::i32), Glue};
2200 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
2201 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
2204 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2205 SelectionDAG &DAG) const {
2207 const GlobalValue *GV = Node->getGlobal();
2208 int64_t Offset = Node->getOffset();
2209 EVT PtrVT = getPointerTy();
2210 Reloc::Model RM = DAG.getTarget().getRelocationModel();
2211 CodeModel::Model CM = DAG.getTarget().getCodeModel();
2214 if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
2215 // Assign anchors at 1<<12 byte boundaries.
2216 uint64_t Anchor = Offset & ~uint64_t(0xfff);
2217 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2218 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2220 // The offset can be folded into the address if it is aligned to a halfword.
2222 if (Offset != 0 && (Offset & 1) == 0) {
2223 SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2224 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2228 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2229 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2230 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2231 MachinePointerInfo::getGOT(), false, false, false, 0);
2234 // If there was a non-zero offset that we didn't fold, create an explicit
2237 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2238 DAG.getConstant(Offset, DL, PtrVT));
2243 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2246 SDValue GOTOffset) const {
2248 EVT PtrVT = getPointerTy();
2249 SDValue Chain = DAG.getEntryNode();
2252 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
2253 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2254 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
2255 Glue = Chain.getValue(1);
2256 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
2257 Glue = Chain.getValue(1);
2259 // The first call operand is the chain and the second is the TLS symbol.
2260 SmallVector<SDValue, 8> Ops;
2261 Ops.push_back(Chain);
2262 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
2263 Node->getValueType(0),
2266 // Add argument registers to the end of the list so that they are
2267 // known live into the call.
2268 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
2269 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
2271 // Add a register mask operand representing the call-preserved registers.
2272 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2273 const uint32_t *Mask =
2274 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
2275 assert(Mask && "Missing call preserved mask for calling convention");
2276 Ops.push_back(DAG.getRegisterMask(Mask));
2278 // Glue the call to the argument copies.
2279 Ops.push_back(Glue);
2282 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2283 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
2284 Glue = Chain.getValue(1);
2286 // Copy the return value from %r2.
2287 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
2290 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
2291 SelectionDAG &DAG) const {
2293 const GlobalValue *GV = Node->getGlobal();
2294 EVT PtrVT = getPointerTy();
2295 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
2297 // The high part of the thread pointer is in access register 0.
2298 SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2299 DAG.getConstant(0, DL, MVT::i32));
2300 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
2302 // The low part of the thread pointer is in access register 1.
2303 SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2304 DAG.getConstant(1, DL, MVT::i32));
2305 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
2307 // Merge them into a single 64-bit address.
2308 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
2309 DAG.getConstant(32, DL, PtrVT));
2310 SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
2312 // Get the offset of GA from the thread pointer, based on the TLS model.
2315 case TLSModel::GeneralDynamic: {
2316 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
2317 SystemZConstantPoolValue *CPV =
2318 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
2320 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2321 Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2322 Offset, MachinePointerInfo::getConstantPool(),
2323 false, false, false, 0);
2325 // Call __tls_get_offset to retrieve the offset.
2326 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
2330 case TLSModel::LocalDynamic: {
2331 // Load the GOT offset of the module ID.
2332 SystemZConstantPoolValue *CPV =
2333 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
2335 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2336 Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2337 Offset, MachinePointerInfo::getConstantPool(),
2338 false, false, false, 0);
2340 // Call __tls_get_offset to retrieve the module base offset.
2341 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
2343 // Note: The SystemZLDCleanupPass will remove redundant computations
2344 // of the module base offset. Count total number of local-dynamic
2345 // accesses to trigger execution of that pass.
2346 SystemZMachineFunctionInfo* MFI =
2347 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
2348 MFI->incNumLocalDynamicTLSAccesses();
2350 // Add the per-symbol offset.
2351 CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
2353 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
2354 DTPOffset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2355 DTPOffset, MachinePointerInfo::getConstantPool(),
2356 false, false, false, 0);
2358 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
2362 case TLSModel::InitialExec: {
2363 // Load the offset from the GOT.
2364 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2365 SystemZII::MO_INDNTPOFF);
2366 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
2367 Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2368 Offset, MachinePointerInfo::getGOT(),
2369 false, false, false, 0);
2373 case TLSModel::LocalExec: {
2374 // Force the offset into the constant pool and load it from there.
2375 SystemZConstantPoolValue *CPV =
2376 SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
2378 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2379 Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2380 Offset, MachinePointerInfo::getConstantPool(),
2381 false, false, false, 0);
2386 // Add the base and offset together.
2387 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
2390 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
2391 SelectionDAG &DAG) const {
2393 const BlockAddress *BA = Node->getBlockAddress();
2394 int64_t Offset = Node->getOffset();
2395 EVT PtrVT = getPointerTy();
2397 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
2398 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2402 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2403 SelectionDAG &DAG) const {
2405 EVT PtrVT = getPointerTy();
2406 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2408 // Use LARL to load the address of the table.
2409 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2412 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2413 SelectionDAG &DAG) const {
2415 EVT PtrVT = getPointerTy();
2418 if (CP->isMachineConstantPoolEntry())
2419 Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2420 CP->getAlignment());
2422 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2423 CP->getAlignment(), CP->getOffset());
2425 // Use LARL to load the address of the constant pool entry.
2426 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2429 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2430 SelectionDAG &DAG) const {
2432 SDValue In = Op.getOperand(0);
2433 EVT InVT = In.getValueType();
2434 EVT ResVT = Op.getValueType();
2436 // Convert loads directly. This is normally done by DAGCombiner,
2437 // but we need this case for bitcasts that are created during lowering
2438 // and which are then lowered themselves.
2439 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
2440 return DAG.getLoad(ResVT, DL, LoadN->getChain(), LoadN->getBasePtr(),
2441 LoadN->getMemOperand());
2443 if (InVT == MVT::i32 && ResVT == MVT::f32) {
2445 if (Subtarget.hasHighWord()) {
2446 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2448 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2449 MVT::i64, SDValue(U64, 0), In);
2451 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2452 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2453 DAG.getConstant(32, DL, MVT::i64));
2455 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2456 return DAG.getTargetExtractSubreg(SystemZ::subreg_r32,
2457 DL, MVT::f32, Out64);
2459 if (InVT == MVT::f32 && ResVT == MVT::i32) {
2460 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2461 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_r32, DL,
2462 MVT::f64, SDValue(U64, 0), In);
2463 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2464 if (Subtarget.hasHighWord())
2465 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2467 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2468 DAG.getConstant(32, DL, MVT::i64));
2469 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2471 llvm_unreachable("Unexpected bitcast combination");
2474 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2475 SelectionDAG &DAG) const {
2476 MachineFunction &MF = DAG.getMachineFunction();
2477 SystemZMachineFunctionInfo *FuncInfo =
2478 MF.getInfo<SystemZMachineFunctionInfo>();
2479 EVT PtrVT = getPointerTy();
2481 SDValue Chain = Op.getOperand(0);
2482 SDValue Addr = Op.getOperand(1);
2483 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2486 // The initial values of each field.
2487 const unsigned NumFields = 4;
2488 SDValue Fields[NumFields] = {
2489 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
2490 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
2491 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2492 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2495 // Store each field into its respective slot.
2496 SDValue MemOps[NumFields];
2497 unsigned Offset = 0;
2498 for (unsigned I = 0; I < NumFields; ++I) {
2499 SDValue FieldAddr = Addr;
2501 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
2502 DAG.getIntPtrConstant(Offset, DL));
2503 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
2504 MachinePointerInfo(SV, Offset),
2508 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2511 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
2512 SelectionDAG &DAG) const {
2513 SDValue Chain = Op.getOperand(0);
2514 SDValue DstPtr = Op.getOperand(1);
2515 SDValue SrcPtr = Op.getOperand(2);
2516 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2517 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
2520 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
2521 /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
2522 /*isTailCall*/false,
2523 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
2526 SDValue SystemZTargetLowering::
2527 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
2528 SDValue Chain = Op.getOperand(0);
2529 SDValue Size = Op.getOperand(1);
2532 unsigned SPReg = getStackPointerRegisterToSaveRestore();
2534 // Get a reference to the stack pointer.
2535 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
2537 // Get the new stack pointer value.
2538 SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
2540 // Copy the new stack pointer back.
2541 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
2543 // The allocated data lives above the 160 bytes allocated for the standard
2544 // frame, plus any outgoing stack arguments. We don't know how much that
2545 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
2546 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2547 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
2549 SDValue Ops[2] = { Result, Chain };
2550 return DAG.getMergeValues(Ops, DL);
2553 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
2554 SelectionDAG &DAG) const {
2555 EVT VT = Op.getValueType();
2559 // Just do a normal 64-bit multiplication and extract the results.
2560 // We define this so that it can be used for constant division.
2561 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
2562 Op.getOperand(1), Ops[1], Ops[0]);
2564 // Do a full 128-bit multiplication based on UMUL_LOHI64:
2566 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
2568 // but using the fact that the upper halves are either all zeros
2571 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
2573 // and grouping the right terms together since they are quicker than the
2576 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
2577 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
2578 SDValue LL = Op.getOperand(0);
2579 SDValue RL = Op.getOperand(1);
2580 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
2581 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
2582 // UMUL_LOHI64 returns the low result in the odd register and the high
2583 // result in the even register. SMUL_LOHI is defined to return the
2584 // low half first, so the results are in reverse order.
2585 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2586 LL, RL, Ops[1], Ops[0]);
2587 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
2588 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
2589 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
2590 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
2592 return DAG.getMergeValues(Ops, DL);
2595 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
2596 SelectionDAG &DAG) const {
2597 EVT VT = Op.getValueType();
2601 // Just do a normal 64-bit multiplication and extract the results.
2602 // We define this so that it can be used for constant division.
2603 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
2604 Op.getOperand(1), Ops[1], Ops[0]);
2606 // UMUL_LOHI64 returns the low result in the odd register and the high
2607 // result in the even register. UMUL_LOHI is defined to return the
2608 // low half first, so the results are in reverse order.
2609 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2610 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2611 return DAG.getMergeValues(Ops, DL);
2614 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
2615 SelectionDAG &DAG) const {
2616 SDValue Op0 = Op.getOperand(0);
2617 SDValue Op1 = Op.getOperand(1);
2618 EVT VT = Op.getValueType();
2622 // We use DSGF for 32-bit division.
2624 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
2625 Opcode = SystemZISD::SDIVREM32;
2626 } else if (DAG.ComputeNumSignBits(Op1) > 32) {
2627 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
2628 Opcode = SystemZISD::SDIVREM32;
2630 Opcode = SystemZISD::SDIVREM64;
2632 // DSG(F) takes a 64-bit dividend, so the even register in the GR128
2633 // input is "don't care". The instruction returns the remainder in
2634 // the even register and the quotient in the odd register.
2636 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
2637 Op0, Op1, Ops[1], Ops[0]);
2638 return DAG.getMergeValues(Ops, DL);
2641 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
2642 SelectionDAG &DAG) const {
2643 EVT VT = Op.getValueType();
2646 // DL(G) uses a double-width dividend, so we need to clear the even
2647 // register in the GR128 input. The instruction returns the remainder
2648 // in the even register and the quotient in the odd register.
2651 lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
2652 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2654 lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
2655 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2656 return DAG.getMergeValues(Ops, DL);
2659 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
2660 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
2662 // Get the known-zero masks for each operand.
2663 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
2664 APInt KnownZero[2], KnownOne[2];
2665 DAG.computeKnownBits(Ops[0], KnownZero[0], KnownOne[0]);
2666 DAG.computeKnownBits(Ops[1], KnownZero[1], KnownOne[1]);
2668 // See if the upper 32 bits of one operand and the lower 32 bits of the
2669 // other are known zero. They are the low and high operands respectively.
2670 uint64_t Masks[] = { KnownZero[0].getZExtValue(),
2671 KnownZero[1].getZExtValue() };
2673 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
2675 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
2680 SDValue LowOp = Ops[Low];
2681 SDValue HighOp = Ops[High];
2683 // If the high part is a constant, we're better off using IILH.
2684 if (HighOp.getOpcode() == ISD::Constant)
2687 // If the low part is a constant that is outside the range of LHI,
2688 // then we're better off using IILF.
2689 if (LowOp.getOpcode() == ISD::Constant) {
2690 int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
2691 if (!isInt<16>(Value))
2695 // Check whether the high part is an AND that doesn't change the
2696 // high 32 bits and just masks out low bits. We can skip it if so.
2697 if (HighOp.getOpcode() == ISD::AND &&
2698 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
2699 SDValue HighOp0 = HighOp.getOperand(0);
2700 uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
2701 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
2705 // Take advantage of the fact that all GR32 operations only change the
2706 // low 32 bits by truncating Low to an i32 and inserting it directly
2707 // using a subreg. The interesting cases are those where the truncation
2710 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
2711 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
2712 MVT::i64, HighOp, Low32);
2715 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
2716 SelectionDAG &DAG) const {
2717 EVT VT = Op.getValueType();
2719 Op = Op.getOperand(0);
2721 // Handle vector types via VPOPCT.
2722 if (VT.isVector()) {
2723 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
2724 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
2725 switch (VT.getVectorElementType().getSizeInBits()) {
2729 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
2730 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
2731 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
2732 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
2733 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
2737 SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2738 DAG.getConstant(0, DL, MVT::i32));
2739 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
2743 SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2744 DAG.getConstant(0, DL, MVT::i32));
2745 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
2746 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
2750 llvm_unreachable("Unexpected type");
2755 // Get the known-zero mask for the operand.
2756 APInt KnownZero, KnownOne;
2757 DAG.computeKnownBits(Op, KnownZero, KnownOne);
2758 unsigned NumSignificantBits = (~KnownZero).getActiveBits();
2759 if (NumSignificantBits == 0)
2760 return DAG.getConstant(0, DL, VT);
2762 // Skip known-zero high parts of the operand.
2763 int64_t OrigBitSize = VT.getSizeInBits();
2764 int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
2765 BitSize = std::min(BitSize, OrigBitSize);
2767 // The POPCNT instruction counts the number of bits in each byte.
2768 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
2769 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
2770 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
2772 // Add up per-byte counts in a binary tree. All bits of Op at
2773 // position larger than BitSize remain zero throughout.
2774 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
2775 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
2776 if (BitSize != OrigBitSize)
2777 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
2778 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
2779 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
2782 // Extract overall result from high byte.
2784 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
2785 DAG.getConstant(BitSize - 8, DL, VT));
2790 // Op is an atomic load. Lower it into a normal volatile load.
2791 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
2792 SelectionDAG &DAG) const {
2793 auto *Node = cast<AtomicSDNode>(Op.getNode());
2794 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
2795 Node->getChain(), Node->getBasePtr(),
2796 Node->getMemoryVT(), Node->getMemOperand());
2799 // Op is an atomic store. Lower it into a normal volatile store followed
2800 // by a serialization.
2801 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
2802 SelectionDAG &DAG) const {
2803 auto *Node = cast<AtomicSDNode>(Op.getNode());
2804 SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
2805 Node->getBasePtr(), Node->getMemoryVT(),
2806 Node->getMemOperand());
2807 return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
2811 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
2812 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
2813 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
2815 unsigned Opcode) const {
2816 auto *Node = cast<AtomicSDNode>(Op.getNode());
2818 // 32-bit operations need no code outside the main loop.
2819 EVT NarrowVT = Node->getMemoryVT();
2820 EVT WideVT = MVT::i32;
2821 if (NarrowVT == WideVT)
2824 int64_t BitSize = NarrowVT.getSizeInBits();
2825 SDValue ChainIn = Node->getChain();
2826 SDValue Addr = Node->getBasePtr();
2827 SDValue Src2 = Node->getVal();
2828 MachineMemOperand *MMO = Node->getMemOperand();
2830 EVT PtrVT = Addr.getValueType();
2832 // Convert atomic subtracts of constants into additions.
2833 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
2834 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
2835 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
2836 Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
2839 // Get the address of the containing word.
2840 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2841 DAG.getConstant(-4, DL, PtrVT));
2843 // Get the number of bits that the word must be rotated left in order
2844 // to bring the field to the top bits of a GR32.
2845 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2846 DAG.getConstant(3, DL, PtrVT));
2847 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2849 // Get the complementing shift amount, for rotating a field in the top
2850 // bits back to its proper position.
2851 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2852 DAG.getConstant(0, DL, WideVT), BitShift);
2854 // Extend the source operand to 32 bits and prepare it for the inner loop.
2855 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
2856 // operations require the source to be shifted in advance. (This shift
2857 // can be folded if the source is constant.) For AND and NAND, the lower
2858 // bits must be set, while for other opcodes they should be left clear.
2859 if (Opcode != SystemZISD::ATOMIC_SWAPW)
2860 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
2861 DAG.getConstant(32 - BitSize, DL, WideVT));
2862 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
2863 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
2864 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
2865 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
2867 // Construct the ATOMIC_LOADW_* node.
2868 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2869 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
2870 DAG.getConstant(BitSize, DL, WideVT) };
2871 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
2874 // Rotate the result of the final CS so that the field is in the lower
2875 // bits of a GR32, then truncate it.
2876 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
2877 DAG.getConstant(BitSize, DL, WideVT));
2878 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
2880 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
2881 return DAG.getMergeValues(RetOps, DL);
2884 // Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations
2885 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
2886 // operations into additions.
2887 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
2888 SelectionDAG &DAG) const {
2889 auto *Node = cast<AtomicSDNode>(Op.getNode());
2890 EVT MemVT = Node->getMemoryVT();
2891 if (MemVT == MVT::i32 || MemVT == MVT::i64) {
2892 // A full-width operation.
2893 assert(Op.getValueType() == MemVT && "Mismatched VTs");
2894 SDValue Src2 = Node->getVal();
2898 if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
2899 // Use an addition if the operand is constant and either LAA(G) is
2900 // available or the negative value is in the range of A(G)FHI.
2901 int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
2902 if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
2903 NegSrc2 = DAG.getConstant(Value, DL, MemVT);
2904 } else if (Subtarget.hasInterlockedAccess1())
2905 // Use LAA(G) if available.
2906 NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
2909 if (NegSrc2.getNode())
2910 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
2911 Node->getChain(), Node->getBasePtr(), NegSrc2,
2912 Node->getMemOperand(), Node->getOrdering(),
2913 Node->getSynchScope());
2915 // Use the node as-is.
2919 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
2922 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation. Lower the first two
2923 // into a fullword ATOMIC_CMP_SWAPW operation.
2924 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
2925 SelectionDAG &DAG) const {
2926 auto *Node = cast<AtomicSDNode>(Op.getNode());
2928 // We have native support for 32-bit compare and swap.
2929 EVT NarrowVT = Node->getMemoryVT();
2930 EVT WideVT = MVT::i32;
2931 if (NarrowVT == WideVT)
2934 int64_t BitSize = NarrowVT.getSizeInBits();
2935 SDValue ChainIn = Node->getOperand(0);
2936 SDValue Addr = Node->getOperand(1);
2937 SDValue CmpVal = Node->getOperand(2);
2938 SDValue SwapVal = Node->getOperand(3);
2939 MachineMemOperand *MMO = Node->getMemOperand();
2941 EVT PtrVT = Addr.getValueType();
2943 // Get the address of the containing word.
2944 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2945 DAG.getConstant(-4, DL, PtrVT));
2947 // Get the number of bits that the word must be rotated left in order
2948 // to bring the field to the top bits of a GR32.
2949 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2950 DAG.getConstant(3, DL, PtrVT));
2951 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2953 // Get the complementing shift amount, for rotating a field in the top
2954 // bits back to its proper position.
2955 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2956 DAG.getConstant(0, DL, WideVT), BitShift);
2958 // Construct the ATOMIC_CMP_SWAPW node.
2959 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2960 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
2961 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
2962 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
2963 VTList, Ops, NarrowVT, MMO);
2967 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
2968 SelectionDAG &DAG) const {
2969 MachineFunction &MF = DAG.getMachineFunction();
2970 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
2971 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
2972 SystemZ::R15D, Op.getValueType());
2975 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
2976 SelectionDAG &DAG) const {
2977 MachineFunction &MF = DAG.getMachineFunction();
2978 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
2979 return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
2980 SystemZ::R15D, Op.getOperand(1));
2983 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
2984 SelectionDAG &DAG) const {
2985 bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2987 // Just preserve the chain.
2988 return Op.getOperand(0);
2991 bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2992 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
2993 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
2996 DAG.getConstant(Code, DL, MVT::i32),
2999 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
3000 Node->getVTList(), Ops,
3001 Node->getMemoryVT(), Node->getMemOperand());
3004 // Return an i32 that contains the value of CC immediately after After,
3005 // whose final operand must be MVT::Glue.
3006 static SDValue getCCResult(SelectionDAG &DAG, SDNode *After) {
3008 SDValue Glue = SDValue(After, After->getNumValues() - 1);
3009 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
3010 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
3011 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
3015 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
3016 SelectionDAG &DAG) const {
3017 unsigned Opcode, CCValid;
3018 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
3019 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
3020 SDValue Glued = emitIntrinsicWithChainAndGlue(DAG, Op, Opcode);
3021 SDValue CC = getCCResult(DAG, Glued.getNode());
3022 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
3030 // Says that SystemZISD operation Opcode can be used to perform the equivalent
3031 // of a VPERM with permute vector Bytes. If Opcode takes three operands,
3032 // Operand is the constant third operand, otherwise it is the number of
3033 // bytes in each element of the result.
3037 unsigned char Bytes[SystemZ::VectorBytes];
3041 static const Permute PermuteForms[] = {
3043 { SystemZISD::MERGE_HIGH, 8,
3044 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
3046 { SystemZISD::MERGE_HIGH, 4,
3047 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
3049 { SystemZISD::MERGE_HIGH, 2,
3050 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
3052 { SystemZISD::MERGE_HIGH, 1,
3053 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
3055 { SystemZISD::MERGE_LOW, 8,
3056 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
3058 { SystemZISD::MERGE_LOW, 4,
3059 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
3061 { SystemZISD::MERGE_LOW, 2,
3062 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
3064 { SystemZISD::MERGE_LOW, 1,
3065 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
3067 { SystemZISD::PACK, 4,
3068 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
3070 { SystemZISD::PACK, 2,
3071 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
3073 { SystemZISD::PACK, 1,
3074 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
3075 // VPDI V1, V2, 4 (low half of V1, high half of V2)
3076 { SystemZISD::PERMUTE_DWORDS, 4,
3077 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
3078 // VPDI V1, V2, 1 (high half of V1, low half of V2)
3079 { SystemZISD::PERMUTE_DWORDS, 1,
3080 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
3083 // Called after matching a vector shuffle against a particular pattern.
3084 // Both the original shuffle and the pattern have two vector operands.
3085 // OpNos[0] is the operand of the original shuffle that should be used for
3086 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
3087 // OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
3088 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
3089 // for operands 0 and 1 of the pattern.
3090 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
3094 OpNo0 = OpNo1 = OpNos[1];
3095 } else if (OpNos[1] < 0) {
3096 OpNo0 = OpNo1 = OpNos[0];
3104 // Bytes is a VPERM-like permute vector, except that -1 is used for
3105 // undefined bytes. Return true if the VPERM can be implemented using P.
3106 // When returning true set OpNo0 to the VPERM operand that should be
3107 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
3109 // For example, if swapping the VPERM operands allows P to match, OpNo0
3110 // will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
3111 // operand, but rewriting it to use two duplicated operands allows it to
3112 // match P, then OpNo0 and OpNo1 will be the same.
3113 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
3114 unsigned &OpNo0, unsigned &OpNo1) {
3115 int OpNos[] = { -1, -1 };
3116 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
3119 // Make sure that the two permute vectors use the same suboperand
3120 // byte number. Only the operand numbers (the high bits) are
3121 // allowed to differ.
3122 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
3124 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
3125 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
3126 // Make sure that the operand mappings are consistent with previous
3128 if (OpNos[ModelOpNo] == 1 - RealOpNo)
3130 OpNos[ModelOpNo] = RealOpNo;
3133 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3136 // As above, but search for a matching permute.
3137 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
3138 unsigned &OpNo0, unsigned &OpNo1) {
3139 for (auto &P : PermuteForms)
3140 if (matchPermute(Bytes, P, OpNo0, OpNo1))
3145 // Bytes is a VPERM-like permute vector, except that -1 is used for
3146 // undefined bytes. This permute is an operand of an outer permute.
3147 // See whether redistributing the -1 bytes gives a shuffle that can be
3148 // implemented using P. If so, set Transform to a VPERM-like permute vector
3149 // that, when applied to the result of P, gives the original permute in Bytes.
3150 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3152 SmallVectorImpl<int> &Transform) {
3154 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
3155 int Elt = Bytes[From];
3157 // Byte number From of the result is undefined.
3158 Transform[From] = -1;
3160 while (P.Bytes[To] != Elt) {
3162 if (To == SystemZ::VectorBytes)
3165 Transform[From] = To;
3171 // As above, but search for a matching permute.
3172 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3173 SmallVectorImpl<int> &Transform) {
3174 for (auto &P : PermuteForms)
3175 if (matchDoublePermute(Bytes, P, Transform))
3180 // Convert the mask of the given VECTOR_SHUFFLE into a byte-level mask,
3181 // as if it had type vNi8.
3182 static void getVPermMask(ShuffleVectorSDNode *VSN,
3183 SmallVectorImpl<int> &Bytes) {
3184 EVT VT = VSN->getValueType(0);
3185 unsigned NumElements = VT.getVectorNumElements();
3186 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3187 Bytes.resize(NumElements * BytesPerElement, -1);
3188 for (unsigned I = 0; I < NumElements; ++I) {
3189 int Index = VSN->getMaskElt(I);
3191 for (unsigned J = 0; J < BytesPerElement; ++J)
3192 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
3196 // Bytes is a VPERM-like permute vector, except that -1 is used for
3197 // undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
3198 // the result come from a contiguous sequence of bytes from one input.
3199 // Set Base to the selector for the first byte if so.
3200 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
3201 unsigned BytesPerElement, int &Base) {
3203 for (unsigned I = 0; I < BytesPerElement; ++I) {
3204 if (Bytes[Start + I] >= 0) {
3205 unsigned Elem = Bytes[Start + I];
3208 // Make sure the bytes would come from one input operand.
3209 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
3211 } else if (unsigned(Base) != Elem - I)
3218 // Bytes is a VPERM-like permute vector, except that -1 is used for
3219 // undefined bytes. Return true if it can be performed using VSLDI.
3220 // When returning true, set StartIndex to the shift amount and OpNo0
3221 // and OpNo1 to the VPERM operands that should be used as the first
3222 // and second shift operand respectively.
3223 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
3224 unsigned &StartIndex, unsigned &OpNo0,
3226 int OpNos[] = { -1, -1 };
3228 for (unsigned I = 0; I < 16; ++I) {
3229 int Index = Bytes[I];
3231 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
3232 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
3233 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
3235 Shift = ExpectedShift;
3236 else if (Shift != ExpectedShift)
3238 // Make sure that the operand mappings are consistent with previous
3240 if (OpNos[ModelOpNo] == 1 - RealOpNo)
3242 OpNos[ModelOpNo] = RealOpNo;
3246 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3249 // Create a node that performs P on operands Op0 and Op1, casting the
3250 // operands to the appropriate type. The type of the result is determined by P.
3251 static SDValue getPermuteNode(SelectionDAG &DAG, SDLoc DL,
3252 const Permute &P, SDValue Op0, SDValue Op1) {
3253 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
3254 // elements of a PACK are twice as wide as the outputs.
3255 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
3256 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
3258 // Cast both operands to the appropriate type.
3259 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
3260 SystemZ::VectorBytes / InBytes);
3261 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
3262 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
3264 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
3265 SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32);
3266 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
3267 } else if (P.Opcode == SystemZISD::PACK) {
3268 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
3269 SystemZ::VectorBytes / P.Operand);
3270 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
3272 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
3277 // Bytes is a VPERM-like permute vector, except that -1 is used for
3278 // undefined bytes. Implement it on operands Ops[0] and Ops[1] using
3280 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, SDLoc DL, SDValue *Ops,
3281 const SmallVectorImpl<int> &Bytes) {
3282 for (unsigned I = 0; I < 2; ++I)
3283 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
3285 // First see whether VSLDI can be used.
3286 unsigned StartIndex, OpNo0, OpNo1;
3287 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
3288 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
3289 Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32));
3291 // Fall back on VPERM. Construct an SDNode for the permute vector.
3292 SDValue IndexNodes[SystemZ::VectorBytes];
3293 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3295 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
3297 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
3298 SDValue Op2 = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, IndexNodes);
3299 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
3303 // Describes a general N-operand vector shuffle.
3304 struct GeneralShuffle {
3305 GeneralShuffle(EVT vt) : VT(vt) {}
3307 void add(SDValue, unsigned);
3308 SDValue getNode(SelectionDAG &, SDLoc);
3310 // The operands of the shuffle.
3311 SmallVector<SDValue, SystemZ::VectorBytes> Ops;
3313 // Index I is -1 if byte I of the result is undefined. Otherwise the
3314 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
3315 // Bytes[I] / SystemZ::VectorBytes.
3316 SmallVector<int, SystemZ::VectorBytes> Bytes;
3318 // The type of the shuffle result.
3323 // Add an extra undefined element to the shuffle.
3324 void GeneralShuffle::addUndef() {
3325 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3326 for (unsigned I = 0; I < BytesPerElement; ++I)
3327 Bytes.push_back(-1);
3330 // Add an extra element to the shuffle, taking it from element Elem of Op.
3331 // A null Op indicates a vector input whose value will be calculated later;
3332 // there is at most one such input per shuffle and it always has the same
3333 // type as the result.
3334 void GeneralShuffle::add(SDValue Op, unsigned Elem) {
3335 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3337 // The source vector can have wider elements than the result,
3338 // either through an explicit TRUNCATE or because of type legalization.
3339 // We want the least significant part.
3340 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
3341 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
3342 assert(FromBytesPerElement >= BytesPerElement &&
3343 "Invalid EXTRACT_VECTOR_ELT");
3344 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
3345 (FromBytesPerElement - BytesPerElement));
3347 // Look through things like shuffles and bitcasts.
3348 while (Op.getNode()) {
3349 if (Op.getOpcode() == ISD::BITCAST)
3350 Op = Op.getOperand(0);
3351 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
3352 // See whether the bytes we need come from a contiguous part of one
3354 SmallVector<int, SystemZ::VectorBytes> OpBytes;
3355 getVPermMask(cast<ShuffleVectorSDNode>(Op), OpBytes);
3357 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
3363 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
3364 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
3365 } else if (Op.getOpcode() == ISD::UNDEF) {
3372 // Make sure that the source of the extraction is in Ops.
3374 for (; OpNo < Ops.size(); ++OpNo)
3375 if (Ops[OpNo] == Op)
3377 if (OpNo == Ops.size())
3380 // Add the element to Bytes.
3381 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
3382 for (unsigned I = 0; I < BytesPerElement; ++I)
3383 Bytes.push_back(Base + I);
3386 // Return SDNodes for the completed shuffle.
3387 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, SDLoc DL) {
3388 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
3390 if (Ops.size() == 0)
3391 return DAG.getUNDEF(VT);
3393 // Make sure that there are at least two shuffle operands.
3394 if (Ops.size() == 1)
3395 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
3397 // Create a tree of shuffles, deferring root node until after the loop.
3398 // Try to redistribute the undefined elements of non-root nodes so that
3399 // the non-root shuffles match something like a pack or merge, then adjust
3400 // the parent node's permute vector to compensate for the new order.
3401 // Among other things, this copes with vectors like <2 x i16> that were
3402 // padded with undefined elements during type legalization.
3404 // In the best case this redistribution will lead to the whole tree
3405 // using packs and merges. It should rarely be a loss in other cases.
3406 unsigned Stride = 1;
3407 for (; Stride * 2 < Ops.size(); Stride *= 2) {
3408 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
3409 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
3411 // Create a mask for just these two operands.
3412 SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
3413 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3414 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
3415 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
3418 else if (OpNo == I + Stride)
3419 NewBytes[J] = SystemZ::VectorBytes + Byte;
3423 // See if it would be better to reorganize NewMask to avoid using VPERM.
3424 SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
3425 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
3426 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
3427 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
3428 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3429 if (NewBytes[J] >= 0) {
3430 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
3431 "Invalid double permute");
3432 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
3434 assert(NewBytesMap[J] < 0 && "Invalid double permute");
3437 // Just use NewBytes on the operands.
3438 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
3439 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
3440 if (NewBytes[J] >= 0)
3441 Bytes[J] = I * SystemZ::VectorBytes + J;
3446 // Now we just have 2 inputs. Put the second operand in Ops[1].
3448 Ops[1] = Ops[Stride];
3449 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3450 if (Bytes[I] >= int(SystemZ::VectorBytes))
3451 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
3454 // Look for an instruction that can do the permute without resorting
3456 unsigned OpNo0, OpNo1;
3458 if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
3459 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
3461 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
3462 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3465 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
3466 static bool isScalarToVector(SDValue Op) {
3467 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
3468 if (Op.getOperand(I).getOpcode() != ISD::UNDEF)
3473 // Return a vector of type VT that contains Value in the first element.
3474 // The other elements don't matter.
3475 static SDValue buildScalarToVector(SelectionDAG &DAG, SDLoc DL, EVT VT,
3477 // If we have a constant, replicate it to all elements and let the
3478 // BUILD_VECTOR lowering take care of it.
3479 if (Value.getOpcode() == ISD::Constant ||
3480 Value.getOpcode() == ISD::ConstantFP) {
3481 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
3482 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
3484 if (Value.getOpcode() == ISD::UNDEF)
3485 return DAG.getUNDEF(VT);
3486 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
3489 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
3490 // element 1. Used for cases in which replication is cheap.
3491 static SDValue buildMergeScalars(SelectionDAG &DAG, SDLoc DL, EVT VT,
3492 SDValue Op0, SDValue Op1) {
3493 if (Op0.getOpcode() == ISD::UNDEF) {
3494 if (Op1.getOpcode() == ISD::UNDEF)
3495 return DAG.getUNDEF(VT);
3496 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
3498 if (Op1.getOpcode() == ISD::UNDEF)
3499 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
3500 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
3501 buildScalarToVector(DAG, DL, VT, Op0),
3502 buildScalarToVector(DAG, DL, VT, Op1));
3505 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
3507 static SDValue joinDwords(SelectionDAG &DAG, SDLoc DL, SDValue Op0,
3509 if (Op0.getOpcode() == ISD::UNDEF && Op1.getOpcode() == ISD::UNDEF)
3510 return DAG.getUNDEF(MVT::v2i64);
3511 // If one of the two inputs is undefined then replicate the other one,
3512 // in order to avoid using another register unnecessarily.
3513 if (Op0.getOpcode() == ISD::UNDEF)
3514 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3515 else if (Op1.getOpcode() == ISD::UNDEF)
3516 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3518 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3519 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3521 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
3524 // Try to represent constant BUILD_VECTOR node BVN using a
3525 // SystemZISD::BYTE_MASK-style mask. Store the mask value in Mask
3527 static bool tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) {
3528 EVT ElemVT = BVN->getValueType(0).getVectorElementType();
3529 unsigned BytesPerElement = ElemVT.getStoreSize();
3530 for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) {
3531 SDValue Op = BVN->getOperand(I);
3532 if (Op.getOpcode() != ISD::UNDEF) {
3534 if (Op.getOpcode() == ISD::Constant)
3535 Value = dyn_cast<ConstantSDNode>(Op)->getZExtValue();
3536 else if (Op.getOpcode() == ISD::ConstantFP)
3537 Value = (dyn_cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()
3541 for (unsigned J = 0; J < BytesPerElement; ++J) {
3542 uint64_t Byte = (Value >> (J * 8)) & 0xff;
3544 Mask |= 1 << ((E - I - 1) * BytesPerElement + J);
3553 // Try to load a vector constant in which BitsPerElement-bit value Value
3554 // is replicated to fill the vector. VT is the type of the resulting
3555 // constant, which may have elements of a different size from BitsPerElement.
3556 // Return the SDValue of the constant on success, otherwise return
3558 static SDValue tryBuildVectorReplicate(SelectionDAG &DAG,
3559 const SystemZInstrInfo *TII,
3560 SDLoc DL, EVT VT, uint64_t Value,
3561 unsigned BitsPerElement) {
3562 // Signed 16-bit values can be replicated using VREPI.
3563 int64_t SignedValue = SignExtend64(Value, BitsPerElement);
3564 if (isInt<16>(SignedValue)) {
3565 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
3566 SystemZ::VectorBits / BitsPerElement);
3567 SDValue Op = DAG.getNode(SystemZISD::REPLICATE, DL, VecVT,
3568 DAG.getConstant(SignedValue, DL, MVT::i32));
3569 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3571 // See whether rotating the constant left some N places gives a value that
3572 // is one less than a power of 2 (i.e. all zeros followed by all ones).
3573 // If so we can use VGM.
3574 unsigned Start, End;
3575 if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) {
3576 // isRxSBGMask returns the bit numbers for a full 64-bit value,
3577 // with 0 denoting 1 << 63 and 63 denoting 1. Convert them to
3578 // bit numbers for an BitsPerElement value, so that 0 denotes
3579 // 1 << (BitsPerElement-1).
3580 Start -= 64 - BitsPerElement;
3581 End -= 64 - BitsPerElement;
3582 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
3583 SystemZ::VectorBits / BitsPerElement);
3584 SDValue Op = DAG.getNode(SystemZISD::ROTATE_MASK, DL, VecVT,
3585 DAG.getConstant(Start, DL, MVT::i32),
3586 DAG.getConstant(End, DL, MVT::i32));
3587 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3592 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
3593 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
3594 // the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
3595 // would benefit from this representation and return it if so.
3596 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
3597 BuildVectorSDNode *BVN) {
3598 EVT VT = BVN->getValueType(0);
3599 unsigned NumElements = VT.getVectorNumElements();
3601 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
3602 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
3603 // need a BUILD_VECTOR, add an additional placeholder operand for that
3604 // BUILD_VECTOR and store its operands in ResidueOps.
3605 GeneralShuffle GS(VT);
3606 SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
3607 bool FoundOne = false;
3608 for (unsigned I = 0; I < NumElements; ++I) {
3609 SDValue Op = BVN->getOperand(I);
3610 if (Op.getOpcode() == ISD::TRUNCATE)
3611 Op = Op.getOperand(0);
3612 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3613 Op.getOperand(1).getOpcode() == ISD::Constant) {
3614 unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3615 GS.add(Op.getOperand(0), Elem);
3617 } else if (Op.getOpcode() == ISD::UNDEF) {
3620 GS.add(SDValue(), ResidueOps.size());
3621 ResidueOps.push_back(Op);
3625 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
3629 // Create the BUILD_VECTOR for the remaining elements, if any.
3630 if (!ResidueOps.empty()) {
3631 while (ResidueOps.size() < NumElements)
3632 ResidueOps.push_back(DAG.getUNDEF(VT.getVectorElementType()));
3633 for (auto &Op : GS.Ops) {
3634 if (!Op.getNode()) {
3635 Op = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BVN), VT, ResidueOps);
3640 return GS.getNode(DAG, SDLoc(BVN));
3643 // Combine GPR scalar values Elems into a vector of type VT.
3644 static SDValue buildVector(SelectionDAG &DAG, SDLoc DL, EVT VT,
3645 SmallVectorImpl<SDValue> &Elems) {
3646 // See whether there is a single replicated value.
3648 unsigned int NumElements = Elems.size();
3649 unsigned int Count = 0;
3650 for (auto Elem : Elems) {
3651 if (Elem.getOpcode() != ISD::UNDEF) {
3652 if (!Single.getNode())
3654 else if (Elem != Single) {
3661 // There are three cases here:
3663 // - if the only defined element is a loaded one, the best sequence
3664 // is a replicating load.
3666 // - otherwise, if the only defined element is an i64 value, we will
3667 // end up with the same VLVGP sequence regardless of whether we short-cut
3668 // for replication or fall through to the later code.
3670 // - otherwise, if the only defined element is an i32 or smaller value,
3671 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
3672 // This is only a win if the single defined element is used more than once.
3673 // In other cases we're better off using a single VLVGx.
3674 if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD))
3675 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
3677 // The best way of building a v2i64 from two i64s is to use VLVGP.
3678 if (VT == MVT::v2i64)
3679 return joinDwords(DAG, DL, Elems[0], Elems[1]);
3681 // Use a 64-bit merge high to combine two doubles.
3682 if (VT == MVT::v2f64)
3683 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
3685 // Build v4f32 values directly from the FPRs:
3687 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
3692 if (VT == MVT::v4f32) {
3693 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
3694 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
3695 // Avoid unnecessary undefs by reusing the other operand.
3696 if (Op01.getOpcode() == ISD::UNDEF)
3698 else if (Op23.getOpcode() == ISD::UNDEF)
3700 // Merging identical replications is a no-op.
3701 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
3703 Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
3704 Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
3705 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
3706 DL, MVT::v2i64, Op01, Op23);
3707 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3710 // Collect the constant terms.
3711 SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
3712 SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
3714 unsigned NumConstants = 0;
3715 for (unsigned I = 0; I < NumElements; ++I) {
3716 SDValue Elem = Elems[I];
3717 if (Elem.getOpcode() == ISD::Constant ||
3718 Elem.getOpcode() == ISD::ConstantFP) {
3720 Constants[I] = Elem;
3724 // If there was at least one constant, fill in the other elements of
3725 // Constants with undefs to get a full vector constant and use that
3726 // as the starting point.
3728 if (NumConstants > 0) {
3729 for (unsigned I = 0; I < NumElements; ++I)
3730 if (!Constants[I].getNode())
3731 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
3732 Result = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Constants);
3734 // Otherwise try to use VLVGP to start the sequence in order to
3735 // avoid a false dependency on any previous contents of the vector
3736 // register. This only makes sense if one of the associated elements
3738 unsigned I1 = NumElements / 2 - 1;
3739 unsigned I2 = NumElements - 1;
3740 bool Def1 = (Elems[I1].getOpcode() != ISD::UNDEF);
3741 bool Def2 = (Elems[I2].getOpcode() != ISD::UNDEF);
3743 SDValue Elem1 = Elems[Def1 ? I1 : I2];
3744 SDValue Elem2 = Elems[Def2 ? I2 : I1];
3745 Result = DAG.getNode(ISD::BITCAST, DL, VT,
3746 joinDwords(DAG, DL, Elem1, Elem2));
3750 Result = DAG.getUNDEF(VT);
3753 // Use VLVGx to insert the other elements.
3754 for (unsigned I = 0; I < NumElements; ++I)
3755 if (!Done[I] && Elems[I].getOpcode() != ISD::UNDEF)
3756 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
3757 DAG.getConstant(I, DL, MVT::i32));
3761 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
3762 SelectionDAG &DAG) const {
3763 const SystemZInstrInfo *TII =
3764 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
3765 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
3767 EVT VT = Op.getValueType();
3769 if (BVN->isConstant()) {
3770 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
3771 // preferred way of creating all-zero and all-one vectors so give it
3772 // priority over other methods below.
3774 if (tryBuildVectorByteMask(BVN, Mask)) {
3775 SDValue Op = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3776 DAG.getConstant(Mask, DL, MVT::i32));
3777 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3780 // Try using some form of replication.
3781 APInt SplatBits, SplatUndef;
3782 unsigned SplatBitSize;
3784 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
3786 SplatBitSize <= 64) {
3787 // First try assuming that any undefined bits above the highest set bit
3788 // and below the lowest set bit are 1s. This increases the likelihood of
3789 // being able to use a sign-extended element value in VECTOR REPLICATE
3790 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
3791 uint64_t SplatBitsZ = SplatBits.getZExtValue();
3792 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
3793 uint64_t Lower = (SplatUndefZ
3794 & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
3795 uint64_t Upper = (SplatUndefZ
3796 & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
3797 uint64_t Value = SplatBitsZ | Upper | Lower;
3798 SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value,
3803 // Now try assuming that any undefined bits between the first and
3804 // last defined set bits are set. This increases the chances of
3805 // using a non-wraparound mask.
3806 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
3807 Value = SplatBitsZ | Middle;
3808 Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize);
3813 // Fall back to loading it from memory.
3817 // See if we should use shuffles to construct the vector from other vectors.
3818 SDValue Res = tryBuildVectorShuffle(DAG, BVN);
3822 // Detect SCALAR_TO_VECTOR conversions.
3823 if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
3824 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
3826 // Otherwise use buildVector to build the vector up from GPRs.
3827 unsigned NumElements = Op.getNumOperands();
3828 SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
3829 for (unsigned I = 0; I < NumElements; ++I)
3830 Ops[I] = Op.getOperand(I);
3831 return buildVector(DAG, DL, VT, Ops);
3834 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
3835 SelectionDAG &DAG) const {
3836 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
3838 EVT VT = Op.getValueType();
3839 unsigned NumElements = VT.getVectorNumElements();
3841 if (VSN->isSplat()) {
3842 SDValue Op0 = Op.getOperand(0);
3843 unsigned Index = VSN->getSplatIndex();
3844 assert(Index < VT.getVectorNumElements() &&
3845 "Splat index should be defined and in first operand");
3846 // See whether the value we're splatting is directly available as a scalar.
3847 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
3848 Op0.getOpcode() == ISD::BUILD_VECTOR)
3849 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
3850 // Otherwise keep it as a vector-to-vector operation.
3851 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
3852 DAG.getConstant(Index, DL, MVT::i32));
3855 GeneralShuffle GS(VT);
3856 for (unsigned I = 0; I < NumElements; ++I) {
3857 int Elt = VSN->getMaskElt(I);
3861 GS.add(Op.getOperand(unsigned(Elt) / NumElements),
3862 unsigned(Elt) % NumElements);
3864 return GS.getNode(DAG, SDLoc(VSN));
3867 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
3868 SelectionDAG &DAG) const {
3870 // Just insert the scalar into element 0 of an undefined vector.
3871 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
3872 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
3873 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
3876 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3877 SelectionDAG &DAG) const {
3878 // Handle insertions of floating-point values.
3880 SDValue Op0 = Op.getOperand(0);
3881 SDValue Op1 = Op.getOperand(1);
3882 SDValue Op2 = Op.getOperand(2);
3883 EVT VT = Op.getValueType();
3885 // Insertions into constant indices of a v2f64 can be done using VPDI.
3886 // However, if the inserted value is a bitcast or a constant then it's
3887 // better to use GPRs, as below.
3888 if (VT == MVT::v2f64 &&
3889 Op1.getOpcode() != ISD::BITCAST &&
3890 Op1.getOpcode() != ISD::ConstantFP &&
3891 Op2.getOpcode() == ISD::Constant) {
3892 uint64_t Index = dyn_cast<ConstantSDNode>(Op2)->getZExtValue();
3893 unsigned Mask = VT.getVectorNumElements() - 1;
3898 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
3899 MVT IntVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
3900 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
3901 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
3902 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
3903 DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
3904 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
3908 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3909 SelectionDAG &DAG) const {
3910 // Handle extractions of floating-point values.
3912 SDValue Op0 = Op.getOperand(0);
3913 SDValue Op1 = Op.getOperand(1);
3914 EVT VT = Op.getValueType();
3915 EVT VecVT = Op0.getValueType();
3917 // Extractions of constant indices can be done directly.
3918 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
3919 uint64_t Index = CIndexN->getZExtValue();
3920 unsigned Mask = VecVT.getVectorNumElements() - 1;
3925 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
3926 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
3927 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
3928 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
3929 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
3930 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
3934 SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG,
3935 unsigned UnpackHigh) const {
3936 SDValue PackedOp = Op.getOperand(0);
3937 EVT OutVT = Op.getValueType();
3938 EVT InVT = PackedOp.getValueType();
3939 unsigned ToBits = OutVT.getVectorElementType().getSizeInBits();
3940 unsigned FromBits = InVT.getVectorElementType().getSizeInBits();
3943 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
3944 SystemZ::VectorBits / FromBits);
3945 PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp);
3946 } while (FromBits != ToBits);
3950 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
3951 unsigned ByScalar) const {
3952 // Look for cases where a vector shift can use the *_BY_SCALAR form.
3953 SDValue Op0 = Op.getOperand(0);
3954 SDValue Op1 = Op.getOperand(1);
3956 EVT VT = Op.getValueType();
3957 unsigned ElemBitSize = VT.getVectorElementType().getSizeInBits();
3959 // See whether the shift vector is a splat represented as BUILD_VECTOR.
3960 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
3961 APInt SplatBits, SplatUndef;
3962 unsigned SplatBitSize;
3964 // Check for constant splats. Use ElemBitSize as the minimum element
3965 // width and reject splats that need wider elements.
3966 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
3967 ElemBitSize, true) &&
3968 SplatBitSize == ElemBitSize) {
3969 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
3971 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
3973 // Check for variable splats.
3974 BitVector UndefElements;
3975 SDValue Splat = BVN->getSplatValue(&UndefElements);
3977 // Since i32 is the smallest legal type, we either need a no-op
3979 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
3980 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
3984 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
3985 // and the shift amount is directly available in a GPR.
3986 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
3987 if (VSN->isSplat()) {
3988 SDValue VSNOp0 = VSN->getOperand(0);
3989 unsigned Index = VSN->getSplatIndex();
3990 assert(Index < VT.getVectorNumElements() &&
3991 "Splat index should be defined and in first operand");
3992 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
3993 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
3994 // Since i32 is the smallest legal type, we either need a no-op
3996 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
3997 VSNOp0.getOperand(Index));
3998 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4003 // Otherwise just treat the current form as legal.
4007 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
4008 SelectionDAG &DAG) const {
4009 switch (Op.getOpcode()) {
4011 return lowerBR_CC(Op, DAG);
4012 case ISD::SELECT_CC:
4013 return lowerSELECT_CC(Op, DAG);
4015 return lowerSETCC(Op, DAG);
4016 case ISD::GlobalAddress:
4017 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
4018 case ISD::GlobalTLSAddress:
4019 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
4020 case ISD::BlockAddress:
4021 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
4022 case ISD::JumpTable:
4023 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
4024 case ISD::ConstantPool:
4025 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
4027 return lowerBITCAST(Op, DAG);
4029 return lowerVASTART(Op, DAG);
4031 return lowerVACOPY(Op, DAG);
4032 case ISD::DYNAMIC_STACKALLOC:
4033 return lowerDYNAMIC_STACKALLOC(Op, DAG);
4034 case ISD::SMUL_LOHI:
4035 return lowerSMUL_LOHI(Op, DAG);
4036 case ISD::UMUL_LOHI:
4037 return lowerUMUL_LOHI(Op, DAG);
4039 return lowerSDIVREM(Op, DAG);
4041 return lowerUDIVREM(Op, DAG);
4043 return lowerOR(Op, DAG);
4045 return lowerCTPOP(Op, DAG);
4046 case ISD::CTLZ_ZERO_UNDEF:
4047 return DAG.getNode(ISD::CTLZ, SDLoc(Op),
4048 Op.getValueType(), Op.getOperand(0));
4049 case ISD::CTTZ_ZERO_UNDEF:
4050 return DAG.getNode(ISD::CTTZ, SDLoc(Op),
4051 Op.getValueType(), Op.getOperand(0));
4052 case ISD::ATOMIC_SWAP:
4053 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
4054 case ISD::ATOMIC_STORE:
4055 return lowerATOMIC_STORE(Op, DAG);
4056 case ISD::ATOMIC_LOAD:
4057 return lowerATOMIC_LOAD(Op, DAG);
4058 case ISD::ATOMIC_LOAD_ADD:
4059 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
4060 case ISD::ATOMIC_LOAD_SUB:
4061 return lowerATOMIC_LOAD_SUB(Op, DAG);
4062 case ISD::ATOMIC_LOAD_AND:
4063 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
4064 case ISD::ATOMIC_LOAD_OR:
4065 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
4066 case ISD::ATOMIC_LOAD_XOR:
4067 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
4068 case ISD::ATOMIC_LOAD_NAND:
4069 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
4070 case ISD::ATOMIC_LOAD_MIN:
4071 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
4072 case ISD::ATOMIC_LOAD_MAX:
4073 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
4074 case ISD::ATOMIC_LOAD_UMIN:
4075 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
4076 case ISD::ATOMIC_LOAD_UMAX:
4077 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
4078 case ISD::ATOMIC_CMP_SWAP:
4079 return lowerATOMIC_CMP_SWAP(Op, DAG);
4080 case ISD::STACKSAVE:
4081 return lowerSTACKSAVE(Op, DAG);
4082 case ISD::STACKRESTORE:
4083 return lowerSTACKRESTORE(Op, DAG);
4085 return lowerPREFETCH(Op, DAG);
4086 case ISD::INTRINSIC_W_CHAIN:
4087 return lowerINTRINSIC_W_CHAIN(Op, DAG);
4088 case ISD::BUILD_VECTOR:
4089 return lowerBUILD_VECTOR(Op, DAG);
4090 case ISD::VECTOR_SHUFFLE:
4091 return lowerVECTOR_SHUFFLE(Op, DAG);
4092 case ISD::SCALAR_TO_VECTOR:
4093 return lowerSCALAR_TO_VECTOR(Op, DAG);
4094 case ISD::INSERT_VECTOR_ELT:
4095 return lowerINSERT_VECTOR_ELT(Op, DAG);
4096 case ISD::EXTRACT_VECTOR_ELT:
4097 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4098 case ISD::SIGN_EXTEND_VECTOR_INREG:
4099 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACK_HIGH);
4100 case ISD::ZERO_EXTEND_VECTOR_INREG:
4101 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACKL_HIGH);
4103 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
4105 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
4107 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
4109 llvm_unreachable("Unexpected node to lower");
4113 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
4114 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
4121 OPCODE(PCREL_WRAPPER);
4122 OPCODE(PCREL_OFFSET);
4128 OPCODE(SELECT_CCMASK);
4129 OPCODE(ADJDYNALLOC);
4130 OPCODE(EXTRACT_ACCESS);
4132 OPCODE(UMUL_LOHI64);
4149 OPCODE(SEARCH_STRING);
4153 OPCODE(TBEGIN_NOFLOAT);
4156 OPCODE(ROTATE_MASK);
4158 OPCODE(JOIN_DWORDS);
4163 OPCODE(PERMUTE_DWORDS);
4166 OPCODE(UNPACK_HIGH);
4167 OPCODE(UNPACKL_HIGH);
4169 OPCODE(UNPACKL_LOW);
4170 OPCODE(VSHL_BY_SCALAR);
4171 OPCODE(VSRL_BY_SCALAR);
4172 OPCODE(VSRA_BY_SCALAR);
4182 OPCODE(ATOMIC_SWAPW);
4183 OPCODE(ATOMIC_LOADW_ADD);
4184 OPCODE(ATOMIC_LOADW_SUB);
4185 OPCODE(ATOMIC_LOADW_AND);
4186 OPCODE(ATOMIC_LOADW_OR);
4187 OPCODE(ATOMIC_LOADW_XOR);
4188 OPCODE(ATOMIC_LOADW_NAND);
4189 OPCODE(ATOMIC_LOADW_MIN);
4190 OPCODE(ATOMIC_LOADW_MAX);
4191 OPCODE(ATOMIC_LOADW_UMIN);
4192 OPCODE(ATOMIC_LOADW_UMAX);
4193 OPCODE(ATOMIC_CMP_SWAPW);
4200 // Return true if VT is a vector whose elements are a whole number of bytes
4202 static bool canTreatAsByteVector(EVT VT) {
4203 return VT.isVector() && VT.getVectorElementType().getSizeInBits() % 8 == 0;
4206 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
4207 // producing a result of type ResVT. Op is a possibly bitcast version
4208 // of the input vector and Index is the index (based on type VecVT) that
4209 // should be extracted. Return the new extraction if a simplification
4210 // was possible or if Force is true.
4211 SDValue SystemZTargetLowering::combineExtract(SDLoc DL, EVT ResVT, EVT VecVT,
4212 SDValue Op, unsigned Index,
4213 DAGCombinerInfo &DCI,
4215 SelectionDAG &DAG = DCI.DAG;
4217 // The number of bytes being extracted.
4218 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4221 unsigned Opcode = Op.getOpcode();
4222 if (Opcode == ISD::BITCAST)
4223 // Look through bitcasts.
4224 Op = Op.getOperand(0);
4225 else if (Opcode == ISD::VECTOR_SHUFFLE &&
4226 canTreatAsByteVector(Op.getValueType())) {
4227 // Get a VPERM-like permute mask and see whether the bytes covered
4228 // by the extracted element are a contiguous sequence from one
4230 SmallVector<int, SystemZ::VectorBytes> Bytes;
4231 getVPermMask(cast<ShuffleVectorSDNode>(Op), Bytes);
4233 if (!getShuffleInput(Bytes, Index * BytesPerElement,
4234 BytesPerElement, First))
4237 return DAG.getUNDEF(ResVT);
4238 // Make sure the contiguous sequence starts at a multiple of the
4239 // original element size.
4240 unsigned Byte = unsigned(First) % Bytes.size();
4241 if (Byte % BytesPerElement != 0)
4243 // We can get the extracted value directly from an input.
4244 Index = Byte / BytesPerElement;
4245 Op = Op.getOperand(unsigned(First) / Bytes.size());
4247 } else if (Opcode == ISD::BUILD_VECTOR &&
4248 canTreatAsByteVector(Op.getValueType())) {
4249 // We can only optimize this case if the BUILD_VECTOR elements are
4250 // at least as wide as the extracted value.
4251 EVT OpVT = Op.getValueType();
4252 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4253 if (OpBytesPerElement < BytesPerElement)
4255 // Make sure that the least-significant bit of the extracted value
4256 // is the least significant bit of an input.
4257 unsigned End = (Index + 1) * BytesPerElement;
4258 if (End % OpBytesPerElement != 0)
4260 // We're extracting the low part of one operand of the BUILD_VECTOR.
4261 Op = Op.getOperand(End / OpBytesPerElement - 1);
4262 if (!Op.getValueType().isInteger()) {
4263 EVT VT = MVT::getIntegerVT(Op.getValueType().getSizeInBits());
4264 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
4265 DCI.AddToWorklist(Op.getNode());
4267 EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
4268 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
4270 DCI.AddToWorklist(Op.getNode());
4271 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
4274 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
4275 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
4276 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
4277 canTreatAsByteVector(Op.getValueType()) &&
4278 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
4279 // Make sure that only the unextended bits are significant.
4280 EVT ExtVT = Op.getValueType();
4281 EVT OpVT = Op.getOperand(0).getValueType();
4282 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
4283 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4284 unsigned Byte = Index * BytesPerElement;
4285 unsigned SubByte = Byte % ExtBytesPerElement;
4286 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
4287 if (SubByte < MinSubByte ||
4288 SubByte + BytesPerElement > ExtBytesPerElement)
4290 // Get the byte offset of the unextended element
4291 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
4292 // ...then add the byte offset relative to that element.
4293 Byte += SubByte - MinSubByte;
4294 if (Byte % BytesPerElement != 0)
4296 Op = Op.getOperand(0);
4297 Index = Byte / BytesPerElement;
4303 if (Op.getValueType() != VecVT) {
4304 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
4305 DCI.AddToWorklist(Op.getNode());
4307 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
4308 DAG.getConstant(Index, DL, MVT::i32));
4313 // Optimize vector operations in scalar value Op on the basis that Op
4314 // is truncated to TruncVT.
4316 SystemZTargetLowering::combineTruncateExtract(SDLoc DL, EVT TruncVT, SDValue Op,
4317 DAGCombinerInfo &DCI) const {
4318 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
4319 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
4321 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4322 TruncVT.getSizeInBits() % 8 == 0) {
4323 SDValue Vec = Op.getOperand(0);
4324 EVT VecVT = Vec.getValueType();
4325 if (canTreatAsByteVector(VecVT)) {
4326 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4327 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4328 unsigned TruncBytes = TruncVT.getStoreSize();
4329 if (BytesPerElement % TruncBytes == 0) {
4330 // Calculate the value of Y' in the above description. We are
4331 // splitting the original elements into Scale equal-sized pieces
4332 // and for truncation purposes want the last (least-significant)
4333 // of these pieces for IndexN. This is easiest to do by calculating
4334 // the start index of the following element and then subtracting 1.
4335 unsigned Scale = BytesPerElement / TruncBytes;
4336 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
4338 // Defer the creation of the bitcast from X to combineExtract,
4339 // which might be able to optimize the extraction.
4340 VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
4341 VecVT.getStoreSize() / TruncBytes);
4342 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
4343 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
4351 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
4352 DAGCombinerInfo &DCI) const {
4353 SelectionDAG &DAG = DCI.DAG;
4354 unsigned Opcode = N->getOpcode();
4355 if (Opcode == ISD::SIGN_EXTEND) {
4356 // Convert (sext (ashr (shl X, C1), C2)) to
4357 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
4358 // cheap as narrower ones.
4359 SDValue N0 = N->getOperand(0);
4360 EVT VT = N->getValueType(0);
4361 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
4362 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4363 SDValue Inner = N0.getOperand(0);
4364 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
4365 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
4366 unsigned Extra = (VT.getSizeInBits() -
4367 N0.getValueType().getSizeInBits());
4368 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
4369 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
4370 EVT ShiftVT = N0.getOperand(1).getValueType();
4371 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
4372 Inner.getOperand(0));
4373 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
4374 DAG.getConstant(NewShlAmt, SDLoc(Inner),
4376 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
4377 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
4382 if (Opcode == SystemZISD::MERGE_HIGH ||
4383 Opcode == SystemZISD::MERGE_LOW) {
4384 SDValue Op0 = N->getOperand(0);
4385 SDValue Op1 = N->getOperand(1);
4386 if (Op0.getOpcode() == ISD::BITCAST)
4387 Op0 = Op0.getOperand(0);
4388 if (Op0.getOpcode() == SystemZISD::BYTE_MASK &&
4389 cast<ConstantSDNode>(Op0.getOperand(0))->getZExtValue() == 0) {
4390 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
4392 if (Op1 == N->getOperand(0))
4394 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
4395 EVT VT = Op1.getValueType();
4396 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
4397 if (ElemBytes <= 4) {
4398 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
4399 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
4400 EVT InVT = VT.changeVectorElementTypeToInteger();
4401 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
4402 SystemZ::VectorBytes / ElemBytes / 2);
4404 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
4405 DCI.AddToWorklist(Op1.getNode());
4407 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
4408 DCI.AddToWorklist(Op.getNode());
4409 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
4413 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
4414 // for the extraction to be done on a vMiN value, so that we can use VSTE.
4415 // If X has wider elements then convert it to:
4416 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
4417 if (Opcode == ISD::STORE) {
4418 auto *SN = cast<StoreSDNode>(N);
4419 EVT MemVT = SN->getMemoryVT();
4420 if (MemVT.isInteger()) {
4421 SDValue Value = combineTruncateExtract(SDLoc(N), MemVT,
4422 SN->getValue(), DCI);
4423 if (Value.getNode()) {
4424 DCI.AddToWorklist(Value.getNode());
4426 // Rewrite the store with the new form of stored value.
4427 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
4428 SN->getBasePtr(), SN->getMemoryVT(),
4429 SN->getMemOperand());
4433 // Try to simplify a vector extraction.
4434 if (Opcode == ISD::EXTRACT_VECTOR_ELT) {
4435 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
4436 SDValue Op0 = N->getOperand(0);
4437 EVT VecVT = Op0.getValueType();
4438 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
4439 IndexN->getZExtValue(), DCI, false);
4442 // (join_dwords X, X) == (replicate X)
4443 if (Opcode == SystemZISD::JOIN_DWORDS &&
4444 N->getOperand(0) == N->getOperand(1))
4445 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
4447 // (fround (extract_vector_elt X 0))
4448 // (fround (extract_vector_elt X 1)) ->
4449 // (extract_vector_elt (VROUND X) 0)
4450 // (extract_vector_elt (VROUND X) 1)
4452 // This is a special case since the target doesn't really support v2f32s.
4453 if (Opcode == ISD::FP_ROUND) {
4454 SDValue Op0 = N->getOperand(0);
4455 if (N->getValueType(0) == MVT::f32 &&
4457 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4458 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
4459 Op0.getOperand(1).getOpcode() == ISD::Constant &&
4460 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
4461 SDValue Vec = Op0.getOperand(0);
4462 for (auto *U : Vec->uses()) {
4463 if (U != Op0.getNode() &&
4465 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4466 U->getOperand(0) == Vec &&
4467 U->getOperand(1).getOpcode() == ISD::Constant &&
4468 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
4469 SDValue OtherRound = SDValue(*U->use_begin(), 0);
4470 if (OtherRound.getOpcode() == ISD::FP_ROUND &&
4471 OtherRound.getOperand(0) == SDValue(U, 0) &&
4472 OtherRound.getValueType() == MVT::f32) {
4473 SDValue VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
4475 DCI.AddToWorklist(VRound.getNode());
4477 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
4478 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
4479 DCI.AddToWorklist(Extract1.getNode());
4480 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
4482 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
4483 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
4493 //===----------------------------------------------------------------------===//
4495 //===----------------------------------------------------------------------===//
4497 // Create a new basic block after MBB.
4498 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
4499 MachineFunction &MF = *MBB->getParent();
4500 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
4501 MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
4505 // Split MBB after MI and return the new block (the one that contains
4506 // instructions after MI).
4507 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
4508 MachineBasicBlock *MBB) {
4509 MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
4510 NewMBB->splice(NewMBB->begin(), MBB,
4511 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
4512 NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
4516 // Split MBB before MI and return the new block (the one that contains MI).
4517 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
4518 MachineBasicBlock *MBB) {
4519 MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
4520 NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
4521 NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
4525 // Force base value Base into a register before MI. Return the register.
4526 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
4527 const SystemZInstrInfo *TII) {
4529 return Base.getReg();
4531 MachineBasicBlock *MBB = MI->getParent();
4532 MachineFunction &MF = *MBB->getParent();
4533 MachineRegisterInfo &MRI = MF.getRegInfo();
4535 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
4536 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
4537 .addOperand(Base).addImm(0).addReg(0);
4541 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
4543 SystemZTargetLowering::emitSelect(MachineInstr *MI,
4544 MachineBasicBlock *MBB) const {
4545 const SystemZInstrInfo *TII =
4546 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4548 unsigned DestReg = MI->getOperand(0).getReg();
4549 unsigned TrueReg = MI->getOperand(1).getReg();
4550 unsigned FalseReg = MI->getOperand(2).getReg();
4551 unsigned CCValid = MI->getOperand(3).getImm();
4552 unsigned CCMask = MI->getOperand(4).getImm();
4553 DebugLoc DL = MI->getDebugLoc();
4555 MachineBasicBlock *StartMBB = MBB;
4556 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB);
4557 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
4560 // BRC CCMask, JoinMBB
4561 // # fallthrough to FalseMBB
4563 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4564 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
4565 MBB->addSuccessor(JoinMBB);
4566 MBB->addSuccessor(FalseMBB);
4569 // # fallthrough to JoinMBB
4571 MBB->addSuccessor(JoinMBB);
4574 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
4577 BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
4578 .addReg(TrueReg).addMBB(StartMBB)
4579 .addReg(FalseReg).addMBB(FalseMBB);
4581 MI->eraseFromParent();
4585 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
4586 // StoreOpcode is the store to use and Invert says whether the store should
4587 // happen when the condition is false rather than true. If a STORE ON
4588 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
4590 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
4591 MachineBasicBlock *MBB,
4592 unsigned StoreOpcode, unsigned STOCOpcode,
4593 bool Invert) const {
4594 const SystemZInstrInfo *TII =
4595 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4597 unsigned SrcReg = MI->getOperand(0).getReg();
4598 MachineOperand Base = MI->getOperand(1);
4599 int64_t Disp = MI->getOperand(2).getImm();
4600 unsigned IndexReg = MI->getOperand(3).getReg();
4601 unsigned CCValid = MI->getOperand(4).getImm();
4602 unsigned CCMask = MI->getOperand(5).getImm();
4603 DebugLoc DL = MI->getDebugLoc();
4605 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
4607 // Use STOCOpcode if possible. We could use different store patterns in
4608 // order to avoid matching the index register, but the performance trade-offs
4609 // might be more complicated in that case.
4610 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
4613 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
4614 .addReg(SrcReg).addOperand(Base).addImm(Disp)
4615 .addImm(CCValid).addImm(CCMask);
4616 MI->eraseFromParent();
4620 // Get the condition needed to branch around the store.
4624 MachineBasicBlock *StartMBB = MBB;
4625 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB);
4626 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
4629 // BRC CCMask, JoinMBB
4630 // # fallthrough to FalseMBB
4632 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4633 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
4634 MBB->addSuccessor(JoinMBB);
4635 MBB->addSuccessor(FalseMBB);
4638 // store %SrcReg, %Disp(%Index,%Base)
4639 // # fallthrough to JoinMBB
4641 BuildMI(MBB, DL, TII->get(StoreOpcode))
4642 .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
4643 MBB->addSuccessor(JoinMBB);
4645 MI->eraseFromParent();
4649 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
4650 // or ATOMIC_SWAP{,W} instruction MI. BinOpcode is the instruction that
4651 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
4652 // BitSize is the width of the field in bits, or 0 if this is a partword
4653 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
4654 // is one of the operands. Invert says whether the field should be
4655 // inverted after performing BinOpcode (e.g. for NAND).
4657 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
4658 MachineBasicBlock *MBB,
4661 bool Invert) const {
4662 MachineFunction &MF = *MBB->getParent();
4663 const SystemZInstrInfo *TII =
4664 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4665 MachineRegisterInfo &MRI = MF.getRegInfo();
4666 bool IsSubWord = (BitSize < 32);
4668 // Extract the operands. Base can be a register or a frame index.
4669 // Src2 can be a register or immediate.
4670 unsigned Dest = MI->getOperand(0).getReg();
4671 MachineOperand Base = earlyUseOperand(MI->getOperand(1));
4672 int64_t Disp = MI->getOperand(2).getImm();
4673 MachineOperand Src2 = earlyUseOperand(MI->getOperand(3));
4674 unsigned BitShift = (IsSubWord ? MI->getOperand(4).getReg() : 0);
4675 unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
4676 DebugLoc DL = MI->getDebugLoc();
4678 BitSize = MI->getOperand(6).getImm();
4680 // Subword operations use 32-bit registers.
4681 const TargetRegisterClass *RC = (BitSize <= 32 ?
4682 &SystemZ::GR32BitRegClass :
4683 &SystemZ::GR64BitRegClass);
4684 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
4685 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
4687 // Get the right opcodes for the displacement.
4688 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
4689 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
4690 assert(LOpcode && CSOpcode && "Displacement out of range");
4692 // Create virtual registers for temporary results.
4693 unsigned OrigVal = MRI.createVirtualRegister(RC);
4694 unsigned OldVal = MRI.createVirtualRegister(RC);
4695 unsigned NewVal = (BinOpcode || IsSubWord ?
4696 MRI.createVirtualRegister(RC) : Src2.getReg());
4697 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
4698 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
4700 // Insert a basic block for the main loop.
4701 MachineBasicBlock *StartMBB = MBB;
4702 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
4703 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
4707 // %OrigVal = L Disp(%Base)
4708 // # fall through to LoopMMB
4710 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
4711 .addOperand(Base).addImm(Disp).addReg(0);
4712 MBB->addSuccessor(LoopMBB);
4715 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
4716 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
4717 // %RotatedNewVal = OP %RotatedOldVal, %Src2
4718 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
4719 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
4721 // # fall through to DoneMMB
4723 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
4724 .addReg(OrigVal).addMBB(StartMBB)
4725 .addReg(Dest).addMBB(LoopMBB);
4727 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
4728 .addReg(OldVal).addReg(BitShift).addImm(0);
4730 // Perform the operation normally and then invert every bit of the field.
4731 unsigned Tmp = MRI.createVirtualRegister(RC);
4732 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
4733 .addReg(RotatedOldVal).addOperand(Src2);
4735 // XILF with the upper BitSize bits set.
4736 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
4737 .addReg(Tmp).addImm(-1U << (32 - BitSize));
4739 // Use LCGR and add -1 to the result, which is more compact than
4740 // an XILF, XILH pair.
4741 unsigned Tmp2 = MRI.createVirtualRegister(RC);
4742 BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
4743 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
4744 .addReg(Tmp2).addImm(-1);
4746 } else if (BinOpcode)
4747 // A simply binary operation.
4748 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
4749 .addReg(RotatedOldVal).addOperand(Src2);
4751 // Use RISBG to rotate Src2 into position and use it to replace the
4752 // field in RotatedOldVal.
4753 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
4754 .addReg(RotatedOldVal).addReg(Src2.getReg())
4755 .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
4757 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
4758 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
4759 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
4760 .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
4761 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4762 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
4763 MBB->addSuccessor(LoopMBB);
4764 MBB->addSuccessor(DoneMBB);
4766 MI->eraseFromParent();
4770 // Implement EmitInstrWithCustomInserter for pseudo
4771 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
4772 // instruction that should be used to compare the current field with the
4773 // minimum or maximum value. KeepOldMask is the BRC condition-code mask
4774 // for when the current field should be kept. BitSize is the width of
4775 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
4777 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
4778 MachineBasicBlock *MBB,
4779 unsigned CompareOpcode,
4780 unsigned KeepOldMask,
4781 unsigned BitSize) const {
4782 MachineFunction &MF = *MBB->getParent();
4783 const SystemZInstrInfo *TII =
4784 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4785 MachineRegisterInfo &MRI = MF.getRegInfo();
4786 bool IsSubWord = (BitSize < 32);
4788 // Extract the operands. Base can be a register or a frame index.
4789 unsigned Dest = MI->getOperand(0).getReg();
4790 MachineOperand Base = earlyUseOperand(MI->getOperand(1));
4791 int64_t Disp = MI->getOperand(2).getImm();
4792 unsigned Src2 = MI->getOperand(3).getReg();
4793 unsigned BitShift = (IsSubWord ? MI->getOperand(4).getReg() : 0);
4794 unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
4795 DebugLoc DL = MI->getDebugLoc();
4797 BitSize = MI->getOperand(6).getImm();
4799 // Subword operations use 32-bit registers.
4800 const TargetRegisterClass *RC = (BitSize <= 32 ?
4801 &SystemZ::GR32BitRegClass :
4802 &SystemZ::GR64BitRegClass);
4803 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
4804 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
4806 // Get the right opcodes for the displacement.
4807 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
4808 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
4809 assert(LOpcode && CSOpcode && "Displacement out of range");
4811 // Create virtual registers for temporary results.
4812 unsigned OrigVal = MRI.createVirtualRegister(RC);
4813 unsigned OldVal = MRI.createVirtualRegister(RC);
4814 unsigned NewVal = MRI.createVirtualRegister(RC);
4815 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
4816 unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
4817 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
4819 // Insert 3 basic blocks for the loop.
4820 MachineBasicBlock *StartMBB = MBB;
4821 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
4822 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
4823 MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
4824 MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
4828 // %OrigVal = L Disp(%Base)
4829 // # fall through to LoopMMB
4831 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
4832 .addOperand(Base).addImm(Disp).addReg(0);
4833 MBB->addSuccessor(LoopMBB);
4836 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
4837 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
4838 // CompareOpcode %RotatedOldVal, %Src2
4839 // BRC KeepOldMask, UpdateMBB
4841 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
4842 .addReg(OrigVal).addMBB(StartMBB)
4843 .addReg(Dest).addMBB(UpdateMBB);
4845 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
4846 .addReg(OldVal).addReg(BitShift).addImm(0);
4847 BuildMI(MBB, DL, TII->get(CompareOpcode))
4848 .addReg(RotatedOldVal).addReg(Src2);
4849 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4850 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
4851 MBB->addSuccessor(UpdateMBB);
4852 MBB->addSuccessor(UseAltMBB);
4855 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
4856 // # fall through to UpdateMMB
4859 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
4860 .addReg(RotatedOldVal).addReg(Src2)
4861 .addImm(32).addImm(31 + BitSize).addImm(0);
4862 MBB->addSuccessor(UpdateMBB);
4865 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
4866 // [ %RotatedAltVal, UseAltMBB ]
4867 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
4868 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
4870 // # fall through to DoneMMB
4872 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
4873 .addReg(RotatedOldVal).addMBB(LoopMBB)
4874 .addReg(RotatedAltVal).addMBB(UseAltMBB);
4876 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
4877 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
4878 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
4879 .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
4880 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4881 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
4882 MBB->addSuccessor(LoopMBB);
4883 MBB->addSuccessor(DoneMBB);
4885 MI->eraseFromParent();
4889 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
4892 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
4893 MachineBasicBlock *MBB) const {
4894 MachineFunction &MF = *MBB->getParent();
4895 const SystemZInstrInfo *TII =
4896 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4897 MachineRegisterInfo &MRI = MF.getRegInfo();
4899 // Extract the operands. Base can be a register or a frame index.
4900 unsigned Dest = MI->getOperand(0).getReg();
4901 MachineOperand Base = earlyUseOperand(MI->getOperand(1));
4902 int64_t Disp = MI->getOperand(2).getImm();
4903 unsigned OrigCmpVal = MI->getOperand(3).getReg();
4904 unsigned OrigSwapVal = MI->getOperand(4).getReg();
4905 unsigned BitShift = MI->getOperand(5).getReg();
4906 unsigned NegBitShift = MI->getOperand(6).getReg();
4907 int64_t BitSize = MI->getOperand(7).getImm();
4908 DebugLoc DL = MI->getDebugLoc();
4910 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
4912 // Get the right opcodes for the displacement.
4913 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
4914 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
4915 assert(LOpcode && CSOpcode && "Displacement out of range");
4917 // Create virtual registers for temporary results.
4918 unsigned OrigOldVal = MRI.createVirtualRegister(RC);
4919 unsigned OldVal = MRI.createVirtualRegister(RC);
4920 unsigned CmpVal = MRI.createVirtualRegister(RC);
4921 unsigned SwapVal = MRI.createVirtualRegister(RC);
4922 unsigned StoreVal = MRI.createVirtualRegister(RC);
4923 unsigned RetryOldVal = MRI.createVirtualRegister(RC);
4924 unsigned RetryCmpVal = MRI.createVirtualRegister(RC);
4925 unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
4927 // Insert 2 basic blocks for the loop.
4928 MachineBasicBlock *StartMBB = MBB;
4929 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
4930 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
4931 MachineBasicBlock *SetMBB = emitBlockAfter(LoopMBB);
4935 // %OrigOldVal = L Disp(%Base)
4936 // # fall through to LoopMMB
4938 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
4939 .addOperand(Base).addImm(Disp).addReg(0);
4940 MBB->addSuccessor(LoopMBB);
4943 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
4944 // %CmpVal = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
4945 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
4946 // %Dest = RLL %OldVal, BitSize(%BitShift)
4947 // ^^ The low BitSize bits contain the field
4949 // %RetryCmpVal = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
4950 // ^^ Replace the upper 32-BitSize bits of the
4951 // comparison value with those that we loaded,
4952 // so that we can use a full word comparison.
4953 // CR %Dest, %RetryCmpVal
4955 // # Fall through to SetMBB
4957 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
4958 .addReg(OrigOldVal).addMBB(StartMBB)
4959 .addReg(RetryOldVal).addMBB(SetMBB);
4960 BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
4961 .addReg(OrigCmpVal).addMBB(StartMBB)
4962 .addReg(RetryCmpVal).addMBB(SetMBB);
4963 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
4964 .addReg(OrigSwapVal).addMBB(StartMBB)
4965 .addReg(RetrySwapVal).addMBB(SetMBB);
4966 BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
4967 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
4968 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
4969 .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
4970 BuildMI(MBB, DL, TII->get(SystemZ::CR))
4971 .addReg(Dest).addReg(RetryCmpVal);
4972 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4973 .addImm(SystemZ::CCMASK_ICMP)
4974 .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
4975 MBB->addSuccessor(DoneMBB);
4976 MBB->addSuccessor(SetMBB);
4979 // %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
4980 // ^^ Replace the upper 32-BitSize bits of the new
4981 // value with those that we loaded.
4982 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
4983 // ^^ Rotate the new field to its proper position.
4984 // %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
4986 // # fall through to ExitMMB
4988 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
4989 .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
4990 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
4991 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
4992 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
4993 .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
4994 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4995 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
4996 MBB->addSuccessor(LoopMBB);
4997 MBB->addSuccessor(DoneMBB);
4999 MI->eraseFromParent();
5003 // Emit an extension from a GR32 or GR64 to a GR128. ClearEven is true
5004 // if the high register of the GR128 value must be cleared or false if
5005 // it's "don't care". SubReg is subreg_l32 when extending a GR32
5006 // and subreg_l64 when extending a GR64.
5008 SystemZTargetLowering::emitExt128(MachineInstr *MI,
5009 MachineBasicBlock *MBB,
5010 bool ClearEven, unsigned SubReg) const {
5011 MachineFunction &MF = *MBB->getParent();
5012 const SystemZInstrInfo *TII =
5013 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5014 MachineRegisterInfo &MRI = MF.getRegInfo();
5015 DebugLoc DL = MI->getDebugLoc();
5017 unsigned Dest = MI->getOperand(0).getReg();
5018 unsigned Src = MI->getOperand(1).getReg();
5019 unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5021 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
5023 unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5024 unsigned Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
5026 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
5028 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
5029 .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
5032 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
5033 .addReg(In128).addReg(Src).addImm(SubReg);
5035 MI->eraseFromParent();
5040 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
5041 MachineBasicBlock *MBB,
5042 unsigned Opcode) const {
5043 MachineFunction &MF = *MBB->getParent();
5044 const SystemZInstrInfo *TII =
5045 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5046 MachineRegisterInfo &MRI = MF.getRegInfo();
5047 DebugLoc DL = MI->getDebugLoc();
5049 MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
5050 uint64_t DestDisp = MI->getOperand(1).getImm();
5051 MachineOperand SrcBase = earlyUseOperand(MI->getOperand(2));
5052 uint64_t SrcDisp = MI->getOperand(3).getImm();
5053 uint64_t Length = MI->getOperand(4).getImm();
5055 // When generating more than one CLC, all but the last will need to
5056 // branch to the end when a difference is found.
5057 MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
5058 splitBlockAfter(MI, MBB) : nullptr);
5060 // Check for the loop form, in which operand 5 is the trip count.
5061 if (MI->getNumExplicitOperands() > 5) {
5062 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
5064 uint64_t StartCountReg = MI->getOperand(5).getReg();
5065 uint64_t StartSrcReg = forceReg(MI, SrcBase, TII);
5066 uint64_t StartDestReg = (HaveSingleBase ? StartSrcReg :
5067 forceReg(MI, DestBase, TII));
5069 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
5070 uint64_t ThisSrcReg = MRI.createVirtualRegister(RC);
5071 uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
5072 MRI.createVirtualRegister(RC));
5073 uint64_t NextSrcReg = MRI.createVirtualRegister(RC);
5074 uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
5075 MRI.createVirtualRegister(RC));
5077 RC = &SystemZ::GR64BitRegClass;
5078 uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
5079 uint64_t NextCountReg = MRI.createVirtualRegister(RC);
5081 MachineBasicBlock *StartMBB = MBB;
5082 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5083 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5084 MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
5087 // # fall through to LoopMMB
5088 MBB->addSuccessor(LoopMBB);
5091 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
5092 // [ %NextDestReg, NextMBB ]
5093 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
5094 // [ %NextSrcReg, NextMBB ]
5095 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
5096 // [ %NextCountReg, NextMBB ]
5097 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
5098 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
5101 // The prefetch is used only for MVC. The JLH is used only for CLC.
5104 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
5105 .addReg(StartDestReg).addMBB(StartMBB)
5106 .addReg(NextDestReg).addMBB(NextMBB);
5107 if (!HaveSingleBase)
5108 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
5109 .addReg(StartSrcReg).addMBB(StartMBB)
5110 .addReg(NextSrcReg).addMBB(NextMBB);
5111 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
5112 .addReg(StartCountReg).addMBB(StartMBB)
5113 .addReg(NextCountReg).addMBB(NextMBB);
5114 if (Opcode == SystemZ::MVC)
5115 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
5116 .addImm(SystemZ::PFD_WRITE)
5117 .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
5118 BuildMI(MBB, DL, TII->get(Opcode))
5119 .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
5120 .addReg(ThisSrcReg).addImm(SrcDisp);
5122 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5123 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5125 MBB->addSuccessor(EndMBB);
5126 MBB->addSuccessor(NextMBB);
5130 // %NextDestReg = LA 256(%ThisDestReg)
5131 // %NextSrcReg = LA 256(%ThisSrcReg)
5132 // %NextCountReg = AGHI %ThisCountReg, -1
5133 // CGHI %NextCountReg, 0
5135 // # fall through to DoneMMB
5137 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
5140 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
5141 .addReg(ThisDestReg).addImm(256).addReg(0);
5142 if (!HaveSingleBase)
5143 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
5144 .addReg(ThisSrcReg).addImm(256).addReg(0);
5145 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
5146 .addReg(ThisCountReg).addImm(-1);
5147 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
5148 .addReg(NextCountReg).addImm(0);
5149 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5150 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5152 MBB->addSuccessor(LoopMBB);
5153 MBB->addSuccessor(DoneMBB);
5155 DestBase = MachineOperand::CreateReg(NextDestReg, false);
5156 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
5160 // Handle any remaining bytes with straight-line code.
5161 while (Length > 0) {
5162 uint64_t ThisLength = std::min(Length, uint64_t(256));
5163 // The previous iteration might have created out-of-range displacements.
5164 // Apply them using LAY if so.
5165 if (!isUInt<12>(DestDisp)) {
5166 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5167 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5168 .addOperand(DestBase).addImm(DestDisp).addReg(0);
5169 DestBase = MachineOperand::CreateReg(Reg, false);
5172 if (!isUInt<12>(SrcDisp)) {
5173 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5174 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5175 .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
5176 SrcBase = MachineOperand::CreateReg(Reg, false);
5179 BuildMI(*MBB, MI, DL, TII->get(Opcode))
5180 .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
5181 .addOperand(SrcBase).addImm(SrcDisp);
5182 DestDisp += ThisLength;
5183 SrcDisp += ThisLength;
5184 Length -= ThisLength;
5185 // If there's another CLC to go, branch to the end if a difference
5187 if (EndMBB && Length > 0) {
5188 MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
5189 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5190 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5192 MBB->addSuccessor(EndMBB);
5193 MBB->addSuccessor(NextMBB);
5198 MBB->addSuccessor(EndMBB);
5200 MBB->addLiveIn(SystemZ::CC);
5203 MI->eraseFromParent();
5207 // Decompose string pseudo-instruction MI into a loop that continually performs
5208 // Opcode until CC != 3.
5210 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
5211 MachineBasicBlock *MBB,
5212 unsigned Opcode) const {
5213 MachineFunction &MF = *MBB->getParent();
5214 const SystemZInstrInfo *TII =
5215 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5216 MachineRegisterInfo &MRI = MF.getRegInfo();
5217 DebugLoc DL = MI->getDebugLoc();
5219 uint64_t End1Reg = MI->getOperand(0).getReg();
5220 uint64_t Start1Reg = MI->getOperand(1).getReg();
5221 uint64_t Start2Reg = MI->getOperand(2).getReg();
5222 uint64_t CharReg = MI->getOperand(3).getReg();
5224 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
5225 uint64_t This1Reg = MRI.createVirtualRegister(RC);
5226 uint64_t This2Reg = MRI.createVirtualRegister(RC);
5227 uint64_t End2Reg = MRI.createVirtualRegister(RC);
5229 MachineBasicBlock *StartMBB = MBB;
5230 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5231 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5234 // # fall through to LoopMMB
5235 MBB->addSuccessor(LoopMBB);
5238 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
5239 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
5241 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
5243 // # fall through to DoneMMB
5245 // The load of R0L can be hoisted by post-RA LICM.
5248 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
5249 .addReg(Start1Reg).addMBB(StartMBB)
5250 .addReg(End1Reg).addMBB(LoopMBB);
5251 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
5252 .addReg(Start2Reg).addMBB(StartMBB)
5253 .addReg(End2Reg).addMBB(LoopMBB);
5254 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
5255 BuildMI(MBB, DL, TII->get(Opcode))
5256 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
5257 .addReg(This1Reg).addReg(This2Reg);
5258 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5259 .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
5260 MBB->addSuccessor(LoopMBB);
5261 MBB->addSuccessor(DoneMBB);
5263 DoneMBB->addLiveIn(SystemZ::CC);
5265 MI->eraseFromParent();
5269 // Update TBEGIN instruction with final opcode and register clobbers.
5271 SystemZTargetLowering::emitTransactionBegin(MachineInstr *MI,
5272 MachineBasicBlock *MBB,
5274 bool NoFloat) const {
5275 MachineFunction &MF = *MBB->getParent();
5276 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
5277 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
5280 MI->setDesc(TII->get(Opcode));
5282 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
5283 // Make sure to add the corresponding GRSM bits if they are missing.
5284 uint64_t Control = MI->getOperand(2).getImm();
5285 static const unsigned GPRControlBit[16] = {
5286 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
5287 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
5289 Control |= GPRControlBit[15];
5291 Control |= GPRControlBit[11];
5292 MI->getOperand(2).setImm(Control);
5294 // Add GPR clobbers.
5295 for (int I = 0; I < 16; I++) {
5296 if ((Control & GPRControlBit[I]) == 0) {
5297 unsigned Reg = SystemZMC::GR64Regs[I];
5298 MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5302 // Add FPR/VR clobbers.
5303 if (!NoFloat && (Control & 4) != 0) {
5304 if (Subtarget.hasVector()) {
5305 for (int I = 0; I < 32; I++) {
5306 unsigned Reg = SystemZMC::VR128Regs[I];
5307 MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5310 for (int I = 0; I < 16; I++) {
5311 unsigned Reg = SystemZMC::FP64Regs[I];
5312 MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5320 MachineBasicBlock *SystemZTargetLowering::
5321 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
5322 switch (MI->getOpcode()) {
5323 case SystemZ::Select32Mux:
5324 case SystemZ::Select32:
5325 case SystemZ::SelectF32:
5326 case SystemZ::Select64:
5327 case SystemZ::SelectF64:
5328 case SystemZ::SelectF128:
5329 return emitSelect(MI, MBB);
5331 case SystemZ::CondStore8Mux:
5332 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
5333 case SystemZ::CondStore8MuxInv:
5334 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
5335 case SystemZ::CondStore16Mux:
5336 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
5337 case SystemZ::CondStore16MuxInv:
5338 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
5339 case SystemZ::CondStore8:
5340 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
5341 case SystemZ::CondStore8Inv:
5342 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
5343 case SystemZ::CondStore16:
5344 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
5345 case SystemZ::CondStore16Inv:
5346 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
5347 case SystemZ::CondStore32:
5348 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
5349 case SystemZ::CondStore32Inv:
5350 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
5351 case SystemZ::CondStore64:
5352 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
5353 case SystemZ::CondStore64Inv:
5354 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
5355 case SystemZ::CondStoreF32:
5356 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
5357 case SystemZ::CondStoreF32Inv:
5358 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
5359 case SystemZ::CondStoreF64:
5360 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
5361 case SystemZ::CondStoreF64Inv:
5362 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
5364 case SystemZ::AEXT128_64:
5365 return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
5366 case SystemZ::ZEXT128_32:
5367 return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
5368 case SystemZ::ZEXT128_64:
5369 return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
5371 case SystemZ::ATOMIC_SWAPW:
5372 return emitAtomicLoadBinary(MI, MBB, 0, 0);
5373 case SystemZ::ATOMIC_SWAP_32:
5374 return emitAtomicLoadBinary(MI, MBB, 0, 32);
5375 case SystemZ::ATOMIC_SWAP_64:
5376 return emitAtomicLoadBinary(MI, MBB, 0, 64);
5378 case SystemZ::ATOMIC_LOADW_AR:
5379 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
5380 case SystemZ::ATOMIC_LOADW_AFI:
5381 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
5382 case SystemZ::ATOMIC_LOAD_AR:
5383 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
5384 case SystemZ::ATOMIC_LOAD_AHI:
5385 return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
5386 case SystemZ::ATOMIC_LOAD_AFI:
5387 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
5388 case SystemZ::ATOMIC_LOAD_AGR:
5389 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
5390 case SystemZ::ATOMIC_LOAD_AGHI:
5391 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
5392 case SystemZ::ATOMIC_LOAD_AGFI:
5393 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
5395 case SystemZ::ATOMIC_LOADW_SR:
5396 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
5397 case SystemZ::ATOMIC_LOAD_SR:
5398 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
5399 case SystemZ::ATOMIC_LOAD_SGR:
5400 return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
5402 case SystemZ::ATOMIC_LOADW_NR:
5403 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
5404 case SystemZ::ATOMIC_LOADW_NILH:
5405 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
5406 case SystemZ::ATOMIC_LOAD_NR:
5407 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
5408 case SystemZ::ATOMIC_LOAD_NILL:
5409 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
5410 case SystemZ::ATOMIC_LOAD_NILH:
5411 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
5412 case SystemZ::ATOMIC_LOAD_NILF:
5413 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
5414 case SystemZ::ATOMIC_LOAD_NGR:
5415 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
5416 case SystemZ::ATOMIC_LOAD_NILL64:
5417 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
5418 case SystemZ::ATOMIC_LOAD_NILH64:
5419 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
5420 case SystemZ::ATOMIC_LOAD_NIHL64:
5421 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
5422 case SystemZ::ATOMIC_LOAD_NIHH64:
5423 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
5424 case SystemZ::ATOMIC_LOAD_NILF64:
5425 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
5426 case SystemZ::ATOMIC_LOAD_NIHF64:
5427 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
5429 case SystemZ::ATOMIC_LOADW_OR:
5430 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
5431 case SystemZ::ATOMIC_LOADW_OILH:
5432 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
5433 case SystemZ::ATOMIC_LOAD_OR:
5434 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
5435 case SystemZ::ATOMIC_LOAD_OILL:
5436 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
5437 case SystemZ::ATOMIC_LOAD_OILH:
5438 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
5439 case SystemZ::ATOMIC_LOAD_OILF:
5440 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
5441 case SystemZ::ATOMIC_LOAD_OGR:
5442 return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
5443 case SystemZ::ATOMIC_LOAD_OILL64:
5444 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
5445 case SystemZ::ATOMIC_LOAD_OILH64:
5446 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
5447 case SystemZ::ATOMIC_LOAD_OIHL64:
5448 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
5449 case SystemZ::ATOMIC_LOAD_OIHH64:
5450 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
5451 case SystemZ::ATOMIC_LOAD_OILF64:
5452 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
5453 case SystemZ::ATOMIC_LOAD_OIHF64:
5454 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
5456 case SystemZ::ATOMIC_LOADW_XR:
5457 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
5458 case SystemZ::ATOMIC_LOADW_XILF:
5459 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
5460 case SystemZ::ATOMIC_LOAD_XR:
5461 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
5462 case SystemZ::ATOMIC_LOAD_XILF:
5463 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
5464 case SystemZ::ATOMIC_LOAD_XGR:
5465 return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
5466 case SystemZ::ATOMIC_LOAD_XILF64:
5467 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
5468 case SystemZ::ATOMIC_LOAD_XIHF64:
5469 return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
5471 case SystemZ::ATOMIC_LOADW_NRi:
5472 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
5473 case SystemZ::ATOMIC_LOADW_NILHi:
5474 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
5475 case SystemZ::ATOMIC_LOAD_NRi:
5476 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
5477 case SystemZ::ATOMIC_LOAD_NILLi:
5478 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
5479 case SystemZ::ATOMIC_LOAD_NILHi:
5480 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
5481 case SystemZ::ATOMIC_LOAD_NILFi:
5482 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
5483 case SystemZ::ATOMIC_LOAD_NGRi:
5484 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
5485 case SystemZ::ATOMIC_LOAD_NILL64i:
5486 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
5487 case SystemZ::ATOMIC_LOAD_NILH64i:
5488 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
5489 case SystemZ::ATOMIC_LOAD_NIHL64i:
5490 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
5491 case SystemZ::ATOMIC_LOAD_NIHH64i:
5492 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
5493 case SystemZ::ATOMIC_LOAD_NILF64i:
5494 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
5495 case SystemZ::ATOMIC_LOAD_NIHF64i:
5496 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
5498 case SystemZ::ATOMIC_LOADW_MIN:
5499 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5500 SystemZ::CCMASK_CMP_LE, 0);
5501 case SystemZ::ATOMIC_LOAD_MIN_32:
5502 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5503 SystemZ::CCMASK_CMP_LE, 32);
5504 case SystemZ::ATOMIC_LOAD_MIN_64:
5505 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
5506 SystemZ::CCMASK_CMP_LE, 64);
5508 case SystemZ::ATOMIC_LOADW_MAX:
5509 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5510 SystemZ::CCMASK_CMP_GE, 0);
5511 case SystemZ::ATOMIC_LOAD_MAX_32:
5512 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5513 SystemZ::CCMASK_CMP_GE, 32);
5514 case SystemZ::ATOMIC_LOAD_MAX_64:
5515 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
5516 SystemZ::CCMASK_CMP_GE, 64);
5518 case SystemZ::ATOMIC_LOADW_UMIN:
5519 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5520 SystemZ::CCMASK_CMP_LE, 0);
5521 case SystemZ::ATOMIC_LOAD_UMIN_32:
5522 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5523 SystemZ::CCMASK_CMP_LE, 32);
5524 case SystemZ::ATOMIC_LOAD_UMIN_64:
5525 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
5526 SystemZ::CCMASK_CMP_LE, 64);
5528 case SystemZ::ATOMIC_LOADW_UMAX:
5529 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5530 SystemZ::CCMASK_CMP_GE, 0);
5531 case SystemZ::ATOMIC_LOAD_UMAX_32:
5532 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5533 SystemZ::CCMASK_CMP_GE, 32);
5534 case SystemZ::ATOMIC_LOAD_UMAX_64:
5535 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
5536 SystemZ::CCMASK_CMP_GE, 64);
5538 case SystemZ::ATOMIC_CMP_SWAPW:
5539 return emitAtomicCmpSwapW(MI, MBB);
5540 case SystemZ::MVCSequence:
5541 case SystemZ::MVCLoop:
5542 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
5543 case SystemZ::NCSequence:
5544 case SystemZ::NCLoop:
5545 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
5546 case SystemZ::OCSequence:
5547 case SystemZ::OCLoop:
5548 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
5549 case SystemZ::XCSequence:
5550 case SystemZ::XCLoop:
5551 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
5552 case SystemZ::CLCSequence:
5553 case SystemZ::CLCLoop:
5554 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
5555 case SystemZ::CLSTLoop:
5556 return emitStringWrapper(MI, MBB, SystemZ::CLST);
5557 case SystemZ::MVSTLoop:
5558 return emitStringWrapper(MI, MBB, SystemZ::MVST);
5559 case SystemZ::SRSTLoop:
5560 return emitStringWrapper(MI, MBB, SystemZ::SRST);
5561 case SystemZ::TBEGIN:
5562 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
5563 case SystemZ::TBEGIN_nofloat:
5564 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
5565 case SystemZ::TBEGINC:
5566 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
5568 llvm_unreachable("Unexpected instr type to insert");