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 // We do not yet support 128-bit single-element vector types. If the user
781 // attempts to use such types as function argument or return type, prefer
782 // to error out instead of emitting code violating the ABI.
783 static void VerifyVectorType(MVT VT, EVT ArgVT) {
784 if (ArgVT.isVector() && !VT.isVector())
785 report_fatal_error("Unsupported vector argument or return type");
788 static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) {
789 for (unsigned i = 0; i < Ins.size(); ++i)
790 VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
793 static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) {
794 for (unsigned i = 0; i < Outs.size(); ++i)
795 VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
798 // Value is a value that has been passed to us in the location described by VA
799 // (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
800 // any loads onto Chain.
801 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
802 CCValAssign &VA, SDValue Chain,
804 // If the argument has been promoted from a smaller type, insert an
805 // assertion to capture this.
806 if (VA.getLocInfo() == CCValAssign::SExt)
807 Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
808 DAG.getValueType(VA.getValVT()));
809 else if (VA.getLocInfo() == CCValAssign::ZExt)
810 Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
811 DAG.getValueType(VA.getValVT()));
814 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
815 else if (VA.getLocInfo() == CCValAssign::Indirect)
816 Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
817 MachinePointerInfo(), false, false, false, 0);
818 else if (VA.getLocInfo() == CCValAssign::BCvt) {
819 // If this is a short vector argument loaded from the stack,
820 // extend from i64 to full vector size and then bitcast.
821 assert(VA.getLocVT() == MVT::i64);
822 assert(VA.getValVT().isVector());
823 Value = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i64,
824 Value, DAG.getUNDEF(MVT::i64));
825 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
827 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
831 // Value is a value of type VA.getValVT() that we need to copy into
832 // the location described by VA. Return a copy of Value converted to
833 // VA.getValVT(). The caller is responsible for handling indirect values.
834 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
835 CCValAssign &VA, SDValue Value) {
836 switch (VA.getLocInfo()) {
837 case CCValAssign::SExt:
838 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
839 case CCValAssign::ZExt:
840 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
841 case CCValAssign::AExt:
842 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
843 case CCValAssign::BCvt:
844 // If this is a short vector argument to be stored to the stack,
845 // bitcast to v2i64 and then extract first element.
846 assert(VA.getLocVT() == MVT::i64);
847 assert(VA.getValVT().isVector());
848 Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
849 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
850 DAG.getConstant(0, DL, MVT::i32));
851 case CCValAssign::Full:
854 llvm_unreachable("Unhandled getLocInfo()");
858 SDValue SystemZTargetLowering::
859 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
860 const SmallVectorImpl<ISD::InputArg> &Ins,
861 SDLoc DL, SelectionDAG &DAG,
862 SmallVectorImpl<SDValue> &InVals) const {
863 MachineFunction &MF = DAG.getMachineFunction();
864 MachineFrameInfo *MFI = MF.getFrameInfo();
865 MachineRegisterInfo &MRI = MF.getRegInfo();
866 SystemZMachineFunctionInfo *FuncInfo =
867 MF.getInfo<SystemZMachineFunctionInfo>();
869 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
871 // Detect unsupported vector argument types.
872 if (Subtarget.hasVector())
873 VerifyVectorTypes(Ins);
875 // Assign locations to all of the incoming arguments.
876 SmallVector<CCValAssign, 16> ArgLocs;
877 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
878 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
880 unsigned NumFixedGPRs = 0;
881 unsigned NumFixedFPRs = 0;
882 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
884 CCValAssign &VA = ArgLocs[I];
885 EVT LocVT = VA.getLocVT();
887 // Arguments passed in registers
888 const TargetRegisterClass *RC;
889 switch (LocVT.getSimpleVT().SimpleTy) {
891 // Integers smaller than i64 should be promoted to i64.
892 llvm_unreachable("Unexpected argument type");
895 RC = &SystemZ::GR32BitRegClass;
899 RC = &SystemZ::GR64BitRegClass;
903 RC = &SystemZ::FP32BitRegClass;
907 RC = &SystemZ::FP64BitRegClass;
915 RC = &SystemZ::VR128BitRegClass;
919 unsigned VReg = MRI.createVirtualRegister(RC);
920 MRI.addLiveIn(VA.getLocReg(), VReg);
921 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
923 assert(VA.isMemLoc() && "Argument not register or memory");
925 // Create the frame index object for this incoming parameter.
926 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
927 VA.getLocMemOffset(), true);
929 // Create the SelectionDAG nodes corresponding to a load
930 // from this parameter. Unpromoted ints and floats are
931 // passed as right-justified 8-byte values.
932 EVT PtrVT = getPointerTy();
933 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
934 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
935 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
936 DAG.getIntPtrConstant(4, DL));
937 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
938 MachinePointerInfo::getFixedStack(FI),
939 false, false, false, 0);
942 // Convert the value of the argument register into the value that's
944 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
948 // Save the number of non-varargs registers for later use by va_start, etc.
949 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
950 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
952 // Likewise the address (in the form of a frame index) of where the
953 // first stack vararg would be. The 1-byte size here is arbitrary.
954 int64_t StackSize = CCInfo.getNextStackOffset();
955 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
957 // ...and a similar frame index for the caller-allocated save area
958 // that will be used to store the incoming registers.
959 int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
960 unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
961 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
963 // Store the FPR varargs in the reserved frame slots. (We store the
964 // GPRs as part of the prologue.)
965 if (NumFixedFPRs < SystemZ::NumArgFPRs) {
966 SDValue MemOps[SystemZ::NumArgFPRs];
967 for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
968 unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
969 int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
970 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
971 unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
972 &SystemZ::FP64BitRegClass);
973 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
974 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
975 MachinePointerInfo::getFixedStack(FI),
979 // Join the stores, which are independent of one another.
980 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
981 makeArrayRef(&MemOps[NumFixedFPRs],
982 SystemZ::NumArgFPRs-NumFixedFPRs));
989 static bool canUseSiblingCall(const CCState &ArgCCInfo,
990 SmallVectorImpl<CCValAssign> &ArgLocs) {
991 // Punt if there are any indirect or stack arguments, or if the call
992 // needs the call-saved argument register R6.
993 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
994 CCValAssign &VA = ArgLocs[I];
995 if (VA.getLocInfo() == CCValAssign::Indirect)
999 unsigned Reg = VA.getLocReg();
1000 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1007 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
1008 SmallVectorImpl<SDValue> &InVals) const {
1009 SelectionDAG &DAG = CLI.DAG;
1011 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1012 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1013 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1014 SDValue Chain = CLI.Chain;
1015 SDValue Callee = CLI.Callee;
1016 bool &IsTailCall = CLI.IsTailCall;
1017 CallingConv::ID CallConv = CLI.CallConv;
1018 bool IsVarArg = CLI.IsVarArg;
1019 MachineFunction &MF = DAG.getMachineFunction();
1020 EVT PtrVT = getPointerTy();
1022 // Detect unsupported vector argument and return types.
1023 if (Subtarget.hasVector()) {
1024 VerifyVectorTypes(Outs);
1025 VerifyVectorTypes(Ins);
1028 // Analyze the operands of the call, assigning locations to each operand.
1029 SmallVector<CCValAssign, 16> ArgLocs;
1030 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1031 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1033 // We don't support GuaranteedTailCallOpt, only automatically-detected
1035 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs))
1038 // Get a count of how many bytes are to be pushed on the stack.
1039 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1041 // Mark the start of the call.
1043 Chain = DAG.getCALLSEQ_START(Chain,
1044 DAG.getConstant(NumBytes, DL, PtrVT, true),
1047 // Copy argument values to their designated locations.
1048 SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1049 SmallVector<SDValue, 8> MemOpChains;
1051 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1052 CCValAssign &VA = ArgLocs[I];
1053 SDValue ArgValue = OutVals[I];
1055 if (VA.getLocInfo() == CCValAssign::Indirect) {
1056 // Store the argument in a stack slot and pass its address.
1057 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1058 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1059 MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1060 MachinePointerInfo::getFixedStack(FI),
1062 ArgValue = SpillSlot;
1064 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1067 // Queue up the argument copies and emit them at the end.
1068 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1070 assert(VA.isMemLoc() && "Argument not register or memory");
1072 // Work out the address of the stack slot. Unpromoted ints and
1073 // floats are passed as right-justified 8-byte values.
1074 if (!StackPtr.getNode())
1075 StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1076 unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1077 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1079 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1080 DAG.getIntPtrConstant(Offset, DL));
1083 MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
1084 MachinePointerInfo(),
1089 // Join the stores, which are independent of one another.
1090 if (!MemOpChains.empty())
1091 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1093 // Accept direct calls by converting symbolic call addresses to the
1094 // associated Target* opcodes. Force %r1 to be used for indirect
1097 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1098 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1099 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1100 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1101 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1102 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1103 } else if (IsTailCall) {
1104 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1105 Glue = Chain.getValue(1);
1106 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1109 // Build a sequence of copy-to-reg nodes, chained and glued together.
1110 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1111 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1112 RegsToPass[I].second, Glue);
1113 Glue = Chain.getValue(1);
1116 // The first call operand is the chain and the second is the target address.
1117 SmallVector<SDValue, 8> Ops;
1118 Ops.push_back(Chain);
1119 Ops.push_back(Callee);
1121 // Add argument registers to the end of the list so that they are
1122 // known live into the call.
1123 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1124 Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1125 RegsToPass[I].second.getValueType()));
1127 // Add a register mask operand representing the call-preserved registers.
1128 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1129 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1130 assert(Mask && "Missing call preserved mask for calling convention");
1131 Ops.push_back(DAG.getRegisterMask(Mask));
1133 // Glue the call to the argument copies, if any.
1135 Ops.push_back(Glue);
1138 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1140 return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1141 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1142 Glue = Chain.getValue(1);
1144 // Mark the end of the call, which is glued to the call itself.
1145 Chain = DAG.getCALLSEQ_END(Chain,
1146 DAG.getConstant(NumBytes, DL, PtrVT, true),
1147 DAG.getConstant(0, DL, PtrVT, true),
1149 Glue = Chain.getValue(1);
1151 // Assign locations to each value returned by this call.
1152 SmallVector<CCValAssign, 16> RetLocs;
1153 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1154 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1156 // Copy all of the result registers out of their specified physreg.
1157 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1158 CCValAssign &VA = RetLocs[I];
1160 // Copy the value out, gluing the copy to the end of the call sequence.
1161 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1162 VA.getLocVT(), Glue);
1163 Chain = RetValue.getValue(1);
1164 Glue = RetValue.getValue(2);
1166 // Convert the value of the return register into the value that's
1168 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1175 SystemZTargetLowering::LowerReturn(SDValue Chain,
1176 CallingConv::ID CallConv, bool IsVarArg,
1177 const SmallVectorImpl<ISD::OutputArg> &Outs,
1178 const SmallVectorImpl<SDValue> &OutVals,
1179 SDLoc DL, SelectionDAG &DAG) const {
1180 MachineFunction &MF = DAG.getMachineFunction();
1182 // Detect unsupported vector return types.
1183 if (Subtarget.hasVector())
1184 VerifyVectorTypes(Outs);
1186 // Assign locations to each returned value.
1187 SmallVector<CCValAssign, 16> RetLocs;
1188 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1189 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1191 // Quick exit for void returns
1192 if (RetLocs.empty())
1193 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1195 // Copy the result values into the output registers.
1197 SmallVector<SDValue, 4> RetOps;
1198 RetOps.push_back(Chain);
1199 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1200 CCValAssign &VA = RetLocs[I];
1201 SDValue RetValue = OutVals[I];
1203 // Make the return register live on exit.
1204 assert(VA.isRegLoc() && "Can only return in registers!");
1206 // Promote the value as required.
1207 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1209 // Chain and glue the copies together.
1210 unsigned Reg = VA.getLocReg();
1211 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1212 Glue = Chain.getValue(1);
1213 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1216 // Update chain and glue.
1219 RetOps.push_back(Glue);
1221 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1224 SDValue SystemZTargetLowering::
1225 prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL, SelectionDAG &DAG) const {
1226 return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
1229 // Return true if Op is an intrinsic node with chain that returns the CC value
1230 // as its only (other) argument. Provide the associated SystemZISD opcode and
1231 // the mask of valid CC values if so.
1232 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1233 unsigned &CCValid) {
1234 unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1236 case Intrinsic::s390_tbegin:
1237 Opcode = SystemZISD::TBEGIN;
1238 CCValid = SystemZ::CCMASK_TBEGIN;
1241 case Intrinsic::s390_tbegin_nofloat:
1242 Opcode = SystemZISD::TBEGIN_NOFLOAT;
1243 CCValid = SystemZ::CCMASK_TBEGIN;
1246 case Intrinsic::s390_tend:
1247 Opcode = SystemZISD::TEND;
1248 CCValid = SystemZ::CCMASK_TEND;
1256 // Emit an intrinsic with chain with a glued value instead of its CC result.
1257 static SDValue emitIntrinsicWithChainAndGlue(SelectionDAG &DAG, SDValue Op,
1259 // Copy all operands except the intrinsic ID.
1260 unsigned NumOps = Op.getNumOperands();
1261 SmallVector<SDValue, 6> Ops;
1262 Ops.reserve(NumOps - 1);
1263 Ops.push_back(Op.getOperand(0));
1264 for (unsigned I = 2; I < NumOps; ++I)
1265 Ops.push_back(Op.getOperand(I));
1267 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1268 SDVTList RawVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1269 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1270 SDValue OldChain = SDValue(Op.getNode(), 1);
1271 SDValue NewChain = SDValue(Intr.getNode(), 0);
1272 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1276 // CC is a comparison that will be implemented using an integer or
1277 // floating-point comparison. Return the condition code mask for
1278 // a branch on true. In the integer case, CCMASK_CMP_UO is set for
1279 // unsigned comparisons and clear for signed ones. In the floating-point
1280 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1281 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1283 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1284 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1285 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1289 llvm_unreachable("Invalid integer condition!");
1298 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
1299 case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1304 // Return a sequence for getting a 1 from an IPM result when CC has a
1305 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1306 // The handling of CC values outside CCValid doesn't matter.
1307 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1308 // Deal with cases where the result can be taken directly from a bit
1309 // of the IPM result.
1310 if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1311 return IPMConversion(0, 0, SystemZ::IPM_CC);
1312 if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1313 return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1315 // Deal with cases where we can add a value to force the sign bit
1316 // to contain the right value. Putting the bit in 31 means we can
1317 // use SRL rather than RISBG(L), and also makes it easier to get a
1318 // 0/-1 value, so it has priority over the other tests below.
1320 // These sequences rely on the fact that the upper two bits of the
1321 // IPM result are zero.
1322 uint64_t TopBit = uint64_t(1) << 31;
1323 if (CCMask == (CCValid & SystemZ::CCMASK_0))
1324 return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1325 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1326 return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1327 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1329 | SystemZ::CCMASK_2)))
1330 return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1331 if (CCMask == (CCValid & SystemZ::CCMASK_3))
1332 return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1333 if (CCMask == (CCValid & (SystemZ::CCMASK_1
1335 | SystemZ::CCMASK_3)))
1336 return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1338 // Next try inverting the value and testing a bit. 0/1 could be
1339 // handled this way too, but we dealt with that case above.
1340 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1341 return IPMConversion(-1, 0, SystemZ::IPM_CC);
1343 // Handle cases where adding a value forces a non-sign bit to contain
1345 if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1346 return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1347 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1348 return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1350 // The remaining cases are 1, 2, 0/1/3 and 0/2/3. All these are
1351 // can be done by inverting the low CC bit and applying one of the
1352 // sign-based extractions above.
1353 if (CCMask == (CCValid & SystemZ::CCMASK_1))
1354 return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1355 if (CCMask == (CCValid & SystemZ::CCMASK_2))
1356 return IPMConversion(1 << SystemZ::IPM_CC,
1357 TopBit - (3 << SystemZ::IPM_CC), 31);
1358 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1360 | SystemZ::CCMASK_3)))
1361 return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1362 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1364 | SystemZ::CCMASK_3)))
1365 return IPMConversion(1 << SystemZ::IPM_CC,
1366 TopBit - (1 << SystemZ::IPM_CC), 31);
1368 llvm_unreachable("Unexpected CC combination");
1371 // If C can be converted to a comparison against zero, adjust the operands
1373 static void adjustZeroCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1374 if (C.ICmpType == SystemZICMP::UnsignedOnly)
1377 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1381 int64_t Value = ConstOp1->getSExtValue();
1382 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1383 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1384 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1385 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1386 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1387 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1391 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1392 // adjust the operands as necessary.
1393 static void adjustSubwordCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1394 // For us to make any changes, it must a comparison between a single-use
1395 // load and a constant.
1396 if (!C.Op0.hasOneUse() ||
1397 C.Op0.getOpcode() != ISD::LOAD ||
1398 C.Op1.getOpcode() != ISD::Constant)
1401 // We must have an 8- or 16-bit load.
1402 auto *Load = cast<LoadSDNode>(C.Op0);
1403 unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1404 if (NumBits != 8 && NumBits != 16)
1407 // The load must be an extending one and the constant must be within the
1408 // range of the unextended value.
1409 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1410 uint64_t Value = ConstOp1->getZExtValue();
1411 uint64_t Mask = (1 << NumBits) - 1;
1412 if (Load->getExtensionType() == ISD::SEXTLOAD) {
1413 // Make sure that ConstOp1 is in range of C.Op0.
1414 int64_t SignedValue = ConstOp1->getSExtValue();
1415 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1417 if (C.ICmpType != SystemZICMP::SignedOnly) {
1418 // Unsigned comparison between two sign-extended values is equivalent
1419 // to unsigned comparison between two zero-extended values.
1421 } else if (NumBits == 8) {
1422 // Try to treat the comparison as unsigned, so that we can use CLI.
1423 // Adjust CCMask and Value as necessary.
1424 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1425 // Test whether the high bit of the byte is set.
1426 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1427 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1428 // Test whether the high bit of the byte is clear.
1429 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1431 // No instruction exists for this combination.
1433 C.ICmpType = SystemZICMP::UnsignedOnly;
1435 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1438 assert(C.ICmpType == SystemZICMP::Any &&
1439 "Signedness shouldn't matter here.");
1443 // Make sure that the first operand is an i32 of the right extension type.
1444 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1447 if (C.Op0.getValueType() != MVT::i32 ||
1448 Load->getExtensionType() != ExtType)
1449 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
1450 Load->getChain(), Load->getBasePtr(),
1451 Load->getPointerInfo(), Load->getMemoryVT(),
1452 Load->isVolatile(), Load->isNonTemporal(),
1453 Load->isInvariant(), Load->getAlignment());
1455 // Make sure that the second operand is an i32 with the right value.
1456 if (C.Op1.getValueType() != MVT::i32 ||
1457 Value != ConstOp1->getZExtValue())
1458 C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
1461 // Return true if Op is either an unextended load, or a load suitable
1462 // for integer register-memory comparisons of type ICmpType.
1463 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1464 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1466 // There are no instructions to compare a register with a memory byte.
1467 if (Load->getMemoryVT() == MVT::i8)
1469 // Otherwise decide on extension type.
1470 switch (Load->getExtensionType()) {
1471 case ISD::NON_EXTLOAD:
1474 return ICmpType != SystemZICMP::UnsignedOnly;
1476 return ICmpType != SystemZICMP::SignedOnly;
1484 // Return true if it is better to swap the operands of C.
1485 static bool shouldSwapCmpOperands(const Comparison &C) {
1486 // Leave f128 comparisons alone, since they have no memory forms.
1487 if (C.Op0.getValueType() == MVT::f128)
1490 // Always keep a floating-point constant second, since comparisons with
1491 // zero can use LOAD TEST and comparisons with other constants make a
1492 // natural memory operand.
1493 if (isa<ConstantFPSDNode>(C.Op1))
1496 // Never swap comparisons with zero since there are many ways to optimize
1498 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1499 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1502 // Also keep natural memory operands second if the loaded value is
1503 // only used here. Several comparisons have memory forms.
1504 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1507 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1508 // In that case we generally prefer the memory to be second.
1509 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1510 // The only exceptions are when the second operand is a constant and
1511 // we can use things like CHHSI.
1514 // The unsigned memory-immediate instructions can handle 16-bit
1515 // unsigned integers.
1516 if (C.ICmpType != SystemZICMP::SignedOnly &&
1517 isUInt<16>(ConstOp1->getZExtValue()))
1519 // The signed memory-immediate instructions can handle 16-bit
1521 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1522 isInt<16>(ConstOp1->getSExtValue()))
1527 // Try to promote the use of CGFR and CLGFR.
1528 unsigned Opcode0 = C.Op0.getOpcode();
1529 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1531 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1533 if (C.ICmpType != SystemZICMP::SignedOnly &&
1534 Opcode0 == ISD::AND &&
1535 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1536 cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1542 // Return a version of comparison CC mask CCMask in which the LT and GT
1543 // actions are swapped.
1544 static unsigned reverseCCMask(unsigned CCMask) {
1545 return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1546 (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1547 (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1548 (CCMask & SystemZ::CCMASK_CMP_UO));
1551 // Check whether C tests for equality between X and Y and whether X - Y
1552 // or Y - X is also computed. In that case it's better to compare the
1553 // result of the subtraction against zero.
1554 static void adjustForSubtraction(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1555 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1556 C.CCMask == SystemZ::CCMASK_CMP_NE) {
1557 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1559 if (N->getOpcode() == ISD::SUB &&
1560 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1561 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1562 C.Op0 = SDValue(N, 0);
1563 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
1570 // Check whether C compares a floating-point value with zero and if that
1571 // floating-point value is also negated. In this case we can use the
1572 // negation to set CC, so avoiding separate LOAD AND TEST and
1573 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1574 static void adjustForFNeg(Comparison &C) {
1575 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1576 if (C1 && C1->isZero()) {
1577 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1579 if (N->getOpcode() == ISD::FNEG) {
1580 C.Op0 = SDValue(N, 0);
1581 C.CCMask = reverseCCMask(C.CCMask);
1588 // Check whether C compares (shl X, 32) with 0 and whether X is
1589 // also sign-extended. In that case it is better to test the result
1590 // of the sign extension using LTGFR.
1592 // This case is important because InstCombine transforms a comparison
1593 // with (sext (trunc X)) into a comparison with (shl X, 32).
1594 static void adjustForLTGFR(Comparison &C) {
1595 // Check for a comparison between (shl X, 32) and 0.
1596 if (C.Op0.getOpcode() == ISD::SHL &&
1597 C.Op0.getValueType() == MVT::i64 &&
1598 C.Op1.getOpcode() == ISD::Constant &&
1599 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1600 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
1601 if (C1 && C1->getZExtValue() == 32) {
1602 SDValue ShlOp0 = C.Op0.getOperand(0);
1603 // See whether X has any SIGN_EXTEND_INREG uses.
1604 for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
1606 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1607 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1608 C.Op0 = SDValue(N, 0);
1616 // If C compares the truncation of an extending load, try to compare
1617 // the untruncated value instead. This exposes more opportunities to
1619 static void adjustICmpTruncate(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1620 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
1621 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
1622 C.Op1.getOpcode() == ISD::Constant &&
1623 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1624 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
1625 if (L->getMemoryVT().getStoreSizeInBits()
1626 <= C.Op0.getValueType().getSizeInBits()) {
1627 unsigned Type = L->getExtensionType();
1628 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
1629 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
1630 C.Op0 = C.Op0.getOperand(0);
1631 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
1637 // Return true if shift operation N has an in-range constant shift value.
1638 // Store it in ShiftVal if so.
1639 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1640 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1644 uint64_t Amount = Shift->getZExtValue();
1645 if (Amount >= N.getValueType().getSizeInBits())
1652 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1653 // instruction and whether the CC value is descriptive enough to handle
1654 // a comparison of type Opcode between the AND result and CmpVal.
1655 // CCMask says which comparison result is being tested and BitSize is
1656 // the number of bits in the operands. If TEST UNDER MASK can be used,
1657 // return the corresponding CC mask, otherwise return 0.
1658 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1659 uint64_t Mask, uint64_t CmpVal,
1660 unsigned ICmpType) {
1661 assert(Mask != 0 && "ANDs with zero should have been removed by now");
1663 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1664 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1665 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1668 // Work out the masks for the lowest and highest bits.
1669 unsigned HighShift = 63 - countLeadingZeros(Mask);
1670 uint64_t High = uint64_t(1) << HighShift;
1671 uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1673 // Signed ordered comparisons are effectively unsigned if the sign
1675 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1677 // Check for equality comparisons with 0, or the equivalent.
1679 if (CCMask == SystemZ::CCMASK_CMP_EQ)
1680 return SystemZ::CCMASK_TM_ALL_0;
1681 if (CCMask == SystemZ::CCMASK_CMP_NE)
1682 return SystemZ::CCMASK_TM_SOME_1;
1684 if (EffectivelyUnsigned && CmpVal <= Low) {
1685 if (CCMask == SystemZ::CCMASK_CMP_LT)
1686 return SystemZ::CCMASK_TM_ALL_0;
1687 if (CCMask == SystemZ::CCMASK_CMP_GE)
1688 return SystemZ::CCMASK_TM_SOME_1;
1690 if (EffectivelyUnsigned && CmpVal < Low) {
1691 if (CCMask == SystemZ::CCMASK_CMP_LE)
1692 return SystemZ::CCMASK_TM_ALL_0;
1693 if (CCMask == SystemZ::CCMASK_CMP_GT)
1694 return SystemZ::CCMASK_TM_SOME_1;
1697 // Check for equality comparisons with the mask, or the equivalent.
1698 if (CmpVal == Mask) {
1699 if (CCMask == SystemZ::CCMASK_CMP_EQ)
1700 return SystemZ::CCMASK_TM_ALL_1;
1701 if (CCMask == SystemZ::CCMASK_CMP_NE)
1702 return SystemZ::CCMASK_TM_SOME_0;
1704 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1705 if (CCMask == SystemZ::CCMASK_CMP_GT)
1706 return SystemZ::CCMASK_TM_ALL_1;
1707 if (CCMask == SystemZ::CCMASK_CMP_LE)
1708 return SystemZ::CCMASK_TM_SOME_0;
1710 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1711 if (CCMask == SystemZ::CCMASK_CMP_GE)
1712 return SystemZ::CCMASK_TM_ALL_1;
1713 if (CCMask == SystemZ::CCMASK_CMP_LT)
1714 return SystemZ::CCMASK_TM_SOME_0;
1717 // Check for ordered comparisons with the top bit.
1718 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1719 if (CCMask == SystemZ::CCMASK_CMP_LE)
1720 return SystemZ::CCMASK_TM_MSB_0;
1721 if (CCMask == SystemZ::CCMASK_CMP_GT)
1722 return SystemZ::CCMASK_TM_MSB_1;
1724 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1725 if (CCMask == SystemZ::CCMASK_CMP_LT)
1726 return SystemZ::CCMASK_TM_MSB_0;
1727 if (CCMask == SystemZ::CCMASK_CMP_GE)
1728 return SystemZ::CCMASK_TM_MSB_1;
1731 // If there are just two bits, we can do equality checks for Low and High
1733 if (Mask == Low + High) {
1734 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1735 return SystemZ::CCMASK_TM_MIXED_MSB_0;
1736 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1737 return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1738 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1739 return SystemZ::CCMASK_TM_MIXED_MSB_1;
1740 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1741 return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
1744 // Looks like we've exhausted our options.
1748 // See whether C can be implemented as a TEST UNDER MASK instruction.
1749 // Update the arguments with the TM version if so.
1750 static void adjustForTestUnderMask(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1751 // Check that we have a comparison with a constant.
1752 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1755 uint64_t CmpVal = ConstOp1->getZExtValue();
1757 // Check whether the nonconstant input is an AND with a constant mask.
1760 ConstantSDNode *Mask = nullptr;
1761 if (C.Op0.getOpcode() == ISD::AND) {
1762 NewC.Op0 = C.Op0.getOperand(0);
1763 NewC.Op1 = C.Op0.getOperand(1);
1764 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
1767 MaskVal = Mask->getZExtValue();
1769 // There is no instruction to compare with a 64-bit immediate
1770 // so use TMHH instead if possible. We need an unsigned ordered
1771 // comparison with an i64 immediate.
1772 if (NewC.Op0.getValueType() != MVT::i64 ||
1773 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
1774 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
1775 NewC.ICmpType == SystemZICMP::SignedOnly)
1777 // Convert LE and GT comparisons into LT and GE.
1778 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
1779 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
1780 if (CmpVal == uint64_t(-1))
1783 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1785 // If the low N bits of Op1 are zero than the low N bits of Op0 can
1786 // be masked off without changing the result.
1787 MaskVal = -(CmpVal & -CmpVal);
1788 NewC.ICmpType = SystemZICMP::UnsignedOnly;
1793 // Check whether the combination of mask, comparison value and comparison
1794 // type are suitable.
1795 unsigned BitSize = NewC.Op0.getValueType().getSizeInBits();
1796 unsigned NewCCMask, ShiftVal;
1797 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
1798 NewC.Op0.getOpcode() == ISD::SHL &&
1799 isSimpleShift(NewC.Op0, ShiftVal) &&
1800 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
1801 MaskVal >> ShiftVal,
1803 SystemZICMP::Any))) {
1804 NewC.Op0 = NewC.Op0.getOperand(0);
1805 MaskVal >>= ShiftVal;
1806 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
1807 NewC.Op0.getOpcode() == ISD::SRL &&
1808 isSimpleShift(NewC.Op0, ShiftVal) &&
1809 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
1810 MaskVal << ShiftVal,
1812 SystemZICMP::UnsignedOnly))) {
1813 NewC.Op0 = NewC.Op0.getOperand(0);
1814 MaskVal <<= ShiftVal;
1816 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
1822 // Go ahead and make the change.
1823 C.Opcode = SystemZISD::TM;
1825 if (Mask && Mask->getZExtValue() == MaskVal)
1826 C.Op1 = SDValue(Mask, 0);
1828 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
1829 C.CCValid = SystemZ::CCMASK_TM;
1830 C.CCMask = NewCCMask;
1833 // Return a Comparison that tests the condition-code result of intrinsic
1834 // node Call against constant integer CC using comparison code Cond.
1835 // Opcode is the opcode of the SystemZISD operation for the intrinsic
1836 // and CCValid is the set of possible condition-code results.
1837 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
1838 SDValue Call, unsigned CCValid, uint64_t CC,
1839 ISD::CondCode Cond) {
1840 Comparison C(Call, SDValue());
1842 C.CCValid = CCValid;
1843 if (Cond == ISD::SETEQ)
1844 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
1845 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
1846 else if (Cond == ISD::SETNE)
1847 // ...and the inverse of that.
1848 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
1849 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
1850 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
1851 // always true for CC>3.
1852 C.CCMask = CC < 4 ? -1 << (4 - CC) : -1;
1853 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
1854 // ...and the inverse of that.
1855 C.CCMask = CC < 4 ? ~(-1 << (4 - CC)) : 0;
1856 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
1857 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
1858 // always true for CC>3.
1859 C.CCMask = CC < 4 ? -1 << (3 - CC) : -1;
1860 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
1861 // ...and the inverse of that.
1862 C.CCMask = CC < 4 ? ~(-1 << (3 - CC)) : 0;
1864 llvm_unreachable("Unexpected integer comparison type");
1865 C.CCMask &= CCValid;
1869 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
1870 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
1871 ISD::CondCode Cond, SDLoc DL) {
1872 if (CmpOp1.getOpcode() == ISD::Constant) {
1873 uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
1874 unsigned Opcode, CCValid;
1875 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
1876 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
1877 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
1878 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
1880 Comparison C(CmpOp0, CmpOp1);
1881 C.CCMask = CCMaskForCondCode(Cond);
1882 if (C.Op0.getValueType().isFloatingPoint()) {
1883 C.CCValid = SystemZ::CCMASK_FCMP;
1884 C.Opcode = SystemZISD::FCMP;
1887 C.CCValid = SystemZ::CCMASK_ICMP;
1888 C.Opcode = SystemZISD::ICMP;
1889 // Choose the type of comparison. Equality and inequality tests can
1890 // use either signed or unsigned comparisons. The choice also doesn't
1891 // matter if both sign bits are known to be clear. In those cases we
1892 // want to give the main isel code the freedom to choose whichever
1894 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1895 C.CCMask == SystemZ::CCMASK_CMP_NE ||
1896 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
1897 C.ICmpType = SystemZICMP::Any;
1898 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
1899 C.ICmpType = SystemZICMP::UnsignedOnly;
1901 C.ICmpType = SystemZICMP::SignedOnly;
1902 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
1903 adjustZeroCmp(DAG, DL, C);
1904 adjustSubwordCmp(DAG, DL, C);
1905 adjustForSubtraction(DAG, DL, C);
1907 adjustICmpTruncate(DAG, DL, C);
1910 if (shouldSwapCmpOperands(C)) {
1911 std::swap(C.Op0, C.Op1);
1912 C.CCMask = reverseCCMask(C.CCMask);
1915 adjustForTestUnderMask(DAG, DL, C);
1919 // Emit the comparison instruction described by C.
1920 static SDValue emitCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1921 if (!C.Op1.getNode()) {
1923 switch (C.Op0.getOpcode()) {
1924 case ISD::INTRINSIC_W_CHAIN:
1925 Op = emitIntrinsicWithChainAndGlue(DAG, C.Op0, C.Opcode);
1928 llvm_unreachable("Invalid comparison operands");
1930 return SDValue(Op.getNode(), Op->getNumValues() - 1);
1932 if (C.Opcode == SystemZISD::ICMP)
1933 return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
1934 DAG.getConstant(C.ICmpType, DL, MVT::i32));
1935 if (C.Opcode == SystemZISD::TM) {
1936 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
1937 bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
1938 return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
1939 DAG.getConstant(RegisterOnly, DL, MVT::i32));
1941 return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
1944 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
1945 // 64 bits. Extend is the extension type to use. Store the high part
1946 // in Hi and the low part in Lo.
1947 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
1948 unsigned Extend, SDValue Op0, SDValue Op1,
1949 SDValue &Hi, SDValue &Lo) {
1950 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
1951 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
1952 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
1953 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1954 DAG.getConstant(32, DL, MVT::i64));
1955 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
1956 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
1959 // Lower a binary operation that produces two VT results, one in each
1960 // half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
1961 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
1962 // on the extended Op0 and (unextended) Op1. Store the even register result
1963 // in Even and the odd register result in Odd.
1964 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
1965 unsigned Extend, unsigned Opcode,
1966 SDValue Op0, SDValue Op1,
1967 SDValue &Even, SDValue &Odd) {
1968 SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
1969 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
1970 SDValue(In128, 0), Op1);
1971 bool Is32Bit = is32Bit(VT);
1972 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
1973 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
1976 // Return an i32 value that is 1 if the CC value produced by Glue is
1977 // in the mask CCMask and 0 otherwise. CC is known to have a value
1978 // in CCValid, so other values can be ignored.
1979 static SDValue emitSETCC(SelectionDAG &DAG, SDLoc DL, SDValue Glue,
1980 unsigned CCValid, unsigned CCMask) {
1981 IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
1982 SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
1984 if (Conversion.XORValue)
1985 Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
1986 DAG.getConstant(Conversion.XORValue, DL, MVT::i32));
1988 if (Conversion.AddValue)
1989 Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
1990 DAG.getConstant(Conversion.AddValue, DL, MVT::i32));
1992 // The SHR/AND sequence should get optimized to an RISBG.
1993 Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
1994 DAG.getConstant(Conversion.Bit, DL, MVT::i32));
1995 if (Conversion.Bit != 31)
1996 Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
1997 DAG.getConstant(1, DL, MVT::i32));
2001 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2002 // be done directly. IsFP is true if CC is for a floating-point rather than
2003 // integer comparison.
2004 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) {
2008 return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE;
2012 return IsFP ? SystemZISD::VFCMPHE : 0;
2016 return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH;
2019 return IsFP ? 0 : SystemZISD::VICMPHL;
2026 // Return the SystemZISD vector comparison operation for CC or its inverse,
2027 // or 0 if neither can be done directly. Indicate in Invert whether the
2028 // result is for the inverse of CC. IsFP is true if CC is for a
2029 // floating-point rather than integer comparison.
2030 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP,
2032 if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2037 CC = ISD::getSetCCInverse(CC, !IsFP);
2038 if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2046 // Return a v2f64 that contains the extended form of elements Start and Start+1
2047 // of v4f32 value Op.
2048 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, SDLoc DL,
2050 int Mask[] = { Start, -1, Start + 1, -1 };
2051 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2052 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2055 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2056 // producing a result of type VT.
2057 static SDValue getVectorCmp(SelectionDAG &DAG, unsigned Opcode, SDLoc DL,
2058 EVT VT, SDValue CmpOp0, SDValue CmpOp1) {
2059 // There is no hardware support for v4f32, so extend the vector into
2060 // two v2f64s and compare those.
2061 if (CmpOp0.getValueType() == MVT::v4f32) {
2062 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0);
2063 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0);
2064 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1);
2065 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1);
2066 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2067 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2068 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2070 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2073 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2074 // an integer mask of type VT.
2075 static SDValue lowerVectorSETCC(SelectionDAG &DAG, SDLoc DL, EVT VT,
2076 ISD::CondCode CC, SDValue CmpOp0,
2078 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2079 bool Invert = false;
2082 // Handle tests for order using (or (ogt y x) (oge x y)).
2086 assert(IsFP && "Unexpected integer comparison");
2087 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2088 SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1);
2089 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2093 // Handle <> tests using (or (ogt y x) (ogt x y)).
2097 assert(IsFP && "Unexpected integer comparison");
2098 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2099 SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1);
2100 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2104 // Otherwise a single comparison is enough. It doesn't really
2105 // matter whether we try the inversion or the swap first, since
2106 // there are no cases where both work.
2108 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2109 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1);
2111 CC = ISD::getSetCCSwappedOperands(CC);
2112 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2113 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0);
2115 llvm_unreachable("Unhandled comparison");
2120 SDValue Mask = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2121 DAG.getConstant(65535, DL, MVT::i32));
2122 Mask = DAG.getNode(ISD::BITCAST, DL, VT, Mask);
2123 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2128 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2129 SelectionDAG &DAG) const {
2130 SDValue CmpOp0 = Op.getOperand(0);
2131 SDValue CmpOp1 = Op.getOperand(1);
2132 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2134 EVT VT = Op.getValueType();
2136 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2138 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2139 SDValue Glue = emitCmp(DAG, DL, C);
2140 return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2143 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2144 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2145 SDValue CmpOp0 = Op.getOperand(2);
2146 SDValue CmpOp1 = Op.getOperand(3);
2147 SDValue Dest = Op.getOperand(4);
2150 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2151 SDValue Glue = emitCmp(DAG, DL, C);
2152 return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
2153 Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32),
2154 DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, Glue);
2157 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2158 // allowing Pos and Neg to be wider than CmpOp.
2159 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2160 return (Neg.getOpcode() == ISD::SUB &&
2161 Neg.getOperand(0).getOpcode() == ISD::Constant &&
2162 cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2163 Neg.getOperand(1) == Pos &&
2165 (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2166 Pos.getOperand(0) == CmpOp)));
2169 // Return the absolute or negative absolute of Op; IsNegative decides which.
2170 static SDValue getAbsolute(SelectionDAG &DAG, SDLoc DL, SDValue Op,
2172 Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2174 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2175 DAG.getConstant(0, DL, Op.getValueType()), Op);
2179 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2180 SelectionDAG &DAG) const {
2181 SDValue CmpOp0 = Op.getOperand(0);
2182 SDValue CmpOp1 = Op.getOperand(1);
2183 SDValue TrueOp = Op.getOperand(2);
2184 SDValue FalseOp = Op.getOperand(3);
2185 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2188 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2190 // Check for absolute and negative-absolute selections, including those
2191 // where the comparison value is sign-extended (for LPGFR and LNGFR).
2192 // This check supplements the one in DAGCombiner.
2193 if (C.Opcode == SystemZISD::ICMP &&
2194 C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2195 C.CCMask != SystemZ::CCMASK_CMP_NE &&
2196 C.Op1.getOpcode() == ISD::Constant &&
2197 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2198 if (isAbsolute(C.Op0, TrueOp, FalseOp))
2199 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2200 if (isAbsolute(C.Op0, FalseOp, TrueOp))
2201 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2204 SDValue Glue = emitCmp(DAG, DL, C);
2206 // Special case for handling -1/0 results. The shifts we use here
2207 // should get optimized with the IPM conversion sequence.
2208 auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
2209 auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
2210 if (TrueC && FalseC) {
2211 int64_t TrueVal = TrueC->getSExtValue();
2212 int64_t FalseVal = FalseC->getSExtValue();
2213 if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
2214 // Invert the condition if we want -1 on false.
2216 C.CCMask ^= C.CCValid;
2217 SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2218 EVT VT = Op.getValueType();
2219 // Extend the result to VT. Upper bits are ignored.
2221 Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
2222 // Sign-extend from the low bit.
2223 SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32);
2224 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
2225 return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
2229 SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32),
2230 DAG.getConstant(C.CCMask, DL, MVT::i32), Glue};
2232 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
2233 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
2236 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2237 SelectionDAG &DAG) const {
2239 const GlobalValue *GV = Node->getGlobal();
2240 int64_t Offset = Node->getOffset();
2241 EVT PtrVT = getPointerTy();
2242 Reloc::Model RM = DAG.getTarget().getRelocationModel();
2243 CodeModel::Model CM = DAG.getTarget().getCodeModel();
2246 if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
2247 // Assign anchors at 1<<12 byte boundaries.
2248 uint64_t Anchor = Offset & ~uint64_t(0xfff);
2249 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2250 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2252 // The offset can be folded into the address if it is aligned to a halfword.
2254 if (Offset != 0 && (Offset & 1) == 0) {
2255 SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2256 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2260 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2261 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2262 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2263 MachinePointerInfo::getGOT(), false, false, false, 0);
2266 // If there was a non-zero offset that we didn't fold, create an explicit
2269 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2270 DAG.getConstant(Offset, DL, PtrVT));
2275 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2278 SDValue GOTOffset) const {
2280 EVT PtrVT = getPointerTy();
2281 SDValue Chain = DAG.getEntryNode();
2284 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
2285 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2286 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
2287 Glue = Chain.getValue(1);
2288 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
2289 Glue = Chain.getValue(1);
2291 // The first call operand is the chain and the second is the TLS symbol.
2292 SmallVector<SDValue, 8> Ops;
2293 Ops.push_back(Chain);
2294 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
2295 Node->getValueType(0),
2298 // Add argument registers to the end of the list so that they are
2299 // known live into the call.
2300 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
2301 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
2303 // Add a register mask operand representing the call-preserved registers.
2304 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2305 const uint32_t *Mask =
2306 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
2307 assert(Mask && "Missing call preserved mask for calling convention");
2308 Ops.push_back(DAG.getRegisterMask(Mask));
2310 // Glue the call to the argument copies.
2311 Ops.push_back(Glue);
2314 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2315 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
2316 Glue = Chain.getValue(1);
2318 // Copy the return value from %r2.
2319 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
2322 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
2323 SelectionDAG &DAG) const {
2325 const GlobalValue *GV = Node->getGlobal();
2326 EVT PtrVT = getPointerTy();
2327 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
2329 // The high part of the thread pointer is in access register 0.
2330 SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2331 DAG.getConstant(0, DL, MVT::i32));
2332 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
2334 // The low part of the thread pointer is in access register 1.
2335 SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2336 DAG.getConstant(1, DL, MVT::i32));
2337 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
2339 // Merge them into a single 64-bit address.
2340 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
2341 DAG.getConstant(32, DL, PtrVT));
2342 SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
2344 // Get the offset of GA from the thread pointer, based on the TLS model.
2347 case TLSModel::GeneralDynamic: {
2348 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
2349 SystemZConstantPoolValue *CPV =
2350 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
2352 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2353 Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2354 Offset, MachinePointerInfo::getConstantPool(),
2355 false, false, false, 0);
2357 // Call __tls_get_offset to retrieve the offset.
2358 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
2362 case TLSModel::LocalDynamic: {
2363 // Load the GOT offset of the module ID.
2364 SystemZConstantPoolValue *CPV =
2365 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
2367 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2368 Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2369 Offset, MachinePointerInfo::getConstantPool(),
2370 false, false, false, 0);
2372 // Call __tls_get_offset to retrieve the module base offset.
2373 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
2375 // Note: The SystemZLDCleanupPass will remove redundant computations
2376 // of the module base offset. Count total number of local-dynamic
2377 // accesses to trigger execution of that pass.
2378 SystemZMachineFunctionInfo* MFI =
2379 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
2380 MFI->incNumLocalDynamicTLSAccesses();
2382 // Add the per-symbol offset.
2383 CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
2385 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
2386 DTPOffset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2387 DTPOffset, MachinePointerInfo::getConstantPool(),
2388 false, false, false, 0);
2390 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
2394 case TLSModel::InitialExec: {
2395 // Load the offset from the GOT.
2396 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2397 SystemZII::MO_INDNTPOFF);
2398 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
2399 Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2400 Offset, MachinePointerInfo::getGOT(),
2401 false, false, false, 0);
2405 case TLSModel::LocalExec: {
2406 // Force the offset into the constant pool and load it from there.
2407 SystemZConstantPoolValue *CPV =
2408 SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
2410 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2411 Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
2412 Offset, MachinePointerInfo::getConstantPool(),
2413 false, false, false, 0);
2418 // Add the base and offset together.
2419 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
2422 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
2423 SelectionDAG &DAG) const {
2425 const BlockAddress *BA = Node->getBlockAddress();
2426 int64_t Offset = Node->getOffset();
2427 EVT PtrVT = getPointerTy();
2429 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
2430 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2434 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2435 SelectionDAG &DAG) const {
2437 EVT PtrVT = getPointerTy();
2438 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2440 // Use LARL to load the address of the table.
2441 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2444 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2445 SelectionDAG &DAG) const {
2447 EVT PtrVT = getPointerTy();
2450 if (CP->isMachineConstantPoolEntry())
2451 Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2452 CP->getAlignment());
2454 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2455 CP->getAlignment(), CP->getOffset());
2457 // Use LARL to load the address of the constant pool entry.
2458 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2461 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2462 SelectionDAG &DAG) const {
2464 SDValue In = Op.getOperand(0);
2465 EVT InVT = In.getValueType();
2466 EVT ResVT = Op.getValueType();
2468 // Convert loads directly. This is normally done by DAGCombiner,
2469 // but we need this case for bitcasts that are created during lowering
2470 // and which are then lowered themselves.
2471 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
2472 return DAG.getLoad(ResVT, DL, LoadN->getChain(), LoadN->getBasePtr(),
2473 LoadN->getMemOperand());
2475 if (InVT == MVT::i32 && ResVT == MVT::f32) {
2477 if (Subtarget.hasHighWord()) {
2478 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2480 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2481 MVT::i64, SDValue(U64, 0), In);
2483 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2484 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2485 DAG.getConstant(32, DL, MVT::i64));
2487 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2488 return DAG.getTargetExtractSubreg(SystemZ::subreg_r32,
2489 DL, MVT::f32, Out64);
2491 if (InVT == MVT::f32 && ResVT == MVT::i32) {
2492 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2493 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_r32, DL,
2494 MVT::f64, SDValue(U64, 0), In);
2495 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2496 if (Subtarget.hasHighWord())
2497 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2499 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2500 DAG.getConstant(32, DL, MVT::i64));
2501 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2503 llvm_unreachable("Unexpected bitcast combination");
2506 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2507 SelectionDAG &DAG) const {
2508 MachineFunction &MF = DAG.getMachineFunction();
2509 SystemZMachineFunctionInfo *FuncInfo =
2510 MF.getInfo<SystemZMachineFunctionInfo>();
2511 EVT PtrVT = getPointerTy();
2513 SDValue Chain = Op.getOperand(0);
2514 SDValue Addr = Op.getOperand(1);
2515 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2518 // The initial values of each field.
2519 const unsigned NumFields = 4;
2520 SDValue Fields[NumFields] = {
2521 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
2522 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
2523 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2524 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2527 // Store each field into its respective slot.
2528 SDValue MemOps[NumFields];
2529 unsigned Offset = 0;
2530 for (unsigned I = 0; I < NumFields; ++I) {
2531 SDValue FieldAddr = Addr;
2533 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
2534 DAG.getIntPtrConstant(Offset, DL));
2535 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
2536 MachinePointerInfo(SV, Offset),
2540 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2543 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
2544 SelectionDAG &DAG) const {
2545 SDValue Chain = Op.getOperand(0);
2546 SDValue DstPtr = Op.getOperand(1);
2547 SDValue SrcPtr = Op.getOperand(2);
2548 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2549 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
2552 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
2553 /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
2554 /*isTailCall*/false,
2555 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
2558 SDValue SystemZTargetLowering::
2559 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
2560 SDValue Chain = Op.getOperand(0);
2561 SDValue Size = Op.getOperand(1);
2564 unsigned SPReg = getStackPointerRegisterToSaveRestore();
2566 // Get a reference to the stack pointer.
2567 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
2569 // Get the new stack pointer value.
2570 SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
2572 // Copy the new stack pointer back.
2573 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
2575 // The allocated data lives above the 160 bytes allocated for the standard
2576 // frame, plus any outgoing stack arguments. We don't know how much that
2577 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
2578 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2579 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
2581 SDValue Ops[2] = { Result, Chain };
2582 return DAG.getMergeValues(Ops, DL);
2585 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
2586 SelectionDAG &DAG) const {
2587 EVT VT = Op.getValueType();
2591 // Just do a normal 64-bit multiplication and extract the results.
2592 // We define this so that it can be used for constant division.
2593 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
2594 Op.getOperand(1), Ops[1], Ops[0]);
2596 // Do a full 128-bit multiplication based on UMUL_LOHI64:
2598 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
2600 // but using the fact that the upper halves are either all zeros
2603 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
2605 // and grouping the right terms together since they are quicker than the
2608 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
2609 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
2610 SDValue LL = Op.getOperand(0);
2611 SDValue RL = Op.getOperand(1);
2612 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
2613 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
2614 // UMUL_LOHI64 returns the low result in the odd register and the high
2615 // result in the even register. SMUL_LOHI is defined to return the
2616 // low half first, so the results are in reverse order.
2617 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2618 LL, RL, Ops[1], Ops[0]);
2619 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
2620 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
2621 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
2622 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
2624 return DAG.getMergeValues(Ops, DL);
2627 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
2628 SelectionDAG &DAG) const {
2629 EVT VT = Op.getValueType();
2633 // Just do a normal 64-bit multiplication and extract the results.
2634 // We define this so that it can be used for constant division.
2635 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
2636 Op.getOperand(1), Ops[1], Ops[0]);
2638 // UMUL_LOHI64 returns the low result in the odd register and the high
2639 // result in the even register. UMUL_LOHI is defined to return the
2640 // low half first, so the results are in reverse order.
2641 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2642 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2643 return DAG.getMergeValues(Ops, DL);
2646 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
2647 SelectionDAG &DAG) const {
2648 SDValue Op0 = Op.getOperand(0);
2649 SDValue Op1 = Op.getOperand(1);
2650 EVT VT = Op.getValueType();
2654 // We use DSGF for 32-bit division.
2656 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
2657 Opcode = SystemZISD::SDIVREM32;
2658 } else if (DAG.ComputeNumSignBits(Op1) > 32) {
2659 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
2660 Opcode = SystemZISD::SDIVREM32;
2662 Opcode = SystemZISD::SDIVREM64;
2664 // DSG(F) takes a 64-bit dividend, so the even register in the GR128
2665 // input is "don't care". The instruction returns the remainder in
2666 // the even register and the quotient in the odd register.
2668 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
2669 Op0, Op1, Ops[1], Ops[0]);
2670 return DAG.getMergeValues(Ops, DL);
2673 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
2674 SelectionDAG &DAG) const {
2675 EVT VT = Op.getValueType();
2678 // DL(G) uses a double-width dividend, so we need to clear the even
2679 // register in the GR128 input. The instruction returns the remainder
2680 // in the even register and the quotient in the odd register.
2683 lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
2684 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2686 lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
2687 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2688 return DAG.getMergeValues(Ops, DL);
2691 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
2692 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
2694 // Get the known-zero masks for each operand.
2695 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
2696 APInt KnownZero[2], KnownOne[2];
2697 DAG.computeKnownBits(Ops[0], KnownZero[0], KnownOne[0]);
2698 DAG.computeKnownBits(Ops[1], KnownZero[1], KnownOne[1]);
2700 // See if the upper 32 bits of one operand and the lower 32 bits of the
2701 // other are known zero. They are the low and high operands respectively.
2702 uint64_t Masks[] = { KnownZero[0].getZExtValue(),
2703 KnownZero[1].getZExtValue() };
2705 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
2707 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
2712 SDValue LowOp = Ops[Low];
2713 SDValue HighOp = Ops[High];
2715 // If the high part is a constant, we're better off using IILH.
2716 if (HighOp.getOpcode() == ISD::Constant)
2719 // If the low part is a constant that is outside the range of LHI,
2720 // then we're better off using IILF.
2721 if (LowOp.getOpcode() == ISD::Constant) {
2722 int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
2723 if (!isInt<16>(Value))
2727 // Check whether the high part is an AND that doesn't change the
2728 // high 32 bits and just masks out low bits. We can skip it if so.
2729 if (HighOp.getOpcode() == ISD::AND &&
2730 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
2731 SDValue HighOp0 = HighOp.getOperand(0);
2732 uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
2733 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
2737 // Take advantage of the fact that all GR32 operations only change the
2738 // low 32 bits by truncating Low to an i32 and inserting it directly
2739 // using a subreg. The interesting cases are those where the truncation
2742 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
2743 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
2744 MVT::i64, HighOp, Low32);
2747 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
2748 SelectionDAG &DAG) const {
2749 EVT VT = Op.getValueType();
2751 Op = Op.getOperand(0);
2753 // Handle vector types via VPOPCT.
2754 if (VT.isVector()) {
2755 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
2756 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
2757 switch (VT.getVectorElementType().getSizeInBits()) {
2761 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
2762 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
2763 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
2764 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
2765 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
2769 SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2770 DAG.getConstant(0, DL, MVT::i32));
2771 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
2775 SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2776 DAG.getConstant(0, DL, MVT::i32));
2777 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
2778 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
2782 llvm_unreachable("Unexpected type");
2787 // Get the known-zero mask for the operand.
2788 APInt KnownZero, KnownOne;
2789 DAG.computeKnownBits(Op, KnownZero, KnownOne);
2790 unsigned NumSignificantBits = (~KnownZero).getActiveBits();
2791 if (NumSignificantBits == 0)
2792 return DAG.getConstant(0, DL, VT);
2794 // Skip known-zero high parts of the operand.
2795 int64_t OrigBitSize = VT.getSizeInBits();
2796 int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
2797 BitSize = std::min(BitSize, OrigBitSize);
2799 // The POPCNT instruction counts the number of bits in each byte.
2800 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
2801 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
2802 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
2804 // Add up per-byte counts in a binary tree. All bits of Op at
2805 // position larger than BitSize remain zero throughout.
2806 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
2807 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
2808 if (BitSize != OrigBitSize)
2809 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
2810 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
2811 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
2814 // Extract overall result from high byte.
2816 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
2817 DAG.getConstant(BitSize - 8, DL, VT));
2822 // Op is an atomic load. Lower it into a normal volatile load.
2823 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
2824 SelectionDAG &DAG) const {
2825 auto *Node = cast<AtomicSDNode>(Op.getNode());
2826 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
2827 Node->getChain(), Node->getBasePtr(),
2828 Node->getMemoryVT(), Node->getMemOperand());
2831 // Op is an atomic store. Lower it into a normal volatile store followed
2832 // by a serialization.
2833 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
2834 SelectionDAG &DAG) const {
2835 auto *Node = cast<AtomicSDNode>(Op.getNode());
2836 SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
2837 Node->getBasePtr(), Node->getMemoryVT(),
2838 Node->getMemOperand());
2839 return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
2843 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
2844 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
2845 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
2847 unsigned Opcode) const {
2848 auto *Node = cast<AtomicSDNode>(Op.getNode());
2850 // 32-bit operations need no code outside the main loop.
2851 EVT NarrowVT = Node->getMemoryVT();
2852 EVT WideVT = MVT::i32;
2853 if (NarrowVT == WideVT)
2856 int64_t BitSize = NarrowVT.getSizeInBits();
2857 SDValue ChainIn = Node->getChain();
2858 SDValue Addr = Node->getBasePtr();
2859 SDValue Src2 = Node->getVal();
2860 MachineMemOperand *MMO = Node->getMemOperand();
2862 EVT PtrVT = Addr.getValueType();
2864 // Convert atomic subtracts of constants into additions.
2865 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
2866 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
2867 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
2868 Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
2871 // Get the address of the containing word.
2872 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2873 DAG.getConstant(-4, DL, PtrVT));
2875 // Get the number of bits that the word must be rotated left in order
2876 // to bring the field to the top bits of a GR32.
2877 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2878 DAG.getConstant(3, DL, PtrVT));
2879 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2881 // Get the complementing shift amount, for rotating a field in the top
2882 // bits back to its proper position.
2883 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2884 DAG.getConstant(0, DL, WideVT), BitShift);
2886 // Extend the source operand to 32 bits and prepare it for the inner loop.
2887 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
2888 // operations require the source to be shifted in advance. (This shift
2889 // can be folded if the source is constant.) For AND and NAND, the lower
2890 // bits must be set, while for other opcodes they should be left clear.
2891 if (Opcode != SystemZISD::ATOMIC_SWAPW)
2892 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
2893 DAG.getConstant(32 - BitSize, DL, WideVT));
2894 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
2895 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
2896 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
2897 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
2899 // Construct the ATOMIC_LOADW_* node.
2900 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2901 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
2902 DAG.getConstant(BitSize, DL, WideVT) };
2903 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
2906 // Rotate the result of the final CS so that the field is in the lower
2907 // bits of a GR32, then truncate it.
2908 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
2909 DAG.getConstant(BitSize, DL, WideVT));
2910 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
2912 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
2913 return DAG.getMergeValues(RetOps, DL);
2916 // Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations
2917 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
2918 // operations into additions.
2919 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
2920 SelectionDAG &DAG) const {
2921 auto *Node = cast<AtomicSDNode>(Op.getNode());
2922 EVT MemVT = Node->getMemoryVT();
2923 if (MemVT == MVT::i32 || MemVT == MVT::i64) {
2924 // A full-width operation.
2925 assert(Op.getValueType() == MemVT && "Mismatched VTs");
2926 SDValue Src2 = Node->getVal();
2930 if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
2931 // Use an addition if the operand is constant and either LAA(G) is
2932 // available or the negative value is in the range of A(G)FHI.
2933 int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
2934 if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
2935 NegSrc2 = DAG.getConstant(Value, DL, MemVT);
2936 } else if (Subtarget.hasInterlockedAccess1())
2937 // Use LAA(G) if available.
2938 NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
2941 if (NegSrc2.getNode())
2942 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
2943 Node->getChain(), Node->getBasePtr(), NegSrc2,
2944 Node->getMemOperand(), Node->getOrdering(),
2945 Node->getSynchScope());
2947 // Use the node as-is.
2951 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
2954 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation. Lower the first two
2955 // into a fullword ATOMIC_CMP_SWAPW operation.
2956 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
2957 SelectionDAG &DAG) const {
2958 auto *Node = cast<AtomicSDNode>(Op.getNode());
2960 // We have native support for 32-bit compare and swap.
2961 EVT NarrowVT = Node->getMemoryVT();
2962 EVT WideVT = MVT::i32;
2963 if (NarrowVT == WideVT)
2966 int64_t BitSize = NarrowVT.getSizeInBits();
2967 SDValue ChainIn = Node->getOperand(0);
2968 SDValue Addr = Node->getOperand(1);
2969 SDValue CmpVal = Node->getOperand(2);
2970 SDValue SwapVal = Node->getOperand(3);
2971 MachineMemOperand *MMO = Node->getMemOperand();
2973 EVT PtrVT = Addr.getValueType();
2975 // Get the address of the containing word.
2976 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2977 DAG.getConstant(-4, DL, PtrVT));
2979 // Get the number of bits that the word must be rotated left in order
2980 // to bring the field to the top bits of a GR32.
2981 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2982 DAG.getConstant(3, DL, PtrVT));
2983 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2985 // Get the complementing shift amount, for rotating a field in the top
2986 // bits back to its proper position.
2987 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2988 DAG.getConstant(0, DL, WideVT), BitShift);
2990 // Construct the ATOMIC_CMP_SWAPW node.
2991 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2992 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
2993 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
2994 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
2995 VTList, Ops, NarrowVT, MMO);
2999 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
3000 SelectionDAG &DAG) const {
3001 MachineFunction &MF = DAG.getMachineFunction();
3002 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3003 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
3004 SystemZ::R15D, Op.getValueType());
3007 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
3008 SelectionDAG &DAG) const {
3009 MachineFunction &MF = DAG.getMachineFunction();
3010 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3011 return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
3012 SystemZ::R15D, Op.getOperand(1));
3015 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
3016 SelectionDAG &DAG) const {
3017 bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3019 // Just preserve the chain.
3020 return Op.getOperand(0);
3023 bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3024 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
3025 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
3028 DAG.getConstant(Code, DL, MVT::i32),
3031 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
3032 Node->getVTList(), Ops,
3033 Node->getMemoryVT(), Node->getMemOperand());
3036 // Return an i32 that contains the value of CC immediately after After,
3037 // whose final operand must be MVT::Glue.
3038 static SDValue getCCResult(SelectionDAG &DAG, SDNode *After) {
3040 SDValue Glue = SDValue(After, After->getNumValues() - 1);
3041 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
3042 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
3043 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
3047 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
3048 SelectionDAG &DAG) const {
3049 unsigned Opcode, CCValid;
3050 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
3051 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
3052 SDValue Glued = emitIntrinsicWithChainAndGlue(DAG, Op, Opcode);
3053 SDValue CC = getCCResult(DAG, Glued.getNode());
3054 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
3062 // Says that SystemZISD operation Opcode can be used to perform the equivalent
3063 // of a VPERM with permute vector Bytes. If Opcode takes three operands,
3064 // Operand is the constant third operand, otherwise it is the number of
3065 // bytes in each element of the result.
3069 unsigned char Bytes[SystemZ::VectorBytes];
3073 static const Permute PermuteForms[] = {
3075 { SystemZISD::MERGE_HIGH, 8,
3076 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
3078 { SystemZISD::MERGE_HIGH, 4,
3079 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
3081 { SystemZISD::MERGE_HIGH, 2,
3082 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
3084 { SystemZISD::MERGE_HIGH, 1,
3085 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
3087 { SystemZISD::MERGE_LOW, 8,
3088 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
3090 { SystemZISD::MERGE_LOW, 4,
3091 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
3093 { SystemZISD::MERGE_LOW, 2,
3094 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
3096 { SystemZISD::MERGE_LOW, 1,
3097 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
3099 { SystemZISD::PACK, 4,
3100 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
3102 { SystemZISD::PACK, 2,
3103 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
3105 { SystemZISD::PACK, 1,
3106 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
3107 // VPDI V1, V2, 4 (low half of V1, high half of V2)
3108 { SystemZISD::PERMUTE_DWORDS, 4,
3109 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
3110 // VPDI V1, V2, 1 (high half of V1, low half of V2)
3111 { SystemZISD::PERMUTE_DWORDS, 1,
3112 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
3115 // Called after matching a vector shuffle against a particular pattern.
3116 // Both the original shuffle and the pattern have two vector operands.
3117 // OpNos[0] is the operand of the original shuffle that should be used for
3118 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
3119 // OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
3120 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
3121 // for operands 0 and 1 of the pattern.
3122 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
3126 OpNo0 = OpNo1 = OpNos[1];
3127 } else if (OpNos[1] < 0) {
3128 OpNo0 = OpNo1 = OpNos[0];
3136 // Bytes is a VPERM-like permute vector, except that -1 is used for
3137 // undefined bytes. Return true if the VPERM can be implemented using P.
3138 // When returning true set OpNo0 to the VPERM operand that should be
3139 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
3141 // For example, if swapping the VPERM operands allows P to match, OpNo0
3142 // will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
3143 // operand, but rewriting it to use two duplicated operands allows it to
3144 // match P, then OpNo0 and OpNo1 will be the same.
3145 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
3146 unsigned &OpNo0, unsigned &OpNo1) {
3147 int OpNos[] = { -1, -1 };
3148 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
3151 // Make sure that the two permute vectors use the same suboperand
3152 // byte number. Only the operand numbers (the high bits) are
3153 // allowed to differ.
3154 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
3156 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
3157 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
3158 // Make sure that the operand mappings are consistent with previous
3160 if (OpNos[ModelOpNo] == 1 - RealOpNo)
3162 OpNos[ModelOpNo] = RealOpNo;
3165 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3168 // As above, but search for a matching permute.
3169 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
3170 unsigned &OpNo0, unsigned &OpNo1) {
3171 for (auto &P : PermuteForms)
3172 if (matchPermute(Bytes, P, OpNo0, OpNo1))
3177 // Bytes is a VPERM-like permute vector, except that -1 is used for
3178 // undefined bytes. This permute is an operand of an outer permute.
3179 // See whether redistributing the -1 bytes gives a shuffle that can be
3180 // implemented using P. If so, set Transform to a VPERM-like permute vector
3181 // that, when applied to the result of P, gives the original permute in Bytes.
3182 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3184 SmallVectorImpl<int> &Transform) {
3186 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
3187 int Elt = Bytes[From];
3189 // Byte number From of the result is undefined.
3190 Transform[From] = -1;
3192 while (P.Bytes[To] != Elt) {
3194 if (To == SystemZ::VectorBytes)
3197 Transform[From] = To;
3203 // As above, but search for a matching permute.
3204 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3205 SmallVectorImpl<int> &Transform) {
3206 for (auto &P : PermuteForms)
3207 if (matchDoublePermute(Bytes, P, Transform))
3212 // Convert the mask of the given VECTOR_SHUFFLE into a byte-level mask,
3213 // as if it had type vNi8.
3214 static void getVPermMask(ShuffleVectorSDNode *VSN,
3215 SmallVectorImpl<int> &Bytes) {
3216 EVT VT = VSN->getValueType(0);
3217 unsigned NumElements = VT.getVectorNumElements();
3218 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3219 Bytes.resize(NumElements * BytesPerElement, -1);
3220 for (unsigned I = 0; I < NumElements; ++I) {
3221 int Index = VSN->getMaskElt(I);
3223 for (unsigned J = 0; J < BytesPerElement; ++J)
3224 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
3228 // Bytes is a VPERM-like permute vector, except that -1 is used for
3229 // undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
3230 // the result come from a contiguous sequence of bytes from one input.
3231 // Set Base to the selector for the first byte if so.
3232 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
3233 unsigned BytesPerElement, int &Base) {
3235 for (unsigned I = 0; I < BytesPerElement; ++I) {
3236 if (Bytes[Start + I] >= 0) {
3237 unsigned Elem = Bytes[Start + I];
3240 // Make sure the bytes would come from one input operand.
3241 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
3243 } else if (unsigned(Base) != Elem - I)
3250 // Bytes is a VPERM-like permute vector, except that -1 is used for
3251 // undefined bytes. Return true if it can be performed using VSLDI.
3252 // When returning true, set StartIndex to the shift amount and OpNo0
3253 // and OpNo1 to the VPERM operands that should be used as the first
3254 // and second shift operand respectively.
3255 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
3256 unsigned &StartIndex, unsigned &OpNo0,
3258 int OpNos[] = { -1, -1 };
3260 for (unsigned I = 0; I < 16; ++I) {
3261 int Index = Bytes[I];
3263 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
3264 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
3265 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
3267 Shift = ExpectedShift;
3268 else if (Shift != ExpectedShift)
3270 // Make sure that the operand mappings are consistent with previous
3272 if (OpNos[ModelOpNo] == 1 - RealOpNo)
3274 OpNos[ModelOpNo] = RealOpNo;
3278 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3281 // Create a node that performs P on operands Op0 and Op1, casting the
3282 // operands to the appropriate type. The type of the result is determined by P.
3283 static SDValue getPermuteNode(SelectionDAG &DAG, SDLoc DL,
3284 const Permute &P, SDValue Op0, SDValue Op1) {
3285 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
3286 // elements of a PACK are twice as wide as the outputs.
3287 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
3288 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
3290 // Cast both operands to the appropriate type.
3291 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
3292 SystemZ::VectorBytes / InBytes);
3293 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
3294 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
3296 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
3297 SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32);
3298 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
3299 } else if (P.Opcode == SystemZISD::PACK) {
3300 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
3301 SystemZ::VectorBytes / P.Operand);
3302 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
3304 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
3309 // Bytes is a VPERM-like permute vector, except that -1 is used for
3310 // undefined bytes. Implement it on operands Ops[0] and Ops[1] using
3312 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, SDLoc DL, SDValue *Ops,
3313 const SmallVectorImpl<int> &Bytes) {
3314 for (unsigned I = 0; I < 2; ++I)
3315 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
3317 // First see whether VSLDI can be used.
3318 unsigned StartIndex, OpNo0, OpNo1;
3319 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
3320 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
3321 Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32));
3323 // Fall back on VPERM. Construct an SDNode for the permute vector.
3324 SDValue IndexNodes[SystemZ::VectorBytes];
3325 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3327 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
3329 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
3330 SDValue Op2 = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, IndexNodes);
3331 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
3335 // Describes a general N-operand vector shuffle.
3336 struct GeneralShuffle {
3337 GeneralShuffle(EVT vt) : VT(vt) {}
3339 void add(SDValue, unsigned);
3340 SDValue getNode(SelectionDAG &, SDLoc);
3342 // The operands of the shuffle.
3343 SmallVector<SDValue, SystemZ::VectorBytes> Ops;
3345 // Index I is -1 if byte I of the result is undefined. Otherwise the
3346 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
3347 // Bytes[I] / SystemZ::VectorBytes.
3348 SmallVector<int, SystemZ::VectorBytes> Bytes;
3350 // The type of the shuffle result.
3355 // Add an extra undefined element to the shuffle.
3356 void GeneralShuffle::addUndef() {
3357 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3358 for (unsigned I = 0; I < BytesPerElement; ++I)
3359 Bytes.push_back(-1);
3362 // Add an extra element to the shuffle, taking it from element Elem of Op.
3363 // A null Op indicates a vector input whose value will be calculated later;
3364 // there is at most one such input per shuffle and it always has the same
3365 // type as the result.
3366 void GeneralShuffle::add(SDValue Op, unsigned Elem) {
3367 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3369 // The source vector can have wider elements than the result,
3370 // either through an explicit TRUNCATE or because of type legalization.
3371 // We want the least significant part.
3372 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
3373 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
3374 assert(FromBytesPerElement >= BytesPerElement &&
3375 "Invalid EXTRACT_VECTOR_ELT");
3376 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
3377 (FromBytesPerElement - BytesPerElement));
3379 // Look through things like shuffles and bitcasts.
3380 while (Op.getNode()) {
3381 if (Op.getOpcode() == ISD::BITCAST)
3382 Op = Op.getOperand(0);
3383 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
3384 // See whether the bytes we need come from a contiguous part of one
3386 SmallVector<int, SystemZ::VectorBytes> OpBytes;
3387 getVPermMask(cast<ShuffleVectorSDNode>(Op), OpBytes);
3389 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
3395 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
3396 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
3397 } else if (Op.getOpcode() == ISD::UNDEF) {
3404 // Make sure that the source of the extraction is in Ops.
3406 for (; OpNo < Ops.size(); ++OpNo)
3407 if (Ops[OpNo] == Op)
3409 if (OpNo == Ops.size())
3412 // Add the element to Bytes.
3413 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
3414 for (unsigned I = 0; I < BytesPerElement; ++I)
3415 Bytes.push_back(Base + I);
3418 // Return SDNodes for the completed shuffle.
3419 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, SDLoc DL) {
3420 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
3422 if (Ops.size() == 0)
3423 return DAG.getUNDEF(VT);
3425 // Make sure that there are at least two shuffle operands.
3426 if (Ops.size() == 1)
3427 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
3429 // Create a tree of shuffles, deferring root node until after the loop.
3430 // Try to redistribute the undefined elements of non-root nodes so that
3431 // the non-root shuffles match something like a pack or merge, then adjust
3432 // the parent node's permute vector to compensate for the new order.
3433 // Among other things, this copes with vectors like <2 x i16> that were
3434 // padded with undefined elements during type legalization.
3436 // In the best case this redistribution will lead to the whole tree
3437 // using packs and merges. It should rarely be a loss in other cases.
3438 unsigned Stride = 1;
3439 for (; Stride * 2 < Ops.size(); Stride *= 2) {
3440 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
3441 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
3443 // Create a mask for just these two operands.
3444 SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
3445 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3446 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
3447 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
3450 else if (OpNo == I + Stride)
3451 NewBytes[J] = SystemZ::VectorBytes + Byte;
3455 // See if it would be better to reorganize NewMask to avoid using VPERM.
3456 SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
3457 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
3458 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
3459 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
3460 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3461 if (NewBytes[J] >= 0) {
3462 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
3463 "Invalid double permute");
3464 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
3466 assert(NewBytesMap[J] < 0 && "Invalid double permute");
3469 // Just use NewBytes on the operands.
3470 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
3471 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
3472 if (NewBytes[J] >= 0)
3473 Bytes[J] = I * SystemZ::VectorBytes + J;
3478 // Now we just have 2 inputs. Put the second operand in Ops[1].
3480 Ops[1] = Ops[Stride];
3481 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3482 if (Bytes[I] >= int(SystemZ::VectorBytes))
3483 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
3486 // Look for an instruction that can do the permute without resorting
3488 unsigned OpNo0, OpNo1;
3490 if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
3491 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
3493 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
3494 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3497 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
3498 static bool isScalarToVector(SDValue Op) {
3499 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
3500 if (Op.getOperand(I).getOpcode() != ISD::UNDEF)
3505 // Return a vector of type VT that contains Value in the first element.
3506 // The other elements don't matter.
3507 static SDValue buildScalarToVector(SelectionDAG &DAG, SDLoc DL, EVT VT,
3509 // If we have a constant, replicate it to all elements and let the
3510 // BUILD_VECTOR lowering take care of it.
3511 if (Value.getOpcode() == ISD::Constant ||
3512 Value.getOpcode() == ISD::ConstantFP) {
3513 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
3514 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
3516 if (Value.getOpcode() == ISD::UNDEF)
3517 return DAG.getUNDEF(VT);
3518 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
3521 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
3522 // element 1. Used for cases in which replication is cheap.
3523 static SDValue buildMergeScalars(SelectionDAG &DAG, SDLoc DL, EVT VT,
3524 SDValue Op0, SDValue Op1) {
3525 if (Op0.getOpcode() == ISD::UNDEF) {
3526 if (Op1.getOpcode() == ISD::UNDEF)
3527 return DAG.getUNDEF(VT);
3528 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
3530 if (Op1.getOpcode() == ISD::UNDEF)
3531 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
3532 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
3533 buildScalarToVector(DAG, DL, VT, Op0),
3534 buildScalarToVector(DAG, DL, VT, Op1));
3537 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
3539 static SDValue joinDwords(SelectionDAG &DAG, SDLoc DL, SDValue Op0,
3541 if (Op0.getOpcode() == ISD::UNDEF && Op1.getOpcode() == ISD::UNDEF)
3542 return DAG.getUNDEF(MVT::v2i64);
3543 // If one of the two inputs is undefined then replicate the other one,
3544 // in order to avoid using another register unnecessarily.
3545 if (Op0.getOpcode() == ISD::UNDEF)
3546 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3547 else if (Op1.getOpcode() == ISD::UNDEF)
3548 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3550 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3551 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3553 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
3556 // Try to represent constant BUILD_VECTOR node BVN using a
3557 // SystemZISD::BYTE_MASK-style mask. Store the mask value in Mask
3559 static bool tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) {
3560 EVT ElemVT = BVN->getValueType(0).getVectorElementType();
3561 unsigned BytesPerElement = ElemVT.getStoreSize();
3562 for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) {
3563 SDValue Op = BVN->getOperand(I);
3564 if (Op.getOpcode() != ISD::UNDEF) {
3566 if (Op.getOpcode() == ISD::Constant)
3567 Value = dyn_cast<ConstantSDNode>(Op)->getZExtValue();
3568 else if (Op.getOpcode() == ISD::ConstantFP)
3569 Value = (dyn_cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()
3573 for (unsigned J = 0; J < BytesPerElement; ++J) {
3574 uint64_t Byte = (Value >> (J * 8)) & 0xff;
3576 Mask |= 1 << ((E - I - 1) * BytesPerElement + J);
3585 // Try to load a vector constant in which BitsPerElement-bit value Value
3586 // is replicated to fill the vector. VT is the type of the resulting
3587 // constant, which may have elements of a different size from BitsPerElement.
3588 // Return the SDValue of the constant on success, otherwise return
3590 static SDValue tryBuildVectorReplicate(SelectionDAG &DAG,
3591 const SystemZInstrInfo *TII,
3592 SDLoc DL, EVT VT, uint64_t Value,
3593 unsigned BitsPerElement) {
3594 // Signed 16-bit values can be replicated using VREPI.
3595 int64_t SignedValue = SignExtend64(Value, BitsPerElement);
3596 if (isInt<16>(SignedValue)) {
3597 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
3598 SystemZ::VectorBits / BitsPerElement);
3599 SDValue Op = DAG.getNode(SystemZISD::REPLICATE, DL, VecVT,
3600 DAG.getConstant(SignedValue, DL, MVT::i32));
3601 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3603 // See whether rotating the constant left some N places gives a value that
3604 // is one less than a power of 2 (i.e. all zeros followed by all ones).
3605 // If so we can use VGM.
3606 unsigned Start, End;
3607 if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) {
3608 // isRxSBGMask returns the bit numbers for a full 64-bit value,
3609 // with 0 denoting 1 << 63 and 63 denoting 1. Convert them to
3610 // bit numbers for an BitsPerElement value, so that 0 denotes
3611 // 1 << (BitsPerElement-1).
3612 Start -= 64 - BitsPerElement;
3613 End -= 64 - BitsPerElement;
3614 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
3615 SystemZ::VectorBits / BitsPerElement);
3616 SDValue Op = DAG.getNode(SystemZISD::ROTATE_MASK, DL, VecVT,
3617 DAG.getConstant(Start, DL, MVT::i32),
3618 DAG.getConstant(End, DL, MVT::i32));
3619 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3624 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
3625 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
3626 // the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
3627 // would benefit from this representation and return it if so.
3628 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
3629 BuildVectorSDNode *BVN) {
3630 EVT VT = BVN->getValueType(0);
3631 unsigned NumElements = VT.getVectorNumElements();
3633 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
3634 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
3635 // need a BUILD_VECTOR, add an additional placeholder operand for that
3636 // BUILD_VECTOR and store its operands in ResidueOps.
3637 GeneralShuffle GS(VT);
3638 SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
3639 bool FoundOne = false;
3640 for (unsigned I = 0; I < NumElements; ++I) {
3641 SDValue Op = BVN->getOperand(I);
3642 if (Op.getOpcode() == ISD::TRUNCATE)
3643 Op = Op.getOperand(0);
3644 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3645 Op.getOperand(1).getOpcode() == ISD::Constant) {
3646 unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3647 GS.add(Op.getOperand(0), Elem);
3649 } else if (Op.getOpcode() == ISD::UNDEF) {
3652 GS.add(SDValue(), ResidueOps.size());
3653 ResidueOps.push_back(Op);
3657 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
3661 // Create the BUILD_VECTOR for the remaining elements, if any.
3662 if (!ResidueOps.empty()) {
3663 while (ResidueOps.size() < NumElements)
3664 ResidueOps.push_back(DAG.getUNDEF(VT.getVectorElementType()));
3665 for (auto &Op : GS.Ops) {
3666 if (!Op.getNode()) {
3667 Op = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BVN), VT, ResidueOps);
3672 return GS.getNode(DAG, SDLoc(BVN));
3675 // Combine GPR scalar values Elems into a vector of type VT.
3676 static SDValue buildVector(SelectionDAG &DAG, SDLoc DL, EVT VT,
3677 SmallVectorImpl<SDValue> &Elems) {
3678 // See whether there is a single replicated value.
3680 unsigned int NumElements = Elems.size();
3681 unsigned int Count = 0;
3682 for (auto Elem : Elems) {
3683 if (Elem.getOpcode() != ISD::UNDEF) {
3684 if (!Single.getNode())
3686 else if (Elem != Single) {
3693 // There are three cases here:
3695 // - if the only defined element is a loaded one, the best sequence
3696 // is a replicating load.
3698 // - otherwise, if the only defined element is an i64 value, we will
3699 // end up with the same VLVGP sequence regardless of whether we short-cut
3700 // for replication or fall through to the later code.
3702 // - otherwise, if the only defined element is an i32 or smaller value,
3703 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
3704 // This is only a win if the single defined element is used more than once.
3705 // In other cases we're better off using a single VLVGx.
3706 if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD))
3707 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
3709 // The best way of building a v2i64 from two i64s is to use VLVGP.
3710 if (VT == MVT::v2i64)
3711 return joinDwords(DAG, DL, Elems[0], Elems[1]);
3713 // Use a 64-bit merge high to combine two doubles.
3714 if (VT == MVT::v2f64)
3715 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
3717 // Build v4f32 values directly from the FPRs:
3719 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
3724 if (VT == MVT::v4f32) {
3725 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
3726 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
3727 // Avoid unnecessary undefs by reusing the other operand.
3728 if (Op01.getOpcode() == ISD::UNDEF)
3730 else if (Op23.getOpcode() == ISD::UNDEF)
3732 // Merging identical replications is a no-op.
3733 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
3735 Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
3736 Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
3737 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
3738 DL, MVT::v2i64, Op01, Op23);
3739 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3742 // Collect the constant terms.
3743 SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
3744 SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
3746 unsigned NumConstants = 0;
3747 for (unsigned I = 0; I < NumElements; ++I) {
3748 SDValue Elem = Elems[I];
3749 if (Elem.getOpcode() == ISD::Constant ||
3750 Elem.getOpcode() == ISD::ConstantFP) {
3752 Constants[I] = Elem;
3756 // If there was at least one constant, fill in the other elements of
3757 // Constants with undefs to get a full vector constant and use that
3758 // as the starting point.
3760 if (NumConstants > 0) {
3761 for (unsigned I = 0; I < NumElements; ++I)
3762 if (!Constants[I].getNode())
3763 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
3764 Result = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Constants);
3766 // Otherwise try to use VLVGP to start the sequence in order to
3767 // avoid a false dependency on any previous contents of the vector
3768 // register. This only makes sense if one of the associated elements
3770 unsigned I1 = NumElements / 2 - 1;
3771 unsigned I2 = NumElements - 1;
3772 bool Def1 = (Elems[I1].getOpcode() != ISD::UNDEF);
3773 bool Def2 = (Elems[I2].getOpcode() != ISD::UNDEF);
3775 SDValue Elem1 = Elems[Def1 ? I1 : I2];
3776 SDValue Elem2 = Elems[Def2 ? I2 : I1];
3777 Result = DAG.getNode(ISD::BITCAST, DL, VT,
3778 joinDwords(DAG, DL, Elem1, Elem2));
3782 Result = DAG.getUNDEF(VT);
3785 // Use VLVGx to insert the other elements.
3786 for (unsigned I = 0; I < NumElements; ++I)
3787 if (!Done[I] && Elems[I].getOpcode() != ISD::UNDEF)
3788 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
3789 DAG.getConstant(I, DL, MVT::i32));
3793 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
3794 SelectionDAG &DAG) const {
3795 const SystemZInstrInfo *TII =
3796 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
3797 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
3799 EVT VT = Op.getValueType();
3801 if (BVN->isConstant()) {
3802 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
3803 // preferred way of creating all-zero and all-one vectors so give it
3804 // priority over other methods below.
3806 if (tryBuildVectorByteMask(BVN, Mask)) {
3807 SDValue Op = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3808 DAG.getConstant(Mask, DL, MVT::i32));
3809 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3812 // Try using some form of replication.
3813 APInt SplatBits, SplatUndef;
3814 unsigned SplatBitSize;
3816 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
3818 SplatBitSize <= 64) {
3819 // First try assuming that any undefined bits above the highest set bit
3820 // and below the lowest set bit are 1s. This increases the likelihood of
3821 // being able to use a sign-extended element value in VECTOR REPLICATE
3822 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
3823 uint64_t SplatBitsZ = SplatBits.getZExtValue();
3824 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
3825 uint64_t Lower = (SplatUndefZ
3826 & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
3827 uint64_t Upper = (SplatUndefZ
3828 & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
3829 uint64_t Value = SplatBitsZ | Upper | Lower;
3830 SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value,
3835 // Now try assuming that any undefined bits between the first and
3836 // last defined set bits are set. This increases the chances of
3837 // using a non-wraparound mask.
3838 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
3839 Value = SplatBitsZ | Middle;
3840 Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize);
3845 // Fall back to loading it from memory.
3849 // See if we should use shuffles to construct the vector from other vectors.
3850 SDValue Res = tryBuildVectorShuffle(DAG, BVN);
3854 // Detect SCALAR_TO_VECTOR conversions.
3855 if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
3856 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
3858 // Otherwise use buildVector to build the vector up from GPRs.
3859 unsigned NumElements = Op.getNumOperands();
3860 SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
3861 for (unsigned I = 0; I < NumElements; ++I)
3862 Ops[I] = Op.getOperand(I);
3863 return buildVector(DAG, DL, VT, Ops);
3866 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
3867 SelectionDAG &DAG) const {
3868 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
3870 EVT VT = Op.getValueType();
3871 unsigned NumElements = VT.getVectorNumElements();
3873 if (VSN->isSplat()) {
3874 SDValue Op0 = Op.getOperand(0);
3875 unsigned Index = VSN->getSplatIndex();
3876 assert(Index < VT.getVectorNumElements() &&
3877 "Splat index should be defined and in first operand");
3878 // See whether the value we're splatting is directly available as a scalar.
3879 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
3880 Op0.getOpcode() == ISD::BUILD_VECTOR)
3881 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
3882 // Otherwise keep it as a vector-to-vector operation.
3883 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
3884 DAG.getConstant(Index, DL, MVT::i32));
3887 GeneralShuffle GS(VT);
3888 for (unsigned I = 0; I < NumElements; ++I) {
3889 int Elt = VSN->getMaskElt(I);
3893 GS.add(Op.getOperand(unsigned(Elt) / NumElements),
3894 unsigned(Elt) % NumElements);
3896 return GS.getNode(DAG, SDLoc(VSN));
3899 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
3900 SelectionDAG &DAG) const {
3902 // Just insert the scalar into element 0 of an undefined vector.
3903 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
3904 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
3905 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
3908 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3909 SelectionDAG &DAG) const {
3910 // Handle insertions of floating-point values.
3912 SDValue Op0 = Op.getOperand(0);
3913 SDValue Op1 = Op.getOperand(1);
3914 SDValue Op2 = Op.getOperand(2);
3915 EVT VT = Op.getValueType();
3917 // Insertions into constant indices of a v2f64 can be done using VPDI.
3918 // However, if the inserted value is a bitcast or a constant then it's
3919 // better to use GPRs, as below.
3920 if (VT == MVT::v2f64 &&
3921 Op1.getOpcode() != ISD::BITCAST &&
3922 Op1.getOpcode() != ISD::ConstantFP &&
3923 Op2.getOpcode() == ISD::Constant) {
3924 uint64_t Index = dyn_cast<ConstantSDNode>(Op2)->getZExtValue();
3925 unsigned Mask = VT.getVectorNumElements() - 1;
3930 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
3931 MVT IntVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
3932 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
3933 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
3934 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
3935 DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
3936 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
3940 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3941 SelectionDAG &DAG) const {
3942 // Handle extractions of floating-point values.
3944 SDValue Op0 = Op.getOperand(0);
3945 SDValue Op1 = Op.getOperand(1);
3946 EVT VT = Op.getValueType();
3947 EVT VecVT = Op0.getValueType();
3949 // Extractions of constant indices can be done directly.
3950 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
3951 uint64_t Index = CIndexN->getZExtValue();
3952 unsigned Mask = VecVT.getVectorNumElements() - 1;
3957 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
3958 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
3959 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
3960 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
3961 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
3962 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
3966 SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG,
3967 unsigned UnpackHigh) const {
3968 SDValue PackedOp = Op.getOperand(0);
3969 EVT OutVT = Op.getValueType();
3970 EVT InVT = PackedOp.getValueType();
3971 unsigned ToBits = OutVT.getVectorElementType().getSizeInBits();
3972 unsigned FromBits = InVT.getVectorElementType().getSizeInBits();
3975 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
3976 SystemZ::VectorBits / FromBits);
3977 PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp);
3978 } while (FromBits != ToBits);
3982 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
3983 unsigned ByScalar) const {
3984 // Look for cases where a vector shift can use the *_BY_SCALAR form.
3985 SDValue Op0 = Op.getOperand(0);
3986 SDValue Op1 = Op.getOperand(1);
3988 EVT VT = Op.getValueType();
3989 unsigned ElemBitSize = VT.getVectorElementType().getSizeInBits();
3991 // See whether the shift vector is a splat represented as BUILD_VECTOR.
3992 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
3993 APInt SplatBits, SplatUndef;
3994 unsigned SplatBitSize;
3996 // Check for constant splats. Use ElemBitSize as the minimum element
3997 // width and reject splats that need wider elements.
3998 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
3999 ElemBitSize, true) &&
4000 SplatBitSize == ElemBitSize) {
4001 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
4003 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4005 // Check for variable splats.
4006 BitVector UndefElements;
4007 SDValue Splat = BVN->getSplatValue(&UndefElements);
4009 // Since i32 is the smallest legal type, we either need a no-op
4011 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
4012 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4016 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
4017 // and the shift amount is directly available in a GPR.
4018 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
4019 if (VSN->isSplat()) {
4020 SDValue VSNOp0 = VSN->getOperand(0);
4021 unsigned Index = VSN->getSplatIndex();
4022 assert(Index < VT.getVectorNumElements() &&
4023 "Splat index should be defined and in first operand");
4024 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4025 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
4026 // Since i32 is the smallest legal type, we either need a no-op
4028 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
4029 VSNOp0.getOperand(Index));
4030 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4035 // Otherwise just treat the current form as legal.
4039 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
4040 SelectionDAG &DAG) const {
4041 switch (Op.getOpcode()) {
4043 return lowerBR_CC(Op, DAG);
4044 case ISD::SELECT_CC:
4045 return lowerSELECT_CC(Op, DAG);
4047 return lowerSETCC(Op, DAG);
4048 case ISD::GlobalAddress:
4049 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
4050 case ISD::GlobalTLSAddress:
4051 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
4052 case ISD::BlockAddress:
4053 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
4054 case ISD::JumpTable:
4055 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
4056 case ISD::ConstantPool:
4057 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
4059 return lowerBITCAST(Op, DAG);
4061 return lowerVASTART(Op, DAG);
4063 return lowerVACOPY(Op, DAG);
4064 case ISD::DYNAMIC_STACKALLOC:
4065 return lowerDYNAMIC_STACKALLOC(Op, DAG);
4066 case ISD::SMUL_LOHI:
4067 return lowerSMUL_LOHI(Op, DAG);
4068 case ISD::UMUL_LOHI:
4069 return lowerUMUL_LOHI(Op, DAG);
4071 return lowerSDIVREM(Op, DAG);
4073 return lowerUDIVREM(Op, DAG);
4075 return lowerOR(Op, DAG);
4077 return lowerCTPOP(Op, DAG);
4078 case ISD::CTLZ_ZERO_UNDEF:
4079 return DAG.getNode(ISD::CTLZ, SDLoc(Op),
4080 Op.getValueType(), Op.getOperand(0));
4081 case ISD::CTTZ_ZERO_UNDEF:
4082 return DAG.getNode(ISD::CTTZ, SDLoc(Op),
4083 Op.getValueType(), Op.getOperand(0));
4084 case ISD::ATOMIC_SWAP:
4085 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
4086 case ISD::ATOMIC_STORE:
4087 return lowerATOMIC_STORE(Op, DAG);
4088 case ISD::ATOMIC_LOAD:
4089 return lowerATOMIC_LOAD(Op, DAG);
4090 case ISD::ATOMIC_LOAD_ADD:
4091 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
4092 case ISD::ATOMIC_LOAD_SUB:
4093 return lowerATOMIC_LOAD_SUB(Op, DAG);
4094 case ISD::ATOMIC_LOAD_AND:
4095 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
4096 case ISD::ATOMIC_LOAD_OR:
4097 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
4098 case ISD::ATOMIC_LOAD_XOR:
4099 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
4100 case ISD::ATOMIC_LOAD_NAND:
4101 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
4102 case ISD::ATOMIC_LOAD_MIN:
4103 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
4104 case ISD::ATOMIC_LOAD_MAX:
4105 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
4106 case ISD::ATOMIC_LOAD_UMIN:
4107 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
4108 case ISD::ATOMIC_LOAD_UMAX:
4109 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
4110 case ISD::ATOMIC_CMP_SWAP:
4111 return lowerATOMIC_CMP_SWAP(Op, DAG);
4112 case ISD::STACKSAVE:
4113 return lowerSTACKSAVE(Op, DAG);
4114 case ISD::STACKRESTORE:
4115 return lowerSTACKRESTORE(Op, DAG);
4117 return lowerPREFETCH(Op, DAG);
4118 case ISD::INTRINSIC_W_CHAIN:
4119 return lowerINTRINSIC_W_CHAIN(Op, DAG);
4120 case ISD::BUILD_VECTOR:
4121 return lowerBUILD_VECTOR(Op, DAG);
4122 case ISD::VECTOR_SHUFFLE:
4123 return lowerVECTOR_SHUFFLE(Op, DAG);
4124 case ISD::SCALAR_TO_VECTOR:
4125 return lowerSCALAR_TO_VECTOR(Op, DAG);
4126 case ISD::INSERT_VECTOR_ELT:
4127 return lowerINSERT_VECTOR_ELT(Op, DAG);
4128 case ISD::EXTRACT_VECTOR_ELT:
4129 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4130 case ISD::SIGN_EXTEND_VECTOR_INREG:
4131 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACK_HIGH);
4132 case ISD::ZERO_EXTEND_VECTOR_INREG:
4133 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACKL_HIGH);
4135 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
4137 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
4139 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
4141 llvm_unreachable("Unexpected node to lower");
4145 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
4146 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
4153 OPCODE(PCREL_WRAPPER);
4154 OPCODE(PCREL_OFFSET);
4160 OPCODE(SELECT_CCMASK);
4161 OPCODE(ADJDYNALLOC);
4162 OPCODE(EXTRACT_ACCESS);
4164 OPCODE(UMUL_LOHI64);
4181 OPCODE(SEARCH_STRING);
4185 OPCODE(TBEGIN_NOFLOAT);
4188 OPCODE(ROTATE_MASK);
4190 OPCODE(JOIN_DWORDS);
4195 OPCODE(PERMUTE_DWORDS);
4198 OPCODE(UNPACK_HIGH);
4199 OPCODE(UNPACKL_HIGH);
4201 OPCODE(UNPACKL_LOW);
4202 OPCODE(VSHL_BY_SCALAR);
4203 OPCODE(VSRL_BY_SCALAR);
4204 OPCODE(VSRA_BY_SCALAR);
4214 OPCODE(ATOMIC_SWAPW);
4215 OPCODE(ATOMIC_LOADW_ADD);
4216 OPCODE(ATOMIC_LOADW_SUB);
4217 OPCODE(ATOMIC_LOADW_AND);
4218 OPCODE(ATOMIC_LOADW_OR);
4219 OPCODE(ATOMIC_LOADW_XOR);
4220 OPCODE(ATOMIC_LOADW_NAND);
4221 OPCODE(ATOMIC_LOADW_MIN);
4222 OPCODE(ATOMIC_LOADW_MAX);
4223 OPCODE(ATOMIC_LOADW_UMIN);
4224 OPCODE(ATOMIC_LOADW_UMAX);
4225 OPCODE(ATOMIC_CMP_SWAPW);
4232 // Return true if VT is a vector whose elements are a whole number of bytes
4234 static bool canTreatAsByteVector(EVT VT) {
4235 return VT.isVector() && VT.getVectorElementType().getSizeInBits() % 8 == 0;
4238 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
4239 // producing a result of type ResVT. Op is a possibly bitcast version
4240 // of the input vector and Index is the index (based on type VecVT) that
4241 // should be extracted. Return the new extraction if a simplification
4242 // was possible or if Force is true.
4243 SDValue SystemZTargetLowering::combineExtract(SDLoc DL, EVT ResVT, EVT VecVT,
4244 SDValue Op, unsigned Index,
4245 DAGCombinerInfo &DCI,
4247 SelectionDAG &DAG = DCI.DAG;
4249 // The number of bytes being extracted.
4250 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4253 unsigned Opcode = Op.getOpcode();
4254 if (Opcode == ISD::BITCAST)
4255 // Look through bitcasts.
4256 Op = Op.getOperand(0);
4257 else if (Opcode == ISD::VECTOR_SHUFFLE &&
4258 canTreatAsByteVector(Op.getValueType())) {
4259 // Get a VPERM-like permute mask and see whether the bytes covered
4260 // by the extracted element are a contiguous sequence from one
4262 SmallVector<int, SystemZ::VectorBytes> Bytes;
4263 getVPermMask(cast<ShuffleVectorSDNode>(Op), Bytes);
4265 if (!getShuffleInput(Bytes, Index * BytesPerElement,
4266 BytesPerElement, First))
4269 return DAG.getUNDEF(ResVT);
4270 // Make sure the contiguous sequence starts at a multiple of the
4271 // original element size.
4272 unsigned Byte = unsigned(First) % Bytes.size();
4273 if (Byte % BytesPerElement != 0)
4275 // We can get the extracted value directly from an input.
4276 Index = Byte / BytesPerElement;
4277 Op = Op.getOperand(unsigned(First) / Bytes.size());
4279 } else if (Opcode == ISD::BUILD_VECTOR &&
4280 canTreatAsByteVector(Op.getValueType())) {
4281 // We can only optimize this case if the BUILD_VECTOR elements are
4282 // at least as wide as the extracted value.
4283 EVT OpVT = Op.getValueType();
4284 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4285 if (OpBytesPerElement < BytesPerElement)
4287 // Make sure that the least-significant bit of the extracted value
4288 // is the least significant bit of an input.
4289 unsigned End = (Index + 1) * BytesPerElement;
4290 if (End % OpBytesPerElement != 0)
4292 // We're extracting the low part of one operand of the BUILD_VECTOR.
4293 Op = Op.getOperand(End / OpBytesPerElement - 1);
4294 if (!Op.getValueType().isInteger()) {
4295 EVT VT = MVT::getIntegerVT(Op.getValueType().getSizeInBits());
4296 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
4297 DCI.AddToWorklist(Op.getNode());
4299 EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
4300 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
4302 DCI.AddToWorklist(Op.getNode());
4303 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
4306 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
4307 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
4308 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
4309 canTreatAsByteVector(Op.getValueType()) &&
4310 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
4311 // Make sure that only the unextended bits are significant.
4312 EVT ExtVT = Op.getValueType();
4313 EVT OpVT = Op.getOperand(0).getValueType();
4314 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
4315 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4316 unsigned Byte = Index * BytesPerElement;
4317 unsigned SubByte = Byte % ExtBytesPerElement;
4318 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
4319 if (SubByte < MinSubByte ||
4320 SubByte + BytesPerElement > ExtBytesPerElement)
4322 // Get the byte offset of the unextended element
4323 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
4324 // ...then add the byte offset relative to that element.
4325 Byte += SubByte - MinSubByte;
4326 if (Byte % BytesPerElement != 0)
4328 Op = Op.getOperand(0);
4329 Index = Byte / BytesPerElement;
4335 if (Op.getValueType() != VecVT) {
4336 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
4337 DCI.AddToWorklist(Op.getNode());
4339 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
4340 DAG.getConstant(Index, DL, MVT::i32));
4345 // Optimize vector operations in scalar value Op on the basis that Op
4346 // is truncated to TruncVT.
4348 SystemZTargetLowering::combineTruncateExtract(SDLoc DL, EVT TruncVT, SDValue Op,
4349 DAGCombinerInfo &DCI) const {
4350 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
4351 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
4353 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4354 TruncVT.getSizeInBits() % 8 == 0) {
4355 SDValue Vec = Op.getOperand(0);
4356 EVT VecVT = Vec.getValueType();
4357 if (canTreatAsByteVector(VecVT)) {
4358 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4359 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4360 unsigned TruncBytes = TruncVT.getStoreSize();
4361 if (BytesPerElement % TruncBytes == 0) {
4362 // Calculate the value of Y' in the above description. We are
4363 // splitting the original elements into Scale equal-sized pieces
4364 // and for truncation purposes want the last (least-significant)
4365 // of these pieces for IndexN. This is easiest to do by calculating
4366 // the start index of the following element and then subtracting 1.
4367 unsigned Scale = BytesPerElement / TruncBytes;
4368 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
4370 // Defer the creation of the bitcast from X to combineExtract,
4371 // which might be able to optimize the extraction.
4372 VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
4373 VecVT.getStoreSize() / TruncBytes);
4374 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
4375 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
4383 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
4384 DAGCombinerInfo &DCI) const {
4385 SelectionDAG &DAG = DCI.DAG;
4386 unsigned Opcode = N->getOpcode();
4387 if (Opcode == ISD::SIGN_EXTEND) {
4388 // Convert (sext (ashr (shl X, C1), C2)) to
4389 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
4390 // cheap as narrower ones.
4391 SDValue N0 = N->getOperand(0);
4392 EVT VT = N->getValueType(0);
4393 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
4394 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4395 SDValue Inner = N0.getOperand(0);
4396 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
4397 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
4398 unsigned Extra = (VT.getSizeInBits() -
4399 N0.getValueType().getSizeInBits());
4400 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
4401 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
4402 EVT ShiftVT = N0.getOperand(1).getValueType();
4403 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
4404 Inner.getOperand(0));
4405 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
4406 DAG.getConstant(NewShlAmt, SDLoc(Inner),
4408 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
4409 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
4414 if (Opcode == SystemZISD::MERGE_HIGH ||
4415 Opcode == SystemZISD::MERGE_LOW) {
4416 SDValue Op0 = N->getOperand(0);
4417 SDValue Op1 = N->getOperand(1);
4418 if (Op0.getOpcode() == ISD::BITCAST)
4419 Op0 = Op0.getOperand(0);
4420 if (Op0.getOpcode() == SystemZISD::BYTE_MASK &&
4421 cast<ConstantSDNode>(Op0.getOperand(0))->getZExtValue() == 0) {
4422 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
4424 if (Op1 == N->getOperand(0))
4426 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
4427 EVT VT = Op1.getValueType();
4428 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
4429 if (ElemBytes <= 4) {
4430 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
4431 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
4432 EVT InVT = VT.changeVectorElementTypeToInteger();
4433 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
4434 SystemZ::VectorBytes / ElemBytes / 2);
4436 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
4437 DCI.AddToWorklist(Op1.getNode());
4439 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
4440 DCI.AddToWorklist(Op.getNode());
4441 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
4445 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
4446 // for the extraction to be done on a vMiN value, so that we can use VSTE.
4447 // If X has wider elements then convert it to:
4448 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
4449 if (Opcode == ISD::STORE) {
4450 auto *SN = cast<StoreSDNode>(N);
4451 EVT MemVT = SN->getMemoryVT();
4452 if (MemVT.isInteger()) {
4453 SDValue Value = combineTruncateExtract(SDLoc(N), MemVT,
4454 SN->getValue(), DCI);
4455 if (Value.getNode()) {
4456 DCI.AddToWorklist(Value.getNode());
4458 // Rewrite the store with the new form of stored value.
4459 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
4460 SN->getBasePtr(), SN->getMemoryVT(),
4461 SN->getMemOperand());
4465 // Try to simplify a vector extraction.
4466 if (Opcode == ISD::EXTRACT_VECTOR_ELT) {
4467 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
4468 SDValue Op0 = N->getOperand(0);
4469 EVT VecVT = Op0.getValueType();
4470 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
4471 IndexN->getZExtValue(), DCI, false);
4474 // (join_dwords X, X) == (replicate X)
4475 if (Opcode == SystemZISD::JOIN_DWORDS &&
4476 N->getOperand(0) == N->getOperand(1))
4477 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
4479 // (fround (extract_vector_elt X 0))
4480 // (fround (extract_vector_elt X 1)) ->
4481 // (extract_vector_elt (VROUND X) 0)
4482 // (extract_vector_elt (VROUND X) 1)
4484 // This is a special case since the target doesn't really support v2f32s.
4485 if (Opcode == ISD::FP_ROUND) {
4486 SDValue Op0 = N->getOperand(0);
4487 if (N->getValueType(0) == MVT::f32 &&
4489 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4490 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
4491 Op0.getOperand(1).getOpcode() == ISD::Constant &&
4492 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
4493 SDValue Vec = Op0.getOperand(0);
4494 for (auto *U : Vec->uses()) {
4495 if (U != Op0.getNode() &&
4497 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4498 U->getOperand(0) == Vec &&
4499 U->getOperand(1).getOpcode() == ISD::Constant &&
4500 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
4501 SDValue OtherRound = SDValue(*U->use_begin(), 0);
4502 if (OtherRound.getOpcode() == ISD::FP_ROUND &&
4503 OtherRound.getOperand(0) == SDValue(U, 0) &&
4504 OtherRound.getValueType() == MVT::f32) {
4505 SDValue VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
4507 DCI.AddToWorklist(VRound.getNode());
4509 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
4510 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
4511 DCI.AddToWorklist(Extract1.getNode());
4512 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
4514 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
4515 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
4525 //===----------------------------------------------------------------------===//
4527 //===----------------------------------------------------------------------===//
4529 // Create a new basic block after MBB.
4530 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
4531 MachineFunction &MF = *MBB->getParent();
4532 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
4533 MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
4537 // Split MBB after MI and return the new block (the one that contains
4538 // instructions after MI).
4539 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
4540 MachineBasicBlock *MBB) {
4541 MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
4542 NewMBB->splice(NewMBB->begin(), MBB,
4543 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
4544 NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
4548 // Split MBB before MI and return the new block (the one that contains MI).
4549 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
4550 MachineBasicBlock *MBB) {
4551 MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
4552 NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
4553 NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
4557 // Force base value Base into a register before MI. Return the register.
4558 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
4559 const SystemZInstrInfo *TII) {
4561 return Base.getReg();
4563 MachineBasicBlock *MBB = MI->getParent();
4564 MachineFunction &MF = *MBB->getParent();
4565 MachineRegisterInfo &MRI = MF.getRegInfo();
4567 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
4568 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
4569 .addOperand(Base).addImm(0).addReg(0);
4573 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
4575 SystemZTargetLowering::emitSelect(MachineInstr *MI,
4576 MachineBasicBlock *MBB) const {
4577 const SystemZInstrInfo *TII =
4578 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4580 unsigned DestReg = MI->getOperand(0).getReg();
4581 unsigned TrueReg = MI->getOperand(1).getReg();
4582 unsigned FalseReg = MI->getOperand(2).getReg();
4583 unsigned CCValid = MI->getOperand(3).getImm();
4584 unsigned CCMask = MI->getOperand(4).getImm();
4585 DebugLoc DL = MI->getDebugLoc();
4587 MachineBasicBlock *StartMBB = MBB;
4588 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB);
4589 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
4592 // BRC CCMask, JoinMBB
4593 // # fallthrough to FalseMBB
4595 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4596 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
4597 MBB->addSuccessor(JoinMBB);
4598 MBB->addSuccessor(FalseMBB);
4601 // # fallthrough to JoinMBB
4603 MBB->addSuccessor(JoinMBB);
4606 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
4609 BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
4610 .addReg(TrueReg).addMBB(StartMBB)
4611 .addReg(FalseReg).addMBB(FalseMBB);
4613 MI->eraseFromParent();
4617 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
4618 // StoreOpcode is the store to use and Invert says whether the store should
4619 // happen when the condition is false rather than true. If a STORE ON
4620 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
4622 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
4623 MachineBasicBlock *MBB,
4624 unsigned StoreOpcode, unsigned STOCOpcode,
4625 bool Invert) const {
4626 const SystemZInstrInfo *TII =
4627 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4629 unsigned SrcReg = MI->getOperand(0).getReg();
4630 MachineOperand Base = MI->getOperand(1);
4631 int64_t Disp = MI->getOperand(2).getImm();
4632 unsigned IndexReg = MI->getOperand(3).getReg();
4633 unsigned CCValid = MI->getOperand(4).getImm();
4634 unsigned CCMask = MI->getOperand(5).getImm();
4635 DebugLoc DL = MI->getDebugLoc();
4637 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
4639 // Use STOCOpcode if possible. We could use different store patterns in
4640 // order to avoid matching the index register, but the performance trade-offs
4641 // might be more complicated in that case.
4642 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
4645 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
4646 .addReg(SrcReg).addOperand(Base).addImm(Disp)
4647 .addImm(CCValid).addImm(CCMask);
4648 MI->eraseFromParent();
4652 // Get the condition needed to branch around the store.
4656 MachineBasicBlock *StartMBB = MBB;
4657 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB);
4658 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
4661 // BRC CCMask, JoinMBB
4662 // # fallthrough to FalseMBB
4664 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4665 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
4666 MBB->addSuccessor(JoinMBB);
4667 MBB->addSuccessor(FalseMBB);
4670 // store %SrcReg, %Disp(%Index,%Base)
4671 // # fallthrough to JoinMBB
4673 BuildMI(MBB, DL, TII->get(StoreOpcode))
4674 .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
4675 MBB->addSuccessor(JoinMBB);
4677 MI->eraseFromParent();
4681 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
4682 // or ATOMIC_SWAP{,W} instruction MI. BinOpcode is the instruction that
4683 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
4684 // BitSize is the width of the field in bits, or 0 if this is a partword
4685 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
4686 // is one of the operands. Invert says whether the field should be
4687 // inverted after performing BinOpcode (e.g. for NAND).
4689 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
4690 MachineBasicBlock *MBB,
4693 bool Invert) const {
4694 MachineFunction &MF = *MBB->getParent();
4695 const SystemZInstrInfo *TII =
4696 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4697 MachineRegisterInfo &MRI = MF.getRegInfo();
4698 bool IsSubWord = (BitSize < 32);
4700 // Extract the operands. Base can be a register or a frame index.
4701 // Src2 can be a register or immediate.
4702 unsigned Dest = MI->getOperand(0).getReg();
4703 MachineOperand Base = earlyUseOperand(MI->getOperand(1));
4704 int64_t Disp = MI->getOperand(2).getImm();
4705 MachineOperand Src2 = earlyUseOperand(MI->getOperand(3));
4706 unsigned BitShift = (IsSubWord ? MI->getOperand(4).getReg() : 0);
4707 unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
4708 DebugLoc DL = MI->getDebugLoc();
4710 BitSize = MI->getOperand(6).getImm();
4712 // Subword operations use 32-bit registers.
4713 const TargetRegisterClass *RC = (BitSize <= 32 ?
4714 &SystemZ::GR32BitRegClass :
4715 &SystemZ::GR64BitRegClass);
4716 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
4717 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
4719 // Get the right opcodes for the displacement.
4720 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
4721 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
4722 assert(LOpcode && CSOpcode && "Displacement out of range");
4724 // Create virtual registers for temporary results.
4725 unsigned OrigVal = MRI.createVirtualRegister(RC);
4726 unsigned OldVal = MRI.createVirtualRegister(RC);
4727 unsigned NewVal = (BinOpcode || IsSubWord ?
4728 MRI.createVirtualRegister(RC) : Src2.getReg());
4729 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
4730 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
4732 // Insert a basic block for the main loop.
4733 MachineBasicBlock *StartMBB = MBB;
4734 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
4735 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
4739 // %OrigVal = L Disp(%Base)
4740 // # fall through to LoopMMB
4742 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
4743 .addOperand(Base).addImm(Disp).addReg(0);
4744 MBB->addSuccessor(LoopMBB);
4747 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
4748 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
4749 // %RotatedNewVal = OP %RotatedOldVal, %Src2
4750 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
4751 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
4753 // # fall through to DoneMMB
4755 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
4756 .addReg(OrigVal).addMBB(StartMBB)
4757 .addReg(Dest).addMBB(LoopMBB);
4759 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
4760 .addReg(OldVal).addReg(BitShift).addImm(0);
4762 // Perform the operation normally and then invert every bit of the field.
4763 unsigned Tmp = MRI.createVirtualRegister(RC);
4764 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
4765 .addReg(RotatedOldVal).addOperand(Src2);
4767 // XILF with the upper BitSize bits set.
4768 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
4769 .addReg(Tmp).addImm(-1U << (32 - BitSize));
4771 // Use LCGR and add -1 to the result, which is more compact than
4772 // an XILF, XILH pair.
4773 unsigned Tmp2 = MRI.createVirtualRegister(RC);
4774 BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
4775 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
4776 .addReg(Tmp2).addImm(-1);
4778 } else if (BinOpcode)
4779 // A simply binary operation.
4780 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
4781 .addReg(RotatedOldVal).addOperand(Src2);
4783 // Use RISBG to rotate Src2 into position and use it to replace the
4784 // field in RotatedOldVal.
4785 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
4786 .addReg(RotatedOldVal).addReg(Src2.getReg())
4787 .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
4789 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
4790 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
4791 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
4792 .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
4793 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4794 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
4795 MBB->addSuccessor(LoopMBB);
4796 MBB->addSuccessor(DoneMBB);
4798 MI->eraseFromParent();
4802 // Implement EmitInstrWithCustomInserter for pseudo
4803 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
4804 // instruction that should be used to compare the current field with the
4805 // minimum or maximum value. KeepOldMask is the BRC condition-code mask
4806 // for when the current field should be kept. BitSize is the width of
4807 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
4809 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
4810 MachineBasicBlock *MBB,
4811 unsigned CompareOpcode,
4812 unsigned KeepOldMask,
4813 unsigned BitSize) const {
4814 MachineFunction &MF = *MBB->getParent();
4815 const SystemZInstrInfo *TII =
4816 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4817 MachineRegisterInfo &MRI = MF.getRegInfo();
4818 bool IsSubWord = (BitSize < 32);
4820 // Extract the operands. Base can be a register or a frame index.
4821 unsigned Dest = MI->getOperand(0).getReg();
4822 MachineOperand Base = earlyUseOperand(MI->getOperand(1));
4823 int64_t Disp = MI->getOperand(2).getImm();
4824 unsigned Src2 = MI->getOperand(3).getReg();
4825 unsigned BitShift = (IsSubWord ? MI->getOperand(4).getReg() : 0);
4826 unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
4827 DebugLoc DL = MI->getDebugLoc();
4829 BitSize = MI->getOperand(6).getImm();
4831 // Subword operations use 32-bit registers.
4832 const TargetRegisterClass *RC = (BitSize <= 32 ?
4833 &SystemZ::GR32BitRegClass :
4834 &SystemZ::GR64BitRegClass);
4835 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
4836 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
4838 // Get the right opcodes for the displacement.
4839 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
4840 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
4841 assert(LOpcode && CSOpcode && "Displacement out of range");
4843 // Create virtual registers for temporary results.
4844 unsigned OrigVal = MRI.createVirtualRegister(RC);
4845 unsigned OldVal = MRI.createVirtualRegister(RC);
4846 unsigned NewVal = MRI.createVirtualRegister(RC);
4847 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
4848 unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
4849 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
4851 // Insert 3 basic blocks for the loop.
4852 MachineBasicBlock *StartMBB = MBB;
4853 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
4854 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
4855 MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
4856 MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
4860 // %OrigVal = L Disp(%Base)
4861 // # fall through to LoopMMB
4863 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
4864 .addOperand(Base).addImm(Disp).addReg(0);
4865 MBB->addSuccessor(LoopMBB);
4868 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
4869 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
4870 // CompareOpcode %RotatedOldVal, %Src2
4871 // BRC KeepOldMask, UpdateMBB
4873 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
4874 .addReg(OrigVal).addMBB(StartMBB)
4875 .addReg(Dest).addMBB(UpdateMBB);
4877 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
4878 .addReg(OldVal).addReg(BitShift).addImm(0);
4879 BuildMI(MBB, DL, TII->get(CompareOpcode))
4880 .addReg(RotatedOldVal).addReg(Src2);
4881 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4882 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
4883 MBB->addSuccessor(UpdateMBB);
4884 MBB->addSuccessor(UseAltMBB);
4887 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
4888 // # fall through to UpdateMMB
4891 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
4892 .addReg(RotatedOldVal).addReg(Src2)
4893 .addImm(32).addImm(31 + BitSize).addImm(0);
4894 MBB->addSuccessor(UpdateMBB);
4897 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
4898 // [ %RotatedAltVal, UseAltMBB ]
4899 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
4900 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
4902 // # fall through to DoneMMB
4904 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
4905 .addReg(RotatedOldVal).addMBB(LoopMBB)
4906 .addReg(RotatedAltVal).addMBB(UseAltMBB);
4908 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
4909 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
4910 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
4911 .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
4912 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4913 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
4914 MBB->addSuccessor(LoopMBB);
4915 MBB->addSuccessor(DoneMBB);
4917 MI->eraseFromParent();
4921 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
4924 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
4925 MachineBasicBlock *MBB) const {
4926 MachineFunction &MF = *MBB->getParent();
4927 const SystemZInstrInfo *TII =
4928 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4929 MachineRegisterInfo &MRI = MF.getRegInfo();
4931 // Extract the operands. Base can be a register or a frame index.
4932 unsigned Dest = MI->getOperand(0).getReg();
4933 MachineOperand Base = earlyUseOperand(MI->getOperand(1));
4934 int64_t Disp = MI->getOperand(2).getImm();
4935 unsigned OrigCmpVal = MI->getOperand(3).getReg();
4936 unsigned OrigSwapVal = MI->getOperand(4).getReg();
4937 unsigned BitShift = MI->getOperand(5).getReg();
4938 unsigned NegBitShift = MI->getOperand(6).getReg();
4939 int64_t BitSize = MI->getOperand(7).getImm();
4940 DebugLoc DL = MI->getDebugLoc();
4942 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
4944 // Get the right opcodes for the displacement.
4945 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
4946 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
4947 assert(LOpcode && CSOpcode && "Displacement out of range");
4949 // Create virtual registers for temporary results.
4950 unsigned OrigOldVal = MRI.createVirtualRegister(RC);
4951 unsigned OldVal = MRI.createVirtualRegister(RC);
4952 unsigned CmpVal = MRI.createVirtualRegister(RC);
4953 unsigned SwapVal = MRI.createVirtualRegister(RC);
4954 unsigned StoreVal = MRI.createVirtualRegister(RC);
4955 unsigned RetryOldVal = MRI.createVirtualRegister(RC);
4956 unsigned RetryCmpVal = MRI.createVirtualRegister(RC);
4957 unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
4959 // Insert 2 basic blocks for the loop.
4960 MachineBasicBlock *StartMBB = MBB;
4961 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
4962 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
4963 MachineBasicBlock *SetMBB = emitBlockAfter(LoopMBB);
4967 // %OrigOldVal = L Disp(%Base)
4968 // # fall through to LoopMMB
4970 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
4971 .addOperand(Base).addImm(Disp).addReg(0);
4972 MBB->addSuccessor(LoopMBB);
4975 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
4976 // %CmpVal = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
4977 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
4978 // %Dest = RLL %OldVal, BitSize(%BitShift)
4979 // ^^ The low BitSize bits contain the field
4981 // %RetryCmpVal = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
4982 // ^^ Replace the upper 32-BitSize bits of the
4983 // comparison value with those that we loaded,
4984 // so that we can use a full word comparison.
4985 // CR %Dest, %RetryCmpVal
4987 // # Fall through to SetMBB
4989 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
4990 .addReg(OrigOldVal).addMBB(StartMBB)
4991 .addReg(RetryOldVal).addMBB(SetMBB);
4992 BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
4993 .addReg(OrigCmpVal).addMBB(StartMBB)
4994 .addReg(RetryCmpVal).addMBB(SetMBB);
4995 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
4996 .addReg(OrigSwapVal).addMBB(StartMBB)
4997 .addReg(RetrySwapVal).addMBB(SetMBB);
4998 BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
4999 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
5000 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
5001 .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5002 BuildMI(MBB, DL, TII->get(SystemZ::CR))
5003 .addReg(Dest).addReg(RetryCmpVal);
5004 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5005 .addImm(SystemZ::CCMASK_ICMP)
5006 .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
5007 MBB->addSuccessor(DoneMBB);
5008 MBB->addSuccessor(SetMBB);
5011 // %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
5012 // ^^ Replace the upper 32-BitSize bits of the new
5013 // value with those that we loaded.
5014 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
5015 // ^^ Rotate the new field to its proper position.
5016 // %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
5018 // # fall through to ExitMMB
5020 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
5021 .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5022 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
5023 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
5024 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
5025 .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
5026 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5027 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5028 MBB->addSuccessor(LoopMBB);
5029 MBB->addSuccessor(DoneMBB);
5031 MI->eraseFromParent();
5035 // Emit an extension from a GR32 or GR64 to a GR128. ClearEven is true
5036 // if the high register of the GR128 value must be cleared or false if
5037 // it's "don't care". SubReg is subreg_l32 when extending a GR32
5038 // and subreg_l64 when extending a GR64.
5040 SystemZTargetLowering::emitExt128(MachineInstr *MI,
5041 MachineBasicBlock *MBB,
5042 bool ClearEven, unsigned SubReg) 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 unsigned Dest = MI->getOperand(0).getReg();
5050 unsigned Src = MI->getOperand(1).getReg();
5051 unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5053 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
5055 unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5056 unsigned Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
5058 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
5060 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
5061 .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
5064 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
5065 .addReg(In128).addReg(Src).addImm(SubReg);
5067 MI->eraseFromParent();
5072 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
5073 MachineBasicBlock *MBB,
5074 unsigned Opcode) const {
5075 MachineFunction &MF = *MBB->getParent();
5076 const SystemZInstrInfo *TII =
5077 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5078 MachineRegisterInfo &MRI = MF.getRegInfo();
5079 DebugLoc DL = MI->getDebugLoc();
5081 MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
5082 uint64_t DestDisp = MI->getOperand(1).getImm();
5083 MachineOperand SrcBase = earlyUseOperand(MI->getOperand(2));
5084 uint64_t SrcDisp = MI->getOperand(3).getImm();
5085 uint64_t Length = MI->getOperand(4).getImm();
5087 // When generating more than one CLC, all but the last will need to
5088 // branch to the end when a difference is found.
5089 MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
5090 splitBlockAfter(MI, MBB) : nullptr);
5092 // Check for the loop form, in which operand 5 is the trip count.
5093 if (MI->getNumExplicitOperands() > 5) {
5094 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
5096 uint64_t StartCountReg = MI->getOperand(5).getReg();
5097 uint64_t StartSrcReg = forceReg(MI, SrcBase, TII);
5098 uint64_t StartDestReg = (HaveSingleBase ? StartSrcReg :
5099 forceReg(MI, DestBase, TII));
5101 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
5102 uint64_t ThisSrcReg = MRI.createVirtualRegister(RC);
5103 uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
5104 MRI.createVirtualRegister(RC));
5105 uint64_t NextSrcReg = MRI.createVirtualRegister(RC);
5106 uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
5107 MRI.createVirtualRegister(RC));
5109 RC = &SystemZ::GR64BitRegClass;
5110 uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
5111 uint64_t NextCountReg = MRI.createVirtualRegister(RC);
5113 MachineBasicBlock *StartMBB = MBB;
5114 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5115 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5116 MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
5119 // # fall through to LoopMMB
5120 MBB->addSuccessor(LoopMBB);
5123 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
5124 // [ %NextDestReg, NextMBB ]
5125 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
5126 // [ %NextSrcReg, NextMBB ]
5127 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
5128 // [ %NextCountReg, NextMBB ]
5129 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
5130 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
5133 // The prefetch is used only for MVC. The JLH is used only for CLC.
5136 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
5137 .addReg(StartDestReg).addMBB(StartMBB)
5138 .addReg(NextDestReg).addMBB(NextMBB);
5139 if (!HaveSingleBase)
5140 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
5141 .addReg(StartSrcReg).addMBB(StartMBB)
5142 .addReg(NextSrcReg).addMBB(NextMBB);
5143 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
5144 .addReg(StartCountReg).addMBB(StartMBB)
5145 .addReg(NextCountReg).addMBB(NextMBB);
5146 if (Opcode == SystemZ::MVC)
5147 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
5148 .addImm(SystemZ::PFD_WRITE)
5149 .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
5150 BuildMI(MBB, DL, TII->get(Opcode))
5151 .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
5152 .addReg(ThisSrcReg).addImm(SrcDisp);
5154 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5155 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5157 MBB->addSuccessor(EndMBB);
5158 MBB->addSuccessor(NextMBB);
5162 // %NextDestReg = LA 256(%ThisDestReg)
5163 // %NextSrcReg = LA 256(%ThisSrcReg)
5164 // %NextCountReg = AGHI %ThisCountReg, -1
5165 // CGHI %NextCountReg, 0
5167 // # fall through to DoneMMB
5169 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
5172 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
5173 .addReg(ThisDestReg).addImm(256).addReg(0);
5174 if (!HaveSingleBase)
5175 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
5176 .addReg(ThisSrcReg).addImm(256).addReg(0);
5177 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
5178 .addReg(ThisCountReg).addImm(-1);
5179 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
5180 .addReg(NextCountReg).addImm(0);
5181 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5182 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5184 MBB->addSuccessor(LoopMBB);
5185 MBB->addSuccessor(DoneMBB);
5187 DestBase = MachineOperand::CreateReg(NextDestReg, false);
5188 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
5192 // Handle any remaining bytes with straight-line code.
5193 while (Length > 0) {
5194 uint64_t ThisLength = std::min(Length, uint64_t(256));
5195 // The previous iteration might have created out-of-range displacements.
5196 // Apply them using LAY if so.
5197 if (!isUInt<12>(DestDisp)) {
5198 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5199 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5200 .addOperand(DestBase).addImm(DestDisp).addReg(0);
5201 DestBase = MachineOperand::CreateReg(Reg, false);
5204 if (!isUInt<12>(SrcDisp)) {
5205 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5206 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5207 .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
5208 SrcBase = MachineOperand::CreateReg(Reg, false);
5211 BuildMI(*MBB, MI, DL, TII->get(Opcode))
5212 .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
5213 .addOperand(SrcBase).addImm(SrcDisp);
5214 DestDisp += ThisLength;
5215 SrcDisp += ThisLength;
5216 Length -= ThisLength;
5217 // If there's another CLC to go, branch to the end if a difference
5219 if (EndMBB && Length > 0) {
5220 MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
5221 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5222 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5224 MBB->addSuccessor(EndMBB);
5225 MBB->addSuccessor(NextMBB);
5230 MBB->addSuccessor(EndMBB);
5232 MBB->addLiveIn(SystemZ::CC);
5235 MI->eraseFromParent();
5239 // Decompose string pseudo-instruction MI into a loop that continually performs
5240 // Opcode until CC != 3.
5242 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
5243 MachineBasicBlock *MBB,
5244 unsigned Opcode) const {
5245 MachineFunction &MF = *MBB->getParent();
5246 const SystemZInstrInfo *TII =
5247 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5248 MachineRegisterInfo &MRI = MF.getRegInfo();
5249 DebugLoc DL = MI->getDebugLoc();
5251 uint64_t End1Reg = MI->getOperand(0).getReg();
5252 uint64_t Start1Reg = MI->getOperand(1).getReg();
5253 uint64_t Start2Reg = MI->getOperand(2).getReg();
5254 uint64_t CharReg = MI->getOperand(3).getReg();
5256 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
5257 uint64_t This1Reg = MRI.createVirtualRegister(RC);
5258 uint64_t This2Reg = MRI.createVirtualRegister(RC);
5259 uint64_t End2Reg = MRI.createVirtualRegister(RC);
5261 MachineBasicBlock *StartMBB = MBB;
5262 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5263 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5266 // # fall through to LoopMMB
5267 MBB->addSuccessor(LoopMBB);
5270 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
5271 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
5273 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
5275 // # fall through to DoneMMB
5277 // The load of R0L can be hoisted by post-RA LICM.
5280 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
5281 .addReg(Start1Reg).addMBB(StartMBB)
5282 .addReg(End1Reg).addMBB(LoopMBB);
5283 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
5284 .addReg(Start2Reg).addMBB(StartMBB)
5285 .addReg(End2Reg).addMBB(LoopMBB);
5286 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
5287 BuildMI(MBB, DL, TII->get(Opcode))
5288 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
5289 .addReg(This1Reg).addReg(This2Reg);
5290 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5291 .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
5292 MBB->addSuccessor(LoopMBB);
5293 MBB->addSuccessor(DoneMBB);
5295 DoneMBB->addLiveIn(SystemZ::CC);
5297 MI->eraseFromParent();
5301 // Update TBEGIN instruction with final opcode and register clobbers.
5303 SystemZTargetLowering::emitTransactionBegin(MachineInstr *MI,
5304 MachineBasicBlock *MBB,
5306 bool NoFloat) const {
5307 MachineFunction &MF = *MBB->getParent();
5308 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
5309 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
5312 MI->setDesc(TII->get(Opcode));
5314 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
5315 // Make sure to add the corresponding GRSM bits if they are missing.
5316 uint64_t Control = MI->getOperand(2).getImm();
5317 static const unsigned GPRControlBit[16] = {
5318 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
5319 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
5321 Control |= GPRControlBit[15];
5323 Control |= GPRControlBit[11];
5324 MI->getOperand(2).setImm(Control);
5326 // Add GPR clobbers.
5327 for (int I = 0; I < 16; I++) {
5328 if ((Control & GPRControlBit[I]) == 0) {
5329 unsigned Reg = SystemZMC::GR64Regs[I];
5330 MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5334 // Add FPR/VR clobbers.
5335 if (!NoFloat && (Control & 4) != 0) {
5336 if (Subtarget.hasVector()) {
5337 for (int I = 0; I < 32; I++) {
5338 unsigned Reg = SystemZMC::VR128Regs[I];
5339 MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5342 for (int I = 0; I < 16; I++) {
5343 unsigned Reg = SystemZMC::FP64Regs[I];
5344 MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5352 MachineBasicBlock *SystemZTargetLowering::
5353 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
5354 switch (MI->getOpcode()) {
5355 case SystemZ::Select32Mux:
5356 case SystemZ::Select32:
5357 case SystemZ::SelectF32:
5358 case SystemZ::Select64:
5359 case SystemZ::SelectF64:
5360 case SystemZ::SelectF128:
5361 return emitSelect(MI, MBB);
5363 case SystemZ::CondStore8Mux:
5364 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
5365 case SystemZ::CondStore8MuxInv:
5366 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
5367 case SystemZ::CondStore16Mux:
5368 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
5369 case SystemZ::CondStore16MuxInv:
5370 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
5371 case SystemZ::CondStore8:
5372 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
5373 case SystemZ::CondStore8Inv:
5374 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
5375 case SystemZ::CondStore16:
5376 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
5377 case SystemZ::CondStore16Inv:
5378 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
5379 case SystemZ::CondStore32:
5380 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
5381 case SystemZ::CondStore32Inv:
5382 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
5383 case SystemZ::CondStore64:
5384 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
5385 case SystemZ::CondStore64Inv:
5386 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
5387 case SystemZ::CondStoreF32:
5388 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
5389 case SystemZ::CondStoreF32Inv:
5390 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
5391 case SystemZ::CondStoreF64:
5392 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
5393 case SystemZ::CondStoreF64Inv:
5394 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
5396 case SystemZ::AEXT128_64:
5397 return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
5398 case SystemZ::ZEXT128_32:
5399 return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
5400 case SystemZ::ZEXT128_64:
5401 return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
5403 case SystemZ::ATOMIC_SWAPW:
5404 return emitAtomicLoadBinary(MI, MBB, 0, 0);
5405 case SystemZ::ATOMIC_SWAP_32:
5406 return emitAtomicLoadBinary(MI, MBB, 0, 32);
5407 case SystemZ::ATOMIC_SWAP_64:
5408 return emitAtomicLoadBinary(MI, MBB, 0, 64);
5410 case SystemZ::ATOMIC_LOADW_AR:
5411 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
5412 case SystemZ::ATOMIC_LOADW_AFI:
5413 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
5414 case SystemZ::ATOMIC_LOAD_AR:
5415 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
5416 case SystemZ::ATOMIC_LOAD_AHI:
5417 return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
5418 case SystemZ::ATOMIC_LOAD_AFI:
5419 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
5420 case SystemZ::ATOMIC_LOAD_AGR:
5421 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
5422 case SystemZ::ATOMIC_LOAD_AGHI:
5423 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
5424 case SystemZ::ATOMIC_LOAD_AGFI:
5425 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
5427 case SystemZ::ATOMIC_LOADW_SR:
5428 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
5429 case SystemZ::ATOMIC_LOAD_SR:
5430 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
5431 case SystemZ::ATOMIC_LOAD_SGR:
5432 return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
5434 case SystemZ::ATOMIC_LOADW_NR:
5435 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
5436 case SystemZ::ATOMIC_LOADW_NILH:
5437 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
5438 case SystemZ::ATOMIC_LOAD_NR:
5439 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
5440 case SystemZ::ATOMIC_LOAD_NILL:
5441 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
5442 case SystemZ::ATOMIC_LOAD_NILH:
5443 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
5444 case SystemZ::ATOMIC_LOAD_NILF:
5445 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
5446 case SystemZ::ATOMIC_LOAD_NGR:
5447 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
5448 case SystemZ::ATOMIC_LOAD_NILL64:
5449 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
5450 case SystemZ::ATOMIC_LOAD_NILH64:
5451 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
5452 case SystemZ::ATOMIC_LOAD_NIHL64:
5453 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
5454 case SystemZ::ATOMIC_LOAD_NIHH64:
5455 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
5456 case SystemZ::ATOMIC_LOAD_NILF64:
5457 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
5458 case SystemZ::ATOMIC_LOAD_NIHF64:
5459 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
5461 case SystemZ::ATOMIC_LOADW_OR:
5462 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
5463 case SystemZ::ATOMIC_LOADW_OILH:
5464 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
5465 case SystemZ::ATOMIC_LOAD_OR:
5466 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
5467 case SystemZ::ATOMIC_LOAD_OILL:
5468 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
5469 case SystemZ::ATOMIC_LOAD_OILH:
5470 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
5471 case SystemZ::ATOMIC_LOAD_OILF:
5472 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
5473 case SystemZ::ATOMIC_LOAD_OGR:
5474 return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
5475 case SystemZ::ATOMIC_LOAD_OILL64:
5476 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
5477 case SystemZ::ATOMIC_LOAD_OILH64:
5478 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
5479 case SystemZ::ATOMIC_LOAD_OIHL64:
5480 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
5481 case SystemZ::ATOMIC_LOAD_OIHH64:
5482 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
5483 case SystemZ::ATOMIC_LOAD_OILF64:
5484 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
5485 case SystemZ::ATOMIC_LOAD_OIHF64:
5486 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
5488 case SystemZ::ATOMIC_LOADW_XR:
5489 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
5490 case SystemZ::ATOMIC_LOADW_XILF:
5491 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
5492 case SystemZ::ATOMIC_LOAD_XR:
5493 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
5494 case SystemZ::ATOMIC_LOAD_XILF:
5495 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
5496 case SystemZ::ATOMIC_LOAD_XGR:
5497 return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
5498 case SystemZ::ATOMIC_LOAD_XILF64:
5499 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
5500 case SystemZ::ATOMIC_LOAD_XIHF64:
5501 return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
5503 case SystemZ::ATOMIC_LOADW_NRi:
5504 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
5505 case SystemZ::ATOMIC_LOADW_NILHi:
5506 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
5507 case SystemZ::ATOMIC_LOAD_NRi:
5508 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
5509 case SystemZ::ATOMIC_LOAD_NILLi:
5510 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
5511 case SystemZ::ATOMIC_LOAD_NILHi:
5512 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
5513 case SystemZ::ATOMIC_LOAD_NILFi:
5514 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
5515 case SystemZ::ATOMIC_LOAD_NGRi:
5516 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
5517 case SystemZ::ATOMIC_LOAD_NILL64i:
5518 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
5519 case SystemZ::ATOMIC_LOAD_NILH64i:
5520 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
5521 case SystemZ::ATOMIC_LOAD_NIHL64i:
5522 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
5523 case SystemZ::ATOMIC_LOAD_NIHH64i:
5524 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
5525 case SystemZ::ATOMIC_LOAD_NILF64i:
5526 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
5527 case SystemZ::ATOMIC_LOAD_NIHF64i:
5528 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
5530 case SystemZ::ATOMIC_LOADW_MIN:
5531 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5532 SystemZ::CCMASK_CMP_LE, 0);
5533 case SystemZ::ATOMIC_LOAD_MIN_32:
5534 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5535 SystemZ::CCMASK_CMP_LE, 32);
5536 case SystemZ::ATOMIC_LOAD_MIN_64:
5537 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
5538 SystemZ::CCMASK_CMP_LE, 64);
5540 case SystemZ::ATOMIC_LOADW_MAX:
5541 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5542 SystemZ::CCMASK_CMP_GE, 0);
5543 case SystemZ::ATOMIC_LOAD_MAX_32:
5544 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5545 SystemZ::CCMASK_CMP_GE, 32);
5546 case SystemZ::ATOMIC_LOAD_MAX_64:
5547 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
5548 SystemZ::CCMASK_CMP_GE, 64);
5550 case SystemZ::ATOMIC_LOADW_UMIN:
5551 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5552 SystemZ::CCMASK_CMP_LE, 0);
5553 case SystemZ::ATOMIC_LOAD_UMIN_32:
5554 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5555 SystemZ::CCMASK_CMP_LE, 32);
5556 case SystemZ::ATOMIC_LOAD_UMIN_64:
5557 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
5558 SystemZ::CCMASK_CMP_LE, 64);
5560 case SystemZ::ATOMIC_LOADW_UMAX:
5561 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5562 SystemZ::CCMASK_CMP_GE, 0);
5563 case SystemZ::ATOMIC_LOAD_UMAX_32:
5564 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5565 SystemZ::CCMASK_CMP_GE, 32);
5566 case SystemZ::ATOMIC_LOAD_UMAX_64:
5567 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
5568 SystemZ::CCMASK_CMP_GE, 64);
5570 case SystemZ::ATOMIC_CMP_SWAPW:
5571 return emitAtomicCmpSwapW(MI, MBB);
5572 case SystemZ::MVCSequence:
5573 case SystemZ::MVCLoop:
5574 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
5575 case SystemZ::NCSequence:
5576 case SystemZ::NCLoop:
5577 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
5578 case SystemZ::OCSequence:
5579 case SystemZ::OCLoop:
5580 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
5581 case SystemZ::XCSequence:
5582 case SystemZ::XCLoop:
5583 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
5584 case SystemZ::CLCSequence:
5585 case SystemZ::CLCLoop:
5586 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
5587 case SystemZ::CLSTLoop:
5588 return emitStringWrapper(MI, MBB, SystemZ::CLST);
5589 case SystemZ::MVSTLoop:
5590 return emitStringWrapper(MI, MBB, SystemZ::MVST);
5591 case SystemZ::SRSTLoop:
5592 return emitStringWrapper(MI, MBB, SystemZ::SRST);
5593 case SystemZ::TBEGIN:
5594 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
5595 case SystemZ::TBEGIN_nofloat:
5596 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
5597 case SystemZ::TBEGINC:
5598 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
5600 llvm_unreachable("Unexpected instr type to insert");