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"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/KnownBits.h"
30 #define DEBUG_TYPE "systemz-lower"
33 // Represents a sequence for extracting a 0/1 value from an IPM result:
34 // (((X ^ XORValue) + AddValue) >> Bit)
35 struct IPMConversion {
36 IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
37 : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
44 // Represents information about a comparison.
46 Comparison(SDValue Op0In, SDValue Op1In)
47 : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
49 // The operands to the comparison.
52 // The opcode that should be used to compare Op0 and Op1.
55 // A SystemZICMP value. Only used for integer comparisons.
58 // The mask of CC values that Opcode can produce.
61 // The mask of CC values for which the original condition is true.
64 } // end anonymous namespace
66 // Classify VT as either 32 or 64 bit.
67 static bool is32Bit(EVT VT) {
68 switch (VT.getSimpleVT().SimpleTy) {
74 llvm_unreachable("Unsupported type");
78 // Return a version of MachineOperand that can be safely used before the
80 static MachineOperand earlyUseOperand(MachineOperand Op) {
86 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &TM,
87 const SystemZSubtarget &STI)
88 : TargetLowering(TM), Subtarget(STI) {
89 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
91 // Set up the register classes.
92 if (Subtarget.hasHighWord())
93 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
95 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
96 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
97 if (Subtarget.hasVector()) {
98 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
99 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
101 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
102 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
104 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
106 if (Subtarget.hasVector()) {
107 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
108 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
109 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
110 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
111 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
112 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
115 // Compute derived properties from the register classes
116 computeRegisterProperties(Subtarget.getRegisterInfo());
118 // Set up special registers.
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::ROTR, VT, Expand);
191 // Use *MUL_LOHI where possible instead of MULH*.
192 setOperationAction(ISD::MULHS, VT, Expand);
193 setOperationAction(ISD::MULHU, VT, Expand);
194 setOperationAction(ISD::SMUL_LOHI, VT, Custom);
195 setOperationAction(ISD::UMUL_LOHI, VT, Custom);
197 // Only z196 and above have native support for conversions to unsigned.
198 // On z10, promoting to i64 doesn't generate an inexact condition for
199 // values that are outside the i32 range but in the i64 range, so use
200 // the default expansion.
201 if (!Subtarget.hasFPExtension())
202 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
206 // Type legalization will convert 8- and 16-bit atomic operations into
207 // forms that operate on i32s (but still keeping the original memory VT).
208 // Lower them into full i32 operations.
209 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Custom);
210 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Custom);
211 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
212 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
213 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Custom);
214 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Custom);
215 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
216 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Custom);
217 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Custom);
218 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
219 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
220 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
222 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
224 // Traps are legal, as we will convert them to "j .+2".
225 setOperationAction(ISD::TRAP, MVT::Other, Legal);
227 // z10 has instructions for signed but not unsigned FP conversion.
228 // Handle unsigned 32-bit types as signed 64-bit types.
229 if (!Subtarget.hasFPExtension()) {
230 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
231 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
234 // We have native support for a 64-bit CTLZ, via FLOGR.
235 setOperationAction(ISD::CTLZ, MVT::i32, Promote);
236 setOperationAction(ISD::CTLZ, MVT::i64, Legal);
238 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
239 setOperationAction(ISD::OR, MVT::i64, Custom);
241 // FIXME: Can we support these natively?
242 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
243 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
244 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
246 // We have native instructions for i8, i16 and i32 extensions, but not i1.
247 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
248 for (MVT VT : MVT::integer_valuetypes()) {
249 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
250 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
251 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
254 // Handle the various types of symbolic address.
255 setOperationAction(ISD::ConstantPool, PtrVT, Custom);
256 setOperationAction(ISD::GlobalAddress, PtrVT, Custom);
257 setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
258 setOperationAction(ISD::BlockAddress, PtrVT, Custom);
259 setOperationAction(ISD::JumpTable, PtrVT, Custom);
261 // We need to handle dynamic allocations specially because of the
262 // 160-byte area at the bottom of the stack.
263 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
264 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, PtrVT, Custom);
266 // Use custom expanders so that we can force the function to use
268 setOperationAction(ISD::STACKSAVE, MVT::Other, Custom);
269 setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
271 // Handle prefetches with PFD or PFDRL.
272 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
274 for (MVT VT : MVT::vector_valuetypes()) {
275 // Assume by default that all vector operations need to be expanded.
276 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
277 if (getOperationAction(Opcode, VT) == Legal)
278 setOperationAction(Opcode, VT, Expand);
280 // Likewise all truncating stores and extending loads.
281 for (MVT InnerVT : MVT::vector_valuetypes()) {
282 setTruncStoreAction(VT, InnerVT, Expand);
283 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
284 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
285 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
288 if (isTypeLegal(VT)) {
289 // These operations are legal for anything that can be stored in a
290 // vector register, even if there is no native support for the format
291 // as such. In particular, we can do these for v4f32 even though there
292 // are no specific instructions for that format.
293 setOperationAction(ISD::LOAD, VT, Legal);
294 setOperationAction(ISD::STORE, VT, Legal);
295 setOperationAction(ISD::VSELECT, VT, Legal);
296 setOperationAction(ISD::BITCAST, VT, Legal);
297 setOperationAction(ISD::UNDEF, VT, Legal);
299 // Likewise, except that we need to replace the nodes with something
301 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
302 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
306 // Handle integer vector types.
307 for (MVT VT : MVT::integer_vector_valuetypes()) {
308 if (isTypeLegal(VT)) {
309 // These operations have direct equivalents.
310 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
311 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
312 setOperationAction(ISD::ADD, VT, Legal);
313 setOperationAction(ISD::SUB, VT, Legal);
314 if (VT != MVT::v2i64)
315 setOperationAction(ISD::MUL, VT, Legal);
316 setOperationAction(ISD::AND, VT, Legal);
317 setOperationAction(ISD::OR, VT, Legal);
318 setOperationAction(ISD::XOR, VT, Legal);
319 setOperationAction(ISD::CTPOP, VT, Custom);
320 setOperationAction(ISD::CTTZ, VT, Legal);
321 setOperationAction(ISD::CTLZ, VT, Legal);
323 // Convert a GPR scalar to a vector by inserting it into element 0.
324 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
326 // Use a series of unpacks for extensions.
327 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
328 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
330 // Detect shifts by a scalar amount and convert them into
332 setOperationAction(ISD::SHL, VT, Custom);
333 setOperationAction(ISD::SRA, VT, Custom);
334 setOperationAction(ISD::SRL, VT, Custom);
336 // At present ROTL isn't matched by DAGCombiner. ROTR should be
337 // converted into ROTL.
338 setOperationAction(ISD::ROTL, VT, Expand);
339 setOperationAction(ISD::ROTR, VT, Expand);
341 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
342 // and inverting the result as necessary.
343 setOperationAction(ISD::SETCC, VT, Custom);
347 if (Subtarget.hasVector()) {
348 // There should be no need to check for float types other than v2f64
349 // since <2 x f32> isn't a legal type.
350 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
351 setOperationAction(ISD::FP_TO_SINT, MVT::v2f64, Legal);
352 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
353 setOperationAction(ISD::FP_TO_UINT, MVT::v2f64, Legal);
354 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
355 setOperationAction(ISD::SINT_TO_FP, MVT::v2f64, Legal);
356 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
357 setOperationAction(ISD::UINT_TO_FP, MVT::v2f64, Legal);
360 // Handle floating-point types.
361 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
362 I <= MVT::LAST_FP_VALUETYPE;
364 MVT VT = MVT::SimpleValueType(I);
365 if (isTypeLegal(VT)) {
366 // We can use FI for FRINT.
367 setOperationAction(ISD::FRINT, VT, Legal);
369 // We can use the extended form of FI for other rounding operations.
370 if (Subtarget.hasFPExtension()) {
371 setOperationAction(ISD::FNEARBYINT, VT, Legal);
372 setOperationAction(ISD::FFLOOR, VT, Legal);
373 setOperationAction(ISD::FCEIL, VT, Legal);
374 setOperationAction(ISD::FTRUNC, VT, Legal);
375 setOperationAction(ISD::FROUND, VT, Legal);
378 // No special instructions for these.
379 setOperationAction(ISD::FSIN, VT, Expand);
380 setOperationAction(ISD::FCOS, VT, Expand);
381 setOperationAction(ISD::FSINCOS, VT, Expand);
382 setOperationAction(ISD::FREM, VT, Expand);
383 setOperationAction(ISD::FPOW, VT, Expand);
387 // Handle floating-point vector types.
388 if (Subtarget.hasVector()) {
389 // Scalar-to-vector conversion is just a subreg.
390 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
391 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
393 // Some insertions and extractions can be done directly but others
394 // need to go via integers.
395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
400 // These operations have direct equivalents.
401 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
402 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
403 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
404 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
405 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
406 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
407 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
408 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
409 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
410 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
411 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
412 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
413 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
414 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
417 // We have fused multiply-addition for f32 and f64 but not f128.
418 setOperationAction(ISD::FMA, MVT::f32, Legal);
419 setOperationAction(ISD::FMA, MVT::f64, Legal);
420 setOperationAction(ISD::FMA, MVT::f128, Expand);
422 // Needed so that we don't try to implement f128 constant loads using
423 // a load-and-extend of a f80 constant (in cases where the constant
424 // would fit in an f80).
425 for (MVT VT : MVT::fp_valuetypes())
426 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
428 // Floating-point truncation and stores need to be done separately.
429 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
430 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
431 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
433 // We have 64-bit FPR<->GPR moves, but need special handling for
435 if (!Subtarget.hasVector()) {
436 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
437 setOperationAction(ISD::BITCAST, MVT::f32, Custom);
440 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
441 // structure, but VAEND is a no-op.
442 setOperationAction(ISD::VASTART, MVT::Other, Custom);
443 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
444 setOperationAction(ISD::VAEND, MVT::Other, Expand);
446 // Codes for which we want to perform some z-specific combinations.
447 setTargetDAGCombine(ISD::SIGN_EXTEND);
448 setTargetDAGCombine(ISD::STORE);
449 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
450 setTargetDAGCombine(ISD::FP_ROUND);
451 setTargetDAGCombine(ISD::BSWAP);
452 setTargetDAGCombine(ISD::SHL);
453 setTargetDAGCombine(ISD::SRA);
454 setTargetDAGCombine(ISD::SRL);
455 setTargetDAGCombine(ISD::ROTL);
457 // Handle intrinsics.
458 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
459 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
461 // We want to use MVC in preference to even a single load/store pair.
462 MaxStoresPerMemcpy = 0;
463 MaxStoresPerMemcpyOptSize = 0;
465 // The main memset sequence is a byte store followed by an MVC.
466 // Two STC or MV..I stores win over that, but the kind of fused stores
467 // generated by target-independent code don't when the byte value is
468 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
469 // than "STC;MVC". Handle the choice in target-specific code instead.
470 MaxStoresPerMemset = 0;
471 MaxStoresPerMemsetOptSize = 0;
474 EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL,
475 LLVMContext &, EVT VT) const {
478 return VT.changeVectorElementTypeToInteger();
481 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
482 VT = VT.getScalarType();
487 switch (VT.getSimpleVT().SimpleTy) {
500 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
501 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
502 return Imm.isZero() || Imm.isNegZero();
505 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
506 // We can use CGFI or CLGFI.
507 return isInt<32>(Imm) || isUInt<32>(Imm);
510 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
511 // We can use ALGFI or SLGFI.
512 return isUInt<32>(Imm) || isUInt<32>(-Imm);
515 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
519 // Unaligned accesses should never be slower than the expanded version.
520 // We check specifically for aligned accesses in the few cases where
521 // they are required.
527 bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL,
528 const AddrMode &AM, Type *Ty,
530 // Punt on globals for now, although they can be used in limited
531 // RELATIVE LONG cases.
535 // Require a 20-bit signed offset.
536 if (!isInt<20>(AM.BaseOffs))
539 // Indexing is OK but no scale factor can be applied.
540 return AM.Scale == 0 || AM.Scale == 1;
543 bool SystemZTargetLowering::isFoldableMemAccessOffset(Instruction *I,
544 int64_t Offset) const {
545 // This only applies to z13.
546 if (!Subtarget.hasVector())
549 // * Use LDE instead of LE/LEY to avoid partial register
550 // dependencies (LDE only supports small offsets).
551 // * Utilize the vector registers to hold floating point
552 // values (vector load / store instructions only support small
555 assert (isa<LoadInst>(I) || isa<StoreInst>(I));
556 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
557 I->getOperand(0)->getType());
558 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
559 bool IsVectorAccess = MemAccessTy->isVectorTy();
561 // A store of an extracted vector element will be combined into a VSTE type
563 if (!IsVectorAccess && isa<StoreInst>(I)) {
564 Value *DataOp = I->getOperand(0);
565 if (isa<ExtractElementInst>(DataOp))
566 IsVectorAccess = true;
569 // A load which gets inserted into a vector element will be combined into a
570 // VLE type instruction.
571 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
572 User *LoadUser = *I->user_begin();
573 if (isa<InsertElementInst>(LoadUser))
574 IsVectorAccess = true;
577 if (!isUInt<12>(Offset) && (IsFPAccess || IsVectorAccess))
583 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
584 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
586 unsigned FromBits = FromType->getPrimitiveSizeInBits();
587 unsigned ToBits = ToType->getPrimitiveSizeInBits();
588 return FromBits > ToBits;
591 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
592 if (!FromVT.isInteger() || !ToVT.isInteger())
594 unsigned FromBits = FromVT.getSizeInBits();
595 unsigned ToBits = ToVT.getSizeInBits();
596 return FromBits > ToBits;
599 //===----------------------------------------------------------------------===//
600 // Inline asm support
601 //===----------------------------------------------------------------------===//
603 TargetLowering::ConstraintType
604 SystemZTargetLowering::getConstraintType(StringRef Constraint) const {
605 if (Constraint.size() == 1) {
606 switch (Constraint[0]) {
607 case 'a': // Address register
608 case 'd': // Data register (equivalent to 'r')
609 case 'f': // Floating-point register
610 case 'h': // High-part register
611 case 'r': // General-purpose register
612 return C_RegisterClass;
614 case 'Q': // Memory with base and unsigned 12-bit displacement
615 case 'R': // Likewise, plus an index
616 case 'S': // Memory with base and signed 20-bit displacement
617 case 'T': // Likewise, plus an index
618 case 'm': // Equivalent to 'T'.
621 case 'I': // Unsigned 8-bit constant
622 case 'J': // Unsigned 12-bit constant
623 case 'K': // Signed 16-bit constant
624 case 'L': // Signed 20-bit displacement (on all targets we support)
625 case 'M': // 0x7fffffff
632 return TargetLowering::getConstraintType(Constraint);
635 TargetLowering::ConstraintWeight SystemZTargetLowering::
636 getSingleConstraintMatchWeight(AsmOperandInfo &info,
637 const char *constraint) const {
638 ConstraintWeight weight = CW_Invalid;
639 Value *CallOperandVal = info.CallOperandVal;
640 // If we don't have a value, we can't do a match,
641 // but allow it at the lowest weight.
644 Type *type = CallOperandVal->getType();
645 // Look at the constraint type.
646 switch (*constraint) {
648 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
651 case 'a': // Address register
652 case 'd': // Data register (equivalent to 'r')
653 case 'h': // High-part register
654 case 'r': // General-purpose register
655 if (CallOperandVal->getType()->isIntegerTy())
656 weight = CW_Register;
659 case 'f': // Floating-point register
660 if (type->isFloatingPointTy())
661 weight = CW_Register;
664 case 'I': // Unsigned 8-bit constant
665 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
666 if (isUInt<8>(C->getZExtValue()))
667 weight = CW_Constant;
670 case 'J': // Unsigned 12-bit constant
671 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
672 if (isUInt<12>(C->getZExtValue()))
673 weight = CW_Constant;
676 case 'K': // Signed 16-bit constant
677 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
678 if (isInt<16>(C->getSExtValue()))
679 weight = CW_Constant;
682 case 'L': // Signed 20-bit displacement (on all targets we support)
683 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
684 if (isInt<20>(C->getSExtValue()))
685 weight = CW_Constant;
688 case 'M': // 0x7fffffff
689 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
690 if (C->getZExtValue() == 0x7fffffff)
691 weight = CW_Constant;
697 // Parse a "{tNNN}" register constraint for which the register type "t"
698 // has already been verified. MC is the class associated with "t" and
699 // Map maps 0-based register numbers to LLVM register numbers.
700 static std::pair<unsigned, const TargetRegisterClass *>
701 parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC,
702 const unsigned *Map) {
703 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
704 if (isdigit(Constraint[2])) {
707 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
708 if (!Failed && Index < 16 && Map[Index])
709 return std::make_pair(Map[Index], RC);
711 return std::make_pair(0U, nullptr);
714 std::pair<unsigned, const TargetRegisterClass *>
715 SystemZTargetLowering::getRegForInlineAsmConstraint(
716 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
717 if (Constraint.size() == 1) {
718 // GCC Constraint Letters
719 switch (Constraint[0]) {
721 case 'd': // Data register (equivalent to 'r')
722 case 'r': // General-purpose register
724 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
725 else if (VT == MVT::i128)
726 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
727 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
729 case 'a': // Address register
731 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
732 else if (VT == MVT::i128)
733 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
734 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
736 case 'h': // High-part register (an LLVM extension)
737 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
739 case 'f': // Floating-point register
741 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
742 else if (VT == MVT::f128)
743 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
744 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
747 if (Constraint.size() > 0 && Constraint[0] == '{') {
748 // We need to override the default register parsing for GPRs and FPRs
749 // because the interpretation depends on VT. The internal names of
750 // the registers are also different from the external names
751 // (F0D and F0S instead of F0, etc.).
752 if (Constraint[1] == 'r') {
754 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
755 SystemZMC::GR32Regs);
757 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
758 SystemZMC::GR128Regs);
759 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
760 SystemZMC::GR64Regs);
762 if (Constraint[1] == 'f') {
764 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
765 SystemZMC::FP32Regs);
767 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
768 SystemZMC::FP128Regs);
769 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
770 SystemZMC::FP64Regs);
773 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
776 void SystemZTargetLowering::
777 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
778 std::vector<SDValue> &Ops,
779 SelectionDAG &DAG) const {
780 // Only support length 1 constraints for now.
781 if (Constraint.length() == 1) {
782 switch (Constraint[0]) {
783 case 'I': // Unsigned 8-bit constant
784 if (auto *C = dyn_cast<ConstantSDNode>(Op))
785 if (isUInt<8>(C->getZExtValue()))
786 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
790 case 'J': // Unsigned 12-bit constant
791 if (auto *C = dyn_cast<ConstantSDNode>(Op))
792 if (isUInt<12>(C->getZExtValue()))
793 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
797 case 'K': // Signed 16-bit constant
798 if (auto *C = dyn_cast<ConstantSDNode>(Op))
799 if (isInt<16>(C->getSExtValue()))
800 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
804 case 'L': // Signed 20-bit displacement (on all targets we support)
805 if (auto *C = dyn_cast<ConstantSDNode>(Op))
806 if (isInt<20>(C->getSExtValue()))
807 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
811 case 'M': // 0x7fffffff
812 if (auto *C = dyn_cast<ConstantSDNode>(Op))
813 if (C->getZExtValue() == 0x7fffffff)
814 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
819 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
822 //===----------------------------------------------------------------------===//
823 // Calling conventions
824 //===----------------------------------------------------------------------===//
826 #include "SystemZGenCallingConv.inc"
828 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
829 Type *ToType) const {
830 return isTruncateFree(FromType, ToType);
833 bool SystemZTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
834 return CI->isTailCall();
837 // We do not yet support 128-bit single-element vector types. If the user
838 // attempts to use such types as function argument or return type, prefer
839 // to error out instead of emitting code violating the ABI.
840 static void VerifyVectorType(MVT VT, EVT ArgVT) {
841 if (ArgVT.isVector() && !VT.isVector())
842 report_fatal_error("Unsupported vector argument or return type");
845 static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) {
846 for (unsigned i = 0; i < Ins.size(); ++i)
847 VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
850 static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) {
851 for (unsigned i = 0; i < Outs.size(); ++i)
852 VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
855 // Value is a value that has been passed to us in the location described by VA
856 // (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
857 // any loads onto Chain.
858 static SDValue convertLocVTToValVT(SelectionDAG &DAG, const SDLoc &DL,
859 CCValAssign &VA, SDValue Chain,
861 // If the argument has been promoted from a smaller type, insert an
862 // assertion to capture this.
863 if (VA.getLocInfo() == CCValAssign::SExt)
864 Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
865 DAG.getValueType(VA.getValVT()));
866 else if (VA.getLocInfo() == CCValAssign::ZExt)
867 Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
868 DAG.getValueType(VA.getValVT()));
871 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
872 else if (VA.getLocInfo() == CCValAssign::BCvt) {
873 // If this is a short vector argument loaded from the stack,
874 // extend from i64 to full vector size and then bitcast.
875 assert(VA.getLocVT() == MVT::i64);
876 assert(VA.getValVT().isVector());
877 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
878 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
880 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
884 // Value is a value of type VA.getValVT() that we need to copy into
885 // the location described by VA. Return a copy of Value converted to
886 // VA.getValVT(). The caller is responsible for handling indirect values.
887 static SDValue convertValVTToLocVT(SelectionDAG &DAG, const SDLoc &DL,
888 CCValAssign &VA, SDValue Value) {
889 switch (VA.getLocInfo()) {
890 case CCValAssign::SExt:
891 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
892 case CCValAssign::ZExt:
893 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
894 case CCValAssign::AExt:
895 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
896 case CCValAssign::BCvt:
897 // If this is a short vector argument to be stored to the stack,
898 // bitcast to v2i64 and then extract first element.
899 assert(VA.getLocVT() == MVT::i64);
900 assert(VA.getValVT().isVector());
901 Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
902 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
903 DAG.getConstant(0, DL, MVT::i32));
904 case CCValAssign::Full:
907 llvm_unreachable("Unhandled getLocInfo()");
911 SDValue SystemZTargetLowering::LowerFormalArguments(
912 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
913 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
914 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
915 MachineFunction &MF = DAG.getMachineFunction();
916 MachineFrameInfo &MFI = MF.getFrameInfo();
917 MachineRegisterInfo &MRI = MF.getRegInfo();
918 SystemZMachineFunctionInfo *FuncInfo =
919 MF.getInfo<SystemZMachineFunctionInfo>();
921 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
922 EVT PtrVT = getPointerTy(DAG.getDataLayout());
924 // Detect unsupported vector argument types.
925 if (Subtarget.hasVector())
926 VerifyVectorTypes(Ins);
928 // Assign locations to all of the incoming arguments.
929 SmallVector<CCValAssign, 16> ArgLocs;
930 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
931 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
933 unsigned NumFixedGPRs = 0;
934 unsigned NumFixedFPRs = 0;
935 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
937 CCValAssign &VA = ArgLocs[I];
938 EVT LocVT = VA.getLocVT();
940 // Arguments passed in registers
941 const TargetRegisterClass *RC;
942 switch (LocVT.getSimpleVT().SimpleTy) {
944 // Integers smaller than i64 should be promoted to i64.
945 llvm_unreachable("Unexpected argument type");
948 RC = &SystemZ::GR32BitRegClass;
952 RC = &SystemZ::GR64BitRegClass;
956 RC = &SystemZ::FP32BitRegClass;
960 RC = &SystemZ::FP64BitRegClass;
968 RC = &SystemZ::VR128BitRegClass;
972 unsigned VReg = MRI.createVirtualRegister(RC);
973 MRI.addLiveIn(VA.getLocReg(), VReg);
974 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
976 assert(VA.isMemLoc() && "Argument not register or memory");
978 // Create the frame index object for this incoming parameter.
979 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
980 VA.getLocMemOffset(), true);
982 // Create the SelectionDAG nodes corresponding to a load
983 // from this parameter. Unpromoted ints and floats are
984 // passed as right-justified 8-byte values.
985 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
986 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
987 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
988 DAG.getIntPtrConstant(4, DL));
989 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
990 MachinePointerInfo::getFixedStack(MF, FI));
993 // Convert the value of the argument register into the value that's
995 if (VA.getLocInfo() == CCValAssign::Indirect) {
996 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
997 MachinePointerInfo()));
998 // If the original argument was split (e.g. i128), we need
999 // to load all parts of it here (using the same address).
1000 unsigned ArgIndex = Ins[I].OrigArgIndex;
1001 assert (Ins[I].PartOffset == 0);
1002 while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
1003 CCValAssign &PartVA = ArgLocs[I + 1];
1004 unsigned PartOffset = Ins[I + 1].PartOffset;
1005 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1006 DAG.getIntPtrConstant(PartOffset, DL));
1007 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1008 MachinePointerInfo()));
1012 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
1016 // Save the number of non-varargs registers for later use by va_start, etc.
1017 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
1018 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
1020 // Likewise the address (in the form of a frame index) of where the
1021 // first stack vararg would be. The 1-byte size here is arbitrary.
1022 int64_t StackSize = CCInfo.getNextStackOffset();
1023 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
1025 // ...and a similar frame index for the caller-allocated save area
1026 // that will be used to store the incoming registers.
1027 int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
1028 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
1029 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
1031 // Store the FPR varargs in the reserved frame slots. (We store the
1032 // GPRs as part of the prologue.)
1033 if (NumFixedFPRs < SystemZ::NumArgFPRs) {
1034 SDValue MemOps[SystemZ::NumArgFPRs];
1035 for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
1036 unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
1037 int FI = MFI.CreateFixedObject(8, RegSaveOffset + Offset, true);
1038 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1039 unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
1040 &SystemZ::FP64BitRegClass);
1041 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
1042 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
1043 MachinePointerInfo::getFixedStack(MF, FI));
1045 // Join the stores, which are independent of one another.
1046 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1047 makeArrayRef(&MemOps[NumFixedFPRs],
1048 SystemZ::NumArgFPRs-NumFixedFPRs));
1055 static bool canUseSiblingCall(const CCState &ArgCCInfo,
1056 SmallVectorImpl<CCValAssign> &ArgLocs,
1057 SmallVectorImpl<ISD::OutputArg> &Outs) {
1058 // Punt if there are any indirect or stack arguments, or if the call
1059 // needs the callee-saved argument register R6, or if the call uses
1060 // the callee-saved register arguments SwiftSelf and SwiftError.
1061 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1062 CCValAssign &VA = ArgLocs[I];
1063 if (VA.getLocInfo() == CCValAssign::Indirect)
1067 unsigned Reg = VA.getLocReg();
1068 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1070 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1077 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
1078 SmallVectorImpl<SDValue> &InVals) const {
1079 SelectionDAG &DAG = CLI.DAG;
1081 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1082 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1083 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1084 SDValue Chain = CLI.Chain;
1085 SDValue Callee = CLI.Callee;
1086 bool &IsTailCall = CLI.IsTailCall;
1087 CallingConv::ID CallConv = CLI.CallConv;
1088 bool IsVarArg = CLI.IsVarArg;
1089 MachineFunction &MF = DAG.getMachineFunction();
1090 EVT PtrVT = getPointerTy(MF.getDataLayout());
1092 // Detect unsupported vector argument and return types.
1093 if (Subtarget.hasVector()) {
1094 VerifyVectorTypes(Outs);
1095 VerifyVectorTypes(Ins);
1098 // Analyze the operands of the call, assigning locations to each operand.
1099 SmallVector<CCValAssign, 16> ArgLocs;
1100 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1101 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1103 // We don't support GuaranteedTailCallOpt, only automatically-detected
1105 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1108 // Get a count of how many bytes are to be pushed on the stack.
1109 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1111 // Mark the start of the call.
1113 Chain = DAG.getCALLSEQ_START(Chain,
1114 DAG.getConstant(NumBytes, DL, PtrVT, true),
1117 // Copy argument values to their designated locations.
1118 SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1119 SmallVector<SDValue, 8> MemOpChains;
1121 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1122 CCValAssign &VA = ArgLocs[I];
1123 SDValue ArgValue = OutVals[I];
1125 if (VA.getLocInfo() == CCValAssign::Indirect) {
1126 // Store the argument in a stack slot and pass its address.
1127 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[I].ArgVT);
1128 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1129 MemOpChains.push_back(
1130 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1131 MachinePointerInfo::getFixedStack(MF, FI)));
1132 // If the original argument was split (e.g. i128), we need
1133 // to store all parts of it here (and pass just one address).
1134 unsigned ArgIndex = Outs[I].OrigArgIndex;
1135 assert (Outs[I].PartOffset == 0);
1136 while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1137 SDValue PartValue = OutVals[I + 1];
1138 unsigned PartOffset = Outs[I + 1].PartOffset;
1139 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1140 DAG.getIntPtrConstant(PartOffset, DL));
1141 MemOpChains.push_back(
1142 DAG.getStore(Chain, DL, PartValue, Address,
1143 MachinePointerInfo::getFixedStack(MF, FI)));
1146 ArgValue = SpillSlot;
1148 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1151 // Queue up the argument copies and emit them at the end.
1152 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1154 assert(VA.isMemLoc() && "Argument not register or memory");
1156 // Work out the address of the stack slot. Unpromoted ints and
1157 // floats are passed as right-justified 8-byte values.
1158 if (!StackPtr.getNode())
1159 StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1160 unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1161 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1163 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1164 DAG.getIntPtrConstant(Offset, DL));
1167 MemOpChains.push_back(
1168 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1172 // Join the stores, which are independent of one another.
1173 if (!MemOpChains.empty())
1174 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1176 // Accept direct calls by converting symbolic call addresses to the
1177 // associated Target* opcodes. Force %r1 to be used for indirect
1180 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1181 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1182 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1183 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1184 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1185 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1186 } else if (IsTailCall) {
1187 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1188 Glue = Chain.getValue(1);
1189 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1192 // Build a sequence of copy-to-reg nodes, chained and glued together.
1193 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1194 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1195 RegsToPass[I].second, Glue);
1196 Glue = Chain.getValue(1);
1199 // The first call operand is the chain and the second is the target address.
1200 SmallVector<SDValue, 8> Ops;
1201 Ops.push_back(Chain);
1202 Ops.push_back(Callee);
1204 // Add argument registers to the end of the list so that they are
1205 // known live into the call.
1206 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1207 Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1208 RegsToPass[I].second.getValueType()));
1210 // Add a register mask operand representing the call-preserved registers.
1211 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1212 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1213 assert(Mask && "Missing call preserved mask for calling convention");
1214 Ops.push_back(DAG.getRegisterMask(Mask));
1216 // Glue the call to the argument copies, if any.
1218 Ops.push_back(Glue);
1221 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1223 return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1224 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1225 Glue = Chain.getValue(1);
1227 // Mark the end of the call, which is glued to the call itself.
1228 Chain = DAG.getCALLSEQ_END(Chain,
1229 DAG.getConstant(NumBytes, DL, PtrVT, true),
1230 DAG.getConstant(0, DL, PtrVT, true),
1232 Glue = Chain.getValue(1);
1234 // Assign locations to each value returned by this call.
1235 SmallVector<CCValAssign, 16> RetLocs;
1236 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1237 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1239 // Copy all of the result registers out of their specified physreg.
1240 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1241 CCValAssign &VA = RetLocs[I];
1243 // Copy the value out, gluing the copy to the end of the call sequence.
1244 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1245 VA.getLocVT(), Glue);
1246 Chain = RetValue.getValue(1);
1247 Glue = RetValue.getValue(2);
1249 // Convert the value of the return register into the value that's
1251 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1257 bool SystemZTargetLowering::
1258 CanLowerReturn(CallingConv::ID CallConv,
1259 MachineFunction &MF, bool isVarArg,
1260 const SmallVectorImpl<ISD::OutputArg> &Outs,
1261 LLVMContext &Context) const {
1262 // Detect unsupported vector return types.
1263 if (Subtarget.hasVector())
1264 VerifyVectorTypes(Outs);
1266 // Special case that we cannot easily detect in RetCC_SystemZ since
1267 // i128 is not a legal type.
1268 for (auto &Out : Outs)
1269 if (Out.ArgVT == MVT::i128)
1272 SmallVector<CCValAssign, 16> RetLocs;
1273 CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1274 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1278 SystemZTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1280 const SmallVectorImpl<ISD::OutputArg> &Outs,
1281 const SmallVectorImpl<SDValue> &OutVals,
1282 const SDLoc &DL, SelectionDAG &DAG) const {
1283 MachineFunction &MF = DAG.getMachineFunction();
1285 // Detect unsupported vector return types.
1286 if (Subtarget.hasVector())
1287 VerifyVectorTypes(Outs);
1289 // Assign locations to each returned value.
1290 SmallVector<CCValAssign, 16> RetLocs;
1291 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1292 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1294 // Quick exit for void returns
1295 if (RetLocs.empty())
1296 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1298 // Copy the result values into the output registers.
1300 SmallVector<SDValue, 4> RetOps;
1301 RetOps.push_back(Chain);
1302 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1303 CCValAssign &VA = RetLocs[I];
1304 SDValue RetValue = OutVals[I];
1306 // Make the return register live on exit.
1307 assert(VA.isRegLoc() && "Can only return in registers!");
1309 // Promote the value as required.
1310 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1312 // Chain and glue the copies together.
1313 unsigned Reg = VA.getLocReg();
1314 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1315 Glue = Chain.getValue(1);
1316 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1319 // Update chain and glue.
1322 RetOps.push_back(Glue);
1324 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1327 SDValue SystemZTargetLowering::prepareVolatileOrAtomicLoad(
1328 SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const {
1329 return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
1332 // Return true if Op is an intrinsic node with chain that returns the CC value
1333 // as its only (other) argument. Provide the associated SystemZISD opcode and
1334 // the mask of valid CC values if so.
1335 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1336 unsigned &CCValid) {
1337 unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1339 case Intrinsic::s390_tbegin:
1340 Opcode = SystemZISD::TBEGIN;
1341 CCValid = SystemZ::CCMASK_TBEGIN;
1344 case Intrinsic::s390_tbegin_nofloat:
1345 Opcode = SystemZISD::TBEGIN_NOFLOAT;
1346 CCValid = SystemZ::CCMASK_TBEGIN;
1349 case Intrinsic::s390_tend:
1350 Opcode = SystemZISD::TEND;
1351 CCValid = SystemZ::CCMASK_TEND;
1359 // Return true if Op is an intrinsic node without chain that returns the
1360 // CC value as its final argument. Provide the associated SystemZISD
1361 // opcode and the mask of valid CC values if so.
1362 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
1363 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1365 case Intrinsic::s390_vpkshs:
1366 case Intrinsic::s390_vpksfs:
1367 case Intrinsic::s390_vpksgs:
1368 Opcode = SystemZISD::PACKS_CC;
1369 CCValid = SystemZ::CCMASK_VCMP;
1372 case Intrinsic::s390_vpklshs:
1373 case Intrinsic::s390_vpklsfs:
1374 case Intrinsic::s390_vpklsgs:
1375 Opcode = SystemZISD::PACKLS_CC;
1376 CCValid = SystemZ::CCMASK_VCMP;
1379 case Intrinsic::s390_vceqbs:
1380 case Intrinsic::s390_vceqhs:
1381 case Intrinsic::s390_vceqfs:
1382 case Intrinsic::s390_vceqgs:
1383 Opcode = SystemZISD::VICMPES;
1384 CCValid = SystemZ::CCMASK_VCMP;
1387 case Intrinsic::s390_vchbs:
1388 case Intrinsic::s390_vchhs:
1389 case Intrinsic::s390_vchfs:
1390 case Intrinsic::s390_vchgs:
1391 Opcode = SystemZISD::VICMPHS;
1392 CCValid = SystemZ::CCMASK_VCMP;
1395 case Intrinsic::s390_vchlbs:
1396 case Intrinsic::s390_vchlhs:
1397 case Intrinsic::s390_vchlfs:
1398 case Intrinsic::s390_vchlgs:
1399 Opcode = SystemZISD::VICMPHLS;
1400 CCValid = SystemZ::CCMASK_VCMP;
1403 case Intrinsic::s390_vtm:
1404 Opcode = SystemZISD::VTM;
1405 CCValid = SystemZ::CCMASK_VCMP;
1408 case Intrinsic::s390_vfaebs:
1409 case Intrinsic::s390_vfaehs:
1410 case Intrinsic::s390_vfaefs:
1411 Opcode = SystemZISD::VFAE_CC;
1412 CCValid = SystemZ::CCMASK_ANY;
1415 case Intrinsic::s390_vfaezbs:
1416 case Intrinsic::s390_vfaezhs:
1417 case Intrinsic::s390_vfaezfs:
1418 Opcode = SystemZISD::VFAEZ_CC;
1419 CCValid = SystemZ::CCMASK_ANY;
1422 case Intrinsic::s390_vfeebs:
1423 case Intrinsic::s390_vfeehs:
1424 case Intrinsic::s390_vfeefs:
1425 Opcode = SystemZISD::VFEE_CC;
1426 CCValid = SystemZ::CCMASK_ANY;
1429 case Intrinsic::s390_vfeezbs:
1430 case Intrinsic::s390_vfeezhs:
1431 case Intrinsic::s390_vfeezfs:
1432 Opcode = SystemZISD::VFEEZ_CC;
1433 CCValid = SystemZ::CCMASK_ANY;
1436 case Intrinsic::s390_vfenebs:
1437 case Intrinsic::s390_vfenehs:
1438 case Intrinsic::s390_vfenefs:
1439 Opcode = SystemZISD::VFENE_CC;
1440 CCValid = SystemZ::CCMASK_ANY;
1443 case Intrinsic::s390_vfenezbs:
1444 case Intrinsic::s390_vfenezhs:
1445 case Intrinsic::s390_vfenezfs:
1446 Opcode = SystemZISD::VFENEZ_CC;
1447 CCValid = SystemZ::CCMASK_ANY;
1450 case Intrinsic::s390_vistrbs:
1451 case Intrinsic::s390_vistrhs:
1452 case Intrinsic::s390_vistrfs:
1453 Opcode = SystemZISD::VISTR_CC;
1454 CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3;
1457 case Intrinsic::s390_vstrcbs:
1458 case Intrinsic::s390_vstrchs:
1459 case Intrinsic::s390_vstrcfs:
1460 Opcode = SystemZISD::VSTRC_CC;
1461 CCValid = SystemZ::CCMASK_ANY;
1464 case Intrinsic::s390_vstrczbs:
1465 case Intrinsic::s390_vstrczhs:
1466 case Intrinsic::s390_vstrczfs:
1467 Opcode = SystemZISD::VSTRCZ_CC;
1468 CCValid = SystemZ::CCMASK_ANY;
1471 case Intrinsic::s390_vfcedbs:
1472 Opcode = SystemZISD::VFCMPES;
1473 CCValid = SystemZ::CCMASK_VCMP;
1476 case Intrinsic::s390_vfchdbs:
1477 Opcode = SystemZISD::VFCMPHS;
1478 CCValid = SystemZ::CCMASK_VCMP;
1481 case Intrinsic::s390_vfchedbs:
1482 Opcode = SystemZISD::VFCMPHES;
1483 CCValid = SystemZ::CCMASK_VCMP;
1486 case Intrinsic::s390_vftcidb:
1487 Opcode = SystemZISD::VFTCI;
1488 CCValid = SystemZ::CCMASK_VCMP;
1491 case Intrinsic::s390_tdc:
1492 Opcode = SystemZISD::TDC;
1493 CCValid = SystemZ::CCMASK_TDC;
1501 // Emit an intrinsic with chain with a glued value instead of its CC result.
1502 static SDValue emitIntrinsicWithChainAndGlue(SelectionDAG &DAG, SDValue Op,
1504 // Copy all operands except the intrinsic ID.
1505 unsigned NumOps = Op.getNumOperands();
1506 SmallVector<SDValue, 6> Ops;
1507 Ops.reserve(NumOps - 1);
1508 Ops.push_back(Op.getOperand(0));
1509 for (unsigned I = 2; I < NumOps; ++I)
1510 Ops.push_back(Op.getOperand(I));
1512 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1513 SDVTList RawVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1514 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1515 SDValue OldChain = SDValue(Op.getNode(), 1);
1516 SDValue NewChain = SDValue(Intr.getNode(), 0);
1517 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1521 // Emit an intrinsic with a glued value instead of its CC result.
1522 static SDValue emitIntrinsicWithGlue(SelectionDAG &DAG, SDValue Op,
1524 // Copy all operands except the intrinsic ID.
1525 unsigned NumOps = Op.getNumOperands();
1526 SmallVector<SDValue, 6> Ops;
1527 Ops.reserve(NumOps - 1);
1528 for (unsigned I = 1; I < NumOps; ++I)
1529 Ops.push_back(Op.getOperand(I));
1531 if (Op->getNumValues() == 1)
1532 return DAG.getNode(Opcode, SDLoc(Op), MVT::Glue, Ops);
1533 assert(Op->getNumValues() == 2 && "Expected exactly one non-CC result");
1534 SDVTList RawVTs = DAG.getVTList(Op->getValueType(0), MVT::Glue);
1535 return DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1538 // CC is a comparison that will be implemented using an integer or
1539 // floating-point comparison. Return the condition code mask for
1540 // a branch on true. In the integer case, CCMASK_CMP_UO is set for
1541 // unsigned comparisons and clear for signed ones. In the floating-point
1542 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1543 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1545 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1546 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1547 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1551 llvm_unreachable("Invalid integer condition!");
1560 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
1561 case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1566 // Return a sequence for getting a 1 from an IPM result when CC has a
1567 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1568 // The handling of CC values outside CCValid doesn't matter.
1569 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1570 // Deal with cases where the result can be taken directly from a bit
1571 // of the IPM result.
1572 if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1573 return IPMConversion(0, 0, SystemZ::IPM_CC);
1574 if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1575 return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1577 // Deal with cases where we can add a value to force the sign bit
1578 // to contain the right value. Putting the bit in 31 means we can
1579 // use SRL rather than RISBG(L), and also makes it easier to get a
1580 // 0/-1 value, so it has priority over the other tests below.
1582 // These sequences rely on the fact that the upper two bits of the
1583 // IPM result are zero.
1584 uint64_t TopBit = uint64_t(1) << 31;
1585 if (CCMask == (CCValid & SystemZ::CCMASK_0))
1586 return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1587 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1588 return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1589 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1591 | SystemZ::CCMASK_2)))
1592 return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1593 if (CCMask == (CCValid & SystemZ::CCMASK_3))
1594 return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1595 if (CCMask == (CCValid & (SystemZ::CCMASK_1
1597 | SystemZ::CCMASK_3)))
1598 return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1600 // Next try inverting the value and testing a bit. 0/1 could be
1601 // handled this way too, but we dealt with that case above.
1602 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1603 return IPMConversion(-1, 0, SystemZ::IPM_CC);
1605 // Handle cases where adding a value forces a non-sign bit to contain
1607 if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1608 return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1609 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1610 return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1612 // The remaining cases are 1, 2, 0/1/3 and 0/2/3. All these are
1613 // can be done by inverting the low CC bit and applying one of the
1614 // sign-based extractions above.
1615 if (CCMask == (CCValid & SystemZ::CCMASK_1))
1616 return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1617 if (CCMask == (CCValid & SystemZ::CCMASK_2))
1618 return IPMConversion(1 << SystemZ::IPM_CC,
1619 TopBit - (3 << SystemZ::IPM_CC), 31);
1620 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1622 | SystemZ::CCMASK_3)))
1623 return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1624 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1626 | SystemZ::CCMASK_3)))
1627 return IPMConversion(1 << SystemZ::IPM_CC,
1628 TopBit - (1 << SystemZ::IPM_CC), 31);
1630 llvm_unreachable("Unexpected CC combination");
1633 // If C can be converted to a comparison against zero, adjust the operands
1635 static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
1636 if (C.ICmpType == SystemZICMP::UnsignedOnly)
1639 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1643 int64_t Value = ConstOp1->getSExtValue();
1644 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1645 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1646 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1647 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1648 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1649 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1653 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1654 // adjust the operands as necessary.
1655 static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
1657 // For us to make any changes, it must a comparison between a single-use
1658 // load and a constant.
1659 if (!C.Op0.hasOneUse() ||
1660 C.Op0.getOpcode() != ISD::LOAD ||
1661 C.Op1.getOpcode() != ISD::Constant)
1664 // We must have an 8- or 16-bit load.
1665 auto *Load = cast<LoadSDNode>(C.Op0);
1666 unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1667 if (NumBits != 8 && NumBits != 16)
1670 // The load must be an extending one and the constant must be within the
1671 // range of the unextended value.
1672 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1673 uint64_t Value = ConstOp1->getZExtValue();
1674 uint64_t Mask = (1 << NumBits) - 1;
1675 if (Load->getExtensionType() == ISD::SEXTLOAD) {
1676 // Make sure that ConstOp1 is in range of C.Op0.
1677 int64_t SignedValue = ConstOp1->getSExtValue();
1678 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1680 if (C.ICmpType != SystemZICMP::SignedOnly) {
1681 // Unsigned comparison between two sign-extended values is equivalent
1682 // to unsigned comparison between two zero-extended values.
1684 } else if (NumBits == 8) {
1685 // Try to treat the comparison as unsigned, so that we can use CLI.
1686 // Adjust CCMask and Value as necessary.
1687 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1688 // Test whether the high bit of the byte is set.
1689 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1690 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1691 // Test whether the high bit of the byte is clear.
1692 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1694 // No instruction exists for this combination.
1696 C.ICmpType = SystemZICMP::UnsignedOnly;
1698 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1701 // If the constant is in range, we can use any comparison.
1702 C.ICmpType = SystemZICMP::Any;
1706 // Make sure that the first operand is an i32 of the right extension type.
1707 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1710 if (C.Op0.getValueType() != MVT::i32 ||
1711 Load->getExtensionType() != ExtType)
1712 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
1713 Load->getBasePtr(), Load->getPointerInfo(),
1714 Load->getMemoryVT(), Load->getAlignment(),
1715 Load->getMemOperand()->getFlags());
1717 // Make sure that the second operand is an i32 with the right value.
1718 if (C.Op1.getValueType() != MVT::i32 ||
1719 Value != ConstOp1->getZExtValue())
1720 C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
1723 // Return true if Op is either an unextended load, or a load suitable
1724 // for integer register-memory comparisons of type ICmpType.
1725 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1726 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1728 // There are no instructions to compare a register with a memory byte.
1729 if (Load->getMemoryVT() == MVT::i8)
1731 // Otherwise decide on extension type.
1732 switch (Load->getExtensionType()) {
1733 case ISD::NON_EXTLOAD:
1736 return ICmpType != SystemZICMP::UnsignedOnly;
1738 return ICmpType != SystemZICMP::SignedOnly;
1746 // Return true if it is better to swap the operands of C.
1747 static bool shouldSwapCmpOperands(const Comparison &C) {
1748 // Leave f128 comparisons alone, since they have no memory forms.
1749 if (C.Op0.getValueType() == MVT::f128)
1752 // Always keep a floating-point constant second, since comparisons with
1753 // zero can use LOAD TEST and comparisons with other constants make a
1754 // natural memory operand.
1755 if (isa<ConstantFPSDNode>(C.Op1))
1758 // Never swap comparisons with zero since there are many ways to optimize
1760 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1761 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1764 // Also keep natural memory operands second if the loaded value is
1765 // only used here. Several comparisons have memory forms.
1766 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1769 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1770 // In that case we generally prefer the memory to be second.
1771 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1772 // The only exceptions are when the second operand is a constant and
1773 // we can use things like CHHSI.
1776 // The unsigned memory-immediate instructions can handle 16-bit
1777 // unsigned integers.
1778 if (C.ICmpType != SystemZICMP::SignedOnly &&
1779 isUInt<16>(ConstOp1->getZExtValue()))
1781 // The signed memory-immediate instructions can handle 16-bit
1783 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1784 isInt<16>(ConstOp1->getSExtValue()))
1789 // Try to promote the use of CGFR and CLGFR.
1790 unsigned Opcode0 = C.Op0.getOpcode();
1791 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1793 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1795 if (C.ICmpType != SystemZICMP::SignedOnly &&
1796 Opcode0 == ISD::AND &&
1797 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1798 cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1804 // Return a version of comparison CC mask CCMask in which the LT and GT
1805 // actions are swapped.
1806 static unsigned reverseCCMask(unsigned CCMask) {
1807 return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1808 (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1809 (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1810 (CCMask & SystemZ::CCMASK_CMP_UO));
1813 // Check whether C tests for equality between X and Y and whether X - Y
1814 // or Y - X is also computed. In that case it's better to compare the
1815 // result of the subtraction against zero.
1816 static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL,
1818 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1819 C.CCMask == SystemZ::CCMASK_CMP_NE) {
1820 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1822 if (N->getOpcode() == ISD::SUB &&
1823 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1824 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1825 C.Op0 = SDValue(N, 0);
1826 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
1833 // Check whether C compares a floating-point value with zero and if that
1834 // floating-point value is also negated. In this case we can use the
1835 // negation to set CC, so avoiding separate LOAD AND TEST and
1836 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1837 static void adjustForFNeg(Comparison &C) {
1838 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1839 if (C1 && C1->isZero()) {
1840 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1842 if (N->getOpcode() == ISD::FNEG) {
1843 C.Op0 = SDValue(N, 0);
1844 C.CCMask = reverseCCMask(C.CCMask);
1851 // Check whether C compares (shl X, 32) with 0 and whether X is
1852 // also sign-extended. In that case it is better to test the result
1853 // of the sign extension using LTGFR.
1855 // This case is important because InstCombine transforms a comparison
1856 // with (sext (trunc X)) into a comparison with (shl X, 32).
1857 static void adjustForLTGFR(Comparison &C) {
1858 // Check for a comparison between (shl X, 32) and 0.
1859 if (C.Op0.getOpcode() == ISD::SHL &&
1860 C.Op0.getValueType() == MVT::i64 &&
1861 C.Op1.getOpcode() == ISD::Constant &&
1862 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1863 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
1864 if (C1 && C1->getZExtValue() == 32) {
1865 SDValue ShlOp0 = C.Op0.getOperand(0);
1866 // See whether X has any SIGN_EXTEND_INREG uses.
1867 for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
1869 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1870 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1871 C.Op0 = SDValue(N, 0);
1879 // If C compares the truncation of an extending load, try to compare
1880 // the untruncated value instead. This exposes more opportunities to
1882 static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
1884 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
1885 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
1886 C.Op1.getOpcode() == ISD::Constant &&
1887 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1888 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
1889 if (L->getMemoryVT().getStoreSizeInBits() <= C.Op0.getValueSizeInBits()) {
1890 unsigned Type = L->getExtensionType();
1891 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
1892 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
1893 C.Op0 = C.Op0.getOperand(0);
1894 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
1900 // Return true if shift operation N has an in-range constant shift value.
1901 // Store it in ShiftVal if so.
1902 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1903 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1907 uint64_t Amount = Shift->getZExtValue();
1908 if (Amount >= N.getValueSizeInBits())
1915 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1916 // instruction and whether the CC value is descriptive enough to handle
1917 // a comparison of type Opcode between the AND result and CmpVal.
1918 // CCMask says which comparison result is being tested and BitSize is
1919 // the number of bits in the operands. If TEST UNDER MASK can be used,
1920 // return the corresponding CC mask, otherwise return 0.
1921 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1922 uint64_t Mask, uint64_t CmpVal,
1923 unsigned ICmpType) {
1924 assert(Mask != 0 && "ANDs with zero should have been removed by now");
1926 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1927 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1928 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1931 // Work out the masks for the lowest and highest bits.
1932 unsigned HighShift = 63 - countLeadingZeros(Mask);
1933 uint64_t High = uint64_t(1) << HighShift;
1934 uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1936 // Signed ordered comparisons are effectively unsigned if the sign
1938 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1940 // Check for equality comparisons with 0, or the equivalent.
1942 if (CCMask == SystemZ::CCMASK_CMP_EQ)
1943 return SystemZ::CCMASK_TM_ALL_0;
1944 if (CCMask == SystemZ::CCMASK_CMP_NE)
1945 return SystemZ::CCMASK_TM_SOME_1;
1947 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
1948 if (CCMask == SystemZ::CCMASK_CMP_LT)
1949 return SystemZ::CCMASK_TM_ALL_0;
1950 if (CCMask == SystemZ::CCMASK_CMP_GE)
1951 return SystemZ::CCMASK_TM_SOME_1;
1953 if (EffectivelyUnsigned && CmpVal < Low) {
1954 if (CCMask == SystemZ::CCMASK_CMP_LE)
1955 return SystemZ::CCMASK_TM_ALL_0;
1956 if (CCMask == SystemZ::CCMASK_CMP_GT)
1957 return SystemZ::CCMASK_TM_SOME_1;
1960 // Check for equality comparisons with the mask, or the equivalent.
1961 if (CmpVal == Mask) {
1962 if (CCMask == SystemZ::CCMASK_CMP_EQ)
1963 return SystemZ::CCMASK_TM_ALL_1;
1964 if (CCMask == SystemZ::CCMASK_CMP_NE)
1965 return SystemZ::CCMASK_TM_SOME_0;
1967 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1968 if (CCMask == SystemZ::CCMASK_CMP_GT)
1969 return SystemZ::CCMASK_TM_ALL_1;
1970 if (CCMask == SystemZ::CCMASK_CMP_LE)
1971 return SystemZ::CCMASK_TM_SOME_0;
1973 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1974 if (CCMask == SystemZ::CCMASK_CMP_GE)
1975 return SystemZ::CCMASK_TM_ALL_1;
1976 if (CCMask == SystemZ::CCMASK_CMP_LT)
1977 return SystemZ::CCMASK_TM_SOME_0;
1980 // Check for ordered comparisons with the top bit.
1981 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1982 if (CCMask == SystemZ::CCMASK_CMP_LE)
1983 return SystemZ::CCMASK_TM_MSB_0;
1984 if (CCMask == SystemZ::CCMASK_CMP_GT)
1985 return SystemZ::CCMASK_TM_MSB_1;
1987 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1988 if (CCMask == SystemZ::CCMASK_CMP_LT)
1989 return SystemZ::CCMASK_TM_MSB_0;
1990 if (CCMask == SystemZ::CCMASK_CMP_GE)
1991 return SystemZ::CCMASK_TM_MSB_1;
1994 // If there are just two bits, we can do equality checks for Low and High
1996 if (Mask == Low + High) {
1997 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1998 return SystemZ::CCMASK_TM_MIXED_MSB_0;
1999 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
2000 return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
2001 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
2002 return SystemZ::CCMASK_TM_MIXED_MSB_1;
2003 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
2004 return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
2007 // Looks like we've exhausted our options.
2011 // See whether C can be implemented as a TEST UNDER MASK instruction.
2012 // Update the arguments with the TM version if so.
2013 static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL,
2015 // Check that we have a comparison with a constant.
2016 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2019 uint64_t CmpVal = ConstOp1->getZExtValue();
2021 // Check whether the nonconstant input is an AND with a constant mask.
2024 ConstantSDNode *Mask = nullptr;
2025 if (C.Op0.getOpcode() == ISD::AND) {
2026 NewC.Op0 = C.Op0.getOperand(0);
2027 NewC.Op1 = C.Op0.getOperand(1);
2028 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
2031 MaskVal = Mask->getZExtValue();
2033 // There is no instruction to compare with a 64-bit immediate
2034 // so use TMHH instead if possible. We need an unsigned ordered
2035 // comparison with an i64 immediate.
2036 if (NewC.Op0.getValueType() != MVT::i64 ||
2037 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
2038 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
2039 NewC.ICmpType == SystemZICMP::SignedOnly)
2041 // Convert LE and GT comparisons into LT and GE.
2042 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
2043 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
2044 if (CmpVal == uint64_t(-1))
2047 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2049 // If the low N bits of Op1 are zero than the low N bits of Op0 can
2050 // be masked off without changing the result.
2051 MaskVal = -(CmpVal & -CmpVal);
2052 NewC.ICmpType = SystemZICMP::UnsignedOnly;
2057 // Check whether the combination of mask, comparison value and comparison
2058 // type are suitable.
2059 unsigned BitSize = NewC.Op0.getValueSizeInBits();
2060 unsigned NewCCMask, ShiftVal;
2061 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2062 NewC.Op0.getOpcode() == ISD::SHL &&
2063 isSimpleShift(NewC.Op0, ShiftVal) &&
2064 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2065 MaskVal >> ShiftVal,
2067 SystemZICMP::Any))) {
2068 NewC.Op0 = NewC.Op0.getOperand(0);
2069 MaskVal >>= ShiftVal;
2070 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2071 NewC.Op0.getOpcode() == ISD::SRL &&
2072 isSimpleShift(NewC.Op0, ShiftVal) &&
2073 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2074 MaskVal << ShiftVal,
2076 SystemZICMP::UnsignedOnly))) {
2077 NewC.Op0 = NewC.Op0.getOperand(0);
2078 MaskVal <<= ShiftVal;
2080 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2086 // Go ahead and make the change.
2087 C.Opcode = SystemZISD::TM;
2089 if (Mask && Mask->getZExtValue() == MaskVal)
2090 C.Op1 = SDValue(Mask, 0);
2092 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2093 C.CCValid = SystemZ::CCMASK_TM;
2094 C.CCMask = NewCCMask;
2097 // Return a Comparison that tests the condition-code result of intrinsic
2098 // node Call against constant integer CC using comparison code Cond.
2099 // Opcode is the opcode of the SystemZISD operation for the intrinsic
2100 // and CCValid is the set of possible condition-code results.
2101 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2102 SDValue Call, unsigned CCValid, uint64_t CC,
2103 ISD::CondCode Cond) {
2104 Comparison C(Call, SDValue());
2106 C.CCValid = CCValid;
2107 if (Cond == ISD::SETEQ)
2108 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2109 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2110 else if (Cond == ISD::SETNE)
2111 // ...and the inverse of that.
2112 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2113 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2114 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2115 // always true for CC>3.
2116 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2117 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2118 // ...and the inverse of that.
2119 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2120 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2121 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2122 // always true for CC>3.
2123 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2124 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2125 // ...and the inverse of that.
2126 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2128 llvm_unreachable("Unexpected integer comparison type");
2129 C.CCMask &= CCValid;
2133 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2134 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2135 ISD::CondCode Cond, const SDLoc &DL) {
2136 if (CmpOp1.getOpcode() == ISD::Constant) {
2137 uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2138 unsigned Opcode, CCValid;
2139 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2140 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2141 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2142 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2143 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2144 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2145 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2146 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2148 Comparison C(CmpOp0, CmpOp1);
2149 C.CCMask = CCMaskForCondCode(Cond);
2150 if (C.Op0.getValueType().isFloatingPoint()) {
2151 C.CCValid = SystemZ::CCMASK_FCMP;
2152 C.Opcode = SystemZISD::FCMP;
2155 C.CCValid = SystemZ::CCMASK_ICMP;
2156 C.Opcode = SystemZISD::ICMP;
2157 // Choose the type of comparison. Equality and inequality tests can
2158 // use either signed or unsigned comparisons. The choice also doesn't
2159 // matter if both sign bits are known to be clear. In those cases we
2160 // want to give the main isel code the freedom to choose whichever
2162 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2163 C.CCMask == SystemZ::CCMASK_CMP_NE ||
2164 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2165 C.ICmpType = SystemZICMP::Any;
2166 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2167 C.ICmpType = SystemZICMP::UnsignedOnly;
2169 C.ICmpType = SystemZICMP::SignedOnly;
2170 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2171 adjustZeroCmp(DAG, DL, C);
2172 adjustSubwordCmp(DAG, DL, C);
2173 adjustForSubtraction(DAG, DL, C);
2175 adjustICmpTruncate(DAG, DL, C);
2178 if (shouldSwapCmpOperands(C)) {
2179 std::swap(C.Op0, C.Op1);
2180 C.CCMask = reverseCCMask(C.CCMask);
2183 adjustForTestUnderMask(DAG, DL, C);
2187 // Emit the comparison instruction described by C.
2188 static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2189 if (!C.Op1.getNode()) {
2191 switch (C.Op0.getOpcode()) {
2192 case ISD::INTRINSIC_W_CHAIN:
2193 Op = emitIntrinsicWithChainAndGlue(DAG, C.Op0, C.Opcode);
2195 case ISD::INTRINSIC_WO_CHAIN:
2196 Op = emitIntrinsicWithGlue(DAG, C.Op0, C.Opcode);
2199 llvm_unreachable("Invalid comparison operands");
2201 return SDValue(Op.getNode(), Op->getNumValues() - 1);
2203 if (C.Opcode == SystemZISD::ICMP)
2204 return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
2205 DAG.getConstant(C.ICmpType, DL, MVT::i32));
2206 if (C.Opcode == SystemZISD::TM) {
2207 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2208 bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
2209 return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
2210 DAG.getConstant(RegisterOnly, DL, MVT::i32));
2212 return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
2215 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
2216 // 64 bits. Extend is the extension type to use. Store the high part
2217 // in Hi and the low part in Lo.
2218 static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
2219 SDValue Op0, SDValue Op1, SDValue &Hi,
2221 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2222 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2223 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2224 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2225 DAG.getConstant(32, DL, MVT::i64));
2226 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
2227 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
2230 // Lower a binary operation that produces two VT results, one in each
2231 // half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
2232 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
2233 // on the extended Op0 and (unextended) Op1. Store the even register result
2234 // in Even and the odd register result in Odd.
2235 static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2236 unsigned Extend, unsigned Opcode, SDValue Op0,
2237 SDValue Op1, SDValue &Even, SDValue &Odd) {
2238 SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
2239 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
2240 SDValue(In128, 0), Op1);
2241 bool Is32Bit = is32Bit(VT);
2242 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2243 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2246 // Return an i32 value that is 1 if the CC value produced by Glue is
2247 // in the mask CCMask and 0 otherwise. CC is known to have a value
2248 // in CCValid, so other values can be ignored.
2249 static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue Glue,
2250 unsigned CCValid, unsigned CCMask) {
2251 IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
2252 SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
2254 if (Conversion.XORValue)
2255 Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
2256 DAG.getConstant(Conversion.XORValue, DL, MVT::i32));
2258 if (Conversion.AddValue)
2259 Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
2260 DAG.getConstant(Conversion.AddValue, DL, MVT::i32));
2262 // The SHR/AND sequence should get optimized to an RISBG.
2263 Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
2264 DAG.getConstant(Conversion.Bit, DL, MVT::i32));
2265 if (Conversion.Bit != 31)
2266 Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
2267 DAG.getConstant(1, DL, MVT::i32));
2271 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2272 // be done directly. IsFP is true if CC is for a floating-point rather than
2273 // integer comparison.
2274 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) {
2278 return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE;
2282 return IsFP ? SystemZISD::VFCMPHE : static_cast<SystemZISD::NodeType>(0);
2286 return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH;
2289 return IsFP ? static_cast<SystemZISD::NodeType>(0) : SystemZISD::VICMPHL;
2296 // Return the SystemZISD vector comparison operation for CC or its inverse,
2297 // or 0 if neither can be done directly. Indicate in Invert whether the
2298 // result is for the inverse of CC. IsFP is true if CC is for a
2299 // floating-point rather than integer comparison.
2300 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP,
2302 if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2307 CC = ISD::getSetCCInverse(CC, !IsFP);
2308 if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2316 // Return a v2f64 that contains the extended form of elements Start and Start+1
2317 // of v4f32 value Op.
2318 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
2320 int Mask[] = { Start, -1, Start + 1, -1 };
2321 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2322 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2325 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2326 // producing a result of type VT.
2327 static SDValue getVectorCmp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &DL,
2328 EVT VT, SDValue CmpOp0, SDValue CmpOp1) {
2329 // There is no hardware support for v4f32, so extend the vector into
2330 // two v2f64s and compare those.
2331 if (CmpOp0.getValueType() == MVT::v4f32) {
2332 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0);
2333 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0);
2334 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1);
2335 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1);
2336 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2337 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2338 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2340 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2343 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2344 // an integer mask of type VT.
2345 static SDValue lowerVectorSETCC(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2346 ISD::CondCode CC, SDValue CmpOp0,
2348 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2349 bool Invert = false;
2352 // Handle tests for order using (or (ogt y x) (oge x y)).
2356 assert(IsFP && "Unexpected integer comparison");
2357 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2358 SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1);
2359 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2363 // Handle <> tests using (or (ogt y x) (ogt x y)).
2367 assert(IsFP && "Unexpected integer comparison");
2368 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2369 SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1);
2370 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2374 // Otherwise a single comparison is enough. It doesn't really
2375 // matter whether we try the inversion or the swap first, since
2376 // there are no cases where both work.
2378 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2379 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1);
2381 CC = ISD::getSetCCSwappedOperands(CC);
2382 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2383 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0);
2385 llvm_unreachable("Unhandled comparison");
2390 SDValue Mask = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2391 DAG.getConstant(65535, DL, MVT::i32));
2392 Mask = DAG.getNode(ISD::BITCAST, DL, VT, Mask);
2393 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2398 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2399 SelectionDAG &DAG) const {
2400 SDValue CmpOp0 = Op.getOperand(0);
2401 SDValue CmpOp1 = Op.getOperand(1);
2402 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2404 EVT VT = Op.getValueType();
2406 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2408 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2409 SDValue Glue = emitCmp(DAG, DL, C);
2410 return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2413 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2414 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2415 SDValue CmpOp0 = Op.getOperand(2);
2416 SDValue CmpOp1 = Op.getOperand(3);
2417 SDValue Dest = Op.getOperand(4);
2420 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2421 SDValue Glue = emitCmp(DAG, DL, C);
2422 return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
2423 Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32),
2424 DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, Glue);
2427 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2428 // allowing Pos and Neg to be wider than CmpOp.
2429 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2430 return (Neg.getOpcode() == ISD::SUB &&
2431 Neg.getOperand(0).getOpcode() == ISD::Constant &&
2432 cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2433 Neg.getOperand(1) == Pos &&
2435 (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2436 Pos.getOperand(0) == CmpOp)));
2439 // Return the absolute or negative absolute of Op; IsNegative decides which.
2440 static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op,
2442 Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2444 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2445 DAG.getConstant(0, DL, Op.getValueType()), Op);
2449 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2450 SelectionDAG &DAG) const {
2451 SDValue CmpOp0 = Op.getOperand(0);
2452 SDValue CmpOp1 = Op.getOperand(1);
2453 SDValue TrueOp = Op.getOperand(2);
2454 SDValue FalseOp = Op.getOperand(3);
2455 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2458 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2460 // Check for absolute and negative-absolute selections, including those
2461 // where the comparison value is sign-extended (for LPGFR and LNGFR).
2462 // This check supplements the one in DAGCombiner.
2463 if (C.Opcode == SystemZISD::ICMP &&
2464 C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2465 C.CCMask != SystemZ::CCMASK_CMP_NE &&
2466 C.Op1.getOpcode() == ISD::Constant &&
2467 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2468 if (isAbsolute(C.Op0, TrueOp, FalseOp))
2469 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2470 if (isAbsolute(C.Op0, FalseOp, TrueOp))
2471 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2474 SDValue Glue = emitCmp(DAG, DL, C);
2476 // Special case for handling -1/0 results. The shifts we use here
2477 // should get optimized with the IPM conversion sequence.
2478 auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
2479 auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
2480 if (TrueC && FalseC) {
2481 int64_t TrueVal = TrueC->getSExtValue();
2482 int64_t FalseVal = FalseC->getSExtValue();
2483 if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
2484 // Invert the condition if we want -1 on false.
2486 C.CCMask ^= C.CCValid;
2487 SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2488 EVT VT = Op.getValueType();
2489 // Extend the result to VT. Upper bits are ignored.
2491 Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
2492 // Sign-extend from the low bit.
2493 SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32);
2494 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
2495 return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
2499 SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32),
2500 DAG.getConstant(C.CCMask, DL, MVT::i32), Glue};
2502 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
2503 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
2506 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2507 SelectionDAG &DAG) const {
2509 const GlobalValue *GV = Node->getGlobal();
2510 int64_t Offset = Node->getOffset();
2511 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2512 CodeModel::Model CM = DAG.getTarget().getCodeModel();
2515 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
2516 // Assign anchors at 1<<12 byte boundaries.
2517 uint64_t Anchor = Offset & ~uint64_t(0xfff);
2518 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2519 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2521 // The offset can be folded into the address if it is aligned to a halfword.
2523 if (Offset != 0 && (Offset & 1) == 0) {
2524 SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2525 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2529 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2530 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2531 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2532 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2535 // If there was a non-zero offset that we didn't fold, create an explicit
2538 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2539 DAG.getConstant(Offset, DL, PtrVT));
2544 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2547 SDValue GOTOffset) const {
2549 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2550 SDValue Chain = DAG.getEntryNode();
2553 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
2554 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2555 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
2556 Glue = Chain.getValue(1);
2557 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
2558 Glue = Chain.getValue(1);
2560 // The first call operand is the chain and the second is the TLS symbol.
2561 SmallVector<SDValue, 8> Ops;
2562 Ops.push_back(Chain);
2563 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
2564 Node->getValueType(0),
2567 // Add argument registers to the end of the list so that they are
2568 // known live into the call.
2569 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
2570 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
2572 // Add a register mask operand representing the call-preserved registers.
2573 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2574 const uint32_t *Mask =
2575 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
2576 assert(Mask && "Missing call preserved mask for calling convention");
2577 Ops.push_back(DAG.getRegisterMask(Mask));
2579 // Glue the call to the argument copies.
2580 Ops.push_back(Glue);
2583 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2584 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
2585 Glue = Chain.getValue(1);
2587 // Copy the return value from %r2.
2588 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
2591 SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
2592 SelectionDAG &DAG) const {
2593 SDValue Chain = DAG.getEntryNode();
2594 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2596 // The high part of the thread pointer is in access register 0.
2597 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
2598 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
2600 // The low part of the thread pointer is in access register 1.
2601 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
2602 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
2604 // Merge them into a single 64-bit address.
2605 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
2606 DAG.getConstant(32, DL, PtrVT));
2607 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
2610 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
2611 SelectionDAG &DAG) const {
2612 if (DAG.getTarget().Options.EmulatedTLS)
2613 return LowerToTLSEmulatedModel(Node, DAG);
2615 const GlobalValue *GV = Node->getGlobal();
2616 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2617 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
2619 SDValue TP = lowerThreadPointer(DL, DAG);
2621 // Get the offset of GA from the thread pointer, based on the TLS model.
2624 case TLSModel::GeneralDynamic: {
2625 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
2626 SystemZConstantPoolValue *CPV =
2627 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
2629 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2630 Offset = DAG.getLoad(
2631 PtrVT, DL, DAG.getEntryNode(), Offset,
2632 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2634 // Call __tls_get_offset to retrieve the offset.
2635 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
2639 case TLSModel::LocalDynamic: {
2640 // Load the GOT offset of the module ID.
2641 SystemZConstantPoolValue *CPV =
2642 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
2644 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2645 Offset = DAG.getLoad(
2646 PtrVT, DL, DAG.getEntryNode(), Offset,
2647 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2649 // Call __tls_get_offset to retrieve the module base offset.
2650 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
2652 // Note: The SystemZLDCleanupPass will remove redundant computations
2653 // of the module base offset. Count total number of local-dynamic
2654 // accesses to trigger execution of that pass.
2655 SystemZMachineFunctionInfo* MFI =
2656 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
2657 MFI->incNumLocalDynamicTLSAccesses();
2659 // Add the per-symbol offset.
2660 CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
2662 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
2663 DTPOffset = DAG.getLoad(
2664 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
2665 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2667 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
2671 case TLSModel::InitialExec: {
2672 // Load the offset from the GOT.
2673 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2674 SystemZII::MO_INDNTPOFF);
2675 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
2677 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
2678 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2682 case TLSModel::LocalExec: {
2683 // Force the offset into the constant pool and load it from there.
2684 SystemZConstantPoolValue *CPV =
2685 SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
2687 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2688 Offset = DAG.getLoad(
2689 PtrVT, DL, DAG.getEntryNode(), Offset,
2690 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2695 // Add the base and offset together.
2696 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
2699 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
2700 SelectionDAG &DAG) const {
2702 const BlockAddress *BA = Node->getBlockAddress();
2703 int64_t Offset = Node->getOffset();
2704 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2706 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
2707 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2711 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2712 SelectionDAG &DAG) const {
2714 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2715 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2717 // Use LARL to load the address of the table.
2718 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2721 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2722 SelectionDAG &DAG) const {
2724 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2727 if (CP->isMachineConstantPoolEntry())
2728 Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2729 CP->getAlignment());
2731 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2732 CP->getAlignment(), CP->getOffset());
2734 // Use LARL to load the address of the constant pool entry.
2735 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2738 SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
2739 SelectionDAG &DAG) const {
2740 MachineFunction &MF = DAG.getMachineFunction();
2741 MachineFrameInfo &MFI = MF.getFrameInfo();
2742 MFI.setFrameAddressIsTaken(true);
2745 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2746 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2748 // If the back chain frame index has not been allocated yet, do so.
2749 SystemZMachineFunctionInfo *FI = MF.getInfo<SystemZMachineFunctionInfo>();
2750 int BackChainIdx = FI->getFramePointerSaveIndex();
2751 if (!BackChainIdx) {
2752 // By definition, the frame address is the address of the back chain.
2753 BackChainIdx = MFI.CreateFixedObject(8, -SystemZMC::CallFrameSize, false);
2754 FI->setFramePointerSaveIndex(BackChainIdx);
2756 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
2758 // FIXME The frontend should detect this case.
2760 report_fatal_error("Unsupported stack frame traversal count");
2766 SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
2767 SelectionDAG &DAG) const {
2768 MachineFunction &MF = DAG.getMachineFunction();
2769 MachineFrameInfo &MFI = MF.getFrameInfo();
2770 MFI.setReturnAddressIsTaken(true);
2772 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2776 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2777 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2779 // FIXME The frontend should detect this case.
2781 report_fatal_error("Unsupported stack frame traversal count");
2784 // Return R14D, which has the return address. Mark it an implicit live-in.
2785 unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
2786 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
2789 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2790 SelectionDAG &DAG) const {
2792 SDValue In = Op.getOperand(0);
2793 EVT InVT = In.getValueType();
2794 EVT ResVT = Op.getValueType();
2796 // Convert loads directly. This is normally done by DAGCombiner,
2797 // but we need this case for bitcasts that are created during lowering
2798 // and which are then lowered themselves.
2799 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
2800 if (ISD::isNormalLoad(LoadN))
2801 return DAG.getLoad(ResVT, DL, LoadN->getChain(), LoadN->getBasePtr(),
2802 LoadN->getMemOperand());
2804 if (InVT == MVT::i32 && ResVT == MVT::f32) {
2806 if (Subtarget.hasHighWord()) {
2807 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2809 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2810 MVT::i64, SDValue(U64, 0), In);
2812 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2813 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2814 DAG.getConstant(32, DL, MVT::i64));
2816 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2817 return DAG.getTargetExtractSubreg(SystemZ::subreg_r32,
2818 DL, MVT::f32, Out64);
2820 if (InVT == MVT::f32 && ResVT == MVT::i32) {
2821 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2822 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_r32, DL,
2823 MVT::f64, SDValue(U64, 0), In);
2824 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2825 if (Subtarget.hasHighWord())
2826 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2828 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2829 DAG.getConstant(32, DL, MVT::i64));
2830 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2832 llvm_unreachable("Unexpected bitcast combination");
2835 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2836 SelectionDAG &DAG) const {
2837 MachineFunction &MF = DAG.getMachineFunction();
2838 SystemZMachineFunctionInfo *FuncInfo =
2839 MF.getInfo<SystemZMachineFunctionInfo>();
2840 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2842 SDValue Chain = Op.getOperand(0);
2843 SDValue Addr = Op.getOperand(1);
2844 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2847 // The initial values of each field.
2848 const unsigned NumFields = 4;
2849 SDValue Fields[NumFields] = {
2850 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
2851 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
2852 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2853 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2856 // Store each field into its respective slot.
2857 SDValue MemOps[NumFields];
2858 unsigned Offset = 0;
2859 for (unsigned I = 0; I < NumFields; ++I) {
2860 SDValue FieldAddr = Addr;
2862 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
2863 DAG.getIntPtrConstant(Offset, DL));
2864 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
2865 MachinePointerInfo(SV, Offset));
2868 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2871 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
2872 SelectionDAG &DAG) const {
2873 SDValue Chain = Op.getOperand(0);
2874 SDValue DstPtr = Op.getOperand(1);
2875 SDValue SrcPtr = Op.getOperand(2);
2876 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2877 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
2880 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
2881 /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
2882 /*isTailCall*/false,
2883 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
2886 SDValue SystemZTargetLowering::
2887 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
2888 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
2889 MachineFunction &MF = DAG.getMachineFunction();
2890 bool RealignOpt = !MF.getFunction()-> hasFnAttribute("no-realign-stack");
2891 bool StoreBackchain = MF.getFunction()->hasFnAttribute("backchain");
2893 SDValue Chain = Op.getOperand(0);
2894 SDValue Size = Op.getOperand(1);
2895 SDValue Align = Op.getOperand(2);
2898 // If user has set the no alignment function attribute, ignore
2899 // alloca alignments.
2900 uint64_t AlignVal = (RealignOpt ?
2901 dyn_cast<ConstantSDNode>(Align)->getZExtValue() : 0);
2903 uint64_t StackAlign = TFI->getStackAlignment();
2904 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
2905 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
2907 unsigned SPReg = getStackPointerRegisterToSaveRestore();
2908 SDValue NeededSpace = Size;
2910 // Get a reference to the stack pointer.
2911 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
2913 // If we need a backchain, save it now.
2916 Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
2918 // Add extra space for alignment if needed.
2919 if (ExtraAlignSpace)
2920 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
2921 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
2923 // Get the new stack pointer value.
2924 SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
2926 // Copy the new stack pointer back.
2927 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
2929 // The allocated data lives above the 160 bytes allocated for the standard
2930 // frame, plus any outgoing stack arguments. We don't know how much that
2931 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
2932 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2933 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
2935 // Dynamically realign if needed.
2936 if (RequiredAlign > StackAlign) {
2938 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
2939 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
2941 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
2942 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
2946 Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
2948 SDValue Ops[2] = { Result, Chain };
2949 return DAG.getMergeValues(Ops, DL);
2952 SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
2953 SDValue Op, SelectionDAG &DAG) const {
2956 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2959 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
2960 SelectionDAG &DAG) const {
2961 EVT VT = Op.getValueType();
2965 // Just do a normal 64-bit multiplication and extract the results.
2966 // We define this so that it can be used for constant division.
2967 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
2968 Op.getOperand(1), Ops[1], Ops[0]);
2970 // Do a full 128-bit multiplication based on UMUL_LOHI64:
2972 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
2974 // but using the fact that the upper halves are either all zeros
2977 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
2979 // and grouping the right terms together since they are quicker than the
2982 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
2983 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
2984 SDValue LL = Op.getOperand(0);
2985 SDValue RL = Op.getOperand(1);
2986 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
2987 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
2988 // UMUL_LOHI64 returns the low result in the odd register and the high
2989 // result in the even register. SMUL_LOHI is defined to return the
2990 // low half first, so the results are in reverse order.
2991 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2992 LL, RL, Ops[1], Ops[0]);
2993 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
2994 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
2995 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
2996 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
2998 return DAG.getMergeValues(Ops, DL);
3001 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
3002 SelectionDAG &DAG) const {
3003 EVT VT = Op.getValueType();
3007 // Just do a normal 64-bit multiplication and extract the results.
3008 // We define this so that it can be used for constant division.
3009 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
3010 Op.getOperand(1), Ops[1], Ops[0]);
3012 // UMUL_LOHI64 returns the low result in the odd register and the high
3013 // result in the even register. UMUL_LOHI is defined to return the
3014 // low half first, so the results are in reverse order.
3015 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
3016 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3017 return DAG.getMergeValues(Ops, DL);
3020 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
3021 SelectionDAG &DAG) const {
3022 SDValue Op0 = Op.getOperand(0);
3023 SDValue Op1 = Op.getOperand(1);
3024 EVT VT = Op.getValueType();
3028 // We use DSGF for 32-bit division.
3030 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
3031 Opcode = SystemZISD::SDIVREM32;
3032 } else if (DAG.ComputeNumSignBits(Op1) > 32) {
3033 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
3034 Opcode = SystemZISD::SDIVREM32;
3036 Opcode = SystemZISD::SDIVREM64;
3038 // DSG(F) takes a 64-bit dividend, so the even register in the GR128
3039 // input is "don't care". The instruction returns the remainder in
3040 // the even register and the quotient in the odd register.
3042 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
3043 Op0, Op1, Ops[1], Ops[0]);
3044 return DAG.getMergeValues(Ops, DL);
3047 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
3048 SelectionDAG &DAG) const {
3049 EVT VT = Op.getValueType();
3052 // DL(G) uses a double-width dividend, so we need to clear the even
3053 // register in the GR128 input. The instruction returns the remainder
3054 // in the even register and the quotient in the odd register.
3057 lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
3058 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3060 lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
3061 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3062 return DAG.getMergeValues(Ops, DL);
3065 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
3066 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
3068 // Get the known-zero masks for each operand.
3069 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
3071 DAG.computeKnownBits(Ops[0], Known[0]);
3072 DAG.computeKnownBits(Ops[1], Known[1]);
3074 // See if the upper 32 bits of one operand and the lower 32 bits of the
3075 // other are known zero. They are the low and high operands respectively.
3076 uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
3077 Known[1].Zero.getZExtValue() };
3079 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
3081 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
3086 SDValue LowOp = Ops[Low];
3087 SDValue HighOp = Ops[High];
3089 // If the high part is a constant, we're better off using IILH.
3090 if (HighOp.getOpcode() == ISD::Constant)
3093 // If the low part is a constant that is outside the range of LHI,
3094 // then we're better off using IILF.
3095 if (LowOp.getOpcode() == ISD::Constant) {
3096 int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
3097 if (!isInt<16>(Value))
3101 // Check whether the high part is an AND that doesn't change the
3102 // high 32 bits and just masks out low bits. We can skip it if so.
3103 if (HighOp.getOpcode() == ISD::AND &&
3104 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
3105 SDValue HighOp0 = HighOp.getOperand(0);
3106 uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
3107 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
3111 // Take advantage of the fact that all GR32 operations only change the
3112 // low 32 bits by truncating Low to an i32 and inserting it directly
3113 // using a subreg. The interesting cases are those where the truncation
3116 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
3117 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
3118 MVT::i64, HighOp, Low32);
3121 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
3122 SelectionDAG &DAG) const {
3123 EVT VT = Op.getValueType();
3125 Op = Op.getOperand(0);
3127 // Handle vector types via VPOPCT.
3128 if (VT.isVector()) {
3129 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
3130 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
3131 switch (VT.getScalarSizeInBits()) {
3135 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
3136 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
3137 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
3138 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3139 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
3143 SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3144 DAG.getConstant(0, DL, MVT::i32));
3145 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3149 SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3150 DAG.getConstant(0, DL, MVT::i32));
3151 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
3152 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3156 llvm_unreachable("Unexpected type");
3161 // Get the known-zero mask for the operand.
3163 DAG.computeKnownBits(Op, Known);
3164 unsigned NumSignificantBits = (~Known.Zero).getActiveBits();
3165 if (NumSignificantBits == 0)
3166 return DAG.getConstant(0, DL, VT);
3168 // Skip known-zero high parts of the operand.
3169 int64_t OrigBitSize = VT.getSizeInBits();
3170 int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
3171 BitSize = std::min(BitSize, OrigBitSize);
3173 // The POPCNT instruction counts the number of bits in each byte.
3174 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
3175 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
3176 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
3178 // Add up per-byte counts in a binary tree. All bits of Op at
3179 // position larger than BitSize remain zero throughout.
3180 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
3181 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
3182 if (BitSize != OrigBitSize)
3183 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
3184 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
3185 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3188 // Extract overall result from high byte.
3190 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
3191 DAG.getConstant(BitSize - 8, DL, VT));
3196 SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
3197 SelectionDAG &DAG) const {
3199 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
3200 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
3201 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
3202 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
3204 // The only fence that needs an instruction is a sequentially-consistent
3205 // cross-thread fence.
3206 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
3207 FenceScope == CrossThread) {
3208 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
3213 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
3214 return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
3217 // Op is an atomic load. Lower it into a normal volatile load.
3218 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
3219 SelectionDAG &DAG) const {
3220 auto *Node = cast<AtomicSDNode>(Op.getNode());
3221 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
3222 Node->getChain(), Node->getBasePtr(),
3223 Node->getMemoryVT(), Node->getMemOperand());
3226 // Op is an atomic store. Lower it into a normal volatile store followed
3227 // by a serialization.
3228 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
3229 SelectionDAG &DAG) const {
3230 auto *Node = cast<AtomicSDNode>(Op.getNode());
3231 SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
3232 Node->getBasePtr(), Node->getMemoryVT(),
3233 Node->getMemOperand());
3234 return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
3238 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
3239 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
3240 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
3242 unsigned Opcode) const {
3243 auto *Node = cast<AtomicSDNode>(Op.getNode());
3245 // 32-bit operations need no code outside the main loop.
3246 EVT NarrowVT = Node->getMemoryVT();
3247 EVT WideVT = MVT::i32;
3248 if (NarrowVT == WideVT)
3251 int64_t BitSize = NarrowVT.getSizeInBits();
3252 SDValue ChainIn = Node->getChain();
3253 SDValue Addr = Node->getBasePtr();
3254 SDValue Src2 = Node->getVal();
3255 MachineMemOperand *MMO = Node->getMemOperand();
3257 EVT PtrVT = Addr.getValueType();
3259 // Convert atomic subtracts of constants into additions.
3260 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
3261 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
3262 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
3263 Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
3266 // Get the address of the containing word.
3267 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3268 DAG.getConstant(-4, DL, PtrVT));
3270 // Get the number of bits that the word must be rotated left in order
3271 // to bring the field to the top bits of a GR32.
3272 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3273 DAG.getConstant(3, DL, PtrVT));
3274 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3276 // Get the complementing shift amount, for rotating a field in the top
3277 // bits back to its proper position.
3278 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3279 DAG.getConstant(0, DL, WideVT), BitShift);
3281 // Extend the source operand to 32 bits and prepare it for the inner loop.
3282 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
3283 // operations require the source to be shifted in advance. (This shift
3284 // can be folded if the source is constant.) For AND and NAND, the lower
3285 // bits must be set, while for other opcodes they should be left clear.
3286 if (Opcode != SystemZISD::ATOMIC_SWAPW)
3287 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
3288 DAG.getConstant(32 - BitSize, DL, WideVT));
3289 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
3290 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
3291 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
3292 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
3294 // Construct the ATOMIC_LOADW_* node.
3295 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3296 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
3297 DAG.getConstant(BitSize, DL, WideVT) };
3298 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
3301 // Rotate the result of the final CS so that the field is in the lower
3302 // bits of a GR32, then truncate it.
3303 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
3304 DAG.getConstant(BitSize, DL, WideVT));
3305 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
3307 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
3308 return DAG.getMergeValues(RetOps, DL);
3311 // Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations
3312 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
3313 // operations into additions.
3314 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
3315 SelectionDAG &DAG) const {
3316 auto *Node = cast<AtomicSDNode>(Op.getNode());
3317 EVT MemVT = Node->getMemoryVT();
3318 if (MemVT == MVT::i32 || MemVT == MVT::i64) {
3319 // A full-width operation.
3320 assert(Op.getValueType() == MemVT && "Mismatched VTs");
3321 SDValue Src2 = Node->getVal();
3325 if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
3326 // Use an addition if the operand is constant and either LAA(G) is
3327 // available or the negative value is in the range of A(G)FHI.
3328 int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
3329 if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
3330 NegSrc2 = DAG.getConstant(Value, DL, MemVT);
3331 } else if (Subtarget.hasInterlockedAccess1())
3332 // Use LAA(G) if available.
3333 NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
3336 if (NegSrc2.getNode())
3337 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
3338 Node->getChain(), Node->getBasePtr(), NegSrc2,
3339 Node->getMemOperand());
3341 // Use the node as-is.
3345 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
3348 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation. Lower the first two
3349 // into a fullword ATOMIC_CMP_SWAPW operation.
3350 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
3351 SelectionDAG &DAG) const {
3352 auto *Node = cast<AtomicSDNode>(Op.getNode());
3354 // We have native support for 32-bit compare and swap.
3355 EVT NarrowVT = Node->getMemoryVT();
3356 EVT WideVT = MVT::i32;
3357 if (NarrowVT == WideVT)
3360 int64_t BitSize = NarrowVT.getSizeInBits();
3361 SDValue ChainIn = Node->getOperand(0);
3362 SDValue Addr = Node->getOperand(1);
3363 SDValue CmpVal = Node->getOperand(2);
3364 SDValue SwapVal = Node->getOperand(3);
3365 MachineMemOperand *MMO = Node->getMemOperand();
3367 EVT PtrVT = Addr.getValueType();
3369 // Get the address of the containing word.
3370 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3371 DAG.getConstant(-4, DL, PtrVT));
3373 // Get the number of bits that the word must be rotated left in order
3374 // to bring the field to the top bits of a GR32.
3375 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3376 DAG.getConstant(3, DL, PtrVT));
3377 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3379 // Get the complementing shift amount, for rotating a field in the top
3380 // bits back to its proper position.
3381 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3382 DAG.getConstant(0, DL, WideVT), BitShift);
3384 // Construct the ATOMIC_CMP_SWAPW node.
3385 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3386 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
3387 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
3388 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
3389 VTList, Ops, NarrowVT, MMO);
3393 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
3394 SelectionDAG &DAG) const {
3395 MachineFunction &MF = DAG.getMachineFunction();
3396 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3397 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
3398 SystemZ::R15D, Op.getValueType());
3401 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
3402 SelectionDAG &DAG) const {
3403 MachineFunction &MF = DAG.getMachineFunction();
3404 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3405 bool StoreBackchain = MF.getFunction()->hasFnAttribute("backchain");
3407 SDValue Chain = Op.getOperand(0);
3408 SDValue NewSP = Op.getOperand(1);
3412 if (StoreBackchain) {
3413 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, MVT::i64);
3414 Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
3417 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R15D, NewSP);
3420 Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
3425 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
3426 SelectionDAG &DAG) const {
3427 bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3429 // Just preserve the chain.
3430 return Op.getOperand(0);
3433 bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3434 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
3435 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
3438 DAG.getConstant(Code, DL, MVT::i32),
3441 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
3442 Node->getVTList(), Ops,
3443 Node->getMemoryVT(), Node->getMemOperand());
3446 // Return an i32 that contains the value of CC immediately after After,
3447 // whose final operand must be MVT::Glue.
3448 static SDValue getCCResult(SelectionDAG &DAG, SDNode *After) {
3450 SDValue Glue = SDValue(After, After->getNumValues() - 1);
3451 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
3452 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
3453 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
3457 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
3458 SelectionDAG &DAG) const {
3459 unsigned Opcode, CCValid;
3460 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
3461 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
3462 SDValue Glued = emitIntrinsicWithChainAndGlue(DAG, Op, Opcode);
3463 SDValue CC = getCCResult(DAG, Glued.getNode());
3464 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
3472 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
3473 SelectionDAG &DAG) const {
3474 unsigned Opcode, CCValid;
3475 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
3476 SDValue Glued = emitIntrinsicWithGlue(DAG, Op, Opcode);
3477 SDValue CC = getCCResult(DAG, Glued.getNode());
3478 if (Op->getNumValues() == 1)
3480 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
3481 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(), Glued,
3485 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3487 case Intrinsic::thread_pointer:
3488 return lowerThreadPointer(SDLoc(Op), DAG);
3490 case Intrinsic::s390_vpdi:
3491 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
3492 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3494 case Intrinsic::s390_vperm:
3495 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
3496 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3498 case Intrinsic::s390_vuphb:
3499 case Intrinsic::s390_vuphh:
3500 case Intrinsic::s390_vuphf:
3501 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
3504 case Intrinsic::s390_vuplhb:
3505 case Intrinsic::s390_vuplhh:
3506 case Intrinsic::s390_vuplhf:
3507 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
3510 case Intrinsic::s390_vuplb:
3511 case Intrinsic::s390_vuplhw:
3512 case Intrinsic::s390_vuplf:
3513 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
3516 case Intrinsic::s390_vupllb:
3517 case Intrinsic::s390_vupllh:
3518 case Intrinsic::s390_vupllf:
3519 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
3522 case Intrinsic::s390_vsumb:
3523 case Intrinsic::s390_vsumh:
3524 case Intrinsic::s390_vsumgh:
3525 case Intrinsic::s390_vsumgf:
3526 case Intrinsic::s390_vsumqf:
3527 case Intrinsic::s390_vsumqg:
3528 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
3529 Op.getOperand(1), Op.getOperand(2));
3536 // Says that SystemZISD operation Opcode can be used to perform the equivalent
3537 // of a VPERM with permute vector Bytes. If Opcode takes three operands,
3538 // Operand is the constant third operand, otherwise it is the number of
3539 // bytes in each element of the result.
3543 unsigned char Bytes[SystemZ::VectorBytes];
3547 static const Permute PermuteForms[] = {
3549 { SystemZISD::MERGE_HIGH, 8,
3550 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
3552 { SystemZISD::MERGE_HIGH, 4,
3553 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
3555 { SystemZISD::MERGE_HIGH, 2,
3556 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
3558 { SystemZISD::MERGE_HIGH, 1,
3559 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
3561 { SystemZISD::MERGE_LOW, 8,
3562 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
3564 { SystemZISD::MERGE_LOW, 4,
3565 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
3567 { SystemZISD::MERGE_LOW, 2,
3568 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
3570 { SystemZISD::MERGE_LOW, 1,
3571 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
3573 { SystemZISD::PACK, 4,
3574 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
3576 { SystemZISD::PACK, 2,
3577 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
3579 { SystemZISD::PACK, 1,
3580 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
3581 // VPDI V1, V2, 4 (low half of V1, high half of V2)
3582 { SystemZISD::PERMUTE_DWORDS, 4,
3583 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
3584 // VPDI V1, V2, 1 (high half of V1, low half of V2)
3585 { SystemZISD::PERMUTE_DWORDS, 1,
3586 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
3589 // Called after matching a vector shuffle against a particular pattern.
3590 // Both the original shuffle and the pattern have two vector operands.
3591 // OpNos[0] is the operand of the original shuffle that should be used for
3592 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
3593 // OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
3594 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
3595 // for operands 0 and 1 of the pattern.
3596 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
3600 OpNo0 = OpNo1 = OpNos[1];
3601 } else if (OpNos[1] < 0) {
3602 OpNo0 = OpNo1 = OpNos[0];
3610 // Bytes is a VPERM-like permute vector, except that -1 is used for
3611 // undefined bytes. Return true if the VPERM can be implemented using P.
3612 // When returning true set OpNo0 to the VPERM operand that should be
3613 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
3615 // For example, if swapping the VPERM operands allows P to match, OpNo0
3616 // will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
3617 // operand, but rewriting it to use two duplicated operands allows it to
3618 // match P, then OpNo0 and OpNo1 will be the same.
3619 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
3620 unsigned &OpNo0, unsigned &OpNo1) {
3621 int OpNos[] = { -1, -1 };
3622 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
3625 // Make sure that the two permute vectors use the same suboperand
3626 // byte number. Only the operand numbers (the high bits) are
3627 // allowed to differ.
3628 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
3630 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
3631 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
3632 // Make sure that the operand mappings are consistent with previous
3634 if (OpNos[ModelOpNo] == 1 - RealOpNo)
3636 OpNos[ModelOpNo] = RealOpNo;
3639 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3642 // As above, but search for a matching permute.
3643 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
3644 unsigned &OpNo0, unsigned &OpNo1) {
3645 for (auto &P : PermuteForms)
3646 if (matchPermute(Bytes, P, OpNo0, OpNo1))
3651 // Bytes is a VPERM-like permute vector, except that -1 is used for
3652 // undefined bytes. This permute is an operand of an outer permute.
3653 // See whether redistributing the -1 bytes gives a shuffle that can be
3654 // implemented using P. If so, set Transform to a VPERM-like permute vector
3655 // that, when applied to the result of P, gives the original permute in Bytes.
3656 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3658 SmallVectorImpl<int> &Transform) {
3660 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
3661 int Elt = Bytes[From];
3663 // Byte number From of the result is undefined.
3664 Transform[From] = -1;
3666 while (P.Bytes[To] != Elt) {
3668 if (To == SystemZ::VectorBytes)
3671 Transform[From] = To;
3677 // As above, but search for a matching permute.
3678 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3679 SmallVectorImpl<int> &Transform) {
3680 for (auto &P : PermuteForms)
3681 if (matchDoublePermute(Bytes, P, Transform))
3686 // Convert the mask of the given VECTOR_SHUFFLE into a byte-level mask,
3687 // as if it had type vNi8.
3688 static void getVPermMask(ShuffleVectorSDNode *VSN,
3689 SmallVectorImpl<int> &Bytes) {
3690 EVT VT = VSN->getValueType(0);
3691 unsigned NumElements = VT.getVectorNumElements();
3692 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3693 Bytes.resize(NumElements * BytesPerElement, -1);
3694 for (unsigned I = 0; I < NumElements; ++I) {
3695 int Index = VSN->getMaskElt(I);
3697 for (unsigned J = 0; J < BytesPerElement; ++J)
3698 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
3702 // Bytes is a VPERM-like permute vector, except that -1 is used for
3703 // undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
3704 // the result come from a contiguous sequence of bytes from one input.
3705 // Set Base to the selector for the first byte if so.
3706 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
3707 unsigned BytesPerElement, int &Base) {
3709 for (unsigned I = 0; I < BytesPerElement; ++I) {
3710 if (Bytes[Start + I] >= 0) {
3711 unsigned Elem = Bytes[Start + I];
3714 // Make sure the bytes would come from one input operand.
3715 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
3717 } else if (unsigned(Base) != Elem - I)
3724 // Bytes is a VPERM-like permute vector, except that -1 is used for
3725 // undefined bytes. Return true if it can be performed using VSLDI.
3726 // When returning true, set StartIndex to the shift amount and OpNo0
3727 // and OpNo1 to the VPERM operands that should be used as the first
3728 // and second shift operand respectively.
3729 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
3730 unsigned &StartIndex, unsigned &OpNo0,
3732 int OpNos[] = { -1, -1 };
3734 for (unsigned I = 0; I < 16; ++I) {
3735 int Index = Bytes[I];
3737 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
3738 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
3739 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
3741 Shift = ExpectedShift;
3742 else if (Shift != ExpectedShift)
3744 // Make sure that the operand mappings are consistent with previous
3746 if (OpNos[ModelOpNo] == 1 - RealOpNo)
3748 OpNos[ModelOpNo] = RealOpNo;
3752 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3755 // Create a node that performs P on operands Op0 and Op1, casting the
3756 // operands to the appropriate type. The type of the result is determined by P.
3757 static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
3758 const Permute &P, SDValue Op0, SDValue Op1) {
3759 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
3760 // elements of a PACK are twice as wide as the outputs.
3761 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
3762 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
3764 // Cast both operands to the appropriate type.
3765 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
3766 SystemZ::VectorBytes / InBytes);
3767 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
3768 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
3770 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
3771 SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32);
3772 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
3773 } else if (P.Opcode == SystemZISD::PACK) {
3774 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
3775 SystemZ::VectorBytes / P.Operand);
3776 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
3778 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
3783 // Bytes is a VPERM-like permute vector, except that -1 is used for
3784 // undefined bytes. Implement it on operands Ops[0] and Ops[1] using
3786 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
3788 const SmallVectorImpl<int> &Bytes) {
3789 for (unsigned I = 0; I < 2; ++I)
3790 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
3792 // First see whether VSLDI can be used.
3793 unsigned StartIndex, OpNo0, OpNo1;
3794 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
3795 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
3796 Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32));
3798 // Fall back on VPERM. Construct an SDNode for the permute vector.
3799 SDValue IndexNodes[SystemZ::VectorBytes];
3800 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3802 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
3804 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
3805 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
3806 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
3810 // Describes a general N-operand vector shuffle.
3811 struct GeneralShuffle {
3812 GeneralShuffle(EVT vt) : VT(vt) {}
3814 bool add(SDValue, unsigned);
3815 SDValue getNode(SelectionDAG &, const SDLoc &);
3817 // The operands of the shuffle.
3818 SmallVector<SDValue, SystemZ::VectorBytes> Ops;
3820 // Index I is -1 if byte I of the result is undefined. Otherwise the
3821 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
3822 // Bytes[I] / SystemZ::VectorBytes.
3823 SmallVector<int, SystemZ::VectorBytes> Bytes;
3825 // The type of the shuffle result.
3830 // Add an extra undefined element to the shuffle.
3831 void GeneralShuffle::addUndef() {
3832 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3833 for (unsigned I = 0; I < BytesPerElement; ++I)
3834 Bytes.push_back(-1);
3837 // Add an extra element to the shuffle, taking it from element Elem of Op.
3838 // A null Op indicates a vector input whose value will be calculated later;
3839 // there is at most one such input per shuffle and it always has the same
3840 // type as the result. Aborts and returns false if the source vector elements
3841 // of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
3842 // LLVM they become implicitly extended, but this is rare and not optimized.
3843 bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
3844 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3846 // The source vector can have wider elements than the result,
3847 // either through an explicit TRUNCATE or because of type legalization.
3848 // We want the least significant part.
3849 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
3850 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
3852 // Return false if the source elements are smaller than their destination
3854 if (FromBytesPerElement < BytesPerElement)
3857 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
3858 (FromBytesPerElement - BytesPerElement));
3860 // Look through things like shuffles and bitcasts.
3861 while (Op.getNode()) {
3862 if (Op.getOpcode() == ISD::BITCAST)
3863 Op = Op.getOperand(0);
3864 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
3865 // See whether the bytes we need come from a contiguous part of one
3867 SmallVector<int, SystemZ::VectorBytes> OpBytes;
3868 getVPermMask(cast<ShuffleVectorSDNode>(Op), OpBytes);
3870 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
3876 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
3877 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
3878 } else if (Op.isUndef()) {
3885 // Make sure that the source of the extraction is in Ops.
3887 for (; OpNo < Ops.size(); ++OpNo)
3888 if (Ops[OpNo] == Op)
3890 if (OpNo == Ops.size())
3893 // Add the element to Bytes.
3894 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
3895 for (unsigned I = 0; I < BytesPerElement; ++I)
3896 Bytes.push_back(Base + I);
3901 // Return SDNodes for the completed shuffle.
3902 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
3903 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
3905 if (Ops.size() == 0)
3906 return DAG.getUNDEF(VT);
3908 // Make sure that there are at least two shuffle operands.
3909 if (Ops.size() == 1)
3910 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
3912 // Create a tree of shuffles, deferring root node until after the loop.
3913 // Try to redistribute the undefined elements of non-root nodes so that
3914 // the non-root shuffles match something like a pack or merge, then adjust
3915 // the parent node's permute vector to compensate for the new order.
3916 // Among other things, this copes with vectors like <2 x i16> that were
3917 // padded with undefined elements during type legalization.
3919 // In the best case this redistribution will lead to the whole tree
3920 // using packs and merges. It should rarely be a loss in other cases.
3921 unsigned Stride = 1;
3922 for (; Stride * 2 < Ops.size(); Stride *= 2) {
3923 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
3924 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
3926 // Create a mask for just these two operands.
3927 SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
3928 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3929 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
3930 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
3933 else if (OpNo == I + Stride)
3934 NewBytes[J] = SystemZ::VectorBytes + Byte;
3938 // See if it would be better to reorganize NewMask to avoid using VPERM.
3939 SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
3940 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
3941 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
3942 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
3943 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3944 if (NewBytes[J] >= 0) {
3945 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
3946 "Invalid double permute");
3947 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
3949 assert(NewBytesMap[J] < 0 && "Invalid double permute");
3952 // Just use NewBytes on the operands.
3953 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
3954 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
3955 if (NewBytes[J] >= 0)
3956 Bytes[J] = I * SystemZ::VectorBytes + J;
3961 // Now we just have 2 inputs. Put the second operand in Ops[1].
3963 Ops[1] = Ops[Stride];
3964 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3965 if (Bytes[I] >= int(SystemZ::VectorBytes))
3966 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
3969 // Look for an instruction that can do the permute without resorting
3971 unsigned OpNo0, OpNo1;
3973 if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
3974 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
3976 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
3977 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3980 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
3981 static bool isScalarToVector(SDValue Op) {
3982 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
3983 if (!Op.getOperand(I).isUndef())
3988 // Return a vector of type VT that contains Value in the first element.
3989 // The other elements don't matter.
3990 static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3992 // If we have a constant, replicate it to all elements and let the
3993 // BUILD_VECTOR lowering take care of it.
3994 if (Value.getOpcode() == ISD::Constant ||
3995 Value.getOpcode() == ISD::ConstantFP) {
3996 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
3997 return DAG.getBuildVector(VT, DL, Ops);
3999 if (Value.isUndef())
4000 return DAG.getUNDEF(VT);
4001 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
4004 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
4005 // element 1. Used for cases in which replication is cheap.
4006 static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4007 SDValue Op0, SDValue Op1) {
4008 if (Op0.isUndef()) {
4010 return DAG.getUNDEF(VT);
4011 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
4014 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
4015 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
4016 buildScalarToVector(DAG, DL, VT, Op0),
4017 buildScalarToVector(DAG, DL, VT, Op1));
4020 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
4022 static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0,
4024 if (Op0.isUndef() && Op1.isUndef())
4025 return DAG.getUNDEF(MVT::v2i64);
4026 // If one of the two inputs is undefined then replicate the other one,
4027 // in order to avoid using another register unnecessarily.
4029 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4030 else if (Op1.isUndef())
4031 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4033 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4034 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4036 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
4039 // Try to represent constant BUILD_VECTOR node BVN using a
4040 // SystemZISD::BYTE_MASK-style mask. Store the mask value in Mask
4042 static bool tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) {
4043 EVT ElemVT = BVN->getValueType(0).getVectorElementType();
4044 unsigned BytesPerElement = ElemVT.getStoreSize();
4045 for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) {
4046 SDValue Op = BVN->getOperand(I);
4047 if (!Op.isUndef()) {
4049 if (Op.getOpcode() == ISD::Constant)
4050 Value = dyn_cast<ConstantSDNode>(Op)->getZExtValue();
4051 else if (Op.getOpcode() == ISD::ConstantFP)
4052 Value = (dyn_cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()
4056 for (unsigned J = 0; J < BytesPerElement; ++J) {
4057 uint64_t Byte = (Value >> (J * 8)) & 0xff;
4059 Mask |= 1ULL << ((E - I - 1) * BytesPerElement + J);
4068 // Try to load a vector constant in which BitsPerElement-bit value Value
4069 // is replicated to fill the vector. VT is the type of the resulting
4070 // constant, which may have elements of a different size from BitsPerElement.
4071 // Return the SDValue of the constant on success, otherwise return
4073 static SDValue tryBuildVectorReplicate(SelectionDAG &DAG,
4074 const SystemZInstrInfo *TII,
4075 const SDLoc &DL, EVT VT, uint64_t Value,
4076 unsigned BitsPerElement) {
4077 // Signed 16-bit values can be replicated using VREPI.
4078 int64_t SignedValue = SignExtend64(Value, BitsPerElement);
4079 if (isInt<16>(SignedValue)) {
4080 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4081 SystemZ::VectorBits / BitsPerElement);
4082 SDValue Op = DAG.getNode(SystemZISD::REPLICATE, DL, VecVT,
4083 DAG.getConstant(SignedValue, DL, MVT::i32));
4084 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4086 // See whether rotating the constant left some N places gives a value that
4087 // is one less than a power of 2 (i.e. all zeros followed by all ones).
4088 // If so we can use VGM.
4089 unsigned Start, End;
4090 if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) {
4091 // isRxSBGMask returns the bit numbers for a full 64-bit value,
4092 // with 0 denoting 1 << 63 and 63 denoting 1. Convert them to
4093 // bit numbers for an BitsPerElement value, so that 0 denotes
4094 // 1 << (BitsPerElement-1).
4095 Start -= 64 - BitsPerElement;
4096 End -= 64 - BitsPerElement;
4097 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4098 SystemZ::VectorBits / BitsPerElement);
4099 SDValue Op = DAG.getNode(SystemZISD::ROTATE_MASK, DL, VecVT,
4100 DAG.getConstant(Start, DL, MVT::i32),
4101 DAG.getConstant(End, DL, MVT::i32));
4102 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4107 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
4108 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
4109 // the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
4110 // would benefit from this representation and return it if so.
4111 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
4112 BuildVectorSDNode *BVN) {
4113 EVT VT = BVN->getValueType(0);
4114 unsigned NumElements = VT.getVectorNumElements();
4116 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
4117 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
4118 // need a BUILD_VECTOR, add an additional placeholder operand for that
4119 // BUILD_VECTOR and store its operands in ResidueOps.
4120 GeneralShuffle GS(VT);
4121 SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
4122 bool FoundOne = false;
4123 for (unsigned I = 0; I < NumElements; ++I) {
4124 SDValue Op = BVN->getOperand(I);
4125 if (Op.getOpcode() == ISD::TRUNCATE)
4126 Op = Op.getOperand(0);
4127 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4128 Op.getOperand(1).getOpcode() == ISD::Constant) {
4129 unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4130 if (!GS.add(Op.getOperand(0), Elem))
4133 } else if (Op.isUndef()) {
4136 if (!GS.add(SDValue(), ResidueOps.size()))
4138 ResidueOps.push_back(BVN->getOperand(I));
4142 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
4146 // Create the BUILD_VECTOR for the remaining elements, if any.
4147 if (!ResidueOps.empty()) {
4148 while (ResidueOps.size() < NumElements)
4149 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
4150 for (auto &Op : GS.Ops) {
4151 if (!Op.getNode()) {
4152 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
4157 return GS.getNode(DAG, SDLoc(BVN));
4160 // Combine GPR scalar values Elems into a vector of type VT.
4161 static SDValue buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4162 SmallVectorImpl<SDValue> &Elems) {
4163 // See whether there is a single replicated value.
4165 unsigned int NumElements = Elems.size();
4166 unsigned int Count = 0;
4167 for (auto Elem : Elems) {
4168 if (!Elem.isUndef()) {
4169 if (!Single.getNode())
4171 else if (Elem != Single) {
4178 // There are three cases here:
4180 // - if the only defined element is a loaded one, the best sequence
4181 // is a replicating load.
4183 // - otherwise, if the only defined element is an i64 value, we will
4184 // end up with the same VLVGP sequence regardless of whether we short-cut
4185 // for replication or fall through to the later code.
4187 // - otherwise, if the only defined element is an i32 or smaller value,
4188 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
4189 // This is only a win if the single defined element is used more than once.
4190 // In other cases we're better off using a single VLVGx.
4191 if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD))
4192 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
4194 // The best way of building a v2i64 from two i64s is to use VLVGP.
4195 if (VT == MVT::v2i64)
4196 return joinDwords(DAG, DL, Elems[0], Elems[1]);
4198 // Use a 64-bit merge high to combine two doubles.
4199 if (VT == MVT::v2f64)
4200 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4202 // Build v4f32 values directly from the FPRs:
4204 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
4209 if (VT == MVT::v4f32) {
4210 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4211 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
4212 // Avoid unnecessary undefs by reusing the other operand.
4215 else if (Op23.isUndef())
4217 // Merging identical replications is a no-op.
4218 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
4220 Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
4221 Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
4222 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
4223 DL, MVT::v2i64, Op01, Op23);
4224 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4227 // Collect the constant terms.
4228 SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
4229 SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
4231 unsigned NumConstants = 0;
4232 for (unsigned I = 0; I < NumElements; ++I) {
4233 SDValue Elem = Elems[I];
4234 if (Elem.getOpcode() == ISD::Constant ||
4235 Elem.getOpcode() == ISD::ConstantFP) {
4237 Constants[I] = Elem;
4241 // If there was at least one constant, fill in the other elements of
4242 // Constants with undefs to get a full vector constant and use that
4243 // as the starting point.
4245 if (NumConstants > 0) {
4246 for (unsigned I = 0; I < NumElements; ++I)
4247 if (!Constants[I].getNode())
4248 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
4249 Result = DAG.getBuildVector(VT, DL, Constants);
4251 // Otherwise try to use VLVGP to start the sequence in order to
4252 // avoid a false dependency on any previous contents of the vector
4253 // register. This only makes sense if one of the associated elements
4255 unsigned I1 = NumElements / 2 - 1;
4256 unsigned I2 = NumElements - 1;
4257 bool Def1 = !Elems[I1].isUndef();
4258 bool Def2 = !Elems[I2].isUndef();
4260 SDValue Elem1 = Elems[Def1 ? I1 : I2];
4261 SDValue Elem2 = Elems[Def2 ? I2 : I1];
4262 Result = DAG.getNode(ISD::BITCAST, DL, VT,
4263 joinDwords(DAG, DL, Elem1, Elem2));
4267 Result = DAG.getUNDEF(VT);
4270 // Use VLVGx to insert the other elements.
4271 for (unsigned I = 0; I < NumElements; ++I)
4272 if (!Done[I] && !Elems[I].isUndef())
4273 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
4274 DAG.getConstant(I, DL, MVT::i32));
4278 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
4279 SelectionDAG &DAG) const {
4280 const SystemZInstrInfo *TII =
4281 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4282 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
4284 EVT VT = Op.getValueType();
4286 if (BVN->isConstant()) {
4287 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
4288 // preferred way of creating all-zero and all-one vectors so give it
4289 // priority over other methods below.
4291 if (tryBuildVectorByteMask(BVN, Mask)) {
4292 SDValue Op = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
4293 DAG.getConstant(Mask, DL, MVT::i32));
4294 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4297 // Try using some form of replication.
4298 APInt SplatBits, SplatUndef;
4299 unsigned SplatBitSize;
4301 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4303 SplatBitSize <= 64) {
4304 // First try assuming that any undefined bits above the highest set bit
4305 // and below the lowest set bit are 1s. This increases the likelihood of
4306 // being able to use a sign-extended element value in VECTOR REPLICATE
4307 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
4308 uint64_t SplatBitsZ = SplatBits.getZExtValue();
4309 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
4310 uint64_t Lower = (SplatUndefZ
4311 & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
4312 uint64_t Upper = (SplatUndefZ
4313 & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
4314 uint64_t Value = SplatBitsZ | Upper | Lower;
4315 SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value,
4320 // Now try assuming that any undefined bits between the first and
4321 // last defined set bits are set. This increases the chances of
4322 // using a non-wraparound mask.
4323 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
4324 Value = SplatBitsZ | Middle;
4325 Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize);
4330 // Fall back to loading it from memory.
4334 // See if we should use shuffles to construct the vector from other vectors.
4335 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
4338 // Detect SCALAR_TO_VECTOR conversions.
4339 if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
4340 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
4342 // Otherwise use buildVector to build the vector up from GPRs.
4343 unsigned NumElements = Op.getNumOperands();
4344 SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
4345 for (unsigned I = 0; I < NumElements; ++I)
4346 Ops[I] = Op.getOperand(I);
4347 return buildVector(DAG, DL, VT, Ops);
4350 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4351 SelectionDAG &DAG) const {
4352 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
4354 EVT VT = Op.getValueType();
4355 unsigned NumElements = VT.getVectorNumElements();
4357 if (VSN->isSplat()) {
4358 SDValue Op0 = Op.getOperand(0);
4359 unsigned Index = VSN->getSplatIndex();
4360 assert(Index < VT.getVectorNumElements() &&
4361 "Splat index should be defined and in first operand");
4362 // See whether the value we're splatting is directly available as a scalar.
4363 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4364 Op0.getOpcode() == ISD::BUILD_VECTOR)
4365 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
4366 // Otherwise keep it as a vector-to-vector operation.
4367 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
4368 DAG.getConstant(Index, DL, MVT::i32));
4371 GeneralShuffle GS(VT);
4372 for (unsigned I = 0; I < NumElements; ++I) {
4373 int Elt = VSN->getMaskElt(I);
4376 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
4377 unsigned(Elt) % NumElements))
4380 return GS.getNode(DAG, SDLoc(VSN));
4383 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
4384 SelectionDAG &DAG) const {
4386 // Just insert the scalar into element 0 of an undefined vector.
4387 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
4388 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
4389 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
4392 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4393 SelectionDAG &DAG) const {
4394 // Handle insertions of floating-point values.
4396 SDValue Op0 = Op.getOperand(0);
4397 SDValue Op1 = Op.getOperand(1);
4398 SDValue Op2 = Op.getOperand(2);
4399 EVT VT = Op.getValueType();
4401 // Insertions into constant indices of a v2f64 can be done using VPDI.
4402 // However, if the inserted value is a bitcast or a constant then it's
4403 // better to use GPRs, as below.
4404 if (VT == MVT::v2f64 &&
4405 Op1.getOpcode() != ISD::BITCAST &&
4406 Op1.getOpcode() != ISD::ConstantFP &&
4407 Op2.getOpcode() == ISD::Constant) {
4408 uint64_t Index = dyn_cast<ConstantSDNode>(Op2)->getZExtValue();
4409 unsigned Mask = VT.getVectorNumElements() - 1;
4414 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
4415 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
4416 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
4417 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
4418 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
4419 DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
4420 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4424 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4425 SelectionDAG &DAG) const {
4426 // Handle extractions of floating-point values.
4428 SDValue Op0 = Op.getOperand(0);
4429 SDValue Op1 = Op.getOperand(1);
4430 EVT VT = Op.getValueType();
4431 EVT VecVT = Op0.getValueType();
4433 // Extractions of constant indices can be done directly.
4434 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
4435 uint64_t Index = CIndexN->getZExtValue();
4436 unsigned Mask = VecVT.getVectorNumElements() - 1;
4441 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
4442 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
4443 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
4444 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
4445 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
4446 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4450 SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG,
4451 unsigned UnpackHigh) const {
4452 SDValue PackedOp = Op.getOperand(0);
4453 EVT OutVT = Op.getValueType();
4454 EVT InVT = PackedOp.getValueType();
4455 unsigned ToBits = OutVT.getScalarSizeInBits();
4456 unsigned FromBits = InVT.getScalarSizeInBits();
4459 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
4460 SystemZ::VectorBits / FromBits);
4461 PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp);
4462 } while (FromBits != ToBits);
4466 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
4467 unsigned ByScalar) const {
4468 // Look for cases where a vector shift can use the *_BY_SCALAR form.
4469 SDValue Op0 = Op.getOperand(0);
4470 SDValue Op1 = Op.getOperand(1);
4472 EVT VT = Op.getValueType();
4473 unsigned ElemBitSize = VT.getScalarSizeInBits();
4475 // See whether the shift vector is a splat represented as BUILD_VECTOR.
4476 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
4477 APInt SplatBits, SplatUndef;
4478 unsigned SplatBitSize;
4480 // Check for constant splats. Use ElemBitSize as the minimum element
4481 // width and reject splats that need wider elements.
4482 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4483 ElemBitSize, true) &&
4484 SplatBitSize == ElemBitSize) {
4485 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
4487 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4489 // Check for variable splats.
4490 BitVector UndefElements;
4491 SDValue Splat = BVN->getSplatValue(&UndefElements);
4493 // Since i32 is the smallest legal type, we either need a no-op
4495 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
4496 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4500 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
4501 // and the shift amount is directly available in a GPR.
4502 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
4503 if (VSN->isSplat()) {
4504 SDValue VSNOp0 = VSN->getOperand(0);
4505 unsigned Index = VSN->getSplatIndex();
4506 assert(Index < VT.getVectorNumElements() &&
4507 "Splat index should be defined and in first operand");
4508 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4509 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
4510 // Since i32 is the smallest legal type, we either need a no-op
4512 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
4513 VSNOp0.getOperand(Index));
4514 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4519 // Otherwise just treat the current form as legal.
4523 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
4524 SelectionDAG &DAG) const {
4525 switch (Op.getOpcode()) {
4526 case ISD::FRAMEADDR:
4527 return lowerFRAMEADDR(Op, DAG);
4528 case ISD::RETURNADDR:
4529 return lowerRETURNADDR(Op, DAG);
4531 return lowerBR_CC(Op, DAG);
4532 case ISD::SELECT_CC:
4533 return lowerSELECT_CC(Op, DAG);
4535 return lowerSETCC(Op, DAG);
4536 case ISD::GlobalAddress:
4537 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
4538 case ISD::GlobalTLSAddress:
4539 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
4540 case ISD::BlockAddress:
4541 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
4542 case ISD::JumpTable:
4543 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
4544 case ISD::ConstantPool:
4545 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
4547 return lowerBITCAST(Op, DAG);
4549 return lowerVASTART(Op, DAG);
4551 return lowerVACOPY(Op, DAG);
4552 case ISD::DYNAMIC_STACKALLOC:
4553 return lowerDYNAMIC_STACKALLOC(Op, DAG);
4554 case ISD::GET_DYNAMIC_AREA_OFFSET:
4555 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
4556 case ISD::SMUL_LOHI:
4557 return lowerSMUL_LOHI(Op, DAG);
4558 case ISD::UMUL_LOHI:
4559 return lowerUMUL_LOHI(Op, DAG);
4561 return lowerSDIVREM(Op, DAG);
4563 return lowerUDIVREM(Op, DAG);
4565 return lowerOR(Op, DAG);
4567 return lowerCTPOP(Op, DAG);
4568 case ISD::ATOMIC_FENCE:
4569 return lowerATOMIC_FENCE(Op, DAG);
4570 case ISD::ATOMIC_SWAP:
4571 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
4572 case ISD::ATOMIC_STORE:
4573 return lowerATOMIC_STORE(Op, DAG);
4574 case ISD::ATOMIC_LOAD:
4575 return lowerATOMIC_LOAD(Op, DAG);
4576 case ISD::ATOMIC_LOAD_ADD:
4577 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
4578 case ISD::ATOMIC_LOAD_SUB:
4579 return lowerATOMIC_LOAD_SUB(Op, DAG);
4580 case ISD::ATOMIC_LOAD_AND:
4581 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
4582 case ISD::ATOMIC_LOAD_OR:
4583 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
4584 case ISD::ATOMIC_LOAD_XOR:
4585 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
4586 case ISD::ATOMIC_LOAD_NAND:
4587 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
4588 case ISD::ATOMIC_LOAD_MIN:
4589 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
4590 case ISD::ATOMIC_LOAD_MAX:
4591 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
4592 case ISD::ATOMIC_LOAD_UMIN:
4593 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
4594 case ISD::ATOMIC_LOAD_UMAX:
4595 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
4596 case ISD::ATOMIC_CMP_SWAP:
4597 return lowerATOMIC_CMP_SWAP(Op, DAG);
4598 case ISD::STACKSAVE:
4599 return lowerSTACKSAVE(Op, DAG);
4600 case ISD::STACKRESTORE:
4601 return lowerSTACKRESTORE(Op, DAG);
4603 return lowerPREFETCH(Op, DAG);
4604 case ISD::INTRINSIC_W_CHAIN:
4605 return lowerINTRINSIC_W_CHAIN(Op, DAG);
4606 case ISD::INTRINSIC_WO_CHAIN:
4607 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
4608 case ISD::BUILD_VECTOR:
4609 return lowerBUILD_VECTOR(Op, DAG);
4610 case ISD::VECTOR_SHUFFLE:
4611 return lowerVECTOR_SHUFFLE(Op, DAG);
4612 case ISD::SCALAR_TO_VECTOR:
4613 return lowerSCALAR_TO_VECTOR(Op, DAG);
4614 case ISD::INSERT_VECTOR_ELT:
4615 return lowerINSERT_VECTOR_ELT(Op, DAG);
4616 case ISD::EXTRACT_VECTOR_ELT:
4617 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4618 case ISD::SIGN_EXTEND_VECTOR_INREG:
4619 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACK_HIGH);
4620 case ISD::ZERO_EXTEND_VECTOR_INREG:
4621 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACKL_HIGH);
4623 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
4625 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
4627 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
4629 llvm_unreachable("Unexpected node to lower");
4633 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
4634 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
4635 switch ((SystemZISD::NodeType)Opcode) {
4636 case SystemZISD::FIRST_NUMBER: break;
4642 OPCODE(PCREL_WRAPPER);
4643 OPCODE(PCREL_OFFSET);
4649 OPCODE(SELECT_CCMASK);
4650 OPCODE(ADJDYNALLOC);
4652 OPCODE(UMUL_LOHI64);
4669 OPCODE(SEARCH_STRING);
4674 OPCODE(TBEGIN_NOFLOAT);
4677 OPCODE(ROTATE_MASK);
4679 OPCODE(JOIN_DWORDS);
4684 OPCODE(PERMUTE_DWORDS);
4689 OPCODE(UNPACK_HIGH);
4690 OPCODE(UNPACKL_HIGH);
4692 OPCODE(UNPACKL_LOW);
4693 OPCODE(VSHL_BY_SCALAR);
4694 OPCODE(VSRL_BY_SCALAR);
4695 OPCODE(VSRA_BY_SCALAR);
4723 OPCODE(ATOMIC_SWAPW);
4724 OPCODE(ATOMIC_LOADW_ADD);
4725 OPCODE(ATOMIC_LOADW_SUB);
4726 OPCODE(ATOMIC_LOADW_AND);
4727 OPCODE(ATOMIC_LOADW_OR);
4728 OPCODE(ATOMIC_LOADW_XOR);
4729 OPCODE(ATOMIC_LOADW_NAND);
4730 OPCODE(ATOMIC_LOADW_MIN);
4731 OPCODE(ATOMIC_LOADW_MAX);
4732 OPCODE(ATOMIC_LOADW_UMIN);
4733 OPCODE(ATOMIC_LOADW_UMAX);
4734 OPCODE(ATOMIC_CMP_SWAPW);
4743 // Return true if VT is a vector whose elements are a whole number of bytes
4744 // in width. Also check for presence of vector support.
4745 bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
4746 if (!Subtarget.hasVector())
4749 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
4752 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
4753 // producing a result of type ResVT. Op is a possibly bitcast version
4754 // of the input vector and Index is the index (based on type VecVT) that
4755 // should be extracted. Return the new extraction if a simplification
4756 // was possible or if Force is true.
4757 SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
4758 EVT VecVT, SDValue Op,
4760 DAGCombinerInfo &DCI,
4762 SelectionDAG &DAG = DCI.DAG;
4764 // The number of bytes being extracted.
4765 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4768 unsigned Opcode = Op.getOpcode();
4769 if (Opcode == ISD::BITCAST)
4770 // Look through bitcasts.
4771 Op = Op.getOperand(0);
4772 else if (Opcode == ISD::VECTOR_SHUFFLE &&
4773 canTreatAsByteVector(Op.getValueType())) {
4774 // Get a VPERM-like permute mask and see whether the bytes covered
4775 // by the extracted element are a contiguous sequence from one
4777 SmallVector<int, SystemZ::VectorBytes> Bytes;
4778 getVPermMask(cast<ShuffleVectorSDNode>(Op), Bytes);
4780 if (!getShuffleInput(Bytes, Index * BytesPerElement,
4781 BytesPerElement, First))
4784 return DAG.getUNDEF(ResVT);
4785 // Make sure the contiguous sequence starts at a multiple of the
4786 // original element size.
4787 unsigned Byte = unsigned(First) % Bytes.size();
4788 if (Byte % BytesPerElement != 0)
4790 // We can get the extracted value directly from an input.
4791 Index = Byte / BytesPerElement;
4792 Op = Op.getOperand(unsigned(First) / Bytes.size());
4794 } else if (Opcode == ISD::BUILD_VECTOR &&
4795 canTreatAsByteVector(Op.getValueType())) {
4796 // We can only optimize this case if the BUILD_VECTOR elements are
4797 // at least as wide as the extracted value.
4798 EVT OpVT = Op.getValueType();
4799 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4800 if (OpBytesPerElement < BytesPerElement)
4802 // Make sure that the least-significant bit of the extracted value
4803 // is the least significant bit of an input.
4804 unsigned End = (Index + 1) * BytesPerElement;
4805 if (End % OpBytesPerElement != 0)
4807 // We're extracting the low part of one operand of the BUILD_VECTOR.
4808 Op = Op.getOperand(End / OpBytesPerElement - 1);
4809 if (!Op.getValueType().isInteger()) {
4810 EVT VT = MVT::getIntegerVT(Op.getValueSizeInBits());
4811 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
4812 DCI.AddToWorklist(Op.getNode());
4814 EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
4815 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
4817 DCI.AddToWorklist(Op.getNode());
4818 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
4821 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
4822 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
4823 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
4824 canTreatAsByteVector(Op.getValueType()) &&
4825 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
4826 // Make sure that only the unextended bits are significant.
4827 EVT ExtVT = Op.getValueType();
4828 EVT OpVT = Op.getOperand(0).getValueType();
4829 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
4830 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4831 unsigned Byte = Index * BytesPerElement;
4832 unsigned SubByte = Byte % ExtBytesPerElement;
4833 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
4834 if (SubByte < MinSubByte ||
4835 SubByte + BytesPerElement > ExtBytesPerElement)
4837 // Get the byte offset of the unextended element
4838 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
4839 // ...then add the byte offset relative to that element.
4840 Byte += SubByte - MinSubByte;
4841 if (Byte % BytesPerElement != 0)
4843 Op = Op.getOperand(0);
4844 Index = Byte / BytesPerElement;
4850 if (Op.getValueType() != VecVT) {
4851 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
4852 DCI.AddToWorklist(Op.getNode());
4854 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
4855 DAG.getConstant(Index, DL, MVT::i32));
4860 // Optimize vector operations in scalar value Op on the basis that Op
4861 // is truncated to TruncVT.
4862 SDValue SystemZTargetLowering::combineTruncateExtract(
4863 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
4864 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
4865 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
4867 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4868 TruncVT.getSizeInBits() % 8 == 0) {
4869 SDValue Vec = Op.getOperand(0);
4870 EVT VecVT = Vec.getValueType();
4871 if (canTreatAsByteVector(VecVT)) {
4872 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4873 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4874 unsigned TruncBytes = TruncVT.getStoreSize();
4875 if (BytesPerElement % TruncBytes == 0) {
4876 // Calculate the value of Y' in the above description. We are
4877 // splitting the original elements into Scale equal-sized pieces
4878 // and for truncation purposes want the last (least-significant)
4879 // of these pieces for IndexN. This is easiest to do by calculating
4880 // the start index of the following element and then subtracting 1.
4881 unsigned Scale = BytesPerElement / TruncBytes;
4882 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
4884 // Defer the creation of the bitcast from X to combineExtract,
4885 // which might be able to optimize the extraction.
4886 VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
4887 VecVT.getStoreSize() / TruncBytes);
4888 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
4889 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
4897 SDValue SystemZTargetLowering::combineSIGN_EXTEND(
4898 SDNode *N, DAGCombinerInfo &DCI) const {
4899 // Convert (sext (ashr (shl X, C1), C2)) to
4900 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
4901 // cheap as narrower ones.
4902 SelectionDAG &DAG = DCI.DAG;
4903 SDValue N0 = N->getOperand(0);
4904 EVT VT = N->getValueType(0);
4905 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
4906 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4907 SDValue Inner = N0.getOperand(0);
4908 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
4909 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
4910 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
4911 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
4912 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
4913 EVT ShiftVT = N0.getOperand(1).getValueType();
4914 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
4915 Inner.getOperand(0));
4916 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
4917 DAG.getConstant(NewShlAmt, SDLoc(Inner),
4919 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
4920 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
4927 SDValue SystemZTargetLowering::combineMERGE(
4928 SDNode *N, DAGCombinerInfo &DCI) const {
4929 SelectionDAG &DAG = DCI.DAG;
4930 unsigned Opcode = N->getOpcode();
4931 SDValue Op0 = N->getOperand(0);
4932 SDValue Op1 = N->getOperand(1);
4933 if (Op0.getOpcode() == ISD::BITCAST)
4934 Op0 = Op0.getOperand(0);
4935 if (Op0.getOpcode() == SystemZISD::BYTE_MASK &&
4936 cast<ConstantSDNode>(Op0.getOperand(0))->getZExtValue() == 0) {
4937 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
4939 if (Op1 == N->getOperand(0))
4941 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
4942 EVT VT = Op1.getValueType();
4943 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
4944 if (ElemBytes <= 4) {
4945 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
4946 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
4947 EVT InVT = VT.changeVectorElementTypeToInteger();
4948 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
4949 SystemZ::VectorBytes / ElemBytes / 2);
4951 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
4952 DCI.AddToWorklist(Op1.getNode());
4954 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
4955 DCI.AddToWorklist(Op.getNode());
4956 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
4962 SDValue SystemZTargetLowering::combineSTORE(
4963 SDNode *N, DAGCombinerInfo &DCI) const {
4964 SelectionDAG &DAG = DCI.DAG;
4965 auto *SN = cast<StoreSDNode>(N);
4966 auto &Op1 = N->getOperand(1);
4967 EVT MemVT = SN->getMemoryVT();
4968 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
4969 // for the extraction to be done on a vMiN value, so that we can use VSTE.
4970 // If X has wider elements then convert it to:
4971 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
4972 if (MemVT.isInteger()) {
4974 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
4975 DCI.AddToWorklist(Value.getNode());
4977 // Rewrite the store with the new form of stored value.
4978 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
4979 SN->getBasePtr(), SN->getMemoryVT(),
4980 SN->getMemOperand());
4983 // Combine STORE (BSWAP) into STRVH/STRV/STRVG
4984 // See comment in combineBSWAP about volatile accesses.
4985 if (!SN->isVolatile() &&
4986 Op1.getOpcode() == ISD::BSWAP &&
4987 Op1.getNode()->hasOneUse() &&
4988 (Op1.getValueType() == MVT::i16 ||
4989 Op1.getValueType() == MVT::i32 ||
4990 Op1.getValueType() == MVT::i64)) {
4992 SDValue BSwapOp = Op1.getOperand(0);
4994 if (BSwapOp.getValueType() == MVT::i16)
4995 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
4998 N->getOperand(0), BSwapOp, N->getOperand(2),
4999 DAG.getValueType(Op1.getValueType())
5003 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
5004 Ops, MemVT, SN->getMemOperand());
5009 SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
5010 SDNode *N, DAGCombinerInfo &DCI) const {
5012 if (!Subtarget.hasVector())
5015 // Try to simplify a vector extraction.
5016 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
5017 SDValue Op0 = N->getOperand(0);
5018 EVT VecVT = Op0.getValueType();
5019 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
5020 IndexN->getZExtValue(), DCI, false);
5025 SDValue SystemZTargetLowering::combineJOIN_DWORDS(
5026 SDNode *N, DAGCombinerInfo &DCI) const {
5027 SelectionDAG &DAG = DCI.DAG;
5028 // (join_dwords X, X) == (replicate X)
5029 if (N->getOperand(0) == N->getOperand(1))
5030 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
5035 SDValue SystemZTargetLowering::combineFP_ROUND(
5036 SDNode *N, DAGCombinerInfo &DCI) const {
5037 // (fpround (extract_vector_elt X 0))
5038 // (fpround (extract_vector_elt X 1)) ->
5039 // (extract_vector_elt (VROUND X) 0)
5040 // (extract_vector_elt (VROUND X) 1)
5042 // This is a special case since the target doesn't really support v2f32s.
5043 SelectionDAG &DAG = DCI.DAG;
5044 SDValue Op0 = N->getOperand(0);
5045 if (N->getValueType(0) == MVT::f32 &&
5047 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5048 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
5049 Op0.getOperand(1).getOpcode() == ISD::Constant &&
5050 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
5051 SDValue Vec = Op0.getOperand(0);
5052 for (auto *U : Vec->uses()) {
5053 if (U != Op0.getNode() &&
5055 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5056 U->getOperand(0) == Vec &&
5057 U->getOperand(1).getOpcode() == ISD::Constant &&
5058 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
5059 SDValue OtherRound = SDValue(*U->use_begin(), 0);
5060 if (OtherRound.getOpcode() == ISD::FP_ROUND &&
5061 OtherRound.getOperand(0) == SDValue(U, 0) &&
5062 OtherRound.getValueType() == MVT::f32) {
5063 SDValue VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
5065 DCI.AddToWorklist(VRound.getNode());
5067 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
5068 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
5069 DCI.AddToWorklist(Extract1.getNode());
5070 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
5072 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
5073 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
5082 SDValue SystemZTargetLowering::combineBSWAP(
5083 SDNode *N, DAGCombinerInfo &DCI) const {
5084 SelectionDAG &DAG = DCI.DAG;
5085 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG
5086 // These loads are allowed to access memory multiple times, and so we must check
5087 // that the loads are not volatile before performing the combine.
5088 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
5089 N->getOperand(0).hasOneUse() &&
5090 (N->getValueType(0) == MVT::i16 || N->getValueType(0) == MVT::i32 ||
5091 N->getValueType(0) == MVT::i64) &&
5092 !cast<LoadSDNode>(N->getOperand(0))->isVolatile()) {
5093 SDValue Load = N->getOperand(0);
5094 LoadSDNode *LD = cast<LoadSDNode>(Load);
5096 // Create the byte-swapping load.
5098 LD->getChain(), // Chain
5099 LD->getBasePtr(), // Ptr
5100 DAG.getValueType(N->getValueType(0)) // VT
5103 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
5104 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
5105 MVT::i64 : MVT::i32, MVT::Other),
5106 Ops, LD->getMemoryVT(), LD->getMemOperand());
5108 // If this is an i16 load, insert the truncate.
5109 SDValue ResVal = BSLoad;
5110 if (N->getValueType(0) == MVT::i16)
5111 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
5113 // First, combine the bswap away. This makes the value produced by the
5115 DCI.CombineTo(N, ResVal);
5117 // Next, combine the load away, we give it a bogus result value but a real
5118 // chain result. The result value is dead because the bswap is dead.
5119 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
5121 // Return N so it doesn't get rechecked!
5122 return SDValue(N, 0);
5127 SDValue SystemZTargetLowering::combineSHIFTROT(
5128 SDNode *N, DAGCombinerInfo &DCI) const {
5130 SelectionDAG &DAG = DCI.DAG;
5132 // Shift/rotate instructions only use the last 6 bits of the second operand
5133 // register. If the second operand is the result of an AND with an immediate
5134 // value that has its last 6 bits set, we can safely remove the AND operation.
5136 // If the AND operation doesn't have the last 6 bits set, we can't remove it
5137 // entirely, but we can still truncate it to a 16-bit value. This prevents
5138 // us from ending up with a NILL with a signed operand, which will cause the
5139 // instruction printer to abort.
5140 SDValue N1 = N->getOperand(1);
5141 if (N1.getOpcode() == ISD::AND) {
5142 SDValue AndMaskOp = N1->getOperand(1);
5143 auto *AndMask = dyn_cast<ConstantSDNode>(AndMaskOp);
5145 // The AND mask is constant
5147 auto AmtVal = AndMask->getZExtValue();
5149 // Bottom 6 bits are set
5150 if ((AmtVal & 0x3f) == 0x3f) {
5151 SDValue AndOp = N1->getOperand(0);
5153 // This is the only use, so remove the node
5154 if (N1.hasOneUse()) {
5155 // Combine the AND away
5156 DCI.CombineTo(N1.getNode(), AndOp);
5158 // Return N so it isn't rechecked
5159 return SDValue(N, 0);
5161 // The node will be reused, so create a new node for this one use
5163 SDValue Replace = DAG.getNode(N->getOpcode(), SDLoc(N),
5164 N->getValueType(0), N->getOperand(0),
5166 DCI.AddToWorklist(Replace.getNode());
5171 // We can't remove the AND, but we can use NILL here (normally we would
5172 // use NILF). Only keep the last 16 bits of the mask. The actual
5173 // transformation will be handled by .td definitions.
5174 } else if (AmtVal >> 16 != 0) {
5175 SDValue AndOp = N1->getOperand(0);
5177 auto NewMask = DAG.getConstant(AndMask->getZExtValue() & 0x0000ffff,
5179 AndMaskOp.getValueType());
5181 auto NewAnd = DAG.getNode(N1.getOpcode(), SDLoc(N1), N1.getValueType(),
5184 SDValue Replace = DAG.getNode(N->getOpcode(), SDLoc(N),
5185 N->getValueType(0), N->getOperand(0),
5187 DCI.AddToWorklist(Replace.getNode());
5197 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
5198 DAGCombinerInfo &DCI) const {
5199 switch(N->getOpcode()) {
5201 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI);
5202 case SystemZISD::MERGE_HIGH:
5203 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI);
5204 case ISD::STORE: return combineSTORE(N, DCI);
5205 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
5206 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
5207 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI);
5208 case ISD::BSWAP: return combineBSWAP(N, DCI);
5212 case ISD::ROTL: return combineSHIFTROT(N, DCI);
5218 //===----------------------------------------------------------------------===//
5220 //===----------------------------------------------------------------------===//
5222 // Create a new basic block after MBB.
5223 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
5224 MachineFunction &MF = *MBB->getParent();
5225 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
5226 MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
5230 // Split MBB after MI and return the new block (the one that contains
5231 // instructions after MI).
5232 static MachineBasicBlock *splitBlockAfter(MachineBasicBlock::iterator MI,
5233 MachineBasicBlock *MBB) {
5234 MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
5235 NewMBB->splice(NewMBB->begin(), MBB,
5236 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
5237 NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
5241 // Split MBB before MI and return the new block (the one that contains MI).
5242 static MachineBasicBlock *splitBlockBefore(MachineBasicBlock::iterator MI,
5243 MachineBasicBlock *MBB) {
5244 MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
5245 NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
5246 NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
5250 // Force base value Base into a register before MI. Return the register.
5251 static unsigned forceReg(MachineInstr &MI, MachineOperand &Base,
5252 const SystemZInstrInfo *TII) {
5254 return Base.getReg();
5256 MachineBasicBlock *MBB = MI.getParent();
5257 MachineFunction &MF = *MBB->getParent();
5258 MachineRegisterInfo &MRI = MF.getRegInfo();
5260 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5261 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
5268 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
5270 SystemZTargetLowering::emitSelect(MachineInstr &MI,
5271 MachineBasicBlock *MBB,
5272 unsigned LOCROpcode) const {
5273 const SystemZInstrInfo *TII =
5274 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5276 unsigned DestReg = MI.getOperand(0).getReg();
5277 unsigned TrueReg = MI.getOperand(1).getReg();
5278 unsigned FalseReg = MI.getOperand(2).getReg();
5279 unsigned CCValid = MI.getOperand(3).getImm();
5280 unsigned CCMask = MI.getOperand(4).getImm();
5281 DebugLoc DL = MI.getDebugLoc();
5283 // Use LOCROpcode if possible.
5284 if (LOCROpcode && Subtarget.hasLoadStoreOnCond()) {
5285 BuildMI(*MBB, MI, DL, TII->get(LOCROpcode), DestReg)
5286 .addReg(FalseReg).addReg(TrueReg)
5287 .addImm(CCValid).addImm(CCMask);
5288 MI.eraseFromParent();
5292 MachineBasicBlock *StartMBB = MBB;
5293 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB);
5294 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
5297 // BRC CCMask, JoinMBB
5298 // # fallthrough to FalseMBB
5300 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5301 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
5302 MBB->addSuccessor(JoinMBB);
5303 MBB->addSuccessor(FalseMBB);
5306 // # fallthrough to JoinMBB
5308 MBB->addSuccessor(JoinMBB);
5311 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
5314 BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
5315 .addReg(TrueReg).addMBB(StartMBB)
5316 .addReg(FalseReg).addMBB(FalseMBB);
5318 MI.eraseFromParent();
5322 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
5323 // StoreOpcode is the store to use and Invert says whether the store should
5324 // happen when the condition is false rather than true. If a STORE ON
5325 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
5326 MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
5327 MachineBasicBlock *MBB,
5328 unsigned StoreOpcode,
5329 unsigned STOCOpcode,
5330 bool Invert) const {
5331 const SystemZInstrInfo *TII =
5332 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5334 unsigned SrcReg = MI.getOperand(0).getReg();
5335 MachineOperand Base = MI.getOperand(1);
5336 int64_t Disp = MI.getOperand(2).getImm();
5337 unsigned IndexReg = MI.getOperand(3).getReg();
5338 unsigned CCValid = MI.getOperand(4).getImm();
5339 unsigned CCMask = MI.getOperand(5).getImm();
5340 DebugLoc DL = MI.getDebugLoc();
5342 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
5344 // Use STOCOpcode if possible. We could use different store patterns in
5345 // order to avoid matching the index register, but the performance trade-offs
5346 // might be more complicated in that case.
5347 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
5350 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
5356 MI.eraseFromParent();
5360 // Get the condition needed to branch around the store.
5364 MachineBasicBlock *StartMBB = MBB;
5365 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB);
5366 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
5369 // BRC CCMask, JoinMBB
5370 // # fallthrough to FalseMBB
5372 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5373 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
5374 MBB->addSuccessor(JoinMBB);
5375 MBB->addSuccessor(FalseMBB);
5378 // store %SrcReg, %Disp(%Index,%Base)
5379 // # fallthrough to JoinMBB
5381 BuildMI(MBB, DL, TII->get(StoreOpcode))
5386 MBB->addSuccessor(JoinMBB);
5388 MI.eraseFromParent();
5392 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
5393 // or ATOMIC_SWAP{,W} instruction MI. BinOpcode is the instruction that
5394 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
5395 // BitSize is the width of the field in bits, or 0 if this is a partword
5396 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
5397 // is one of the operands. Invert says whether the field should be
5398 // inverted after performing BinOpcode (e.g. for NAND).
5399 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
5400 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
5401 unsigned BitSize, bool Invert) const {
5402 MachineFunction &MF = *MBB->getParent();
5403 const SystemZInstrInfo *TII =
5404 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5405 MachineRegisterInfo &MRI = MF.getRegInfo();
5406 bool IsSubWord = (BitSize < 32);
5408 // Extract the operands. Base can be a register or a frame index.
5409 // Src2 can be a register or immediate.
5410 unsigned Dest = MI.getOperand(0).getReg();
5411 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
5412 int64_t Disp = MI.getOperand(2).getImm();
5413 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
5414 unsigned BitShift = (IsSubWord ? MI.getOperand(4).getReg() : 0);
5415 unsigned NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : 0);
5416 DebugLoc DL = MI.getDebugLoc();
5418 BitSize = MI.getOperand(6).getImm();
5420 // Subword operations use 32-bit registers.
5421 const TargetRegisterClass *RC = (BitSize <= 32 ?
5422 &SystemZ::GR32BitRegClass :
5423 &SystemZ::GR64BitRegClass);
5424 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
5425 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
5427 // Get the right opcodes for the displacement.
5428 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
5429 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
5430 assert(LOpcode && CSOpcode && "Displacement out of range");
5432 // Create virtual registers for temporary results.
5433 unsigned OrigVal = MRI.createVirtualRegister(RC);
5434 unsigned OldVal = MRI.createVirtualRegister(RC);
5435 unsigned NewVal = (BinOpcode || IsSubWord ?
5436 MRI.createVirtualRegister(RC) : Src2.getReg());
5437 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
5438 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
5440 // Insert a basic block for the main loop.
5441 MachineBasicBlock *StartMBB = MBB;
5442 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5443 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5447 // %OrigVal = L Disp(%Base)
5448 // # fall through to LoopMMB
5450 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
5451 MBB->addSuccessor(LoopMBB);
5454 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
5455 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
5456 // %RotatedNewVal = OP %RotatedOldVal, %Src2
5457 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
5458 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
5460 // # fall through to DoneMMB
5462 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5463 .addReg(OrigVal).addMBB(StartMBB)
5464 .addReg(Dest).addMBB(LoopMBB);
5466 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
5467 .addReg(OldVal).addReg(BitShift).addImm(0);
5469 // Perform the operation normally and then invert every bit of the field.
5470 unsigned Tmp = MRI.createVirtualRegister(RC);
5471 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp).addReg(RotatedOldVal).add(Src2);
5473 // XILF with the upper BitSize bits set.
5474 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
5475 .addReg(Tmp).addImm(-1U << (32 - BitSize));
5477 // Use LCGR and add -1 to the result, which is more compact than
5478 // an XILF, XILH pair.
5479 unsigned Tmp2 = MRI.createVirtualRegister(RC);
5480 BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
5481 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
5482 .addReg(Tmp2).addImm(-1);
5484 } else if (BinOpcode)
5485 // A simply binary operation.
5486 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
5487 .addReg(RotatedOldVal)
5490 // Use RISBG to rotate Src2 into position and use it to replace the
5491 // field in RotatedOldVal.
5492 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
5493 .addReg(RotatedOldVal).addReg(Src2.getReg())
5494 .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
5496 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
5497 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
5498 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
5503 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5504 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5505 MBB->addSuccessor(LoopMBB);
5506 MBB->addSuccessor(DoneMBB);
5508 MI.eraseFromParent();
5512 // Implement EmitInstrWithCustomInserter for pseudo
5513 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
5514 // instruction that should be used to compare the current field with the
5515 // minimum or maximum value. KeepOldMask is the BRC condition-code mask
5516 // for when the current field should be kept. BitSize is the width of
5517 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
5518 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
5519 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
5520 unsigned KeepOldMask, unsigned BitSize) const {
5521 MachineFunction &MF = *MBB->getParent();
5522 const SystemZInstrInfo *TII =
5523 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5524 MachineRegisterInfo &MRI = MF.getRegInfo();
5525 bool IsSubWord = (BitSize < 32);
5527 // Extract the operands. Base can be a register or a frame index.
5528 unsigned Dest = MI.getOperand(0).getReg();
5529 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
5530 int64_t Disp = MI.getOperand(2).getImm();
5531 unsigned Src2 = MI.getOperand(3).getReg();
5532 unsigned BitShift = (IsSubWord ? MI.getOperand(4).getReg() : 0);
5533 unsigned NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : 0);
5534 DebugLoc DL = MI.getDebugLoc();
5536 BitSize = MI.getOperand(6).getImm();
5538 // Subword operations use 32-bit registers.
5539 const TargetRegisterClass *RC = (BitSize <= 32 ?
5540 &SystemZ::GR32BitRegClass :
5541 &SystemZ::GR64BitRegClass);
5542 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
5543 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
5545 // Get the right opcodes for the displacement.
5546 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
5547 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
5548 assert(LOpcode && CSOpcode && "Displacement out of range");
5550 // Create virtual registers for temporary results.
5551 unsigned OrigVal = MRI.createVirtualRegister(RC);
5552 unsigned OldVal = MRI.createVirtualRegister(RC);
5553 unsigned NewVal = MRI.createVirtualRegister(RC);
5554 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
5555 unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
5556 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
5558 // Insert 3 basic blocks for the loop.
5559 MachineBasicBlock *StartMBB = MBB;
5560 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5561 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5562 MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
5563 MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
5567 // %OrigVal = L Disp(%Base)
5568 // # fall through to LoopMMB
5570 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
5571 MBB->addSuccessor(LoopMBB);
5574 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
5575 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
5576 // CompareOpcode %RotatedOldVal, %Src2
5577 // BRC KeepOldMask, UpdateMBB
5579 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5580 .addReg(OrigVal).addMBB(StartMBB)
5581 .addReg(Dest).addMBB(UpdateMBB);
5583 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
5584 .addReg(OldVal).addReg(BitShift).addImm(0);
5585 BuildMI(MBB, DL, TII->get(CompareOpcode))
5586 .addReg(RotatedOldVal).addReg(Src2);
5587 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5588 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
5589 MBB->addSuccessor(UpdateMBB);
5590 MBB->addSuccessor(UseAltMBB);
5593 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
5594 // # fall through to UpdateMMB
5597 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
5598 .addReg(RotatedOldVal).addReg(Src2)
5599 .addImm(32).addImm(31 + BitSize).addImm(0);
5600 MBB->addSuccessor(UpdateMBB);
5603 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
5604 // [ %RotatedAltVal, UseAltMBB ]
5605 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
5606 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
5608 // # fall through to DoneMMB
5610 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
5611 .addReg(RotatedOldVal).addMBB(LoopMBB)
5612 .addReg(RotatedAltVal).addMBB(UseAltMBB);
5614 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
5615 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
5616 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
5621 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5622 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5623 MBB->addSuccessor(LoopMBB);
5624 MBB->addSuccessor(DoneMBB);
5626 MI.eraseFromParent();
5630 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
5633 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
5634 MachineBasicBlock *MBB) const {
5636 MachineFunction &MF = *MBB->getParent();
5637 const SystemZInstrInfo *TII =
5638 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5639 MachineRegisterInfo &MRI = MF.getRegInfo();
5641 // Extract the operands. Base can be a register or a frame index.
5642 unsigned Dest = MI.getOperand(0).getReg();
5643 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
5644 int64_t Disp = MI.getOperand(2).getImm();
5645 unsigned OrigCmpVal = MI.getOperand(3).getReg();
5646 unsigned OrigSwapVal = MI.getOperand(4).getReg();
5647 unsigned BitShift = MI.getOperand(5).getReg();
5648 unsigned NegBitShift = MI.getOperand(6).getReg();
5649 int64_t BitSize = MI.getOperand(7).getImm();
5650 DebugLoc DL = MI.getDebugLoc();
5652 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
5654 // Get the right opcodes for the displacement.
5655 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
5656 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
5657 assert(LOpcode && CSOpcode && "Displacement out of range");
5659 // Create virtual registers for temporary results.
5660 unsigned OrigOldVal = MRI.createVirtualRegister(RC);
5661 unsigned OldVal = MRI.createVirtualRegister(RC);
5662 unsigned CmpVal = MRI.createVirtualRegister(RC);
5663 unsigned SwapVal = MRI.createVirtualRegister(RC);
5664 unsigned StoreVal = MRI.createVirtualRegister(RC);
5665 unsigned RetryOldVal = MRI.createVirtualRegister(RC);
5666 unsigned RetryCmpVal = MRI.createVirtualRegister(RC);
5667 unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
5669 // Insert 2 basic blocks for the loop.
5670 MachineBasicBlock *StartMBB = MBB;
5671 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5672 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5673 MachineBasicBlock *SetMBB = emitBlockAfter(LoopMBB);
5677 // %OrigOldVal = L Disp(%Base)
5678 // # fall through to LoopMMB
5680 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
5684 MBB->addSuccessor(LoopMBB);
5687 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
5688 // %CmpVal = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
5689 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
5690 // %Dest = RLL %OldVal, BitSize(%BitShift)
5691 // ^^ The low BitSize bits contain the field
5693 // %RetryCmpVal = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
5694 // ^^ Replace the upper 32-BitSize bits of the
5695 // comparison value with those that we loaded,
5696 // so that we can use a full word comparison.
5697 // CR %Dest, %RetryCmpVal
5699 // # Fall through to SetMBB
5701 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5702 .addReg(OrigOldVal).addMBB(StartMBB)
5703 .addReg(RetryOldVal).addMBB(SetMBB);
5704 BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
5705 .addReg(OrigCmpVal).addMBB(StartMBB)
5706 .addReg(RetryCmpVal).addMBB(SetMBB);
5707 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
5708 .addReg(OrigSwapVal).addMBB(StartMBB)
5709 .addReg(RetrySwapVal).addMBB(SetMBB);
5710 BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
5711 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
5712 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
5713 .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5714 BuildMI(MBB, DL, TII->get(SystemZ::CR))
5715 .addReg(Dest).addReg(RetryCmpVal);
5716 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5717 .addImm(SystemZ::CCMASK_ICMP)
5718 .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
5719 MBB->addSuccessor(DoneMBB);
5720 MBB->addSuccessor(SetMBB);
5723 // %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
5724 // ^^ Replace the upper 32-BitSize bits of the new
5725 // value with those that we loaded.
5726 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
5727 // ^^ Rotate the new field to its proper position.
5728 // %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
5730 // # fall through to ExitMMB
5732 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
5733 .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5734 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
5735 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
5736 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
5741 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5742 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5743 MBB->addSuccessor(LoopMBB);
5744 MBB->addSuccessor(DoneMBB);
5746 MI.eraseFromParent();
5750 // Emit an extension from a GR32 or GR64 to a GR128. ClearEven is true
5751 // if the high register of the GR128 value must be cleared or false if
5752 // it's "don't care". SubReg is subreg_l32 when extending a GR32
5753 // and subreg_l64 when extending a GR64.
5754 MachineBasicBlock *SystemZTargetLowering::emitExt128(MachineInstr &MI,
5755 MachineBasicBlock *MBB,
5757 unsigned SubReg) const {
5758 MachineFunction &MF = *MBB->getParent();
5759 const SystemZInstrInfo *TII =
5760 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5761 MachineRegisterInfo &MRI = MF.getRegInfo();
5762 DebugLoc DL = MI.getDebugLoc();
5764 unsigned Dest = MI.getOperand(0).getReg();
5765 unsigned Src = MI.getOperand(1).getReg();
5766 unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5768 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
5770 unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5771 unsigned Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
5773 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
5775 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
5776 .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
5779 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
5780 .addReg(In128).addReg(Src).addImm(SubReg);
5782 MI.eraseFromParent();
5786 MachineBasicBlock *SystemZTargetLowering::emitMemMemWrapper(
5787 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
5788 MachineFunction &MF = *MBB->getParent();
5789 const SystemZInstrInfo *TII =
5790 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5791 MachineRegisterInfo &MRI = MF.getRegInfo();
5792 DebugLoc DL = MI.getDebugLoc();
5794 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
5795 uint64_t DestDisp = MI.getOperand(1).getImm();
5796 MachineOperand SrcBase = earlyUseOperand(MI.getOperand(2));
5797 uint64_t SrcDisp = MI.getOperand(3).getImm();
5798 uint64_t Length = MI.getOperand(4).getImm();
5800 // When generating more than one CLC, all but the last will need to
5801 // branch to the end when a difference is found.
5802 MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
5803 splitBlockAfter(MI, MBB) : nullptr);
5805 // Check for the loop form, in which operand 5 is the trip count.
5806 if (MI.getNumExplicitOperands() > 5) {
5807 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
5809 uint64_t StartCountReg = MI.getOperand(5).getReg();
5810 uint64_t StartSrcReg = forceReg(MI, SrcBase, TII);
5811 uint64_t StartDestReg = (HaveSingleBase ? StartSrcReg :
5812 forceReg(MI, DestBase, TII));
5814 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
5815 uint64_t ThisSrcReg = MRI.createVirtualRegister(RC);
5816 uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
5817 MRI.createVirtualRegister(RC));
5818 uint64_t NextSrcReg = MRI.createVirtualRegister(RC);
5819 uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
5820 MRI.createVirtualRegister(RC));
5822 RC = &SystemZ::GR64BitRegClass;
5823 uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
5824 uint64_t NextCountReg = MRI.createVirtualRegister(RC);
5826 MachineBasicBlock *StartMBB = MBB;
5827 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5828 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5829 MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
5832 // # fall through to LoopMMB
5833 MBB->addSuccessor(LoopMBB);
5836 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
5837 // [ %NextDestReg, NextMBB ]
5838 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
5839 // [ %NextSrcReg, NextMBB ]
5840 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
5841 // [ %NextCountReg, NextMBB ]
5842 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
5843 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
5846 // The prefetch is used only for MVC. The JLH is used only for CLC.
5849 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
5850 .addReg(StartDestReg).addMBB(StartMBB)
5851 .addReg(NextDestReg).addMBB(NextMBB);
5852 if (!HaveSingleBase)
5853 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
5854 .addReg(StartSrcReg).addMBB(StartMBB)
5855 .addReg(NextSrcReg).addMBB(NextMBB);
5856 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
5857 .addReg(StartCountReg).addMBB(StartMBB)
5858 .addReg(NextCountReg).addMBB(NextMBB);
5859 if (Opcode == SystemZ::MVC)
5860 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
5861 .addImm(SystemZ::PFD_WRITE)
5862 .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
5863 BuildMI(MBB, DL, TII->get(Opcode))
5864 .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
5865 .addReg(ThisSrcReg).addImm(SrcDisp);
5867 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5868 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5870 MBB->addSuccessor(EndMBB);
5871 MBB->addSuccessor(NextMBB);
5875 // %NextDestReg = LA 256(%ThisDestReg)
5876 // %NextSrcReg = LA 256(%ThisSrcReg)
5877 // %NextCountReg = AGHI %ThisCountReg, -1
5878 // CGHI %NextCountReg, 0
5880 // # fall through to DoneMMB
5882 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
5885 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
5886 .addReg(ThisDestReg).addImm(256).addReg(0);
5887 if (!HaveSingleBase)
5888 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
5889 .addReg(ThisSrcReg).addImm(256).addReg(0);
5890 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
5891 .addReg(ThisCountReg).addImm(-1);
5892 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
5893 .addReg(NextCountReg).addImm(0);
5894 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5895 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5897 MBB->addSuccessor(LoopMBB);
5898 MBB->addSuccessor(DoneMBB);
5900 DestBase = MachineOperand::CreateReg(NextDestReg, false);
5901 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
5905 // Handle any remaining bytes with straight-line code.
5906 while (Length > 0) {
5907 uint64_t ThisLength = std::min(Length, uint64_t(256));
5908 // The previous iteration might have created out-of-range displacements.
5909 // Apply them using LAY if so.
5910 if (!isUInt<12>(DestDisp)) {
5911 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5912 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5916 DestBase = MachineOperand::CreateReg(Reg, false);
5919 if (!isUInt<12>(SrcDisp)) {
5920 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5921 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5925 SrcBase = MachineOperand::CreateReg(Reg, false);
5928 BuildMI(*MBB, MI, DL, TII->get(Opcode))
5934 DestDisp += ThisLength;
5935 SrcDisp += ThisLength;
5936 Length -= ThisLength;
5937 // If there's another CLC to go, branch to the end if a difference
5939 if (EndMBB && Length > 0) {
5940 MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
5941 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5942 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5944 MBB->addSuccessor(EndMBB);
5945 MBB->addSuccessor(NextMBB);
5950 MBB->addSuccessor(EndMBB);
5952 MBB->addLiveIn(SystemZ::CC);
5955 MI.eraseFromParent();
5959 // Decompose string pseudo-instruction MI into a loop that continually performs
5960 // Opcode until CC != 3.
5961 MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
5962 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
5963 MachineFunction &MF = *MBB->getParent();
5964 const SystemZInstrInfo *TII =
5965 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5966 MachineRegisterInfo &MRI = MF.getRegInfo();
5967 DebugLoc DL = MI.getDebugLoc();
5969 uint64_t End1Reg = MI.getOperand(0).getReg();
5970 uint64_t Start1Reg = MI.getOperand(1).getReg();
5971 uint64_t Start2Reg = MI.getOperand(2).getReg();
5972 uint64_t CharReg = MI.getOperand(3).getReg();
5974 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
5975 uint64_t This1Reg = MRI.createVirtualRegister(RC);
5976 uint64_t This2Reg = MRI.createVirtualRegister(RC);
5977 uint64_t End2Reg = MRI.createVirtualRegister(RC);
5979 MachineBasicBlock *StartMBB = MBB;
5980 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5981 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5984 // # fall through to LoopMMB
5985 MBB->addSuccessor(LoopMBB);
5988 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
5989 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
5991 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
5993 // # fall through to DoneMMB
5995 // The load of R0L can be hoisted by post-RA LICM.
5998 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
5999 .addReg(Start1Reg).addMBB(StartMBB)
6000 .addReg(End1Reg).addMBB(LoopMBB);
6001 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
6002 .addReg(Start2Reg).addMBB(StartMBB)
6003 .addReg(End2Reg).addMBB(LoopMBB);
6004 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
6005 BuildMI(MBB, DL, TII->get(Opcode))
6006 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
6007 .addReg(This1Reg).addReg(This2Reg);
6008 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
6009 .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
6010 MBB->addSuccessor(LoopMBB);
6011 MBB->addSuccessor(DoneMBB);
6013 DoneMBB->addLiveIn(SystemZ::CC);
6015 MI.eraseFromParent();
6019 // Update TBEGIN instruction with final opcode and register clobbers.
6020 MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
6021 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
6022 bool NoFloat) const {
6023 MachineFunction &MF = *MBB->getParent();
6024 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
6025 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
6028 MI.setDesc(TII->get(Opcode));
6030 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
6031 // Make sure to add the corresponding GRSM bits if they are missing.
6032 uint64_t Control = MI.getOperand(2).getImm();
6033 static const unsigned GPRControlBit[16] = {
6034 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
6035 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
6037 Control |= GPRControlBit[15];
6039 Control |= GPRControlBit[11];
6040 MI.getOperand(2).setImm(Control);
6042 // Add GPR clobbers.
6043 for (int I = 0; I < 16; I++) {
6044 if ((Control & GPRControlBit[I]) == 0) {
6045 unsigned Reg = SystemZMC::GR64Regs[I];
6046 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
6050 // Add FPR/VR clobbers.
6051 if (!NoFloat && (Control & 4) != 0) {
6052 if (Subtarget.hasVector()) {
6053 for (int I = 0; I < 32; I++) {
6054 unsigned Reg = SystemZMC::VR128Regs[I];
6055 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
6058 for (int I = 0; I < 16; I++) {
6059 unsigned Reg = SystemZMC::FP64Regs[I];
6060 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
6068 MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
6069 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
6070 MachineFunction &MF = *MBB->getParent();
6071 MachineRegisterInfo *MRI = &MF.getRegInfo();
6072 const SystemZInstrInfo *TII =
6073 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
6074 DebugLoc DL = MI.getDebugLoc();
6076 unsigned SrcReg = MI.getOperand(0).getReg();
6078 // Create new virtual register of the same class as source.
6079 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
6080 unsigned DstReg = MRI->createVirtualRegister(RC);
6082 // Replace pseudo with a normal load-and-test that models the def as
6084 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
6086 MI.eraseFromParent();
6091 MachineBasicBlock *SystemZTargetLowering::EmitInstrWithCustomInserter(
6092 MachineInstr &MI, MachineBasicBlock *MBB) const {
6093 switch (MI.getOpcode()) {
6094 case SystemZ::Select32Mux:
6095 return emitSelect(MI, MBB,
6096 Subtarget.hasLoadStoreOnCond2()? SystemZ::LOCRMux : 0);
6097 case SystemZ::Select32:
6098 return emitSelect(MI, MBB, SystemZ::LOCR);
6099 case SystemZ::Select64:
6100 return emitSelect(MI, MBB, SystemZ::LOCGR);
6101 case SystemZ::SelectF32:
6102 case SystemZ::SelectF64:
6103 case SystemZ::SelectF128:
6104 return emitSelect(MI, MBB, 0);
6106 case SystemZ::CondStore8Mux:
6107 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
6108 case SystemZ::CondStore8MuxInv:
6109 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
6110 case SystemZ::CondStore16Mux:
6111 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
6112 case SystemZ::CondStore16MuxInv:
6113 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
6114 case SystemZ::CondStore32Mux:
6115 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
6116 case SystemZ::CondStore32MuxInv:
6117 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
6118 case SystemZ::CondStore8:
6119 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
6120 case SystemZ::CondStore8Inv:
6121 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
6122 case SystemZ::CondStore16:
6123 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
6124 case SystemZ::CondStore16Inv:
6125 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
6126 case SystemZ::CondStore32:
6127 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
6128 case SystemZ::CondStore32Inv:
6129 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
6130 case SystemZ::CondStore64:
6131 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
6132 case SystemZ::CondStore64Inv:
6133 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
6134 case SystemZ::CondStoreF32:
6135 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
6136 case SystemZ::CondStoreF32Inv:
6137 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
6138 case SystemZ::CondStoreF64:
6139 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
6140 case SystemZ::CondStoreF64Inv:
6141 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
6143 case SystemZ::AEXT128_64:
6144 return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
6145 case SystemZ::ZEXT128_32:
6146 return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
6147 case SystemZ::ZEXT128_64:
6148 return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
6150 case SystemZ::ATOMIC_SWAPW:
6151 return emitAtomicLoadBinary(MI, MBB, 0, 0);
6152 case SystemZ::ATOMIC_SWAP_32:
6153 return emitAtomicLoadBinary(MI, MBB, 0, 32);
6154 case SystemZ::ATOMIC_SWAP_64:
6155 return emitAtomicLoadBinary(MI, MBB, 0, 64);
6157 case SystemZ::ATOMIC_LOADW_AR:
6158 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
6159 case SystemZ::ATOMIC_LOADW_AFI:
6160 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
6161 case SystemZ::ATOMIC_LOAD_AR:
6162 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
6163 case SystemZ::ATOMIC_LOAD_AHI:
6164 return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
6165 case SystemZ::ATOMIC_LOAD_AFI:
6166 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
6167 case SystemZ::ATOMIC_LOAD_AGR:
6168 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
6169 case SystemZ::ATOMIC_LOAD_AGHI:
6170 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
6171 case SystemZ::ATOMIC_LOAD_AGFI:
6172 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
6174 case SystemZ::ATOMIC_LOADW_SR:
6175 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
6176 case SystemZ::ATOMIC_LOAD_SR:
6177 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
6178 case SystemZ::ATOMIC_LOAD_SGR:
6179 return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
6181 case SystemZ::ATOMIC_LOADW_NR:
6182 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
6183 case SystemZ::ATOMIC_LOADW_NILH:
6184 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
6185 case SystemZ::ATOMIC_LOAD_NR:
6186 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
6187 case SystemZ::ATOMIC_LOAD_NILL:
6188 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
6189 case SystemZ::ATOMIC_LOAD_NILH:
6190 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
6191 case SystemZ::ATOMIC_LOAD_NILF:
6192 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
6193 case SystemZ::ATOMIC_LOAD_NGR:
6194 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
6195 case SystemZ::ATOMIC_LOAD_NILL64:
6196 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
6197 case SystemZ::ATOMIC_LOAD_NILH64:
6198 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
6199 case SystemZ::ATOMIC_LOAD_NIHL64:
6200 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
6201 case SystemZ::ATOMIC_LOAD_NIHH64:
6202 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
6203 case SystemZ::ATOMIC_LOAD_NILF64:
6204 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
6205 case SystemZ::ATOMIC_LOAD_NIHF64:
6206 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
6208 case SystemZ::ATOMIC_LOADW_OR:
6209 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
6210 case SystemZ::ATOMIC_LOADW_OILH:
6211 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
6212 case SystemZ::ATOMIC_LOAD_OR:
6213 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
6214 case SystemZ::ATOMIC_LOAD_OILL:
6215 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
6216 case SystemZ::ATOMIC_LOAD_OILH:
6217 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
6218 case SystemZ::ATOMIC_LOAD_OILF:
6219 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
6220 case SystemZ::ATOMIC_LOAD_OGR:
6221 return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
6222 case SystemZ::ATOMIC_LOAD_OILL64:
6223 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
6224 case SystemZ::ATOMIC_LOAD_OILH64:
6225 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
6226 case SystemZ::ATOMIC_LOAD_OIHL64:
6227 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
6228 case SystemZ::ATOMIC_LOAD_OIHH64:
6229 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
6230 case SystemZ::ATOMIC_LOAD_OILF64:
6231 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
6232 case SystemZ::ATOMIC_LOAD_OIHF64:
6233 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
6235 case SystemZ::ATOMIC_LOADW_XR:
6236 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
6237 case SystemZ::ATOMIC_LOADW_XILF:
6238 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
6239 case SystemZ::ATOMIC_LOAD_XR:
6240 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
6241 case SystemZ::ATOMIC_LOAD_XILF:
6242 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
6243 case SystemZ::ATOMIC_LOAD_XGR:
6244 return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
6245 case SystemZ::ATOMIC_LOAD_XILF64:
6246 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
6247 case SystemZ::ATOMIC_LOAD_XIHF64:
6248 return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
6250 case SystemZ::ATOMIC_LOADW_NRi:
6251 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
6252 case SystemZ::ATOMIC_LOADW_NILHi:
6253 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
6254 case SystemZ::ATOMIC_LOAD_NRi:
6255 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
6256 case SystemZ::ATOMIC_LOAD_NILLi:
6257 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
6258 case SystemZ::ATOMIC_LOAD_NILHi:
6259 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
6260 case SystemZ::ATOMIC_LOAD_NILFi:
6261 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
6262 case SystemZ::ATOMIC_LOAD_NGRi:
6263 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
6264 case SystemZ::ATOMIC_LOAD_NILL64i:
6265 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
6266 case SystemZ::ATOMIC_LOAD_NILH64i:
6267 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
6268 case SystemZ::ATOMIC_LOAD_NIHL64i:
6269 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
6270 case SystemZ::ATOMIC_LOAD_NIHH64i:
6271 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
6272 case SystemZ::ATOMIC_LOAD_NILF64i:
6273 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
6274 case SystemZ::ATOMIC_LOAD_NIHF64i:
6275 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
6277 case SystemZ::ATOMIC_LOADW_MIN:
6278 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6279 SystemZ::CCMASK_CMP_LE, 0);
6280 case SystemZ::ATOMIC_LOAD_MIN_32:
6281 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6282 SystemZ::CCMASK_CMP_LE, 32);
6283 case SystemZ::ATOMIC_LOAD_MIN_64:
6284 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
6285 SystemZ::CCMASK_CMP_LE, 64);
6287 case SystemZ::ATOMIC_LOADW_MAX:
6288 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6289 SystemZ::CCMASK_CMP_GE, 0);
6290 case SystemZ::ATOMIC_LOAD_MAX_32:
6291 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6292 SystemZ::CCMASK_CMP_GE, 32);
6293 case SystemZ::ATOMIC_LOAD_MAX_64:
6294 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
6295 SystemZ::CCMASK_CMP_GE, 64);
6297 case SystemZ::ATOMIC_LOADW_UMIN:
6298 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6299 SystemZ::CCMASK_CMP_LE, 0);
6300 case SystemZ::ATOMIC_LOAD_UMIN_32:
6301 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6302 SystemZ::CCMASK_CMP_LE, 32);
6303 case SystemZ::ATOMIC_LOAD_UMIN_64:
6304 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
6305 SystemZ::CCMASK_CMP_LE, 64);
6307 case SystemZ::ATOMIC_LOADW_UMAX:
6308 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6309 SystemZ::CCMASK_CMP_GE, 0);
6310 case SystemZ::ATOMIC_LOAD_UMAX_32:
6311 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6312 SystemZ::CCMASK_CMP_GE, 32);
6313 case SystemZ::ATOMIC_LOAD_UMAX_64:
6314 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
6315 SystemZ::CCMASK_CMP_GE, 64);
6317 case SystemZ::ATOMIC_CMP_SWAPW:
6318 return emitAtomicCmpSwapW(MI, MBB);
6319 case SystemZ::MVCSequence:
6320 case SystemZ::MVCLoop:
6321 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
6322 case SystemZ::NCSequence:
6323 case SystemZ::NCLoop:
6324 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
6325 case SystemZ::OCSequence:
6326 case SystemZ::OCLoop:
6327 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
6328 case SystemZ::XCSequence:
6329 case SystemZ::XCLoop:
6330 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
6331 case SystemZ::CLCSequence:
6332 case SystemZ::CLCLoop:
6333 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
6334 case SystemZ::CLSTLoop:
6335 return emitStringWrapper(MI, MBB, SystemZ::CLST);
6336 case SystemZ::MVSTLoop:
6337 return emitStringWrapper(MI, MBB, SystemZ::MVST);
6338 case SystemZ::SRSTLoop:
6339 return emitStringWrapper(MI, MBB, SystemZ::SRST);
6340 case SystemZ::TBEGIN:
6341 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
6342 case SystemZ::TBEGIN_nofloat:
6343 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
6344 case SystemZ::TBEGINC:
6345 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
6346 case SystemZ::LTEBRCompare_VecPseudo:
6347 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
6348 case SystemZ::LTDBRCompare_VecPseudo:
6349 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
6350 case SystemZ::LTXBRCompare_VecPseudo:
6351 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
6354 llvm_unreachable("Unexpected instr type to insert");